I use the funchook library hook PyUnicode_Format function, and my code looks like this,
https://github.com/kubo/funchook
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <funchook.h>
#include <stdio.h>
// Original PyUnicode_Format function pointer
static PyObject *(*orig_PyUnicode_Format)(PyObject *format, PyObject *args) = NULL;
// Hooked version of PyUnicode_Format
static PyObject *hooked_PyUnicode_Format(PyObject *format, PyObject *args) {
printf("PyUnicode_Format is called with format: %sn", PyUnicode_AsUTF8(format));
// Call the original function
return orig_PyUnicode_Format(format, args);
}
static int hook_PyUnicode_Format() {
funchook_t *funchook = funchook_create();
if (funchook == NULL) {
return -1;
}
// Get the address of the original PyUnicode_Format function
orig_PyUnicode_Format = (PyObject *(*)(PyObject *, PyObject *))PyUnicode_Format;
// Prepare the hook
if (funchook_prepare(funchook, (void **)&orig_PyUnicode_Format, (void *)hooked_PyUnicode_Format) != 0) {
funchook_destroy(funchook);
return -1;
}
// Install the hook
if (funchook_install(funchook, 0) != 0) {
funchook_destroy(funchook);
return -1;
}
return 0;
}
// Module initialization function
static PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"myhook",
"A module that hooks PyUnicode_Format",
-1,
NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_myhook(void) {
if (hook_PyUnicode_Format() != 0) {
return NULL;
}
return PyModule_Create(&moduledef);
}
setup(
packages=find_packages(),
data_files=[
('lib', ['funchook/libfunchook.so.2']), # 将库文件安装到lib目录
],
name="test_module",
include_package_data=True,
ext_modules=[
Extension(
name="myhook",
sources=["spammify.c"],
include_dirs=include_dirs,
library_dirs=include_dirs,
libraries=["funchook"],
runtime_library_dirs=['$ORIGIN/lib']
),
]
)
import myhook
print("as{0}".format("a"))
I use PyCharm, and when I start it normally, it doesn’t work. However, when I debug the program to start it, it can output normally and print the following content on the console
asa
PyUnicode_Format is called with format: IDE_PROJECT_ROOTS %s
PyUnicode_Format is called with format: LIBRARY_ROOTS %s
Who can help me,I can’t find examples on the Internet