从MMAP分配的地址施放功能 - 我可以找出要使用的地址
我正在用mmap
分配一个私有内存块:(
char *err = mmap(
(void*) ( alloc_size * (1 << 20)), // Map from the start of the 2^20th page
4 * alloc_size, // for one page length
PROT_READ | PROT_WRITE | PROT_EXEC,
34, // to a private block of hardware memory
0,
0
);
alloc_size
is 1&lt;&lt; 12 = 4096
)
显然我可以施放到函数指针[typedef int(*foo)()
]类似:
foo f = (foo)0x10000000
f();
系统找到地址并因此调用函数。但是,当我尝试大于4096的东西时,问题就会发生,即1&lt;&lt; 13 = 8192
,它再也无法找到地址有效。我可以使用什么地址?所有这些都如何真正起作用?
I'm allocating a private block of memory with mmap
like this :
char *err = mmap(
(void*) ( alloc_size * (1 << 20)), // Map from the start of the 2^20th page
4 * alloc_size, // for one page length
PROT_READ | PROT_WRITE | PROT_EXEC,
34, // to a private block of hardware memory
0,
0
);
( The alloc_size
is 1<<12 = 4096
)
apparently I can cast to a function pointer [typedef int (*foo)()
] like this:
foo f = (foo)0x10000000
f();
the system finds the address and thus calls the function. But the problem occures when I try something bigger than 4096, namely 1<<13 = 8192
, it can no longer find the address valid. What address can I use and how do all of these really work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要试图找出要使用的地址。 目前
到
,将指针自然隐藏在
typedef
后面是非常差的形式,并且声明不提供原型的函数或功能指针类型是值得怀疑的。否则,是的,您可以做到这一点,但是将整数转换为指针的结果是实现定义的,除非在几个不包括该指针的情况下。如果您正在为独立实施而写作,那么这可能是有意义的,但否则却没有。我想您正在尝试将函数的地址与映射内存的地址匹配,但是只要您依靠Posix
mmap
,您也可以依靠Posix的规定来说明您可以将void *
转换为功能指针:总的来说,重点似乎是动态创建功能,然后调用它。请不要像以任何方式宽容这种活动那样回答您的问题。这是一个可怕的想法,也不得到ISO C的支持。POSIX语义提供了一种做到这一点的方法。
Don't try to figure out an address to use. By far the easiest and most portable way to do it is to let
mmap()
choose by passing a null pointer as the first argument:As far as
, it is very poor form to hide pointer nature behind a
typedef
, and it is questionable to declare a function or function pointer type that does not provide a prototype. Otherwise, yes, you can do that, but the result of converting an integer to a pointer is implementation-defined, except in a couple of narrow cases that do not include that one. If you were writing for a freestanding implementation then that might nevertheless make sense to do, but otherwise not.I suppose that you are trying to match the address of the function to the address of the mapped memory, but as long as you are relying on POSIX
mmap
, you might as well also rely on POSIX's provision that you may convert avoid *
to a function pointer:Overall, the point appears to be to create a function dynamically, and then call it. Please do not take my answering your question as in any way condoning such activity. It is a terrible idea, and not supported by ISO C. That POSIX semantics provide a way to do it in no way makes it a good idea.