What does the declaration“extern struct cpu *cpu asm(“%gs:0”);” mean?

余生颓废 提交于 2019-12-18 04:59:15

问题


When I'm reading the xv6 source code, I'm confused about the syntax of the declaration below. Can anyone explain it to me?

extern struct cpu *cpu asm("%gs:0");

回答1:


I assume you understand what extern struct cpu *cpu means. The question you have is: What does the asm("%gs:0") part mean?

This code is using a gcc extension called asm labels to say that the variable cpu is defined by the assembler string %gs:0.

This is NOT how this extension is intended to be used and is considered a hack.

There's an excellent discussion of gs (and fs) here, but in short gs points to the current thread's local storage. The format of the data at gs depends on your OS (Windows is very different than Linux). This particular code is saying that at offset 0 from gs, there is a pointer to a struct cpu.




回答2:


It is a special case of an asm label. It instructs the compiler to emit %gs:0 instead of the usual symbol name if you reference the cpu variable. Presumably %gs has been previously set up as a per-cpu storage area, with a struct cpu pointer at offset zero. The purpose is to allow each cpu to access its own data.



来源:https://stackoverflow.com/questions/39578898/what-does-the-declaration-extern-struct-cpu-cpu-asmgs0-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!