crt0.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Types.h>
  7. #include <assert.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <sys/internals.h>
  11. #include <unistd.h>
  12. #ifndef _DYNAMIC_LOADER
  13. extern "C" {
  14. extern size_t __stack_chk_guard;
  15. int main(int, char**, char**);
  16. // Tell the compiler that this may be called from somewhere else.
  17. int _entry(int argc, char** argv, char** env) __attribute__((used));
  18. void _start(int, char**, char**) __attribute__((used));
  19. NAKED void _start(int, char**, char**)
  20. {
  21. asm(
  22. "push $0\n"
  23. "jmp _entry@plt\n");
  24. }
  25. int _entry(int argc, char** argv, char** env)
  26. {
  27. size_t original_stack_chk = __stack_chk_guard;
  28. arc4random_buf(&__stack_chk_guard, sizeof(__stack_chk_guard));
  29. if (__stack_chk_guard == 0)
  30. __stack_chk_guard = original_stack_chk;
  31. environ = env;
  32. __environ_is_malloced = false;
  33. __begin_atexit_locking();
  34. _init();
  35. int status = main(argc, argv, environ);
  36. exit(status);
  37. // We should never get here, but if we ever do, make sure to
  38. // restore the stack guard to the value we entered _start with.
  39. // Then we won't trigger the stack canary check on the way out.
  40. __stack_chk_guard = original_stack_chk;
  41. return 20150614;
  42. }
  43. }
  44. #endif