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

108
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ @user17752 This is actually a transformation GCC makes even at -O0. (GCC 4.8, anyway. Perhaps other versions do need some other options.) \$\endgroup\$
    – hvd
    Commented Mar 2, 2014 at 9:02
  • 1
    \$\begingroup\$ sorry, my mistake, forgot that i was using clang on my macbook. \$\endgroup\$
    – user17752
    Commented Mar 2, 2014 at 10:24
  • \$\begingroup\$ @user17752 Thanks, I hadn't tested with other compilers, nice to know that clang at least has an option to get the same transformation. \$\endgroup\$
    – hvd
    Commented Mar 2, 2014 at 19:28
  • \$\begingroup\$ Congratulation! A winner is you! \$\endgroup\$
    – user12385
    Commented Mar 21, 2014 at 17:35
85
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Beat me to it (+1) - this is the obvious C solution. \$\endgroup\$
    – Comintern
    Commented Mar 1, 2014 at 1:25
  • 20
    \$\begingroup\$ Use <!-- language: lang-c --> two lines before your code to highlight it. \$\endgroup\$ Commented Mar 1, 2014 at 4:43
  • 9
    \$\begingroup\$ All hail @Victor, syntax highlighting hero! \$\endgroup\$
    – Jason C
    Commented Mar 2, 2014 at 3:38
  • \$\begingroup\$ @Victor is this officially documented? If yes, where? \$\endgroup\$ Commented Mar 4, 2014 at 9:18
  • 3
    \$\begingroup\$ @ThorbjørnRavnAndersen meta.stackexchange.com/questions/184108/… \$\endgroup\$ Commented Mar 4, 2014 at 9:22
77
\$\begingroup\$

Bash

#!/bin/bash

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

Does this look like a function call to you?
\$\endgroup\$
1
  • 8
    \$\begingroup\$ Exception handling. The other method call! \$\endgroup\$
    – phyrfox
    Commented Mar 2, 2014 at 0:14
57
\$\begingroup\$

Python 2

>>> def func(*args):
        print('somebody called me?')

Here are some ways inspired by the other answers:

  1. executing the code directly

    >>> exec(func.func_code) # just the code, not a call
    somebody called me?
    

    This is the best way of really not calling the function.

  2. using the destructor

    >>> class X(object):pass
    >>> x = X()
    >>> X.__del__ = func # let  the garbage collector do the call
    >>> del x
    somebody called me?
    
  3. Using the std I/O

    >>> x.write = func # from above
    >>> import sys
    >>> a = sys.stderr
    >>> sys.stderr = x
    >>> asdjkadjls
    somebody called me?
    somebody called me?
    somebody called me?
    somebody called me?
    somebody called me?
    >>> sys.stderr = a # back to normality
    
  4. using attribute lookups

    >>> x = X() # from above
    >>> x.__get__ = func
    >>> X.x = x
    >>> x.x # __get__ of class attributes
    somebody called me?
    <__main__.X object at 0x02BB1510>
    >>> X.__getattr__ = func
    >>> x.jahsdhajhsdjkahdkasjsd # nonexistent attributes
    somebody called me?
    >>> X.__getattribute__ = func
    >>> x.__class__ # any attribute
    somebody called me?
    
  5. The import mechanism

    >>> __builtins__.__import__ = func
    >>> import os # important module!
    somebody called me?
    >>> os is None
    True
    

    Well I guess that's all.. I can not import anything now. No wait..

  6. Using the get-item brackets []

    >>> class Y(dict): pass
    >>> Y.__getitem__ = func
    >>> d = Y()
    >>> d[1] # that is easy
    somebody called me?
    
  7. Using global variables. My favorite!

    >>> exec "hello;hello" in d # from above
    somebody called me?
    somebody called me?
    

    hello is an access to d['hello']. After this the world seems gray.

  8. Meta classes ;)

    >>> class T(type): pass
    >>> T.__init__ = func
    >>> class A:
        __metaclass__ = T
    somebody called me?
    
  9. Using iterators (you can overload any operator and use it)

    >>> class X(object): pass
    >>> x = X()
    >>> X.__iter__ = func
    >>> for i in x: pass # only once with error
    somebody called me?
    
    >>> X.__iter__ = lambda a: x 
    >>> X.next = func
    >>> for i in x: pass # endlessly!
    somebody called me?
    somebody called me?
    somebody called me?
    ...
    
  10. Errors!

    >>> class Exc(Exception):__init__ = func
    >>> raise Exc # removed in Python 3
    somebody called me?
    
  11. Frameworks call you back. Almost every GUI has this functionality.

    >>> import Tkinter
    >>> t = Tkinter.Tk()
    >>> t.after(0, func) # or QTimer.singleShot(1000, func)
    >>> t.update()
    somebody called me?
    
  12. Execute the source string (func must be in a file)

    >>> import linecache
    >>> exec('if 1:' + '\n'.join(linecache.getlines(func.func_code.co_filename, func.func_globals)[1:]))
    somebody called me?
    
  13. Decorators

    >>> @func
    def nothing():pass
    sombody called me?
    
  14. with pickle de-serialization (least favorites coming)

    >>> import pickle # serialization
    >>> def __reduce__(self):
        return func, ()
    >>> X.__reduce__ = __reduce__
    >>> x = X()
    >>> s = pickle.dumps(x)
    >>> pickle.loads(s) # this is a call but it is hidden somewhere else
    somebody called me?
    
  15. Using serialization

    >>> import copy_reg
    >>> copy_reg.pickle(X, func)
    >>> pickle.dumps(x) # again a hidden call
    somebody called me?
    

More Python answers:

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Nice collection, but you forgot about threads. ;) \$\endgroup\$
    – user344
    Commented Mar 5, 2014 at 15:07
  • \$\begingroup\$ This answer is absurd. +1 \$\endgroup\$
    – asteri
    Commented Apr 4, 2014 at 19:58
  • \$\begingroup\$ This is python 3 \$\endgroup\$ Commented Apr 14, 2014 at 17:51
  • 1
    \$\begingroup\$ Many of those examples also work with Python 3. The shown meta-class and exception-raising do not work in Python 3. \$\endgroup\$
    – User
    Commented Apr 14, 2014 at 18:26
23
\$\begingroup\$

Javascript

This one uses JSFuck to do the dirty work.

function x() { alert("Hello, you are inside the x function!"); }

// Warning: JSFuck Black magic follows.
// Please, don't even try to understand this shit.
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]
+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][
(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!
![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[
]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+
(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!!
[]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+
[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(!
[]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![
]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+
!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[
+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!
+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((+(+
!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]
]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+
[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[]
)[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+
[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[
])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[
+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[
]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!
+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+
([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])
[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[]
[[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[
!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]
])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+
!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[
+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+
[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+
[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[
!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!
+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[
]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]
]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]
]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[
]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]
+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+
[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]]+(![]+[][(![]+
[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[
])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[
+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[]
)[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[
+!+[]]])[!+[]+!+[]+[+[]]])()
\$\endgroup\$
3
  • 55
    \$\begingroup\$ I think this qualifies as an explicit function call. Just a very obfuscated one. \$\endgroup\$
    – primo
    Commented Mar 2, 2014 at 6:47
  • 3
    \$\begingroup\$ @primo, it will be constructing a string of javascript to execute, and acquiring the Function object to call it with. But to do that, it uses implicit conversions between types; e.g. "" is a string, and [] evaluates to 0, so ""[[]] is undefined, and ""[[]]+"" is "undefined". From there you can pull out individual letters: (""[[]]+"")[[]] is "u". So it's more like a hack to call exec with arbitrary code. I think that counts? \$\endgroup\$
    – Phil H
    Commented Mar 4, 2014 at 13:05
  • 1
    \$\begingroup\$ @PhilH I understand how it works. Remove the last two parentheses: function anonymous() { x() }. \$\endgroup\$
    – primo
    Commented Mar 4, 2014 at 14:30
22
\$\begingroup\$

Python

import sys

def the_function(*void):
    print 'Hi there!'

sys.setprofile(the_function)

This sets the_function as the profiling function, causing it to be executed on each function call and return.

>>> sys.setprofile(the_function)
Hi there!
>>> print 'Hello there!'
Hi there!
Hi there!
Hi there!
Hi there!
Hi there!
Hello there!
Hi there!
\$\endgroup\$
5
  • \$\begingroup\$ Is this Python? \$\endgroup\$
    – user10766
    Commented Mar 1, 2014 at 1:52
  • \$\begingroup\$ @user2509848 Yes, I forgot to mention that. \$\endgroup\$
    – grc
    Commented Mar 1, 2014 at 1:53
  • \$\begingroup\$ A non-C answer! I'd love to see more :D \$\endgroup\$
    – user12385
    Commented Mar 1, 2014 at 1:54
  • \$\begingroup\$ @Johnsyweb Please see meta.codegolf.stackexchange.com/q/1109/9498 . There is no need to edit every single post to include syntax highlighting, especially if it barely affects the look of the code (e.g. short code). \$\endgroup\$
    – Justin
    Commented Mar 1, 2014 at 5:04
  • \$\begingroup\$ @Quincunx: Acknowledged ☻ \$\endgroup\$
    – johnsyweb
    Commented Mar 1, 2014 at 5:49
18
\$\begingroup\$

C#

We can abuse the DLR to always execute some code whenever you try to call any method on a class. This is slightly less cheap/obvious than solutions like delegates, reflections, static constructors, etc., because the method being executed is not only never invoked but never even referenced, not even by its name.

void Main()
{
    dynamic a = new A();
    a.What();
}

class A : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, Object[] args,
        out Object result)
    {
        Console.WriteLine("Ha! Tricked you!");
        result = null;
        return true;
    }
}

This always prints "Ha! Tricked you!" no matter what you try to invoke on a. So I could just as easily write a.SuperCaliFragilisticExpiAlidocious() and it would do the same thing.

\$\endgroup\$
17
\$\begingroup\$

GNU C

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

void hello_world() {
  puts(__func__);
  exit(0);
}

int main() {
  goto *&hello_world;
}

This is very direct, but is certainly not a call to hello_world, even though the function does execute.

\$\endgroup\$
16
\$\begingroup\$

Ruby

Inspired by wat.

require 'net/http'

def method_missing(*args) 
    # some odd code        
    http.request_post ("http://example.com/malicious_site.php", args.join " ")
    args.join " "
end

ruby has bare words
# => "ruby has bare words"
\$\endgroup\$
0
15
\$\begingroup\$

C

You can register a function to be called at the end of the program in C, if that fits your needs:

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

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

int main()
{
    atexit(&the_function);
}
\$\endgroup\$
15
\$\begingroup\$

Java

Tried this with java:

import java.io.PrintStream;
import java.lang.reflect.Method;

public class CallWithoutCalling {
    public static class StrangeException extends RuntimeException {
        @Override
        public void printStackTrace(PrintStream s) {
            for (Method m : CallWithoutCalling.class.getMethods()) {
                if ("main".equals(m.getName())) continue;
                try {
                    m.invoke(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void secretMethodNotCalledInMain() {
        System.out.println("Congratulations, you won a million dollars!");
    }

    public static void main(String[] args) {
        throw new StrangeException();
    }
}

The method secretMethodNotCalledInMain is called only by reflection, and I am not searching for anything called secretMethodNotCalledInMain (instead I am searching for anything not called main). Further, the reflective part of code is called outside the main method when the JDK's uncaught exception handler kicks in.

Here is my JVM info:

C:\>java -version
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b109)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b51, mixed mode)

Here is the output of my program:

Congratulations, you won a million dollars!
Exception in thread "main" java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
java.lang.NullPointerException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:491)
    at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061)
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052)
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1931)
Java Result: 1

I was not expecting those NullPointerExceptions being thrown from the native code to handle reflection. But, as mentioned by @johnchen902 that is because it inherits some methods from java.lang.Object and I ended up calling them on nulls.

\$\endgroup\$
2
  • \$\begingroup\$ Those NPEs are not JDK bug. They're thrown because you tried to invoke instance methods declared in java.lang.Object such as toString() with null. \$\endgroup\$ Commented Mar 2, 2014 at 6:41
  • \$\begingroup\$ @johnchen902 Oh, of course. Thank you. I edited it. \$\endgroup\$ Commented Mar 2, 2014 at 7:08
14
\$\begingroup\$

C++

One way in C++ is in the constructor and/or destructor of a static object:

struct foo { 
    foo() { printf("function called"); }
    ~foo() { printf("Another call"); }
}f;

int main() { }
\$\endgroup\$
5
  • 1
    \$\begingroup\$ I also thought of overloading new and delete, but I think three answers are enough :) \$\endgroup\$ Commented Mar 1, 2014 at 1:44
  • \$\begingroup\$ Are constructors/destructors considered "methods" in C++? In .NET and Java they're actually a different member type. You can't directly call a static ctor, even if you want to... \$\endgroup\$
    – Aaronaught
    Commented Mar 2, 2014 at 1:42
  • \$\begingroup\$ @Aaronaught: Nothing is considered a "method" in C++ (at least by anybody who knows what they're talking about). Constructors and destructors are member functions. They are "special" member functions though (e.g., constructors don't have names, so you can't invoke them directly). \$\endgroup\$ Commented Mar 2, 2014 at 1:44
  • \$\begingroup\$ Well, I only used that term because the OP did. I know that C/C++ and almost every other non-Java/.NET language have functions, not methods. But the salient point is that they can't be directly invoked. You could argue that an instance constructor is technically being directly invoked with new, and so it would be an interesting answer to have a way to invoke one without new. But I don't know, static constructors feels like a bit of a cheat. \$\endgroup\$
    – Aaronaught
    Commented Mar 2, 2014 at 2:02
  • \$\begingroup\$ @Aaronaught If you want to call a constructor on a piece of memory that's already allocated, you can write new (p) foo(). And you can destruct an object without releasing the memory via p->~foo(). \$\endgroup\$ Commented Mar 2, 2014 at 6:54
12
\$\begingroup\$

C: Hello World

#include <stdio.h>
void donotuse(){
   printf("How to use printf without actually calling it?\n");
}
int main(){
    (*main-276)("Hello World\n");
}

Output:

Hello World!

In order to link the method, we need printf() to be compiled somewhere in the program, but it does not have to actually be called. The printf() and main() functions are located 276 bytes apart from each other in the code segment. This value will change based on OS and compiler. You can find the actual addresses on your system with this code and then just subtract them:

printf("%d %d\n", &printf, &main);
\$\endgroup\$
4
  • 4
    \$\begingroup\$ The * before main is really confusing and unnecessary. main is a function which you cannot dereference, so it implicitly decays to a function pointer which is then dereferenced to yield a function again. You can't subtract an int from a function, so it decays to a function pointer again. You might as well write (*****main-276) ;) You probably meant to write (&main-276) or (*(main-276)) instead. \$\endgroup\$ Commented Mar 2, 2014 at 6:59
  • 6
    \$\begingroup\$ The * before main is really confusing and unnecessary. - Isn't that generally a good thing on this site? \$\endgroup\$ Commented Mar 3, 2014 at 17:35
  • \$\begingroup\$ I was under ther impression the standard said that a well-formed programm shall not use main, but can't find it now... \$\endgroup\$
    – Damon
    Commented Mar 3, 2014 at 17:37
  • 3
    \$\begingroup\$ you explicitly call it by obfuscated reference \$\endgroup\$
    – Nowayz
    Commented Mar 4, 2014 at 13:47
9
\$\begingroup\$

C (with GCC inline asm)

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

/* prevent GCC optimising it away */
void the_function(void) __attribute__((__noreturn__, __used__));

int
main(void)
{
    asm volatile (".section fnord");
    return (1);
}

void
the_function(void)
{
    asm volatile (".text");
    printf("Hi there!\n");
    exit(0);
}

This will cause some GCC-emitted code to end up in a different segment of the object file, effectively making control flow “fall through” the_function. Note that this does not work if GCC decides to reorder the functions, obviously. Tested with GCC 3.4.6 on MirBSD-current/i386, using -O2. (Also, it breaks debugging, compiling with -g errors out ☺)

\$\endgroup\$
8
\$\begingroup\$

PHP ≥5.4.0

This solution is admittedly a horrid mess, but it performs the task given to it (there was no stipulation how well it has to perform).

The function to call without calling:

function getRandomString( $len = 5 )
{
    $chars = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
    $string = "";

    for( $i = 0; $i < $len; ++$i )
    {
        $idx = mt_rand( 0, strlen( $chars ) - 1 );
        $string .= $chars[$idx];
    }

    return $string;
}

The solution:

function executeFunction( $name, $args = [ ] )
{
    global $argv;

    $code = file_get_contents( $argv[0] );
    $matches = [];
    $funcArgs = "";
    $funcBody = "";

    if( preg_match( "~function(?:.*?){$name}(?:.*?)\(~i", $code, $matches ) )
    {
        $idx = strpos( $code, $matches[0] ) + strlen( substr( $matches[0], 0 ) );

        $parenNestLevel = 1;
        $len = strlen( $code );

        while( $idx < $len and $parenNestLevel > 0 )
        {
            $char = $code[$idx];

            if( $char == "(" )
                ++$parenNestLevel;
            elseif( $char == ")" )
            {
                if( $parenNestLevel == 1 )
                    break;
                else
                    --$parenNestLevel;
            }

            ++$idx;
            $funcArgs .= $char;
        }

        $idx = strpos( $code, "{", $idx ) + 1;
        $curlyNestLevel = 1;

        while( $idx < $len and $curlyNestLevel > 0 )
        {
            $char = $code[$idx];

            if( $char == "{" )
                ++$curlyNestLevel;
            elseif( $char == "}" )
            {
                if( $curlyNestLevel == 1 )
                    break;
                else
                    --$curlyNestLevel;
            }

            ++$idx;
            $funcBody .= $char;
        }
    } else return;

    while( preg_match( "@(?:(\\$[A-Z_][A-Z0-9_]*)[\r\n\s\t\v]*,)@i", $funcArgs, $matches ) )
    {
        var_dump( $matches );
        $funcArgs = str_replace( $matches[0], "global " . $matches[1] . ";", $funcArgs );
    }

    $funcArgs .= ";";
    $code = $funcArgs;

    foreach( $args as $k => $v )
        $code .= sprintf( "\$%s = \"%s\";", $k, addslashes( $v ) );

    $code .= $funcBody;

    return eval( $code );
}

Example:

//Call getRandomString() with default arguments.
$str = executeFunction( "getRandomString" );
print( $str . PHP_EOL );

//You can also pass your own arguments in.
$args = [ "len" => 25 ]; //The array key must be the name of one of the arguments as it appears in the function declaration.
$str = executeFunction( "getRandomString", $args );
print( $str . PHP_EOL );

Possible outputs:

6Dz2r
X7J0p8KVeiaDzm8BInYqkeXB9

Explanation:

When called, executeFunction() will read the contents of the currently executing file (which means this is only meant to be run from CLI, as it uses $argv), parse out the arguments and body of the specified function, hack everything back together into a new chunk of code, eval() it all, and return the result. The result being that getRandomString() is never actually called, either directly or indirectly, but the code in the function body is still executed.

\$\endgroup\$
2
  • \$\begingroup\$ Well, does creating __construct() method counts in PHP since you never call the function directly, but use new Something() instead? \$\endgroup\$
    – dkasipovic
    Commented Mar 3, 2014 at 13:43
  • \$\begingroup\$ @D.Kasipovic Kind of, one could argue you're directly invoking it still, just in a different way. I chose my current approach because I like to think outside of the box. I could have just registered the function as a callback to register_tick_function(), register_shutdown_function(), or spl_autoload_register() similar to @grc's Python answer, but I feel like that's 'cheating' and taking the easy way out. \$\endgroup\$
    – Tony Ellis
    Commented Mar 3, 2014 at 15:34
8
\$\begingroup\$

Perl

sub INIT {
    print "Nothing to see here...\n";
}

Yes, that's all there is to it. Not all subroutines are created equal.

\$\endgroup\$
7
\$\begingroup\$

T-SQL

It's a built in feature. Triggers for the win!

If you really want to have fun with it, create a bunch of INSTEAD OF triggers on April Fool's Day.

CREATE TABLE hw(
  Greeting VARCHAR(MAX)
  );

CREATE TRIGGER TR_I_hw
ON hw
INSTEAD OF INSERT
AS
BEGIN
  INSERT hw
  VALUES ('Hello, Code Golf!')
END;

INSERT hw
VALUES ('Hello, World!');

SELECT * FROM hw

Results:

|          GREETING |
|-------------------|
| Hello, Code Golf! |

Very prank. Such lulz. Wow.

Tinker wid it on SQLFiddle.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Triggers always get me, as an application developer, I never expect them. \$\endgroup\$
    – Matthew
    Commented Mar 1, 2014 at 16:26
7
\$\begingroup\$

JavaScript

In Firefox console:

    this.toString = function(){alert('Wow')};

Then just start typing anything in console - Firefox calls .toString() multiple times when you're typing in console.

Similar approach is:

    window.toString = function(){alert('Wow');
            return 'xyz';
    };
    "" + window;
\$\endgroup\$
6
\$\begingroup\$

C

Platform of choice is Linux. We can't call our function, so we'll have our linker do it instead:

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

#define ADDRESS 0x00000000600720 // ¡magic!

void hello()
{
        printf("hello world\n");
}

int main(int argc, char *argv[])
{
        *((unsigned long *) ADDRESS) = (unsigned long) hello;
}

How to obtain the magic address?

We're relying on the Linux Standard Base Core Specification, which says:

.fini_array

This section holds an array of function pointers that contributes to a single termination array for the executable or shared object containing the section.

  1. Compile the code:

    gcc but_for_what_reason_exactly.c -o but_for_what_reason_exactly

  2. Examine the address of .fini_array:

    objdump -h -j .fini_array but_for_what_reason_exactly

  3. Find the VMA of it:

 but_for_what_reason_exactly:     file format elf64-x86-64
 Sections:
 Idx Name          Size      VMA               LMA               File off  Algn
  18 .fini_array   00000008  0000000000600720  0000000000600720  00000720  2**3
                   CONTENTS, ALLOC, LOAD, DATA

and replace that value for ADDRESS.

\$\endgroup\$
5
\$\begingroup\$

VB6 and VBA

Not sure if this qualifies or not, because it is calling a method of a class:

This goes in a class module:

Public Sub TheFunction()

    MsgBox ("WTF?")

End Sub

Public Sub SomeOtherFunction()

    MsgBox ("Expecting this.")

End Sub

And this is the "calling" code:

Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long)

Sub Demo()

    Dim a As Long, b as Long
    Dim example As New Class1

    CopyMemory a, ByVal ObjPtr(example), 4
    CopyMemory b, ByVal a + &H1C, 4
    CopyMemory ByVal a + &H1C, ByVal a + &H1C + 4, 4
    CopyMemory ByVal a + &H1C + 4, b, 4

    Call example.SomeOtherFunction

End Sub

This works by swapping the function vptr's for the two Subs in the vtable for the class.

\$\endgroup\$
2
  • \$\begingroup\$ Dude, you're dangerous! Nice one! \$\endgroup\$ Commented Nov 2, 2014 at 21:31
  • \$\begingroup\$ I'd say it does qualify, because in VB6/VBA a method is a member of a class - otherwise it's a procedure ;) \$\endgroup\$ Commented Nov 2, 2014 at 21:43
5
\$\begingroup\$

Haskell

In haskell if you do:

main=putStrLn "This is the main action."

It will get executed immediately without calling its name when you run it. Magic!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Haskell doesn't count. You can't call an IO action, only chain more IO actions to it or assign it somewhere. \$\endgroup\$ Commented Apr 14, 2014 at 6:37
  • \$\begingroup\$ It is the equivalent concept for IO actions. \$\endgroup\$ Commented Apr 14, 2014 at 19:59
5
\$\begingroup\$

Javascript

Easy, just use on___ events in JS. For example:

var img = document.createElement('img')
img.onload = func
img.src = 'http://placehold.it/100'
\$\endgroup\$
4
\$\begingroup\$

Java

Other java answer from me. As you see in the code, it directly calls theCalledMethod, but the method notCalledMethod is executed instead.

So, in the end I am doing 2 things:

  • Calling a method without calling it.
  • Not calling a method by calling it.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ClassRewriting {
    public static void main(String[] args) throws IOException {
        patchClass();
        OtherClass.theCalledMethod();
    }

    private static void patchClass() throws IOException {
        File f = new File("OtherClass.class");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (InputStream is = new BufferedInputStream(new FileInputStream(f))) {
            int c;
            while ((c = is.read()) != -1) baos.write(c);
        }
        String s = baos.toString()
                .replace("theCalledMethod", "myUselessMethod")
                .replace("notCalledMethod", "theCalledMethod");
        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(f))) {
            for (byte b : s.getBytes()) os.write(b);
        }
    }
}

class OtherClass {
    public static void theCalledMethod() {
        System.out.println("Hi, this is the called method.");
    }

    public static void notCalledMethod() {
        System.out.println("This method is not called anywhere, you should never see this.");
    }
}

Running it:

> javac ClassRewriting.java

> java ClassRewriting
This method is not called anywhere, you should never see this.

>
\$\endgroup\$
4
  • \$\begingroup\$ This is platform dependent. In particular, it will likely fail on OS X where the platform default character encoding is UTF-8. \$\endgroup\$
    – ntoskrnl
    Commented Mar 2, 2014 at 15:23
  • \$\begingroup\$ @ntoskrnl This should be easy to fix if you pass the encoding name as a parameter to the getBytes() method, turning it on getBytes("UTF-8"). Since I do not have an OS X, could you test if this works? \$\endgroup\$ Commented Mar 3, 2014 at 4:55
  • \$\begingroup\$ UTF-8 doesn't work for binary data. A single-byte encoding like ISO-8859-1 should work, but treating binary data as a string is still wrong. \$\endgroup\$
    – ntoskrnl
    Commented Mar 3, 2014 at 11:50
  • 3
    \$\begingroup\$ @ntoskrnl In fact, raping classfiles for doing the thing I am doing here is wrong, the encoding is the smallest of the problems. :) \$\endgroup\$ Commented Mar 3, 2014 at 15:22
4
\$\begingroup\$

Python

class Snake:

    @property
    def sneak(self):
        print("Hey, what's this box doing here!")
        return True

solid = Snake()

if hasattr(solid, 'sneak'):
    print('Solid Snake can sneak')
\$\endgroup\$
4
\$\begingroup\$

Java

Yay, garbage collection!

public class CrazyDriver {
    
    private static class CrazyObject {
        public CrazyObject() {
            System.out.println("Woo!  Constructor!");
        }

        private void indirectMethod() {
            System.out.println("I win!");
        }
        
        @Override
        public void finalize() {
            indirectMethod();
        }
    }
    
    public static void main(String[] args) {
        randomMethod();
        System.gc();
    }

    private static void randomMethod() {
        CrazyObject wut = new CrazyObject();
    }
}

A version for those who will inevitably say that System.gc() is unreliable:

public class UselessDriver {
    
    private static class UselessObject {
        
        public UselessObject() {
            System.out.println("Woo!  Constructor!");
        }
        
        public void theWinningMethod() {
            System.out.println("I win!");
        }
        
        @Override
        public void finalize() {
            theWinningMethod();
        }
    }
    
    public static void main(String[] args) {
        randomMethod();
        System.gc();
        fillTheJVM();
    }
    
    
    private static void randomMethod() {
        UselessObject wut = new UselessObject();
    }
    
    private static void fillTheJVM() {
        try {
            List<Object> jvmFiller = new ArrayList<Object>();
            while(true) {
                jvmFiller.add(new Object());
            }
        }
        catch(OutOfMemoryError oome) {
            System.gc();
        }
    }
}
\$\endgroup\$
4
\$\begingroup\$

Objective-C

(Probably only if compiled with clang on Mac OS X)

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

void unusedFunction(void) {
    printf("huh?\n");
    exit(0);
}

int main() {

    NSString *string;
    string = (__bridge id)(void*)0x2A27; // Is this really valid?

    NSLog(@"%@", [string stringByAppendingString:@"foo"]);

    return 0;
}

@interface MyClass : NSObject
@end
@implementation MyClass

+ (void)load {
    Class newClass = objc_allocateClassPair([NSValue class], "MyClass2", 0);
    IMP imp = class_getMethodImplementation(self, @selector(unusedMethod));
    class_addMethod(object_getClass(newClass), _cmd, imp, "");
    objc_registerClassPair(newClass);
    [newClass load];
}

- (void)unusedMethod {
    Class class = [self superclass];
    IMP imp = (IMP)unusedFunction;
    class_addMethod(class, @selector(doesNotRecognizeSelector:), imp, "");
}

@end

This code uses several tricks to get to the unused function. First is the value 0x2A27. This is a tagged pointer for the integer 42, which encodes the value in the pointer to avoid allocating an object.

Next is MyClass. It is never used, but the runtime calls the +load method when it is loaded, before main. This dynamically creates and registers a new class, using NSValue as its superclass. It also adds a +load method for that class, using MyClass's -unusedMethod as the implementation. After registration, it calls the load method on the new class (for some reason it isn't called automatically).

Since the new class's load method uses the same implementation as unusedMethod, that is effectively called. It takes the superclass of itself, and adds unusedFunction as an implementation for that class's doesNotRecognizeSelector: method. This method was originally an instance method on MyClass, but is being called as a class method on the new class, so self is the new class object. Therefore, the superclass is NSValue, which is also the superclass for NSNumber.

Finally, main runs. It takes the pointer value and sticks it in a NSString * variable (the __bridge and first cast to void * allow this to be used with or without ARC). Then, it tries to call stringByAppendingString: on that variable. Since it is actually a number, which does not implement that method, the doesNotRecognizeSelector: method is called instead, which travels up through the class hierarchy to NSValue where it is implemented using unusedFunction.


Note: the incompatibility with other systems is due to the tagged pointer usage, which I do not believe has been implemented by other implementations. If this were replaced with a normally created number the rest of the code should work fine.

\$\endgroup\$
5
  • \$\begingroup\$ Hm, try with ciruZ' ObjFW, it's a pretty decent Objective-C runtime and framework, maybe this, or something close, will work with it too ;-) \$\endgroup\$
    – mirabilos
    Commented Mar 3, 2014 at 20:22
  • \$\begingroup\$ @mirabilos The only incompatibility in it is the 0x2A27 value, so I just don't know if that is implemented anywhere else. ObjFW definitely is interesting though. \$\endgroup\$
    – ughoavgfhw
    Commented Mar 3, 2014 at 22:29
  • \$\begingroup\$ 0x2A27 is tagged pointer \$\endgroup\$
    – Bryan Chen
    Commented Mar 4, 2014 at 0:10
  • \$\begingroup\$ @Bryan Thanks! I was looking for that exact article and couldn't remember the proper name. \$\endgroup\$
    – ughoavgfhw
    Commented Mar 4, 2014 at 2:11
  • \$\begingroup\$ @BryanChen ah okay. ughoavgfhw: Sure, just wanted to point out the alternative runtime in case you wanted to play with it. \$\endgroup\$
    – mirabilos
    Commented Mar 4, 2014 at 20:44
3
\$\begingroup\$

Javascript

I feel like this doesn't explicitly look like it is calling the function

window["false"] =  function() { alert("Hello world"); }
window[![]]();
\$\endgroup\$
2
  • 5
    \$\begingroup\$ Pretty borderline if you ask me. \$\endgroup\$
    – Cole Tobin
    Commented Mar 1, 2014 at 23:10
  • \$\begingroup\$ @ColeJohnson I think he already crossed it... \$\endgroup\$
    – Tomas
    Commented Mar 4, 2014 at 22:46
3
\$\begingroup\$

C# (via using)

using System;

namespace P
{
    class Program : IDisposable
    {
        static void Main(string[] args)
        {
            using (new Program()) ;
        }

        public void Dispose()
        {
            Console.Write("I was called without calling me!");
        }
    }
}
\$\endgroup\$
3
\$\begingroup\$

Java

package stuff;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class SerialCall {
    static class Obj implements Serializable {
        private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
            System.out.println("Magic!");
        }
    }

    private static final byte[] data = { -84, -19, 0, 5, 115, 114, 0, 20, 115,
            116, 117, 102, 102, 46, 83, 101, 114, 105, 97, 108, 67, 97, 108,
            108, 36, 79, 98, 106, 126, -35, -23, -68, 115, -91, -19, -120, 2,
            0, 0, 120, 112 };

    public static void main(String[] args) throws Exception {
//      ByteArrayOutputStream baos = new ByteArrayOutputStream();
//      ObjectOutputStream out = new ObjectOutputStream(baos);
//      out.writeObject(new Obj());
//      System.out.println(Arrays.toString(baos.toByteArray()));

        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
        in.readObject();
    }
}

I'm taking advantage of a special feature of Java serialization. The readObject method is invoked when an object is deserialized, but it's not directly called - not by my code, nor by the deserialization library. If you dig deep into the source, you'll see that at a low level the method is internally called via reflection.

\$\endgroup\$
1
  • \$\begingroup\$ yeah; serialisation allows pretty funny jokes :); btw theres are similar ways in other serialisation lobs for java \$\endgroup\$
    – masterX244
    Commented Mar 4, 2014 at 14:49
3
\$\begingroup\$

Perl

This is so easy. The code below automatically runs code in subroutine, even without explicit call.

sub call_me_plz {
    BEGIN {
        print "Hello, world!\n";
    }
}
# call_me_plz(); # don't call the method

Even if you uncomment the call, it will still be called just once.

\$\endgroup\$
1
  • \$\begingroup\$ how? cant get behind the magic+ \$\endgroup\$
    – masterX244
    Commented Mar 4, 2014 at 14:46