Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python模块缓存造成对模块修改不生效 #1

Open
Cirn09 opened this issue Jul 25, 2022 · 2 comments
Open

Python模块缓存造成对模块修改不生效 #1

Cirn09 opened this issue Jul 25, 2022 · 2 comments

Comments

@Cirn09
Copy link
Owner

Cirn09 commented Jul 25, 2022

首先明确 idavscode 是通过在 Python 中调用 exec 实现启动被调试脚本,被调试脚本和 ida 插件部分执行在同一个 Python 实例下,被调试脚本执行完成后、Python 实例并不会销毁。同时 Python 对模块有缓存机制,所以在被调试脚本第二次运行会直接使用内存中的缓存,除非显式通过 importlib.reload 导入模块,否则模块不会重新加载。

解决方案有两个:
一是在调试前保存缓存,调试后恢复缓存,这也是当前的解决方案
不过这个方案有缺陷,被调试脚本运行前就被 import 的模块,脚本调试时依然不会重载。
以及其他潜在的缺陷,具体可以看 Python 文档对这部分的说明:https://docs.python.org/3/reference/import.html#the-module-cache

另一个方案是实现 import hook,调试前挂上 hook,调完卸载。

还一个可行性未知的方案,使用 C++ 实现插件,把被调试脚本扔进一个独立的 Python 实例中运行。不过不清楚嵌入 Python 支不支持多实例,IDAPython 能不能多实例。

@Cirn09
Copy link
Owner Author

Cirn09 commented Jul 25, 2022

Python 文档中有说 https://docs.python.org/zh-cn/3/reference/import.html#finders-and-loaders:

如果指定名称的模块在 sys.modules 找不到,则将发起调用 Python 的导入协议以查找和加载该模块。

理解没错的话,import hook 对强制模块 reload 没有帮助

@Cirn09
Copy link
Owner Author

Cirn09 commented Mar 15, 2023

目前是靠调试前保存所有模块列表,调试后 del 所有新增的模块。

这种方法绝大部分情形是没问题的,但是 numpy 的警告:

UserWarning: The NumPy module was reloaded (imported a second time). This can in some cases result in small but subtle issues and is discouraged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant