Call a method without calling it

C

#include <stdio.h>

int puts(const char *str) {
  fputs("Hello, world!\n", stdout);
}

int main() {
  printf("Goodbye!\n");
}

When compiled with GCC, the compiler replaces printf("Goodbye!\n") with puts("Goodbye!"), which is simpler and is supposed to be equivalent. I've sneakily provided my custom puts function, so that gets called instead.


Well, how is malware able to execute functions that aren't called in the code? By overflowing buffers!

#include <stdio.h>

void the_function()
{
    puts("How did I get here?");
}

int main()
{
    void (*temp[1])();         // This is an array of 1 function pointer
    temp[3] = &the_function;   // Writing to index 3 is technically undefined behavior
}

On my system, the return address of main happens to be stored 3 words above the first local variable. By scrambling that return address with the address of another function, main "returns" to that function. If you want to reproduce this behavior on another system, you might have to tweak 3 to another value.


Bash

#!/bin/bash

function command_not_found_handle () {
    echo "Who called me?"
}

Does this look like a function call to you?