xianyutech / aspectd Goto Github PK
View Code? Open in Web Editor NEWAOP for Flutter(Dart)
License: MIT License
AOP for Flutter(Dart)
License: MIT License
您好,尝试用了demo中的instanceUniversalHook方法
dynamic instanceUniversalHook(PointCut pointcut) { print('mmm,Before:${pointcut.target}-${pointcut.function}}'); dynamic obj = pointcut.proceed(); return obj; }
其中某些页面的参数是自定义的枚举类型,这里报错Invalid argument(s),希望能改进,谢谢!
某页面为Tab 页,进入该页面执行instanceUniversalHook时,会报错 StackOverFlow
错误如下:
Can you please provide a detail guide on How to do logging before after and around for a particular function in flutter considering this sample example
import 'package:aspectd/aspectd.dart';
import 'package:flutter/material.dart';
import 'aop_iml.dart';
void main() => runApp(MyApp());
@Aspect()
@pragma("vm:entry-point")
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
与flutter_boost单独使用都没问题,一起使用后,编译报错:
warning: The iOS Simulator deployment target is set to 4.3, but the range of supported deployment target versions for this platform is 8.0 to 12.2.99. (in target 'FMDB')
warning: Capabilities for Runner may not function correctly because its entitlements use a placeholder team ID. To resolve this, select a development team in the build settings editor. (in target 'Runner')
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.m:101:9: warning: 'dispatch_queue_set_specific' is only available on iOS 5.0 or newer [-Wunguarded-availability]
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
In module 'Foundation' imported from /Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.h:9:
In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6:
In module 'Dispatch' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:20:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/dispatch/queue.h:1352:1: note: 'dispatch_queue_set_specific' has been marked as being introduced in iOS 5.0 here, but the deployment target is iOS 4.3.0
dispatch_queue_set_specific(dispatch_queue_t queue, const void *key,
^
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.m:101:9: note: enclose 'dispatch_queue_set_specific' in an @available check to silence this warning
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.m:184:54: warning: 'dispatch_get_specific' is only available on iOS 5.0 or newer [-Wunguarded-availability]
FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
^~~~~~~~~~~~~~~~~~~~~
In module 'Foundation' imported from /Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.h:9:
In module 'CoreFoundation' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6:
In module 'Dispatch' imported from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:20:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/dispatch/queue.h:1408:1: note: 'dispatch_get_specific' has been marked as being introduced in iOS 5.0 here, but the deployment target is iOS 4.3.0
dispatch_get_specific(const void *key);
^
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabaseQueue.m:184:54: note: enclose 'dispatch_get_specific' in an @available check to silence this warning
FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
^~~~~~~~~~~~~~~~~~~~~
2 warnings generated.
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabase.m:1486:15: warning: 'sqlite3_wal_checkpoint_v2' is only available on iOS 5.0 or newer [-Wunguarded-availability]
int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount);
^~~~~~~~~~~~~~~~~~~~~~~~~
In module 'SQLite3' imported from /Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabase.m:8:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.2.sdk/usr/include/sqlite3.h:8245:16: note: 'sqlite3_wal_checkpoint_v2' has been marked as being introduced in iOS 5.0 here, but the deployment target is iOS 4.3.0
SQLITE_API int sqlite3_wal_checkpoint_v2(
^
/Users/xxx/flutter/flutter_wallet/.ios/Pods/FMDB/src/fmdb/FMDatabase.m:1486:15: note: enclose 'sqlite3_wal_checkpoint_v2' in an @available check to silence this warning
int err = sqlite3_wal_checkpoint_v2(_db, dbName, checkpointMode, logFrameCount, checkpointCount);
^~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
Compiler message:
Error: Could not resolve the package 'flutter_boost' in 'package:flutter_boost/flutter_boost.dart'.
../lib/main.dart:8:8: Error: Not found: 'package:flutter_boost/flutter_boost.dart'
import 'package:flutter_boost/flutter_boost.dart';
^
Error: Could not resolve the package 'flutter_boost' in 'package:flutter_boost/channel/boost_channel.dart'.
../lib/page/goods_coupon_page.dart:2:8: Error: Not found: 'package:flutter_boost/channel/boost_channel.dart'
import 'package:flutter_boost/channel/boost_channel.dart';
^
../lib/main.dart:72:5: Error: Getter not found: 'FlutterBoost'.
FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
^^^^^^^^^^^^
../lib/main.dart:73:10: Error: 'ContainerLifeCycle' isn't a type.
(ContainerLifeCycle state, BoostContainerSettings settings) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:73:36: Error: 'BoostContainerSettings' isn't a type.
(ContainerLifeCycle state, BoostContainerSettings settings) {
^^^^^^^^^^^^^^^^^^^^^^
../lib/main.dart:90:20: Error: Getter not found: 'ContainerLifeCycle'.
if (state == ContainerLifeCycle.Init) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:92:27: Error: Getter not found: 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Destroy) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:94:27: Error: Getter not found: 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Disappear) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:96:27: Error: Getter not found: 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Background) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:100:5: Error: Getter not found: 'FlutterBoost'.
FlutterBoost.singleton.registerPageBuilders({
^^^^^^^^^^^^
../lib/main.dart:72:5: Error: The getter 'FlutterBoost' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'FlutterBoost'.
FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
^^^^^^^^^^^^
../lib/main.dart:90:20: Error: The getter 'ContainerLifeCycle' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'ContainerLifeCycle'.
if (state == ContainerLifeCycle.Init) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:92:27: Error: The getter 'ContainerLifeCycle' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Destroy) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:94:27: Error: The getter 'ContainerLifeCycle' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Disappear) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:96:27: Error: The getter 'ContainerLifeCycle' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'ContainerLifeCycle'.
} else if (state == ContainerLifeCycle.Background) {
^^^^^^^^^^^^^^^^^^
../lib/main.dart:100:5: Error: The getter 'FlutterBoost' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'FlutterBoost'.
FlutterBoost.singleton.registerPageBuilders({
^^^^^^^^^^^^
../lib/main.dart:164:16: Error: Getter not found: 'FlutterBoost'.
builder: FlutterBoost.init(postPush: _onRoutePushed),
^^^^^^^^^^^^
../lib/main.dart:164:16: Error: The getter 'FlutterBoost' isn't defined for the class '_WalletAppState'.
- '_WalletAppState' is from 'package:flutter_module/main.dart' ('../lib/main.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'FlutterBoost'.
builder: FlutterBoost.init(postPush: _onRoutePushed),
^^^^^^^^^^^^
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:package%3Aflutter_boost%2Fflutter_boost.dart; message=StandardFileSystem only supports file:* and data:* URIs)
#0 StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:33:7)
#1 asFileUri (package:vm/kernel_front_end.dart:578:37)
<asynchronous suspension>
#2 writeDepfile (package:vm/kernel_front_end.dart:755:21)
<asynchronous suspension>
#3 FrontendCompiler.compile (package:vm/frontend_server.dart:407:15)
<asynchronous suspension>
#4 _FlutterFrontendCompiler.compile (package:frontend_server/server.dart:29:22)
<asynchronous suspension>
#5 starter (package:frontend_server/server.dart:127:27)
<asynchronous suspension>
#6 main (file:///b/s/w/ir/k/src/flutter/frontend_server/bin/starter.dart:8:30)
<asynchronous suspension>
#7 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:32)
#8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
Compiler failed on /Users/xxx/flutter/flutter_wallet/aspectd_impl/lib/aspectd_impl.dart
Failed to package /Users/xxx/flutter/flutter_wallet.
Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build systemnote: Planning buildnote: Constructing build description
flutter doctor信息如下:
[✓] Flutter (Channel stable, v1.9.1, on Mac OS X 10.14.4 18E226, locale
zh-Hans-CN)
• Flutter version 1.9.1 at /Users/xxx/flutter/flutter
• Framework revision c382b8e990 (9 months ago), 2019-08-18 15:22:36 -0400
• Engine revision 5540684152
• Dart version 2.5.0
[!] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
• Android SDK at /Users/xxx/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling
support)
• Platform android-29, build-tools 29.0.1
• Java binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
1.8.0_202-release-1483-b49-5587405)
! Some Android licenses not accepted. To resolve this, run: flutter doctor
--android-licenses
[✓] Xcode - develop for iOS and macOS (Xcode 10.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 10.2, Build version 10E125
• CocoaPods version 1.6.1
[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 39.0.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build
1.8.0_202-release-1483-b49-5587405)
[!] IntelliJ IDEA Community Edition (version 2018.3.5)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
https://flutter.dev/intellij-setup/#installing-the-plugins
[✓] Connected device (1 available)
• iPhone Xʀ • 0D623F81-C315-4F5A-8267-F8936B55FFEA • ios •
com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)
! Doctor found issues in 2 categories.
@kangwang1988
反复测试发现一个问题,我给一个library方法添加call aop,debug模式下能正常编译,而且运行结果也正确。release模式下,出现“Dart snapshot generator failed with exit code -6”错误,生成的app.dill文件,转为txt查看了下,也是正确的,但是最后在flutter/bin/flutter中出错。
以下是我的测试代码:
环境:Flutter 1.5.4-hotfix.2 , Dart 2.3.0
git apply --3way /Users/cuikuangye/rong360work/androiddemo/aspectd-master/0001-aspectd.patch 我在执行这个命令行的时候报错:
error: patch failed: packages/flutter_tools/lib/src/commands/build_aot.dart:5
error: repository lacks the necessary blob to fall back on 3-way merge.
error: packages/flutter_tools/lib/src/commands/build_aot.dart: patch does not apply
error: patch failed: packages/flutter_tools/lib/src/commands/build_bundle.dart:4
error: repository lacks the necessary blob to fall back on 3-way merge.
error: packages/flutter_tools/lib/src/commands/build_bundle.dart: patch does not apply
Hook的代码:
@call("package:flutter/src/widgets/gesture_detector.dart", "GestureDetector",
"+GestureDetector")
@pragma("vm:entry-point")
static dynamic GestureDetector(PointCut pointcut) {
print('[KWLM-ljg]: Hook GestureDetector Constructor!');
return pointcut.proceed();
}
系统GestureDetector的构造函数:
GestureDetector({
Key key,
this.child,
this.onTap,
...
this.excludeFromSemantics = false,
this.dragStartBehavior = DragStartBehavior.start,
}) : assert(excludeFromSemantics != null),
assert(dragStartBehavior != null),
assert(() {
...
}
分析处理后的dill文件
return new ges::GestureDetector::•(
key: this.namedParams. as key::Key*,
child: this.namedParams. as fra::Widget*,
onTap: this.namedParams. as () →* void,
...
excludeFromSemantics: this.namedParams. as core::bool*,
dragStartBehavior: this.namedParams. as rec::DragStartBehavior*,
$creationLocationd_0dea112b090073317d4: this.namedParams. as wid::_Location*);
excludeFromSemantics和dragStartBehavior赋值为null。
测试debug环境是有问题的,release是正常的,因为release会删除assert。
在debug手动配置默认值后也是正常的,代码如下:
static dynamic GestureDetector(PointCut pointcut) {
print('[KWLM-ljg]: Hook GestureDetector Constructor!');
pointcut.namedParams['excludeFromSemantics'] = false;
pointcut.namedParams['dragStartBehavior'] = DragStartBehavior.start;
return pointcut.proceed();
}
希望能优化该问题。
I tested with master branch and failed, while v1.12.13 still works.
Error:
Target kernel_snapshot failed: Exception: Transformer terminated unexpectedly.
These methods cause "Transformer terminated unexpectedly" when run command
flutter build ios
@Execute("package:flutter/src/gestures/recognizer.dart", "GestureRecognizer",
"-invokeCallback")
@pragma("vm:entry-point")
dynamic hookInvokeCallback(PointCut pointcut) {
return pointcut.proceed();
}
@Execute("package:flutter/src/material/ink_well.dart", "_InkResponseState",
"-_handleTap")
@pragma("vm:entry-point")
Widget hook_handleTap(PointCut pointcut) {
Widget res = pointcut.proceed();
return res;
}
@Execute("package:flutter/src/widgets/routes.dart", "RouteObserver",
"-didPush")
@pragma("vm:entry-point")
void hookDidPush(PointCut pointcut) {
pointcut.proceed();
}
@Execute(
"package:flutter/src/widgets/routes.dart", "RouteObserver", "-didPop")
@pragma("vm:entry-point")
//pop
void hookDidPop(PointCut pointcut) {
pointcut.proceed();
}
比如if当前行,forin当前行和循环体内代码,for当前行和循环体内代码都无法Inject代码,见下面的case
int a = 10;
if (a > 5) {
print('[KWLM]:if1');
}
print('[KWLM]:a');
for (Observer o in observers) {
print('[KWLM]:Observer1');
o.onChanged();
print('[KWLM]:Observer2');
}
print('[KWLM]:b');
for (int i = 0; i < 10; i++) {
print('[KWLM]:for i $i');
print('[KWLM]:for i $i');
}
print('[KWLM]:c');
if (a > 5)
这一行前面即int a = 10;
这一行后面无法用Inject注入代码
for (Observer o in observers) {
这一行前面即print('[KWLM]:a');
这一行后面无法用Inject注入代码
循环体内无法用Inject注入代码
for (Observer o in observers) {
print('[KWLM]:Observer1');
o.onChanged();
print('[KWLM]:Observer2');
}
for (int i = 0; i < 10; i++) {
这一行前面即print('[KWLM]:b');
这一行后面无法用Inject注入代码
循环体内无法用Inject注入代码
for (int i = 0; i < 10; i++) {
print('[KWLM]:for i $i');
print('[KWLM]:for i $i');
}
可能和这个函数没有处理for循环有关:
static Node getNodeToVisitRecursively(Object statement) {
if (statement is FunctionDeclaration) {
return statement.function;
}
if (statement is LabeledStatement) {
return statement.body;
}
if (statement is IfStatement) {
return statement.then;
}
return null;
}
可以在Inject注解上增加后向插入
if (statement2InsertPos != -1) {
_curAopStatementsInsertInfo = null;
statements.insertAll(statement2InsertPos, aopInsertStatements);
_curAopLibrary = aopItemInfo.aopMember?.parent?.parent;
visitNode(node);
break;
}
后向插入取statement2InsertPos+1
这样就能在if语句和for循环语句前面一行插入,即插入上一行的后面。
print('[KWLM]:onPluginDemo Called!');
demo运行只打了这一行log
使用aspectd v1.5.4分支代码,运行example正常,尝试在项目工程中使用aspectd方案,编译失败,提示 Transformer terminated unexpectedly.
想问下有什么方法可以排查转换失败的具体原因?感谢!
→ flutter doctor -v [d3640fa8]
[✓] Flutter (Channel v1.5.4-hotfixes, v1.5.4-hotfix.2-pre.1, on Mac OS X 10.14.5 18F2058, locale zh-Hans-CN)
• Flutter version 1.5.4-hotfix.2-pre.1 at /Users/ivonhoe/Flutter/flutter
• Framework revision 953bbe2ccd (7 个月前), 2019-05-02 09:59:16 -0700
• Engine revision 52c7a1e849
• Dart version 2.3.0 (build 2.3.0-dev.0.5 a1668566e5)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
• Android SDK at /Users/ivonhoe/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.1
• ANDROID_HOME = /Users/ivonhoe/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.
[!] iOS toolchain - develop for iOS devices (Xcode 11.0)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.0, Build version 11A420a
✗ libimobiledevice and ideviceinstaller are not installed. To install with Brew, run:
brew update
brew install --HEAD usbmuxd
brew link usbmuxd
brew install --HEAD libimobiledevice
brew install ideviceinstaller
✗ ios-deploy not installed. To install:
brew install ios-deploy
✗ CocoaPods installed but not initialized.
CocoaPods is used to retrieve the iOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without resolving iOS dependencies with CocoaPods, plugins will not work on iOS.
For more info, see https://flutter.dev/platform-plugins
To initialize CocoaPods, run:
pod setup
once to finalize CocoaPods' installation.
[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 40.1.2
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.2.3)
• IntelliJ at /Applications/IntelliJ IDEA.app
• Flutter plugin version 40.2.3
• Dart plugin version 192.7402
[✓] VS Code (version 1.40.0)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.6.0
[✓] Connected device (3 available)
• SM N9008 • 004241ed • android-arm • Android 5.0 (API 21)
• A0001 • b2175f20 • android-arm • Android 5.1.1 (API 22)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 8.0.0 (API 26) (emulator)
! Doctor found issues in 1 category.
Apologies, but this is more of a question that a bug report, but I don't know where discussion for this repo goes on. I'm a total noob to Dart as I write this. I can't tell if AspectD can be used outside of Flutter projects.
So, can AspectD be used in vanilla Dart projects that have nothing to do with Flutter or any other UI framework?
Exception:
Unhandled exception:
RangeError (index): Index out of range: no indices are valid: 0
#0 Uint8List.[] (dart:typed_data-patch/typed_data_patch.dart:2207:7)
#1 BinaryBuilder.readByte (package:kernel/binary/ast_from_binary.dart:104:27)
#2 BinaryBuilder.readUint32 (package:kernel/binary/ast_from_binary.dart:124:13)
#3 BinaryBuilder.readComponent (package:kernel/binary/ast_from_binary.dart:444:17)
#4 main (file:///Dart/sdk/pkg/vm/bin/dump_kernel.dart:47:40)
#5 _startIsolate. (dart:isolate-patch/isolate_patch.dart:303:32)
#6 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
I have tried running the example project
,but its not calling the aop from main.dart,do we need to make any additional configurations to call the AOP?
My Understanding is that when any function in main.dart
gets called say e.g _incrementCounter()
then the method in aop_impl.dart()
on line no 95 instanceUniversalHook()
must get called but its not calling it.
Some additional details on how to call AOP implementation from our main project would be really helpful.
按照readme的步骤操作了多次,执行dart --snapshot=aspectd_impl.dill lib/aspectd_impl.dart时报Error: Not found: 'dart:ui',请大神帮忙解决下
I'm try hook abstract class GestureRecognizer.invokeCallback but not effect.Is it support the abstract class?
@Execute("package:flutter/src/gestures/recognizer.dart",
"GestureRecognizer", "-invokeCallback")
@pragma("vm:entry-point")
dynamic hookinvokeCallback(PointCut pointcut) {
var raw = pointcut.positionalParams[0];
print("invokeCallback");
return pointcut.proceed();
}
您好,
请问一下@Inject可以注入到自己写的方法中么?
比方说 注入到 官方 example 的_incrementCounter 中,
比方说想在【91】行写入一个输出
` @Inject("package:example/lib/main.dart","_MyHomePageState","-_incrementCounter",lineNum:91)
@pragma("vm:entry-point")
static void counterHook() {
int count;//Aspectd Ignore
int _counter;//Aspectd Ignore
print("[KWLM12]:count:$count,counter:$_counter");
//【91】行 }`
dart bin/dump_kernel.dart app.dill app.dill.txt 为啥我这条命令一直执行不成功?
需要什么配置?
环境:
Flutter 1.9.1+hotfix.6
AspectD v1.9.1
执行命令 git apply --3way /Users/zhaoxy/Desktop/code/aspectd/0001-aspectd.patch 报错如下:
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/aspectd.dart' cleanly.
error: patch failed: packages/flutter_tools/lib/src/commands/build_aot.dart:5
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/commands/build_aot.dart' cleanly.
error: patch failed: packages/flutter_tools/lib/src/commands/build_bundle.dart:4
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/commands/build_bundle.dart' cleanly.
修改为cls ?.name,(cls?.parent as Library) ?.importUri.toString()后执行成功
原因是pragma("vm:entry-point")这个解析时出了问题
log
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5) #1 AopWrapperTransformer._processAopMember (file:../aspectd-master/transformer/plugins/aop/aop_transformer_wrapper.dart:189:69) #2 AopWrapperTransformer._resolveAopProcedures (file:///Users/chenkang/Demo/aspectd-master/transformer/plugins/aop/aop_transformer_wrapper.dart:131:38) #3 AopWrapperTransformer.transform (file:../aspectd-master/transformer/plugins/aop/aop_transformer_wrapper.dart:20:5) #4 TransformerWrapper.transform (file:../aspectd-master/transformer/transformer_wrapper.dart:12:27) #5 main (file:../aspectd-master/tool/starter.dart:44:22) #6 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:298:32) #7 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
你好,我apply patch 后,使用此方法:debug flutter_tools 开启ide调试,但是在AspectdHook.isAspectdEnabled
方法里断点并没有执行到,请问要如何才能调试这方面的源码呢?期待解答,谢谢
就唯独这个,不会用。安装都没装上。好尴尬。
1.AOP中如何调用私有类和私有方法?
2.AOP如果拦截Initializes方法?
3.能不能新增一个可以给所有函数插桩的注解?可以用来实现打印方法耗时等功能。 @kangwang1988
作者你好,我正在使用你的框架,发现patch里的aspectd.dart
源码里的generateAspectdSnapshot
方法调用的sdkBinaryName('dart')
获取的是dart.bat可执行文件,实际上Cache.flutterRoot/bin/cache/dart-sdk/
目录下只有dart.exe
,所以会报文件找不到的错误。
我这边将 sdkBinaryName('dart')
改为:artifacts.getArtifactPath(Artifact.engineDartBinary)
,运行正常打包注入,代码片段如下:
static Future<void> generateAspectdSnapshot(
String aspectdSnapshotPath) async {
...
if (pubspecLockFile.existsSync()) {
await processManager.run(<String>[
artifacts.getArtifactPath(Artifact.engineDartBinary),
// sdkBinaryName('dart'),
'--snapshot=snapshot/aspectd.dart.snapshot',
'tool/starter.dart'
], workingDirectory: snapshotDir.parent.path);
}
}
https://ivonhoe.github.io/2019/11/08/hello-flutter-aspectd/
阅读本文你将得到什么?
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.9.1+hotfix.2, on Microsoft Windows [Version 6.1.7601], locale zh-CN)
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[√] Android Studio (version 3.4)
[!] IntelliJ IDEA Community Edition (version 2019.2)
X Flutter plugin not installed; this adds Flutter specific functionality.
[√] Connected device (1 available)
! Doctor found issues in 1 category.
git apply --3way /e/flutter/aspectd-1.9.1/0001-aspectd.patch
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/aspectd.dart' cleanly.
error: patch failed: packages/flutter_tools/lib/src/commands/build_aot.dart:5
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/commands/build_aot.dart' cleanly.
error: patch failed: packages/flutter_tools/lib/src/commands/build_bundle.dart:4
Falling back to three-way merge...
Applied patch to 'packages/flutter_tools/lib/src/commands/build_bundle.dart' cleanly.
$ flutter doctor -v
Building flutter tool...
/d/src/flutter/bin/flutter: line 46: /d/src/flutter/bin/cache/dart-sdk/bin/pub: No such file or directory
Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... (9 tries left)
Flutter version: v1.9.1+hotfix.4
Dependency:
dependencies:
flutter:
sdk: flutter
aspectd:
git:
url: [email protected]:alibaba-flutter/aspectd.git
ref: v1.9.1
Reproduce code
add the code to main.dart
T testGenericType<T>(Map<T, dynamic> param) {
return null;
}
Exception
Transformer terminated unexpectedly.
Unhandled exception:
Invalid argument(s): Type parameter T is not indexed
#0 TypeParameterIndexer.[] (package:kernel/binary/ast_to_binary.dart:2487:8)
#1 BinaryPrinter.visitTypeParameterType (package:kernel/binary/ast_to_binary.dart:2076:38)
#2 TypeParameterType.accept (package:kernel/ast.dart:5498:34)
#3 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#4 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#5 BinaryPrinter.writeNodeList (package:kernel/binary/ast_to_binary.dart:298:7)
#6 BinaryPrinter.visitInterfaceType (package:kernel/binary/ast_to_binary.dart:2016:7)
#7 InterfaceType.accept (package:kernel/ast.dart:5192:34)
#8 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#9 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#10 BinaryPrinter.visitAsExpression (package:kernel/binary/ast_to_binary.dart:1569:5)
#11 AsExpression.accept (package:kernel/ast.dart:3637:36)
#12 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#13 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#14 BinaryPrinter.writeNodeList (package:kernel/binary/ast_to_binary.dart:298:7)
#15 BinaryPrinter.visitArguments (package:kernel/binary/ast_to_binary.dart:1465:5)
#16 Arguments.accept (package:kernel/ast.dart:2955:30)
#17 BinaryPrinter.writeArgumentsNode (package:kernel/binary/ast_to_binary.dart:393:10)
#18 BinaryPrinter.visitStaticInvocation (package:kernel/binary/ast_to_binary.dart:1448:5)
#19 StaticInvocation.accept (package:kernel/ast.dart:3177:36)
#20 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#21 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#22 BinaryPrinter.writeOptionalNode (package:kernel/binary/ast_to_binary.dart:465:7)
#23 BinaryPrinter.visitReturnStatement (package:kernel/binary/ast_to_binary.dart:1897:5)
#24 ReturnStatement.accept (package:kernel/ast.dart:4577:35)
#25 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#26 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#27 BinaryPrinter.writeNodeList (package:kernel/binary/ast_to_binary.dart:298:7)
#28 BinaryPrinter.visitBlock (package:kernel/binary/ast_to_binary.dart:1756:5)
#29 Block.accept (package:kernel/ast.dart:4156:35)
#30 BinaryPrinter.writeNode (package:kernel/binary/ast_to_binary.dart:379:10)
#31 LimitedBinaryPrinter.writeNode (package:kernel/binary/limited_ast_to_binary.dart:59:11)
#32 BinaryPrinter.writeOptionalNode (package:kernel/binary/ast_to_binary.dart:465:7)
#33 BinaryPrinter.visitFunctionNode (package:kernel/binary/ast_to_binary.dart:1296:5)
#34 FunctionNode.accept (package:kernel/ast.dart:2322:30)
#35 BinaryPrinter.writeFunctionNode (package:kernel/binary/ast_to_binary.dart:386:10)
#36 BinaryPrinter.writeOptionalFunctionNode (package:kernel/binary/ast_to_binary.dart:474:7)
#37 BinaryPrinter.visitProcedure (package:kernel/binary/ast_to_binary.dart:1172:5)
#38 Procedure.accept (package:kernel/ast.dart:1984:32)
#39 BinaryPrinter.writeProcedureNode (package:kernel/binary/ast_to_binary.dart:407:10)
#40 BinaryPrinter.writeProcedureNodeList (package:kernel/binary/ast_to_binary.dart:307:7)
#41 BinaryPrinter.visitClass (package:kernel/binary/ast_to_binary.dart:1100:5)
#42 Class.accept (package:kernel/ast.dart:1043:30)
#43 BinaryPrinter.writeClassNode (package:kernel/binary/ast_to_binary.dart:421:10)
#44 BinaryPrinter.writeClassNodeList (package:kernel/binary/ast_to_binary.dart:325:7)
#45 BinaryPrinter.visitLibrary (package:kernel/binary/ast_to_binary.dart:933:5)
#46 Library.accept (package:kernel/ast.dart:468:30)
#47 BinaryPrinter.writeLibraryNode (package:kernel/binary/ast_to_binary.dart:400:10)
#48 LimitedBinaryPrinter.writeLibraries (package:kernel/binary/limited_ast_to_binary.dart:52:31)
#49 BinaryPrinter.writeComponentFile (package:kernel/binary/ast_to_binary.dart:541:5)
#50 DillOps.writeDillFile (/path/to/aspectd/util/dill_ops.dart:51:13)
<asynchronous suspension>
#51 main (/path/to/aspectd/tool/starter.dart:46:11)
#52 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:32)
#53 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
用flutter master分支的话出现的异常堆栈有所不同,具体可自测
不支持Hot reload
假设有下面的类结构
class A {
void fa(){}
}
class B {
void fb();
}
class C with A,B {
void fc(){}
}
直接改A的fa方法是无效的,需要改_C&A类的fa方法才可以。
@kangwang1988
这是一个和aspectd本身没关系的问题。
我只是想在这项目的基础上做一些定制,我在starter.dart文件里打印了一些日志,aspected.dart.snaphost也正确生成了,但是实际编译的时候却没有打印日志。另外,aspectd.dart文件中打印的语句编译时是能正常输出的。
无法hook住dart:io中的代码:
调用HttpClient的代码:
void _getIPAddress() async {
var url = 'https://httpbin.org/ip';
var httpClient = HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(utf8.decoder).join();
dynamic data = jsonDecode(json);
result = data['origin'];
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed getting IP address';
}
print(result);
}
HttpClient属于dart.io库,下面的函数无法出发。
@call("dart:io",'.', '-.+', isRegex: true)
@pragma("vm:entry-point")
dynamic instanceUniversalHook(PointCut pointcut) {
print('[KWLM4]instanceUniversalHook:${pointcut.target}-${pointcut.function}-${pointcut.namedParams}-${pointcut.positionalParams}');
dynamic obj = pointcut.proceed();
return obj;
}
@call("dart:io",'.', "+^.*$", isRegex: true)
@pragma("vm:entry-point")
static dynamic staticUniversalHook(PointCut pointcut) {
print('[KWLM5]staticUniversalHook:${pointcut.target}-${pointcut.function}-${pointcut.namedParams}-${pointcut.positionalParams}');
dynamic obj = pointcut.proceed();
return obj;
}
使用的1.9.1的patch
error: patch failed: packages/flutter_tools/lib/src/commands/build_bundle.dart:140
error: repository lacks the necessary blob to fall back on 3-way merge.
error: packages/flutter_tools/lib/src/commands/build_bundle.dart: patch does not apply
F:\flutter\flutter>flutter doctor -v
[√] Flutter (Channel unknown, v1.9.1+hotfix.2, on Microsoft Windows [Version 10.0.17763.437], locale zh-CN)
• Flutter version 1.9.1+hotfix.2 at F:\flutter\flutter
• Framework revision 2d2a1ffec9 (7 months ago), 2019-09-06 18:39:49 -0700
• Engine revision b863200c37
• Dart version 2.5.0
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at C:\Users\wangziyang\AppData\Local\Android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_SDK_ROOT = C:\Users\wangziyang\AppData\Local\Android\sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
[!] IntelliJ IDEA Community Edition (version 2019.3)
• IntelliJ at D:\develop_tools\IntelliJ IDEA Community Edition 2019.3.3
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
https://flutter.dev/intellij-setup/#installing-the-plugins
[!] IntelliJ IDEA Ultimate Edition (version 2018.2)
• IntelliJ at D:\develop_tools\IntelliJ IDEA 2018.2.5
X Flutter plugin not installed; this adds Flutter specific functionality.
• Dart plugin version 182.5215
• For information about installing plugins, see
https://flutter.dev/intellij-setup/#installing-the-plugins
[!] Connected device
! No devices available
! Doctor found issues in 4 categories.
在您的基础上尝试修改component时,read之后直接write就报错了.
Unhandled exception:
Reference to root::dart:collection is not bound to an AST node. A library was expected
#请教下是什么原因呢
1.void readComponent(Component component, {bool checkCanonicalNames: false})
2. void writeComponentFile(Component component)
Unhandled exception:
Reference to root::dart:collection is not bound to an AST node. A library was expected
#0 Reference.asLibrary (package:kernel/ast.dart:217:7)
#1 _PrivateName.library (package:kernel/ast.dart:4764:38)
#2 CanonicalName.getChildFromQualifiedName (package:kernel/canonical_name.dart:117:32)
#3 CanonicalName.getChildFromMember (package:kernel/canonical_name.dart:123:10)
#4 Class.computeCanonicalNames (package:kernel/ast.dart:917:21)
#5 Library.computeCanonicalNames (package:kernel/ast.dart:423:14)
#6 Component.computeCanonicalNamesForLibrary (package:kernel/ast.dart:5784:13)
#7 Component.computeCanonicalNames (package:kernel/ast.dart:5778:7)
Finally, paste the output of running flutter doctor -v
here.
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.5.4-hotfix.2, on Mac OS X 10.13.6 17G2208, locale zh-Hans-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
[✓] Android Studio (version 3.4)
[!] IntelliJ IDEA Ultimate Edition (version 2018.2.4)
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] Connected device (1 available)
when I am adding the dependency to aspectd_impl (pubspecyaml) as mentioned in step 2 and running flutter packages get I am getting permission denied cloning error
dependencies:
flutter:
sdk: flutter
aspectd:
git:
url: [email protected]:alibaba-flutter/aspectd.git
ref: master
example:
path: ../
[aspectd_impl] flutter packages get
Running "flutter pub get" in aspectd_impl...
Git error. Command: git clone --mirror [email protected]:alibaba-flutter/aspectd.git /home/al004/flutter_linux_v1.7.8+hotfix.4-stable/flutter/.pub-cache/git/cache/aspectd-13577356093be3047a2bed83d4a388403aa4c5c6
Cloning into bare repository '/home/al004/flutter_linux_v1.7.8+hotfix.4-stable/flutter/.pub-cache/git/cache/aspectd-13577356093be3047a2bed83d4a388403aa4c5c6'...
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
抽象类都无效了
aspectd.dart文件中getExpectedDartSha()方法获取dartSha,必须先下载DEPS文件(http://raw.githubusercontent.com/flutter/engine/$engineVersion/DEPS),这个文件必须开启vpn才能下载,有时候还很慢。为什么不直接从flutter/bin/cache/dart-sdk/revision文件中读取呢?
像这样:
static Future<String> getExpectedDartSha() async { final File dartShaFile = fs.file( fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'revision')); final String dartSha = dartShaFile.readAsStringSync().trim(); print('===dartSha: $dartSha'); return Future<String>.sync(() => dartSha); }
I have a flutter project called testproject
I have created a dart package names aspectd_impl inside my project and in the pubspec I have added the dependency
dependencies:
flutter:
sdk: flutter
aspectd:
git:
url: https://github.com/alibaba-flutter/aspectd.git
ref: master
testproject:
path: ../
even if I make it to example it gives an error
dependencies:
flutter:
sdk: flutter
aspectd:
git:
url: https://github.com/alibaba-flutter/aspectd.git
ref: master
example:
path: ../
../pubspec.yaml: "name" field doesn't match expected name "example".
It is very inconvenient to transfer the Main Package to the AOP Module for AOP functions, and the Main Package will be unidirectionally dependent by AOP, making it difficult to use classes in the AOP Module.
[✓] Flutter (Channel master, v1.8.5-pre.77, on Mac OS X 10.14 18A391, locale zh-Hans-CN)
• Flutter version 1.8.5-pre.77 at /Users/hb/development/flutter
• Framework revision 8e5fb8c35d (3 hours ago), 2019-08-07 22:29:24 -0400
• Engine revision f200ee13aa
• Dart version 2.5.0 (build 2.5.0-dev.1.0 f29f41f1a5)
flutter git 目录执行过
git apply --3way path-for-aspectd-package/0001-aspectd.patch
rm bin/cache/flutter_tools.stamp
操作
demo中const MyHomePage(title: 'Flutter Demo Home Page')
,如果切MyHomePage的构造函数,这种情况不会有打印。去掉const可以。
Git error. Command: git fetch
fatal: not a git repository (or any of the parent directories): .git
Git error. Command: git fetch
fatal: not a git repository (or any of the parent directories): .git
Git error. Command: git fetch
fatal: not a git repository (or any of the parent directories): .git
Git error. Command: git fetch
fatal: not a git repository (or any of the parent directories): .git
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.