crt0.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. extern bool s_global_initializers_ran;
  16. int main(int, char**, char**);
  17. // Tell the compiler that this may be called from somewhere else.
  18. int _entry(int argc, char** argv, char** env) __attribute__((used));
  19. void _start(int, char**, char**) __attribute__((used));
  20. NAKED void _start(int, char**, char**)
  21. {
  22. asm(
  23. "push $0\n"
  24. "jmp _entry@plt\n");
  25. }
  26. int _entry(int argc, char** argv, char** env)
  27. {
  28. size_t original_stack_chk = __stack_chk_guard;
  29. arc4random_buf(&__stack_chk_guard, sizeof(__stack_chk_guard));
  30. if (__stack_chk_guard == 0)
  31. __stack_chk_guard = original_stack_chk;
  32. environ = env;
  33. __environ_is_malloced = false;
  34. __begin_atexit_locking();
  35. s_global_initializers_ran = true;
  36. _init();
  37. int status = main(argc, argv, environ);
  38. exit(status);
  39. // We should never get here, but if we ever do, make sure to
  40. // restore the stack guard to the value we entered _start with.
  41. // Then we won't trigger the stack canary check on the way out.
  42. __stack_chk_guard = original_stack_chk;
  43. return 20150614;
  44. }
  45. }
  46. #endif