Skip to content

Commit 8e6c1ca

Browse files
dbebawycalltekk
authored andcommitted
fix(windows): use wcsnlen for defensive programming (CWE-126) (flutter#180419)
## Description This PR replaces `wcslen` with `wcsnlen` in the Windows runner template and all example/dev/integration test files to address CWE-126 (Buffer Over-read) flagged by static analysis tools (Semgrep/GitLab SAST). ## Changes The `Utf8FromUtf16` function now uses `wcsnlen` with the `UNICODE_STRING_MAX_CHARS` constant (32767) as the maximum length, providing defensive programming against potential buffer over-reads. **Key improvements:** 1. Calculate `input_length` **first** using `wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)` 2. Use that bounded length for **both** `WideCharToMultiByte` calls (eliminates the `-1` unbounded read) 3. Remove the `-1` adjustment since explicit length excludes null terminator 4. Use `static_cast` instead of C-style casts per Google C++ Style Guide ## Test Coverage Added comprehensive edge case tests for `Utf8FromUtf16` in `windows_startup_test`: - **nullptr input**: Verifies function returns empty string - **Empty string input**: Verifies function returns empty string - **Invalid UTF-16 (unpaired surrogate)**: Verifies function handles malformed input gracefully These tests address reviewer feedback from @loic-sharma requesting coverage for corner cases. ## Files Updated **Template (source of truth):** - `packages/flutter_tools/templates/app/windows.tmpl/runner/utils.cpp` **Integration tests (4 files):** - `dev/integration_tests/flutter_gallery/windows/runner/utils.cpp` - `dev/integration_tests/ui/windows/runner/utils.cpp` - `dev/integration_tests/windowing_test/windows/runner/utils.cpp` - `dev/integration_tests/windows_startup_test/windows/runner/utils.cpp` **Examples and dev apps (10 files):** - `examples/hello_world/windows/runner/utils.cpp` - `examples/layers/windows/runner/utils.cpp` - `examples/platform_view/windows/runner/utils.cpp` - `examples/flutter_view/windows/runner/utils.cpp` - `examples/platform_channel/windows/runner/utils.cpp` - `examples/api/windows/runner/utils.cpp` - `examples/multiple_windows/windows/runner/utils.cpp` - `dev/manual_tests/windows/runner/utils.cpp` - `dev/benchmarks/complex_layout/windows/runner/utils.cpp` - `dev/a11y_assessments/windows/runner/utils.cpp` **Test files (4 files):** - `dev/integration_tests/windows_startup_test/windows/runner/flutter_window.cpp` - `dev/integration_tests/windows_startup_test/lib/main.dart` - `dev/integration_tests/windows_startup_test/lib/windows.dart` - `dev/integration_tests/windows_startup_test/test_driver/main_test.dart` ## Rationale While the Windows API guarantees null-termination for strings returned by `CommandLineToArgvW`, using `wcsnlen` with an explicit bound is a defensive programming best practice that: - Satisfies static analysis tools - Provides an extra safety layer - Follows the principle of defense in depth The limit of 32767 (`UNICODE_STRING_MAX_CHARS`) is the maximum length of a `UNICODE_STRING` structure and is far beyond any realistic command-line argument length. ## Related Issues Fixes flutter#180418 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and labeled this PR with `severe: API break` if it contains a breaking change. - [x] All existing and new tests are passing. [Contributor Guide]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview [Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [breaking change policy]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#breaking-changes
1 parent 88b6120 commit 8e6c1ca

19 files changed

Lines changed: 235 additions & 75 deletions

File tree

‎dev/a11y_assessments/windows/runner/utils.cpp‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
56-
int input_length = (int)wcslen(utf16_string);
60+
input_length, nullptr, 0, nullptr, nullptr);
5761
std::string utf8_string;
58-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5963
return utf8_string;
6064
}
6165
utf8_string.resize(target_length);

‎dev/benchmarks/complex_layout/windows/runner/utils.cpp‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,18 +49,23 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
60+
input_length, nullptr, 0, nullptr, nullptr);
5661
std::string utf8_string;
57-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5863
return utf8_string;
5964
}
6065
utf8_string.resize(target_length);
6166
int converted_length = ::WideCharToMultiByte(
6267
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
63-
-1, utf8_string.data(), target_length, nullptr, nullptr);
68+
input_length, utf8_string.data(), target_length, nullptr, nullptr);
6469
if (converted_length == 0) {
6570
return std::string();
6671
}

‎dev/integration_tests/flutter_gallery/windows/runner/utils.cpp‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
56-
int input_length = (int)wcslen(utf16_string);
60+
input_length, nullptr, 0, nullptr, nullptr);
5761
std::string utf8_string;
58-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5963
return utf8_string;
6064
}
6165
utf8_string.resize(target_length);

‎dev/integration_tests/ui/windows/runner/utils.cpp‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
56-
int input_length = (int)wcslen(utf16_string);
60+
input_length, nullptr, 0, nullptr, nullptr);
5761
std::string utf8_string;
58-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5963
return utf8_string;
6064
}
6165
utf8_string.resize(target_length);

‎dev/integration_tests/windowing_test/windows/runner/utils.cpp‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
56-
int input_length = (int)wcslen(utf16_string);
60+
input_length, nullptr, 0, nullptr, nullptr);
5761
std::string utf8_string;
58-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5963
return utf8_string;
6064
}
6165
utf8_string.resize(target_length);

‎dev/integration_tests/windows_startup_test/lib/main.dart‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,26 @@ void main() async {
7979
return (converted == expected)
8080
? 'success'
8181
: 'error: conversion of UTF16 string to UTF8 failed, expected "${expected.codeUnits}" but got "${converted.codeUnits}"';
82+
} else if (message == 'verifyNullStringConversion') {
83+
// Test that Utf8FromUtf16 handles nullptr gracefully by returning empty string.
84+
final String converted = await testNullStringConversion();
85+
return converted.isEmpty
86+
? 'success'
87+
: 'error: nullptr conversion should return empty string, got "${converted.codeUnits}"';
88+
} else if (message == 'verifyEmptyStringConversion') {
89+
// Test that Utf8FromUtf16 handles empty string gracefully.
90+
final String converted = await testEmptyStringConversion();
91+
return converted.isEmpty
92+
? 'success'
93+
: 'error: empty string conversion should return empty string, got "${converted.codeUnits}"';
94+
} else if (message == 'verifyInvalidUtf16Conversion') {
95+
// Test that Utf8FromUtf16 handles invalid UTF-16 (unpaired surrogate) gracefully.
96+
// With WC_ERR_INVALID_CHARS flag, WideCharToMultiByte returns 0 for invalid input,
97+
// so Utf8FromUtf16 should return an empty string.
98+
final String converted = await testInvalidUtf16Conversion();
99+
return converted.isEmpty
100+
? 'success'
101+
: 'error: invalid UTF-16 conversion should return empty string, got "${converted.codeUnits}"';
82102
}
83103

84104
throw 'Unrecognized message: $message';

‎dev/integration_tests/windows_startup_test/lib/windows.dart‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,33 @@ Future<String> testStringConversion(Int32List twoByteCodes) async {
5050

5151
return converted;
5252
}
53+
54+
/// Test that Utf8FromUtf16 handles nullptr gracefully.
55+
Future<String> testNullStringConversion() async {
56+
final String? converted = await _kMethodChannel.invokeMethod<String?>('convertNullString');
57+
if (converted == null) {
58+
throw 'Method channel unavailable.';
59+
}
60+
61+
return converted;
62+
}
63+
64+
/// Test that Utf8FromUtf16 handles empty string gracefully.
65+
Future<String> testEmptyStringConversion() async {
66+
final String? converted = await _kMethodChannel.invokeMethod<String?>('convertEmptyString');
67+
if (converted == null) {
68+
throw 'Method channel unavailable.';
69+
}
70+
71+
return converted;
72+
}
73+
74+
/// Test that Utf8FromUtf16 handles invalid UTF-16 (unpaired surrogate) gracefully.
75+
Future<String> testInvalidUtf16Conversion() async {
76+
final String? converted = await _kMethodChannel.invokeMethod<String?>('convertInvalidUtf16');
77+
if (converted == null) {
78+
throw 'Method channel unavailable.';
79+
}
80+
81+
return converted;
82+
}

‎dev/integration_tests/windows_startup_test/test_driver/main_test.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,31 @@ void main() {
3232

3333
await driver.close();
3434
}, timeout: Timeout.none);
35+
36+
test('Windows app template Utf8FromUtf16 handles nullptr', () async {
37+
final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true);
38+
final String result = await driver.requestData('verifyNullStringConversion');
39+
40+
expect(result, equals('success'));
41+
42+
await driver.close();
43+
}, timeout: Timeout.none);
44+
45+
test('Windows app template Utf8FromUtf16 handles empty string', () async {
46+
final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true);
47+
final String result = await driver.requestData('verifyEmptyStringConversion');
48+
49+
expect(result, equals('success'));
50+
51+
await driver.close();
52+
}, timeout: Timeout.none);
53+
54+
test('Windows app template Utf8FromUtf16 handles invalid UTF-16', () async {
55+
final FlutterDriver driver = await FlutterDriver.connect(printCommunication: true);
56+
final String result = await driver.requestData('verifyInvalidUtf16Conversion');
57+
58+
expect(result, equals('success'));
59+
60+
await driver.close();
61+
}, timeout: Timeout.none);
3562
}

‎dev/integration_tests/windows_startup_test/windows/runner/flutter_window.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,21 @@ bool FlutterWindow::OnCreate() {
122122
wide_str.push_back((wchar_t)0);
123123
const std::string string = Utf8FromUtf16(wide_str.data());
124124
result->Success(string);
125+
} else if (method == "convertNullString") {
126+
// Test that Utf8FromUtf16 handles nullptr gracefully.
127+
const std::string string = Utf8FromUtf16(nullptr);
128+
result->Success(string);
129+
} else if (method == "convertEmptyString") {
130+
// Test that Utf8FromUtf16 handles empty string gracefully.
131+
const wchar_t empty[] = L"";
132+
const std::string string = Utf8FromUtf16(empty);
133+
result->Success(string);
134+
} else if (method == "convertInvalidUtf16") {
135+
// Test that Utf8FromUtf16 handles invalid UTF-16 (unpaired surrogate).
136+
// 0xD800 is a high surrogate without a matching low surrogate.
137+
const wchar_t invalid[] = { 0xD800, 0 };
138+
const std::string string = Utf8FromUtf16(invalid);
139+
result->Success(string);
125140
} else {
126141
result->NotImplemented();
127142
}

‎dev/integration_tests/windows_startup_test/windows/runner/utils.cpp‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,17 @@ std::string Utf8FromUtf16(const wchar_t* utf16_string) {
4949
if (utf16_string == nullptr) {
5050
return std::string();
5151
}
52-
unsigned int target_length = ::WideCharToMultiByte(
52+
// First, find the length of the string with a safe upper bound (CWE-126).
53+
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
54+
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
55+
// Now use that bounded length to determine the required buffer size.
56+
// When an explicit length is passed, WideCharToMultiByte does not include
57+
// the null terminator in its returned size.
58+
int target_length = ::WideCharToMultiByte(
5359
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
54-
-1, nullptr, 0, nullptr, nullptr)
55-
-1; // remove the trailing null character
56-
int input_length = (int)wcslen(utf16_string);
60+
input_length, nullptr, 0, nullptr, nullptr);
5761
std::string utf8_string;
58-
if (target_length == 0 || target_length > utf8_string.max_size()) {
62+
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
5963
return utf8_string;
6064
}
6165
utf8_string.resize(target_length);

0 commit comments

Comments
 (0)