I have seen questions similar to this one on here before but I was unable to solve my problem from the answers to those.
I have a file libfoo.c from which I'm creating a shared object. Using gcc's __attribute__((constructor)), I'd like to print a message to a file when this shared object is loaded:
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static char *term = NULL;
static void init (void) __attribute__((constructor));
static void
init (void)
{
FILE *f = fopen ("lib.log", "w");
if (f)
{
if (isatty (STDOUT_FILENO))
{
char *tmp = ttyname (STDERR_FILENO);
if (tmp && *tmp)
{
term = strdup (tmp); // nevermind the memory leak
fprintf (f, "Found terminal %s\n", term);
}
}
else
fprintf (f, "Failed to find terminal\n");
fclose(f);
}
}
void *
malloc (size_t size)
{
return NULL;
}
The dummy malloc implementation (to be extended later) should replace stdlib.h's malloc in another dummy program, whose source code resides in main.c:
#include <stdlib.h>
int main (void)
{
char *m = malloc(1024);
(void)m;
return 0;
}
I'm compling and linking both files as follows:
gcc -o main main.c
gcc -fpic -shared -o libfoo libfoo.c
And then when I execute the following no file is created and no output is logged:
LD_PRELOAD=$(readlink -f libfoo) ./main
What is going on here? As a sidenote: how could I try to debug a problem like this using ltrace? ltrace "LD_PRELOAD=... ./main" is not a valid command.
EDIT: What is going on here? It seems at least printf works inside the shared object, but only inside the setup function, if I call printf inside malloc the program segfaults. In trying to at least figure out what terminal stdout is connected to I did the following (inside the setup function):
// ...
char buf[100];
buf[readlink ("/proc/self/fd/1", buf, 100)] = '\0';
printf ("STDOUT (buf): %s\n", buf);
char *tmp = ttyname (1);
printf ("STDOUT (ttyname): %s, %s\n", tmp, strerror (errno));
// ...
This prints:
STDOUT (buf): /dev/pts/1
STDOUT (ttyname): (null), Success
According to the ttyname manpage, that second line of output should be impossible. Am I completely misunderstanding something here?
here is what I ran, created from your code, and it ran perfectly, generating a file:
lib.logThe contents of the file: lib.log
and now, the code I ran:
Of course, your posted code is missing a header file. Such a header file should be referenced/included by your
main.cfile and your libfoo.c file