80
\$\begingroup\$

Inspired by a now deleted StackOverflow question. Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better.

Here's what I mean, exactly (C used just for exemplification, all languages accepted):

// Call this.
void the_function(void)
{
    printf("Hi there!\n");
}

int main(int argc, char** argv)
{
    the_function(); // NO! Bad! This is a direct call.
    return 0;
}

Original question: enter image description here

\$\endgroup\$
19
  • 59
    \$\begingroup\$ +10471 ... nice \$\endgroup\$
    – qwr
    Commented Mar 1, 2014 at 1:11
  • 31
    \$\begingroup\$ I wonder how much rep you need to overflow stack overflow? \$\endgroup\$ Commented Mar 1, 2014 at 3:07
  • 35
    \$\begingroup\$ Apparently this is a screencap from @Mysticial's account, seeing the avatar. Mysticial, could you please just click on your rep tab?!?!?! \$\endgroup\$
    – Doorknob
    Commented Mar 1, 2014 at 3:30
  • 5
    \$\begingroup\$ @Doorknob Why should he? Its all coming from one answer. \$\endgroup\$
    – FDinoff
    Commented Mar 1, 2014 at 3:37
  • 9
    \$\begingroup\$ @PyRulez Jon Skeet hasn't yet, so we're safe for now. \$\endgroup\$
    – Cole Tobin
    Commented Mar 1, 2014 at 5:14

78 Answers 78

3
\$\begingroup\$

C (with inline asm)

void the_function(void)
{
    printf("Hi there!\n");
}

int main(int argc, char** argv)
{
    _asm push the_function;
    _asm ret;
}
\$\endgroup\$
1
  • \$\begingroup\$ just to note - depending on the calling convention you can push a label from the caller function first and the code flow would even potentially remain in-tact. \$\endgroup\$
    – Nowayz
    Commented Mar 4, 2014 at 14:07
3
\$\begingroup\$

C++

In C++, if an exception is thrown during stack unwinding caused by an earlier exception which is still underway, program execution is stopped by calling a customizable terminate handler:

#include <iostream>
#include <exception>

void the_function()
{
    std::cout << "How did I get here?\n";
}

struct X
{
    ~X()
    {
        throw 2;
    }
};

int main()
{
    std::set_terminate(the_function);
    try
    {
        X x;
        throw 1;
    }
    catch (...)
    {
        std::cout << "Can't catch this!\n";
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ This crashed after it printed "How did I get here?" \$\endgroup\$
    – user10766
    Commented Mar 1, 2014 at 1:46
3
\$\begingroup\$

Groovy

By using an object's meta class you can override the toString method and call any method you choose in the closure. When outputting an object with System.out.print, by default the object's toString() method is called. Effectively using a standard Java function's default behaviour to execute your code, without a named call to the method.

class Job {
    String title

    @Override
    public String toString(){ title }
}

Job.metaClass.toString = { -> "Software Engineer".toUpperCase() }

def job = new Job(title:"Developer")

println job
\$\endgroup\$
2
\$\begingroup\$

Python

>>> def foo(*args, **kwargs):
...     print "%d args, %d kwargs" % (len(args), len(kwargs))
... 
>>> foo()
0 args, 0 kwargs
>>> foo(a=1)
0 args, 1 kwargs

then

>>> def indirect(name, *args, **kwargs):
...     globals()[name].__call__(*args, **kwargs)
... 
>>> indirect('foo', 1, 2, a=1)
2 args, 1 kwargs
>>> indirect('of'[1]+'of'[0]*2, 1, 2, a=1)
2 args, 1 kwargs
\$\endgroup\$
2
\$\begingroup\$

Preloading (DYLD_INSERT_LIBRARIES) on OSX

main.c:

#include <stdio.h>

int main(int argc, char** argv)
{
    return 0;
}

lib.c:

#include <stdio.h>
static void __attribute__ ((constructor)) lib_init(void);
static void lib_init(void) {
    printf("Hi there!\n");
}

building:

$ gcc main.c 
$ gcc -dynamiclib -o preload.dylib lib.c

test:

$ ./a.out 
$ DYLD_INSERT_LIBRARIES=preload.dylib ./a.out 
Hi there!
$ DYLD_INSERT_LIBRARIES=preload.dylib whoami
Hi there!
damien
\$\endgroup\$
2
\$\begingroup\$

Java, based on the SnakeYAML logic :P

if you know how SnakeYAML serializes you know how the method is called :P

class callme
{
    public static void main(String[]a)
    {
        new org.yaml.snakeyaml.Yaml().dump(new callme());
    }
    public void setXXX(String xxx){};
    public String getXXX()
    {
        System.out.println("who called me???");
        return "";
    }
}
\$\endgroup\$
2
\$\begingroup\$

Python

import threading


def hello():
    print('Hello, world!')


threading.Thread(target=hello).start()
\$\endgroup\$
2
\$\begingroup\$

Lua

mt = {__index = function(x) print("Who ordered that?"); end}
setmetatable(mt, mt);
i = mt.nonExistantValue;

prints

Who ordered that?


The __index function of a Lua metatable is called if a table is indexed with a value it doesn't contain. i is still nil at the end of the assignment.

Bonus points for recognizing the quotation!

\$\endgroup\$
2
  • \$\begingroup\$ This can be done a lot better in Lua. See my answer. ;) \$\endgroup\$
    – TwoThe
    Commented Mar 6, 2014 at 23:39
  • \$\begingroup\$ @TwoThe: you're right, and I'm 2 rep short right now of being able to upvote yours :( \$\endgroup\$
    – ballesta25
    Commented Mar 7, 2014 at 20:21
2
\$\begingroup\$

C

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

int __cdecl answer () {
  return 42;
}

int __cdecl multiply (int a, int b) {
  return a * b;
}

int main () {
  memcpy(multiply, answer, multiply - answer);
  printf("%i\n", multiply(6, 9));
}

Compile with gcc -O0 -N. The -N option is an undocumented linker option that makes the .text section writable.

Your antivirus software might pick it up when you compile it.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ your anti-virus does not mean windows wont let you. it will \$\endgroup\$
    – Nowayz
    Commented Mar 4, 2014 at 13:45
2
\$\begingroup\$

Perl

In Perl, to call a method "foo" you'd normally do this:

$obj->foo($arg);

The UNIVERSAL class, which all classes inherit from (equivalent to, say, java.lang.Object in Java) provides a method called can which can be called to figure out if a class has a named method. So to find out if $obj has a method called foo, you'd do this:

if ($obj->can("foo")) { ... }

Now, Perl doesn't have a built-in boolean datatype. To indicate false, you can use undef, the number 0, the empty string, the string "0", or an object overloading boolification. I can't remember which can does... for the purposes of this answer it doesn't matter. But to indicate truth can returns a reference (pointer) to the method's code.

This can then be called, passing the object itself as the first parameter:

$obj->can("foo")->($obj, $arg);   # roughly the same as: $obj->foo($arg)

OK, let's make things a little more convoluted. The B::Deparse module can take a reference to a function and return a string of Perl code representing the body of the function. Assuming that the string didn't close over any variables (and method definitions usually don't) we can then eval that string to execute it.

The one trick we need to do first is place the arguments the code needs (including the object itself) into the global array @_. So our method call becomes this:

do {
   require B::Deparse;
   my $coderef     = $obj->can("foo");
   my $deparser    = B::Deparse->new;
   my $perl_string = $deparser->coderef2text($coderef);

   local @_ = ($obj, $arg);
   eval $perl_string;
};

But if we've got that code in a string, why not place it into a file and run it?

do {
   require B::Deparse;
   require File::Temp;
   my $coderef     = $obj->can("foo");
   my $deparser    = B::Deparse->new;
   my $perl_string = $deparser->coderef2text($coderef);
   my $perl_file   = File::Temp->new;
   $perl_file->print($perl_string);
   $perl_file->close;
   local @_ = ($obj, $arg);
   do($perl_file->filename);
};

Anyway, here's the whole thing as a script:

#!/usr/bin/env perl

use v5.14;
use warnings;

package Answerer {
   sub new {
      bless {}, shift;
   }
   sub foo {
      my ($self, $n) = @_;
      return 40 + $n;
   }
}

my $obj = Answerer->new;
my $arg = 2;

my $answer = do {
   require B::Deparse;
   require File::Temp;
   my $coderef     = $obj->can("foo");
   my $deparser    = B::Deparse->new;
   my $perl_string = $deparser->coderef2text($coderef);
   my $perl_file   = File::Temp->new;
   $perl_file->print($perl_string);
   $perl_file->close;
   local @_ = ($obj, $arg);
   do($perl_file->filename);
};

say $answer;
\$\endgroup\$
2
\$\begingroup\$

Javascript

Well, there is an obvious solution in Javascript that I did not see posted. Maybe it is invalid, but I will post it anyway:

(function bla() { alert('Hello!'); })();
\$\endgroup\$
1
  • 3
    \$\begingroup\$ directly invoking the function as soon as it's defined seems to be a violation of the rules \$\endgroup\$
    – Ryan
    Commented Mar 3, 2014 at 19:00
2
\$\begingroup\$

Bash

Self-modifying script

#!/bin/bash
function command_not_found_handle () {
 echo -e ""
}
function hiddentrait {
 echo "I have a superpower!"
 echo "# hidden again" >> $0
}

echo -n "hiddentrait" >> $0

And if you see the code after an execution, the hiddentrait function is not being called either, disabled by making it a bad identifier (hiddentrait#).

\$\endgroup\$
2
\$\begingroup\$

C#

In C#, the property has an implied getter and setter

int a { get; set;}
a = 2;

This will internally call the setter method set to store the value of 2 in a. IMHO this is a shortest sample of code.

\$\endgroup\$
2
\$\begingroup\$

PHP

<?php register_shutdown_function("print_r", "Hello World!");

This code prints Hello World!.

I'm indirectly calling print_r (the rules doen't says I have to define a function, so I'm just using a native one). register_shutdown_function just calls the method when the program has ended.

\$\endgroup\$
2
\$\begingroup\$

Delphi XE3

Not sure if this is allowed but its not a direct call.
Defined a class, created it and destroyed it. The destructor isnt called directly.

type TMyType=class
  destructor Destroy;Override;
end;
var
  x:TMyType;
destructor TMyType.Destroy;
begin
  writeln('muhaha')
end;

begin
  x:=TMyType.Create;
  x.free;
end.
\$\endgroup\$
2
\$\begingroup\$

C

Involves heavy usage of #defines. You aren't calling it directly when it looks like you are calling a function called a rather than foo.

#include <stdio.h>
#define a bb
#define b cd
#define c fe
#define d ee
#define e og
#define g ho
#define h ii
#define ii o
#define ooo o

void foo() {
    printf("foo");
}
int main() {
    a();
}
\$\endgroup\$
2
\$\begingroup\$

Heres some assembly

[BITS 64]

global main

main:
    xor rax, rax    ; Set to zero
    xor rcx, rcx    ; Set to zero
    inc rax         ; increment to 1
    cmp rax, rcx
    je done         ; If they are equal, go to done

; Some function
unused_function:
    inc rcx
    cmp rax, rcx
    je main
ret             ; return from function being called

done:
ret             ; return from program

This can be compiled and run like so:

nasm -f elf64 -o file.o file.asm
gcc file.o -o file
./file

It ends up running an infinite loop. After the first cmp rax, rcx, they are not equal, and thus the program doesn't jump to done. Execution runs through to the function, which is declared below.

\$\endgroup\$
2
\$\begingroup\$

PHP

<?php

function super_secret()
{
    echo 'Halp i am trapped in comput0r';
}

function run()
{
    preg_match_all('~\{((.*?))\}~s', file_get_contents(@reset(reset(debug_backtrace()))), $x) && eval(trim(@reset($x[1])));
}

run();

This really really doesn't call the method. The backtrace is read to find out the file currently executing, we get the contents of the file as a string, then use a regex to cut the first statement out of the super_secret() method, then eval it.

The @ suppresses errors on the calls to reset(), as you're only supposed to use it on references.

\$\endgroup\$
2
\$\begingroup\$

Lua

Cause its such a great language. You can test the code here.

function i() print "Hello World" end
f = setmetatable({}, { __index = _G["\105"] })
q = f[42]

This will print Hello World

\$\endgroup\$
2
\$\begingroup\$

Ruby 1.9

c = class SomeClass

define_method(:some_method_name) {|arg|
  s = "Some method called on #{arg}"
  puts s}
end

if c === 'some class'
  puts 'Comparison of class to string succeeded, somehow'
end

Outputs "Some method called on some class". Never trust indentation. Unless it's Python.

Edit: See it live

\$\endgroup\$
5
  • \$\begingroup\$ Doesn't work... \$\endgroup\$
    – Jwosty
    Commented Mar 1, 2014 at 21:39
  • \$\begingroup\$ Works in 1.9.3, not sure about other versions. Added a link to ideone.com/7oiLGw as proof. \$\endgroup\$
    – histocrat
    Commented Mar 2, 2014 at 2:19
  • 1
    \$\begingroup\$ Ah, whatever black magic you're using doesn't work in 1.8.7 (I thought I've been using 1.9.3 all this time... :O) \$\endgroup\$
    – Jwosty
    Commented Mar 2, 2014 at 2:35
  • \$\begingroup\$ It might be because SO et al have a tendency to kill indentation, turning tabs into spaces... \$\endgroup\$ Commented Mar 2, 2014 at 10:07
  • \$\begingroup\$ It seems this trick only works on Ruby <2 though :( (now define_method returns a Symbol instead of a Proc or a Method like it used to) \$\endgroup\$
    – epidemian
    Commented Mar 4, 2014 at 3:35
1
\$\begingroup\$

Java

public class Temp {
    public static void main(String[] args) throws Exception {
        Temp.class.getMethod("main", String[].class).invoke(null, new Object[]{null});
    }
}

Not calling a method explicitly, but under the Java hood.

Also posted in Weirdest way to produce a stack overflow

\$\endgroup\$
1
\$\begingroup\$

PHP 4 and up

function hello_world()
{
        echo "Hello, world!\n";
}
 
register_shutdown_function('hello_world');
\$\endgroup\$
1
\$\begingroup\$

C

Uses nm to read the executable and find the function address, then calls it.

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

const char *me; // name of binary
int counter = 0; // just to demonstrate side-effects


// our callable functions

int itis (const char *p) {
  counter += strlen(p);
  printf("it's %s.\n", p);
  return 128;
}

int notreally (const char *p) {
  counter -= strlen(p);
  printf("i want to say it's %s, but it's not.\n", p);
  return 42;
}

typedef int (* ptr) (const char *);


// use nm to find address of function by name, then call it and
// return its return value.
int callbyname (const char *name, const char *p) {

  ptr fnptr = NULL;

  char buf[1000];
  sprintf(buf, "nm -C %s", me);
  FILE *f = popen(buf, "r");

  while (fgets(buf, sizeof(buf), f)) {
    if (strstr(buf, name)) {
      fnptr = (ptr)strtoul(buf, NULL, 16);
      break;
    }
  }

  pclose(f);

  return fnptr ? fnptr(p) : 0;

}


int main (int argc, char **argv) {

  me = argv[0];
  const char *words[] = { "awesome", "cool", "kick-ass", "the shizzle" };
  const char *names[] = { "itis", "notreally" };
  int n;

  srand(time(NULL));
  for (n = 0; n < sizeof(words)/sizeof(char*); ++ n) {
    const char *name = names[rand() % (sizeof(names)/sizeof(char*))];
    int r = callbyname(name, words[n]);
    printf("^ %i %i\n", r, counter);
  }

  return 0;

}

Compile with gcc -O0. The work is done in callbyname. The nm utility is required.

On Windows you must include the .exe suffix in the command when you run it, as argv[0] is used to determine the executable's filename.

This is basically the same as taking the address of a function, but it uses nm instead. Can be used with any function as long as it's called through the correct function pointer type.

\$\endgroup\$
1
\$\begingroup\$

C++

This program works by opening its own source file, extracting the desired function, writing it to a new source file (which prints the result), compiling it, then executing it and reading its output.

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;

//=== here's all our "callable" functions ===

int add (int a, int b) {
    return a + b;
}

int indexof (const char *str, char c) {
    for (int n = 0; str[n]; ++ n) {
        if (str[n] == c)
            return n;
    }
    return -1;
}

const char * addsuffix (int n) {
    static char buffer[20];
    switch (n % 10) {
      case 1: sprintf(buffer, "%dst", n); break;
      case 2: sprintf(buffer, "%dnd", n); break;
      default: sprintf(buffer, "%dth", n); break;
    }
    return buffer;
}

//=== end of "callable" functions ===

int count (const char *s, int c) {
    int n = 0;
    while (*s)
        n += (*(s ++) == c);
    return n;
}

template <typename ReturnType>
ReturnType icall (const char *fn, const char *p) {

    // generate output

    ifstream me(__FILE__);
    ofstream out("temp~.cpp");
    char line[1000];
    int infunc = 0;

    while (!me.eof()) {
        me.getline(line, sizeof(line));
        if (!strncmp(line, "#include", 8))
            out << line << endl;
        else if (!strncmp(line, "using", 5))
            out << line << endl;
        else {
            if (!infunc) {
                char *fname = strstr(line, fn);
                if (fname) {
                    infunc += 1;
                    *fname = 0;
                    out << line << "oneTrickPony" << (fname + strlen(fn)) << endl;
                    *fname = ' ';
                }
            } else {
                out << line << endl;
            }
            if (infunc)
                infunc += count(line, '{') - count(line, '}');
            if (strchr(line, '}') && infunc == 1)
                break;
        }
    }

    out << "int main () { cout << oneTrickPony(" << p << "); }" << endl;
    out.close();

    // compile output

    system("g++ temp~.cpp -o temp~.exe"); // exe suffix ok on linux

    // execute output
    FILE *res = popen("temp~.exe", "r");
    fgets(line, sizeof(line), res);
    pclose(res);

    // parse output

    ReturnType rval;
    stringstream rss(line);
    rss >> rval;
    return rval;

}

#define call(rt,fn,p...) icall<rt>(fn, #p)


int main () {

    // call functions and store results
    int resulta = call(int, "add", 14, 99);
    int resultn = call(int, "indexof", "abcdefg", 'e');
    string results = call(string, "addsuffix", 1);

    // print results
    cout << resulta << endl
        << resultn << endl
        << results << endl;

}

The icall function is responsible for doing all the dirty work; the template type is the return type and is used for parsing the output into a usable value. The call macro exists to allow us to write a variable number of function parameters to the generated source file. The calls are made in main:

  // call functions and store results
  int resulta = call(int, "add", 14, 99);
  int resultn = call(int, "indexof", "abcdefg", 'e');
  string results = call(string, "addsuffix", 1);

Requires gcc. Tested on MinGW.

Supports:

  1. Any return types supported by the istream >> operator.
  2. Runtime function names.
  3. Any number of parameters, of any type.

Does not support:

  1. Non-constant function parameters. This is a tradeoff for number 3 and also for brevity. I could add support for this by dropping the macro and using more templates, but I didn't want to add too much code to distract from the general idea.
  2. Functions with void return types. A specialized icall that does not parse the returned value would allow this. Again, didn't go too crazy.

A little messy but gets the job done. It's pretty good at parsing itself but will fail under certain conditions (e.g. if a curly brace appears in a string, or the function name appears before the function in another context... I didn't really want to implement a full-on C++ parser...).

Here is an example generated file for a call to indexof:

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
int oneTrickPony (const char *str, char c) {
  for (int n = 0; str[n]; ++ n) {
    if (str[n] == c)
      return n;
  }
  return -1;
}
int main () { cout << oneTrickPony("abcdefg", 'e'); }
\$\endgroup\$
1
\$\begingroup\$

AutoHotkey

Here are four distinct ways of indirectly calling a function

;built in indirect function call
funcy := Func("func2Call")
funcy.()

;register this function so that it can be called from any program, then call it as if it's a DLL
funcy := RegisterCallback("func2Call")
DllCall(funcy)

;as error handler
try
    throw
catch
    func2call()


;as default method of default base object
r.base.__Call := func("func2Call")

randomString.randomFuncName()

func2Call()
{
    MsgBox, Don't call this number ever again!!
}
\$\endgroup\$
1
  • \$\begingroup\$ Idk 'bout AHK but I think error handler is direct call. \$\endgroup\$ Commented Apr 11, 2016 at 19:18
1
\$\begingroup\$

Javascript

It's not pretty:

function myFun(arg) {
    alert("Called with "+arg);
}

// To "call" that with the argument 'toast':

var arg1 = 'toast';
eval("("+ myFun.toString() +")(arg1)");

From an unloved answer by Engineer.

We are still calling a function, but arguably not the original function - we are calling a new function we created using the source code of the original.

An alternative might be to strip the function wrapper around myFun.toString() and eval the function's body code directly, but then there are complications passing it the correct arguments.

\$\endgroup\$
1
  • \$\begingroup\$ The complications could be avoided by creating a new Function(...) passing it the body of the original. That new function could have arguments passed to it. One major caveat with all these approaches in Javascript is that we cannot get back the scope that the original function ran in, so if it had any closure on outer variables these would be lost. \$\endgroup\$ Commented Aug 1, 2014 at 10:12
1
\$\begingroup\$

C

Signal handling:

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

void fun(int) {
  puts("fun()");
  exit(0);
}

int main() {
  int *null = 0;

  signal(SIGSEGV, &fun);

  printf("%d", *null);
}
\$\endgroup\$
1
\$\begingroup\$

Python 3:

import reprlib

class Repr(reprlib.Repr):
    def repr_module(self, obj, level):
        return "How?"

print(Repr().repr(__import__("antigravity")))

http://docs.python.org/3.1/library/reprlib.html

\$\endgroup\$
1
\$\begingroup\$

Scala using reflection

class Shy {
  private def AhaYouWillNeverCallMe() = println("Argh you found me.")
}

classOf[Shy].getDeclaredMethods.map(
  knowledge => { knowledge.setAccessible(true);
  knowledge }).head.invoke(new Shy)

Scala using implicits

implicit def YouShouldNotWakeMeUp(i: String) = { println("Ok ok I wake up"); 1}
1/""
\$\endgroup\$
1
\$\begingroup\$

C (With GCC inline asm)

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

void the_function(void)
{
    __asm__ volatile ("boo:");
    printf("Hi there!\n");
}

int main(void)
{
    __asm__ volatile ("jmp boo");
    return 0;
}
\$\endgroup\$