B”H
Just for some fun I tried to write a little shared library. The only
function of this would be to reverse text. I decided to just work with
printf, since well it is the most common and made my life quite
simple.
Well first i had to figure out how to write a function that behaved
like printf. We know that the definition of printf is int
printf( const char* fmt, ... ), and by reading the info file
for GNU libc (or your man file, or K&R) we find out that we need to
return the number of outputted characters, no biggie.
Well then we have the issue of not knowing how many arguments we
get. But that is quite simple to fix. Since I several times before had
used va_list and the some parts of the va_ family, I used that (not
sure maybe there are other ones?).
So how would our function look?
int printf( const char* fmt, ... )
{
char* buff;
char temp;
int ret, x;
va_list ap;
va_start( ap, fmt );
ret = vasprintf( &buff, fmt, ap );
va_end( ap );
/* mirror string code goes here */
fprintf( stdout, buff );
free( buff );
return ret;
}
And well mirroring then? Not hard at all (if we as selected previously
writes an utterly stupid one).
for( x = 0; x < ret / 2; x++ )
{
temp = buff[(ret - x) -1];
buff[(ret - x) -1] = buff[x];
buff[x] = temp;
}
So now you know what the x and temp variables where for.
sadly this code isn’t that effective as I hoped and behaves rather
strange sometimes, not all printfs are mirrored etc, but as a simple
hack it works.
Example of the broken output:
8.0.0v tsobCopyright (C) 2006-2009 Patrik Lembke.
This is free software with ABSOLUTELY NO WARRANTY.
:mahkra
9.0.32.271 :0
So as a conclusion I have to say that it was a fun idea for showing
how dynamic libraries can do some quite interesting things to your
programs. A great example would be tsocks that makes non-SOCKS
aware programs use SOCKS a proxy by overloading certain network
related calls (in a much cleaner way then I did).
Here is the full source code and compile instructions:
ld_printf.c