我可以使用一些指针(x86_64)来存储自定义数据吗?以及如果可能怎么办? [英] Can I use some bits of pointer (x86_64) for custom data? And how if possible?

查看:75
本文介绍了我可以使用一些指针(x86_64)来存储自定义数据吗?以及如果可能怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自$ cat /proc/cpuinfo | grep address:

address sizes   : 39 bits physical, 48 bits virtual
address sizes   : 39 bits physical, 48 bits virtual

因此,根据我的计算,指针大小为64位. 48位用于计算物理地址,还有16位未使用.

So, from my calculations pointer size is 64bits. 48bits are used to calculate physical address, and there are 16bits unused.

可以免费使用这些空闲的16位吗?

Can these free 16 bits be used safely?

如果是,那他们是谁?以及如何使用它们?我是否总是需要对地址或其他内容进行位掩码?

If yes, then which are they? And how can they be used? Do I always have to bitmask the address, or something else?

免责声明:我正在为将要制定的编程语言设计低级约定.我需要通过一些指针传递一个额外的微小信息,并且如果可能的话,我希望将其压缩到指针中.

推荐答案

在当前体系结构中,CPU使用的指针的最低有效48位,使您可以随意使用16个最高有效位.您要做的就是在取消引用指针之前将它们屏蔽掉,这样就可以了.

In current architectures, the least-significant 48 bits of pointers are used by the CPU, leaving you the 16 most-significant bits to use as you wish. All you have to do is mask them off before you dereference a pointer and you will be fine.

在我熟悉的每个OS中,用户模式的位47为0,因此任何用户模式指针的最高有效17位为0.这意味着简单的位掩码操作会将您的自定义数据转换为指针.如果您的指针将对齐8个字节,则您可以使用另外3个低位,以便您随意使用20个空闲位.

In every OS I'm familiar with, bit 47 is 0 for user mode, so any user mode pointer will have the most-significant 17 bits be 0. This means a simple bit mask operation will turn your custom data into a pointer. If your pointers will be 8-byte aligned, you have an additional 3 low bits that you can use, giving you 20 free bits to do with as you please.

如果您不知道指针是否设置了高位,则可以将指针存储在最高有效位中,并进行算术右移以将自定义值转换为规范指针.

If you don't know whether your pointers will have their high bit set, you can store the pointer in the most-significant bits and do an arithmetic right shift to turn the custom value into a canonical pointer.

换句话说,在指针中使用否则未使用的位是绝对安全的.您只需要遵循两个规则:

In other words, it is absolutely safe to use the otherwise-unused bits in pointer. There are just two rules you need to follow:

  1. 从不使用的比特数超出允许的范围.如果操作系统显示48 bits virtual,则意味着您只能使用高16位.如果某天有一个新的CPU表示50 bits virtual,那么您将只有14位.

  1. Never use more bits than allowed. If the OS says 48 bits virtual, that means you can only use the high 16 bits. If some day a new CPU makes it say 50 bits virtual, you would only have 14 bits.

在取消引用时始终生成规范的指针.这意味着最高的16位必须全部与第17位相同.如果您有50 bits virtual,则必须确保最高的14位与第15位的最高位相同.

Always produce a canonical pointer when dereferencing. That means the highest 16 bits must all be identical to the 17th bit. If you have 50 bits virtual, you have to make sure the highest 14 bits are identical to the 15th highest bit.

这篇关于我可以使用一些指针(x86_64)来存储自定义数据吗?以及如果可能怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆