Okay, let's break down this fascinating IOCCC (International Obfuscated C Code Contest) entry. These entries are famous for being cryptic, clever, and often surprising.
This specific entry is Yang's 2004 winner. Its primary function is to display Conway's Game of Life in the terminal.
Here's a breakdown of how it achieves this through obfuscation:
Headers: Includes many headers, hinting at various capabilities: dynamic linking (dlfcn.h), file I/O (stdio.h, fcntl.h), possibly threading (pthread.h), error handling (err.h, errno.h), etc. Not all included headers are necessarily used meaningfully.
Global Variables:
f, e: Integers, seemingly used as state variables or counters in the main loop.
l[1<<22], V[1<<22]: Large arrays. V stores pointers (likely to strings), and l stores integers (likely hashes). 2
22
is over 4 million elements.
a = "%[^a-z]%m[a-z]\0r": A format string for fscanf. It's designed to:
%[^a-z]: Skip any characters that are not lowercase letters.
%m[a-z]: Read and dynamically allocate memory (%m) for a sequence of lowercase letters ([a-z]).
The \0r part isn't used by fscanf but the address a+16 points to the 'r', which is used later in popen.
W = "cpp " FILE: A string containing the command to run the C preprocessor (cpp) on the source file itself (FILE).
Function A(char s) - The Hash Function:
This function implements the FNV-1a hash algorithm (32-bit version).
It takes a string s and calculates a hash value based on its contents. The constants (0x811C9DC5) and (0x01000193) are characteristic of FNV-1a.
Function X(unsigned Y) - Dynamic Function Lookup:
This is the core of the dynamic behaviour. It's designed to return a pointer to a function based on its hash Y.
Self-Preprocessing (First Call Only):
if (!V): This check ensures the following block runs only once (when V[0] is still NULL).
W=popen(W, a+16): Executes the command stored in (initially "cpp your_source_file.c") in read mode ("r" comes from a+16). It runs the C preprocessor on the program's own source code and opens a pipe to read the output.
while(fscanf(W, a, V+e) > 0; e++): Reads the preprocessed source code using the format string a. This extracts all sequences of only lowercase letters (potential identifiers/function names). The extracted strings are allocated memory, and their pointers are stored sequentially in the V array.
l[e]=A(V[e]): Calculates the FNV-1a hash of each extracted identifier string and stores it in the corresponding index in the l array.
In essence: The first time X is called, it preprocesses its own source code, finds all lowercase identifiers (like int, char, while, if, putc, getc, main, etc.), stores them in V, and stores their hashes in l.
Symbol Searching:
for (W=V; l[W-(void)V]!=Y; W++);: This loop intends to find the index idx in the l array where the hash l[idx] matches the input hash Y.
Obfuscation/Weirdness: The indexing W-(void)V is highly suspect. It calculates the byte offset of the pointer W from the start of V. Using a byte offset to index the integer array l relies on non-standard, potentially undefined behaviour, or exploits a specific relationship between pointer size and integer size on the target architecture. It somehow works on the intended platform to find the correct index corresponding to the hash Y. Let's assume idx is the index it finds.
Dynamic Linking:
return dlsym(0, V[W-(void*)V]);: Once the loop finds the matching hash (and presumably the correct index idx), this retrieves the corresponding string (the identifier/function name) from V[idx].
dlsym(0, name) (or , name)) searches the global symbol table (including the program itself and loaded libraries like libc) for a symbol with the given name.
It returns a pointer to the found function.
Function main() - The Game Loop:
while(1): An infinite loop.
Inside the loop, four if statements control the program flow based on the state variables e and f and the constants 0x100 (256) and 0x101 (257).
Each if block calls a function obtained dynamically using X with a specific hash value. Let's find the functions for those hashes:
A("putc") = 0xae94bd2f
A("puts") = 0xcded1a85
A("getc") = 0xdc0f32d8
A("exit") = 0x15026602
So the loop effectively translates to:
C
// Pre-calculated function pointers
int (my_putc)(int, FILE) = ); // dlsym lookup for "putc"
int (my_puts)(const char) = X(0xcded1a85); // dlsym lookup for "puts"
int (my_getc)(FILE) = X(0xdc0f32d8); // dlsym lookup for "getc"
void (*my_exit)(int) = X(0x15026602); // dlsym lookup for "exit"
while (1) {
// Note: arguments passed don't match standard signatures!
if (f ^ 0x100) e = my_putc(e, ++f); // Call putc with (e, f+1)
if (e & 0x100) f = my_puts(e, ++f); // Call puts with (e, f+1) -> uses comma operator, passes f+1 as char*
if (f & 0x101) e = my_getc(e, ++f); // Call getc with (e, f+1) -> uses comma operator, passes f+1 as FILE*
if (e ^ 0x101) f = my_exit(e, ++f); // Call exit with (e, f+1) -> uses comma operator, passes e as status
}
The Core Obfuscation - Abusing Function Calls:
The program calls standard C library functions (putc, puts, getc, exit) with incorrect arguments and types. For example, putc expects (int c, FILE *stream), but it's called with (e, ++f), where f is an int. puts expects (const char s) but is called effectively with an integer ++f cast to char.
This code does not rely on the standard behavior of these functions for I/O in the way you'd normally expect.
Instead, it relies on the side effects of making these invalid calls on the specific compiler and C library it was developed for. The way arguments are passed (e.g., via registers), how return values are generated (even for failed calls), and how invalid pointers/file descriptors are handled likely influences the values of e and f (or other machine state) in a way that simulates the rules of Conway's Game of Life.
The if conditions (f ^ 0x100, e & 0x100, etc.) select which function's side effects are used to advance the game state (e, f) in each iteration, eventually using putc (perhaps when arguments accidentally align correctly or cause specific character output side effects) to print the game board to the console. might be used for pausing, and exit for termination (though the condition e ^ 0x101 might control when it's actually called).
In Summary:
This IOCCC entry is a highly obfuscated implementation of 's Game of Life that works by:
Self-inspection: Preprocessing its own source code to find potential function names.
Hashing: Using FNV-1a to hash these names.
Dynamic Loading: Using dlsym to get pointers to standard C library functions (putc, puts, getc, exit) based on their hashes.
State Machine: Using a while loop and state variables e, f.
Exploiting Undefined Behavior: Calling the standard functions with incorrect arguments and relying on the resulting side effects (rather than their intended I/O behavior) on a specific platform to simulate the Game of Life logic and produce output.
It's a prime example of obfuscation through clever tricks (self-preprocessing, dynamic lookup) and reliance on non-portable, implementation-defined behavior. It likely won't compile or run correctly on many modern systems without modification or a specific compatible environment.