简体   繁体   English

x86_32/64 中指针和整数之间的转换

[英]Cast between a pointer and integer in x86_32/64

I have a simple virtual machine which I made for fun.我有一个简单的虚拟机,我是为了好玩而制作的。 It works in a very low level and it doesn't have any notion of types.它在非常低的层次上工作,并且没有任何类型的概念。 Everything is just an integer.一切都只是一个整数。 There are some instructions for getting a pointer and accessing memory by a pointer.有一些获取指针和通过指针访问内存的指令。 The problem is that these pointers are simply stored as uint64_t , and any pointer arithmetic is an integer arithmetic.问题是这些指针被简单地存储为uint64_t ,并且任何指针算术都是整数算术。 The machine casts this to a void* when using it as a pointer.当将其用作指针时,机器将其转换为void* Well, this kind of code is obvious in the assembly level, but the C and C++ standard doesn't let programmers do integer-pointer cast safely, especially when the integer is used to change the value of the pointer.嗯,这种代码在汇编层面上是显而易见的,但是C和C++标准并没有让程序员安全地进行整数指针转换,尤其是当使用整数来改变指针的值时。

I'm not making this toy VM portable everywhere.我不会让这个玩具虚拟机随处携带。 It is just expected to work under x86_32/64 machines, and it does seem to work very fine even after full compiler optimizations.预计它可以在 x86_32/64 机器下工作,即使经过完整的编译器优化,它似乎也能很好地工作。 I think it's because pointers are represented no differently as integers in the x86 architecture.我认为这是因为在 x86 体系结构中,指针作为整数表示没有什么不同。

What kind of solution is usually applied in such situations, that the language standards doesn't declare certain code as safe, but it really should be safe in the targeted hardware, and the results does seem okay?在这种情况下通常采用什么样的解决方案,语言标准没有声明某些代码是安全的,但它在目标硬件中确实应该是安全的,并且结果看起来还可以?

Or as a more practical question, how can I let a compiler (gcc) not perform breaking optimizations on code like或者作为一个更实际的问题,我怎样才能让编译器(gcc)不对像这样的代码执行破坏性优化

uint64_t registers[0x100];
registers[0] = (uint64_t)malloc(8);
registers[0] += 4;
registers[2] = 0;
memcpy(&registers[2], (void*)registers[0], 4);

The above isn't real code, but a certain sequence of bytecode instructions would actually do something similar as above.以上不是真正的代码,但一定的字节码指令序列实际上会做与上面类似的事情。

If you really need to cast a pointer to an integer, use at least uintptr_t , for spaghetti monster's sake!如果您真的需要将指针转换为整数,请至少使用uintptr_t ,看在意大利面怪物的份上! This type (along with its signed counterpart) is meant to be casted safely to/from a pointer.这种类型(连同其有符号的对应物)旨在安全地转换为/从指针转换。 It is, however, not to be used for operations (but might be safe for a linear model with no modifications to the representation of both values).但是,它不能用于操作(但对于没有修改两个值的表示的线性模型可能是安全的)。

Still then, your code does not seem to make sense, but might hinder the compiler actively to optimize.尽管如此,您的代码似乎没有意义,但可能会阻碍编译器主动优化。 Without deeper knowledge about what you intend to accomplish, I would say, chances are there are better ways.如果没有对您打算完成的工作有更深入的了解,我想说,可能有更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM