C memcpy() a function

2019-03-30 02:44发布

Is there any method to calculate size of a function? I have a pointer to a function and I have to copy entire function using memcpy. I have to malloc some space and know 3rd parameter of memcpy - size. I know that sizeof(function) doesn't work. Do you have any suggestions?

15条回答
等我变得足够好
2楼-- · 2019-03-30 02:59

If your linker doesn't do global optimizations, then just calculate the difference between the function pointer and the address of the next function.

Note that copying the function will produce something which can't be invoked if your code isn't compiled relocatable (i.e. all addresses in the code must be relative, for example branches; globals work, though since they don't move).

查看更多
时光不老,我们不散
3楼-- · 2019-03-30 02:59

My suggestion is: don't.

Injecting code into kernel space is such an enormous security hole that most modern OSes forbid self-modifying code altogether.

查看更多
一夜七次
4楼-- · 2019-03-30 03:07

It doesn't directly answer your question, but you should not implement call-backs from kernel code to user-space.

Injecting code into kernel-space is not a great work-around either.

It's better to represent the user/kernel barrier like a inter-process barrier. Pass data, not code, back and forth between a well defined protocol through a char device. If you really need to pass code, just wrap it up in a kernel module. You can then dynamically load/unload it, just like a .so-based plugin system.

On a side note, at first I misread that you did want to pass memcpy() to the kernel. You have to remind that it is a very special function. It is defined in the C standard, quite simple, and of a quite broad scope, so it is a perfect target to be provided as a built-in by the compiler.

Just like strlen(), strcmp() and others in GCC.

That said, the fact that is a built-in does not impede you ability to take a pointer to it.

查看更多
仙女界的扛把子
5楼-- · 2019-03-30 03:08

I have done this on a Nintendo GBA where I've copied some low level render functions from flash (16 bit access slowish memory) to the high speed workspace ram (32 bit access, at least twice as fast). This was done by taking the address of the function immdiately after the function I wanted to copy, size = (int) (NextFuncPtr - SourceFuncPtr). This did work well but obviously cant be garunteed on all platforms (does not work on Windows for sure).

查看更多
SAY GOODBYE
6楼-- · 2019-03-30 03:09

Function isn't just object you can copy. What about cross-references / symbols and so on? Of course you can take something like standard linux "binutils" package and torture your binaries but is it what you want?

By the way if you simply are trying to replace memcpy() implementation, look around LD_PRELOAD mechanics.

查看更多
再贱就再见
7楼-- · 2019-03-30 03:09

I can think of a way to accomplish what you want, but I won't tell you because it's a horrific abuse of the language.

查看更多
登录 后发表回答