How to use the fixups attribute on a section? - windows

What exactly does "fixups" do when applied on a section?
In a fasm sample i found the following section delcaration and i'm really not sure what the fixups attribute does, i couldn't find much information on that in the fasm documentation.
section '.reloc' fixups data readable discardable
if $=$$
dd 0,8 ; if there are no fixups, generate dummy entry
end if

This appears to be a workaround for a bug in how FASM generates PECOFF DLLs. The .reloc section only applies to PECOFF images (EXEs and DLLs), and provides relocations (or "fixups") that allow the image to be loaded at any address. (Relocations of a different sort are used in PECOFF object files; these fixups aren't put in the .reloc section.)
The bug in FASM is that it will generate an empty .reloc section if the DLL doesn't need any relocations rather than not generating one at all. Windows will refuse to load a DLL (or EXE) if has an empty section. The workaround forces a non-empty .reloc section, by adding a dummy "base relocation block" if the .reloc section doesn't have any contents.
Apparently the developer of FASM doesn't think this is a bug in FASM, but rather a bug in Windows, and so hasn't fixed it.
To answer your question directly, the fixups keyword appears to indicate that this section is special to FASM, that it's used for image relocations as described above. Unlike the the other attributes it doesn't correspond to one of the section flags used in PECOFF images, so it appears to only be used internally by FASM.

fixups is just another name for relocation entries.
If you are new to relocation on PE, take a look at the official specifications.
Relocation entries tell the loader how to fix (hence the name fixups) the addresses in the compiled code.
The fixups directive tell FASM that the section declared is the one where the relocation entry should be generated (automatically).
You can still add your data though, presumably the fixups are written before any user supplied data1.
The test if $=$$ check if the current address counter ($) is equal to the value of the address counter when the section started ($$).
If that is true, the user data will be written at the start of the section, hence no fixups have been generated.
The two dwords dd 0, 8 create an empty entry (a dummy entry).
The second DWORD specify the length of the whole entry including the 8 bytes header, a value of 8 specify no additional data.
I don't know why such dummy entry is created.
1 Just inferring this from the snippet, I don't know for sure.

Related

Using Linker Symbol from C++ code as a fixed constant (NOT relocated) in a shared library (DLL)

Sorry if the title is not very clear. I am using MinGW with GCC 6.3.0 to build a x86 32-bit DLL on Windows (so far). I'll spare you the details why I need hacky offsets amongst its sections accessible from code, so please do not ask if it's useful or not (because I don't want to bother explaining that).
So, if I can get the following testcase to work, I'm good. Here's my problem:
In a C++ file, I want to access a linker symbol as an absolute numeric value, not relocated, directly. Remember that I am building a 32-bit DLL which requires a .reloc section for relocations, but in this case I do NOT want relocation, in fact a relocation would screw it up completely.
Here's an example: retrieve the offset of say __imp__MessageBoxW#16 relative to __IAT_start__, in case you don't know what they are, __imp__MessageBoxW#16 is the relocated pointer to the actual function at runtime, and __IAT_start__ is a linker symbol in the default script file. Here's where it is defined:
.idata BLOCK(__section_alignment__) :
{
/* This cannot currently be handled with grouped sections.
See pe.em:sort_sections. */
KEEP (SORT(*)(.idata$2))
KEEP (SORT(*)(.idata$3))
/* These zeroes mark the end of the import list. */
LONG (0); LONG (0); LONG (0); LONG (0); LONG (0);
KEEP (SORT(*)(.idata$4))
__IAT_start__ = .;
KEEP (SORT(*)(.idata$5))
__IAT_end__ = .;
KEEP (SORT(*)(.idata$6))
KEEP (SORT(*)(.idata$7))
}
So far, no problem. Because GAS doesn't allow me to "subtract" two externally defined symbols (both symbols are defined in the linker), I have to define the symbol in the linker script, so at the end of the linker script I have this:
test_symbol = ABSOLUTE("__imp__MessageBoxW#16" - __IAT_start__);
Then in C++ I use this little inline asm to retrieve this relative difference which is supposed to be a fixed value once linked:
asm("movl $test_symbol, %0":"=r"(var));
Now var should contain that fixed number right? Wrong!
Because test_symbol is an "undefined" symbol as far as the assembler is concerned, it makes it relocated. Or I don't know why, but I tried so many things to force it to be an "absolute constant value symbol" instead of a "relocated symbol" to no avail. Even editing the linker script with many things like LD_FEATURE("SANE_EXPR") and others, doesn't work at all.
Its value is correct only if the DLL does not get relocated.
You see, either GNU LD or the assembler adds an entry in the .reloc section for that movl instruction, which is WRONG!
Is there a way to force it to treat an external/undefined symbol as a fixed CONSTANT and apply no relocation to it whatsoever? Basically, omit it from the .reloc section.
I am going crazy with this, please tell me there's something easy I overlooked, I searched for hours!
In other words, is there a way to use a Linker Symbol from within inline asm/C++ without having it relocated whatsoever? No entry to the .reloc section or anything, basically same as a constant like $1234. So if a DLL gets loaded into another base address, that constant would be the same everytime.
UPDATE: I forgot about this question but decided to bring an update, since it seems it's likely not possible as nobody even commented. For anyone else in the same boat as me, I presume this is a limitation of the COFF object format itself. In other words, external symbols are implicitly relocated, and it doesn't seem there's a way against this.
I didn't "fix" it the way I wanted, I did it in a very hacky way though. If anyone is interested, here's my ugly "hack":
First I put a special "custom" instruction in the inline assembly where I reference this external symbol from C++. This "custom" instruction holds a placeholder instruction that grabs the symbol (normal x86 asm instruction with a dummy constant, e.g. 1234) and a way to identify it. Then let GCC generate the assembly files (.S files), then I parse the assembly with a simple script and when I find that "custom" instruction I insert a label for the linker (make it .global) and at the same time add a directive to a custom "on-the-fly" generated linker script that gets included from my main linker script at the end.
This places data in a temporary section in the resulting DLL with absolute offsets to the custom instruction that I need, but without relocation.
Next, I parse the binary DLL itself, in particular that temporary section I added with all this hack. I take the offsets from there, convert them to file offsets, and modify the DLL's .text section directly where those offsets point (remember those placeholder instructions? it is replacing their immediate constants 1234 with the respective value from the linker's non-relocated constant). Then I strip the temporary section from the DLL, and it's done. Of course, all of this is done automatically by a helper program and script
It's an insane hack, but it works and it's fully automatic now that I got it going. If my assumption is correct that COFF doesn't support non-relocated external symbols, then it's really the only way to use linker constants from C++ without them being relocated, which would be a disaster.

Is it possible to make writeable variables in .text segment using DB directive in NASM?

I've tried declaring variables in .text segment using e.g. file_handle: dd 0.
However, trying to store something in this variable like mov [file_handle], eax results in a write error.
I know, I could declare writeable variables in the .data segment, but to make the code more compact I'd like to try it as above.
Is the only possibility to use the stack for storing these value (e.g. the file handle), or could I somehow write to my variable above?
Executable code segments are not writable by default. This is a basic security precaution. No, it's not a good idea. But if you insist, as this is a toy project anyway, go ahead.
You can make yours writable by letting the linker know to mark it so, e.g. give the following argument to the MS linker:
link /SECTION:.text,EWR ....
You can actually arrange for the text segment of your Windows process to be mapped read+write+execute, see #Kuba's answer. This might also be possible on Linux with ELF binaries; I think ELF has similar flags for segments.
I think you could also call a Windows function (VirtualProtect) to change the mapping of your text segment to read+write+execute from inside your process.
Overall this sounds like a terrible idea, and you should definitely keep temporaries on the stack like a C compiler would, if you want to avoid having a data page.
Static storage for things you only use in part of the program is wasteful.
No it's not possible to have writable "variable" in .text section of an assembly program.
When writing file_handle: dd 0 in the .text section and then assemblying, your label file_handle refers to an address located in the text section of your binary. However the text section is read-only.
If the text section wasn't only read-only accessible, a program could modify itself while executing.

ELF modify section flags

I compiled a C code using gcc and when I check the sections of the ELF using readelf I can see that the flags for .data section are set to WA (Writable and Allocatable).
Is it possible to modify these flags? Can I make this section executable?
I am using gdb to debug this binary and I would like to set the flags for .data section as Executable at a certain point. So, can this be done using either gdb or gcc?
Is it possible to modify these flags? Can I make this section executable?
Yes. If you want to do this as a one-off, the simplest approach may be to compile source to assembly, and modify section attributes there, then compile assembly into object file and link as usual.
I am using gdb to debug this binary and I would like to set the flags for .data section as Executable at a certain point.
You also could call mprotect(addr, len, PROT_READ|PROT_WRITE|PROT_EXEC) from within GDB.
Note: modifying the flags in the .data section after the binary has been linked will have no effect whatsoever: the kernel doesn't look at sections, only at PT_LOAD segments.
how to mark the data section as executable in the assembly code? I think, something like this: .section .data,"awx",#progbits.
Yes, that looks correct. Did it not work?
mprotect() not found
Is your executable statically linked? If not, mprotect should be found (in libc.so), and you possibly have a GDB bug. It may help to nudge GDB into finding mprotect if you print &mprotect first.
Also note: mprotect(0x0804a020, 80, PROT_READ, PROT_WRITE, PROT_EXEC) is very different from what I suggested (mprotect takes 3 parameters, not 5). You also need to read man mprotect carefully -- it requires start address to be page-aligned.

Using DLLs with NASM

I have been doing some x86 programming in Windows with NASM and I have run into some confusion. I am confused as to why I must do this:
extern _ExitProcess#4
Specifically I am confused about the '_' and the '#4'. I know that the '#4' is the size of the stack but why is it needed? When I looked in the kernel32.dll with a hex editor I only saw 'ExitProcess' not '_ExitProcess#4'.
I am also confused as to why C Functions do not need the underscore and the stack size such as this:
extern printf
Why don't C Functions need decorations?
My third question is "Is this the way I should be using these functions?" Right now I am linking with the actual dll files themselves.
I know that the '#4' is the size of the stack but why is it needed?
To enable the linker to report a fatal error if your compiler assumed the wrong calling convention for the function (this can happen if you forget to include header files in C and ignore all the compiler warnings or if a declaration doesn't exactly match the function in the shared library).
Why don't C Functions need decorations?
Functions that use the cdecl calling convention are decorated with a single leading (so it would actually be _printf).
The reason why no parameter size is encoded into the decorated name is that the caller is responsible for both setting up and tearing down the stack, so an argument count mismatch will not be fatal for the stack setup (though the calling function might still crash if it isn't given the right arguments, of course). It might even be possible that the argument count is variable, like in the case of printf.
When I looked in the kernel32.dll with a hex editor I only saw ExitProcess not _ExitProcess#4.
The mangled names are usually mapped to the actual exported names of the DLL using definition files (*.def), which then get compiled to *.lib import library files that can be used in your linker invocation. An example of such a definition file for kernel32.dll is this one. The following line defines the mapping for ExitProcess:
_ExitProcess#4 = ExitProcess
Is this the way I should be using these functions?
I don't know NASM very well, but the code I've seen so far usually specifies the decorated name, like in your example.
You can find more information on this excellent page about Win32 calling conventions.

How can I force the order of functions in a binary with the gcc toolchain?

I'm building a static binary out of several source files and libraries, and I want to control the order in which the functions are put into the resulting binary.
The background is, I have external code which is linked against offsets in this binary. Now if I change the source, all the offsets change because gcc may decide to order the functions differently, so I want to put the referenced functions at the beginning in a fixed order so their offsets stay unchanged...
I looked through ld's documentation but couldn't find anything about order of functions.
The only thing i found was -fno-toplevel-reorder which doesn't really help me.
There is really no clean and reliable way of forcing a function to a particular address (except for the entry function) or even forcing functions having a particular order (and if you could enforce the order that would still not mean that the addresses stay the same when the source is changed!).
The biggest problem that I see is that even if it may be possible to fix a function to some address, it will be sheer impossible to fix all of them to exactly the addresses that the already existing external program expects (assuming you cannot modify this program). If that actually worked, it would be total coincidence and sheer luck.
It might be almost easiest to provide trampolines at the addresses that the other program expects, and having the real functions (whereever they may be) pointed to by these. That would require your code to use a different base address, so the actual program code doesn't collide with the trampolines.
There are three things that almost work for giving functions fixed addresses:
You can place each function that isn't allowed to move in its proper section using __attribute__ ((section ("some name"))). Unluckily, .text always appears as the first section, so if anything in .text changes so the size is bumped over the 512 byte boundary, your offsets will change. By default (but see below) you can't get a section to start before .text.
The -falign-functions=n commandline option lets you align functions to a boundary. Normally this is something around 16 bytes. Now, you could choose a large value like for example 1024. That will waste an immense amount of space, but it will also make sure that as long as functions only change moderately, the addresses of the following functions will remain the same. Obviously it still does not prevent the compiler/linker from reordering entire blocks when it feels like it (though -fno-toplevel-reorder will prevent this at least partially).
If you are willing to write a custom linker script, you can assign a start address for each section. These are virtual memory addresses, not positions in the executable, but I assume the hard linking works with VMAs (based on the default image base) too. So that could kind of work, although with much trouble and not in a pretty way.
When writing your own linker script, you could also consider putting the functions that must not move into their own sections and moving these sections at the beginning of the executable (in front of .text), so changes in .text won't move your functions around.
Update:
The "gcc" tag suggests that you probably target *NIX, so again this is probably not going to help you, but... if you have the option to use COFF, dollar-sign sections might work (the info might be interesting for others, in any case).
I just stumbled across this today (emphasis mine):
The "$" character (dollar sign) has a special interpretation in section names in object files. When determining the image section that will contain the contents of an object section, the linker discards the "$" and all characters that follow it. Thus, an object section named .text$X actually contributes to the .text section in the image. However, the characters following the "$" determine the ordering of the contributions to the image section. All contributions with the same object-section name are allocated contiguously in the image, and the blocks of contributions are sorted in lexical order by object-section name. Therefore, everything in object files with section name .text$X ends up together, after the .text$W contributions and before the .text$Y contributions.
If the documentation does not lie (and if I'm not reading wrong), this means you should be able to pack all the functions that you want located in the front into one section .text$A, and everything else into .text$B, and it should do just that.
Build your code with -ffunction-sections -- this will place each function into its own section.
If you are using GNU-ld, the linker script gives you absolute control, but is a very platform-specific and somewhat painful solution.
A better solution might be to use the recent work on gold, which allows exactly the function ordering you are seeking.
A lot of it comes from the order the functions are in the file and the order the files are on the command line when you link.
Embed something in the code that your external code can find, a const structure with some ascii code and the address to functions perhaps, then no matter where the compiler puts the functions you can find them.
that or use the normal .dll or .so mechanisms, and not have to mess with it.
In my experience, gcc -O0 will fix the binary order of functions to match the order in the source code.
However as others have mentioned, even if the order is fixed, the offsets can change as you modify the source code or upgrade your toolchain.

Resources