1 //===-- Implementation of crt for x86_64 ----------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "config/linux/syscall.h" 10 #include "include/sys/syscall.h" 11 12 #include <linux/auxvec.h> 13 #include <stdint.h> 14 15 extern "C" int main(int, char **, char **); 16 17 struct Args { 18 // At the language level, argc is an int. But we use uint64_t as the x86_64 19 // ABI specifies it as an 8 byte value. 20 uint64_t argc; 21 22 // At the language level, argv is a char** value. However, we use uint64_t as 23 // the x86_64 ABI specifies the argv vector be an |argc| long array of 8-byte 24 // values. Even though a flexible length array would be more suitable here, we 25 // set the array length to 1 to avoid a compiler warning about it being a C99 26 // extension. Length of 1 is not really wrong as |argc| is guaranteed to be 27 // atleast 1, and there is an 8-byte null entry at the end of the argv array. 28 uint64_t argv[1]; 29 }; 30 31 // TODO: Would be nice to use the aux entry structure from elf.h when available. 32 struct AuxEntry { 33 uint64_t type; 34 uint64_t value; 35 }; 36 37 extern "C" void _start() { 38 uintptr_t *frame_ptr = 39 reinterpret_cast<uintptr_t *>(__builtin_frame_address(0)); 40 41 // This TU is compiled with -fno-omit-frame-pointer. Hence, the previous value 42 // of the base pointer is pushed on to the stack. So, we step over it (the 43 // "+ 1" below) to get to the args. 44 Args *args = reinterpret_cast<Args *>(frame_ptr + 1); 45 46 // After the argv array, is a 8-byte long NULL value before the array of env 47 // values. The end of the env values is marked by another 8-byte long NULL 48 // value. We step over it (the "+ 1" below) to get to the env values. 49 uint64_t *env_ptr = args->argv + args->argc + 1; 50 uint64_t *env_end_marker = env_ptr; 51 while (*env_end_marker) 52 ++env_end_marker; 53 54 // After the env array, is the aux-vector. The end of the aux-vector is 55 // denoted by an AT_NULL entry. 56 for (AuxEntry *aux_entry = reinterpret_cast<AuxEntry *>(env_end_marker + 1); 57 aux_entry->type != AT_NULL; ++aux_entry) { 58 // TODO: Read the aux vector and store necessary information in a libc wide 59 // data structure. 60 } 61 62 __llvm_libc::syscall(SYS_exit, 63 main(args->argc, reinterpret_cast<char **>(args->argv), 64 reinterpret_cast<char **>(env_ptr))); 65 } 66