Do not pass nullable parameters of simple types to Tonic-wrapped native functions (flutter/engine#33159)

This commit is contained in:
Jason Simmons
2022-05-09 11:34:05 -07:00
committed by GitHub
parent 8e9ae720fa
commit fff66b32fb
5 changed files with 129 additions and 40 deletions

View File

@@ -24,17 +24,17 @@ class DartPluginRegistrant {
}
// Corelib 'print' implementation.
void _print(Object? arg) {
_Logger._printString(arg.toString());
void _print(String arg) {
_Logger._printString(arg);
}
void _printDebug(Object? arg) {
_Logger._printDebugString(arg.toString());
void _printDebug(String arg) {
_Logger._printDebugString(arg);
}
class _Logger {
static void _printString(String? s) native 'Logger_PrintString';
static void _printDebugString(String? s) native 'Logger_PrintDebugString';
static void _printString(String s) native 'Logger_PrintString';
static void _printDebugString(String s) native 'Logger_PrintDebugString';
}
// If we actually run on big endian machines, we'll need to do something smarter

View File

@@ -913,7 +913,7 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
decreasedValueAttributes,
hint,
hintAttributes,
tooltip,
tooltip ?? '',
textDirection != null ? textDirection.index + 1 : 0,
transform,
childrenInTraversalOrder,
@@ -951,7 +951,7 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
List<StringAttribute> decreasedValueAttributes,
String hint,
List<StringAttribute> hintAttributes,
String? tooltip,
String tooltip,
int textDirection,
Float64List transform,
Int32List childrenInTraversalOrder,
@@ -977,12 +977,12 @@ class SemanticsUpdateBuilder extends NativeFieldWrapperClass1 {
void updateCustomAction({required int id, String? label, String? hint, int overrideId = -1}) {
assert(id != null);
assert(overrideId != null);
_updateCustomAction(id, label, hint, overrideId);
_updateCustomAction(id, label ?? '', hint ?? '', overrideId);
}
void _updateCustomAction(
int id,
String? label,
String? hint,
String label,
String hint,
int overrideId) native 'SemanticsUpdateBuilder_updateCustomAction';
/// Creates a [SemanticsUpdate] object that encapsulates the updates recorded

View File

@@ -2883,11 +2883,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
_constructor(
style._encoded,
encodedStrutStyle,
style._fontFamily,
style._fontFamily ?? '',
strutFontFamilies,
style._fontSize,
style._height,
style._ellipsis,
style._fontSize ?? 0,
style._height ?? 0,
style._ellipsis ?? '',
_encodeLocale(style._locale)
);
}
@@ -2895,11 +2895,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
void _constructor(
Int32List encoded,
ByteData? strutData,
String? fontFamily,
String fontFamily,
List<Object?>? strutFontFamily,
double? fontSize,
double? height,
String? ellipsis,
double fontSize,
double height,
String ellipsis,
String locale
) native 'ParagraphBuilder_constructor';
@@ -2955,11 +2955,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
_pushStyle(
encoded,
fullFontFamilies,
style._fontSize,
style._letterSpacing,
style._wordSpacing,
style._height,
style._decorationThickness,
style._fontSize ?? 0,
style._letterSpacing ?? 0,
style._wordSpacing ?? 0,
style._height ?? 0,
style._decorationThickness ?? 0,
_encodeLocale(style._locale),
style._background?._objects,
style._background?._data,
@@ -2974,11 +2974,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
void _pushStyle(
Int32List encoded,
List<Object?> fontFamilies,
double? fontSize,
double? letterSpacing,
double? wordSpacing,
double? height,
double? decorationThickness,
double fontSize,
double letterSpacing,
double wordSpacing,
double height,
double decorationThickness,
String locale,
List<Object?>? backgroundObjects,
ByteData? backgroundData,
@@ -3068,11 +3068,11 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
// Default the baselineOffset to height if null. This will place the placeholder
// fully above the baseline, similar to [PlaceholderAlignment.aboveBaseline].
baselineOffset = baselineOffset ?? height;
_addPlaceholder(width * scale, height * scale, alignment.index, baselineOffset * scale, baseline?.index);
_addPlaceholder(width * scale, height * scale, alignment.index, baselineOffset * scale, (baseline ?? TextBaseline.alphabetic).index);
_placeholderCount++;
_placeholderScales.add(scale);
}
String? _addPlaceholder(double width, double height, int alignment, double baselineOffset, int? baseline) native 'ParagraphBuilder_addPlaceholder';
String? _addPlaceholder(double width, double height, int alignment, double baselineOffset, int baseline) native 'ParagraphBuilder_addPlaceholder';
/// Applies the given paragraph style and returns a [Paragraph] containing the
/// added text and associated styling.
@@ -3095,7 +3095,7 @@ class ParagraphBuilder extends NativeFieldWrapperClass1 {
Future<void> loadFontFromList(Uint8List list, {String? fontFamily}) {
return _futurize(
(_Callback<void> callback) {
_loadFontFromList(list, callback, fontFamily);
_loadFontFromList(list, callback, fontFamily ?? '');
}
).then((_) => _sendFontChangeMessage());
}
@@ -3119,4 +3119,4 @@ FutureOr<void> _sendFontChangeMessage() async {
}
}
void _loadFontFromList(Uint8List list, _Callback<void> callback, String? fontFamily) native 'loadFontFromList';
void _loadFontFromList(Uint8List list, _Callback<void> callback, String fontFamily) native 'loadFontFromList';

View File

@@ -7,9 +7,13 @@ import 'dart:io';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:pub_semver/pub_semver.dart';
/// Returns all indexed fields in [className].
///
@@ -156,3 +160,21 @@ List<String> _getBlockStartingWith({
final int blockEnd = pos;
return LineSplitter.split(source, blockStart, blockEnd).toList();
}
/// Apply a visitor to all compilation units in the dart:ui library.
void visitUIUnits(String flutterRoot, AstVisitor<void> visitor) {
String uiRoot = '$flutterRoot/lib/ui';
final FeatureSet analyzerFeatures = FeatureSet.fromEnableFlags2(
sdkLanguageVersion: Version.parse('2.12.0'),
flags: <String>['non-nullable'],
);
final ParseStringResult uiResult = parseFile(path: '$uiRoot/ui.dart', featureSet: analyzerFeatures);
for (PartDirective part in uiResult.unit.directives.whereType<PartDirective>()) {
final String partPath = part.uri.stringValue!;
final ParseStringResult partResult = parseFile(path: '$uiRoot/$partPath', featureSet: analyzerFeatures);
for (CompilationUnitMember unitMember in partResult.unit.declarations) {
unitMember.accept(visitor);
}
}
}

View File

@@ -4,9 +4,23 @@
import 'dart:io';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:apicheck/apicheck.dart';
import 'package:litetest/litetest.dart';
main(List<String> arguments) {
if (arguments.length < 1) {
print('usage: dart bin/apicheck.dart path/to/engine/src/flutter');
exit(1);
}
final String flutterRoot = arguments[0];
checkApiConsistency(flutterRoot);
checkNativeApi(flutterRoot);
}
/// Verify that duplicate Flutter API is consistent between implementations.
///
/// Flutter contains API that is required to match between implementations.
@@ -21,13 +35,7 @@ import 'package:litetest/litetest.dart';
/// CANNOT be removed without breaking backward compatibility, which we have
/// never done. See the note at the top of `shell/platform/embedder/embedder.h`
/// for further details.
main(List<String> arguments) {
if (arguments.length < 1) {
print('usage: dart bin/apicheck.dart path/to/engine/src/flutter');
exit(1);
}
final String flutterRoot = arguments[0];
checkApiConsistency(String flutterRoot) {
test('AccessibilityFeatures enums match', () {
// Dart values: _kFooBarIndex = 1 << N
List<String> uiFields = getDartClassFields(
@@ -138,3 +146,62 @@ String allCapsToCamelCase(String identifier) {
}
return buffer.toString();
}
/// Verify that the native functions in the dart:ui package do not use nullable
/// parameters that map to simple types such as numbers and strings.
///
/// The Tonic argument converters used by the native function implementations
/// expect that values of these types will not be null.
class NativeFunctionVisitor extends RecursiveAstVisitor<void> {
final Set<String> simpleTypes = <String>{'int', 'double', 'bool', 'String'};
List<String> errors = <String>[];
@override
void visitNativeFunctionBody(NativeFunctionBody node) {
MethodDeclaration? method = node.thisOrAncestorOfType<MethodDeclaration>();
if (method != null) {
if (method.parameters != null) {
check(method.toString(), method.parameters!);
}
return;
}
FunctionDeclaration? func = node.thisOrAncestorOfType<FunctionDeclaration>();
if (func != null) {
FunctionExpression funcExpr = func.functionExpression;
if (funcExpr.parameters != null) {
check(func.toString(), funcExpr.parameters!);
}
return;
}
throw Exception('unreachable');
}
void check(String description, FormalParameterList parameters) {
for (FormalParameter parameter in parameters.parameters) {
TypeAnnotation? type;
if (parameter is SimpleFormalParameter) {
type = parameter.type;
} else if (parameter is DefaultFormalParameter) {
type = (parameter.parameter as SimpleFormalParameter).type;
}
if (type! is NamedType) {
String name = (type as NamedType).name.name;
if (type.question != null && simpleTypes.contains(name)) {
errors.add(description);
return;
}
}
}
}
}
void checkNativeApi(String flutterRoot) {
test('Native API does not pass nullable parameters of simple types', () {
NativeFunctionVisitor visitor = NativeFunctionVisitor();
visitUIUnits(flutterRoot, visitor);
expect(visitor.errors, isEmpty);
});
}