Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With MACH-O is there a way to register a function that will run before main?

Tags:

c

macos

mach-o

Under Linux, I can register a routine that will run before main. For example:

#include <stdio.h>

void myinit(int argc, char **argv, char **envp) {
  printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof(myinit) *__init = myinit;

By compiling this with GCC and linking it in, the function myinit will be run before main.

Is there way to do this under Mac OSX and MACH-O?

Thanks.

like image 293
user2410881 Avatar asked Jun 08 '15 02:06

user2410881


2 Answers

You could place the function in __mod_init_func data section of Mach-O binary.

From Mach-O format reference:

__DATA,__mod_init_func

Module initialization functions. The C++ compiler places static constructors here.

example.c

#include <stdio.h>

void myinit(int argc, char **argv, char **envp) {
  printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section("__DATA,__mod_init_func"))) typeof(myinit) *__init = myinit;

int main() {
  printf("%s: %s\n", __FILE__, __FUNCTION__);
  return 0;
}

I build your example with clang on OS X platform:

$ clang -Wall example.c
$ ./a.out
example.c: myinit
example.c: main
like image 145
baf Avatar answered Nov 10 '22 09:11

baf


Easiest way is to specify the function to be constructor using constructor attribute. The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. You can also specify optional priority if you have several functions

e.g. __attribute__((constructor(100)))

#include <stdio.h>

__attribute__((constructor)) void myinit() {
    printf("my init\n");
}

int main() {
    printf("my main\n");
    return 0;
}

__attribute__((destructor)) void mydeinit() {
    printf("my deinit\n");
}


$ clang -Wall example.c
$ ./a.out
my init
my main
my deinit
like image 3
Mindaugas Avatar answered Nov 10 '22 09:11

Mindaugas