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

When I read the xv6 source code, I am confused by the syntax of the declaration below. Can anyone explain this to me?

extern struct cpu *cpu asm("%gs:0"); 
+5
source share
2 answers

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

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

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

Here's a great discussion of gs (and fs) here , but in a nutshell gs points to the current local memory of the stream. The data format in gs depends on your OS (Windows is very different from Linux). This specific code says that at offset 0 from gs there is a pointer to struct cpu .

+7
source

This is a special case of the asm label . It instructs the compiler to emit %gs:0 instead of the usual character name if you are referencing a cpu variable. Presumably %gs previously configured as a storage area for each processor, with a struct cpu pointer at a zero offset. The goal is for each processor to access its own data.

+7
source

All Articles