How to get a pointer to a binary section in MSVC?

后端 未结 4 1763
说谎
说谎 2021-01-02 03:38

I\'m writing some code which stores some data structures in a special named binary section. These are all instances of the same struct which are scattered across many C file

4条回答
  •  暖寄归人
    2021-01-02 03:47

    First of all, you'll need to create an ASM-file containing all the sections you are interested (for ex., section.asm):

    .686
    .model flat
    
    PUBLIC C __InitSectionStart
    PUBLIC C __InitSectionEnd
    
    INIT$A SEGMENT DWORD PUBLIC FLAT alias(".init$a")
            __InitSectionStart EQU $
    INIT$A ENDS
    
    INIT$Z SEGMENT DWORD PUBLIC FLAT alias(".init$z")
            __InitSectionEnd EQU $
    INIT$Z ENDS
    
    END
    

    Next, in your code you can use the following:

    #pragma data_seg(".init$u")
    int token1 = 0xdeadbeef;
    int token2 = 0xdeadc0de;
    #pragma data_seg()
    

    This gives such a MAP-file:

     Start         Length     Name                   Class
     0003:00000000 00000000H .init$a                 DATA
     0003:00000000 00000008H .init$u                 DATA
     0003:00000008 00000000H .init$z                 DATA
    
      Address         Publics by Value              Rva+Base       Lib:Object
     0003:00000000       ?token1@@3HA               10005000     dllmain.obj
     0003:00000000       ___InitSectionStart        10005000     section.obj
     0003:00000004       ?token2@@3HA               10005004     dllmain.obj
     0003:00000008       ___InitSectionEnd          10005008     section.obj
    

    So, as you can see it, the section with the name .init$u is placed between .init$a and .init$z and this gives you ability to get the pointer to the begin of the data via __InitSectionStart symbol and to the end of data via __InitSectionEnd symbol.

提交回复
热议问题