The test is on 32-bit x86 Linux.
So basically I am trying to log the information of executed basic blocks by insert instrumentation instructions in assembly code.
My strategy is like this: Write the index of a executed basic block in a globl array, and flush the array from memory to the disk when the array is full (16M).
Here is my problem. I need the flush the array to the disk when the execution of instrumented binary is over, even if it does not reach 16M boundary. However, I just don't know where to find the exit of a assembly program.
I tried this:
grep exit from the target assembly program, and flush the memory right before the call exit instruction. But according to some debugging experience, the target C program, say, a md5sum binary, does not call exit when it finishes the execution.
Flush the memory at the end of main function. However, in the assembly code, I just don't know where is the exact end of main function. I can do a conservative approach, say, looking for all the ret instruction, but it seems to me that not all the main function ends with a ret instruction.
So here is my question, how to identify the exact execution end of a assembly code , and insert some instrumentation instructions there? Hooking some library code is fine to me. I understand with different input, binary could exit at different position, so I guess I need some conservative estimation. Am I clear? thanks!
I believe you cannot do that in the general case. First, if main is returning some code, it is an exit code (if main has no explicit return the recent C standards require that the compiler adds an implicit return 0;). Then a function could store the address of exit in some data (e.g. a global function, a field in a struct, ...), and some other function could indrectly call that thru a function pointer. Practically, a program can load some plugins using dlopen and use dlsym for "exit" name, or simply call exit inside the plugin, etc... AFAIU solving that problem (of finding actual exit calls, in the dynamic sense) in full generality can be proved equivalent to the halting problem. See also Rice's theorem.
Without claiming an exhaustive approach, I would suggest something else (assuming you are interested in instrumenting programs coded in C or C++, etc... whose source code is available to you). You could customize the GCC compiler with MELT to change the basic blocks processed inside GCC to call some of your instrumentation functions. It is not trivial, but it is doable... Of course you'll need to recompile some C code with such a customized GCC to instrument it.
(Disclaimer, I am the main author of MELT; feel free to contact me for more...)
BTW, do you know about atexit(3)? It could be helpful for your flushing issue... And you might also use LD_PRELOAD tricks (read about dynamic linkers, see ld-linux(8)).
atexit() will properly handle 95+% of programs. You can either modify its chain of registered handlers, or instrument it as you are other blocks. However, some programs may terminate by use of _exit() which does not invoke atexit handlers. Probably instrumenting _exit to invoke data flushing and installing an atexit (or on_exit() on BSD-like programs) handler should cover nearly 100% of programs.
Addendum: Note that the Linux Base Specification says that the C library startup shall:
call the initializer function (*init)().
call main() with appropriate arguments.
call exit() with the return value from main().
A method that should be working everytime would be to create a shared memory section for storing your data there.
You also create a child process which is waiting for the process being debugged to finish.
As soon as the process being debugged has finished the child process will finalize the write operations using the data that is in the shared memory.
This should work on all forms of exit, process interruptions (e.g. Ctrl+C, closing the terminal window, ...) or even if the process has been killed using "kill".
But according to some debugging experience, the target C program, say, a md5sum binary, does not call exit when it finishes the execution.
Let's take a look at a md5sum binary on an i686 GNU/Linux system:
In the disassembly (objdump -d /usr/bin/md5sum) we have this:
Disassembly of section .text:
08048f50 <.text>:
8048f50: 55 push %ebp
8048f51: 89 e5 mov %esp,%ebp
8048f53: 57 push %edi
8048f54: 56 push %esi
8048f55: 53 push %ebx
8048f56: 83 e4 f0 and $0xfffffff0,%esp
8048f59: 81 ec c0 00 00 00 sub $0xc0,%esp
8048f5f: 8b 7d 0c mov 0xc(%ebp),%edi
[ ... ]
8049e8f: 68 b0 d6 04 08 push $0x804d6b0
8049e94: 68 40 d6 04 08 push $0x804d640
8049e99: 51 push %ecx
8049e9a: 56 push %esi
8049e9b: 68 50 8f 04 08 push $0x8048f50
8049ea0: e8 4b ef ff ff call 8048df0 <__libc_start_main#plt>
8049ea5: f4 hlt
This is all startup boilerplate code. The actual program's main call is invoked inside the call __libc_start_main. If the program returns from that, then, hey look, there is a hlt instruction. That's your target. Look for that hlt instruction and instrument that as the end of the program.
You could try this:
int main()
bool keepGoing = true;
{
while(keepGoing) {
string x;
cin >> x;
if(x == "stop") {
keepGoing = false;
}
}
}
even though it is primitive... I probably butchered the coding but it's just a concept.
Related
Note, this question already has similar answers here, which I want to point out to:
"global main" in Assembly
What is global _start in assembly language?
However this question is asking more about the return formats of them and how they relate to each other (which I don't think is entirely covered in the above questions).
What are the differences between _start and main ? It seems to me like ld uses _start, but that gcc uses main as the entry point. The other difference that I've noticed is that main seems to return the value in %rax, whereas _start returns the value in %rbx
The following is an example of the two ways I'm seeing this:
.globl _start
_start:
mov $1, %rax
mov $2, %rbx
int $0x80
And to run it:
$ as script.s -o script.o; ld script.o -o script; ./script; echo $?
# 2
And the other way:
.globl main
main:
mov $3, %rax
ret
And to run it:
$ gcc script.s -o script; ./script; echo $?
3
What is the difference between these two methods? Does main automatically invoke _start somewhere, or how do they relate to each other? Why does one return their value in rbx whereas the other one returns it in rax ?
TL:DR: function return values and system-call arguments use separate registers because they're completely unrelated.
When you compile with gcc, it links CRT startup code that defines a _start. That _start (indirectly) calls main, and passes main's return value (which main leaves in EAX) to the exit() library function. (Which eventually makes an exit system call, after doing any necessary libc cleanup like flushing stdio buffers.)
See also Return vs Exit from main function in C - this is exactly analogous to what you're doing, except you're using _exit() which bypasses libc cleanup, instead of exit(). Syscall implementation of exit()
An int $0x80 system call takes its argument in EBX, as per the 32-bit system-call ABI (which you shouldn't be using in 64-bit code). It's not a return value from a function, it's the process exit status. See Hello, world in assembly language with Linux system calls? for more about system calls.
Note that _start is not a function; it can't return in that sense because there's no return address on the stack. You're taking a casual description like "return to the OS" and conflating that with a function's "return value". You can call exit from main if you want, but you can't ret from _start.
EAX is the return-value register for int-sized values in the function-calling convention. (The high 32 bits of RAX are ignored because main returns int. But also, $? exit status can only get the low 8 bits of the value passed to exit().)
Related:
Why am I allowed to exit main using ret?
What happens with the return value of main()?
where goes the ret instruction of the main
What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? explains why you should use syscall, and shows some of the kernel side of what happens inside the kernel after a system call.
_start is the entry point for the binary. Main is the entry point for the C code.
_start is specific to a toolchain, main() is specific to a language.
You can't simply start executing compiled C code, you need a bootstrap, some code that preps the minimum things that a high level language like that requires, other languages have a longer list of requirements but for C you need to either through the loader if on an operation system or the bootstrap or both a solution for the stack pointer so that there is a stack, the read/write global data (often called .data) is initialized and the zeroed (often called .bss) data is zeroed. Then the bootstrap can call main().
Because most code runs on some operating system, and the operating system can/does load that code into ram it doesn't need a hard entry point requirement as you would need for booting a processor for example where there is a hard entry point or there is a hard vector table address. So gnu is flexible enough and some operating systems are flexible enough that the entry point of the code doesn't have to be the first machine code in the binary. Now that doesn't mean that _start indicates the entry point per se as you need to tell the linker the entry point ENTRY(_start) for example if you use a linker script for gnu ld. But the tools do expect a label to be found called _start, and if the linker doesn't then it issues a warning, it keeps going but issues a warning.
main() is specific to the C language as the C entry point, the label the bootstrap calls after it does its job and is ready to run the compiled C code.
If loading into ram and if the binary file format supports it and the operating system's loader supports it the entry point into the binary can be anywhere in the binary, indicated in the binary file.
You can kind of think of _start as the entry point into the binary and main as the entry point into the compiled C code.
The return for a C function is defined by the calling convention that C compiler uses, which the compiler authors are free to do whatever they want, but modern times they often conform to a target defined (ARM, x86, MIPS, etc) defined convention. So that C calling convention defines exactly how to return something depending on the thing, so int main () is a return of an int but float myfun() might have a different rule within the convention.
The return from a binary if you can even return, is defined by the operating system or operating environment which is independent of the high level language. So on a mac on an x86 processor the rule may be one thing on Windows on an x86 the rule may be another, on Ubuntu Linux on the same x86 may be another, bsd, another, probably not but Mint Linux another, and so on.
The rules and system calls are specific to the operating system not the processor or computer or certainly not the high level language that does not directly touch the operating system anyway (handled in bootstrap or library code not in high level language code). A number of them you are supposed to make a system call not simply return a value in a register, but clearly the operating system needs to be robust enough to handle an improper return, for malformed binaries. And/or allow that as a legal return without an exiting system call, and in that case would then define a rule for how to return without a system call.
As far as main calling _start you can easily see this yourself:
int main ( void )
{
return(5);
}
readelf shows:
Entry point address: 0x500
objdump shows (not the whole output here)
Disassembly of section .init:
00000000000004b8 <_init>:
4b8: 48 83 ec 08 sub $0x8,%rsp
4bc: 48 8b 05 25 0b 20 00 mov 0x200b25(%rip),%rax # 200fe8 <__gmon_start__>
4c3: 48 85 c0 test %rax,%rax
4c6: 74 02 je 4ca <_init+0x12>
4c8: ff d0 callq *%rax
4ca: 48 83 c4 08 add $0x8,%rsp
4ce: c3 retq
...
Disassembly of section .text:
00000000000004f0 <main>:
4f0: b8 05 00 00 00 mov $0x5,%eax
4f5: c3 retq
4f6: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
4fd: 00 00 00
...
0000000000000500 <_start>:
500: 31 ed xor %ebp,%ebp
502: 49 89 d1 mov %rdx,%r9
505: 5e pop %rsi
506: 48 89 e2 mov %rsp,%rdx
509: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp
50d: 50 push %rax
50e: 54 push %rsp
50f: 4c 8d 05 6a 01 00 00 lea 0x16a(%rip),%r8 # 680 <__libc_csu_fini>
516: 48 8d 0d f3 00 00 00 lea 0xf3(%rip),%rcx # 610 <__libc_csu_init>
51d: 48 8d 3d cc ff ff ff lea -0x34(%rip),%rdi # 4f0 <main>
524: ff 15 b6 0a 20 00 callq *0x200ab6(%rip) # 200fe0 <__libc_start_main#GLIBC_2.2.5>
52a: f4 hlt
52b: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
So you can see everything I mentioned above. The entry point for the binary is not at the beginning of the binary. The entry point (for the binary) is _start, somewhere in the middle of the binary. And somewhere after _start (not necessarily as close as seen here, could be buried under other nested calls) main is called from the bootstrap code. It is assumed that .data and .bss and the stack are setup by the loader not by the bootstrap before calling the C entry point.
So in this case which is typical _start is the entry point for the binary, somewhere after it bootstraps for C it calls the C entry point main(). As the programmer though you control which linker script and bootstrap are used and as a result don't have to use _start as the entry point you can create your own (certainly can't be main() though, unless you are not fully supporting C and possibly other exceptions related to the operating system).
I am about to figure out how exactly a programm stack is set up.
I have learned that calling the function with
call pointer;
Is effectively the same as:
mov register, pc ;programcounter
add register, 1 ; where 1 is one instruction not 1 byte ...
push register
jump pointer
However, this would mean that when the Unix Kernel calls the main function that the stack base should point to reentry in the kernel function which calls main.
Therefore jumping "*rbp-1" in the C - Code should reenter the main function.
This, however, is not what happens in the following code:
#include <stdlib.h>
#include <unistd.h>
extern void ** rbp(); //pointer to stack pointing to function
int main() {
void ** p = rbp();
printf("Main: %p\n", main);
printf("&Main: %p\n", &main); //WTF
printf("*Main: %p\n", *main); //WTF
printf("Stackbasepointer: %p\n", p);
int (*c)(void) = (*p)-4;
asm("movq %rax, 0");
c();
return 0; //should never be executed...
}
Assembly file: rsp.asm
...
.intel_syntax
.text:
.global _rbp
_rbp:
mov rax, rbp
ret;
This is not allowed, unsurprisingly, maybe because the instruction at this point are not exactly 64 bits, maybe because UNIX does not allow this...
But also this call is not allowed:
void (*c)(void) = (*p);
asm("movq %rax, 0"); //Exit code is 11, so now it should be 0
c(); //this comes with stack corruption, when successful
This means I am not obliged to exit the main - calling function.
My question then is: Why am I when I use ret as seen in the end of every GCC main function?, which should do effectively the same as the code above. How does a unix - system check for such attempts effectively...
I hope my question is clear...
Thank you.
P.S.: Code compiles only on macOS, change assembly for linux
C main is called (indirectly) from CRT startup code, not directly from the kernel.
After main returns, that code calls atexit functions to do stuff like flushing stdio buffers, then passes main's return value to a raw _exit system call. Or exit_group which exits all threads.
You make several wrong assumptions, all I think based on a misunderstanding of how kernels work.
The kernel runs at a different privilege level from user-space (ring 0 vs. ring 3 on x86). Even if user-space knew the right address to jump to, it can't jump into kernel code. (And even if it could, it wouldn't be running with kernel privilege level).
ret isn't magic, it's basically just pop %rip and doesn't let you jump anywhere you couldn't jump to with other instructions. Also doesn't change privilege level1.
Kernel addresses aren't mapped / accessible when user-space code is running; those page-table entries are marked as supervisor-only. (Or they're not mapped at all in kernels that mitigate the Meltdown vulnerability, so entering the kernel goes through a "wrapper" block of code that changes CR3.)
Virtual memory is how the kernel protects itself from user-space. User-space can't modify page tables directly, only by asking the kernel to do it via mmap and mprotect system calls. (And user-space can't execute privileged instructions like mov cr3, rax to install new page tables. That's the purpose of having ring 0 (kernel mode) vs. ring 3 (user mode).)
The kernel stack is separate from the user-space stack for a process. (In the kernel, there's also a small kernel stack for each task (aka thread) that's used during system calls / interrupts while that user-space thread is running. At least that's how Linux does it, IDK about others.)
The kernel doesn't literally call user-space code; The user-space stack doesn't hold any return address back into the kernel. A kernel->user transition involves swapping stack pointers, as well as changing privilege levels. e.g. with an instruction like iret (interrupt-return).
Plus, leaving a kernel code address anywhere user-space can see it would defeat kernel ASLR.
Footnote 1: (The compiler-generated ret will always be a normal near ret, not a retf that could return through a call gate or something to a privileged cs value. x86 handles privilege levels via the low 2 bits of CS but nevermind that. MacOS / Linux don't set up call gates that user-space can use to call into the kernel; that's done with syscall or int 0x80 instructions.)
In a fresh process (after an execve system call replaced the previous process with this PID with a new one), execution begins at the process entry point (usually labeled _start), not at the C main function directly.
C implementations come with CRT (C RunTime) startup code that has (among other things) a hand-written asm implementation of _start which (indirectly) calls main, passing args to main according to the calling convention.
_start itself is not a function. On process entry, RSP points at argc, and above that on the user-space stack is argv[0], argv[1], etc. (i.e. the char *argv[] array is right there by value, and above that the envp array.) _start loads argc into a register and puts pointers to the argv and envp into registers. (The x86-64 System V ABI that MacOS and Linux both use documents all this, including the process-startup environment and the calling convention.)
If you try to ret from _start, you're just going to pop argc into RIP, and then code-fetch from absolute address 1 or 2 (or other small number) will segfault. For example, Nasm segmentation fault on RET in _start shows an attempt to ret from the process entry point (linked without CRT startup code). It has a hand-written _start that just falls through into main.
When you run gcc main.c, the gcc front-end runs multiple other programs (use gcc -v to show details). This is how the CRT startup code gets linked into your process:
gcc preprocesses (CPP) and compiles+assembles main.c to main.o (or a temporary file). On MacOS, the gcc command is actually clang which has a built-in assembler, but real gcc really does compile to asm and then run as on that. (The C preprocessor is built-in to the compiler, though.)
gcc runs something like ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie /usr/lib/Scrt1.o /usr/lib/gcc/x86_64-pc-linux-gnu/9.1.0/crtbeginS.o main.o -lc -lgcc /usr/lib/gcc/x86_64-pc-linux-gnu/9.1.0/crtendS.o. That's actually simplified a lot, with some of the CRT files left out, and paths canonicalized to remove ../../lib parts. Also, it doesn't run ld directly, it runs collect2 which is a wrapper for ld. But anyway, that statically links in those .o CRT files that contain _start and some other stuff, and dynamically links libc (-lc) and libgcc (for GCC helper functions like implementing __int128 multiply and divide with 64-bit registers, in case your program uses those).
.intel_syntax
.text:
.global _rbp
_rbp:
mov rax, rbp
ret;
This is not allowed, ...
The only reason that doesn't assemble is because you tried to declare .text: as a label, instead of using the .text directive. If you remove the trailing : it does assemble with clang (which treats .intel_syntax the same as .intel_syntax noprefix).
For GCC / GAS to assemble it, you'd also need the noprefix to tell it that register names aren't prefixed by %. (Yes you can have Intel op dst, src order but still with %rsp register names. No you shouldn't do this!) And of course GNU/Linux doesn't use leading underscores.
Not that it would always do what you want if you called it, though! If you compiled main without optimization (so -fno-omit-frame-pointer was in effect), then yes you'd get a pointer to the stack slot below the return address.
And you definitely use the value incorrectly. (*p)-4; loads the saved RBP value (*p) and then offsets by four 8-byte void-pointers. (Because that's how C pointer math works; *p has type void* because p has type void **).
I think you're trying to get your own return address and re-run the call instruction (in main's caller) that reached main, eventually leading to a stack overflow from pushing more return addresses. In GNU C, use void * __builtin_return_address (0) to get your own return address.
x86 call rel32 instructions are 5 bytes, but the call that called main was probably an indirect call, using a pointer in a register. So it might be a 2-byte call *%rax or a 3-byte call *%r12, you don't know unless you disassemble your caller. (I'd suggest single-stepping by instructions (GDB / LLDB stepi) off the end of main using a debugger in disassembly mode. If it has any symbol info for main's caller, you'll be able to scroll backward and see what the previous instruction was.
If not, you might have to try and see what looks sane; x86 machine code can't be unambiguously decoded backwards because it's variable-length. You can't tell the difference between a byte within an instruction (like an immediate or ModRM) vs. the start of an instruction. It all depends on where you start disassembling from. If you try a few byte offsets, usually only one will produce anything that looks sane.
asm("movq %rax, 0"); //Exit code is 11, so now it should be 0
This is a store of RAX to absolute address 0, in AT&T syntax. This of course segfaults. exit code 11 is from SIGSEGV, which is signal 11. (Use kill -l to see signal numbers).
Perhaps you wanted mov $0, %eax. Although that's still pointless here, you're about to call through your function pointer. In debug mode, the compiler might load it into RAX and step on your value.
Also, writing a register in an asm statement is never safe when you don't tell the compiler which registers you're modifying (using constraints).
printf("Main: %p\n", main);
printf("&Main: %p\n", &main); //WTF
main and &main are the same thing because main is a function. That's just how C syntax works for function names. main isn't an object that can have its address taken. & operator optional in function pointer assignment
It's similar for arrays: the bare name of an array can be assigned to a pointer or passed to functions as a pointer arg. But &array is also the same pointer, same as &array[0]. This is true only for arrays like int array[10], not for pointers like int *ptr; in the latter case the pointer object itself has storage space and can have its own address taken.
I think there are quite a few misunderstandings you have here. First, main is not what gets called by the kernel. The kernel allocates a process and loads our binary into memory - usually from an ELF file if you are using a Unix-based OS. This ELF file contains all of the sections that need to be mapped into memory and an address that is the "Entry Point" for the code in the ELF(among other things). The ELF can specify any address for the loader to jump to in order to start launching the program. In applications built with GCC, this is a function called _start. _start then sets up the stack and does any other initialization it needs to before calling __libc_start_main which is a libc function that can do additional set up before calling main main.
Here is an example of a start function:
00000000000006c0 <_start>:
6c0: 31 ed xor %ebp,%ebp
6c2: 49 89 d1 mov %rdx,%r9
6c5: 5e pop %rsi
6c6: 48 89 e2 mov %rsp,%rdx
6c9: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp
6cd: 50 push %rax
6ce: 54 push %rsp
6cf: 4c 8d 05 0a 02 00 00 lea 0x20a(%rip),%r8 # 8e0 <__libc_csu_fini>
6d6: 48 8d 0d 93 01 00 00 lea 0x193(%rip),%rcx # 870 <__libc_csu_init>
6dd: 48 8d 3d 7c ff ff ff lea -0x84(%rip),%rdi # 660 <main>
6e4: ff 15 f6 08 20 00 callq *0x2008f6(%rip) # 200fe0 <__libc_start_main#GLIBC_2.2.5>
6ea: f4 hlt
6eb: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
As you can see, this function sets the value of the stack and the stack base pointer. Therefore, there is no valid stack frame in this function. The stack frame is not even set to anything but 0 until you call main (at least by this compiler)
Now what is important to see here is that The stack was initialized in this code, and by the loader, it is not a continuation of the kernel's stack. Each program has its own stack, and these are all different from the kernel's stack. In fact, even if you knew the address of the stack in the kernel, you could not read from it or write to it from your program because your process can only see the pages of memory that have been allocated to it by the MMU which is controlled by the kernel.
Just to clarify, when I said the stack was "created" I did not mean that it was allocated. I only mean that the stack pointer and stack base are set here. The memory for it is allocated when the program is loaded, and pages are added to it as needed whenever a page fault is triggered by a write to an unallocated part of the stack. Upon entering start there is clearly some stack in existence as evidence from the pop rsi instruction however this is not the stack the final stack values that will be used by the program. those are the variables that get set up in _start (maybe these get changed in __libc_start_main later on, I'm not sure.)
However, this would mean that when the Unix Kernel calls the main function that the stack base should point to reentry in the kernel function which calls main.
Absolutely not.
This particular question covers the details for MacOS, please have a look. In any case main is most likely returning to start function of the C standard library. Details of implementation differ between different *nix operating systems.
Therefore jumping "*rbp-1" in the C - Code should reenter the main function.
You have no guarantee what the compiler will emit and what will be the state of rsp/rbp when you call rbp() function. You can't make such assumptions.
Btw if you want to access stack entry in 64bit you would do this in +-8 increments (so rbp+8 rbp-8 rsp+8 rsp-8 respectively).
Edit: I want to test the system by inserting a breakpoint and comparing memory before and after the breakpoint.
I used static analysis to get a list of C source code locations and debugging information (ie, a dwarf) provides a mapping between C source code and machine instructions in executable.
But the problem is that there are many machine instructions that mapped to one line of C source code and I need to test all of them.
The machine instruction to be tested is to modify the memory state.
So I want to reduce the number of instruction by eliminating the instruction that doesn't modify the memory.
For example, I have the following source code test.c and I have the line number 5.
2 int var1 = 10;
3 void foo() {
4 int *var2 = (int*)malloc(sizeof(int));
5 for(*var2=var1;;) {
6 /* ... */
7 }
8 }
To be clear, line number 5 accesses the global memory var1 and the heap memory *var2.
I compiled the above program with the command gcc -g test.c and the result is
(a.out)
00000000004004d6 <foo>:
4004d6: 55 push %rbp
4004d7: 48 89 e5 mov %rsp,%rbp
4004da: 48 83 ec 10 sub $0x10,%rsp
4004de: bf 04 00 00 00 mov $0x4,%edi
4004e3: e8 d8 fe ff ff callq 4003c0 <malloc#plt>
4004e8: 48 89 45 f8 mov %rax,-0x8(%rbp)
4004ec: 8b 15 1e 04 20 00 mov 0x20041e(%rip),%edx # 600910 <var2>
4004f2: 48 8b 45 f8 mov -0x8(%rbp),%rax
4004f6: 89 10 mov %edx,(%rax)
4004f8: eb fe jmp 4004f8 <foo+0x22>
and dwarfdump -l a.out give me the following result.
0x004004d6 [ 3, 0] NS uri: "/home/workspace/test.c"
0x004004de [ 4, 0] NS
0x004004ec [ 5, 0] NS
0x004004f8 [ 5, 0] DI=0x1
Now I know that, in the a.out, the location 0x4004ec, 0x4004f2, 0x4004f6 and 0xf004f8 are mapped to the line number 5 in C source code.
But I want to exclude the 0x4004f8 (jmp) which doesn't access the (heap, global or local) memory.
Does anyone know how to get only instructions that access memory?
This is only answering the question about finding asm instructions with explicit memory operands. The part about associating them with C statements is pretty bogus outside of -O0 compiler output (where each statement is compiled to a separate block of instructions to support GDB's jump to another line in the same function, or modifying variables in memory while stopped at breakpoint). See Basile's answer which tries to make some sense of the C statement stuff in the question.
Intel-syntax disassembly might be handy, because all explicit memory operands will have ptr in them, like mov rax, qword ptr [rbp - 0x8], so you can text search.
In asm source, the <size> ptr syntax isn't required when a register operand implies the operand size, but disassemblers like objdump -drwC -Mintel always put it in.
In AT&T syntax, you could also just look for () or a bare symbol name as an operand.
Don't forget to filter out lea instructions. lea is like the & operator in C. It's a shift-and-add instruction that uses memory-operand syntax and machine encoding.
Also don't forget to filter out various long-nop instructions that use addressing modes to get the right amount of padding in one instruction. For example:
66 2e 0f 1f 84 00 00 00 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
So if the mnemonic is lea or nop, ignore the instruction. (32-bit code sometimes uses other instructions as NOPs, but usually it's actually an lea that sets a register to itself in machine code generated by gas / ld from compiler .p2align directives.)
objdump disassembles rep stos with explicit operands, like rep stos QWORD PTR es:[rdi],rax. So you will actually get rep movs and rep stos operands. (Note that rep movs and rep cmps have two memory operands, unlike normal instructions. They're implicit in the machine code, but objdump makes them explicit.) This will also miss implicit memory operands like the stack for push / pop and call / ret.
A given C statement is compiled into several machine instructions, and several of them may access memory. Think of something like ptr->fld = arr[i++] * arr[j]--; .... BTW, in some cases, arr[j] might have been used earlier, could already sit in some register, so might not need another memory load (but only a store, which could be defered later).
I want to know the location, in executable, of the machine instruction that accesses (heap, global or local) memory generated by the given code
So your question might not make sense in general. Several machine instructions (or none of them) might access memory (related to a single C statement in your source code). And register allocation and register spilling may happen, so a given machine instruction might be related to a C variable quite far from the "current" C instruction (which has no sense).
An optimizing compiler is allowed to mix the several C statements and might output intermixed machine code. Read also about sequence points. There is no obvious mapping between machine code instruction and C statement (notably with optimizations enabled), that is why you often debug with less optimizations enabled (so gcc -g prefers to be used with -O0 or -Og, not more).
With GCC compile your src.c source file using
gcc -O -S -Wall -fverbose-asm src.c
and you'll get a slightly more readable src.s assembler file. You could use some editor or pager to look into that generated file.
Does anyone know how to get only instructions that access memory?
That does not make much sense. An optimizing compiler would sometimes share some common machine code related to several different C statements.
BTW, you might also ask GCC to dump various internal representations, for example using gcc -O -fdump-tree-all ; then you get hundreds of (textual) internal dump files (partially dumping various internal representations). Remember that GCC has hundreds of optimization passes.
Notice you might be more interested to work on GCC internal representations (e.g. GENERIC or GIMPLE or even RTL) by adding your own GCC plugin (or GCC MELT extensions). That could require months of work (notably to undestand details of GCC internal architecture and representations).
Without understanding your high-level goals and motivations, we cannot help you more.
You should read much more about semantics and about undefined behavior, which is (indirectly) more relevant to your question than what you believe.
Notice that C statements do not correspond (one to many) to machine instructions. An optimizing compiler don't compile C statements one by one, it compiles an entire translation unit at once (and may for example do inline expansions, loop unrolling, stack unwinding, constant folding, register allocation and spilling, interprocedural optimizations and dead code elimination). This is why C compilers are so complex beasts of many millions of source code lines. BTW, most C compilers (e.g. GCC or Clang) are free software, so you can spend several months or years studying their source code.
Read also some good book on compilers (e.g. the latest Dragon Book), some books on semantics, and on programming languages pragmatics.
If you are interested by GCC internals specifically, my documentation page (also available here) of GCC MELT contains lots of slides and references.
If you only care about machine instructions, you might entirely forget about C and work, with the help of some dissassembler library like libopcode (see this), only on machine code in object files.
Look also into other static source code analyers, including Coccinelle & Frama-C and libclang.
If you are interested only by GCC emitted code and can afford recompiling your C source code, you might instead work inside the GCC compiler (thru your GCC plugin or GCC MELT extension) at the GIMPLE level and detect (and perhaps transform) those GIMPLE instructions accessing memory. Detecting (and perhaps transforming) GIMPLE statements modifying memory could be simpler and might be enough.
I want to test the system by inserting a breakpoint and comparing memory before and after the breakpoint.
This is a bit similar to e.g. address sanitizers and other instrumentation features of GCC. You could spend several years working on something similar (and transforming some GIMPLE), then you probably want to add several additional passes in GCC (and you might need some extra runtime support).
Notice however that recent GDB is scriptable (in Guile or Python) and has watchpoints. If you just want to debug one particular program, that might be enough (and you might not need to dive into compiler internals, which would take many months or years of work). You should also use valgrind and address sanitizers.
In C programming language, a variable can have a memory address and a value.
And as I understood every function as well have an address and also data which allocated at that address. My question is what is the meaning of the data which these functions point to?
You already got (good) answers, but I think some (obscure?) fact about C should be pointed out, regarding your question:
In C programming language, a variable can have a memory address and a value.
Actually the defining property of a variable is that is always has a value – if it's uninitialized, semantically it still has a value, only that this value is the "undefined value" and reading the "undefined value" invokes undefined behaviour.
But, and this is important, not every variable in C does have an address! There is this little storage classifier register, which exact meaning most people do not fully comprehend. The most widespread – and wrong – interpretation is, that register means that the variable is to be placed in registers only. The problem is: There are instruction architectures in which registers do not exist, but C has been designed to be still viable for them.
The true meaning of the register classifier is, that you can not take the address of a variable that is register, which means you can not create pointers toward it.
The upshot of this is, that a variable that is register the only important thing is its value. And it is perfectly legal for the C compiler to generate code that completely discards the "place" (be it register, memory location or something entirely different) where its value came to be, as long as it able to faithfully recreate the value in a way, that it is semantically conforming to the program text. This also implies that it is perfectly legal to perform a whole re-computation of whatever had to be executed to obtain the final value. Which is why applying the register storage qualifier to variable may result in sudden increase of code size and drop of performance.
As such the register storage qualifier is not a mechanism for optimizing code, but should be treated as a special purpose tool for writing code that's neither time nor size critical but has to operate under very specific, tight constraints. One example would be for example bootloaders or system initialization code, which task it is to initialize memory access in the first place and have to operate with just a few bytes – or even none – of usable memory storage, but can re-compute values required for each step.
The C programming language is (like every programming language) a specification (in some report). It is not a software. You probably should read the n1570 (draft specification of C11) report.
Conceptually, a function does not have any data in C (but its code may refer to static addresses, contain literal constants - including pointers- etc...). It has some behavior, practically implemented by some code. What is code is not defined by the C standard.
Practically speaking, and this depends upon the particular implementation (look into the difference between Harvard machine & computer architectures and Von Neumann ones), a function pointer is some address of machine code (often, the target of the CALL machine instruction translating the C calls to it).
On desktops & laptops & tablets with some usual operating system (like Linux, Windows, MacOSX, iOS, Android...) -all are Von Neumann architectures: x86-64 or ARM-, your process has a single virtual address space containing code segments and data segments and heap data. Then function pointers and data pointers are of the same kind, and it is practically meaningful to cast between them. A canonical example is the usage of POSIX dlsym: you often cast its result to some function pointer (e.g. inside some plugin which is dynamically loaded with dlopen). The address of a function is practically speaking the address of its first machine code instruction (sitting in some code segment in the common address space). Read this & that for creative examples. Another useful example is JIT compilation libraries like asmjit, GNU lightning, libgccjit, LLVM: they enable you to generate machine code at runtime, and to get a (fresh) function pointer from these.
Neither dlsym nor JIT libraries are stricto sensu conforming to the C standard, because in a purely standard conforming C program the set of functions is statically known and any function pointer should point to some existing function of the same signature (read about calling conventions & ABIs), otherwise it is undefined behavior.
On some embedded computers with a Harvard architecture (e.g. some Arduino), code and data sit in different spaces, and a code address might not have the same number of bits than a data address. On such systems, a cast between function and data pointers is meaningless (unless you dive into deep implementation details). The C standard was specified to be general enough to take such weird computers into account.
Read also a lot more about closures and continuations. The C standard don't have them (hence callbacks conventionally take some client data argument). You probably will learn a lot by reading SICP. Read also about homoiconicity.
Read also about Operating Systems: If you use Linux (which I recommend, because it is mostly made of free software whose source code you can study), read Advanced Linux Programming. Read also Operating Systems: Three Easy Pieces.
In other words: your question (on function pointers and addresses) has different approaches. A dogmatic programming language lawyer approach (and the issue is to understand deeply the semantics of function pointers in the C standards; look also into CompCert & Frama-C); a pragmatic operating system and implementation specific approach (and then it depends upon your computer, its instruction set, and its OS and even your particular C compiler -and version- and optimization flags; and you may even have some "magic mechanisms" -like dlsym & dlopen or JIT compilation libraries- to create functions at runtime; which is magic because the C standards don't think of that).
You can find your answer here.
The C language supports two kinds of memory allocation through the variables in C programs:
Static allocation: is what happens when you declare a static or global variable. Each static or global variable defines one block of space, of a fixed size. The space is allocated once, when your program is started (part of the exec operation), and is never freed.
Automatic allocation: happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited.
In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must be a constant.
Function pointers point to blocks of machine instructions that get executed when you call the function.
Say you have this:
#include <stdio.h>
int plus_42(int x)
{
int res=x+42;
printf("%d + 42 = %d\n", x,res);
return res;
}
int main()
{
return plus_42(1);
}
If you compile it, link it, and run objdump -d on the result:
gcc plus_42.c && objdump -d a.out
you'll get (depending on your architecture, something like):
0000000000400536 <plus_42>:
400536: 55 push %rbp
400537: 48 89 e5 mov %rsp,%rbp
40053a: 48 83 ec 20 sub $0x20,%rsp
40053e: 89 7d ec mov %edi,-0x14(%rbp)
400541: 8b 45 ec mov -0x14(%rbp),%eax
400544: 83 c0 2a add $0x2a,%eax
400547: 89 45 fc mov %eax,-0x4(%rbp)
40054a: 8b 55 fc mov -0x4(%rbp),%edx
40054d: 8b 45 ec mov -0x14(%rbp),%eax
400550: 89 c6 mov %eax,%esi
400552: bf 04 06 40 00 mov $0x400604,%edi
400557: b8 00 00 00 00 mov $0x0,%eax
40055c: e8 af fe ff ff callq 400410 <printf#plt>
400561: 8b 45 fc mov -0x4(%rbp),%eax
400564: c9 leaveq
400565: c3 retq
0000000000400566 <main>:
400566: 55 push %rbp
400567: 48 89 e5 mov %rsp,%rbp
40056a: bf 01 00 00 00 mov $0x1,%edi
40056f: e8 c2 ff ff ff callq 400536 <plus_42>
400574: 5d pop %rbp
400575: c3 retq
400576: 66 2e 0f 1f 84 00 00 nopw %cs:0x0(%rax,%rax,1)
40057d: 00 00 00
plus some boilerplate.
Here, 0000000000400536 and 0000000000400566 are the addresses of main and plus_42 (= the pointers that main and plus_42 point to) respectively, and the hex numbers you see in the 2nd column is the data, which is decoded in the 3d column into human readable names of the machine instructions that the data represents.
void demo()
{
printf("demo");
}
int main()
{
printf("%p",(void*)demo);
return 0;
}
The above code prints the address of function demo.
So if we can print the address of a function, that means that this function is present in the memory and is occupying some space in it.
So how much space it is occupying in the memory?
You can see for yourself using objdump -r -d:
0000000000000000 <demo>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: bf 00 00 00 00 mov $0x0,%edi
5: R_X86_64_32 .rodata
9: b8 00 00 00 00 mov $0x0,%eax
e: e8 00 00 00 00 callq 13 <demo+0x13>
f: R_X86_64_PC32 printf-0x4
13: 5d pop %rbp
14: c3 retq
0000000000000015 <main>:
EDIT
I took your code and compiled (but not linked!) it. Using objdump you can see the actual way the compiler lays out the code to be run. At the end of the day there is no such thing as a function: for the CPU it's just a jump to some location (that in this listing happens to be labeled). So the size of the "function" is the size of the code that comprises it.
There seems to be some confusion that this is somehow not "real code". Here is what GDB says:
Dump of assembler code for function demo:
0x000000000040052d <+0>: push %rbp
0x000000000040052e <+1>: mov %rsp,%rbp
0x0000000000400531 <+4>: mov $0x400614,%edi
0x0000000000400536 <+9>: mov $0x0,%eax
0x000000000040053b <+14>: callq 0x400410 <printf#plt>
0x0000000000400540 <+19>: pop %rbp
0x0000000000400541 <+20>: retq
This is exactly the same code, with exactly the same size, patched by the linker to use real addresses. gdb prints offsets in decimal while objdump uses the more favourable hex. As you can see, in both cases the size is 21 bytes.
So if we can print the address of a function, that means that this
function is present in the memory and is occupying some space in it.
Yes, the functions you write are compiled into code that's stored in memory. (In the case of an interpreted language, the code itself is kept in memory and executed by an interpreter.)
So how much space it is occupying in the memory?
The amount of memory depends entirely on the function. You can write a very long function or a very short one. The long one will require more memory. Space used for code generally isn't something you need to worry about, though, unless you're working in an environment with severe memory constraints, such as on a very small embedded system. On desktop computer (or even mobile device) with a modern operating system, the virtual memory system will take care of moving pages of code into or out of physical memory as they're needed, so there's very little chance that your code will consume too much memory.
Of course it's occupying space in memory, the entire program is loaded in memory once you execute it. Typically, the program instructions are stored in the lowest bytes of the memory space, known as the text section. You can read more about that here: http://www.geeksforgeeks.org/memory-layout-of-c-program/
Yes, all functions that you use in your code do occupy memory space. However, the memory space does not necessarily belong exclusively to your function. For example, an inline function would occupy space inside each function from where it is called.
The standard does not provide a way to tell how much space a function occupies in memory, as pointer arithmetic, the trick that lets you compute sizes of contiguous memory regions in the data memory, is not defined for function pointers. Moreover, ISO C forbids conversion of function pointer to object pointer type, so you cannot get around this restriction by casting your function pointer to, say, a char*.
printf("%p",demo);
The above code prints the address of function demo().
That is undefined behavior: %p expects a void*, while you are passing it a void (*)(). You should see a compiler warning, telling that what you are doing is not valid (demo).
As for determining the amount of memory it is occupying, this is not possible at run-time. However, there are other ways you can determine it:
How to get the length of a function in bytes?
The functions are compiled into machine code that will run only on a specific ISA (x86, probably ARM if it's going to run on your phone, etc.) Since different processors may need more or fewer instructions to run the same function, and the length of instructions can also vary, there is no way to know in advance exactly how big the function will be until you compile it.
Even if you know what processor and operating system it will be compiled for, different compilers will create different, equivalent representations of the function depending on which instructions they use and how they optimize the code.
Also, keep in mind a function occupies memory in different ways. I think you are talking about the code itself, which is its own section. During execution, the function can also occupy space on the stack - every time the function is called, more memory is taken up in the form of a stack frame. The amount depends on the number and type of local variables and arguments declared by the function.
Yes however you can declare it as being inline, so the compiler will take the source code and move it where ever you call that function. Or you can also use preprocessor macros. Though do keep in mind using inline will generate larger code but it will execute faster, and the compiler can decide to ignore your inline request if it feels that it will become to large.