Pointers to Functions
The instructions of a program are stored in memory, just like the program's data. Pointers (unlike references in Java) don't know / care what type of data they point at - there is no reason you couldn't have pointers that mark sections in the code. In fact, C does just that. First look up the syntax for pointers to functions, then have a look at this code and see if you can work out what it does (many thanks to Dave for providing this wonderfully twisted example).
Now look up dlopen and dlsym and try writing programs that support plug-ins!
Malicious Coding Challenge
When marking the mock exam it occured to me that a sufficiently underhand programmer could cause havoc by submitting code that passed a preliminary inspection but then did something harmful. Althought there are a number of ways of achieving this, creating a very weird mytest.in file and attempting a buffer overrun attack would seem to be the easiest. Thus I propose a small challenge:
- Make minimal (and as innocuous as possible) changes to calc.c to make it run arbitrary code. This can be through buffer overrun or any other method of your choice (mytest.in is fair game - any content you want / need).
- The most nefarious solution come the end of term will win a pint (or equivalent non alcoholic / non beer beverage of the winner's choice)
(P.S. Have a look at last year's sillyness for a starter on buffer overrun attacks - or get Martin to explain the basics)
(P.P.S. Ofcourse, if you were doing this for real you couldn't be sure if we were going to run this on x86 or SPARC. A crate of beer / $BEVERAGE for anyone who's solution includes a shell code that works on both processors)
(P.P.P.S. Don't bother trying this for real, when we run code for marking it is heavily sandboxed, which will not only block but detect this kind of attack. The University takes this sort of thing very seriously and you would likely find yourself not only thrown out but probably talking to the Police as well. This is an exercise for academic interest ONLY.)