Skip to content

Instantly share code, notes, and snippets.

@singleghost2
Created November 21, 2023 03:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save singleghost2/de388b50ec4e2a358eee63ddee3cebd3 to your computer and use it in GitHub Desktop.
Save singleghost2/de388b50ec4e2a358eee63ddee3cebd3 to your computer and use it in GitHub Desktop.
Disable ASLR on macOS for dylib include those loaded with `dlopen`
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>
#include <string.h>
/* ASLR disabling magic constant from Apple LLDB source code
https://opensource.apple.com/source/lldb/lldb-76/tools/darwin-debug/darwin-debug.cpp
*/
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
int main(int argc, char *argv[]) {
pid_t pid;
int status;
// 要执行的程序路径
const char *binaryPath = "/path/to/program";
argv[0] = (char *)binaryPath;
// Prepare envs
char *envp[] = {
"DYLD_INSERT_LIBRARIES=/path/to/your_dlopened_dylib:/path/to/your_second_dlopened_dylib",
NULL
};
posix_spawnattr_t p_attr;
/* set magic constant to disable ASLR */
posix_spawnattr_init(&p_attr);
posix_spawnattr_setflags(&p_attr, _POSIX_SPAWN_DISABLE_ASLR);
status = posix_spawnp(&pid, argv[0], NULL, &p_attr, argv, envp);
if(status == 0) {
/* wait for end */
if (waitpid(pid, &status, WUNTRACED) != -1) {
/* normal case, just exit */
if (WIFEXITED(status)) {
/* return original exit code */
return WEXITSTATUS(status);
}
/* abnormal cases */
else if (WIFSIGNALED(status)) {
fprintf(stderr, "%s SIGNALED by signal %d\n", argv[0], WTERMSIG(status));
return -1;
}
else if (WIFSTOPPED(status)) {
fprintf(stderr, "%s STOPPED by signal %d\n", argv[0], WSTOPSIG(status));
return -1;
}
else {
fprintf(stderr, "%s waitpid unknown status %d\n", argv[0], status);
return -1;
}
}
else {
perror("waitpid");
return -1;
}
}
else {
fprintf(stderr, "posix_spawn: %s\n", strerror(status));
return -1;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment