From e2e7e8a563f67e1b912cc20357aefc0acb38582f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Kowalczyk?= Date: Mon, 7 Sep 2020 20:51:48 +0200 Subject: [PATCH] Reformat repository to our C formatting rules (final iteration) --- .clang-format | 6 +- Documentation/devel/coding-style.rst | 18 +- .../include/arch/x86_64/shim_dl-machine.h | 6 +- .../shim/include/arch/x86_64/shim_tcb-arch.h | 36 +- .../include/arch/x86_64/shim_types-arch.h | 6 +- .../include/arch/x86_64/shim_ucontext-arch.h | 48 +- LibOS/shim/include/shim_checkpoint.h | 5 +- LibOS/shim/include/shim_context.h | 2 +- LibOS/shim/include/shim_defs.h | 22 +- LibOS/shim/include/shim_flags_conv.h | 2 +- LibOS/shim/include/shim_fs.h | 6 +- LibOS/shim/include/shim_handle.h | 13 +- LibOS/shim/include/shim_internal.h | 553 +++++++++--------- LibOS/shim/include/shim_ipc.h | 28 +- LibOS/shim/include/shim_signal.h | 168 +++--- LibOS/shim/include/shim_sysv.h | 7 +- LibOS/shim/include/shim_table.h | 11 +- LibOS/shim/include/shim_tcb.h | 19 +- LibOS/shim/include/shim_thread.h | 91 ++- LibOS/shim/include/shim_types.h | 330 ++++++----- LibOS/shim/include/shim_utils.h | 10 +- LibOS/shim/include/shim_vma.h | 3 +- LibOS/shim/src/bookkeep/shim_handle.c | 27 +- LibOS/shim/src/bookkeep/shim_signal.c | 309 +++++----- LibOS/shim/src/bookkeep/shim_thread.c | 228 ++++---- LibOS/shim/src/bookkeep/shim_vma.c | 187 +++--- LibOS/shim/src/elf/do-rel.h | 7 +- LibOS/shim/src/elf/shim_rtld.c | 29 +- LibOS/shim/src/fs/chroot/fs.c | 390 ++++++------ LibOS/shim/src/fs/dev/attestation.c | 79 ++- LibOS/shim/src/fs/dev/fs.c | 58 +- LibOS/shim/src/fs/dev/random.c | 10 +- LibOS/shim/src/fs/dev/std.c | 20 +- LibOS/shim/src/fs/eventfd/fs.c | 12 +- LibOS/shim/src/fs/pipe/fs.c | 18 +- LibOS/shim/src/fs/proc/fs.c | 33 +- LibOS/shim/src/fs/proc/info.c | 26 +- LibOS/shim/src/fs/proc/ipc-thread.c | 38 +- LibOS/shim/src/fs/proc/thread.c | 45 +- LibOS/shim/src/fs/shim_dcache.c | 18 +- LibOS/shim/src/fs/shim_fs.c | 32 +- LibOS/shim/src/fs/shim_fs_hash.c | 4 +- LibOS/shim/src/fs/shim_fs_pseudo.c | 6 +- LibOS/shim/src/fs/shim_namei.c | 119 ++-- LibOS/shim/src/fs/socket/fs.c | 7 +- LibOS/shim/src/fs/str/fs.c | 13 +- LibOS/shim/src/generated-offsets.c | 13 +- LibOS/shim/src/ipc/shim_ipc.c | 30 +- LibOS/shim/src/ipc/shim_ipc_child.c | 15 +- LibOS/shim/src/ipc/shim_ipc_helper.c | 63 +- LibOS/shim/src/ipc/shim_ipc_pid.c | 3 +- LibOS/shim/src/ipc/shim_ipc_ranges.c | 136 ++--- LibOS/shim/src/ipc/shim_ipc_sysv.c | 26 +- LibOS/shim/src/shim_async.c | 42 +- LibOS/shim/src/shim_checkpoint.c | 37 +- LibOS/shim/src/shim_context-x86_64.c | 4 +- LibOS/shim/src/shim_debug.c | 22 +- LibOS/shim/src/shim_init.c | 292 +++++---- LibOS/shim/src/shim_malloc.c | 16 +- LibOS/shim/src/shim_object.c | 9 +- LibOS/shim/src/shim_parser.c | 3 - LibOS/shim/src/shim_syscalls.c | 37 +- LibOS/shim/src/shim_table-x86_64.c | 4 +- LibOS/shim/src/sys/shim_access.c | 14 +- LibOS/shim/src/sys/shim_alarm.c | 19 +- LibOS/shim/src/sys/shim_brk.c | 19 +- LibOS/shim/src/sys/shim_clone.c | 79 ++- LibOS/shim/src/sys/shim_dup.c | 17 +- LibOS/shim/src/sys/shim_epoll.c | 56 +- LibOS/shim/src/sys/shim_eventfd.c | 14 +- LibOS/shim/src/sys/shim_exec.c | 17 +- LibOS/shim/src/sys/shim_exit.c | 18 +- LibOS/shim/src/sys/shim_fcntl.c | 17 +- LibOS/shim/src/sys/shim_fs.c | 20 +- LibOS/shim/src/sys/shim_futex.c | 37 +- LibOS/shim/src/sys/shim_getcwd.c | 17 +- LibOS/shim/src/sys/shim_getpid.c | 15 +- LibOS/shim/src/sys/shim_getrlimit.c | 11 +- LibOS/shim/src/sys/shim_ioctl.c | 2 +- LibOS/shim/src/sys/shim_mmap.c | 14 +- LibOS/shim/src/sys/shim_msgget.c | 28 +- LibOS/shim/src/sys/shim_open.c | 241 ++++---- LibOS/shim/src/sys/shim_pipe.c | 12 +- LibOS/shim/src/sys/shim_poll.c | 17 +- LibOS/shim/src/sys/shim_sched.c | 28 +- LibOS/shim/src/sys/shim_semget.c | 19 +- LibOS/shim/src/sys/shim_sigaction.c | 16 +- LibOS/shim/src/sys/shim_sleep.c | 16 +- LibOS/shim/src/sys/shim_socket.c | 72 +-- LibOS/shim/src/sys/shim_stat.c | 14 +- LibOS/shim/src/sys/shim_time.c | 13 +- LibOS/shim/src/sys/shim_uname.c | 13 +- LibOS/shim/src/sys/shim_wait.c | 15 +- LibOS/shim/src/sys/shim_wrappers.c | 15 +- LibOS/shim/src/syscallas-x86_64.S | 2 +- LibOS/shim/src/utils/md5.c | 4 +- LibOS/shim/src/utils/printf.c | 13 +- LibOS/shim/src/utils/strobjs.c | 4 +- LibOS/shim/test/benchmark/sig_latency.c | 3 +- LibOS/shim/test/fs/common.c | 2 +- LibOS/shim/test/fs/copy_mmap_seq.c | 3 +- LibOS/shim/test/fs/delete.c | 3 +- LibOS/shim/test/fs/open_flags.c | 12 +- LibOS/shim/test/fs/read_write.c | 3 +- LibOS/shim/test/fs/seek_tell.c | 4 +- LibOS/shim/test/fs/test_fs.py | 14 +- LibOS/shim/test/inline/fork.c | 3 +- LibOS/shim/test/inline/helloworld.c | 2 +- LibOS/shim/test/inline/vfork.c | 3 +- LibOS/shim/test/native/epoll_socket.c | 5 +- LibOS/shim/test/native/malloc.c | 2 +- LibOS/shim/test/native/pid_alloc.c | 4 +- LibOS/shim/test/native/pipe_latency.c | 2 +- .../shim/test/regression/abort_multithread.c | 2 +- LibOS/shim/test/regression/attestation.c | 6 +- LibOS/shim/test/regression/cpuid.c | 15 +- LibOS/shim/test/regression/eventfd.c | 9 +- LibOS/shim/test/regression/exec_same.c | 10 +- LibOS/shim/test/regression/file_size.c | 11 +- LibOS/shim/test/regression/futex_requeue.c | 24 +- LibOS/shim/test/regression/futex_timeout.c | 7 +- LibOS/shim/test/regression/futex_wake_op.c | 26 +- LibOS/shim/test/regression/mmap_file.c | 10 +- .../shim/test/regression/mprotect_file_fork.c | 2 +- LibOS/shim/test/regression/pipe_nonblocking.c | 1 - LibOS/shim/test/regression/pipe_ocloexec.c | 3 +- LibOS/shim/test/regression/poll_closed_fd.c | 4 +- LibOS/shim/test/regression/proc_common.c | 3 +- LibOS/shim/test/regression/rdtsc.c | 16 +- LibOS/shim/test/regression/readdir.c | 7 +- .../test/regression/sigaction_per_process.c | 6 +- LibOS/shim/test/regression/sigaltstack.c | 2 +- LibOS/shim/test/regression/sighandler_reset.c | 5 +- .../shim/test/regression/signal_multithread.c | 2 +- .../test/regression/sigprocmask_pending.c | 15 +- LibOS/shim/test/regression/system.c | 2 +- LibOS/shim/test/regression/tcp_ipv6_v6only.c | 12 +- LibOS/shim/test/regression/tcp_msg_peek.c | 2 +- .../arch/x86_64/Linux-SGX/sigcontext.h | 2 +- Pal/include/arch/x86_64/Linux-SGX/ucontext.h | 2 +- Pal/include/arch/x86_64/Linux/elf-arch.h | 15 +- .../arch/x86_64/Linux/pal_linux_defs.h | 4 +- Pal/include/arch/x86_64/Linux/sysdep-arch.h | 3 +- Pal/include/arch/x86_64/Linux/ucontext.h | 13 +- .../arch/x86_64/Skeleton/pal_host-arch.h | 1 - Pal/include/arch/x86_64/Skeleton/ucontext.h | 2 +- Pal/include/arch/x86_64/cpu.h | 23 +- Pal/include/arch/x86_64/dl-machine.h | 3 +- Pal/include/arch/x86_64/pal-arch.h | 53 +- Pal/include/elf/elf.h | 3 +- Pal/include/lib/api.h | 268 +++++---- Pal/include/lib/assert.h | 2 +- Pal/include/lib/avl_tree.h | 3 +- Pal/include/lib/hex.h | 11 +- Pal/include/lib/pal_crypto.h | 13 +- Pal/include/lib/slabmgr.h | 10 +- Pal/include/lib/spinlock.h | 10 +- Pal/include/pal/pal.h | 216 +++---- Pal/include/pal/pal_debug.h | 6 +- Pal/include/pal/pal_error.h | 2 - Pal/include/sysdeps/generic/ldsodefs.h | 9 +- Pal/lib/avl_tree.c | 35 +- Pal/lib/crypto/adapters/mbedtls_adapter.c | 79 ++- Pal/lib/crypto/adapters/mbedtls_encoding.c | 3 +- Pal/lib/graphene/config.c | 6 +- Pal/lib/graphene/path.c | 6 +- Pal/lib/network/hton.c | 3 +- Pal/lib/stdlib/printfmt.c | 2 +- Pal/lib/string/strchr.c | 2 +- Pal/lib/string/strendswith.c | 2 +- Pal/regression/AttestationReport.c | 9 +- Pal/regression/Exception.c | 99 ++-- Pal/regression/File.c | 24 +- Pal/regression/Hex.c | 5 +- Pal/regression/avl_tree_test.c | 42 +- Pal/regression/normalize_path.c | 8 +- Pal/src/db_events.c | 4 +- Pal/src/db_exception.c | 2 +- Pal/src/db_main.c | 100 ++-- Pal/src/db_misc.c | 8 +- Pal/src/db_mutex.c | 2 +- Pal/src/db_process.c | 2 +- Pal/src/db_rtld.c | 456 +++++++-------- Pal/src/db_threading.c | 4 +- Pal/src/do-rel.h | 3 +- Pal/src/dynamic_link.h | 8 +- Pal/src/host/Linux-SGX/db_devices.c | 8 +- Pal/src/host/Linux-SGX/db_events.c | 10 +- Pal/src/host/Linux-SGX/db_exception.c | 133 +++-- Pal/src/host/Linux-SGX/db_files.c | 35 +- Pal/src/host/Linux-SGX/db_main-x86_64.c | 11 +- Pal/src/host/Linux-SGX/db_main.c | 53 +- Pal/src/host/Linux-SGX/db_memory.c | 4 +- Pal/src/host/Linux-SGX/db_misc.c | 174 +++--- Pal/src/host/Linux-SGX/db_mutex.c | 8 +- Pal/src/host/Linux-SGX/db_object.c | 9 +- Pal/src/host/Linux-SGX/db_pipes.c | 29 +- Pal/src/host/Linux-SGX/db_process.c | 66 +-- Pal/src/host/Linux-SGX/db_rtld.c | 90 ++- Pal/src/host/Linux-SGX/db_sockets.c | 12 +- Pal/src/host/Linux-SGX/db_streams.c | 8 +- Pal/src/host/Linux-SGX/db_threading.c | 58 +- Pal/src/host/Linux-SGX/debugger/sgx_gdb.c | 14 +- Pal/src/host/Linux-SGX/debugger/sgx_gdb.h | 2 +- Pal/src/host/Linux-SGX/elf-x86_64.h | 5 +- Pal/src/host/Linux-SGX/enclave_ecalls.c | 12 +- Pal/src/host/Linux-SGX/enclave_framework.c | 187 +++--- Pal/src/host/Linux-SGX/enclave_ocalls.c | 130 ++-- Pal/src/host/Linux-SGX/enclave_ocalls.h | 58 +- Pal/src/host/Linux-SGX/enclave_pages.c | 40 +- Pal/src/host/Linux-SGX/enclave_pf.c | 41 +- Pal/src/host/Linux-SGX/enclave_platform.c | 14 +- Pal/src/host/Linux-SGX/enclave_untrusted.c | 11 +- Pal/src/host/Linux-SGX/enclave_xstate.c | 51 +- Pal/src/host/Linux-SGX/generated-offsets.c | 14 +- Pal/src/host/Linux-SGX/linux_types.h | 8 +- Pal/src/host/Linux-SGX/ocall_types.h | 21 +- Pal/src/host/Linux-SGX/pal_host.h | 42 +- Pal/src/host/Linux-SGX/pal_linux.h | 164 +++--- Pal/src/host/Linux-SGX/pal_linux_defs.h | 30 +- Pal/src/host/Linux-SGX/pal_linux_error.h | 3 +- Pal/src/host/Linux-SGX/pal_security.h | 36 +- .../Linux-SGX/protected-files/lru_cache.c | 20 +- .../Linux-SGX/protected-files/lru_cache.h | 3 +- .../protected-files/protected_files.c | 136 ++--- .../protected-files/protected_files.h | 16 +- .../protected_files_internal.h | 16 +- Pal/src/host/Linux-SGX/rpc_queue.h | 9 +- Pal/src/host/Linux-SGX/sgx_api.h | 4 +- Pal/src/host/Linux-SGX/sgx_arch.h | 10 +- Pal/src/host/Linux-SGX/sgx_attest.h | 4 +- Pal/src/host/Linux-SGX/sgx_enclave.c | 318 +++++----- Pal/src/host/Linux-SGX/sgx_exception.c | 47 +- Pal/src/host/Linux-SGX/sgx_framework.c | 141 +++-- Pal/src/host/Linux-SGX/sgx_graphene.c | 29 +- Pal/src/host/Linux-SGX/sgx_internal.h | 71 +-- Pal/src/host/Linux-SGX/sgx_main.c | 402 +++++++------ Pal/src/host/Linux-SGX/sgx_platform.c | 2 +- Pal/src/host/Linux-SGX/sgx_process.c | 36 +- Pal/src/host/Linux-SGX/sgx_rtld.c | 14 +- Pal/src/host/Linux-SGX/sgx_thread.c | 45 +- Pal/src/host/Linux-SGX/sgx_tls.h | 43 +- .../host/Linux-SGX/tools/common/attestation.c | 21 +- Pal/src/host/Linux-SGX/tools/common/ias.c | 34 +- Pal/src/host/Linux-SGX/tools/common/pf_util.c | 29 +- Pal/src/host/Linux-SGX/tools/common/pf_util.h | 14 +- Pal/src/host/Linux-SGX/tools/common/util.c | 4 +- Pal/src/host/Linux-SGX/tools/common/util.h | 23 +- .../host/Linux-SGX/tools/pf_crypt/pf_crypt.c | 56 +- Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls.h | 17 +- .../Linux-SGX/tools/ra-tls/ra_tls_attest.c | 22 +- .../tools/ra-tls/ra_tls_verify_dcap.c | 3 +- .../tools/ra-tls/ra_tls_verify_dcap_urts.c | 8 +- .../tools/ra-tls/secret_prov_attest.c | 8 +- .../tools/ra-tls/secret_prov_verify.c | 6 +- Pal/src/host/Linux/db_devices.c | 8 +- Pal/src/host/Linux/db_events.c | 2 +- Pal/src/host/Linux/db_exception.c | 37 +- Pal/src/host/Linux/db_files.c | 204 +++---- Pal/src/host/Linux/db_main-x86_64.c | 11 +- Pal/src/host/Linux/db_main.c | 42 +- Pal/src/host/Linux/db_memory.c | 19 +- Pal/src/host/Linux/db_misc.c | 8 +- Pal/src/host/Linux/db_mutex.c | 2 +- Pal/src/host/Linux/db_object.c | 6 +- Pal/src/host/Linux/db_pipes.c | 12 +- Pal/src/host/Linux/db_process.c | 86 ++- Pal/src/host/Linux/db_rtld.c | 105 ++-- Pal/src/host/Linux/db_sockets.c | 29 +- Pal/src/host/Linux/db_streams.c | 2 +- Pal/src/host/Linux/db_threading.c | 81 +-- Pal/src/host/Linux/pal_host.h | 40 +- Pal/src/host/Linux/pal_linux.h | 134 ++--- Pal/src/host/Linux/pal_linux_error.h | 3 +- Pal/src/host/Linux/pal_security.h | 2 +- Pal/src/host/Skeleton/db_eventfd.c | 2 +- Pal/src/host/Skeleton/db_main.c | 20 +- Pal/src/host/Skeleton/db_misc.c | 8 +- Pal/src/host/Skeleton/db_object.c | 4 +- Pal/src/host/Skeleton/db_rtld.c | 4 +- Pal/src/pal_internal.h | 237 ++++---- Pal/src/pal_rtld.h | 104 ++-- Pal/src/printf.c | 22 +- Pal/src/slab.c | 3 +- 284 files changed, 5320 insertions(+), 5759 deletions(-) diff --git a/.clang-format b/.clang-format index ab4bc68b41..507ba46e80 100644 --- a/.clang-format +++ b/.clang-format @@ -3,9 +3,9 @@ AlignConsecutiveAssignments: true AlignConsecutiveMacros: true AllowShortFunctionsOnASingleLine: Empty AllowShortIfStatementsOnASingleLine: false -ColumnLimit: 100 +ColumnLimit: 100 DerivePointerAlignment: false -IndentWidth: 4 +IndentWidth: 4 ObjCBlockIndentWidth: 4 PointerAlignment: Left -TabWidth: 4 +TabWidth: 4 diff --git a/Documentation/devel/coding-style.rst b/Documentation/devel/coding-style.rst index af57d324d0..dbdb710eb1 100644 --- a/Documentation/devel/coding-style.rst +++ b/Documentation/devel/coding-style.rst @@ -4,8 +4,6 @@ Coding style guidelines This document describes coding conventions and formatting styles we use in Graphene. All newly commited code must conform to them to pass a |~| review. -.. note:: Old code is temporarily excluded from these rules until reformatted. - Automatic reformatting ---------------------- @@ -31,6 +29,13 @@ recommend you first commit them (or add to `git index :command:`git diff` (or :command:`git diff --cached` if you used :command:`git add`). +.. warning:: + + Because of bugs in clang-format and its questionable reformats in many places + (seems it deals with C++ much better than with C) it's intended only as a |~| + helper tool. Adding it to git pre-commit hooks is definitely a |~| bad idea, + at least currently. + C - @@ -101,6 +106,15 @@ Code formatting external dependencies, like :file:`curl.h`). #. Graphene's headers. +#. Assignments may be aligned when assigning some structurized data (e.g. struct + members). Example:: + + int some_int = 0; + bool asdf = true; + file->size = 123; + file->full_path = "/asdf/ghjkl"; + file->perms = 0644; + Conventions and high-level style ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #. Variable and function names should be sane and easy to understand (example: diff --git a/LibOS/shim/include/arch/x86_64/shim_dl-machine.h b/LibOS/shim/include/arch/x86_64/shim_dl-machine.h index bc5968dd5c..137c621d2e 100644 --- a/LibOS/shim/include/arch/x86_64/shim_dl-machine.h +++ b/LibOS/shim/include/arch/x86_64/shim_dl-machine.h @@ -2,10 +2,8 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * dl-machine-x86_64.c - * - * This file contains x64-specific codes for relocating ELF binaries. - * Most of the source codes are imported from GNU C library. + * This file contains x64-specific code for relocating ELF binaries. Most of the source code was + * imported from GNU C library. */ #ifndef __DL_MACHINE_H__ diff --git a/LibOS/shim/include/arch/x86_64/shim_tcb-arch.h b/LibOS/shim/include/arch/x86_64/shim_tcb-arch.h index f94eac5591..413637df0b 100644 --- a/LibOS/shim/include/arch/x86_64/shim_tcb-arch.h +++ b/LibOS/shim/include/arch/x86_64/shim_tcb-arch.h @@ -6,24 +6,24 @@ #include "pal.h" struct shim_regs { - uint64_t orig_rax; - uint64_t rsp; - uint64_t r15; - uint64_t r14; - uint64_t r13; - uint64_t r12; - uint64_t r11; - uint64_t r10; - uint64_t r9; - uint64_t r8; - uint64_t rcx; - uint64_t rdx; - uint64_t rsi; - uint64_t rdi; - uint64_t rbx; - uint64_t rbp; - uint64_t rflags; - uint64_t rip; + uint64_t orig_rax; + uint64_t rsp; + uint64_t r15; + uint64_t r14; + uint64_t r13; + uint64_t r12; + uint64_t r11; + uint64_t r10; + uint64_t r9; + uint64_t r8; + uint64_t rcx; + uint64_t rdx; + uint64_t rsi; + uint64_t rdi; + uint64_t rbx; + uint64_t rbp; + uint64_t rflags; + uint64_t rip; }; static inline uint64_t shim_regs_get_sp(struct shim_regs* sr) { diff --git a/LibOS/shim/include/arch/x86_64/shim_types-arch.h b/LibOS/shim/include/arch/x86_64/shim_types-arch.h index 95452417c5..862c50cfad 100644 --- a/LibOS/shim/include/arch/x86_64/shim_types-arch.h +++ b/LibOS/shim/include/arch/x86_64/shim_types-arch.h @@ -6,13 +6,13 @@ #include "shim_tcb-arch.h" /* asm/signal.h */ -#define NUM_SIGS 64 -#define SIGRTMIN 32 +#define NUM_SIGS 64 +#define SIGRTMIN 32 typedef struct { unsigned long __val[NUM_SIGS / (8 * sizeof(unsigned long))]; } __sigset_t; -#define RED_ZONE_SIZE 128 +#define RED_ZONE_SIZE 128 #endif /* _SHIM_TYPES_ARCH_H_ */ diff --git a/LibOS/shim/include/arch/x86_64/shim_ucontext-arch.h b/LibOS/shim/include/arch/x86_64/shim_ucontext-arch.h index 78c0e5a6cc..8898f14eb6 100644 --- a/LibOS/shim/include/arch/x86_64/shim_ucontext-arch.h +++ b/LibOS/shim/include/arch/x86_64/shim_ucontext-arch.h @@ -3,33 +3,33 @@ #ifndef _SHIM_UCONTEXT_ARCH_H_ #define _SHIM_UCONTEXT_ARCH_H_ -#include -#include +#include "shim_types.h" +#include "ucontext.h" static inline void shim_regs_to_ucontext(ucontext_t* context, struct shim_regs* regs) { - context->uc_mcontext.gregs[REG_R8] = regs->r8; - context->uc_mcontext.gregs[REG_R9] = regs->r9; - context->uc_mcontext.gregs[REG_R10] = regs->r10; - context->uc_mcontext.gregs[REG_R11] = regs->r11; - context->uc_mcontext.gregs[REG_R12] = regs->r12; - context->uc_mcontext.gregs[REG_R13] = regs->r13; - context->uc_mcontext.gregs[REG_R14] = regs->r14; - context->uc_mcontext.gregs[REG_R15] = regs->r15; - context->uc_mcontext.gregs[REG_RDI] = regs->rdi; - context->uc_mcontext.gregs[REG_RSI] = regs->rsi; - context->uc_mcontext.gregs[REG_RBP] = regs->rbp; - context->uc_mcontext.gregs[REG_RBX] = regs->rbx; - context->uc_mcontext.gregs[REG_RDX] = regs->rdx; - context->uc_mcontext.gregs[REG_RAX] = regs->orig_rax; - context->uc_mcontext.gregs[REG_RCX] = regs->rcx; - context->uc_mcontext.gregs[REG_RSP] = regs->rsp; - context->uc_mcontext.gregs[REG_RIP] = regs->rip; - context->uc_mcontext.gregs[REG_EFL] = regs->rflags; - context->uc_mcontext.gregs[REG_CSGSFS] = 0; - context->uc_mcontext.gregs[REG_ERR] = 0; - context->uc_mcontext.gregs[REG_TRAPNO] = 0; + context->uc_mcontext.gregs[REG_R8] = regs->r8; + context->uc_mcontext.gregs[REG_R9] = regs->r9; + context->uc_mcontext.gregs[REG_R10] = regs->r10; + context->uc_mcontext.gregs[REG_R11] = regs->r11; + context->uc_mcontext.gregs[REG_R12] = regs->r12; + context->uc_mcontext.gregs[REG_R13] = regs->r13; + context->uc_mcontext.gregs[REG_R14] = regs->r14; + context->uc_mcontext.gregs[REG_R15] = regs->r15; + context->uc_mcontext.gregs[REG_RDI] = regs->rdi; + context->uc_mcontext.gregs[REG_RSI] = regs->rsi; + context->uc_mcontext.gregs[REG_RBP] = regs->rbp; + context->uc_mcontext.gregs[REG_RBX] = regs->rbx; + context->uc_mcontext.gregs[REG_RDX] = regs->rdx; + context->uc_mcontext.gregs[REG_RAX] = regs->orig_rax; + context->uc_mcontext.gregs[REG_RCX] = regs->rcx; + context->uc_mcontext.gregs[REG_RSP] = regs->rsp; + context->uc_mcontext.gregs[REG_RIP] = regs->rip; + context->uc_mcontext.gregs[REG_EFL] = regs->rflags; + context->uc_mcontext.gregs[REG_CSGSFS] = 0; + context->uc_mcontext.gregs[REG_ERR] = 0; + context->uc_mcontext.gregs[REG_TRAPNO] = 0; context->uc_mcontext.gregs[REG_OLDMASK] = 0; - context->uc_mcontext.gregs[REG_CR2] = 0; + context->uc_mcontext.gregs[REG_CR2] = 0; } #endif /* _SHIM_UCONTEXT_ARCH_H_ */ diff --git a/LibOS/shim/include/shim_checkpoint.h b/LibOS/shim/include/shim_checkpoint.h index 23fd4ea119..9eaf3d61ee 100644 --- a/LibOS/shim/include/shim_checkpoint.h +++ b/LibOS/shim/include/shim_checkpoint.h @@ -14,7 +14,6 @@ #include #include "pal.h" - #include "shim_defs.h" #include "shim_ipc.h" @@ -58,7 +57,7 @@ struct shim_mem_entry { struct shim_mem_entry* next; void* addr; size_t size; - int prot; /* combination of PAL_PROT_* flags */ + int prot; /* combination of PAL_PROT_* flags */ }; struct shim_palhdl_entry { @@ -278,7 +277,7 @@ struct shim_cp_map_entry* get_cp_map_entry(void* map, void* addr, bool create); #define BEGIN_MIGRATION_DEF(name, ...) \ int migrate_cp_##name(struct shim_cp_store* store, ##__VA_ARGS__) { \ - int ret = 0; \ + int ret = 0; \ size_t base = store->base; #define END_MIGRATION_DEF(name) \ diff --git a/LibOS/shim/include/shim_context.h b/LibOS/shim/include/shim_context.h index d64707b17a..22d55f534c 100644 --- a/LibOS/shim/include/shim_context.h +++ b/LibOS/shim/include/shim_context.h @@ -9,7 +9,7 @@ #ifndef _SHIM_CONTEXT_H_ #define _SHIM_CONTEXT_H_ -#include +#include "shim_tcb.h" void restore_context(struct shim_context* context); void fixup_child_context(struct shim_regs* regs); diff --git a/LibOS/shim/include/shim_defs.h b/LibOS/shim/include/shim_defs.h index 7b05a2063e..d256f2e604 100644 --- a/LibOS/shim/include/shim_defs.h +++ b/LibOS/shim/include/shim_defs.h @@ -1,25 +1,25 @@ #ifndef _SHIM_DEFS_H_ #define _SHIM_DEFS_H_ -#define DEFAULT_HEAP_MIN_SIZE (256 * 1024 * 1024) /* 256MB */ -#define DEFAULT_MEM_MAX_NPAGES (1024 * 1024) /* 4GB */ -#define DEFAULT_BRK_MAX_SIZE (256 * 1024) /* 256KB */ -#define DEFAULT_SYS_STACK_SIZE (256 * 1024) /* 256KB */ +#define DEFAULT_HEAP_MIN_SIZE (256 * 1024 * 1024) /* 256MB */ +#define DEFAULT_MEM_MAX_NPAGES (1024 * 1024) /* 4GB */ +#define DEFAULT_BRK_MAX_SIZE (256 * 1024) /* 256KB */ +#define DEFAULT_SYS_STACK_SIZE (256 * 1024) /* 256KB */ -#define CP_INIT_VMA_SIZE (64 * 1024 * 1024) /* 64MB */ +#define CP_INIT_VMA_SIZE (64 * 1024 * 1024) /* 64MB */ /* debug message printout */ -#define DEBUGBUF_SIZE 256 -#define DEBUGBUF_BREAK 0 +#define DEBUGBUF_SIZE 256 +#define DEBUGBUF_BREAK 0 -#define DEFAULT_VMA_COUNT 64 +#define DEFAULT_VMA_COUNT 64 /* ELF aux vectors */ -#define REQUIRED_ELF_AUXV 8 /* number of LibOS-supported vectors */ -#define REQUIRED_ELF_AUXV_SPACE 16 /* extra memory space (in bytes) */ +#define REQUIRED_ELF_AUXV 8 /* number of LibOS-supported vectors */ +#define REQUIRED_ELF_AUXV_SPACE 16 /* extra memory space (in bytes) */ #if defined(__i386__) || defined(__x86_64__) -#define LIBOS_SYSCALL_BOUND (340 + 1) +#define LIBOS_SYSCALL_BOUND (340 + 1) #endif #endif /* _SHIM_DEFS_H_ */ diff --git a/LibOS/shim/include/shim_flags_conv.h b/LibOS/shim/include/shim_flags_conv.h index e063093e93..a80972bfb7 100644 --- a/LibOS/shim/include/shim_flags_conv.h +++ b/LibOS/shim/include/shim_flags_conv.h @@ -13,8 +13,8 @@ #define SHIM_FLAGS_CONV_H #include -#include #include +#include #include "assert.h" #include "pal.h" diff --git a/LibOS/shim/include/shim_fs.h b/LibOS/shim/include/shim_fs.h index e4c885ddfe..f64c8de311 100644 --- a/LibOS/shim/include/shim_fs.h +++ b/LibOS/shim/include/shim_fs.h @@ -11,8 +11,8 @@ #define _SHIM_FS_H_ #define __KERNEL__ -#include #include +#include #include "list.h" #include "pal.h" @@ -295,8 +295,6 @@ void put_mount(struct shim_mount* mount); struct shim_mount* find_mount_from_uri(const char* uri); -#include - static inline void set_handle_fs(struct shim_handle* hdl, struct shim_mount* fs) { get_mount(fs); hdl->fs = fs; @@ -512,7 +510,7 @@ struct pseudo_ent { const char* name; const struct pseudo_name_ops* name_ops; const struct pseudo_fs_ops* fs_ops; - const struct pseudo_dir* dir; /* NULL if pseudo-FS entry is a file */ + const struct pseudo_dir* dir; /* NULL if pseudo-FS entry is a file */ int type; /* LINUX_DT_REG, LINUX_DT_CHR, etc (if dir != NULL, then always LINUX_DT_DIR) */ }; diff --git a/LibOS/shim/include/shim_handle.h b/LibOS/shim/include/shim_handle.h index 4a09c0a16e..5933f87ee1 100644 --- a/LibOS/shim/include/shim_handle.h +++ b/LibOS/shim/include/shim_handle.h @@ -12,18 +12,19 @@ #include #include -#include // TODO: migrate to stdatomic.h #include #include #include #include -#include -#include -#include -#include -#include #include +#include "atomic.h" // TODO: migrate to stdatomic.h +#include "list.h" +#include "pal.h" +#include "shim_defs.h" +#include "shim_sysv.h" +#include "shim_types.h" + /* start definition of shim handle */ enum shim_handle_type { TYPE_FILE, diff --git a/LibOS/shim/include/shim_internal.h b/LibOS/shim/include/shim_internal.h index 9468f7c0ae..aa331179bf 100644 --- a/LibOS/shim/include/shim_internal.h +++ b/LibOS/shim/include/shim_internal.h @@ -12,7 +12,7 @@ #error "this header file can only be used inside SHIM" #endif -#define attribute_hidden __attribute__ ((visibility ("hidden"))) +#define attribute_hidden __attribute__((visibility("hidden"))) #define ALIAS_STR(name) #name @@ -36,12 +36,11 @@ static inline unsigned int get_cur_tid(void) { return SHIM_TCB_GET(tid); } -#define PAL_NATIVE_ERRNO() SHIM_TCB_GET(pal_errno) +#define PAL_NATIVE_ERRNO() SHIM_TCB_GET(pal_errno) -#define INTERNAL_TID_BASE ((IDTYPE) 1 << (sizeof(IDTYPE) * 8 - 1)) +#define INTERNAL_TID_BASE ((IDTYPE)1 << (sizeof(IDTYPE) * 8 - 1)) -static inline bool is_internal_tid(unsigned int tid) -{ +static inline bool is_internal_tid(unsigned int tid) { return tid >= INTERNAL_TID_BASE; } @@ -51,70 +50,69 @@ struct debug_buf { char buf[DEBUGBUF_SIZE]; }; -#include -#include -#include +#include "pal.h" +#include "pal_debug.h" +#include "pal_error.h" extern PAL_HANDLE debug_handle; #include -void debug_printf (const char * fmt, ...) __attribute__((format (printf, 1, 2))); -void debug_puts (const char * str); -void debug_putch (int ch); -void debug_vprintf (const char * fmt, va_list ap) __attribute__((format (printf, 1, 0))); +void debug_printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); +void debug_puts(const char* str); +void debug_putch(int ch); +void debug_vprintf(const char* fmt, va_list ap) __attribute__((format(printf, 1, 0))); -#define debug(fmt, ...) \ - do { \ - if (debug_handle) \ - debug_printf(fmt, ##__VA_ARGS__); \ +#define debug(fmt, ...) \ + do { \ + if (debug_handle) \ + debug_printf(fmt, ##__VA_ARGS__); \ } while (0) /* print system messages */ -#define SYSPRINT_BUFFER_SIZE 256 +#define SYSPRINT_BUFFER_SIZE 256 -void handle_printf (PAL_HANDLE hdl, const char * fmt, ...) __attribute__((format (printf, 2, 3))); -void handle_vprintf (PAL_HANDLE hdl, const char * fmt, va_list ap) __attribute__((format (printf, 2, 0))); +void handle_printf(PAL_HANDLE hdl, const char* fmt, ...) __attribute__((format(printf, 2, 3))); +void handle_vprintf(PAL_HANDLE hdl, const char* fmt, va_list ap) + __attribute__((format(printf, 2, 0))); -#define __SYS_PRINTF(fmt, ...) \ - do { \ - PAL_HANDLE _hdl = __open_shim_stdio(); \ - if (_hdl) \ - handle_printf(_hdl, fmt, ##__VA_ARGS__); \ +#define __SYS_PRINTF(fmt, ...) \ + do { \ + PAL_HANDLE _hdl = __open_shim_stdio(); \ + if (_hdl) \ + handle_printf(_hdl, fmt, ##__VA_ARGS__); \ } while (0) -#define __SYS_VPRINTF(fmt, va) \ - do { \ - PAL_HANDLE _hdl = __open_shim_stdio(); \ - if (_hdl) \ - handle_vprintf(_hdl, fmt, va); \ +#define __SYS_VPRINTF(fmt, va) \ + do { \ + PAL_HANDLE _hdl = __open_shim_stdio(); \ + if (_hdl) \ + handle_vprintf(_hdl, fmt, va); \ } while (0) - -#define __SYS_FPRINTF(hdl, fmt, ...) \ - do { \ - handle_printf(hdl, fmt, ##__VA_ARGS__); \ +#define __SYS_FPRINTF(hdl, fmt, ...) \ + do { \ + handle_printf(hdl, fmt, ##__VA_ARGS__); \ } while (0) -#define SYS_PRINTF(fmt, ...) \ - do { \ - MASTER_LOCK(); \ - __SYS_PRINTF(fmt, ##__VA_ARGS__); \ - MASTER_UNLOCK(); \ +#define SYS_PRINTF(fmt, ...) \ + do { \ + MASTER_LOCK(); \ + __SYS_PRINTF(fmt, ##__VA_ARGS__); \ + MASTER_UNLOCK(); \ } while (0) -#define SYS_FPRINTF(hdl, fmt, ...) \ - do { \ - MASTER_LOCK(); \ - __SYS_FPRINTF(hdl, fmt, ##__VA_ARGS__); \ - MASTER_UNLOCK(); \ +#define SYS_FPRINTF(hdl, fmt, ...) \ + do { \ + MASTER_LOCK(); \ + __SYS_FPRINTF(hdl, fmt, ##__VA_ARGS__); \ + MASTER_UNLOCK(); \ } while (0) extern PAL_HANDLE shim_stdio; -static inline PAL_HANDLE __open_shim_stdio (void) -{ - if (shim_stdio == (PAL_HANDLE) -1) +static inline PAL_HANDLE __open_shim_stdio(void) { + if (shim_stdio == (PAL_HANDLE)-1) return NULL; if (shim_stdio) @@ -123,7 +121,7 @@ static inline PAL_HANDLE __open_shim_stdio (void) shim_stdio = DkStreamOpen(URI_PREFIX_DEV "tty", PAL_ACCESS_RDWR, 0, 0, 0); if (!shim_stdio) { - shim_stdio = (PAL_HANDLE) -1; + shim_stdio = (PAL_HANDLE)-1; return NULL; } @@ -131,20 +129,22 @@ static inline PAL_HANDLE __open_shim_stdio (void) } #if 0 -# define DEBUG_BREAK_ON_FAILURE() DEBUG_BREAK() +#define DEBUG_BREAK_ON_FAILURE() DEBUG_BREAK() #else -# define DEBUG_BREAK_ON_FAILURE() do {} while (0) +#define DEBUG_BREAK_ON_FAILURE() do {} while (0) #endif -#define BUG() \ - do { \ - __SYS_PRINTF("BUG() " __FILE__ ":%d\n", __LINE__); \ - DEBUG_BREAK_ON_FAILURE(); \ - shim_clean_and_exit(-ENOTRECOVERABLE); \ +#define BUG() \ + do { \ + __SYS_PRINTF("BUG() " __FILE__ ":%d\n", __LINE__); \ + DEBUG_BREAK_ON_FAILURE(); \ + shim_clean_and_exit(-ENOTRECOVERABLE); \ } while (0) -#define DEBUG_HERE() \ - do { debug("%s (" __FILE__ ":%d)\n", __func__, __LINE__); } while (0) +#define DEBUG_HERE() \ + do { \ + debug("%s (" __FILE__ ":%d)\n", __func__, __LINE__); \ + } while (0) /* definition for syscall table */ void handle_signals(void); @@ -156,162 +156,161 @@ void syscall_wrapper_after_syscalldb(void); #define SHIM_ARG_TYPE long -static inline int64_t get_cur_preempt (void) { +static inline int64_t get_cur_preempt(void) { shim_tcb_t* tcb = shim_get_tcb(); assert(tcb); return __atomic_load_n(&tcb->context.preempt.counter, __ATOMIC_SEQ_CST); } -#define BEGIN_SHIM(name, args ...) \ - SHIM_ARG_TYPE __shim_##name(args) { \ - SHIM_ARG_TYPE ret = 0; \ - int64_t preempt = get_cur_preempt(); \ +#define BEGIN_SHIM(name, args...) \ + SHIM_ARG_TYPE __shim_##name(args) { \ + SHIM_ARG_TYPE ret = 0; \ + int64_t preempt = get_cur_preempt(); \ __UNUSED(preempt); -#define END_SHIM(name) \ - handle_signals(); \ - assert(preempt == get_cur_preempt()); \ - return ret; \ +#define END_SHIM(name) \ + handle_signals(); \ + assert(preempt == get_cur_preempt()); \ + return ret; \ } -#define DEFINE_SHIM_SYSCALL(name, n, func, ...) \ - SHIM_SYSCALL_##n (name, func, __VA_ARGS__) \ - EXPORT_SHIM_SYSCALL (name, n, __VA_ARGS__) +#define DEFINE_SHIM_SYSCALL(name, n, func, ...) \ + SHIM_SYSCALL_##n(name, func, __VA_ARGS__) \ + EXPORT_SHIM_SYSCALL(name, n, __VA_ARGS__) -#define PROTO_ARGS_0() void -#define PROTO_ARGS_1(t, a) t a -#define PROTO_ARGS_2(t, a, rest ...) t a, PROTO_ARGS_1(rest) -#define PROTO_ARGS_3(t, a, rest ...) t a, PROTO_ARGS_2(rest) -#define PROTO_ARGS_4(t, a, rest ...) t a, PROTO_ARGS_3(rest) -#define PROTO_ARGS_5(t, a, rest ...) t a, PROTO_ARGS_4(rest) -#define PROTO_ARGS_6(t, a, rest ...) t a, PROTO_ARGS_5(rest) +#define PROTO_ARGS_0() void +#define PROTO_ARGS_1(t, a) t a +#define PROTO_ARGS_2(t, a, rest...) t a, PROTO_ARGS_1(rest) +#define PROTO_ARGS_3(t, a, rest...) t a, PROTO_ARGS_2(rest) +#define PROTO_ARGS_4(t, a, rest...) t a, PROTO_ARGS_3(rest) +#define PROTO_ARGS_5(t, a, rest...) t a, PROTO_ARGS_4(rest) +#define PROTO_ARGS_6(t, a, rest...) t a, PROTO_ARGS_5(rest) #define CAST_ARGS_0() -#define CAST_ARGS_1(t, a) (SHIM_ARG_TYPE) a -#define CAST_ARGS_2(t, a, rest ...) (SHIM_ARG_TYPE) a, CAST_ARGS_1(rest) -#define CAST_ARGS_3(t, a, rest ...) (SHIM_ARG_TYPE) a, CAST_ARGS_2(rest) -#define CAST_ARGS_4(t, a, rest ...) (SHIM_ARG_TYPE) a, CAST_ARGS_3(rest) -#define CAST_ARGS_5(t, a, rest ...) (SHIM_ARG_TYPE) a, CAST_ARGS_4(rest) -#define CAST_ARGS_6(t, a, rest ...) (SHIM_ARG_TYPE) a, CAST_ARGS_5(rest) - -#define DEFINE_SHIM_FUNC(func, n, r, args ...) \ - r func (PROTO_ARGS_##n (args)); - -#define TYPE_HASH(t) ({ const char * _s = #t; \ - ((uint16_t) _s[0] << 8) + _s[1]; }) - -#define POINTER_TYPE(t) ({ int _h = TYPE_HASH(t); \ - _h == TYPE_HASH(void *) || _h == TYPE_HASH(char *) || \ - _h == TYPE_HASH(const); }) - -#define EXPORT_SHIM_SYSCALL(name, n, r, args ...) \ - r shim_##name (PROTO_ARGS_##n (args)) { \ - SHIM_ARG_TYPE ret = __shim_##name (CAST_ARGS_##n (args)); \ - if (POINTER_TYPE(r)) { \ - if ((uint64_t) ret >= (uint64_t) -4095L) return (r) 0; \ - } else { \ - if ((int) ret < 0) return (r) -1; \ - } \ - return (r) ret; \ +#define CAST_ARGS_1(t, a) (SHIM_ARG_TYPE)a +#define CAST_ARGS_2(t, a, rest...) (SHIM_ARG_TYPE)a, CAST_ARGS_1(rest) +#define CAST_ARGS_3(t, a, rest...) (SHIM_ARG_TYPE)a, CAST_ARGS_2(rest) +#define CAST_ARGS_4(t, a, rest...) (SHIM_ARG_TYPE)a, CAST_ARGS_3(rest) +#define CAST_ARGS_5(t, a, rest...) (SHIM_ARG_TYPE)a, CAST_ARGS_4(rest) +#define CAST_ARGS_6(t, a, rest...) (SHIM_ARG_TYPE)a, CAST_ARGS_5(rest) + +#define DEFINE_SHIM_FUNC(func, n, r, args...) \ + r func(PROTO_ARGS_##n(args)); + +#define TYPE_HASH(t) \ + ({ \ + const char* _s = #t; \ + ((uint16_t)_s[0] << 8) + _s[1]; \ + }) + +#define POINTER_TYPE(t) \ + ({ \ + int _h = TYPE_HASH(t); \ + _h == TYPE_HASH(void*) || _h == TYPE_HASH(char*) || _h == TYPE_HASH(const); \ + }) + +#define EXPORT_SHIM_SYSCALL(name, n, r, args...) \ + r shim_##name(PROTO_ARGS_##n(args)) { \ + SHIM_ARG_TYPE ret = __shim_##name(CAST_ARGS_##n(args)); \ + if (POINTER_TYPE(r)) { \ + if ((uint64_t)ret >= (uint64_t)-4095L) \ + return (r)0; \ + } else { \ + if ((int)ret < 0) \ + return (r)-1; \ + } \ + return (r)ret; \ } -#define PARSE_SYSCALL1(name, ...) \ - if (debug_handle) \ +#define PARSE_SYSCALL1(name, ...) \ + if (debug_handle) \ parse_syscall_before(__NR_##name, #name, ##__VA_ARGS__); -#define PARSE_SYSCALL2(name, ...) \ - if (debug_handle) \ +#define PARSE_SYSCALL2(name, ...) \ + if (debug_handle) \ parse_syscall_after(__NR_##name, #name, ##__VA_ARGS__); -void parse_syscall_before (int sysno, const char * name, int nr, ...); -void parse_syscall_after (int sysno, const char * name, int nr, ...); +void parse_syscall_before(int sysno, const char* name, int nr, ...); +void parse_syscall_after(int sysno, const char* name, int nr, ...); -#define SHIM_SYSCALL_0(name, func, r) \ - BEGIN_SHIM(name, void) \ - PARSE_SYSCALL1(name, 0); \ - r __ret = (func)(); \ - PARSE_SYSCALL2(name, 0, #r, __ret); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_0(name, func, r) \ + BEGIN_SHIM(name, void) \ + PARSE_SYSCALL1(name, 0); \ + r __ret = (func)(); \ + PARSE_SYSCALL2(name, 0, #r, __ret); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_1(name, func, r, t1, a1) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1) \ - t1 a1 = (t1) __arg1; \ - PARSE_SYSCALL1(name, 1, #t1, a1); \ - r __ret = (func)(a1); \ - PARSE_SYSCALL2(name, 1, #r, __ret, #t1, a1); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_1(name, func, r, t1, a1) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1) \ + t1 a1 = (t1)__arg1; \ + PARSE_SYSCALL1(name, 1, #t1, a1); \ + r __ret = (func)(a1); \ + PARSE_SYSCALL2(name, 1, #r, __ret, #t1, a1); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_2(name, func, r, t1, a1, t2, a2) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2) \ - t1 a1 = (t1) __arg1; \ - t2 a2 = (t2) __arg2; \ - PARSE_SYSCALL1(name, 2, #t1, a1, #t2, a2); \ - r __ret = (func)(a1, a2); \ - PARSE_SYSCALL2(name, 2, #r, __ret, #t1, a1, #t2, a2); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_2(name, func, r, t1, a1, t2, a2) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2) \ + t1 a1 = (t1)__arg1; \ + t2 a2 = (t2)__arg2; \ + PARSE_SYSCALL1(name, 2, #t1, a1, #t2, a2); \ + r __ret = (func)(a1, a2); \ + PARSE_SYSCALL2(name, 2, #r, __ret, #t1, a1, #t2, a2); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_3(name, func, r, t1, a1, t2, a2, t3, a3) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, \ - SHIM_ARG_TYPE __arg3) \ - t1 a1 = (t1) __arg1; \ - t2 a2 = (t2) __arg2; \ - t3 a3 = (t3) __arg3; \ - PARSE_SYSCALL1(name, 3, #t1, a1, #t2, a2, #t3, a3); \ - r __ret = (func)(a1, a2, a3); \ - PARSE_SYSCALL2(name, 3, #r, __ret, #t1, a1, #t2, a2, #t3, a3); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_3(name, func, r, t1, a1, t2, a2, t3, a3) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, SHIM_ARG_TYPE __arg3) \ + t1 a1 = (t1)__arg1; \ + t2 a2 = (t2)__arg2; \ + t3 a3 = (t3)__arg3; \ + PARSE_SYSCALL1(name, 3, #t1, a1, #t2, a2, #t3, a3); \ + r __ret = (func)(a1, a2, a3); \ + PARSE_SYSCALL2(name, 3, #r, __ret, #t1, a1, #t2, a2, #t3, a3); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_4(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, \ - SHIM_ARG_TYPE __arg3, SHIM_ARG_TYPE __arg4) \ - t1 a1 = (t1) __arg1; \ - t2 a2 = (t2) __arg2; \ - t3 a3 = (t3) __arg3; \ - t4 a4 = (t4) __arg4; \ - PARSE_SYSCALL1(name, 4, #t1, a1, #t2, a2, #t3, a3, #t4, a4); \ - r __ret = (func)(a1, a2, a3, a4); \ - PARSE_SYSCALL2(name, 4, #r, __ret, #t1, a1, #t2, a2, #t3, a3, \ - #t4, a4); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_4(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, SHIM_ARG_TYPE __arg3, \ + SHIM_ARG_TYPE __arg4) \ + t1 a1 = (t1)__arg1; \ + t2 a2 = (t2)__arg2; \ + t3 a3 = (t3)__arg3; \ + t4 a4 = (t4)__arg4; \ + PARSE_SYSCALL1(name, 4, #t1, a1, #t2, a2, #t3, a3, #t4, a4); \ + r __ret = (func)(a1, a2, a3, a4); \ + PARSE_SYSCALL2(name, 4, #r, __ret, #t1, a1, #t2, a2, #t3, a3, #t4, a4); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_5(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4, t5, a5) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, \ - SHIM_ARG_TYPE __arg3, SHIM_ARG_TYPE __arg4, \ - SHIM_ARG_TYPE __arg5) \ - t1 a1 = (t1) __arg1; \ - t2 a2 = (t2) __arg2; \ - t3 a3 = (t3) __arg3; \ - t4 a4 = (t4) __arg4; \ - t5 a5 = (t5) __arg5; \ - PARSE_SYSCALL1(name, 5, #t1, a1, #t2, a2, #t3, a3, #t4, a4, \ - #t5, a5); \ - r __ret = (func)(a1, a2, a3, a4, a5); \ - PARSE_SYSCALL2(name, 5, #r, __ret, #t1, a1, #t2, a2, #t3, a3, \ - #t4, a4, #t5, a5); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_5(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4, t5, a5) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, SHIM_ARG_TYPE __arg3, \ + SHIM_ARG_TYPE __arg4, SHIM_ARG_TYPE __arg5) \ + t1 a1 = (t1)__arg1; \ + t2 a2 = (t2)__arg2; \ + t3 a3 = (t3)__arg3; \ + t4 a4 = (t4)__arg4; \ + t5 a5 = (t5)__arg5; \ + PARSE_SYSCALL1(name, 5, #t1, a1, #t2, a2, #t3, a3, #t4, a4, #t5, a5); \ + r __ret = (func)(a1, a2, a3, a4, a5); \ + PARSE_SYSCALL2(name, 5, #r, __ret, #t1, a1, #t2, a2, #t3, a3, #t4, a4, #t5, a5); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) -#define SHIM_SYSCALL_6(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4, t5, a5, t6, a6) \ - BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, \ - SHIM_ARG_TYPE __arg3, SHIM_ARG_TYPE __arg4, \ - SHIM_ARG_TYPE __arg5, SHIM_ARG_TYPE __arg6) \ - t1 a1 = (t1) __arg1; \ - t2 a2 = (t2) __arg2; \ - t3 a3 = (t3) __arg3; \ - t4 a4 = (t4) __arg4; \ - t5 a5 = (t5) __arg5; \ - t6 a6 = (t6) __arg6; \ - PARSE_SYSCALL1(name, 6, #t1, a1, #t2, a2, #t3, a3, #t4, a4, \ - #t5, a5, #t6, a6); \ - r __ret = (func)(a1, a2, a3, a4, a5, a6); \ - PARSE_SYSCALL2(name, 6, #r, __ret, #t1, a1, #t2, a2, #t3, a3, \ - #t4, a4, #t5, a5, #t6, a6); \ - ret = (SHIM_ARG_TYPE) __ret; \ +#define SHIM_SYSCALL_6(name, func, r, t1, a1, t2, a2, t3, a3, t4, a4, t5, a5, t6, a6) \ + BEGIN_SHIM(name, SHIM_ARG_TYPE __arg1, SHIM_ARG_TYPE __arg2, SHIM_ARG_TYPE __arg3, \ + SHIM_ARG_TYPE __arg4, SHIM_ARG_TYPE __arg5, SHIM_ARG_TYPE __arg6) \ + t1 a1 = (t1)__arg1; \ + t2 a2 = (t2)__arg2; \ + t3 a3 = (t3)__arg3; \ + t4 a4 = (t4)__arg4; \ + t5 a5 = (t5)__arg5; \ + t6 a6 = (t6)__arg6; \ + PARSE_SYSCALL1(name, 6, #t1, a1, #t2, a2, #t3, a3, #t4, a4, #t5, a5, #t6, a6); \ + r __ret = (func)(a1, a2, a3, a4, a5, a6); \ + PARSE_SYSCALL2(name, 6, #r, __ret, #t1, a1, #t2, a2, #t3, a3, #t4, a4, #t5, a5, #t6, a6); \ + ret = (SHIM_ARG_TYPE)__ret; \ END_SHIM(name) #define SHIM_PROTO_ARGS_0 void @@ -331,30 +330,36 @@ void parse_syscall_after (int sysno, const char * name, int nr, ...); #define SHIM_UNUSED_ARGS_0() -#define SHIM_UNUSED_ARGS_1() do { \ - __UNUSED(__arg1); \ +#define SHIM_UNUSED_ARGS_1() \ + do { \ + __UNUSED(__arg1); \ } while (0) -#define SHIM_UNUSED_ARGS_2() do { \ - SHIM_UNUSED_ARGS_1(); \ - __UNUSED(__arg2); \ +#define SHIM_UNUSED_ARGS_2() \ + do { \ + SHIM_UNUSED_ARGS_1(); \ + __UNUSED(__arg2); \ } while (0) -#define SHIM_UNUSED_ARGS_3() do { \ - SHIM_UNUSED_ARGS_2(); \ - __UNUSED(__arg3); \ +#define SHIM_UNUSED_ARGS_3() \ + do { \ + SHIM_UNUSED_ARGS_2(); \ + __UNUSED(__arg3); \ } while (0) -#define SHIM_UNUSED_ARGS_4() do { \ - SHIM_UNUSED_ARGS_3(); \ - __UNUSED(__arg4); \ +#define SHIM_UNUSED_ARGS_4() \ + do { \ + SHIM_UNUSED_ARGS_3(); \ + __UNUSED(__arg4); \ } while (0) -#define SHIM_UNUSED_ARGS_5() do { \ - SHIM_UNUSED_ARGS_4(); \ - __UNUSED(__arg5); \ +#define SHIM_UNUSED_ARGS_5() \ + do { \ + SHIM_UNUSED_ARGS_4(); \ + __UNUSED(__arg5); \ } while (0) -#define SHIM_UNUSED_ARGS_6() do { \ - SHIM_UNUSED_ARGS_5(); \ - __UNUSED(__arg6); \ +#define SHIM_UNUSED_ARGS_6() \ + do { \ + SHIM_UNUSED_ARGS_5(); \ + __UNUSED(__arg6); \ } while (0) #define SHIM_SYSCALL_PROTO_0(NAME, RTYPE) \ @@ -387,67 +392,61 @@ void parse_syscall_after (int sysno, const char * name, int nr, ...); END_SHIM(name) \ EXPORT_SHIM_SYSCALL(name, n, __VA_ARGS__) -#define CONCAT2(t1, t2) __CONCAT2(t1, t2) +#define CONCAT2(t1, t2) __CONCAT2(t1, t2) #define __CONCAT2(t1, t2) t1##_##t2 -#define CONCAT3(t1, t2, t3) __CONCAT3(t1, t2, t3) +#define CONCAT3(t1, t2, t3) __CONCAT3(t1, t2, t3) #define __CONCAT3(t1, t2, t3) t1##_##t2##_##t3 /* Some SHIM internal errno */ -#define EISLINK 141 /* the path is a link */ -#define ECONTAINLINK 142 /* part of path contains a link */ -#define ENOTLINK 143 /* the path is not a link */ -#define ESKIPPED 144 /* skip looking up current path */ +#define EISLINK 141 /* the path is a link */ +#define ECONTAINLINK 142 /* part of path contains a link */ +#define ENOTLINK 143 /* the path is not a link */ +#define ESKIPPED 144 /* skip looking up current path */ -#define PAL_CB(member) (pal_control.member) +#define PAL_CB(member) (pal_control.member) -#define LOCK_FREE ((IDTYPE) -1) +#define LOCK_FREE ((IDTYPE)-1) extern bool lock_enabled; -static inline void enable_locking (void) -{ +static inline void enable_locking(void) { if (!lock_enabled) lock_enabled = true; } -static inline PAL_HANDLE thread_create (void * func, void * arg) -{ +static inline PAL_HANDLE thread_create(void* func, void* arg) { assert(lock_enabled); return DkThreadCreate(func, arg); } -static inline int64_t __disable_preempt (shim_tcb_t * tcb) -{ - //tcb->context.syscall_nr += SYSCALL_NR_PREEMPT_INC; +static inline int64_t __disable_preempt(shim_tcb_t* tcb) { + // tcb->context.syscall_nr += SYSCALL_NR_PREEMPT_INC; int64_t preempt = __atomic_add_fetch(&tcb->context.preempt.counter, 1, __ATOMIC_SEQ_CST); /* Assert if this counter overflows */ assert(preempt != 0); - //debug("disable preempt: %d\n", preempt); + // debug("disable preempt: %d\n", preempt); return preempt; } -static inline void disable_preempt (shim_tcb_t * tcb) -{ +static inline void disable_preempt(shim_tcb_t* tcb) { if (!tcb && !(tcb = shim_get_tcb())) return; __disable_preempt(tcb); } -static inline void __enable_preempt (shim_tcb_t * tcb) -{ +static inline void __enable_preempt(shim_tcb_t* tcb) { int64_t preempt = __atomic_sub_fetch(&tcb->context.preempt.counter, 1, __ATOMIC_SEQ_CST); /* Assert if this counter underflows */ __UNUSED(preempt); assert(preempt >= 0); - //debug("enable preempt: %d\n", preempt); + // debug("enable preempt: %d\n", preempt); } void __handle_signals(shim_tcb_t* tcb); -static inline void enable_preempt (shim_tcb_t * tcb) -{ +static inline void enable_preempt(shim_tcb_t* tcb) { if (!tcb && !(tcb = shim_get_tcb())) return; @@ -461,26 +460,24 @@ static inline void enable_preempt (shim_tcb_t * tcb) __enable_preempt(tcb); } -static inline bool lock_created(struct shim_lock* l) -{ +static inline bool lock_created(struct shim_lock* l) { return l->lock != NULL; } -static inline void clear_lock(struct shim_lock* l) -{ - l->lock = NULL; +static inline void clear_lock(struct shim_lock* l) { + l->lock = NULL; l->owner = 0; } static inline bool create_lock(struct shim_lock* l) { l->owner = 0; - l->lock = DkMutexCreate(0); + l->lock = DkMutexCreate(0); return l->lock != NULL; } static inline void destroy_lock(struct shim_lock* l) { DkObjectClose(l->lock); - l->lock = NULL; + l->lock = NULL; l->owner = 0; } @@ -502,7 +499,7 @@ static void lock(struct shim_lock* l) { __abort(); } - shim_tcb_t * tcb = shim_get_tcb(); + shim_tcb_t* tcb = shim_get_tcb(); disable_preempt(tcb); while (!DkSynchronizationObjectWait(l->lock, NO_TIMEOUT)) @@ -549,19 +546,25 @@ static inline bool locked(struct shim_lock* l) { extern struct shim_lock __master_lock; #if DEBUG_MASTER_LOCK == 1 -# define MASTER_LOCK() \ - do { \ - lock(&__master_lock); \ - pal_printf("master lock " __FILE__ ":%d\n", __LINE__); \ +#define MASTER_LOCK() \ + do { \ + lock(&__master_lock); \ + pal_printf("master lock " __FILE__ ":%d\n", __LINE__); \ } while (0) -# define MASTER_UNLOCK() \ - do { \ - pal_printf("master unlock " __FILE__ ":%d\n", __LINE__); \ - unlock(&__master_lock); \ +#define MASTER_UNLOCK() \ + do { \ + pal_printf("master unlock " __FILE__ ":%d\n", __LINE__); \ + unlock(&__master_lock); \ } while (0) #else -# define MASTER_LOCK() do { lock(&__master_lock); } while (0) -# define MASTER_UNLOCK() do { unlock(&__master_lock); } while (0) +#define MASTER_LOCK() \ + do { \ + lock(&__master_lock); \ + } while (0) +#define MASTER_UNLOCK() \ + do { \ + unlock(&__master_lock); \ + } while (0) #endif static inline bool create_lock_runtime(struct shim_lock* l) { @@ -577,41 +580,34 @@ static inline bool create_lock_runtime(struct shim_lock* l) { return ret; } -static inline void create_event (AEVENTTYPE * e) -{ +static inline void create_event(AEVENTTYPE* e) { if (!e->event) - e->event = DkStreamOpen(URI_PREFIX_PIPE, PAL_ACCESS_RDWR, 0, 0, - PAL_OPTION_NONBLOCK); + e->event = DkStreamOpen(URI_PREFIX_PIPE, PAL_ACCESS_RDWR, 0, 0, PAL_OPTION_NONBLOCK); } -static inline bool event_created (AEVENTTYPE * e) -{ +static inline bool event_created(AEVENTTYPE* e) { return e->event != NULL; } -static inline PAL_HANDLE event_handle (AEVENTTYPE * e) -{ +static inline PAL_HANDLE event_handle(AEVENTTYPE* e) { return e->event; } -static inline void destroy_event (AEVENTTYPE * e) -{ +static inline void destroy_event(AEVENTTYPE* e) { if (e->event) { DkObjectClose(e->event); e->event = NULL; } } -static inline void set_event (AEVENTTYPE * e, int n) -{ +static inline void set_event(AEVENTTYPE* e, int n) { if (e->event) { char bytes[n]; DkStreamWrite(e->event, 0, n, bytes, NULL); } } -static inline void wait_event (AEVENTTYPE * e) -{ +static inline void wait_event(AEVENTTYPE* e) { if (e->event) { char byte; int n = 0; @@ -621,8 +617,7 @@ static inline void wait_event (AEVENTTYPE * e) } } -static inline void clear_event (AEVENTTYPE * e) -{ +static inline void clear_event(AEVENTTYPE* e) { if (e->event) { char bytes[100]; int n; @@ -633,11 +628,10 @@ static inline void clear_event (AEVENTTYPE * e) } /* reference counter APIs */ -#define REF_GET(ref) __atomic_load_n(&(ref).counter, __ATOMIC_SEQ_CST) -#define REF_SET(ref, count) __atomic_store_n(&(ref).counter, count, __ATOMIC_SEQ_CST); +#define REF_GET(ref) __atomic_load_n(&(ref).counter, __ATOMIC_SEQ_CST) +#define REF_SET(ref, count) __atomic_store_n(&(ref).counter, count, __ATOMIC_SEQ_CST); -static inline int __ref_inc (REFTYPE * ref) -{ +static inline int __ref_inc(REFTYPE* ref) { int64_t _c; do { _c = __atomic_load_n(&ref->counter, __ATOMIC_SEQ_CST); @@ -647,10 +641,9 @@ static inline int __ref_inc (REFTYPE * ref) return _c + 1; } -#define REF_INC(ref) __ref_inc(&(ref)) +#define REF_INC(ref) __ref_inc(&(ref)) -static inline int __ref_dec (REFTYPE * ref) -{ +static inline int __ref_dec(REFTYPE* ref) { int64_t _c; do { _c = __atomic_load_n(&ref->counter, __ATOMIC_SEQ_CST); @@ -667,7 +660,7 @@ static inline int __ref_dec (REFTYPE * ref) #define REF_DEC(ref) __ref_dec(&(ref)) #ifndef __alloca -# define __alloca __builtin_alloca +#define __alloca __builtin_alloca #endif extern size_t g_pal_alloc_align; @@ -679,40 +672,40 @@ extern size_t g_pal_alloc_align; #define ALLOC_ALIGN_DOWN_PTR(x) ALIGN_DOWN_PTR_POW2(x, g_pal_alloc_align) #define ALLOC_ALIGN_UP_PTR(x) ALIGN_UP_PTR_POW2(x, g_pal_alloc_align) -void * __system_malloc (size_t size); -void __system_free (void * addr, size_t size); +void* __system_malloc(size_t size); +void __system_free(void* addr, size_t size); #define system_malloc __system_malloc -#define system_free __system_free +#define system_free __system_free -extern void * migrated_memory_start; -extern void * migrated_memory_end; +extern void* migrated_memory_start; +extern void* migrated_memory_end; -static inline bool memory_migrated(void * mem) -{ +static inline bool memory_migrated(void* mem) { return mem >= migrated_memory_start && mem < migrated_memory_end; } +extern void* __load_address; +extern void* __load_address_end; +extern void* __code_address; +extern void* __code_address_end; -extern void * __load_address, * __load_address_end; -extern void * __code_address, * __code_address_end; - -unsigned long parse_int (const char * str); +unsigned long parse_int(const char* str); extern const char** migrated_argv; extern const char** migrated_envp; struct shim_handle; -int init_brk_from_executable (struct shim_handle * exec); +int init_brk_from_executable(struct shim_handle* exec); int init_brk_region(void* brk_region, size_t data_segment_size); void reset_brk(void); -int init_internal_map (void); -int init_loader (void); -int init_manifest (PAL_HANDLE manifest_handle); +int init_internal_map(void); +int init_loader(void); +int init_manifest(PAL_HANDLE manifest_handle); int init_rlimit(void); -bool test_user_memory (void * addr, size_t size, bool write); -bool test_user_string (const char * addr); +bool test_user_memory(void* addr, size_t size, bool write); +bool test_user_string(const char* addr); uint64_t get_rlimit_cur(int resource); void set_rlimit_cur(int resource, uint64_t rlim); diff --git a/LibOS/shim/include/shim_ipc.h b/LibOS/shim/include/shim_ipc.h index 8f84ba92a7..5bd44364b5 100644 --- a/LibOS/shim/include/shim_ipc.h +++ b/LibOS/shim/include/shim_ipc.h @@ -10,14 +10,14 @@ #ifndef _SHIM_IPC_H_ #define _SHIM_IPC_H_ -#include -#include -#include -#include -#include -#include -#include -#include +#include "list.h" +#include "pal.h" +#include "shim_defs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_sysv.h" +#include "shim_thread.h" +#include "shim_types.h" /* if callback func returns RESPONSE_CALLBACK, send response msg even if callback succeeded */ #define RESPONSE_CALLBACK 1 @@ -26,7 +26,7 @@ #define LEASE_TIME 1000 #define IPC_MSG_MINIMAL_SIZE 48 -#define IPC_SEM_NOTIMEOUT ((unsigned long)-1) +#define IPC_SEM_NOTIMEOUT ((unsigned long)-1) #define MAX_IPC_PORT_FINI_CB 3 enum { @@ -48,10 +48,10 @@ enum { IPC_PORT_DIRECTCHILD = 1 << IPC_DIRECTCHILD, IPC_PORT_DIRECTPARENT = 1 << IPC_DIRECTPARENT, - IPC_PORT_CLIENT = 1 << IPC_CLIENT, - IPC_PORT_LEADER = 1 << IPC_LEADER, - IPC_PORT_OWNER = 1 << IPC_OWNER, - IPC_PORT_CONNECTION = 1 << IPC_CONNECTION, + IPC_PORT_CLIENT = 1 << IPC_CLIENT, + IPC_PORT_LEADER = 1 << IPC_LEADER, + IPC_PORT_OWNER = 1 << IPC_OWNER, + IPC_PORT_CONNECTION = 1 << IPC_CONNECTION, }; enum { @@ -470,7 +470,7 @@ struct shim_ipc_msg_with_ack* pop_ipc_msg_with_ack(struct shim_ipc_port* port, u int broadcast_ipc(struct shim_ipc_msg* msg, int target_type, struct shim_ipc_port* exclude_port); int send_ipc_message(struct shim_ipc_msg* msg, struct shim_ipc_port* port); int send_ipc_message_with_ack(struct shim_ipc_msg_with_ack* msg, struct shim_ipc_port* port, - unsigned long* seq, void* private_data); + unsigned long* seq, void* private_data); int send_response_ipc_message(struct shim_ipc_port* port, IDTYPE dest, int ret, unsigned long seq); void ipc_port_with_child_fini(struct shim_ipc_port* port, IDTYPE vmid, unsigned int exitcode); diff --git a/LibOS/shim/include/shim_signal.h b/LibOS/shim/include/shim_signal.h index 3b1f6ee121..615af7c20c 100644 --- a/LibOS/shim/include/shim_signal.h +++ b/LibOS/shim/include/shim_signal.h @@ -1,89 +1,98 @@ #ifndef _SHIM_SIGNAL_H_ #define _SHIM_SIGNAL_H_ -#include -#include -#include +#include "shim_defs.h" +#include "shim_types.h" +#include "ucontext.h" void sigaction_make_defaults(struct __kernel_sigaction* sig_action); void thread_sigaction_reset_on_execve(struct shim_thread* thread); -# define BITS_PER_WORD (8 * sizeof(unsigned long)) +#define BITS_PER_WORD (8 * sizeof(unsigned long)) /* The standard def of this macro is dumb */ #undef _SIGSET_NWORDS -# define _SIGSET_NWORDS (NUM_SIGS / BITS_PER_WORD) +#define _SIGSET_NWORDS (NUM_SIGS / BITS_PER_WORD) /* Return a mask that includes the bit for SIG only. */ -# define __sigmask(sig) \ - (((unsigned long int) 1) << (((sig) - 1) % (8 * sizeof (unsigned long int)))) +#define __sigmask(sig) \ + (((unsigned long int)1) << (((sig) - 1) % (8 * sizeof(unsigned long int)))) /* Return the word index for SIG. */ -# define __sigword(sig) (((sig) - 1) / (8 * sizeof (unsigned long int))) +#define __sigword(sig) (((sig) - 1) / (8 * sizeof(unsigned long int))) /* Clear all signals from SET. */ -# define __sigemptyset(set) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - __sigset_t *__set = (set); \ - while (--__cnt >= 0) __set->__val[__cnt] = 0; \ - 0; })) +#define __sigemptyset(set) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + __sigset_t* __set = (set); \ + while (--__cnt >= 0) \ + __set->__val[__cnt] = 0; \ + 0; \ + })) /* Set all signals in SET. */ -# define __sigfillset(set) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - __sigset_t *__set = (set); \ - while (--__cnt >= 0) __set->__val[__cnt] = ~0UL; \ - 0; })) - -# define __sigisemptyset(set) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - const __sigset_t *__set = (set); \ - int __ret = __set->__val[--__cnt]; \ - while (!__ret && --__cnt >= 0) \ - __ret = __set->__val[__cnt]; \ - __ret == 0; })) - -# define __sigandset(dest, left, right) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - __sigset_t *__dest = (dest); \ - const __sigset_t *__left = (left); \ - const __sigset_t *__right = (right); \ - while (--__cnt >= 0) \ - __dest->__val[__cnt] = (__left->__val[__cnt] \ - & __right->__val[__cnt]); \ - 0; })) - -# define __sigorset(dest, left, right) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - __sigset_t *__dest = (dest); \ - const __sigset_t *__left = (left); \ - const __sigset_t *__right = (right); \ - while (--__cnt >= 0) \ - __dest->__val[__cnt] = (__left->__val[__cnt] \ - | __right->__val[__cnt]); \ - 0; })) - -# define __signotset(dest, left, right) \ - (__extension__ ({ int __cnt = _SIGSET_NWORDS; \ - __sigset_t *__dest = (dest); \ - const __sigset_t *__left = (left); \ - const __sigset_t *__right = (right); \ - while (--__cnt >= 0) \ - __dest->__val[__cnt] = (__left->__val[__cnt] \ - & ~__right->__val[__cnt]); \ - 0; })) - -# define __SIGSETFN(NAME, BODY, CONST) \ - static inline int \ - NAME (CONST __sigset_t *__set, int __sig) \ - { \ - unsigned long int __mask = __sigmask (__sig); \ - unsigned long int __word = __sigword (__sig); \ - return BODY; \ +#define __sigfillset(set) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + __sigset_t* __set = (set); \ + while (--__cnt >= 0) \ + __set->__val[__cnt] = ~0UL; \ + 0; \ + })) + +#define __sigisemptyset(set) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + const __sigset_t* __set = (set); \ + int __ret = __set->__val[--__cnt]; \ + while (!__ret && --__cnt >= 0) \ + __ret = __set->__val[__cnt]; \ + __ret == 0; \ + })) + +#define __sigandset(dest, left, right) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + __sigset_t* __dest = (dest); \ + const __sigset_t* __left = (left); \ + const __sigset_t* __right = (right); \ + while (--__cnt >= 0) \ + __dest->__val[__cnt] = (__left->__val[__cnt] & __right->__val[__cnt]); \ + 0; \ + })) + +#define __sigorset(dest, left, right) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + __sigset_t* __dest = (dest); \ + const __sigset_t* __left = (left); \ + const __sigset_t* __right = (right); \ + while (--__cnt >= 0) \ + __dest->__val[__cnt] = (__left->__val[__cnt] | __right->__val[__cnt]); \ + 0; \ + })) + +#define __signotset(dest, left, right) \ + (__extension__({ \ + int __cnt = _SIGSET_NWORDS; \ + __sigset_t* __dest = (dest); \ + const __sigset_t* __left = (left); \ + const __sigset_t* __right = (right); \ + while (--__cnt >= 0) \ + __dest->__val[__cnt] = (__left->__val[__cnt] & ~__right->__val[__cnt]); \ + 0; \ + })) + +#define __SIGSETFN(NAME, BODY, CONST) \ + static inline int NAME(CONST __sigset_t* __set, int __sig) { \ + unsigned long int __mask = __sigmask(__sig); \ + unsigned long int __word = __sigword(__sig); \ + return BODY; \ } -__SIGSETFN (shim_sigismember, (__set->__val[__word] & __mask) ? 1 : 0, __const) -__SIGSETFN (shim_sigaddset, ((__set->__val[__word] |= __mask), 0), ) -__SIGSETFN (shim_sigdelset, ((__set->__val[__word] &= ~__mask), 0), ) +__SIGSETFN(shim_sigismember, (__set->__val[__word] & __mask) ? 1 : 0, __const) +__SIGSETFN(shim_sigaddset, ((__set->__val[__word] |= __mask), 0), ) +__SIGSETFN(shim_sigdelset, ((__set->__val[__word] &= ~__mask), 0), ) #define __sigismember shim_sigismember #define __sigaddset shim_sigaddset @@ -91,32 +100,29 @@ __SIGSETFN (shim_sigdelset, ((__set->__val[__word] &= ~__mask), 0), ) /* NB: Check shim_signal.c if this changes. Some memset(0) elision*/ struct shim_signal { - siginfo_t info; - bool context_stored; - ucontext_t context; - PAL_CONTEXT * pal_context; + siginfo_t info; + bool context_stored; + ucontext_t context; + PAL_CONTEXT* pal_context; }; void get_pending_signals(struct shim_thread* thread, __sigset_t* set); struct shim_thread; -int init_signal (void); +int init_signal(void); -void __store_context (shim_tcb_t * tcb, PAL_CONTEXT * pal_context, - struct shim_signal * signal); +void __store_context(shim_tcb_t* tcb, PAL_CONTEXT* pal_context, struct shim_signal* signal); int append_signal(struct shim_thread* thread, siginfo_t* info); void deliver_signal(siginfo_t* info, PAL_CONTEXT* context); -__sigset_t * get_sig_mask (struct shim_thread * thread); -__sigset_t * set_sig_mask (struct shim_thread * thread, - const __sigset_t * new_set); +__sigset_t* get_sig_mask(struct shim_thread* thread); +__sigset_t* set_sig_mask(struct shim_thread* thread, const __sigset_t* new_set); -int do_kill_thread (IDTYPE sender, IDTYPE tgid, IDTYPE tid, int sig, - bool use_ipc); -int do_kill_proc (IDTYPE sender, IDTYPE tgid, int sig, bool use_ipc); -int do_kill_pgroup (IDTYPE sender, IDTYPE pgid, int sig, bool use_ipc); +int do_kill_thread(IDTYPE sender, IDTYPE tgid, IDTYPE tid, int sig, bool use_ipc); +int do_kill_proc(IDTYPE sender, IDTYPE tgid, int sig, bool use_ipc); +int do_kill_pgroup(IDTYPE sender, IDTYPE pgid, int sig, bool use_ipc); #endif /* _SHIM_SIGNAL_H_ */ diff --git a/LibOS/shim/include/shim_sysv.h b/LibOS/shim/include/shim_sysv.h index 2a88cf8a63..57eaafe127 100644 --- a/LibOS/shim/include/shim_sysv.h +++ b/LibOS/shim/include/shim_sysv.h @@ -11,8 +11,9 @@ #ifndef __SHIM_SYSV_H__ #define __SHIM_SYSV_H__ -#include -#include +#include "list.h" +#include "shim_handle.h" +#include "shim_types.h" #define SYSV_TYPE_STR(type) \ ((type) == SYSV_MSGQ ? "MSGQ" \ @@ -28,8 +29,6 @@ struct shim_handle; #define MSG_NOERROR 010000 -#include - struct __kernel_msgbuf { long mtype; /* type of message */ char mtext[]; /* message text */ diff --git a/LibOS/shim/include/shim_table.h b/LibOS/shim/include/shim_table.h index 059adaca89..0457d301c2 100644 --- a/LibOS/shim/include/shim_table.h +++ b/LibOS/shim/include/shim_table.h @@ -1,13 +1,14 @@ #ifndef _SHIM_TABLE_H_ #define _SHIM_TABLE_H_ -#include -#include #include -#if defined(__i386__) || defined (__x86_64__) +#if defined(__i386__) || defined(__x86_64__) #include #endif +#include "shim_types.h" +#include "shim_unistd.h" + #ifdef IN_SHIM void debug_unsupp(int num); @@ -493,8 +494,8 @@ int shim_do_accept4(int sockfd, struct sockaddr* addr, int* addrlen, int flags); int shim_do_dup3(unsigned int oldfd, unsigned int newfd, int flags); int shim_do_epoll_create1(int flags); int shim_do_pipe2(int* fildes, int flags); -int shim_do_mknod(const char *pathname, mode_t mode, dev_t dev); -int shim_do_mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev); +int shim_do_mknod(const char* pathname, mode_t mode, dev_t dev); +int shim_do_mknodat(int dirfd, const char* pathname, mode_t mode, dev_t dev); ssize_t shim_do_recvmmsg(int sockfd, struct mmsghdr* msg, unsigned int vlen, int flags, struct __kernel_timespec* timeout); int shim_do_prlimit64(pid_t pid, int resource, const struct __kernel_rlimit64* new_rlim, diff --git a/LibOS/shim/include/shim_tcb.h b/LibOS/shim/include/shim_tcb.h index 3d7a4085d3..130e059538 100644 --- a/LibOS/shim/include/shim_tcb.h +++ b/LibOS/shim/include/shim_tcb.h @@ -1,20 +1,18 @@ #ifndef _SHIM_TCB_H_ #define _SHIM_TCB_H_ -#include - #include "api.h" +#include "assert.h" #include "atomic.h" #include "pal.h" - #include "shim_tcb-arch.h" #define SHIM_TCB_CANARY 0xdeadbeef struct shim_context { - struct shim_regs * regs; - uint64_t fs_base; - struct atomic_int preempt; + struct shim_regs* regs; + uint64_t fs_base; + struct atomic_int preempt; }; static inline unsigned long shim_context_get_sp(struct shim_context* sc) { @@ -50,15 +48,16 @@ struct shim_tcb { * If a segfault occurs with the range [start, end], * the code addr is set to cont_addr to alert the caller. */ struct { - void * start, * end; - void * cont_addr; + void* start; + void* end; + void* cont_addr; bool has_fault; } test_range; }; static inline void __shim_tcb_init(shim_tcb_t* shim_tcb) { - shim_tcb->canary = SHIM_TCB_CANARY; - shim_tcb->self = shim_tcb; + shim_tcb->canary = SHIM_TCB_CANARY; + shim_tcb->self = shim_tcb; shim_tcb->vma_cache = NULL; } diff --git a/LibOS/shim/include/shim_thread.h b/LibOS/shim/include/shim_thread.h index 5d19191a50..9ce374a77a 100644 --- a/LibOS/shim/include/shim_thread.h +++ b/LibOS/shim/include/shim_thread.h @@ -1,17 +1,16 @@ #ifndef _SHIM_THREAD_H_ #define _SHIM_THREAD_H_ -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include "api.h" +#include "list.h" +#include "pal.h" +#include "shim_defs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_signal.h" +#include "shim_tcb.h" +#include "shim_utils.h" +#include "shim_vma.h" struct shim_handle; struct shim_fd_map; @@ -63,9 +62,9 @@ struct shim_thread { PAL_HANDLE pal_handle; /* parent handle */ - struct shim_thread * parent; + struct shim_thread* parent; /* thread leader */ - struct shim_thread * leader; + struct shim_thread* leader; /* child handles; protected by thread->lock */ LISTP_TYPE(shim_thread) children; /* nodes in child handles; protected by the parent's lock */ @@ -73,12 +72,12 @@ struct shim_thread { /* nodes in global handles; protected by thread_list_lock */ LIST_TYPE(shim_thread) list; - struct shim_handle_map * handle_map; + struct shim_handle_map* handle_map; /* child tid */ int* set_child_tid; - int* clear_child_tid; /* LibOS zeroes it to notify parent that thread exited */ - int clear_child_tid_pal; /* PAL zeroes it to notify LibOS that thread exited */ + int* clear_child_tid; /* LibOS zeroes it to notify parent that thread exited */ + int clear_child_tid_pal; /* PAL zeroes it to notify LibOS that thread exited */ /* signal handling */ __sigset_t signal_mask; @@ -108,34 +107,36 @@ struct shim_thread { LISTP_TYPE(shim_thread) exited_children; /* file system */ - struct shim_dentry * root, * cwd; + struct shim_dentry* root; + struct shim_dentry* cwd; mode_t umask; /* executable */ - struct shim_handle * exec; + struct shim_handle* exec; - void * stack, * stack_top, * stack_red; - shim_tcb_t * shim_tcb; - void * frameptr; + void* stack; + void* stack_top; + void* stack_red; + shim_tcb_t* shim_tcb; + void* frameptr; REFTYPE ref_count; struct shim_lock lock; }; -int init_thread (void); +int init_thread(void); -static inline bool is_internal(struct shim_thread *thread) -{ +static inline bool is_internal(struct shim_thread* thread) { return thread->tid >= INTERNAL_TID_BASE; } void get_signal_handles(struct shim_signal_handles* handles); void put_signal_handles(struct shim_signal_handles* handles); -void get_thread (struct shim_thread * thread); -void put_thread (struct shim_thread * thread); +void get_thread(struct shim_thread* thread); +void put_thread(struct shim_thread* thread); -void debug_setprefix (shim_tcb_t * tcb); +void debug_setprefix(shim_tcb_t* tcb); static inline void debug_setbuf(shim_tcb_t* tcb, struct debug_buf* debug_buf) { @@ -179,9 +180,7 @@ static inline void set_cur_thread(struct shim_thread* thread) { } } -static inline void thread_setwait (struct shim_thread ** queue, - struct shim_thread * thread) -{ +static inline void thread_setwait(struct shim_thread** queue, struct shim_thread* thread) { if (!thread) thread = get_cur_thread(); DkEventClear(thread->scheduler_event); @@ -191,9 +190,8 @@ static inline void thread_setwait (struct shim_thread ** queue, } } -static inline int thread_sleep (uint64_t timeout_us) -{ - struct shim_thread * cur_thread = get_cur_thread(); +static inline int thread_sleep(uint64_t timeout_us) { + struct shim_thread* cur_thread = get_cur_thread(); if (!cur_thread) return -EINVAL; @@ -208,8 +206,7 @@ static inline int thread_sleep (uint64_t timeout_us) return 0; } -static inline void thread_wakeup (struct shim_thread * thread) -{ +static inline void thread_wakeup(struct shim_thread* thread) { DkEventSet(thread->scheduler_event); } @@ -262,15 +259,15 @@ extern struct shim_lock thread_list_lock; */ struct shim_thread* lookup_thread(IDTYPE tid); -void set_as_child (struct shim_thread * parent, struct shim_thread * child); +void set_as_child(struct shim_thread* parent, struct shim_thread* child); /* creating and revoking thread objects */ -struct shim_thread * get_new_thread (IDTYPE new_tid); -struct shim_thread * get_new_internal_thread (void); +struct shim_thread* get_new_thread(IDTYPE new_tid); +struct shim_thread* get_new_internal_thread(void); /* thread list utilities */ -void add_thread (struct shim_thread * thread); -void del_thread (struct shim_thread * thread); +void add_thread(struct shim_thread* thread); +void del_thread(struct shim_thread* thread); void cleanup_thread(IDTYPE caller, void* thread); bool mark_self_dead(void); @@ -281,8 +278,8 @@ int walk_thread_list(int (*callback)(struct shim_thread*, void*), void* arg, boo void dump_threads(void); /* reference counting of handle maps */ -void get_handle_map (struct shim_handle_map * map); -void put_handle_map (struct shim_handle_map * map); +void get_handle_map(struct shim_handle_map* map); +void put_handle_map(struct shim_handle_map* map); /* retriving handle mapping */ static inline struct shim_handle_map* get_cur_handle_map(struct shim_thread* thread) { @@ -315,14 +312,14 @@ void release_robust_list(struct robust_list_head* head); struct shim_clone_args { PAL_HANDLE create_event; PAL_HANDLE initialize_event; - struct shim_thread * parent, * thread; - void * stack; + struct shim_thread* parent; + struct shim_thread* thread; + void* stack; unsigned long fs_base; }; -void * allocate_stack (size_t size, size_t protect_size, bool user); +void* allocate_stack(size_t size, size_t protect_size, bool user); -int init_stack(const char** argv, const char** envp, const char*** out_argp, - elf_auxv_t** out_auxv); +int init_stack(const char** argv, const char** envp, const char*** out_argp, elf_auxv_t** out_auxv); #endif /* _SHIM_THREAD_H_ */ diff --git a/LibOS/shim/include/shim_types.h b/LibOS/shim/include/shim_types.h index ead775b96d..5d755f334c 100644 --- a/LibOS/shim/include/shim_types.h +++ b/LibOS/shim/include/shim_types.h @@ -1,78 +1,79 @@ #ifndef _SHIM_TYPES_H_ #define _SHIM_TYPES_H_ +#include #include #include -#include #define __KERNEL__ -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include #include +#include +#include +#include #include +#include +#include +#include #include -#include -#include -#include -#include -#include -#include - +#include "elf.h" +#include "pal.h" #include "shim_types-arch.h" -typedef unsigned int __u32; - -typedef unsigned long int nfds_t; -typedef unsigned long int nlink_t; - -typedef __kernel_uid_t uid_t; -typedef __kernel_gid_t gid_t; -typedef __kernel_pid_t pid_t; -typedef __kernel_caddr_t caddr_t; -typedef __kernel_mode_t mode_t; -typedef __kernel_off_t off_t; -typedef __kernel_loff_t loff_t; -typedef __kernel_time_t time_t; -typedef __kernel_old_dev_t dev_t; -typedef __kernel_ino_t ino_t; -typedef __kernel_clockid_t clockid_t; -typedef __kernel_key_t key_t; -typedef __kernel_timer_t timer_t; -typedef __kernel_fd_set fd_set; +typedef unsigned int __u32; + +typedef unsigned long int nfds_t; +typedef unsigned long int nlink_t; + +typedef __kernel_uid_t uid_t; +typedef __kernel_gid_t gid_t; +typedef __kernel_pid_t pid_t; +typedef __kernel_caddr_t caddr_t; +typedef __kernel_mode_t mode_t; +typedef __kernel_off_t off_t; +typedef __kernel_loff_t loff_t; +typedef __kernel_time_t time_t; +typedef __kernel_old_dev_t dev_t; +typedef __kernel_ino_t ino_t; +typedef __kernel_clockid_t clockid_t; +typedef __kernel_key_t key_t; +typedef __kernel_timer_t timer_t; +typedef __kernel_fd_set fd_set; /* linux/time.h */ #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 18, 0) struct __kernel_timespec { - __kernel_time_t tv_sec; /* seconds */ - long tv_nsec; /* nanoseconds */ + __kernel_time_t tv_sec; /* seconds */ + long tv_nsec; /* nanoseconds */ }; #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(4, 19, 0) struct __kernel_itimerspec { - struct __kernel_timespec it_interval; /* timer period */ - struct __kernel_timespec it_value; /* timer expiration */ + struct __kernel_timespec it_interval; /* timer period */ + struct __kernel_timespec it_value; /* timer expiration */ }; #endif struct __kernel_timeval { - __kernel_time_t tv_sec; /* seconds */ - __kernel_suseconds_t tv_usec; /* microsecond */ + __kernel_time_t tv_sec; /* seconds */ + __kernel_suseconds_t tv_usec; /* microsecond */ }; struct __kernel_itimerval { - struct __kernel_timeval it_interval; /* time interval */ - struct __kernel_timeval it_value; /* current value */ + struct __kernel_timeval it_interval; /* time interval */ + struct __kernel_timeval it_value; /* current value */ }; struct __kernel_timezone { @@ -80,73 +81,75 @@ struct __kernel_timezone { int tz_dsttime; /* type of dst correction */ }; - /* linux/time.h * syscall interface - used (mainly by NTP daemon) * to discipline kernel clock oscillator */ struct ____kernel_timex { - unsigned int modes; /* mode selector */ - long offset; /* time offset (usec) */ - long freq; /* frequency offset (scaled ppm) */ - long maxerror; /* maximum error (usec) */ - long esterror; /* estimated error (usec) */ - int status; /* clock command/status */ - long constant; /* pll time constant */ - long precision; /* clock precision (usec) (read only) */ - long tolerance; /* clock frequency tolerance (ppm) - * (read only) */ - struct __kernel_timeval time; /* (read only) */ - long tick; /* (modified) usecs between clock ticks */ - - long ppsfreq; /* pps frequency (scaled ppm) (ro) */ - long jitter; /* pps jitter (us) (ro) */ - int shift; /* interval duration (s) (shift) (ro) */ - long stabil; /* pps stability (scaled ppm) (ro) */ - long jitcnt; /* jitter limit exceeded (ro) */ - long calcnt; /* calibration intervals (ro) */ - long errcnt; /* calibration errors (ro) */ - long stbcnt; /* stability limit exceeded (ro) */ - - int tai; /* TAI offset (ro) */ - - int :32; int :32; int :32; int :32; - int :32; int :32; int :32; int :32; - int :32; int :32; int :32; + unsigned int modes; /* mode selector */ + long offset; /* time offset (usec) */ + long freq; /* frequency offset (scaled ppm) */ + long maxerror; /* maximum error (usec) */ + long esterror; /* estimated error (usec) */ + int status; /* clock command/status */ + long constant; /* pll time constant */ + long precision; /* clock precision (usec) (read only) */ + long tolerance; /* clock frequency tolerance (ppm) (read only) */ + struct __kernel_timeval time; /* (read only) */ + long tick; /* (modified) usecs between clock ticks */ + + long ppsfreq; /* pps frequency (scaled ppm) (ro) */ + long jitter; /* pps jitter (us) (ro) */ + int shift; /* interval duration (s) (shift) (ro) */ + long stabil; /* pps stability (scaled ppm) (ro) */ + long jitcnt; /* jitter limit exceeded (ro) */ + long calcnt; /* calibration intervals (ro) */ + long errcnt; /* calibration errors (ro) */ + long stbcnt; /* stability limit exceeded (ro) */ + + int tai; /* TAI offset (ro) */ + + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; + int : 32; }; - /* /arch/x86/include/asm/posix_types_64.h */ -typedef unsigned int __kernel_uid_t; +typedef unsigned int __kernel_uid_t; typedef __kernel_uid_t __kernel_uid32_t; - /* quota.h */ typedef __kernel_uid32_t qid_t; /* Type in which we store ids in memory */ - /* capability.h */ typedef struct __user_cap_header_struct { __u32 version; int pid; -} *cap_user_header_t; +}* cap_user_header_t; typedef struct __user_cap_data_struct { __u32 effective; __u32 permitted; __u32 inheritable; -} *cap_user_data_t; - +}* cap_user_data_t; /* defined in function in sysdeps/unix/sysv/linux/sysctl.c */ struct __kernel_sysctl_args { - int *name; /* integer vector describing variable */ - int nlen; /* length of this vector */ - void *oldval; /* 0 or address where to store old value */ - size_t *oldlenp; /* available room for old value, + int* name; /* integer vector describing variable */ + int nlen; /* length of this vector */ + void* oldval; /* 0 or address where to store old value */ + size_t* oldlenp; /* available room for old value, overwritten by actual size of old value */ - void *newval; /* 0 or address of new value */ - size_t newlen; /* size of new value */ + void* newval; /* 0 or address of new value */ + size_t newlen; /* size of new value */ }; struct __kernel_sched_param { @@ -156,7 +159,7 @@ struct __kernel_sched_param { struct __kernel_sigaction { __sighandler_t k_sa_handler; unsigned long sa_flags; - void (*sa_restorer) (void); + void (*sa_restorer)(void); __sigset_t sa_mask; }; @@ -165,22 +168,22 @@ typedef unsigned long aio_context_t; /* linux/rlimit.h */ struct __kernel_rusage { - struct __kernel_timeval ru_utime; /* user time used */ - struct __kernel_timeval ru_stime; /* system time used */ - long ru_maxrss; /* maximum resident set size */ - long ru_ixrss; /* integral shared memory size */ - long ru_idrss; /* integral unshared data size */ - long ru_isrss; /* integral unshared stack size */ - long ru_minflt; /* page reclaims */ - long ru_majflt; /* page faults */ - long ru_nswap; /* swaps */ - long ru_inblock; /* block input operations */ - long ru_oublock; /* block output operations */ - long ru_msgsnd; /* messages sent */ - long ru_msgrcv; /* messages received */ - long ru_nsignals; /* signals received */ - long ru_nvcsw; /* voluntary context switches */ - long ru_nivcsw; /* involuntary " */ + struct __kernel_timeval ru_utime; /* user time used */ + struct __kernel_timeval ru_stime; /* system time used */ + long ru_maxrss; /* maximum resident set size */ + long ru_ixrss; /* integral shared memory size */ + long ru_idrss; /* integral unshared data size */ + long ru_isrss; /* integral unshared stack size */ + long ru_minflt; /* page reclaims */ + long ru_majflt; /* page faults */ + long ru_nswap; /* swaps */ + long ru_inblock; /* block input operations */ + long ru_oublock; /* block output operations */ + long ru_msgsnd; /* messages sent */ + long ru_msgrcv; /* messages received */ + long ru_nsignals; /* signals received */ + long ru_nvcsw; /* voluntary context switches */ + long ru_nivcsw; /* involuntary " */ }; struct __kernel_rlimit { @@ -208,44 +211,42 @@ __attribute__((packed)); #endif /* bits/ustat.h */ -struct __kernel_ustat - { - __daddr_t f_tfree; /* Number of free blocks. */ - __ino_t f_tinode; /* Number of free inodes. */ +struct __kernel_ustat { + __daddr_t f_tfree; /* Number of free blocks. */ + __ino_t f_tinode; /* Number of free inodes. */ char f_fname[6]; char f_fpack[6]; - }; +}; /* bits/socket.h */ -enum -{ +enum { MSG_OOB = 0x01, /* Process out-of-band data. */ MSG_PEEK = 0x02, /* Peek at incoming messages. */ MSG_DONTWAIT = 0x40, /* Nonblocking IO. */ MSG_NOSIGNAL = 0x4000, /* Do not generate SIGPIPE. */ -#define MSG_OOB MSG_OOB -#define MSG_PEEK MSG_PEEK +#define MSG_OOB MSG_OOB +#define MSG_PEEK MSG_PEEK #define MSG_DONTWAIT MSG_DONTWAIT #define MSG_NOSIGNAL MSG_NOSIGNAL }; struct msghdr { - void *msg_name; /* Address to send to/receive from. */ - int msg_namelen; /* Length of address data. */ + void* msg_name; /* Address to send to/receive from. */ + int msg_namelen; /* Length of address data. */ - struct iovec *msg_iov; /* Vector of data to send/receive into. */ - size_t msg_iovlen; /* Number of elements in the vector. */ + struct iovec* msg_iov; /* Vector of data to send/receive into. */ + size_t msg_iovlen; /* Number of elements in the vector. */ - void *msg_control; /* Ancillary data (eg BSD filedesc passing). */ - size_t msg_controllen; /* Ancillary data buffer length. */ + void* msg_control; /* Ancillary data (eg BSD filedesc passing). */ + size_t msg_controllen; /* Ancillary data buffer length. */ unsigned int msg_flags; /* Flags on received message. */ }; /* For `recvmmsg'. */ struct mmsghdr { - struct msghdr msg_hdr; /* Actual message header. */ - unsigned int msg_len; /* Number of received bytes for the entry. */ + struct msghdr msg_hdr; /* Actual message header. */ + unsigned int msg_len; /* Number of received bytes for the entry. */ }; /* POSIX.1g specifies this type name for the `sa_family' member. */ @@ -255,38 +256,37 @@ typedef unsigned short int sa_family_t; of the data types used for socket addresses, `struct sockaddr', `struct sockaddr_in', `struct sockaddr_un', etc. */ -#define __SOCKADDR_COMMON(sa_prefix) \ - sa_family_t sa_prefix##family - +#define __SOCKADDR_COMMON(sa_prefix) \ + sa_family_t sa_prefix##family /* Structure describing a generic socket address. */ struct sockaddr { - __SOCKADDR_COMMON (sa_); /* Common data: address family and length. */ - char sa_data[14]; /* Address data. */ + __SOCKADDR_COMMON(sa_); /* Common data: address family and length. */ + char sa_data[14]; /* Address data. */ }; /* From bits/socket.h */ /* Structure large enough to hold any socket address (with the historical exception of AF_UNIX). */ struct sockaddr_storage { - __SOCKADDR_COMMON(ss_); /* Address family, etc. */ + __SOCKADDR_COMMON(ss_); /* Address family, etc. */ char __ss_padding[128 - sizeof(sa_family_t)]; }; /* linux/mqueue.h */ struct __kernel_mq_attr { - long mq_flags; /* message queue flags */ - long mq_maxmsg; /* maximum number of messages */ - long mq_msgsize; /* maximum message size */ - long mq_curmsgs; /* number of messages currently queued */ - long __reserved[4]; /* ignored for input, zeroed for output */ + long mq_flags; /* message queue flags */ + long mq_maxmsg; /* maximum number of messages */ + long mq_msgsize; /* maximum message size */ + long mq_curmsgs; /* number of messages currently queued */ + long __reserved[4]; /* ignored for input, zeroed for output */ }; /* bits/uio.h */ /* Structure for scatter/gather I/O. */ struct iovec { - void * iov_base; /* Pointer to data. */ - size_t iov_len; /* Length of data. */ + void* iov_base; /* Pointer to data. */ + size_t iov_len; /* Length of data. */ }; /* bits/sched.h */ @@ -294,49 +294,49 @@ struct iovec { typedef unsigned long int __kernel_cpu_mask; /* Size definition for CPU sets. */ -# define __CPU_SETSIZE 1024 -# define __NCPUBITS (8 * sizeof (__kernel_cpu_mask)) +#define __CPU_SETSIZE 1024 +#define __NCPUBITS (8 * sizeof(__kernel_cpu_mask)) /* Data structure to describe CPU mask. */ typedef struct { - __kernel_cpu_mask __bits[__CPU_SETSIZE / __NCPUBITS]; + __kernel_cpu_mask __bits[__CPU_SETSIZE / __NCPUBITS]; } __kernel_cpu_set_t; struct getcpu_cache { unsigned long blob[128 / sizeof(long)]; }; -# undef __CPU_SETSIZE -# undef __NCPUBITS +#undef __CPU_SETSIZE +#undef __NCPUBITS -#define LINUX_DT_UNKNOWN 0 -#define LINUX_DT_FIFO 1 -#define LINUX_DT_CHR 2 -#define LINUX_DT_DIR 4 -#define LINUX_DT_BLK 6 -#define LINUX_DT_REG 8 -#define LINUX_DT_LNK 10 -#define LINUX_DT_SOCK 12 -#define LINUX_DT_WHT 14 +#define LINUX_DT_UNKNOWN 0 +#define LINUX_DT_FIFO 1 +#define LINUX_DT_CHR 2 +#define LINUX_DT_DIR 4 +#define LINUX_DT_BLK 6 +#define LINUX_DT_REG 8 +#define LINUX_DT_LNK 10 +#define LINUX_DT_SOCK 12 +#define LINUX_DT_WHT 14 struct linux_dirent64 { - uint64_t d_ino; /* Inode number */ - uint64_t d_off; /* Offset to next linux_dirent */ - unsigned short int d_reclen; /* Length of this linux_dirent */ - unsigned char d_type; - char d_name[]; /* File name (null-terminated) */ + uint64_t d_ino; /* Inode number */ + uint64_t d_off; /* Offset to next linux_dirent */ + unsigned short int d_reclen; /* Length of this linux_dirent */ + unsigned char d_type; + char d_name[]; /* File name (null-terminated) */ }; struct linux_dirent { - unsigned long d_ino; /* Inode number */ - unsigned long d_off; /* Offset to next linux_dirent */ - unsigned short int d_reclen; /* Length of this linux_dirent */ - char d_name[]; /* File name (null-terminated) */ + unsigned long d_ino; /* Inode number */ + unsigned long d_off; /* Offset to next linux_dirent */ + unsigned short int d_reclen; /* Length of this linux_dirent */ + char d_name[]; /* File name (null-terminated) */ }; struct linux_dirent_tail { - char pad; - unsigned char d_type; + char pad; + unsigned char d_type; }; struct linux_file_handle { @@ -345,8 +345,6 @@ struct linux_file_handle { unsigned char f_handle[0]; }; -#include "elf.h" - #ifdef __x86_64__ typedef Elf64_auxv_t elf_auxv_t; #else @@ -361,8 +359,6 @@ typedef uint64_t HASHTYPE; typedef struct atomic_int REFTYPE; -#include - struct shim_lock { PAL_HANDLE lock; IDTYPE owner; @@ -372,21 +368,21 @@ typedef struct shim_aevent { PAL_HANDLE event; } AEVENTTYPE; -#define STR_SIZE 4096 +#define STR_SIZE 4096 struct shim_str { char str[STR_SIZE]; }; -#define QSTR_SIZE 32 +#define QSTR_SIZE 32 /* Use qstr for names. This has fixed size string + string object * if len > SHIM_QSTR_SIZE then use overflow string */ struct shim_qstr { - HASHTYPE hash; - size_t len; - char name[QSTR_SIZE]; - struct shim_str * oflow; + HASHTYPE hash; + size_t len; + char name[QSTR_SIZE]; + struct shim_str* oflow; }; /* maximum length of pipe/FIFO name (should be less than Linux sockaddr_un.sun_path = 108) */ diff --git a/LibOS/shim/include/shim_utils.h b/LibOS/shim/include/shim_utils.h index 934940805c..a195f43532 100644 --- a/LibOS/shim/include/shim_utils.h +++ b/LibOS/shim/include/shim_utils.h @@ -8,11 +8,11 @@ #ifndef _SHIM_UTILS_H_ #define _SHIM_UTILS_H_ -#include -#include -#include -#include -#include +#include "api.h" +#include "list.h" +#include "pal.h" +#include "shim_handle.h" +#include "shim_internal.h" struct shim_handle; diff --git a/LibOS/shim/include/shim_vma.h b/LibOS/shim/include/shim_vma.h index b6dd9c1b53..f5ffe5200a 100644 --- a/LibOS/shim/include/shim_vma.h +++ b/LibOS/shim/include/shim_vma.h @@ -25,7 +25,7 @@ struct shim_vma_info { void* addr; size_t length; - int prot; // memory protection flags: PROT_* + int prot; // memory protection flags: PROT_* int flags; // MAP_* and VMA_* struct shim_handle* file; off_t file_offset; @@ -40,7 +40,6 @@ struct shim_vma_info { #define MAP_SHARED_VALIDATE 0x03 #endif // MAP_SHARED_VALIDATE - /* vma is kept for bookkeeping, but the memory is not actually allocated */ #define VMA_UNMAPPED 0x10000000 /* vma is used internally */ diff --git a/LibOS/shim/src/bookkeep/shim_handle.c b/LibOS/shim/src/bookkeep/shim_handle.c index 06ac90e28d..6760bad554 100644 --- a/LibOS/shim/src/bookkeep/shim_handle.c +++ b/LibOS/shim/src/bookkeep/shim_handle.c @@ -2,18 +2,16 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_handle.c - * - * This file contains codes to maintain bookkeeping for handles in library OS. + * This file contains code to maintain bookkeeping for handles in library OS. */ -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_thread.h" static struct shim_lock handle_mgr_lock; @@ -24,7 +22,7 @@ static struct shim_lock handle_mgr_lock; #define SYSTEM_LOCKED() locked(&handle_mgr_lock) #define OBJ_TYPE struct shim_handle -#include +#include "memmgr.h" static MEM_MGR handle_mgr = NULL; @@ -44,9 +42,9 @@ static inline int init_tty_handle(struct shim_handle* hdl, bool write) { if ((ret = path_lookupat(NULL, "/dev/tty", LOOKUP_OPEN, &dent, NULL)) < 0) return ret; - int flags = (write ? O_WRONLY : O_RDONLY) | O_APPEND; + int flags = (write ? O_WRONLY : O_RDONLY) | O_APPEND; struct shim_mount* fs = dent->fs; - ret = fs->d_ops->open(hdl, dent, flags); + ret = fs->d_ops->open(hdl, dent, flags); if (ret < 0) return ret; @@ -800,7 +798,8 @@ BEGIN_RS_FUNC(handle) { switch (hdl->type) { case TYPE_DEV: /* for device handles, info.dev.dev_ops contains function pointers into LibOS; they may - have become invalid due to relocation of LibOS text section in the child, update them */ + * have become invalid due to relocation of LibOS text section in the child, update them + */ if (dev_update_dev_ops(hdl) < 0) { return -EINVAL; } diff --git a/LibOS/shim/src/bookkeep/shim_signal.c b/LibOS/shim/src/bookkeep/shim_signal.c index 169ee75222..02d1f24e99 100644 --- a/LibOS/shim/src/bookkeep/shim_signal.c +++ b/LibOS/shim/src/bookkeep/shim_signal.c @@ -2,28 +2,28 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_signal.c - * - * This file contains codes to handle signals and exceptions passed from PAL. + * This file contains code for handling signals and exceptions passed from PAL. */ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ #include +#include + +#include "cpu.h" +#include "pal.h" +#include "shim_checkpoint.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_signal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_ucontext-arch.h" +#include "shim_unistd.h" +#include "shim_utils.h" +#include "shim_vma.h" // __rt_sighandler_t is different from __sighandler_t in : // typedef void __signalfn_t(int); @@ -33,8 +33,8 @@ typedef void (*__rt_sighandler_t)(int, siginfo_t*, void*); void sigaction_make_defaults(struct __kernel_sigaction* sig_action) { sig_action->k_sa_handler = (void*)SIG_DFL; - sig_action->sa_flags = 0; - sig_action->sa_restorer = NULL; + sig_action->sa_flags = 0; + sig_action->sa_restorer = NULL; __sigemptyset(&sig_action->sa_mask); } @@ -58,7 +58,7 @@ void thread_sigaction_reset_on_execve(struct shim_thread* thread) { static __rt_sighandler_t default_sighandler[NUM_SIGS]; -static struct shim_signal_queue process_signal_queue = { 0 }; +static struct shim_signal_queue process_signal_queue = {0}; /* This is just an optimization, not to have to check the queue for pending signals. A thread will * be woken up after signal is appended to its queue and will handle all unblocked pending signals * no matter what is the relative ordering of increasing this variable vs. appending signal to @@ -77,7 +77,7 @@ static uint64_t process_pending_signals_cnt = 0; */ static bool is_rt_sq_empty(struct shim_rt_signal_queue* queue) { return __atomic_load_n(&queue->get_idx, __ATOMIC_ACQUIRE) - == __atomic_load_n(&queue->put_idx, __ATOMIC_ACQUIRE); + == __atomic_load_n(&queue->put_idx, __ATOMIC_ACQUIRE); } static bool has_standard_signal(struct shim_signal** queue) { @@ -109,15 +109,14 @@ void get_pending_signals(struct shim_thread* thread, __sigset_t* set) { static bool append_standard_signal(struct shim_signal** signal_slot, struct shim_signal* signal) { struct shim_signal* old = NULL; - return __atomic_compare_exchange_n(signal_slot, &old, signal, /*weak=*/false, - __ATOMIC_RELEASE, __ATOMIC_ACQUIRE); + return __atomic_compare_exchange_n(signal_slot, &old, signal, /*weak=*/false, __ATOMIC_RELEASE, + __ATOMIC_ACQUIRE); } /* In theory `get_idx` and `put_idx` could overflow, but adding signals with 1GHz (10**9 signals * per second) gives a 544 years running time before overflow, which we consider a "safe margin" * for now. */ -static bool append_rt_signal(struct shim_rt_signal_queue* queue, - struct shim_signal* signal) { +static bool append_rt_signal(struct shim_rt_signal_queue* queue, struct shim_signal* signal) { uint64_t get_idx; uint64_t put_idx = __atomic_load_n(&queue->put_idx, __ATOMIC_ACQUIRE); do { @@ -213,15 +212,12 @@ static struct shim_signal* process_pop_signal(int sig) { static void __handle_one_signal(shim_tcb_t* tcb, struct shim_signal* signal); -static void __store_info (siginfo_t * info, struct shim_signal * signal) -{ +static void __store_info(siginfo_t* info, struct shim_signal* signal) { if (info) memcpy(&signal->info, info, sizeof(siginfo_t)); } -void __store_context (shim_tcb_t * tcb, PAL_CONTEXT * pal_context, - struct shim_signal * signal) -{ +void __store_context(shim_tcb_t* tcb, PAL_CONTEXT* pal_context, struct shim_signal* signal) { ucontext_t* context = &signal->context; if (tcb && tcb->context.regs && shim_context_get_syscallnr(&tcb->context)) { @@ -240,9 +236,8 @@ void __store_context (shim_tcb_t * tcb, PAL_CONTEXT * pal_context, } } -void deliver_signal (siginfo_t * info, PAL_CONTEXT * context) -{ - shim_tcb_t * tcb = shim_get_tcb(); +void deliver_signal(siginfo_t* info, PAL_CONTEXT* context) { + shim_tcb_t* tcb = shim_get_tcb(); assert(tcb); struct shim_thread* cur_thread = (struct shim_thread*)tcb->tp; @@ -255,7 +250,7 @@ void deliver_signal (siginfo_t * info, PAL_CONTEXT * context) int64_t preempt = __disable_preempt(tcb); - struct shim_signal * signal = __alloca(sizeof(struct shim_signal)); + struct shim_signal* signal = __alloca(sizeof(struct shim_signal)); /* save in signal */ memset(signal, 0, sizeof(struct shim_signal)); __store_info(info, signal); @@ -263,11 +258,11 @@ void deliver_signal (siginfo_t * info, PAL_CONTEXT * context) signal->pal_context = context; if (preempt > 1 || __sigismember(&cur_thread->signal_mask, sig)) { - signal = malloc_copy(signal,sizeof(struct shim_signal)); + signal = malloc_copy(signal, sizeof(struct shim_signal)); if (signal) { if (!append_thread_signal(cur_thread, signal)) { - debug("Signal %d queue of thread %u is full, dropping the incoming signal\n", - sig, tcb->tid); + debug("Signal %d queue of thread %u is full, dropping the incoming signal\n", sig, + tcb->tid); free(signal); } } @@ -279,25 +274,23 @@ void deliver_signal (siginfo_t * info, PAL_CONTEXT * context) __enable_preempt(tcb); } -#define ALLOC_SIGINFO(signo, code, member, value) \ - ({ \ - siginfo_t * _info = __alloca(sizeof(siginfo_t)); \ - memset(_info, 0, sizeof(siginfo_t)); \ - _info->si_signo = (signo); \ - _info->si_code = (code); \ - _info->member = (value); \ - _info; \ +#define ALLOC_SIGINFO(signo, code, member, value) \ + ({ \ + siginfo_t* _info = __alloca(sizeof(siginfo_t)); \ + memset(_info, 0, sizeof(siginfo_t)); \ + _info->si_signo = (signo); \ + _info->si_code = (code); \ + _info->member = (value); \ + _info; \ }) -static inline bool context_is_internal(PAL_CONTEXT * context) -{ +static inline bool context_is_internal(PAL_CONTEXT* context) { if (!context) return false; void* ip = (void*)pal_context_get_ip(context); - return ip >= (void*)&__code_address && - ip < (void*)&__code_address_end; + return (void*)&__code_address <= ip && ip < (void*)&__code_address_end; } static noreturn void internal_fault(const char* errstr, PAL_NUM addr, PAL_CONTEXT* context) { @@ -305,40 +298,35 @@ static noreturn void internal_fault(const char* errstr, PAL_NUM addr, PAL_CONTEX PAL_NUM ip = pal_context_get_ip(context); if (context_is_internal(context)) - SYS_PRINTF("%s at 0x%08lx (IP = +0x%lx, VMID = %u, TID = %u)\n", errstr, - addr, (void*)ip - (void*)&__load_address, - cur_process.vmid, is_internal_tid(tid) ? 0 : tid); + SYS_PRINTF("%s at 0x%08lx (IP = +0x%lx, VMID = %u, TID = %u)\n", errstr, addr, + (void*)ip - (void*)&__load_address, cur_process.vmid, + is_internal_tid(tid) ? 0 : tid); else - SYS_PRINTF("%s at 0x%08lx (IP = 0x%08lx, VMID = %u, TID = %u)\n", errstr, - addr, context ? ip : 0, - cur_process.vmid, is_internal_tid(tid) ? 0 : tid); + SYS_PRINTF("%s at 0x%08lx (IP = 0x%08lx, VMID = %u, TID = %u)\n", errstr, addr, + context ? ip : 0, cur_process.vmid, is_internal_tid(tid) ? 0 : tid); DEBUG_BREAK_ON_FAILURE(); DkProcessExit(1); } -static void arithmetic_error_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ +static void arithmetic_error_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { if (is_internal_tid(get_cur_tid()) || context_is_internal(context)) { internal_fault("Internal arithmetic fault", arg, context); } else { if (context) debug("arithmetic fault at 0x%08lx\n", pal_context_get_ip(context)); - deliver_signal(ALLOC_SIGINFO(SIGFPE, FPE_INTDIV, - si_addr, (void *) arg), context); + deliver_signal(ALLOC_SIGINFO(SIGFPE, FPE_INTDIV, si_addr, (void*)arg), context); } DkExceptionReturn(event); } -static void memfault_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ - shim_tcb_t * tcb = shim_get_tcb(); +static void memfault_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + shim_tcb_t* tcb = shim_get_tcb(); assert(tcb); - if (tcb->test_range.cont_addr - && (void *) arg >= tcb->test_range.start - && (void *) arg <= tcb->test_range.end) { + if (tcb->test_range.cont_addr && (void*)arg >= tcb->test_range.start && + (void*)arg <= tcb->test_range.end) { assert(context); tcb->test_range.has_fault = true; pal_context_set_ip(context, (PAL_NUM)tcb->test_range.cont_addr); @@ -357,7 +345,7 @@ static void memfault_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) int code; if (!arg) { code = SEGV_MAPERR; - } else if (!lookup_vma((void *) arg, &vma_info)) { + } else if (!lookup_vma((void*)arg, &vma_info)) { if (vma_info.flags & VMA_INTERNAL) { internal_fault("Internal memory fault with VMA", arg, context); } @@ -366,7 +354,7 @@ static void memfault_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) /* DEP 3/3/17: If the mapping exceeds end of a file (but is in the VMA) * then return a SIGBUS. */ uintptr_t eof_in_vma = (uintptr_t)vma_info.addr + vma_info.file_offset - + file->info.file.size; + + file->info.file.size; if (arg > eof_in_vma) { signo = SIGBUS; code = BUS_ADRERR; @@ -391,7 +379,7 @@ static void memfault_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) code = SEGV_MAPERR; } - deliver_signal(ALLOC_SIGINFO(signo, code, si_addr, (void *) arg), context); + deliver_signal(ALLOC_SIGINFO(signo, code, si_addr, (void*)arg), context); ret_exception: DkExceptionReturn(event); @@ -415,13 +403,12 @@ static void memfault_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) * The second option is faster in fault-free case but cannot be used under * SGX PAL. We use the best option for each PAL for now. */ static bool is_sgx_pal(void) { - static struct atomic_int sgx_pal = { .counter = 0 }; - static struct atomic_int inited = { .counter = 0 }; + static struct atomic_int sgx_pal = {.counter = 0}; + static struct atomic_int inited = {.counter = 0}; if (!__atomic_load_n(&inited.counter, __ATOMIC_SEQ_CST)) { /* Ensure that is_sgx_pal is updated before initialized */ - __atomic_store_n(&sgx_pal.counter, - !strcmp_static(PAL_CB(host_type), "Linux-SGX"), + __atomic_store_n(&sgx_pal.counter, !strcmp_static(PAL_CB(host_type), "Linux-SGX"), __ATOMIC_SEQ_CST); __atomic_store_n(&inited.counter, 1, __ATOMIC_SEQ_CST); } @@ -438,8 +425,7 @@ static bool is_sgx_pal(void) { * with a concurrent system call. The purpose of these functions is simply for * the compatibility with programs that rely on the error numbers, such as the * LTP test suite. */ -bool test_user_memory (void * addr, size_t size, bool write) -{ +bool test_user_memory(void* addr, size_t size, bool write) { if (!size) return false; @@ -452,7 +438,7 @@ bool test_user_memory (void * addr, size_t size, bool write) /* Non-SGX path: check if [addr, addr+size) is addressable by touching * a byte of each page; invalid access will be caught in memfault_upcall */ - shim_tcb_t * tcb = shim_get_tcb(); + shim_tcb_t* tcb = shim_get_tcb(); assert(tcb && tcb->tp); __disable_preempt(tcb); @@ -461,25 +447,25 @@ bool test_user_memory (void * addr, size_t size, bool write) assert(!tcb->test_range.cont_addr); tcb->test_range.has_fault = false; tcb->test_range.cont_addr = &&ret_fault; - tcb->test_range.start = addr; - tcb->test_range.end = addr + size - 1; + tcb->test_range.start = addr; + tcb->test_range.end = addr + size - 1; /* enforce compiler to store tcb->test_range into memory */ - __asm__ volatile(""::: "memory"); + __asm__ volatile("" ::: "memory"); /* Try to read or write into one byte inside each page */ - void * tmp = addr; + void* tmp = addr; while (tmp <= addr + size - 1) { if (write) { - *(volatile char *) tmp = *(volatile char *) tmp; + *(volatile char*)tmp = *(volatile char*)tmp; } else { - *(volatile char *) tmp; + *(volatile char*)tmp; } tmp = ALLOC_ALIGN_UP_PTR(tmp + 1); } ret_fault: /* enforce compiler to load tcb->test_range.has_fault below */ - __asm__ volatile("": "=m"(tcb->test_range.has_fault)); + __asm__ volatile("" : "=m"(tcb->test_range.has_fault)); /* If any read or write into the target region causes an exception, * the control flow will immediately jump to here. */ @@ -495,8 +481,7 @@ bool test_user_memory (void * addr, size_t size, bool write) * This function tests a user string with unknown length. It only tests * whether the memory is readable. */ -bool test_user_string (const char * addr) -{ +bool test_user_string(const char* addr) { if (!access_ok(addr, 1)) return true; @@ -510,7 +495,7 @@ bool test_user_string (const char * addr) do { maxlen = next - addr; - if (!access_ok(addr, maxlen) || !is_in_adjacent_user_vmas((void*) addr, maxlen)) + if (!access_ok(addr, maxlen) || !is_in_adjacent_user_vmas((void*)addr, maxlen)) return true; size = strnlen(addr, maxlen); @@ -523,7 +508,7 @@ bool test_user_string (const char * addr) /* Non-SGX path: check if [addr, addr+size) is addressable by touching * a byte of each page; invalid access will be caught in memfault_upcall. */ - shim_tcb_t * tcb = shim_get_tcb(); + shim_tcb_t* tcb = shim_get_tcb(); assert(tcb && tcb->tp); __disable_preempt(tcb); @@ -531,19 +516,19 @@ bool test_user_string (const char * addr) tcb->test_range.has_fault = false; tcb->test_range.cont_addr = &&ret_fault; /* enforce compiler to store tcb->test_range into memory */ - __asm__ volatile(""::: "memory"); + __asm__ volatile("" ::: "memory"); do { /* Add the memory region to the watch list. This is not racy because * each thread has its own record. */ - tcb->test_range.start = (void *) addr; - tcb->test_range.end = (void *) (next - 1); + tcb->test_range.start = (void*)addr; + tcb->test_range.end = (void*)(next - 1); maxlen = next - addr; if (!access_ok(addr, maxlen)) return true; - *(volatile char *) addr; /* try to read one byte from the page */ + *(volatile char*)addr; /* try to read one byte from the page */ size = strnlen(addr, maxlen); addr = next; @@ -552,7 +537,7 @@ bool test_user_string (const char * addr) ret_fault: /* enforce compiler to load tcb->test_range.has_fault below */ - __asm__ volatile("": "=m"(tcb->test_range.has_fault)); + __asm__ volatile("" : "=m"(tcb->test_range.has_fault)); /* If any read or write into the target region causes an exception, * the control flow will immediately jump to here. */ @@ -564,8 +549,7 @@ bool test_user_string (const char * addr) return has_fault; } -void __attribute__((weak)) syscall_wrapper(void) -{ +void __attribute__((weak)) syscall_wrapper(void) { /* * work around for link. * syscalldb.S is excluded for libsysdb_debug.so so it fails to link @@ -573,15 +557,11 @@ void __attribute__((weak)) syscall_wrapper(void) */ } -static void illegal_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ - struct shim_vma_info vma_info = { .file = NULL }; - - if (!is_internal_tid(get_cur_tid()) && - !context_is_internal(context) && - !(lookup_vma((void *)arg, &vma_info)) && - !(vma_info.flags & VMA_INTERNAL)) { +static void illegal_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + struct shim_vma_info vma_info = {.file = NULL}; + if (!is_internal_tid(get_cur_tid()) && !context_is_internal(context) && + !(lookup_vma((void*)arg, &vma_info)) && !(vma_info.flags & VMA_INTERNAL)) { assert(context); uint8_t* rip = (uint8_t*)pal_context_get_ip(context); @@ -623,8 +603,7 @@ static void illegal_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) } else { debug("Illegal instruction during app execution at 0x%08lx; delivering to app\n", (unsigned long)rip); - deliver_signal(ALLOC_SIGINFO(SIGILL, ILL_ILLOPC, - si_addr, (void *) arg), context); + deliver_signal(ALLOC_SIGINFO(SIGILL, ILL_ILLOPC, si_addr, (void*)arg), context); } } else { internal_fault("Illegal instruction during Graphene internal execution", arg, context); @@ -636,8 +615,7 @@ static void illegal_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) DkExceptionReturn(event); } -static void quit_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ +static void quit_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { __UNUSED(arg); __UNUSED(context); if (!is_internal_tid(get_cur_tid())) { @@ -646,8 +624,7 @@ static void quit_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) DkExceptionReturn(event); } -static void suspend_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ +static void suspend_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { __UNUSED(arg); __UNUSED(context); if (!is_internal_tid(get_cur_tid())) { @@ -656,11 +633,10 @@ static void suspend_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) DkExceptionReturn(event); } -static void resume_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ +static void resume_upcall(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { __UNUSED(arg); __UNUSED(context); - shim_tcb_t * tcb = shim_get_tcb(); + shim_tcb_t* tcb = shim_get_tcb(); if (!tcb || !tcb->tp) return; @@ -673,19 +649,17 @@ static void resume_upcall (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) DkExceptionReturn(event); } -int init_signal (void) -{ - DkSetExceptionHandler(&arithmetic_error_upcall, PAL_EVENT_ARITHMETIC_ERROR); - DkSetExceptionHandler(&memfault_upcall, PAL_EVENT_MEMFAULT); - DkSetExceptionHandler(&illegal_upcall, PAL_EVENT_ILLEGAL); - DkSetExceptionHandler(&quit_upcall, PAL_EVENT_QUIT); - DkSetExceptionHandler(&suspend_upcall, PAL_EVENT_SUSPEND); - DkSetExceptionHandler(&resume_upcall, PAL_EVENT_RESUME); +int init_signal(void) { + DkSetExceptionHandler(&arithmetic_error_upcall, PAL_EVENT_ARITHMETIC_ERROR); + DkSetExceptionHandler(&memfault_upcall, PAL_EVENT_MEMFAULT); + DkSetExceptionHandler(&illegal_upcall, PAL_EVENT_ILLEGAL); + DkSetExceptionHandler(&quit_upcall, PAL_EVENT_QUIT); + DkSetExceptionHandler(&suspend_upcall, PAL_EVENT_SUSPEND); + DkSetExceptionHandler(&resume_upcall, PAL_EVENT_RESUME); return 0; } -__sigset_t * get_sig_mask (struct shim_thread * thread) -{ +__sigset_t* get_sig_mask(struct shim_thread* thread) { if (!thread) thread = get_cur_thread(); @@ -694,9 +668,7 @@ __sigset_t * get_sig_mask (struct shim_thread * thread) return &(thread->signal_mask); } -__sigset_t * set_sig_mask (struct shim_thread * thread, - const __sigset_t * set) -{ +__sigset_t* set_sig_mask(struct shim_thread* thread, const __sigset_t* set) { if (!thread) thread = get_cur_thread(); @@ -723,7 +695,7 @@ static __rt_sighandler_t get_sighandler(struct shim_thread* thread, int sig, boo * sa_handler simply ignores 2nd and 3rd argument. */ #ifndef __x86_64__ -# error "get_sighandler: see the comment above" +#error "get_sighandler: see the comment above" #endif __rt_sighandler_t handler = (void*)sig_action->k_sa_handler; @@ -741,8 +713,7 @@ static __rt_sighandler_t get_sighandler(struct shim_thread* thread, int sig, boo return handler; } -static void -__handle_one_signal(shim_tcb_t* tcb, struct shim_signal* signal) { +static void __handle_one_signal(shim_tcb_t* tcb, struct shim_signal* signal) { struct shim_thread* thread = (struct shim_thread*)tcb->tp; __rt_sighandler_t handler = NULL; @@ -768,10 +739,9 @@ __handle_one_signal(shim_tcb_t* tcb, struct shim_signal* signal) { shim_context_set_syscallnr(&tcb->context, 0); } - debug("run signal handler %p (%d, %p, %p)\n", handler, sig, &signal->info, - &signal->context); + debug("run signal handler %p (%d, %p, %p)\n", handler, sig, &signal->info, &signal->context); - (*handler) (sig, &signal->info, &signal->context); + (*handler)(sig, &signal->info, &signal->context); __atomic_store_n(&thread->signal_handled, true, __ATOMIC_RELEASE); @@ -823,7 +793,7 @@ void __handle_signals(shim_tcb_t* tcb) { } void handle_signals(void) { - shim_tcb_t * tcb = shim_get_tcb(); + shim_tcb_t* tcb = shim_get_tcb(); assert(tcb); int64_t preempt = __disable_preempt(tcb); @@ -849,7 +819,7 @@ int append_signal(struct shim_thread* thread, siginfo_t* info) { /* save in signal */ __store_info(info, signal); signal->context_stored = false; - signal->pal_context = NULL; + signal->pal_context = NULL; if (thread) { if (append_thread_signal(thread, signal)) { @@ -884,8 +854,7 @@ static void sighandler_kill(int sig, siginfo_t* info, void* ucontext) { process_exit(0, sig); } -static void sighandler_core (int sig, siginfo_t * info, void * ucontext) -{ +static void sighandler_core(int sig, siginfo_t* info, void* ucontext) { /* NOTE: This implementation only indicates the core dump for wait4() * and friends. No actual core-dump file is created. */ sig = __WCOREDUMP_BIT | sig; @@ -893,41 +862,40 @@ static void sighandler_core (int sig, siginfo_t * info, void * ucontext) } static __rt_sighandler_t default_sighandler[NUM_SIGS] = { - /* SIGHUP */ &sighandler_kill, - /* SIGINT */ &sighandler_kill, - /* SIGQUIT */ &sighandler_core, - /* SIGILL */ &sighandler_core, - /* SIGTRAP */ &sighandler_core, - /* SIGABRT */ &sighandler_core, - /* SIGBUS */ &sighandler_core, - /* SIGFPE */ &sighandler_core, - /* SIGKILL */ &sighandler_kill, - /* SIGUSR1 */ &sighandler_kill, - /* SIGSEGV */ &sighandler_core, - /* SIGUSR2 */ &sighandler_kill, - /* SIGPIPE */ &sighandler_kill, - /* SIGALRM */ &sighandler_kill, - /* SIGTERM */ &sighandler_kill, - /* SIGSTKFLT */ &sighandler_kill, - /* SIGCHLD */ NULL, - /* SIGCONT */ NULL, - /* SIGSTOP */ NULL, - /* SIGTSTP */ NULL, - /* SIGTTIN */ NULL, - /* SIGTTOU */ NULL, - /* SIGURG */ NULL, - /* SIGXCPU */ &sighandler_core, - /* SIGXFSZ */ &sighandler_core, - /* SIGVTALRM */ &sighandler_kill, - /* SIGPROF */ &sighandler_kill, - /* SIGWINCH */ NULL, - /* SIGIO */ &sighandler_kill, - /* SIGPWR */ &sighandler_kill, - /* SIGSYS */ &sighandler_core + [SIGHUP - 1] = &sighandler_kill, + [SIGINT - 1] = &sighandler_kill, + [SIGQUIT - 1] = &sighandler_core, + [SIGILL - 1] = &sighandler_core, + [SIGTRAP - 1] = &sighandler_core, + [SIGABRT - 1] = &sighandler_core, + [SIGBUS - 1] = &sighandler_core, + [SIGFPE - 1] = &sighandler_core, + [SIGKILL - 1] = &sighandler_kill, + [SIGUSR1 - 1] = &sighandler_kill, + [SIGSEGV - 1] = &sighandler_core, + [SIGUSR2 - 1] = &sighandler_kill, + [SIGPIPE - 1] = &sighandler_kill, + [SIGALRM - 1] = &sighandler_kill, + [SIGTERM - 1] = &sighandler_kill, + [SIGSTKFLT - 1] = &sighandler_kill, + [SIGCHLD - 1] = NULL, + [SIGCONT - 1] = NULL, + [SIGSTOP - 1] = NULL, + [SIGTSTP - 1] = NULL, + [SIGTTIN - 1] = NULL, + [SIGTTOU - 1] = NULL, + [SIGURG - 1] = NULL, + [SIGXCPU - 1] = &sighandler_core, + [SIGXFSZ - 1] = &sighandler_core, + [SIGVTALRM - 1] = &sighandler_kill, + [SIGPROF - 1] = &sighandler_kill, + [SIGWINCH - 1] = NULL, + [SIGIO - 1] = &sighandler_kill, + [SIGPWR - 1] = &sighandler_kill, + [SIGSYS - 1] = &sighandler_core, }; -BEGIN_CP_FUNC(pending_signals) -{ +BEGIN_CP_FUNC(pending_signals) { __UNUSED(obj); __UNUSED(size); __UNUSED(objp); @@ -937,7 +905,7 @@ BEGIN_CP_FUNC(pending_signals) * safe margin slots. */ const size_t SAFE_MARGIN_SLOTS = 10; uint64_t n = __atomic_load_n(&process_pending_signals_cnt, __ATOMIC_ACQUIRE) - + SAFE_MARGIN_SLOTS; + + SAFE_MARGIN_SLOTS; uint64_t i = 0; assert(n <= SIGRTMIN - 1 + (NUM_SIGS - SIGRTMIN + 1) * MAX_SIGNAL_LOG + SAFE_MARGIN_SLOTS); siginfo_t infos[n]; @@ -972,8 +940,7 @@ BEGIN_CP_FUNC(pending_signals) } END_CP_FUNC(pending_signals) -BEGIN_RS_FUNC(pending_signals) -{ +BEGIN_RS_FUNC(pending_signals) { __UNUSED(offset); __UNUSED(rebase); @@ -990,7 +957,7 @@ BEGIN_RS_FUNC(pending_signals) memcpy(&signal->info, &infos[i], sizeof(signal->info)); signal->context_stored = false; - signal->pal_context = NULL; + signal->pal_context = NULL; if (!append_process_signal(signal)) { return -EAGAIN; } diff --git a/LibOS/shim/src/bookkeep/shim_thread.c b/LibOS/shim/src/bookkeep/shim_thread.c index 5e319f5846..c5e3e2a9fd 100644 --- a/LibOS/shim/src/bookkeep/shim_thread.c +++ b/LibOS/shim/src/bookkeep/shim_thread.c @@ -2,27 +2,28 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_thread.c - * - * This file contains codes to maintain bookkeeping of threads in library OS. + * This file contains code for maintaining bookkeeping of threads in library OS. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ #include +#include "cpu.h" +#include "list.h" +#include "pal.h" +#include "shim_checkpoint.h" +#include "shim_context.h" +#include "shim_defs.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_thread.h" +#include "shim_utils.h" +#include "shim_vma.h" + static IDTYPE tid_alloc_idx __attribute_migratable = 0; static LISTP_TYPE(shim_thread) thread_list = LISTP_INIT; @@ -40,13 +41,12 @@ PAL_HANDLE thread_start_event = NULL; #define DEBUG_PRINT_REF_COUNT(rc) __UNUSED(rc) #endif -int init_thread (void) -{ +int init_thread(void) { if (!create_lock(&thread_list_lock)) { return -ENOMEM; } - struct shim_thread * cur_thread = get_cur_thread(); + struct shim_thread* cur_thread = get_cur_thread(); if (cur_thread) return 0; @@ -60,14 +60,13 @@ int init_thread (void) return 0; } -void dump_threads (void) -{ - struct shim_thread * tmp; +void dump_threads(void) { + struct shim_thread* tmp; lock(&thread_list_lock); LISTP_FOR_EACH_ENTRY(tmp, &thread_list, list) { - debug("thread %d, vmid = %d, pgid = %d, ppid = %d, tgid = %d, in_vm = %d\n", - tmp->tid, tmp->vmid, tmp->pgid, tmp->ppid, tmp->tgid, tmp->in_vm); + debug("thread %d, vmid = %d, pgid = %d, ppid = %d, tgid = %d, in_vm = %d\n", tmp->tid, + tmp->vmid, tmp->pgid, tmp->ppid, tmp->tgid, tmp->in_vm); } unlock(&thread_list_lock); } @@ -123,8 +122,7 @@ static IDTYPE get_pid(void) { return idx; } -static IDTYPE get_internal_pid (void) -{ +static IDTYPE get_internal_pid(void) { lock(&thread_list_lock); internal_tid_alloc_idx++; IDTYPE idx = internal_tid_alloc_idx; @@ -133,9 +131,8 @@ static IDTYPE get_internal_pid (void) return idx; } -static struct shim_thread * alloc_new_thread (void) -{ - struct shim_thread * thread = calloc(1, sizeof(struct shim_thread)); +static struct shim_thread* alloc_new_thread(void) { + struct shim_thread* thread = calloc(1, sizeof(struct shim_thread)); if (!thread) return NULL; @@ -150,25 +147,24 @@ static struct shim_thread * alloc_new_thread (void) } static struct shim_signal_handles* alloc_default_signal_handles(void) { - struct shim_signal_handles* handles = malloc(sizeof(*handles)); - if (!handles) { - return NULL; - } + struct shim_signal_handles* handles = malloc(sizeof(*handles)); + if (!handles) { + return NULL; + } - if (!create_lock(&handles->lock)) { - free(handles); - return NULL; - } - REF_SET(handles->ref_count, 1); - for (size_t i = 0; i < ARRAY_SIZE(handles->actions); i++) { - sigaction_make_defaults(&handles->actions[i]); - } + if (!create_lock(&handles->lock)) { + free(handles); + return NULL; + } + REF_SET(handles->ref_count, 1); + for (size_t i = 0; i < ARRAY_SIZE(handles->actions); i++) { + sigaction_make_defaults(&handles->actions[i]); + } - return handles; + return handles; } -struct shim_thread * get_new_thread (IDTYPE new_tid) -{ +struct shim_thread* get_new_thread(IDTYPE new_tid) { if (!new_tid) { new_tid = get_pid(); if (!new_tid) { @@ -177,45 +173,44 @@ struct shim_thread * get_new_thread (IDTYPE new_tid) } } - struct shim_thread * thread = alloc_new_thread(); + struct shim_thread* thread = alloc_new_thread(); if (!thread) { release_ipc_id(new_tid); return NULL; } - struct shim_thread * cur_thread = get_cur_thread(); + struct shim_thread* cur_thread = get_cur_thread(); thread->tid = new_tid; if (cur_thread) { /* The newly created thread will be in the same thread group (process group as well) with its parent */ - thread->pgid = cur_thread->pgid; - thread->ppid = cur_thread->tgid; - thread->tgid = cur_thread->tgid; - thread->uid = cur_thread->uid; - thread->gid = cur_thread->gid; - thread->euid = cur_thread->euid; - thread->egid = cur_thread->egid; - thread->parent = cur_thread; - thread->stack = cur_thread->stack; - thread->stack_top = cur_thread->stack_top; - thread->stack_red = cur_thread->stack_red; - thread->cwd = cur_thread->cwd; - thread->root = cur_thread->root; - thread->umask = cur_thread->umask; - thread->exec = cur_thread->exec; + thread->pgid = cur_thread->pgid; + thread->ppid = cur_thread->tgid; + thread->tgid = cur_thread->tgid; + thread->uid = cur_thread->uid; + thread->gid = cur_thread->gid; + thread->euid = cur_thread->euid; + thread->egid = cur_thread->egid; + thread->parent = cur_thread; + thread->stack = cur_thread->stack; + thread->stack_top = cur_thread->stack_top; + thread->stack_red = cur_thread->stack_red; + thread->cwd = cur_thread->cwd; + thread->root = cur_thread->root; + thread->umask = cur_thread->umask; + thread->exec = cur_thread->exec; get_handle(cur_thread->exec); thread->signal_handles = cur_thread->signal_handles; get_signal_handles(thread->signal_handles); - memcpy(&thread->signal_mask, &cur_thread->signal_mask, - sizeof(sigset_t)); + memcpy(&thread->signal_mask, &cur_thread->signal_mask, sizeof(sigset_t)); get_dentry(cur_thread->cwd); get_dentry(cur_thread->root); - struct shim_handle_map * map = get_cur_handle_map(cur_thread); + struct shim_handle_map* map = get_cur_handle_map(cur_thread); assert(map); set_handle_map(thread, map); } else { @@ -226,8 +221,7 @@ struct shim_thread * get_new_thread (IDTYPE new_tid) */ path_lookupat(NULL, "/", 0, &thread->root, NULL); char dir_cfg[CONFIG_MAX]; - if (root_config && - get_config(root_config, "fs.start_dir", dir_cfg, sizeof(dir_cfg)) > 0) { + if (root_config && get_config(root_config, "fs.start_dir", dir_cfg, sizeof(dir_cfg)) > 0) { path_lookupat(NULL, dir_cfg, 0, &thread->cwd, NULL); } else if (thread->root) { get_dentry(thread->root); @@ -244,9 +238,9 @@ struct shim_thread * get_new_thread (IDTYPE new_tid) goto out_error; } - thread->vmid = cur_process.vmid; - thread->scheduler_event = DkNotificationEventCreate(PAL_TRUE); - thread->exit_event = DkNotificationEventCreate(PAL_FALSE); + thread->vmid = cur_process.vmid; + thread->scheduler_event = DkNotificationEventCreate(PAL_TRUE); + thread->exit_event = DkNotificationEventCreate(PAL_FALSE); thread->child_exit_event = DkNotificationEventCreate(PAL_FALSE); return thread; @@ -271,14 +265,13 @@ struct shim_thread * get_new_thread (IDTYPE new_tid) return NULL; } -struct shim_thread * get_new_internal_thread (void) -{ +struct shim_thread* get_new_internal_thread(void) { IDTYPE new_tid = get_internal_pid(); if (!new_tid) { return NULL; } - struct shim_thread * thread = alloc_new_thread(); + struct shim_thread* thread = alloc_new_thread(); if (!thread) return NULL; @@ -320,8 +313,7 @@ void put_thread(struct shim_thread* thread) { DEBUG_PRINT_REF_COUNT(ref_count); if (!ref_count) { - if (thread->pal_handle && - thread->pal_handle != PAL_CB(first_thread)) + if (thread->pal_handle && thread->pal_handle != PAL_CB(first_thread)) DkObjectClose(thread->pal_handle); if (thread->scheduler_event) @@ -359,9 +351,7 @@ void put_thread(struct shim_thread* thread) { } } -void set_as_child (struct shim_thread * parent, - struct shim_thread * child) -{ +void set_as_child(struct shim_thread* parent, struct shim_thread* child) { if (!parent) parent = get_cur_thread(); @@ -369,7 +359,7 @@ void set_as_child (struct shim_thread * parent, get_thread(child); lock(&child->lock); - child->ppid = parent->tid; + child->ppid = parent->tid; child->parent = parent; lock(&parent->lock); @@ -379,12 +369,12 @@ void set_as_child (struct shim_thread * parent, unlock(&child->lock); } -void add_thread (struct shim_thread * thread) -{ +void add_thread(struct shim_thread* thread) { if (is_internal(thread) || !LIST_EMPTY(thread, list)) return; - struct shim_thread * tmp, * prev = NULL; + struct shim_thread* tmp; + struct shim_thread* prev = NULL; lock(&thread_list_lock); /* keep it sorted */ @@ -404,9 +394,8 @@ void add_thread (struct shim_thread * thread) unlock(&thread_list_lock); } -void del_thread (struct shim_thread * thread) -{ - debug("del_thread(%p, %d, %ld)\n", thread, thread ? (int) thread->tid : -1, +void del_thread(struct shim_thread* thread) { + debug("del_thread(%p, %d, %ld)\n", thread, thread ? (int)thread->tid : -1, __atomic_load_n(&thread->ref_count.counter, __ATOMIC_SEQ_CST)); if (is_internal(thread)) { @@ -521,8 +510,7 @@ int walk_thread_list(int (*callback)(struct shim_thread*, void*), void* arg, boo return ret; } -BEGIN_CP_FUNC(signal_handles) -{ +BEGIN_CP_FUNC(signal_handles) { __UNUSED(size); assert(size == sizeof(struct shim_signal_handles)); @@ -552,12 +540,10 @@ BEGIN_CP_FUNC(signal_handles) if (objp) { *objp = (void*)new_handles; } - } END_CP_FUNC(signal_handles) -BEGIN_RS_FUNC(signal_handles) -{ +BEGIN_RS_FUNC(signal_handles) { __UNUSED(offset); __UNUSED(rebase); struct shim_signal_handles* handles = (void*)(base + GET_CP_FUNC_ENTRY()); @@ -568,20 +554,19 @@ BEGIN_RS_FUNC(signal_handles) } END_RS_FUNC(signal_handles) -BEGIN_CP_FUNC(thread) -{ +BEGIN_CP_FUNC(thread) { __UNUSED(size); assert(size == sizeof(struct shim_thread)); - struct shim_thread * thread = (struct shim_thread *) obj; - struct shim_thread * new_thread = NULL; + struct shim_thread* thread = (struct shim_thread*)obj; + struct shim_thread* new_thread = NULL; size_t off = GET_FROM_CP_MAP(obj); if (!off) { off = ADD_CP_OFFSET(sizeof(struct shim_thread)); ADD_TO_CP_MAP(obj, off); - new_thread = (struct shim_thread *) (base + off); + new_thread = (struct shim_thread*)(base + off); memcpy(new_thread, thread, sizeof(struct shim_thread)); INIT_LISTP(&new_thread->children); @@ -589,11 +574,11 @@ BEGIN_CP_FUNC(thread) INIT_LISTP(&new_thread->exited_children); INIT_LIST_HEAD(new_thread, list); - new_thread->in_vm = false; - new_thread->parent = NULL; + new_thread->in_vm = false; + new_thread->parent = NULL; new_thread->handle_map = NULL; - new_thread->root = NULL; - new_thread->cwd = NULL; + new_thread->root = NULL; + new_thread->cwd = NULL; memset(&new_thread->signal_queue, 0, sizeof(new_thread->signal_queue)); new_thread->robust_list = NULL; REF_SET(new_thread->ref_count, 0); @@ -606,17 +591,16 @@ BEGIN_CP_FUNC(thread) DO_CP_MEMBER(dentry, thread, new_thread, cwd); ADD_CP_FUNC_ENTRY(off); } else { - new_thread = (struct shim_thread *) (base + off); + new_thread = (struct shim_thread*)(base + off); } if (objp) - *objp = (void *) new_thread; + *objp = (void*)new_thread; } END_CP_FUNC(thread) -BEGIN_RS_FUNC(thread) -{ - struct shim_thread * thread = (void *) (base + GET_CP_FUNC_ENTRY()); +BEGIN_RS_FUNC(thread) { + struct shim_thread* thread = (void*)(base + GET_CP_FUNC_ENTRY()); __UNUSED(offset); CP_REBASE(thread->children); @@ -632,8 +616,8 @@ BEGIN_RS_FUNC(thread) if (!create_lock(&thread->lock)) { return -ENOMEM; } - thread->scheduler_event = DkNotificationEventCreate(PAL_TRUE); - thread->exit_event = DkNotificationEventCreate(PAL_FALSE); + thread->scheduler_event = DkNotificationEventCreate(PAL_TRUE); + thread->exit_event = DkNotificationEventCreate(PAL_FALSE); thread->child_exit_event = DkNotificationEventCreate(PAL_FALSE); add_thread(thread); @@ -654,41 +638,38 @@ BEGIN_RS_FUNC(thread) get_signal_handles(thread->signal_handles); } - DEBUG_RS("tid=%d,tgid=%d,parent=%d,stack=%p,frameptr=%p,tcb=%p,shim_tcb=%p", - thread->tid, thread->tgid, - thread->parent ? thread->parent->tid : thread->tid, - thread->stack, thread->frameptr, thread->tcb, thread->shim_tcb); + DEBUG_RS("tid=%d,tgid=%d,parent=%d,stack=%p,frameptr=%p,tcb=%p,shim_tcb=%p", thread->tid, + thread->tgid, thread->parent ? thread->parent->tid : thread->tid, thread->stack, + thread->frameptr, thread->tcb, thread->shim_tcb); } END_RS_FUNC(thread) -BEGIN_CP_FUNC(running_thread) -{ +BEGIN_CP_FUNC(running_thread) { __UNUSED(size); __UNUSED(objp); assert(size == sizeof(struct shim_thread)); - struct shim_thread * thread = (struct shim_thread *) obj; - struct shim_thread * new_thread = NULL; + struct shim_thread* thread = (struct shim_thread*)obj; + struct shim_thread* new_thread = NULL; DO_CP(thread, thread, &new_thread); ADD_CP_FUNC_ENTRY((uintptr_t)new_thread - base); if (thread->shim_tcb) { size_t toff = ADD_CP_OFFSET(sizeof(shim_tcb_t)); - new_thread->shim_tcb = (void *)(base + toff); + new_thread->shim_tcb = (void*)(base + toff); struct shim_tcb* new_tcb = new_thread->shim_tcb; memcpy(new_tcb, thread->shim_tcb, sizeof(*new_tcb)); /* don't export stale pointers */ - new_tcb->self = NULL; - new_tcb->tp = NULL; + new_tcb->self = NULL; + new_tcb->tp = NULL; new_tcb->debug_buf = NULL; } } END_CP_FUNC(running_thread) -static int resume_wrapper (void * param) -{ - struct shim_thread * thread = (struct shim_thread *) param; +static int resume_wrapper(void* param) { + struct shim_thread* thread = (struct shim_thread*)param; assert(thread); /* initialize the current shim_tcb_t (= shim_get_tcb()) @@ -704,7 +685,7 @@ static int resume_wrapper (void * param) thread->in_vm = thread->is_alive = true; shim_tcb_t* tcb = shim_get_tcb(); - tcb->context.regs = saved_tcb->context.regs; + tcb->context.regs = saved_tcb->context.regs; tcb->context.preempt = saved_tcb->context.preempt; debug_setbuf(tcb, NULL); debug("set fs_base to 0x%lx\n", fs_base); @@ -715,11 +696,10 @@ static int resume_wrapper (void * param) return 0; } -BEGIN_RS_FUNC(running_thread) -{ +BEGIN_RS_FUNC(running_thread) { __UNUSED(offset); - struct shim_thread * thread = (void *) (base + GET_CP_FUNC_ENTRY()); - struct shim_thread * cur_thread = get_cur_thread(); + struct shim_thread* thread = (void*)(base + GET_CP_FUNC_ENTRY()); + struct shim_thread* cur_thread = get_cur_thread(); thread->in_vm = true; thread->vmid = cur_process.vmid; diff --git a/LibOS/shim/src/bookkeep/shim_vma.c b/LibOS/shim/src/bookkeep/shim_vma.c index b0cb38275b..b2604766f0 100644 --- a/LibOS/shim/src/bookkeep/shim_vma.c +++ b/LibOS/shim/src/bookkeep/shim_vma.c @@ -3,6 +3,10 @@ * Copyright (C) 2020 Invisible Things Lab */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + #include #include #include @@ -60,10 +64,10 @@ static void copy_comment(struct shim_vma* vma, const char* comment) { static void copy_vma(struct shim_vma* old_vma, struct shim_vma* new_vma) { new_vma->begin = old_vma->begin; - new_vma->end = old_vma->end; - new_vma->prot = old_vma->prot; + new_vma->end = old_vma->end; + new_vma->prot = old_vma->prot; new_vma->flags = old_vma->flags; - new_vma->file = old_vma->file; + new_vma->file = old_vma->file; if (new_vma->file) { get_handle(new_vma->file); } @@ -94,7 +98,7 @@ static bool cmp_addr_to_vma(void* addr, struct avl_tree_node* node) { * Currently we do not merge similar adjacent vmas - if we ever start doing it, this code needs * to be revisited as there might be some optimizations that would break due to it. */ -static struct avl_tree vma_tree = { .cmp = vma_tree_cmp }; +static struct avl_tree vma_tree = {.cmp = vma_tree_cmp}; static spinlock_t vma_tree_lock = INIT_SPINLOCK_UNLOCKED; static struct shim_vma* node2vma(struct avl_tree_node* node) { @@ -157,8 +161,7 @@ static void split_vma(struct shim_vma* old_vma, struct shim_vma* new_vma, uintpt * either internal or non-internal. */ static int _vma_bkeep_remove(uintptr_t begin, uintptr_t end, bool is_internal, - struct shim_vma** new_vma_ptr, - struct shim_vma** vmas_to_free) { + struct shim_vma** new_vma_ptr, struct shim_vma** vmas_to_free) { assert(spinlock_is_locked(&vma_tree_lock)); assert(!new_vma_ptr || *new_vma_ptr); assert(IS_ALLOC_ALIGNED_PTR(begin) && IS_ALLOC_ALIGNED_PTR(end)); @@ -183,7 +186,6 @@ static int _vma_bkeep_remove(uintptr_t begin, uintptr_t end, bool is_internal, vma = _get_next_vma(vma); } - vma = first_vma; if (vma->begin < begin) { @@ -278,9 +280,9 @@ static void _vma_free(void* ptr, size_t size) { #undef system_malloc #undef system_free #define system_malloc _vma_malloc -#define system_free _vma_free -#define OBJ_TYPE struct shim_vma -#include +#define system_free _vma_free +#define OBJ_TYPE struct shim_vma +#include "memmgr.h" static struct shim_lock vma_mgr_lock; static MEM_MGR vma_mgr = NULL; @@ -306,9 +308,9 @@ static_assert((VMA_CACHE_SIZE & (VMA_CACHE_SIZE + 1)) == 0, "VMA_CACHE_SIZE must be a power of 2 minus 1!"); static struct shim_vma* cache2ptr(void* vma) { - static_assert(alignof(struct shim_vma) >= VMA_CACHE_SIZE + 1, - "We need some lower bits of pointers to `struct shim_vma` for this optimization!" - ); + static_assert( + alignof(struct shim_vma) >= VMA_CACHE_SIZE + 1, + "We need some lower bits of pointers to `struct shim_vma` for this optimization!"); return (struct shim_vma*)((uintptr_t)vma & ~VMA_CACHE_SIZE); } @@ -392,7 +394,7 @@ static struct shim_vma* alloc_vma(void) { if (!vma) { /* `enlarge_mem_mgr` below will call _vma_malloc, which uses at most 1 vma - so we * temporarily provide it. */ - struct shim_vma tmp_vma = { 0 }; + struct shim_vma tmp_vma = {0}; /* vma cache is empty, as we checked it before. */ if (!add_to_thread_vma_cache(&tmp_vma)) { debug("Failed to add tmp vma to cache!\n"); @@ -479,32 +481,32 @@ static void* g_aslr_addr_top = NULL; int init_vma(void) { struct shim_vma init_vmas[] = { - { .begin = 0 }, // vma for creation of memory manager + {.begin = 0}, // vma for creation of memory manager { - .begin = (uintptr_t)&__load_address, - .end = (uintptr_t)ALLOC_ALIGN_UP_PTR(&__load_address_end), - .prot = PROT_NONE, - .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL, - .file = NULL, - .offset = 0, + .begin = (uintptr_t)&__load_address, + .end = (uintptr_t)ALLOC_ALIGN_UP_PTR(&__load_address_end), + .prot = PROT_NONE, + .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL, + .file = NULL, + .offset = 0, .comment = "LibOS", }, { - .begin = (uintptr_t)ALLOC_ALIGN_DOWN_PTR(PAL_CB(manifest_preload.start)), - .end = (uintptr_t)ALLOC_ALIGN_UP_PTR(PAL_CB(manifest_preload.end)), - .prot = PROT_NONE, - .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL, - .file = NULL, - .offset = 0, + .begin = (uintptr_t)ALLOC_ALIGN_DOWN_PTR(PAL_CB(manifest_preload.start)), + .end = (uintptr_t)ALLOC_ALIGN_UP_PTR(PAL_CB(manifest_preload.end)), + .prot = PROT_NONE, + .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL, + .file = NULL, + .offset = 0, .comment = "manifest", }, { - .begin = (uintptr_t)PAL_CB(executable_range.start), - .end = (uintptr_t)PAL_CB(executable_range.end), - .prot = PROT_NONE, - .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_UNMAPPED, - .file = NULL, - .offset = 0, + .begin = (uintptr_t)PAL_CB(executable_range.start), + .end = (uintptr_t)PAL_CB(executable_range.end), + .prot = PROT_NONE, + .flags = MAP_PRIVATE | MAP_ANONYMOUS | VMA_UNMAPPED, + .file = NULL, + .offset = 0, .comment = "exec", }, }; @@ -522,20 +524,18 @@ int init_vma(void) { } if (!IS_ALLOC_ALIGNED(init_vmas[i].begin) || !IS_ALLOC_ALIGNED(init_vmas[i].end)) { debug("Unaligned VMA region: 0x%lx-0x%lx (%s)\n", init_vmas[i].begin, init_vmas[i].end, - init_vmas[i].comment); + init_vmas[i].comment); ret = -EINVAL; break; } ret = _bkeep_initial_vma(&init_vmas[i]); if (ret < 0) { debug("Failed to bookkeep initial VMA region 0x%lx-0x%lx (%s)\n", init_vmas[i].begin, - init_vmas[i].end, - init_vmas[i].comment); + init_vmas[i].end, init_vmas[i].comment); break; } debug("Initial VMA region 0x%lx-0x%lx (%s) bookkeeped\n", init_vmas[i].begin, - init_vmas[i].end, - init_vmas[i].comment); + init_vmas[i].end, init_vmas[i].comment); } spinlock_unlock_signal_on(&vma_tree_lock); /* From now on if we return with an error we might leave a structure local to this function in @@ -618,11 +618,11 @@ int init_vma(void) { static void _add_unmapped_vma(uintptr_t begin, uintptr_t end, struct shim_vma* vma) { assert(spinlock_is_locked(&vma_tree_lock)); - vma->begin = begin; - vma->end = end; - vma->prot = PROT_NONE; - vma->flags = VMA_INTERNAL | VMA_UNMAPPED; - vma->file = NULL; + vma->begin = begin; + vma->end = end; + vma->prot = PROT_NONE; + vma->flags = VMA_INTERNAL | VMA_UNMAPPED; + vma->file = NULL; vma->offset = 0; copy_comment(vma, ""); @@ -684,8 +684,8 @@ static bool is_file_prot_matching(struct shim_handle* file_hdl, int prot) { return !(prot & PROT_WRITE) || (file_hdl->flags & O_RDWR); } -int bkeep_mmap_fixed(void* addr, size_t length, int prot, int flags, - struct shim_handle* file, off_t offset, const char* comment) { +int bkeep_mmap_fixed(void* addr, size_t length, int prot, int flags, struct shim_handle* file, + off_t offset, const char* comment) { assert(flags & (MAP_FIXED | MAP_FIXED_NOREPLACE)); if (!length || !IS_ALLOC_ALIGNED(length) || !IS_ALLOC_ALIGNED_PTR(addr)) { @@ -700,10 +700,10 @@ int bkeep_mmap_fixed(void* addr, size_t length, int prot, int flags, struct shim_vma* vma1 = alloc_vma(); new_vma->begin = (uintptr_t)addr; - new_vma->end = new_vma->begin + length; - new_vma->prot = prot; + new_vma->end = new_vma->begin + length; + new_vma->prot = prot; new_vma->flags = filter_saved_flags(flags) | ((file && (prot & PROT_WRITE)) ? VMA_TAINTED : 0); - new_vma->file = file; + new_vma->file = file; if (new_vma->file) { get_handle(new_vma->file); } @@ -747,8 +747,7 @@ static void vma_update_prot(struct shim_vma* vma, int prot) { } static int _vma_bkeep_change(uintptr_t begin, uintptr_t end, int prot, bool is_internal, - struct shim_vma** new_vma_ptr1, - struct shim_vma** new_vma_ptr2) { + struct shim_vma** new_vma_ptr1, struct shim_vma** new_vma_ptr2) { assert(spinlock_is_locked(&vma_tree_lock)); assert(IS_ALLOC_ALIGNED_PTR(begin) && IS_ALLOC_ALIGNED_PTR(end)); assert(begin < end); @@ -878,8 +877,8 @@ int bkeep_mprotect(void* addr, size_t length, int prot, bool is_internal) { } spinlock_lock_signal_off(&vma_tree_lock); - int ret = _vma_bkeep_change((uintptr_t)addr, (uintptr_t)addr + length, prot, is_internal, - &vma1, &vma2); + int ret = _vma_bkeep_change((uintptr_t)addr, (uintptr_t)addr + length, prot, is_internal, &vma1, + &vma2); spinlock_unlock_signal_on(&vma_tree_lock); if (vma1) { @@ -912,7 +911,7 @@ int bkeep_mmap_any_in_range(void* _bottom_addr, void* _top_addr, size_t length, return -EINVAL; } - uintptr_t top_addr = (uintptr_t)_top_addr; + uintptr_t top_addr = (uintptr_t)_top_addr; uintptr_t bottom_addr = (uintptr_t)_bottom_addr; int ret = 0; uintptr_t ret_val = 0; @@ -931,9 +930,9 @@ int bkeep_mmap_any_in_range(void* _bottom_addr, void* _top_addr, size_t length, if (!new_vma) { return -ENOMEM; } - new_vma->prot = prot; + new_vma->prot = prot; new_vma->flags = filter_saved_flags(flags) | ((file && (prot & PROT_WRITE)) ? VMA_TAINTED : 0); - new_vma->file = file; + new_vma->file = file; if (new_vma->file) { get_handle(new_vma->file); } @@ -969,7 +968,7 @@ int bkeep_mmap_any_in_range(void* _bottom_addr, void* _top_addr, size_t length, } out_found: - new_vma->end = max_addr; + new_vma->end = max_addr; new_vma->begin = new_vma->end - length; avl_tree_insert(&vma_tree, &new_vma->tree_node); @@ -1007,12 +1006,12 @@ int bkeep_mmap_any_aslr(size_t length, int prot, int flags, struct shim_handle* } static void dump_vma(struct shim_vma_info* vma_info, struct shim_vma* vma) { - vma_info->addr = (void*)vma->begin; - vma_info->length = vma->end - vma->begin; - vma_info->prot = vma->prot; - vma_info->flags = vma->flags; + vma_info->addr = (void*)vma->begin; + vma_info->length = vma->end - vma->begin; + vma_info->prot = vma->prot; + vma_info->flags = vma->flags; vma_info->file_offset = vma->offset; - vma_info->file = vma->file; + vma_info->file = vma->file; if (vma_info->file) { get_handle(vma_info->file); } @@ -1118,12 +1117,11 @@ void free_vma_info_array(struct shim_vma_info* vma_infos, size_t count) { free(vma_infos); } -BEGIN_CP_FUNC(vma) -{ +BEGIN_CP_FUNC(vma) { __UNUSED(size); assert(size == sizeof(struct shim_vma_info)); - struct shim_vma_info* vma = (struct shim_vma_info*) obj; + struct shim_vma_info* vma = (struct shim_vma_info*)obj; struct shim_vma_info* new_vma = NULL; size_t off = GET_FROM_CP_MAP(obj); @@ -1132,13 +1130,13 @@ BEGIN_CP_FUNC(vma) off = ADD_CP_OFFSET(sizeof(*vma)); ADD_TO_CP_MAP(obj, off); - new_vma = (struct shim_vma_info*) (base + off); + new_vma = (struct shim_vma_info*)(base + off); memcpy(new_vma, vma, sizeof(*vma)); if (vma->file) DO_CP(handle, vma->file, &new_vma->file); - void * need_mapped = vma->addr; + void* need_mapped = vma->addr; /* Check whether we need to checkpoint memory this vma bookkeeps. */ if ((vma->flags & VMA_TAINTED || !vma->file) && !(vma->flags & VMA_UNMAPPED)) { @@ -1161,15 +1159,13 @@ BEGIN_CP_FUNC(vma) * forking. Has to be included in process migration. */ off_t file_len = get_file_size(vma->file); - if (file_len >= 0 && - (off_t)(vma->file_offset + vma->length) > file_len) { - send_size = file_len > vma->file_offset ? - file_len - vma->file_offset : 0; + if (file_len >= 0 && (off_t)(vma->file_offset + vma->length) > file_len) { + send_size = file_len > vma->file_offset ? file_len - vma->file_offset : 0; send_size = ALLOC_ALIGN_UP(send_size); } } if (send_size > 0) { - struct shim_mem_entry * mem; + struct shim_mem_entry* mem; DO_CP_SIZE(memory, send_addr, send_size, &mem); mem->prot = LINUX_PROT_TO_PAL(vma->prot, /*map_flags=*/0); @@ -1179,31 +1175,30 @@ BEGIN_CP_FUNC(vma) ADD_CP_FUNC_ENTRY(off); ADD_CP_ENTRY(ADDR, need_mapped); } else { - new_vma = (struct shim_vma_info*) (base + off); + new_vma = (struct shim_vma_info*)(base + off); } if (objp) - *objp = (void *) new_vma; + *objp = (void*)new_vma; } END_CP_FUNC(vma) -BEGIN_RS_FUNC(vma) -{ - struct shim_vma_info* vma = (void *) (base + GET_CP_FUNC_ENTRY()); - void * need_mapped = (void *) GET_CP_ENTRY(ADDR); +BEGIN_RS_FUNC(vma) { + struct shim_vma_info* vma = (void*)(base + GET_CP_FUNC_ENTRY()); + void* need_mapped = (void*)GET_CP_ENTRY(ADDR); CP_REBASE(vma->file); - DEBUG_RS("vma: %p-%p flags 0x%x prot 0x%08x comment \"%s\"\n", - vma->addr, vma->addr + vma->length, vma->flags, vma->prot, vma->comment); + DEBUG_RS("vma: %p-%p flags 0x%x prot 0x%08x comment \"%s\"\n", vma->addr, + vma->addr + vma->length, vma->flags, vma->prot, vma->comment); - int ret = bkeep_mmap_fixed(vma->addr, vma->length, vma->prot, vma->flags | MAP_FIXED, - vma->file, vma->file_offset, vma->comment); + int ret = bkeep_mmap_fixed(vma->addr, vma->length, vma->prot, vma->flags | MAP_FIXED, vma->file, + vma->file_offset, vma->comment); if (ret < 0) return ret; if (!(vma->flags & VMA_UNMAPPED)) { if (vma->file) { - struct shim_mount * fs = vma->file->fs; + struct shim_mount* fs = vma->file->fs; get_handle(vma->file); if (need_mapped < vma->addr + vma->length) { @@ -1212,14 +1207,10 @@ BEGIN_RS_FUNC(vma) return -EINVAL; } - void * addr = need_mapped; - int ret = fs->fs_ops->mmap(vma->file, &addr, - vma->addr + vma->length - - need_mapped, - vma->prot, - vma->flags | MAP_FIXED, - vma->file_offset + - (need_mapped - vma->addr)); + void* addr = need_mapped; + int ret = fs->fs_ops->mmap(vma->file, &addr, vma->addr + vma->length - need_mapped, + vma->prot, vma->flags | MAP_FIXED, + vma->file_offset + (need_mapped - vma->addr)); if (ret < 0) return ret; @@ -1241,24 +1232,20 @@ BEGIN_RS_FUNC(vma) } if (need_mapped < vma->addr + vma->length) - SYS_PRINTF("vma %p-%p cannot be allocated!\n", need_mapped, - vma->addr + vma->length); + SYS_PRINTF("vma %p-%p cannot be allocated!\n", need_mapped, vma->addr + vma->length); } if (vma->file) - DEBUG_RS("%p-%p,size=%ld,prot=%08x,flags=%08x,off=%ld,path=%s,uri=%s", - vma->addr, vma->addr + vma->length, vma->length, - vma->prot, vma->flags, vma->file_offset, + DEBUG_RS("%p-%p,size=%ld,prot=%08x,flags=%08x,off=%ld,path=%s,uri=%s", vma->addr, + vma->addr + vma->length, vma->length, vma->prot, vma->flags, vma->file_offset, qstrgetstr(&vma->file->path), qstrgetstr(&vma->file->uri)); else - DEBUG_RS("%p-%p,size=%ld,prot=%08x,flags=%08x,off=%ld", - vma->addr, vma->addr + vma->length, vma->length, - vma->prot, vma->flags, vma->file_offset); + DEBUG_RS("%p-%p,size=%ld,prot=%08x,flags=%08x,off=%ld", vma->addr, vma->addr + vma->length, + vma->length, vma->prot, vma->flags, vma->file_offset); } END_RS_FUNC(vma) -BEGIN_CP_FUNC(all_vmas) -{ +BEGIN_CP_FUNC(all_vmas) { __UNUSED(obj); __UNUSED(size); __UNUSED(objp); diff --git a/LibOS/shim/src/elf/do-rel.h b/LibOS/shim/src/elf/do-rel.h index 910d78a10a..bfdf2ab569 100644 --- a/LibOS/shim/src/elf/do-rel.h +++ b/LibOS/shim/src/elf/do-rel.h @@ -2,11 +2,8 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * do-rel.c - * - * This file contains architecture-independent codes for relocating ELF - * binaries. - * Most of the source codes are imported from GNU C library. + * This file contains architecture-independent code for relocating ELF binaries. Most of the source + * code was imported from GNU C library. */ #include "shim_dl-machine.h" diff --git a/LibOS/shim/src/elf/shim_rtld.c b/LibOS/shim/src/elf/shim_rtld.c index 103490ef38..ae26022bfc 100644 --- a/LibOS/shim/src/elf/shim_rtld.c +++ b/LibOS/shim/src/elf/shim_rtld.c @@ -2,15 +2,14 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_rtld.c - * - * This file contains codes for dynamic loading of ELF binaries in library OS. + * This file contains code for dynamic loading of ELF binaries in library OS. * It's espeically used for loading interpreter (ld.so, in general) and * optimization of execve. - * Most of the source codes are imported from GNU C library. + * Most of the source code was imported from GNU C library. */ #include +#include #include #include "elf.h" @@ -259,7 +258,6 @@ static struct link_map* new_elf_object(const char* realname, int type) { return new; } -#include #if __BYTE_ORDER == __BIG_ENDIAN #define byteorder ELFDATA2MSB #elif __BYTE_ORDER == __LITTLE_ENDIAN @@ -1057,18 +1055,19 @@ static unsigned long int elf_hash(const char* name_arg) { } /* Check whether the symbol matches. */ -static ElfW(Sym)* check_match(ElfW(Sym)* sym, ElfW(Sym)* ref, const char* strtab, const char *undef_name, int len) { +static ElfW(Sym)* check_match(ElfW(Sym)* sym, ElfW(Sym)* ref, const char* strtab, + const char* undef_name, int len) { unsigned int stt = ELFW(ST_TYPE)(sym->st_info); if ((sym->st_value == 0 /* No value */ && stt != STT_TLS) || sym->st_shndx == SHN_UNDEF) return NULL; -/* Ignore all but STT_NOTYPE, STT_OBJECT, STT_FUNC, - STT_COMMON, STT_TLS, and STT_GNU_IFUNC since these are no - code/data definitions. */ -#define ALLOWED_STT \ - ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) | (1 << STT_COMMON) | \ - (1 << STT_TLS) | (1 << STT_GNU_IFUNC)) + /* Ignore all but STT_NOTYPE, STT_OBJECT, STT_FUNC, + STT_COMMON, STT_TLS, and STT_GNU_IFUNC since these are no + code/data definitions. */ + #define ALLOWED_STT \ + ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) | (1 << STT_COMMON) | \ + (1 << STT_TLS) | (1 << STT_GNU_IFUNC)) if (((1 << stt) & ALLOWED_STT) == 0) return NULL; @@ -1272,7 +1271,7 @@ static int __load_interp_object(struct link_map* exec_map) { debug("search interpreter: %s\n", interp_path); struct shim_dentry* dent = NULL; - int ret = 0; + int ret = 0; if ((ret = path_lookupat(NULL, interp_path, LOOKUP_OPEN, &dent, NULL)) < 0 || dent->state & DENTRY_NEGATIVE) @@ -1450,7 +1449,7 @@ int init_internal_map(void) { int init_loader(void) { struct shim_thread* cur_thread = get_cur_thread(); - int ret = 0; + int ret = 0; lock(&cur_thread->lock); struct shim_handle* exec = cur_thread->exec; @@ -1577,7 +1576,7 @@ noreturn void execute_elf_object(struct shim_handle* exec, void* argp, ElfW(auxv ElfW(Addr) auxp_extra = (ElfW(Addr))&auxp[8]; ElfW(Addr) random = auxp_extra; /* random 16B for AT_RANDOM */ - ret = DkRandomBitsRead((PAL_PTR)random, 16); + ret = DkRandomBitsRead((PAL_PTR)random, 16); if (ret < 0) { debug("execute_elf_object: DkRandomBitsRead failed.\n"); DkThreadExit(/*clear_child_tid=*/NULL); diff --git a/LibOS/shim/src/fs/chroot/fs.c b/LibOS/shim/src/fs/chroot/fs.c index 010b85e338..bcc1400e52 100644 --- a/LibOS/shim/src/fs/chroot/fs.c +++ b/LibOS/shim/src/fs/chroot/fs.c @@ -2,9 +2,7 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * fs.c - * - * This file contains codes for implementation of 'chroot' filesystem. + * This file contains code for implementation of 'chroot' filesystem. */ // FIXME: Sorting these includes causes a bunch of "error: ‘S_IFREG’ undeclared" errors. @@ -25,31 +23,32 @@ #include #include -#define URI_MAX_SIZE STR_SIZE +#define URI_MAX_SIZE STR_SIZE #define FILE_BUFMAP_SIZE (PAL_CB(alloc_align) * 4) -#define FILE_BUF_SIZE (PAL_CB(alloc_align)) +#define FILE_BUF_SIZE (PAL_CB(alloc_align)) struct mount_data { - size_t data_size; + size_t data_size; enum shim_file_type base_type; - unsigned long ino_base; - size_t root_uri_len; - char root_uri[]; + unsigned long ino_base; + size_t root_uri_len; + char root_uri[]; }; #define HANDLE_MOUNT_DATA(h) ((struct mount_data*)(h)->fs->data) #define DENTRY_MOUNT_DATA(d) ((struct mount_data*)(d)->fs->data) -static int chroot_mount (const char * uri, void ** mount_data) -{ +static int chroot_mount(const char* uri, void** mount_data) { enum shim_file_type type; if (strstartswith_static(uri, URI_PREFIX_FILE)) { type = FILE_UNKNOWN; uri += 5; } else if (strstartswith_static(uri, URI_PREFIX_DEV)) { - type = strstartswith_static(uri + static_strlen(URI_PREFIX_DEV), "tty") ? FILE_TTY : FILE_DEV; + type = strstartswith_static(uri + static_strlen(URI_PREFIX_DEV), "tty") + ? FILE_TTY + : FILE_DEV; uri += 4; } else { return -EINVAL; @@ -61,11 +60,11 @@ static int chroot_mount (const char * uri, void ** mount_data) int uri_len = strlen(uri); int data_size = uri_len + 1 + sizeof(struct mount_data); - struct mount_data * mdata = (struct mount_data *) malloc(data_size); + struct mount_data* mdata = (struct mount_data*)malloc(data_size); - mdata->data_size = data_size; - mdata->base_type = type; - mdata->ino_base = hash_path(uri, uri_len); + mdata->data_size = data_size; + mdata->base_type = type; + mdata->ino_base = hash_path(uri, uri_len); mdata->root_uri_len = uri_len; memcpy(mdata->root_uri, uri, uri_len + 1); @@ -73,17 +72,14 @@ static int chroot_mount (const char * uri, void ** mount_data) return 0; } -static int chroot_unmount (void * mount_data) -{ +static int chroot_unmount(void* mount_data) { free(mount_data); return 0; } -static inline ssize_t concat_uri (char * buffer, size_t size, int type, - const char * root, size_t root_len, - const char * trim, size_t trim_len) -{ - char * tmp = NULL; +static inline ssize_t concat_uri(char* buffer, size_t size, int type, const char* root, + size_t root_len, const char* trim, size_t trim_len) { + char* tmp = NULL; switch (type) { case FILE_UNKNOWN: @@ -135,25 +131,20 @@ static struct shim_file_data* __create_data(void) { return data; } -static void __destroy_data (struct shim_file_data * data) -{ +static void __destroy_data(struct shim_file_data* data) { qstrfree(&data->host_uri); destroy_lock(&data->lock); free(data); } -static ssize_t make_uri (struct shim_dentry * dent) -{ - struct mount_data * mdata = DENTRY_MOUNT_DATA(dent); +static ssize_t make_uri(struct shim_dentry* dent) { + struct mount_data* mdata = DENTRY_MOUNT_DATA(dent); assert(mdata); - struct shim_file_data * data = FILE_DENTRY_DATA(dent); + struct shim_file_data* data = FILE_DENTRY_DATA(dent); char uri[URI_MAX_SIZE]; - ssize_t len = concat_uri(uri, URI_MAX_SIZE, data->type, - mdata->root_uri, - mdata->root_uri_len, - qstrgetstr(&dent->rel_path), - dent->rel_path.len); + ssize_t len = concat_uri(uri, URI_MAX_SIZE, data->type, mdata->root_uri, mdata->root_uri_len, + qstrgetstr(&dent->rel_path), dent->rel_path.len); if (len >= 0) qstrsetstr(&data->host_uri, uri, len); @@ -162,23 +153,21 @@ static ssize_t make_uri (struct shim_dentry * dent) /* create a data in the dentry and compose it's uri. dent->lock needs to be held */ -static int create_data (struct shim_dentry * dent, const char * uri, size_t len) -{ +static int create_data(struct shim_dentry* dent, const char* uri, size_t len) { assert(locked(&dent->lock)); if (dent->data) return 0; - struct shim_file_data * data = __create_data(); + struct shim_file_data* data = __create_data(); if (!data) return -ENOMEM; dent->data = data; - struct mount_data * mdata = DENTRY_MOUNT_DATA(dent); + struct mount_data* mdata = DENTRY_MOUNT_DATA(dent); assert(mdata); - data->type = (dent->state & DENTRY_ISDIRECTORY) ? - FILE_DIR : mdata->base_type; + data->type = (dent->state & DENTRY_ISDIRECTORY) ? FILE_DIR : mdata->base_type; data->mode = NO_MODE; if (uri) { @@ -193,26 +182,35 @@ static int create_data (struct shim_dentry * dent, const char * uri, size_t len) return 0; } -static int chroot_readdir (struct shim_dentry * dent, - struct shim_dirent ** dirent); +static int chroot_readdir(struct shim_dentry* dent, struct shim_dirent** dirent); -static int __query_attr (struct shim_dentry * dent, - struct shim_file_data * data, PAL_HANDLE pal_handle) -{ +static int __query_attr(struct shim_dentry* dent, struct shim_file_data* data, + PAL_HANDLE pal_handle) { PAL_STREAM_ATTR pal_attr; enum shim_file_type old_type = data->type; - if (pal_handle ? - !DkStreamAttributesQueryByHandle(pal_handle, &pal_attr) : - !DkStreamAttributesQuery(qstrgetstr(&data->host_uri), &pal_attr)) + if (pal_handle ? !DkStreamAttributesQueryByHandle(pal_handle, &pal_attr) + : !DkStreamAttributesQuery(qstrgetstr(&data->host_uri), &pal_attr)) return -PAL_ERRNO(); /* need to correct the data type */ if (data->type == FILE_UNKNOWN) switch (pal_attr.handle_type) { - case pal_type_file: data->type = FILE_REGULAR; if (dent) dent->type = S_IFREG; break; - case pal_type_dir: data->type = FILE_DIR; if (dent) dent->type = S_IFDIR; break; - case pal_type_dev: data->type = FILE_DEV; if (dent) dent->type = S_IFCHR; break; + case pal_type_file: + data->type = FILE_REGULAR; + if (dent) + dent->type = S_IFREG; + break; + case pal_type_dir: + data->type = FILE_DIR; + if (dent) + dent->type = S_IFDIR; + break; + case pal_type_dev: + data->type = FILE_DEV; + if (dent) + dent->type = S_IFCHR; + break; } data->mode = (pal_attr.readable ? S_IRUSR : 0) | @@ -262,27 +260,23 @@ static int __query_attr (struct shim_dentry * dent, } /* do not need any lock */ -static void chroot_update_ino (struct shim_dentry * dent) -{ +static void chroot_update_ino(struct shim_dentry* dent) { if (dent->state & DENTRY_INO_UPDATED) return; - struct mount_data * mdata = DENTRY_MOUNT_DATA(dent); + struct mount_data* mdata = DENTRY_MOUNT_DATA(dent); unsigned long ino = mdata->ino_base; if (!qstrempty(&dent->rel_path)) - ino = rehash_path(mdata->ino_base, qstrgetstr(&dent->rel_path), - dent->rel_path.len); + ino = rehash_path(mdata->ino_base, qstrgetstr(&dent->rel_path), dent->rel_path.len); dent->ino = ino; dent->state |= DENTRY_INO_UPDATED; } -static inline int try_create_data (struct shim_dentry * dent, - const char * uri, size_t len, - struct shim_file_data ** dataptr) -{ - struct shim_file_data * data = FILE_DENTRY_DATA(dent); +static inline int try_create_data(struct shim_dentry* dent, const char* uri, size_t len, + struct shim_file_data** dataptr) { + struct shim_file_data* data = FILE_DENTRY_DATA(dent); if (!data) { lock(&dent->lock); @@ -298,12 +292,11 @@ static inline int try_create_data (struct shim_dentry * dent, return 0; } -static int query_dentry (struct shim_dentry * dent, PAL_HANDLE pal_handle, - mode_t * mode, struct stat * stat) -{ +static int query_dentry(struct shim_dentry* dent, PAL_HANDLE pal_handle, mode_t* mode, + struct stat* stat) { int ret = 0; - struct shim_file_data * data; + struct shim_file_data* data; if ((ret = try_create_data(dent, NULL, 0, &data)) < 0) return ret; @@ -318,19 +311,19 @@ static int query_dentry (struct shim_dentry * dent, PAL_HANDLE pal_handle, *mode = data->mode; if (stat) { - struct mount_data * mdata = DENTRY_MOUNT_DATA(dent); + struct mount_data* mdata = DENTRY_MOUNT_DATA(dent); chroot_update_ino(dent); memset(stat, 0, sizeof(struct stat)); - stat->st_mode = (mode_t) data->mode; - stat->st_dev = (dev_t) mdata->ino_base; - stat->st_ino = (ino_t) dent->ino; - stat->st_size = (off_t) __atomic_load_n(&data->size.counter, __ATOMIC_SEQ_CST); - stat->st_atime = (time_t) data->atime; - stat->st_mtime = (time_t) data->mtime; - stat->st_ctime = (time_t) data->ctime; - stat->st_nlink = data->nlink; + stat->st_mode = (mode_t)data->mode; + stat->st_dev = (dev_t)mdata->ino_base; + stat->st_ino = (ino_t)dent->ino; + stat->st_size = (off_t)__atomic_load_n(&data->size.counter, __ATOMIC_SEQ_CST); + stat->st_atime = (time_t)data->atime; + stat->st_mtime = (time_t)data->mtime; + stat->st_ctime = (time_t)data->ctime; + stat->st_nlink = data->nlink; switch (data->type) { case FILE_REGULAR: @@ -343,7 +336,8 @@ static int query_dentry (struct shim_dentry * dent, PAL_HANDLE pal_handle, case FILE_TTY: stat->st_mode |= S_IFCHR; break; - default: break; + default: + break; } } @@ -351,19 +345,15 @@ static int query_dentry (struct shim_dentry * dent, PAL_HANDLE pal_handle, return 0; } -static int chroot_mode (struct shim_dentry * dent, mode_t * mode) -{ +static int chroot_mode(struct shim_dentry* dent, mode_t* mode) { return query_dentry(dent, NULL, mode, NULL); } -static int chroot_stat (struct shim_dentry * dent, struct stat * statbuf) -{ +static int chroot_stat(struct shim_dentry* dent, struct stat* statbuf) { return query_dentry(dent, NULL, NULL, statbuf); } -static int chroot_lookup (struct shim_dentry * dent) -{ - +static int chroot_lookup(struct shim_dentry* dent) { return query_dentry(dent, NULL, NULL, NULL); } @@ -441,48 +431,46 @@ static int chroot_open(struct shim_handle* hdl, struct shim_dentry* dent, int fl if ((ret = __chroot_open(dent, NULL, flags, dent->mode, hdl, data)) < 0) return ret; - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; off_t size = __atomic_load_n(&data->size.counter, __ATOMIC_SEQ_CST); /* initialize hdl, does not need a lock because no one is sharing */ - hdl->type = TYPE_FILE; - file->marker = (flags & O_APPEND) ? size : 0; - file->size = size; - hdl->flags = flags; - hdl->acc_mode = ACC_MODE(flags & O_ACCMODE); + hdl->type = TYPE_FILE; + hdl->flags = flags; + hdl->acc_mode = ACC_MODE(flags & O_ACCMODE); + file->marker = (flags & O_APPEND) ? size : 0; + file->size = size; qstrcopy(&hdl->uri, &data->host_uri); return 0; } -static int chroot_creat (struct shim_handle * hdl, struct shim_dentry * dir, - struct shim_dentry * dent, int flags, mode_t mode) -{ +static int chroot_creat(struct shim_handle* hdl, struct shim_dentry* dir, struct shim_dentry* dent, + int flags, mode_t mode) { int ret = 0; - struct shim_file_data * data; + struct shim_file_data* data; if ((ret = try_create_data(dent, NULL, 0, &data)) < 0) return ret; - if ((ret = __chroot_open(dent, NULL, flags|O_CREAT|O_EXCL, mode, hdl, - data)) < 0) + if ((ret = __chroot_open(dent, NULL, flags | O_CREAT | O_EXCL, mode, hdl, data)) < 0) return ret; if (!hdl) return 0; - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; off_t size = __atomic_load_n(&data->size.counter, __ATOMIC_SEQ_CST); /* initialize hdl, does not need a lock because no one is sharing */ - hdl->type = TYPE_FILE; - file->marker = (flags & O_APPEND) ? size : 0; - file->size = size; - hdl->flags = flags; - hdl->acc_mode = ACC_MODE(flags & O_ACCMODE); + hdl->type = TYPE_FILE; + hdl->flags = flags; + hdl->acc_mode = ACC_MODE(flags & O_ACCMODE); + file->marker = (flags & O_APPEND) ? size : 0; + file->size = size; qstrcopy(&hdl->uri, &data->host_uri); /* Increment the parent's link count */ - struct shim_file_data *parent_data = FILE_DENTRY_DATA(dir); + struct shim_file_data* parent_data = FILE_DENTRY_DATA(dir); if (parent_data) { lock(&parent_data->lock); if (parent_data->queried) @@ -492,11 +480,9 @@ static int chroot_creat (struct shim_handle * hdl, struct shim_dentry * dir, return 0; } -static int chroot_mkdir (struct shim_dentry * dir, struct shim_dentry * dent, - mode_t mode) -{ +static int chroot_mkdir(struct shim_dentry* dir, struct shim_dentry* dent, mode_t mode) { int ret = 0; - struct shim_file_data * data; + struct shim_file_data* data; if ((ret = try_create_data(dent, NULL, 0, &data)) < 0) return ret; @@ -510,7 +496,7 @@ static int chroot_mkdir (struct shim_dentry * dir, struct shim_dentry * dent, ret = __chroot_open(dent, NULL, O_CREAT | O_EXCL, mode, NULL, data); /* Increment the parent's link count */ - struct shim_file_data *parent_data = FILE_DENTRY_DATA(dir); + struct shim_file_data* parent_data = FILE_DENTRY_DATA(dir); if (parent_data) { lock(&parent_data->lock); if (parent_data->queried) @@ -520,18 +506,17 @@ static int chroot_mkdir (struct shim_dentry * dir, struct shim_dentry * dent, return ret; } -#define NEED_RECREATE(hdl) (!FILE_HANDLE_DATA(hdl)) +#define NEED_RECREATE(hdl) (!FILE_HANDLE_DATA(hdl)) -static int chroot_recreate (struct shim_handle * hdl) -{ - struct shim_file_data * data = FILE_HANDLE_DATA(hdl); +static int chroot_recreate(struct shim_handle* hdl) { + struct shim_file_data* data = FILE_HANDLE_DATA(hdl); int ret = 0; /* quickly bail out if the data is created */ if (data) return 0; - const char * uri = qstrgetstr(&hdl->uri); + const char* uri = qstrgetstr(&hdl->uri); size_t len = hdl->uri.len; if (hdl->dentry) { @@ -548,12 +533,10 @@ static int chroot_recreate (struct shim_handle * hdl) * when recreating a file handle after migration, the file should * not be created again. */ - return __chroot_open(hdl->dentry, uri, hdl->flags & ~(O_CREAT|O_EXCL), - 0, hdl, data); + return __chroot_open(hdl->dentry, uri, hdl->flags & ~(O_CREAT | O_EXCL), 0, hdl, data); } -static inline bool check_version (struct shim_handle * hdl) -{ +static inline bool check_version(struct shim_handle* hdl) { return __atomic_load_n(&FILE_HANDLE_DATA(hdl)->version.counter, __ATOMIC_SEQ_CST) == hdl->info.file.version; } @@ -572,24 +555,23 @@ static void chroot_update_size(struct shim_handle* hdl, struct shim_file_handle* } } -static int chroot_hstat (struct shim_handle * hdl, struct stat * stat) -{ +static int chroot_hstat(struct shim_handle* hdl, struct stat* stat) { int ret; if (NEED_RECREATE(hdl) && (ret = chroot_recreate(hdl)) < 0) return ret; if (!check_version(hdl) || !hdl->dentry) { - struct shim_file_handle * file = &hdl->info.file; - struct shim_dentry * dent = hdl->dentry; - struct mount_data * mdata = dent ? DENTRY_MOUNT_DATA(dent) : NULL; + struct shim_file_handle* file = &hdl->info.file; + struct shim_dentry* dent = hdl->dentry; + struct mount_data* mdata = dent ? DENTRY_MOUNT_DATA(dent) : NULL; if (dent) chroot_update_ino(dent); if (stat) { memset(stat, 0, sizeof(struct stat)); - stat->st_dev = mdata ? (dev_t) mdata->ino_base : 0; - stat->st_ino = dent ? (ino_t) dent->ino : 0; + stat->st_dev = mdata ? (dev_t)mdata->ino_base : 0; + stat->st_ino = dent ? (ino_t)dent->ino : 0; stat->st_size = file->size; stat->st_mode |= (file->type == FILE_REGULAR) ? S_IFREG : S_IFCHR; } @@ -612,8 +594,7 @@ static int chroot_close(struct shim_handle* hdl) { return 0; } -static ssize_t chroot_read (struct shim_handle * hdl, void * buf, size_t count) -{ +static ssize_t chroot_read(struct shim_handle* hdl, void* buf, size_t count) { ssize_t ret = 0; if (count == 0) @@ -628,7 +609,7 @@ static ssize_t chroot_read (struct shim_handle * hdl, void * buf, size_t count) goto out; } - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; off_t dummy_off_t; if (file->type != FILE_TTY && __builtin_add_overflow(file->marker, count, &dummy_off_t)) { @@ -645,7 +626,7 @@ static ssize_t chroot_read (struct shim_handle * hdl, void * buf, size_t count) if (file->type != FILE_TTY && __builtin_add_overflow(file->marker, pal_ret, &file->marker)) BUG(); } else { - ret = PAL_NATIVE_ERRNO() == PAL_ERROR_ENDOFSTREAM ? 0 : -PAL_ERRNO(); + ret = PAL_NATIVE_ERRNO() == PAL_ERROR_ENDOFSTREAM ? 0 : -PAL_ERRNO(); } unlock(&hdl->lock); @@ -653,8 +634,7 @@ static ssize_t chroot_read (struct shim_handle * hdl, void * buf, size_t count) return ret; } -static ssize_t chroot_write (struct shim_handle * hdl, const void * buf, size_t count) -{ +static ssize_t chroot_write(struct shim_handle* hdl, const void* buf, size_t count) { ssize_t ret; if (count == 0) @@ -669,7 +649,7 @@ static ssize_t chroot_write (struct shim_handle * hdl, const void * buf, size_t goto out; } - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; off_t dummy_off_t; if (file->type != FILE_TTY && __builtin_add_overflow(file->marker, count, &dummy_off_t)) { @@ -679,7 +659,7 @@ static ssize_t chroot_write (struct shim_handle * hdl, const void * buf, size_t lock(&hdl->lock); - PAL_NUM pal_ret = DkStreamWrite(hdl->pal_handle, file->marker, count, (void *) buf, NULL); + PAL_NUM pal_ret = DkStreamWrite(hdl->pal_handle, file->marker, count, (void*)buf, NULL); if (pal_ret != PAL_STREAM_ERROR) { if (__builtin_add_overflow(pal_ret, 0, &ret)) BUG(); @@ -690,7 +670,7 @@ static ssize_t chroot_write (struct shim_handle * hdl, const void * buf, size_t chroot_update_size(hdl, file, FILE_HANDLE_DATA(hdl)); } } else { - ret = PAL_NATIVE_ERRNO() == PAL_ERROR_ENDOFSTREAM ? 0 : -PAL_ERRNO(); + ret = PAL_NATIVE_ERRNO() == PAL_ERROR_ENDOFSTREAM ? 0 : -PAL_ERRNO(); } unlock(&hdl->lock); @@ -698,9 +678,8 @@ static ssize_t chroot_write (struct shim_handle * hdl, const void * buf, size_t return ret; } -static int chroot_mmap (struct shim_handle * hdl, void ** addr, size_t size, - int prot, int flags, off_t offset) -{ +static int chroot_mmap(struct shim_handle* hdl, void** addr, size_t size, int prot, int flags, + off_t offset) { int ret; if (NEED_RECREATE(hdl) && (ret = chroot_recreate(hdl)) < 0) return ret; @@ -714,8 +693,7 @@ static int chroot_mmap (struct shim_handle * hdl, void ** addr, size_t size, #endif return -EINVAL; - void * alloc_addr = - (void *) DkStreamMap(hdl->pal_handle, *addr, pal_prot, offset, size); + void* alloc_addr = (void*)DkStreamMap(hdl->pal_handle, *addr, pal_prot, offset, size); if (!alloc_addr) return -PAL_ERRNO(); @@ -724,21 +702,20 @@ static int chroot_mmap (struct shim_handle * hdl, void ** addr, size_t size, return 0; } -static off_t chroot_seek (struct shim_handle * hdl, off_t offset, int wence) -{ +static off_t chroot_seek(struct shim_handle* hdl, off_t offset, int wence) { off_t ret = -EINVAL; if (NEED_RECREATE(hdl) && (ret = chroot_recreate(hdl)) < 0) return ret; - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; lock(&hdl->lock); off_t marker = file->marker; off_t size = file->size; if (check_version(hdl)) { - struct shim_file_data * data = FILE_HANDLE_DATA(hdl); + struct shim_file_data* data = FILE_HANDLE_DATA(hdl); if (data->type != FILE_REGULAR) { ret = -ESPIPE; goto out; @@ -768,8 +745,7 @@ static off_t chroot_seek (struct shim_handle * hdl, off_t offset, int wence) return ret; } -static int chroot_truncate (struct shim_handle * hdl, off_t len) -{ +static int chroot_truncate(struct shim_handle* hdl, off_t len) { int ret = 0; if (NEED_RECREATE(hdl) && (ret = chroot_recreate(hdl)) < 0) @@ -778,7 +754,7 @@ static int chroot_truncate (struct shim_handle * hdl, off_t len) if (!(hdl->acc_mode & MAY_WRITE)) return -EINVAL; - struct shim_file_handle * file = &hdl->info.file; + struct shim_file_handle* file = &hdl->info.file; lock(&hdl->lock); file->size = len; @@ -806,9 +782,8 @@ static int chroot_truncate (struct shim_handle * hdl, off_t len) return ret; } -static int chroot_dput (struct shim_dentry * dent) -{ - struct shim_file_data * data = FILE_DENTRY_DATA(dent); +static int chroot_dput(struct shim_dentry* dent) { + struct shim_file_data* data = FILE_DENTRY_DATA(dent); if (data) { __destroy_data(data); @@ -822,8 +797,8 @@ static int chroot_readdir(struct shim_dentry* dent, struct shim_dirent** dirent) struct shim_file_data* data = NULL; int ret = 0; PAL_HANDLE pal_hdl = NULL; - size_t buf_size = MAX_PATH, - dirent_buf_size = 0; + size_t buf_size = MAX_PATH; + size_t dirent_buf_size = 0; char* buf = NULL; char* dirent_buf = NULL; @@ -910,7 +885,7 @@ static int chroot_readdir(struct shim_dentry* dent, struct shim_dirent** dirent) } struct shim_dirent* dptr = (struct shim_dirent*)(dirent_buf + dirent_cur_off); - dptr->ino = rehash_name(dent->ino, name, len); + dptr->ino = rehash_name(dent->ino, name, len); dptr->type = is_dir ? LINUX_DT_DIR : LINUX_DT_REG; memcpy(dptr->name, name, len + 1); @@ -928,7 +903,7 @@ static int chroot_readdir(struct shim_dentry* dent, struct shim_dirent** dirent) * rewritten as such one day). */ struct shim_dirent** last = NULL; - for (size_t dirent_cur_off = 0; dirent_cur_off < dirent_buf_size; ) { + for (size_t dirent_cur_off = 0; dirent_cur_off < dirent_buf_size;) { struct shim_dirent* dptr = (struct shim_dirent*)(dirent_buf + dirent_cur_off); size_t len = SHIM_DIRENT_ALIGNED_SIZE(strlen(dptr->name) + 1); dptr->next = (struct shim_dirent*)(dirent_buf + dirent_cur_off + len); @@ -949,13 +924,12 @@ static int chroot_readdir(struct shim_dentry* dent, struct shim_dirent** dirent) return ret; } -static int chroot_checkout (struct shim_handle * hdl) -{ +static int chroot_checkout(struct shim_handle* hdl) { if (hdl->fs == &chroot_builtin_fs) hdl->fs = NULL; if (hdl->type == TYPE_FILE) { - struct shim_file_data * data = FILE_HANDLE_DATA(hdl); + struct shim_file_data* data = FILE_HANDLE_DATA(hdl); if (data) hdl->info.file.data = NULL; } @@ -973,20 +947,18 @@ static int chroot_checkout (struct shim_handle * hdl) return 0; } -static ssize_t chroot_checkpoint (void ** checkpoint, void * mount_data) -{ - struct mount_data * mdata = mount_data; +static ssize_t chroot_checkpoint(void** checkpoint, void* mount_data) { + struct mount_data* mdata = mount_data; *checkpoint = mount_data; return mdata->root_uri_len + sizeof(struct mount_data) + 1; } -static int chroot_migrate (void * checkpoint, void ** mount_data) -{ - struct mount_data * mdata = checkpoint; +static int chroot_migrate(void* checkpoint, void** mount_data) { + struct mount_data* mdata = checkpoint; size_t alloc_len = mdata->root_uri_len + sizeof(struct mount_data) + 1; - void * new_data = malloc(alloc_len); + void* new_data = malloc(alloc_len); if (!new_data) return -ENOMEM; @@ -996,10 +968,9 @@ static int chroot_migrate (void * checkpoint, void ** mount_data) return 0; } -static int chroot_unlink (struct shim_dentry * dir, struct shim_dentry * dent) -{ +static int chroot_unlink(struct shim_dentry* dir, struct shim_dentry* dent) { int ret; - struct shim_file_data * data; + struct shim_file_data* data; if ((ret = try_create_data(dent, NULL, 0, &data)) < 0) return ret; @@ -1017,7 +988,7 @@ static int chroot_unlink (struct shim_dentry * dir, struct shim_dentry * dent) __atomic_store_n(&data->size.counter, 0, __ATOMIC_SEQ_CST); /* Drop the parent's link count */ - struct shim_file_data *parent_data = FILE_DENTRY_DATA(dir); + struct shim_file_data* parent_data = FILE_DENTRY_DATA(dir); if (parent_data) { lock(&parent_data->lock); if (parent_data->queried) @@ -1028,13 +999,12 @@ static int chroot_unlink (struct shim_dentry * dir, struct shim_dentry * dent) return 0; } -static off_t chroot_poll (struct shim_handle * hdl, int poll_type) -{ +static off_t chroot_poll(struct shim_handle* hdl, int poll_type) { int ret; if (NEED_RECREATE(hdl) && (ret = chroot_recreate(hdl)) < 0) return ret; - struct shim_file_data * data = FILE_HANDLE_DATA(hdl); + struct shim_file_data* data = FILE_HANDLE_DATA(hdl); off_t size = __atomic_load_n(&data->size.counter, __ATOMIC_SEQ_CST); if (poll_type == FS_POLL_SZ) @@ -1042,9 +1012,8 @@ static off_t chroot_poll (struct shim_handle * hdl, int poll_type) lock(&hdl->lock); - struct shim_file_handle * file = &hdl->info.file; - if (check_version(hdl) && - file->size < size) + struct shim_file_handle* file = &hdl->info.file; + if (check_version(hdl) && file->size < size) file->size = size; off_t marker = file->marker; @@ -1101,10 +1070,9 @@ static int chroot_rename(struct shim_dentry* old, struct shim_dentry* new) { return 0; } -static int chroot_chmod (struct shim_dentry * dent, mode_t mode) -{ +static int chroot_chmod(struct shim_dentry* dent, mode_t mode) { int ret; - struct shim_file_data * data; + struct shim_file_data* data; if ((ret = try_create_data(dent, NULL, 0, &data)) < 0) return ret; @@ -1112,7 +1080,7 @@ static int chroot_chmod (struct shim_dentry * dent, mode_t mode) if (!pal_hdl) return -PAL_ERRNO(); - PAL_STREAM_ATTR attr = { .share_flags = mode }; + PAL_STREAM_ATTR attr = {.share_flags = mode}; if (!DkStreamAttributesSetByHandle(pal_hdl, &attr)) { DkObjectClose(pal_hdl); @@ -1126,40 +1094,44 @@ static int chroot_chmod (struct shim_dentry * dent, mode_t mode) } struct shim_fs_ops chroot_fs_ops = { - .mount = &chroot_mount, - .unmount = &chroot_unmount, - .flush = &chroot_flush, - .close = &chroot_close, - .read = &chroot_read, - .write = &chroot_write, - .mmap = &chroot_mmap, - .seek = &chroot_seek, - .hstat = &chroot_hstat, - .truncate = &chroot_truncate, - .checkout = &chroot_checkout, - .checkpoint = &chroot_checkpoint, - .migrate = &chroot_migrate, - .poll = &chroot_poll, - }; + .mount = &chroot_mount, + .unmount = &chroot_unmount, + .flush = &chroot_flush, + .close = &chroot_close, + .read = &chroot_read, + .write = &chroot_write, + .mmap = &chroot_mmap, + .seek = &chroot_seek, + .hstat = &chroot_hstat, + .truncate = &chroot_truncate, + .checkout = &chroot_checkout, + .checkpoint = &chroot_checkpoint, + .migrate = &chroot_migrate, + .poll = &chroot_poll, +}; struct shim_d_ops chroot_d_ops = { - .open = &chroot_open, - .mode = &chroot_mode, - .lookup = &chroot_lookup, - .creat = &chroot_creat, - .mkdir = &chroot_mkdir, - .stat = &chroot_stat, - .dput = &chroot_dput, - .readdir = &chroot_readdir, - .unlink = &chroot_unlink, - .rename = &chroot_rename, - .chmod = &chroot_chmod, - }; - -struct mount_data chroot_data = { .root_uri_len = 5, - .root_uri = URI_PREFIX_FILE, }; - -struct shim_mount chroot_builtin_fs = { .type = "chroot", - .fs_ops = &chroot_fs_ops, - .d_ops = &chroot_d_ops, - .data = &chroot_data, }; + .open = &chroot_open, + .mode = &chroot_mode, + .lookup = &chroot_lookup, + .creat = &chroot_creat, + .mkdir = &chroot_mkdir, + .stat = &chroot_stat, + .dput = &chroot_dput, + .readdir = &chroot_readdir, + .unlink = &chroot_unlink, + .rename = &chroot_rename, + .chmod = &chroot_chmod, +}; + +struct mount_data chroot_data = { + .root_uri_len = 5, + .root_uri = URI_PREFIX_FILE, +}; + +struct shim_mount chroot_builtin_fs = { + .type = "chroot", + .fs_ops = &chroot_fs_ops, + .d_ops = &chroot_d_ops, + .data = &chroot_data, +}; diff --git a/LibOS/shim/src/fs/dev/attestation.c b/LibOS/shim/src/fs/dev/attestation.c index cdb4cefc51..d71fe210c2 100644 --- a/LibOS/shim/src/fs/dev/attestation.c +++ b/LibOS/shim/src/fs/dev/attestation.c @@ -21,8 +21,8 @@ * these sizes are overapproximations of SGX requirements (report_data is 64B, target_info is * 512B, EPID quote is about 1KB, DCAP quote is about 4KB). */ #define USER_REPORT_DATA_MAX_SIZE 256 -#define TARGET_INFO_MAX_SIZE 1024 -#define QUOTE_MAX_SIZE 8192 +#define TARGET_INFO_MAX_SIZE 1024 +#define QUOTE_MAX_SIZE 8192 static char g_user_report_data[USER_REPORT_DATA_MAX_SIZE] = {0}; static size_t g_user_report_data_size = 0; @@ -68,8 +68,8 @@ static int dev_attestation_readwrite_mode(const char* name, mode_t* mode) { static int dev_attestation_readonly_stat(const char* name, struct stat* buf) { __UNUSED(name); memset(buf, 0, sizeof(*buf)); - buf->st_dev = 1; /* dummy ID of device containing file */ - buf->st_ino = 1; /* dummy inode number */ + buf->st_dev = 1; /* dummy ID of device containing file */ + buf->st_ino = 1; /* dummy inode number */ buf->st_mode = FILE_R_MODE | S_IFREG; return 0; } @@ -77,8 +77,8 @@ static int dev_attestation_readonly_stat(const char* name, struct stat* buf) { static int dev_attestation_readwrite_stat(const char* name, struct stat* buf) { __UNUSED(name); memset(buf, 0, sizeof(*buf)); - buf->st_dev = 1; /* dummy ID of device containing file */ - buf->st_ino = 1; /* dummy inode number */ + buf->st_dev = 1; /* dummy ID of device containing file */ + buf->st_ino = 1; /* dummy inode number */ buf->st_mode = FILE_RW_MODE | S_IFREG; return 0; } @@ -197,7 +197,8 @@ static int dev_attestation_target_info_open(struct shim_handle* hdl, const char* * * In case of SGX, target info is an opaque blob of size 512B. */ -static int dev_attestation_my_target_info_open(struct shim_handle* hdl, const char* name, int flags) { +static int dev_attestation_my_target_info_open(struct shim_handle* hdl, const char* name, + int flags) { __UNUSED(name); int ret; @@ -234,9 +235,8 @@ static int dev_attestation_my_target_info_open(struct shim_handle* hdl, const ch /* below invocation returns this enclave's target info because we zeroed out (via calloc) * target_info: it's a hint to function to update target_info with this enclave's info */ - bool ok = DkAttestationReport(user_report_data, &user_report_data_size, - target_info, &target_info_size, - /*report=*/NULL, &report_size); + bool ok = DkAttestationReport(user_report_data, &user_report_data_size, target_info, + &target_info_size, /*report=*/NULL, &report_size); if (!ok) { ret = -EACCES; goto out; @@ -253,9 +253,9 @@ static int dev_attestation_my_target_info_open(struct shim_handle* hdl, const ch goto out; } - data->str = target_info; - data->buf_size = target_info_size; - data->len = target_info_size; + data->str = target_info; + data->buf_size = target_info_size; + data->len = target_info_size; hdl->type = TYPE_STR; hdl->acc_mode = MAY_READ; @@ -308,9 +308,8 @@ static int dev_attestation_report_open(struct shim_handle* hdl, const char* name goto out; } - bool ok = DkAttestationReport(&g_user_report_data, &g_user_report_data_size, - &g_target_info, &g_target_info_size, - report, &g_report_size); + bool ok = DkAttestationReport(&g_user_report_data, &g_user_report_data_size, &g_target_info, + &g_target_info_size, report, &g_report_size); if (!ok) { ret = -EACCES; goto out; @@ -389,8 +388,7 @@ static int dev_attestation_quote_open(struct shim_handle* hdl, const char* name, goto out; } - bool ok = DkAttestationQuote(&g_user_report_data, g_user_report_data_size, - quote, "e_size); + bool ok = DkAttestationQuote(&g_user_report_data, g_user_report_data_size, quote, "e_size); if (!ok) { ret = -EACCES; goto out; @@ -410,9 +408,9 @@ static int dev_attestation_quote_open(struct shim_handle* hdl, const char* name, memcpy(data_str_quote, quote, quote_size); - data->str = data_str_quote; - data->buf_size = quote_size; - data->len = quote_size; + data->str = data_str_quote; + data->buf_size = quote_size; + data->len = quote_size; hdl->type = TYPE_STR; hdl->acc_mode = MAY_READ; @@ -525,23 +523,22 @@ struct pseudo_fs_ops dev_attestation_fs_ops = { struct pseudo_dir dev_attestation_dir = { .size = 6, .ent = { - { .name = "user_report_data", - .fs_ops = &dev_attestation_user_report_data_fs_ops, - .type = LINUX_DT_REG }, - { .name = "target_info", - .fs_ops = &dev_attestation_target_info_fs_ops, - .type = LINUX_DT_REG }, - { .name = "my_target_info", - .fs_ops = &dev_attestation_my_target_info_fs_ops, - .type = LINUX_DT_REG }, - { .name = "report", - .fs_ops = &dev_attestation_report_fs_ops, - .type = LINUX_DT_REG }, - { .name = "quote", - .fs_ops = &dev_attestation_quote_fs_ops, - .type = LINUX_DT_REG }, - { .name = "protected_files_key", - .fs_ops = &dev_attestation_pfkey_fs_ops, - .type = LINUX_DT_REG }, - } -}; + {.name = "user_report_data", + .fs_ops = &dev_attestation_user_report_data_fs_ops, + .type = LINUX_DT_REG}, + {.name = "target_info", + .fs_ops = &dev_attestation_target_info_fs_ops, + .type = LINUX_DT_REG}, + {.name = "my_target_info", + .fs_ops = &dev_attestation_my_target_info_fs_ops, + .type = LINUX_DT_REG}, + {.name = "report", + .fs_ops = &dev_attestation_report_fs_ops, + .type = LINUX_DT_REG}, + {.name = "quote", + .fs_ops = &dev_attestation_quote_fs_ops, + .type = LINUX_DT_REG}, + {.name = "protected_files_key", + .fs_ops = &dev_attestation_pfkey_fs_ops, + .type = LINUX_DT_REG}, + }}; diff --git a/LibOS/shim/src/fs/dev/fs.c b/LibOS/shim/src/fs/dev/fs.c index 7c2541c484..ab34cb6d37 100644 --- a/LibOS/shim/src/fs/dev/fs.c +++ b/LibOS/shim/src/fs/dev/fs.c @@ -23,35 +23,35 @@ extern const struct pseudo_dir dev_attestation_dir; static const struct pseudo_dir dev_root_dir = { .size = 9, - .ent = { - { .name = "null", - .fs_ops = &dev_null_fs_ops, - .type = LINUX_DT_CHR }, - { .name = "tty", - .fs_ops = &dev_tty_fs_ops, - .type = LINUX_DT_CHR }, - { .name = "zero", - .fs_ops = &dev_zero_fs_ops, - .type = LINUX_DT_CHR }, - { .name = "random", - .fs_ops = &dev_random_fs_ops, - .type = LINUX_DT_CHR }, - { .name = "urandom", - .fs_ops = &dev_urandom_fs_ops, - .type = LINUX_DT_CHR }, - { .name = "stdin", - .fs_ops = &dev_stdin_fs_ops, - .type = LINUX_DT_LNK }, - { .name = "stdout", - .fs_ops = &dev_stdout_fs_ops, - .type = LINUX_DT_LNK }, - { .name = "stderr", - .fs_ops = &dev_stderr_fs_ops, - .type = LINUX_DT_LNK }, - { .name = "attestation", - .fs_ops = &dev_attestation_fs_ops, - .type = LINUX_DT_DIR, - .dir = &dev_attestation_dir }, + .ent = { + {.name = "null", + .fs_ops = &dev_null_fs_ops, + .type = LINUX_DT_CHR}, + {.name = "tty", + .fs_ops = &dev_tty_fs_ops, + .type = LINUX_DT_CHR}, + {.name = "zero", + .fs_ops = &dev_zero_fs_ops, + .type = LINUX_DT_CHR}, + {.name = "random", + .fs_ops = &dev_random_fs_ops, + .type = LINUX_DT_CHR}, + {.name = "urandom", + .fs_ops = &dev_urandom_fs_ops, + .type = LINUX_DT_CHR}, + {.name = "stdin", + .fs_ops = &dev_stdin_fs_ops, + .type = LINUX_DT_LNK}, + {.name = "stdout", + .fs_ops = &dev_stdout_fs_ops, + .type = LINUX_DT_LNK}, + {.name = "stderr", + .fs_ops = &dev_stderr_fs_ops, + .type = LINUX_DT_LNK}, + {.name = "attestation", + .fs_ops = &dev_attestation_fs_ops, + .type = LINUX_DT_DIR, + .dir = &dev_attestation_dir}, }, }; diff --git a/LibOS/shim/src/fs/dev/random.c b/LibOS/shim/src/fs/dev/random.c index 8c4f89e7f0..39d9b1e97e 100644 --- a/LibOS/shim/src/fs/dev/random.c +++ b/LibOS/shim/src/fs/dev/random.c @@ -49,11 +49,11 @@ static int dev_random_open(struct shim_handle* hdl, const char* name, int flags) __UNUSED(name); __UNUSED(flags); - struct shim_dev_ops ops = {.read = &dev_random_read, - .write = &dev_random_write, - .mode = &dev_random_mode, - .stat = &dev_random_stat, - .hstat = &dev_random_hstat}; + struct shim_dev_ops ops = {.read = &dev_random_read, + .write = &dev_random_write, + .mode = &dev_random_mode, + .stat = &dev_random_stat, + .hstat = &dev_random_hstat}; memcpy(&hdl->info.dev.dev_ops, &ops, sizeof(ops)); return 0; diff --git a/LibOS/shim/src/fs/dev/std.c b/LibOS/shim/src/fs/dev/std.c index 2569751287..97174a99a7 100644 --- a/LibOS/shim/src/fs/dev/std.c +++ b/LibOS/shim/src/fs/dev/std.c @@ -19,7 +19,7 @@ static int dev_std_stat(const char* name, struct stat* buf) { __UNUSED(name); memset(buf, 0, sizeof(*buf)); - buf->st_mode = FILE_RW_MODE | S_IFLNK; + buf->st_mode = FILE_RW_MODE | S_IFLNK; return 0; } @@ -49,22 +49,22 @@ static int dev_stderr_follow_link(const char* name, struct shim_qstr* link) { } struct pseudo_fs_ops dev_stdin_fs_ops = { - .open = &dev_std_open, - .mode = &dev_std_mode, - .stat = &dev_std_stat, + .open = &dev_std_open, + .mode = &dev_std_mode, + .stat = &dev_std_stat, .follow_link = &dev_stdin_follow_link, }; struct pseudo_fs_ops dev_stdout_fs_ops = { - .open = &dev_std_open, - .mode = &dev_std_mode, - .stat = &dev_std_stat, + .open = &dev_std_open, + .mode = &dev_std_mode, + .stat = &dev_std_stat, .follow_link = &dev_stdout_follow_link, }; struct pseudo_fs_ops dev_stderr_fs_ops = { - .open = &dev_std_open, - .mode = &dev_std_mode, - .stat = &dev_std_stat, + .open = &dev_std_open, + .mode = &dev_std_mode, + .stat = &dev_std_stat, .follow_link = &dev_stderr_follow_link, }; diff --git a/LibOS/shim/src/fs/eventfd/fs.c b/LibOS/shim/src/fs/eventfd/fs.c index 04c3fe5c29..26a507b5f0 100644 --- a/LibOS/shim/src/fs/eventfd/fs.c +++ b/LibOS/shim/src/fs/eventfd/fs.c @@ -2,9 +2,7 @@ /* Copyright (C) 2019 Intel Corporation */ /* - * fs.c - * - * This file contains codes for implementation of 'eventfd' filesystem. + * This file contains code for implementation of 'eventfd' filesystem. */ #include @@ -13,10 +11,10 @@ #include #include -#include -#include -#include -#include +#include "pal.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" static ssize_t eventfd_read(struct shim_handle* hdl, void* buf, size_t count) { if (count < sizeof(uint64_t)) diff --git a/LibOS/shim/src/fs/pipe/fs.c b/LibOS/shim/src/fs/pipe/fs.c index dd65a4d374..dd49dbc43c 100644 --- a/LibOS/shim/src/fs/pipe/fs.c +++ b/LibOS/shim/src/fs/pipe/fs.c @@ -2,9 +2,7 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * fs.c - * - * This file contains codes for implementation of 'pipe' filesystem. + * This file contains code for implementation of 'pipe' filesystem. */ #define __KERNEL__ @@ -16,13 +14,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_debug.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_thread.h" static ssize_t pipe_read(struct shim_handle* hdl, void* buf, size_t count) { if (!hdl->info.pipe.ready_for_ops) diff --git a/LibOS/shim/src/fs/proc/fs.c b/LibOS/shim/src/fs/proc/fs.c index 5214ea7493..e8c3b9252b 100644 --- a/LibOS/shim/src/fs/proc/fs.c +++ b/LibOS/shim/src/fs/proc/fs.c @@ -24,23 +24,22 @@ extern const struct pseudo_fs_ops fs_cpuinfo; static const struct pseudo_dir proc_root_dir = { .size = 5, .ent = { - { .name = "self", - .fs_ops = &fs_thread, - .dir = &dir_thread }, - { .name_ops = &nm_thread, - .fs_ops = &fs_thread, - .dir = &dir_thread }, - { .name_ops = &nm_ipc_thread, - .fs_ops = &fs_ipc_thread, - .dir = &dir_ipc_thread }, - { .name = "meminfo", - .fs_ops = &fs_meminfo, - .type = LINUX_DT_REG }, - { .name = "cpuinfo", - .fs_ops = &fs_cpuinfo, - .type = LINUX_DT_REG }, - } -}; + {.name = "self", + .fs_ops = &fs_thread, + .dir = &dir_thread}, + {.name_ops = &nm_thread, + .fs_ops = &fs_thread, + .dir = &dir_thread}, + {.name_ops = &nm_ipc_thread, + .fs_ops = &fs_ipc_thread, + .dir = &dir_ipc_thread}, + {.name = "meminfo", + .fs_ops = &fs_meminfo, + .type = LINUX_DT_REG}, + {.name = "cpuinfo", + .fs_ops = &fs_cpuinfo, + .type = LINUX_DT_REG}, + }}; static const struct pseudo_fs_ops proc_root_fs = { .open = &pseudo_dir_open, diff --git a/LibOS/shim/src/fs/proc/info.c b/LibOS/shim/src/fs/proc/info.c index 2d98d918f1..567a0f178a 100644 --- a/LibOS/shim/src/fs/proc/info.c +++ b/LibOS/shim/src/fs/proc/info.c @@ -18,8 +18,8 @@ static int proc_info_mode(const char* name, mode_t* mode) { static int proc_info_stat(const char* name, struct stat* buf) { __UNUSED(name); memset(buf, 0, sizeof(struct stat)); - buf->st_dev = 1; /* dummy ID of device containing file */ - buf->st_ino = 1; /* dummy inode number */ + buf->st_dev = 1; /* dummy ID of device containing file */ + buf->st_ino = 1; /* dummy inode number */ buf->st_mode = FILE_R_MODE | S_IFREG; return 0; } @@ -126,20 +126,21 @@ static int proc_cpuinfo_open(struct shim_handle* hdl, const char* name, int flag if (flags & (O_WRONLY | O_RDWR)) return -EACCES; - size_t len = 0, - max = 128; + size_t len = 0; + size_t max = 128; char* str = malloc(max); if (!str) { return -ENOMEM; } -#define ADD_INFO(fmt, ...) do { \ - int ret = print_to_str(&str, len, &max, fmt, ##__VA_ARGS__); \ - if (ret < 0) { \ - free(str); \ - return ret; \ - } \ - len += ret; \ +#define ADD_INFO(fmt, ...) \ + do { \ + int ret = print_to_str(&str, len, &max, fmt, ##__VA_ARGS__); \ + if (ret < 0) { \ + free(str); \ + return ret; \ + } \ + len += ret; \ } while (0) for (size_t n = 0; n < pal_control.cpu_info.cpu_num; n++) { @@ -155,8 +156,7 @@ static int proc_cpuinfo_open(struct shim_handle* hdl, const char* name, int flag ADD_INFO("cpu cores\t: %lu\n", pal_control.cpu_info.cpu_num); double bogomips = pal_control.cpu_info.cpu_bogomips; // Apparently graphene snprintf cannot into floats. - ADD_INFO("bogomips\t: %lu.%02lu\n", - (unsigned long)bogomips, + ADD_INFO("bogomips\t: %lu.%02lu\n", (unsigned long)bogomips, (unsigned long)(bogomips * 100.0 + 0.5) % 100); ADD_INFO("\n"); } diff --git a/LibOS/shim/src/fs/proc/ipc-thread.c b/LibOS/shim/src/fs/proc/ipc-thread.c index 3260810823..1b60dd3e38 100644 --- a/LibOS/shim/src/fs/proc/ipc-thread.c +++ b/LibOS/shim/src/fs/proc/ipc-thread.c @@ -7,15 +7,15 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" static int parse_ipc_thread_name(const char* name, IDTYPE* pidptr, const char** next, size_t* next_len, const char** nextnext) { @@ -57,8 +57,8 @@ static int parse_ipc_thread_name(const char* name, IDTYPE* pidptr, const char** static int find_ipc_thread_link(const char* name, struct shim_qstr* link, struct shim_dentry** dentptr) { - const char *next; - const char *nextnext; + const char* next; + const char* nextnext; size_t next_len; IDTYPE pid; @@ -266,7 +266,7 @@ static int proc_list_ipc_thread(const char* name, struct shim_dirent** buf, int // Only one valid name __UNUSED(name); struct pid_status_cache* status = NULL; - int ret = 0; + int ret = 0; if (!create_lock_runtime(&status_lock)) { return -ENOMEM; @@ -375,14 +375,8 @@ const struct pseudo_fs_ops fs_ipc_thread = { const struct pseudo_dir dir_ipc_thread = { .size = 3, .ent = { - { .name = "cwd", - .fs_ops = &fs_ipc_thread_link, - .type = LINUX_DT_LNK }, - { .name = "exe", - .fs_ops = &fs_ipc_thread_link, - .type = LINUX_DT_LNK }, - { .name = "root", - .fs_ops = &fs_ipc_thread_link, - .type = LINUX_DT_LNK }, - } + {.name = "cwd", .fs_ops = &fs_ipc_thread_link, .type = LINUX_DT_LNK}, + {.name = "exe", .fs_ops = &fs_ipc_thread_link, .type = LINUX_DT_LNK}, + {.name = "root", .fs_ops = &fs_ipc_thread_link, .type = LINUX_DT_LNK}, + } }; diff --git a/LibOS/shim/src/fs/proc/thread.c b/LibOS/shim/src/fs/proc/thread.c index 6a41e5e10e..e5bbe464c8 100644 --- a/LibOS/shim/src/fs/proc/thread.c +++ b/LibOS/shim/src/fs/proc/thread.c @@ -7,14 +7,14 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" static int parse_thread_name(const char* name, IDTYPE* pidptr, const char** next, size_t* next_len, const char** nextnext) { @@ -554,13 +554,13 @@ static int proc_thread_maps_open(struct shim_handle* hdl, const char* name, int goto err; } - data->str = buffer; - data->len = offset; + data->str = buffer; + data->len = offset; hdl->type = TYPE_STR; hdl->flags = flags & ~O_RDONLY; hdl->acc_mode = MAY_READ; hdl->info.str.data = data; - ret = 0; + ret = 0; err: if (ret < 0) { @@ -728,20 +728,9 @@ const struct pseudo_fs_ops fs_thread = { const struct pseudo_dir dir_thread = { .size = 5, .ent = { - { .name = "cwd", - .fs_ops = &fs_thread_link, - .type = LINUX_DT_LNK }, - { .name = "exe", - .fs_ops = &fs_thread_link, - .type = LINUX_DT_LNK }, - { .name = "root", - .fs_ops = &fs_thread_link, - .type = LINUX_DT_LNK }, - { .name = "fd", - .fs_ops = &fs_thread_fd, - .dir = &dir_fd }, - { .name = "maps", - .fs_ops = &fs_thread_maps, - .type = LINUX_DT_REG }, - } -}; + {.name = "cwd", .fs_ops = &fs_thread_link, .type = LINUX_DT_LNK}, + {.name = "exe", .fs_ops = &fs_thread_link, .type = LINUX_DT_LNK}, + {.name = "root", .fs_ops = &fs_thread_link, .type = LINUX_DT_LNK}, + {.name = "fd", .fs_ops = &fs_thread_fd, .dir = &dir_fd}, + {.name = "maps", .fs_ops = &fs_thread_maps, .type = LINUX_DT_REG}, + }}; diff --git a/LibOS/shim/src/fs/shim_dcache.c b/LibOS/shim/src/fs/shim_dcache.c index 244809857c..6fd1efb195 100644 --- a/LibOS/shim/src/fs/shim_dcache.c +++ b/LibOS/shim/src/fs/shim_dcache.c @@ -4,17 +4,15 @@ */ /* - * shim_dcache.c - * - * This file contains codes for maintaining directory cache in library OS. + * This file contains code for maintaining directory cache in library OS. */ -#include -#include -#include -#include -#include -#include +#include "list.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_types.h" static struct shim_lock dcache_mgr_lock; @@ -25,7 +23,7 @@ static struct shim_lock dcache_mgr_lock; #define DCACHE_MGR_ALLOC 64 #define OBJ_TYPE struct shim_dentry -#include +#include "memmgr.h" struct shim_lock dcache_lock; diff --git a/LibOS/shim/src/fs/shim_fs.c b/LibOS/shim/src/fs/shim_fs.c index ea219c7d68..53b840893f 100644 --- a/LibOS/shim/src/fs/shim_fs.c +++ b/LibOS/shim/src/fs/shim_fs.c @@ -2,21 +2,19 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_fs.c - * - * This file contains codes for creating filesystems in library OS. + * This file contains code for creating filesystems in library OS. */ #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "list.h" +#include "pal.h" +#include "pal_debug.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_internal.h" +#include "shim_utils.h" struct shim_fs { char name[8]; @@ -60,7 +58,7 @@ static struct shim_lock mount_mgr_lock; #define MOUNT_MGR_ALLOC 64 #define OBJ_TYPE struct shim_mount -#include +#include "memmgr.h" static MEM_MGR mount_mgr = NULL; DEFINE_LISTP(shim_mount); @@ -195,8 +193,8 @@ static int __mount_others(void) { if (nkeys <= 0) goto out; - const char *key = keybuf; - const char *next = NULL; + const char* key = keybuf; + const char* next = NULL; for (int n = 0; n < nkeys; key = next, n++) { for (next = key; *next; next++) ; @@ -408,7 +406,7 @@ int mount_fs(const char* type, const char* uri, const char* mount_point, struct if (parent && last_len > 0) { /* Newly created dentry's relative path will be a concatenation of parent * + last strings (see get_new_dentry), make sure it fits into qstr */ - if (parent->rel_path.len + 1 + last_len >= STR_SIZE) { /* +1 for '/' */ + if (parent->rel_path.len + 1 + last_len >= STR_SIZE) { /* +1 for '/' */ debug("Relative path exceeds the limit %d\n", STR_SIZE); ret = -ENAMETOOLONG; goto out_with_unlock; @@ -490,12 +488,12 @@ int mount_fs(const char* type, const char* uri, const char* mount_point, struct */ void get_mount(struct shim_mount* mount) { __UNUSED(mount); - //REF_INC(mount->ref_count); + // REF_INC(mount->ref_count); } void put_mount(struct shim_mount* mount) { __UNUSED(mount); - //REF_DEC(mount->ref_count); + // REF_DEC(mount->ref_count); } int walk_mounts(int (*walk)(struct shim_mount* mount, void* arg), void* arg) { diff --git a/LibOS/shim/src/fs/shim_fs_hash.c b/LibOS/shim/src/fs/shim_fs_hash.c index 14126505b1..838e77c096 100644 --- a/LibOS/shim/src/fs/shim_fs_hash.c +++ b/LibOS/shim/src/fs/shim_fs_hash.c @@ -5,8 +5,8 @@ * This file contains functions to generate hash values for FS paths. */ -#include -#include +#include "shim_fs.h" +#include "shim_internal.h" static HASHTYPE __hash(const char* p, size_t len) { HASHTYPE hash = 0; diff --git a/LibOS/shim/src/fs/shim_fs_pseudo.c b/LibOS/shim/src/fs/shim_fs_pseudo.c index b37fe44b7c..07aeae5ff0 100644 --- a/LibOS/shim/src/fs/shim_fs_pseudo.c +++ b/LibOS/shim/src/fs/shim_fs_pseudo.c @@ -26,8 +26,8 @@ static int pseudo_findent(const char* path, const struct pseudo_ent* root_ent, const struct pseudo_ent** found_ent) { assert(path); - size_t token_len = 0; - const char* token = path; + size_t token_len = 0; + const char* token = path; const char* next_token = NULL; const struct pseudo_ent* ent = root_ent; @@ -102,7 +102,7 @@ static int populate_dirent(const char* path, const struct pseudo_dir* dir, struc dirent_in_buf->ino = rehash_name(dir_hash, ent->name, name_size - 1); dirent_in_buf->type = ent->dir ? LINUX_DT_DIR : ent->type; - dirent_in_buf = dirent_in_buf->next; + dirent_in_buf = dirent_in_buf->next; } else if (ent->name_ops && ent->name_ops->list_name) { /* directory entry has a list of entries calculated at runtime (via list_name) */ struct shim_dirent* old_dirent_in_buf = dirent_in_buf; diff --git a/LibOS/shim/src/fs/shim_namei.c b/LibOS/shim/src/fs/shim_namei.c index dd46cb4926..d8c1f1f964 100644 --- a/LibOS/shim/src/fs/shim_namei.c +++ b/LibOS/shim/src/fs/shim_namei.c @@ -2,10 +2,7 @@ /* Copyright (C) 2017, University of North Carolina at Chapel Hill and Fortanix, Inc. */ /* - * shim_namei.c - * - * This file contains codes for parsing a FS path and looking up in the - * directory cache. + * This file contains code for parsing a FS path and looking up in the directory cache. */ #include @@ -13,30 +10,28 @@ #include #include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_thread.h" +#include "shim_utils.h" /* Advances a char pointer (string) past any repeated slashes and returns the result. * Must be a null-terminated string. */ -static inline const char * eat_slashes (const char * string) -{ +static inline const char* eat_slashes(const char* string) { while (*string == '/') string++; return string; } -static inline int __lookup_flags (int flags) -{ +static inline int __lookup_flags(int flags) { int retval = LOOKUP_FOLLOW; if (flags & O_NOFOLLOW) retval &= ~LOOKUP_FOLLOW; - if ((flags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL)) + if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) retval &= ~LOOKUP_FOLLOW; if (flags & O_DIRECTORY) @@ -105,7 +100,6 @@ int __permission(struct shim_dentry* dent, mode_t mask) { mode = dent->mode; - if (((mode >> 6) & mask) == mask) return 0; @@ -136,11 +130,11 @@ int __permission(struct shim_dentry* dent, mode_t mask) { * * The caller should hold the dcache_lock. */ -int lookup_dentry (struct shim_dentry * parent, const char * name, int namelen, struct shim_dentry ** new, struct shim_mount * fs) -{ +int lookup_dentry(struct shim_dentry* parent, const char* name, int namelen, + struct shim_dentry** new, struct shim_mount* fs) { assert(locked(&dcache_lock)); - struct shim_dentry * dent = NULL; + struct shim_dentry* dent = NULL; int do_fs_lookup = 0; int err = 0; @@ -151,7 +145,7 @@ int lookup_dentry (struct shim_dentry * parent, const char * name, int namelen, if (parent) { /* Newly created dentry's relative path will be a concatenation of parent * + name strings (see get_new_dentry), make sure it fits into qstr */ - if (parent->rel_path.len + 1 + namelen >= STR_SIZE) { /* +1 for '/' */ + if (parent->rel_path.len + 1 + namelen >= STR_SIZE) { /* +1 for '/' */ debug("Relative path exceeds the limit %d\n", STR_SIZE); err = -ENAMETOOLONG; goto out; @@ -187,7 +181,6 @@ int lookup_dentry (struct shim_dentry * parent, const char * name, int namelen, * negative dentries, so they can still be cached */ dent->state |= DENTRY_NEGATIVE; } else { - /* Trying to weed out ESKIPPED */ assert(err != -ESKIPPED); goto out; @@ -245,25 +238,24 @@ int lookup_dentry (struct shim_dentry * parent, const char * name, int namelen, * If the LOOKUP_DIRECTORY flag is set, and the found file isn't a directory, * returns -ENOTDIR. */ -int __path_lookupat (struct shim_dentry * start, const char * path, int flags, - struct shim_dentry ** dent, int link_depth, - struct shim_mount * fs, bool make_ancestor) -{ +int __path_lookupat(struct shim_dentry* start, const char* path, int flags, + struct shim_dentry** dent, int link_depth, struct shim_mount* fs, + bool make_ancestor) { assert(locked(&dcache_lock)); // Basic idea: recursively iterate over path, peeling off one atom at a // time. /* Chia-Che 12/5/2014: * XXX I am not a big fan of recursion. I am giving a pass to this code * for now, but eventually someone (probably me) should rewrite it. */ - const char * my_path; + const char* my_path; int my_pathlen = 0; int err = 0; - struct shim_dentry *my_dent = NULL; + struct shim_dentry* my_dent = NULL; struct shim_qstr this = QSTR_INIT; bool leaf_case = false; // Leaf call in case of recursion bool no_start = false; // start not passed bool no_fs = false; // fs not passed - struct shim_thread * cur_thread = get_cur_thread(); + struct shim_thread* cur_thread = get_cur_thread(); if (cur_thread && *path == '/') { /* @@ -376,7 +368,7 @@ int __path_lookupat (struct shim_dentry * start, const char * path, int flags, if (path) { /* symlink name starts with a slash, restart lookup at root */ if (*path == '/') { - struct shim_dentry * root; + struct shim_dentry* root; // not sure how to deal with this case if cur_thread isn't defined assert(cur_thread); @@ -406,7 +398,6 @@ int __path_lookupat (struct shim_dentry * start, const char * path, int flags, // If we found something, and there is more, recur if (*my_path != '\0') { - /* If we have more to look up, but got a negative DENTRY, * we need to fail or (unlikely) create an ancestor dentry.*/ if (my_dent->state & DENTRY_NEGATIVE) { @@ -423,8 +414,8 @@ int __path_lookupat (struct shim_dentry * start, const char * path, int flags, /* Although this is slight over-kill, let's just always increment the * mount ref count on a recursion, for easier bookkeeping */ get_mount(my_dent->fs); - err = __path_lookupat (my_dent, my_path, flags, dent, link_depth, - my_dent->fs, make_ancestor); + err = __path_lookupat(my_dent, my_path, flags, dent, link_depth, my_dent->fs, + make_ancestor); if (err < 0) goto out; /* If we aren't returning a live reference to the target dentry, go @@ -475,17 +466,15 @@ int __path_lookupat (struct shim_dentry * start, const char * path, int flags, /* Just wraps __path_lookupat, but also acquires and releases the dcache_lock. */ -int path_lookupat (struct shim_dentry * start, const char * name, int flags, - struct shim_dentry ** dent, struct shim_mount * fs) -{ +int path_lookupat(struct shim_dentry* start, const char* name, int flags, struct shim_dentry** dent, + struct shim_mount* fs) { int ret = 0; lock(&dcache_lock); - ret = __path_lookupat (start, name, flags, dent, 0, fs, 0); + ret = __path_lookupat(start, name, flags, dent, 0, fs, 0); unlock(&dcache_lock); return ret; } - /* Open path with given flags, in mode, similar to Unix open. * * The start dentry specifies where to begin the search, and can be null. If @@ -500,14 +489,12 @@ int path_lookupat (struct shim_dentry * start, const char * name, int flags, * The result is stored in dent. */ -int open_namei (struct shim_handle * hdl, struct shim_dentry * start, - const char * path, int flags, int mode, - struct shim_dentry ** dent) -{ +int open_namei(struct shim_handle* hdl, struct shim_dentry* start, const char* path, int flags, + int mode, struct shim_dentry** dent) { int lookup_flags = __lookup_flags(flags); mode_t acc_mode = ACC_MODE(flags & O_ACCMODE); int err = 0, newly_created = 0; - struct shim_dentry *mydent = NULL; + struct shim_dentry* mydent = NULL; if (*path == '\0') { /* corner case: trying to open with empty filename */ @@ -530,7 +517,7 @@ int open_namei (struct shim_handle * hdl, struct shim_dentry * start, // of directories. if (mydent && err == -ENOENT && (flags & O_CREAT)) { // Create the file - struct shim_dentry * dir = mydent->parent; + struct shim_dentry* dir = mydent->parent; if (!dir) { err = -ENOENT; @@ -571,7 +558,7 @@ int open_namei (struct shim_handle * hdl, struct shim_dentry * start, // Set err back to zero and fall through err = 0; - } else if (err == 0 && ((flags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL))) { + } else if (err == 0 && ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))) { err = -EEXIST; } @@ -608,11 +595,9 @@ int open_namei (struct shim_handle * hdl, struct shim_dentry * start, * the underlying truncate function. */ -int dentry_open (struct shim_handle * hdl, struct shim_dentry * dent, - int flags) -{ +int dentry_open(struct shim_handle* hdl, struct shim_dentry* dent, int flags) { int ret = 0; - struct shim_mount * fs = dent->fs; + struct shim_mount* fs = dent->fs; /* I think missing functionality should be treated as EINVAL, or maybe * ENOSYS?*/ @@ -649,8 +634,8 @@ int dentry_open (struct shim_handle * hdl, struct shim_dentry * dent, // Let's defer setting the DENTRY_LISTED flag until we need it // Use -1 to indicate that the buf/ptr isn't initialized - hdl->dir_info.buf = (void *)-1; - hdl->dir_info.ptr = (void *)-1; + hdl->dir_info.buf = (void*)-1; + hdl->dir_info.ptr = (void*)-1; } if (!dentry_get_path_into_qstr(dent, &hdl->path)) { @@ -675,8 +660,7 @@ int dentry_open (struct shim_handle * hdl, struct shim_dentry * dent, return ret; } -static inline void set_dirent_type (mode_t * type, int d_type) -{ +static inline void set_dirent_type(mode_t* type, int d_type) { switch (d_type) { case LINUX_DT_DIR: *type = S_IFDIR; @@ -716,17 +700,16 @@ static inline void set_dirent_type (mode_t * type, int d_type) * have no consistency semantics, we can apply the principle of laziness and * not do the work until we are sure we really need to. */ -int list_directory_dentry (struct shim_dentry *dent) { - +int list_directory_dentry(struct shim_dentry* dent) { int ret = 0; - struct shim_mount * fs = dent->fs; + struct shim_mount* fs = dent->fs; lock(&dcache_lock); /* DEP 8/4/17: Another process could list this directory * while we are waiting on the dcache lock. This is ok, * no need to blow an assert. */ - if (dent->state & DENTRY_LISTED){ + if (dent->state & DENTRY_LISTED) { unlock(&dcache_lock); return 0; } @@ -742,18 +725,17 @@ int list_directory_dentry (struct shim_dentry *dent) { assert(dent->state & DENTRY_ISDIRECTORY); - struct shim_dirent * dirent = NULL; + struct shim_dirent* dirent = NULL; if ((ret = fs->d_ops->readdir(dent, &dirent)) < 0 || !dirent) { dirent = NULL; goto done_read; } - struct shim_dirent * d = dirent; - for ( ; d ; d = d->next) { - struct shim_dentry * child; - if ((ret = lookup_dentry(dent, d->name, strlen(d->name), - &child, fs)) < 0) { + struct shim_dirent* d = dirent; + for (; d; d = d->next) { + struct shim_dentry* child; + if ((ret = lookup_dentry(dent, d->name, strlen(d->name), &child, fs)) < 0) { if (ret != -ENOENT) { /* if the file is recently deleted or inaccessible, ignore it */ goto done_read; @@ -765,7 +747,7 @@ int list_directory_dentry (struct shim_dentry *dent) { if (!(child->state & DENTRY_VALID)) { set_dirent_type(&child->type, d->type); - child->state |= DENTRY_VALID|DENTRY_RECENTLY; + child->state |= DENTRY_VALID | DENTRY_RECENTLY; } child->ino = d->ino; @@ -789,12 +771,11 @@ int list_directory_dentry (struct shim_dentry *dent) { * * Returns 0 on success, <0 on failure. */ -int list_directory_handle (struct shim_dentry * dent, struct shim_handle * hdl) -{ - struct shim_dentry ** children = NULL; +int list_directory_handle(struct shim_dentry* dent, struct shim_handle* hdl) { + struct shim_dentry** children = NULL; int nchildren = dent->nchildren, count = 0; - struct shim_dentry * child; + struct shim_dentry* child; assert(hdl->dir_info.buf == (void*)-1); assert(hdl->dir_info.ptr == (void*)-1); @@ -808,7 +789,7 @@ int list_directory_handle (struct shim_dentry * dent, struct shim_handle * hdl) return 0; } - children = malloc(sizeof(struct shim_dentry *) * (nchildren + 1)); + children = malloc(sizeof(struct shim_dentry*) * (nchildren + 1)); if (!children) return -ENOMEM; @@ -817,7 +798,7 @@ int list_directory_handle (struct shim_dentry * dent, struct shim_handle * hdl) if (count >= nchildren) break; - struct shim_dentry * c = child; + struct shim_dentry* c = child; while (c->state & DENTRY_MOUNTPOINT) c = c->mounted->root; diff --git a/LibOS/shim/src/fs/socket/fs.c b/LibOS/shim/src/fs/socket/fs.c index 1a3db0b171..30b0e220b4 100644 --- a/LibOS/shim/src/fs/socket/fs.c +++ b/LibOS/shim/src/fs/socket/fs.c @@ -2,9 +2,7 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * fs.c - * - * This file contains codes for implementation of 'socket' filesystem. + * This file contains code for implementation of 'socket' filesystem. */ #define __KERNEL__ @@ -18,7 +16,6 @@ #include "pal.h" #include "pal_error.h" - #include "shim_fs.h" #include "shim_internal.h" #include "shim_thread.h" @@ -133,7 +130,7 @@ static int socket_checkout(struct shim_handle* hdl) { static off_t socket_poll(struct shim_handle* hdl, int poll_type) { struct shim_sock_handle* sock = &hdl->info.sock; - off_t ret = 0; + off_t ret = 0; lock(&hdl->lock); diff --git a/LibOS/shim/src/fs/str/fs.c b/LibOS/shim/src/fs/str/fs.c index c1d1b9796a..c8f16bde39 100644 --- a/LibOS/shim/src/fs/str/fs.c +++ b/LibOS/shim/src/fs/str/fs.c @@ -2,9 +2,7 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * fs.c - * - * This file contains codes for implementation of 'str' filesystem. + * This file contains code for implementation of 'str' filesystem. */ #include @@ -13,10 +11,11 @@ #include #include #include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_internal.h" int str_open(struct shim_handle* hdl, struct shim_dentry* dent, int flags) { struct shim_str_data* data = dent->data; diff --git a/LibOS/shim/src/generated-offsets.c b/LibOS/shim/src/generated-offsets.c index 068dc94f04..32bc4e7240 100644 --- a/LibOS/shim/src/generated-offsets.c +++ b/LibOS/shim/src/generated-offsets.c @@ -1,15 +1,10 @@ -#include - #include -#include -#include - -/* prototype needed due to -Wmissing-prototypes */ -void dummy(void); +#include "generated-offsets-build.h" +#include "shim_internal.h" +#include "shim_tcb.h" -void dummy(void) -{ +__attribute__((__used__)) static void dummy(void) { OFFSET_T(SHIM_TCB_OFFSET, PAL_TCB, libos_tcb); OFFSET_T(TCB_REGS, shim_tcb_t, context.regs); OFFSET(SHIM_REGS_RSP, shim_regs, rsp); diff --git a/LibOS/shim/src/ipc/shim_ipc.c b/LibOS/shim/src/ipc/shim_ipc.c index d1a026852e..1e26a37515 100644 --- a/LibOS/shim/src/ipc/shim_ipc.c +++ b/LibOS/shim/src/ipc/shim_ipc.c @@ -2,23 +2,21 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_ipc.c - * - * This file contains code to maintain generic bookkeeping of IPC: operations - * on shim_ipc_msg (one-way IPC messages), shim_ipc_msg_with_ack (IPC messages - * with acknowledgement), shim_ipc_info (IPC ports of process), shim_process. + * This file contains code to maintain generic bookkeeping of IPC: operations on shim_ipc_msg + * (one-way IPC messages), shim_ipc_msg_with_ack (IPC messages with acknowledgement), shim_ipc_info + * (IPC ports of process), shim_process. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "list.h" +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_thread.h" +#include "shim_unistd.h" +#include "shim_utils.h" static struct shim_lock ipc_info_mgr_lock; @@ -324,7 +322,7 @@ struct shim_ipc_msg_with_ack* pop_ipc_msg_with_ack(struct shim_ipc_port* port, u } int send_ipc_message_with_ack(struct shim_ipc_msg_with_ack* msg, struct shim_ipc_port* port, - unsigned long* seq, void* private_data) { + unsigned long* seq, void* private_data) { int ret = 0; struct shim_thread* thread = get_cur_thread(); diff --git a/LibOS/shim/src/ipc/shim_ipc_child.c b/LibOS/shim/src/ipc/shim_ipc_child.c index a2beb24ef5..1c9ba7adad 100644 --- a/LibOS/shim/src/ipc/shim_ipc_child.c +++ b/LibOS/shim/src/ipc/shim_ipc_child.c @@ -9,13 +9,14 @@ */ #include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_thread.h" +#include "shim_utils.h" struct thread_info { IDTYPE vmid; diff --git a/LibOS/shim/src/ipc/shim_ipc_helper.c b/LibOS/shim/src/ipc/shim_ipc_helper.c index 4a6b9ce3a8..c027a1ef5d 100644 --- a/LibOS/shim/src/ipc/shim_ipc_helper.c +++ b/LibOS/shim/src/ipc/shim_ipc_helper.c @@ -2,21 +2,19 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_ipc_helper.c - * * This file contains code to create an IPC helper thread inside library OS and maintain bookkeeping * of IPC ports. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "list.h" +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_thread.h" +#include "shim_utils.h" #define IPC_HELPER_STACK_SIZE (g_pal_alloc_align * 4) @@ -106,7 +104,7 @@ static int init_parent_ipc_port(void) { assert(cur_process.parent && cur_process.parent->vmid); /* for execve case, my parent is the parent of my parent (current process transparently inherits - * the "real" parent through already opened pal_handle on "temporary" parent's + * the "real" parent through already opened pal_handle on "temporary" parent's * cur_process.parent) */ if (!cur_process.parent->pal_handle) { /* for clone/fork case, parent is connected on parent_process */ @@ -474,14 +472,14 @@ int broadcast_ipc(struct shim_ipc_msg* msg, int target_type, struct shim_ipc_por for (size_t i = 0; i < target_ports_cnt; i++) { port = target_ports[i]; - debug("Broadcast to port %p (handle %p) for process %u (type %x, target %x)\n", - port, port->pal_handle, port->vmid & 0xFFFF, port->type, target_type); + debug("Broadcast to port %p (handle %p) for process %u (type %x, target %x)\n", port, + port->pal_handle, port->vmid & 0xFFFF, port->type, target_type); msg->dst = port->vmid; ret = send_ipc_message(msg, port); if (ret < 0) { - debug("Broadcast to port %p (handle %p) for process %u failed (errno = %d)!\n", - port, port->pal_handle, port->vmid & 0xFFFF, ret); + debug("Broadcast to port %p (handle %p) for process %u failed (errno = %d)!\n", port, + port->pal_handle, port->vmid & 0xFFFF, ret); goto out; } } @@ -520,7 +518,7 @@ int send_response_ipc_message(struct shim_ipc_port* port, IDTYPE dest, int ret, ret = (ret == RESPONSE_CALLBACK) ? 0 : ret; /* create IPC_MSG_RESP msg to send to dest, with sequence number seq, and in-body retval ret */ - size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_resp)); + size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_resp)); struct shim_ipc_msg* resp_msg = __alloca(total_msg_size); init_ipc_msg(resp_msg, IPC_MSG_RESP, total_msg_size, dest); resp_msg->seq = seq; @@ -535,14 +533,14 @@ int send_response_ipc_message(struct shim_ipc_port* port, IDTYPE dest, int ret, static int receive_ipc_message(struct shim_ipc_port* port) { int ret; size_t readahead = IPC_MSG_MINIMAL_SIZE * 2; - size_t bufsize = IPC_MSG_MINIMAL_SIZE + readahead; + size_t bufsize = IPC_MSG_MINIMAL_SIZE + readahead; struct shim_ipc_msg* msg = malloc(bufsize); if (!msg) { return -ENOMEM; } - size_t expected_size = IPC_MSG_MINIMAL_SIZE; - size_t bytes = 0; + size_t expected_size = IPC_MSG_MINIMAL_SIZE; + size_t bytes = 0; do { while (bytes < expected_size) { @@ -606,7 +604,7 @@ static int receive_ipc_message(struct shim_ipc_port* port) { } } - bytes -= expected_size; /* one message was received and handled */ + bytes -= expected_size; /* one message was received and handled */ if (bytes > 0) { /* we may have started reading the next message, move this message to beginning of msg @@ -699,7 +697,7 @@ noreturn static void shim_ipc_helper(void* dummy) { debug("shim_ipc_helper: allocation of tmp_ports failed\n"); goto out_err_unlock; } - PAL_HANDLE* tmp_pals = malloc(sizeof(*tmp_pals) * (1 + ports_max_cnt * 2)); + PAL_HANDLE* tmp_pals = malloc(sizeof(*tmp_pals) * (1 + ports_max_cnt * 2)); if (!tmp_pals) { debug("shim_ipc_helper: allocation of tmp_pals failed\n"); goto out_err_unlock; @@ -742,7 +740,8 @@ noreturn static void shim_ipc_helper(void* dummy) { unlock(&ipc_helper_lock); /* wait on collected ports' PAL handles + install_new_event_pal */ - PAL_BOL polled = DkStreamsWaitEvents(ports_cnt + 1, pals, pal_events, ret_events, NO_TIMEOUT); + PAL_BOL polled = DkStreamsWaitEvents(ports_cnt + 1, pals, pal_events, ret_events, + NO_TIMEOUT); for (size_t i = 0; polled && i < ports_cnt + 1; i++) { if (ret_events[i]) { @@ -765,7 +764,8 @@ noreturn static void shim_ipc_helper(void* dummy) { if (client) { /* type of client port is the same as original server port but with LISTEN * (for remote client) and without SERVER (doesn't wait for new clients) */ - IDTYPE client_type = (polled_port->type & ~IPC_PORT_SERVER) | IPC_PORT_LISTEN; + IDTYPE client_type = + (polled_port->type & ~IPC_PORT_SERVER) | IPC_PORT_LISTEN; add_ipc_port_by_id(polled_port->vmid, client, client_type, NULL, NULL); } else { debug("Port %p (handle %p) was removed during accepting client\n", @@ -781,13 +781,13 @@ noreturn static void shim_ipc_helper(void* dummy) { receive_ipc_message(polled_port); } if (attr.disconnected) { - debug("Port %p (handle %p) disconnected\n", - polled_port, polled_port->pal_handle); + debug("Port %p (handle %p) disconnected\n", polled_port, + polled_port->pal_handle); del_ipc_port_fini(polled_port, -ECONNRESET); } } else { - debug("Port %p (handle %p) was removed during attr querying\n", - polled_port, polled_port->pal_handle); + debug("Port %p (handle %p) was removed during attr querying\n", polled_port, + polled_port->pal_handle); del_ipc_port_fini(polled_port, -PAL_ERRNO()); } } @@ -868,7 +868,7 @@ static int create_ipc_helper(void) { PAL_HANDLE handle = thread_create(shim_ipc_helper_prepare, new); if (!handle) { - int ret = -PAL_ERRNO(); /* put_thread() may overwrite errno */ + int ret = -PAL_ERRNO(); /* put_thread() may overwrite errno */ ipc_helper_thread = NULL; ipc_helper_state = HELPER_NOTALIVE; put_thread(new); @@ -903,9 +903,8 @@ struct shim_thread* terminate_ipc_helper(void) { * through the host-OS stream, the host OS will close the stream, and the message will never be * seen by child. To prevent such cases, we simply wait for a bit before exiting. */ - debug( - "Waiting for 0.5s for all in-flight IPC messages to reach their destinations\n"); - DkThreadDelayExecution(500000); /* in microseconds */ + debug("Waiting for 0.5s for all in-flight IPC messages to reach their destinations\n"); + DkThreadDelayExecution(500000); /* in microseconds */ lock(&ipc_helper_lock); if (ipc_helper_state != HELPER_ALIVE) { diff --git a/LibOS/shim/src/ipc/shim_ipc_pid.c b/LibOS/shim/src/ipc/shim_ipc_pid.c index 5369184031..97cac88edd 100644 --- a/LibOS/shim/src/ipc/shim_ipc_pid.c +++ b/LibOS/shim/src/ipc/shim_ipc_pid.c @@ -71,7 +71,8 @@ int ipc_pid_kill_send(IDTYPE sender, IDTYPE target, enum kill_type type, int sig if (type == KILL_ALL) { debug("IPC broadcast: IPC_MSG_PID_KILL(%u, %d, %u, %d)\n", sender, type, target, signum); - ret = broadcast_ipc(msg, IPC_PORT_DIRECTCHILD | IPC_PORT_DIRECTPARENT, /*exclude_port=*/NULL); + ret = broadcast_ipc(msg, IPC_PORT_DIRECTCHILD | IPC_PORT_DIRECTPARENT, + /*exclude_port=*/NULL); } else { debug("IPC send to %u: IPC_MSG_PID_KILL(%u, %d, %u, %d)\n", dest & 0xFFFF, sender, type, target, signum); diff --git a/LibOS/shim/src/ipc/shim_ipc_ranges.c b/LibOS/shim/src/ipc/shim_ipc_ranges.c index a7f26c24ff..0f9158cba5 100644 --- a/LibOS/shim/src/ipc/shim_ipc_ranges.c +++ b/LibOS/shim/src/ipc/shim_ipc_ranges.c @@ -72,9 +72,9 @@ static LISTP_TYPE(range) range_table[RANGE_HASH_NUM]; static LISTP_TYPE(range) owned_ranges; static LISTP_TYPE(range) offered_ranges; -static int nowned = 0; +static int nowned = 0; static int noffered = 0; -static int nsubed = 0; +static int nsubed = 0; DEFINE_LIST(ns_query); struct ns_query { @@ -129,15 +129,15 @@ static int __extend_range_bitmap(IDTYPE expected) { } new_map->map_size = size; - range_map = new_map; + range_map = new_map; return 0; } static int __set_range_bitmap(IDTYPE off, bool unset) { assert(locked(&range_map_lock)); - IDTYPE i = off / BITS; - IDTYPE j = off - i * BITS; + IDTYPE i = off / BITS; + IDTYPE j = off - i * BITS; unsigned char* m = range_map->map + i; unsigned char f = 1U << j; if (unset) { @@ -155,8 +155,8 @@ static int __set_range_bitmap(IDTYPE off, bool unset) { static bool __check_range_bitmap(IDTYPE off) { assert(locked(&range_map_lock)); - IDTYPE i = off / BITS; - IDTYPE j = off - i * BITS; + IDTYPE i = off / BITS; + IDTYPE j = off - i * BITS; unsigned char* m = range_map->map + i; unsigned char f = 1U << j; return (*m) && ((*m) & f); @@ -188,7 +188,7 @@ static int __add_range(struct range* r, IDTYPE off, IDTYPE owner, const char* ur assert(locked(&range_map_lock)); LISTP_TYPE(range)* head = range_table + RANGE_HASH(off); - int ret = 0; + int ret = 0; if (!range_map || range_map->map_size <= off) { ret = __extend_range_bitmap(off); @@ -272,7 +272,7 @@ static int add_ipc_range(IDTYPE base, IDTYPE owner, const char* uri, LEASETYPE l lock(&range_map_lock); r->owner = NULL; - ret = __add_range(r, off, owner, uri, lease); + ret = __add_range(r, off, owner, uri, lease); if (ret < 0) free(r); unlock(&range_map_lock); @@ -281,16 +281,16 @@ static int add_ipc_range(IDTYPE base, IDTYPE owner, const char* uri, LEASETYPE l static void __del_ipc_subrange(struct subrange** ptr) { struct subrange* s = *ptr; - *ptr = NULL; + *ptr = NULL; put_ipc_info(s->owner); free(s); nsubed--; } int add_ipc_subrange(IDTYPE idx, IDTYPE owner, const char* uri, LEASETYPE* lease) { - IDTYPE off = (idx - 1) / RANGE_SIZE; - IDTYPE base = off * RANGE_SIZE + 1; - int err = 0; + IDTYPE off = (idx - 1) / RANGE_SIZE; + IDTYPE base = off * RANGE_SIZE + 1; + int err = 0; struct subrange* s = malloc(sizeof(struct subrange)); if (!s) return -ENOMEM; @@ -375,7 +375,7 @@ static int alloc_ipc_range(IDTYPE owner, const char* uri, IDTYPE* base, LEASETYP } LEASETYPE l = get_lease(); - ret = __add_range(r, i * BITS + j, owner, uri, l); + ret = __add_range(r, i * BITS + j, owner, uri, l); if (ret < 0) { if (r->owner) put_ipc_info(r->owner); @@ -404,17 +404,17 @@ static int get_ipc_range(IDTYPE idx, struct ipc_range* range, struct shim_ipc_in return -ESRCH; } - IDTYPE base = r->offset * RANGE_SIZE + 1; - IDTYPE sz = RANGE_SIZE; - LEASETYPE l = r->lease; + IDTYPE base = r->offset * RANGE_SIZE + 1; + IDTYPE sz = RANGE_SIZE; + LEASETYPE l = r->lease; struct shim_ipc_info* p = r->owner; if (r->subranges && r->subranges->map[idx - base]) { struct subrange* s = r->subranges->map[idx - base]; - base = idx; - sz = 1; - l = s->lease; - p = s->owner; + base = idx; + sz = 1; + l = s->lease; + p = s->owner; } if (!p) { @@ -444,7 +444,7 @@ static int get_ipc_range(IDTYPE idx, struct ipc_range* range, struct shim_ipc_in #if 0 /* unused */ static int del_ipc_range(IDTYPE idx) { IDTYPE off = (idx - 1) / RANGE_SIZE; - int ret = -ESRCH; + int ret = -ESRCH; lock(&range_map_lock); @@ -494,9 +494,9 @@ static int del_ipc_range(IDTYPE idx) { } int del_ipc_subrange(IDTYPE idx) { - IDTYPE off = (idx - 1) / RANGE_SIZE; + IDTYPE off = (idx - 1) / RANGE_SIZE; IDTYPE base = off * RANGE_SIZE + 1; - int ret = -ESRCH; + int ret = -ESRCH; lock(&range_map_lock); @@ -534,7 +534,7 @@ static int renew_ipc_range(IDTYPE idx, LEASETYPE* lease) { } static int renew_ipc_subrange(IDTYPE idx, LEASETYPE* lease) { - IDTYPE off = (idx - 1) / RANGE_SIZE; + IDTYPE off = (idx - 1) / RANGE_SIZE; IDTYPE base = off * RANGE_SIZE + 1; lock(&range_map_lock); @@ -604,7 +604,7 @@ IDTYPE allocate_ipc_id(IDTYPE min, IDTYPE max) { } void release_ipc_id(IDTYPE idx) { - IDTYPE off = (idx - 1) / RANGE_SIZE; + IDTYPE off = (idx - 1) / RANGE_SIZE; IDTYPE base = off * RANGE_SIZE + 1; lock(&range_map_lock); @@ -622,8 +622,8 @@ void release_ipc_id(IDTYPE idx) { if (idx < base || idx >= base + RANGE_SIZE) goto out; - IDTYPE i = (idx - base) / BITS; - IDTYPE j = (idx - base) - i * BITS; + IDTYPE i = (idx - base) / BITS; + IDTYPE j = (idx - base) - i * BITS; unsigned char* m = r->used->map + i; unsigned char f = 1U << j; if ((*m) & f) { @@ -877,7 +877,7 @@ int ipc_findns_send(bool block) { goto out; } - IDTYPE dest = cur_process.parent->vmid; + IDTYPE dest = cur_process.parent->vmid; struct shim_ipc_port* port = cur_process.parent->port; get_ipc_port(port); unlock(&cur_process.lock); @@ -893,7 +893,7 @@ int ipc_findns_send(bool block) { goto out_port; } - size_t total_msg_size = get_ipc_msg_size(0); + size_t total_msg_size = get_ipc_msg_size(0); struct shim_ipc_msg* msg = __alloca(total_msg_size); init_ipc_msg(msg, IPC_MSG_FINDNS, total_msg_size, dest); @@ -941,7 +941,7 @@ int ipc_tellns_send(struct shim_ipc_port* port, IDTYPE dest, struct shim_ipc_inf init_ipc_msg(msg, IPC_MSG_TELLNS, total_msg_size, dest); struct shim_ipc_tellns* msgin = (void*)&msg->msg; - msgin->vmid = leader->vmid; + msgin->vmid = leader->vmid; memcpy(msgin->uri, qstrgetstr(&leader->uri), leader->uri.len + 1); msg->seq = seq; @@ -1034,7 +1034,7 @@ int ipc_lease_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { debug("ipc callback from %u: IPC_MSG_LEASE(%s)\n", msg->src, msgin->uri); - IDTYPE base = 0; + IDTYPE base = 0; LEASETYPE lease = 0; int ret = alloc_ipc_range(msg->src, msgin->uri, &base, &lease); @@ -1050,7 +1050,7 @@ int ipc_lease_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { int ipc_offer_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE base, IDTYPE size, LEASETYPE lease, unsigned long seq) { int ret = 0; - size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_offer)); + size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_offer)); struct shim_ipc_msg* msg = __alloca(total_msg_size); init_ipc_msg(msg, IPC_MSG_OFFER, total_msg_size, dest); @@ -1058,7 +1058,7 @@ int ipc_offer_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE base, IDTYPE msgin->base = base; msgin->size = size; msgin->lease = lease; - msg->seq = seq; + msg->seq = seq; debug("ipc send to %u: IPC_MSG_OFFER(%u, %u, %lu)\n", port->vmid, base, size, lease); ret = send_ipc_message(msg, port); @@ -1068,8 +1068,8 @@ int ipc_offer_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE base, IDTYPE int ipc_offer_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { struct shim_ipc_offer* msgin = (void*)&msg->msg; - debug("ipc callback from %u: IPC_MSG_OFFER(%u, %u, %lu)\n", msg->src, msgin->base, - msgin->size, msgin->lease); + debug("ipc callback from %u: IPC_MSG_OFFER(%u, %u, %lu)\n", msg->src, msgin->base, msgin->size, + msgin->lease); struct shim_ipc_msg_with_ack* obj = pop_ipc_msg_with_ack(port, msg->seq); @@ -1106,7 +1106,7 @@ int ipc_offer_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { int ipc_renew_send(IDTYPE base, IDTYPE size) { IDTYPE leader; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; if ((ret = connect_ns(&leader, &port)) < 0) goto out; @@ -1116,8 +1116,8 @@ int ipc_renew_send(IDTYPE base, IDTYPE size) { init_ipc_msg(msg, IPC_MSG_RENEW, total_msg_size, leader); struct shim_ipc_renew* msgin = (void*)&msg->msg; - msgin->base = base; - msgin->size = size; + msgin->base = base; + msgin->size = size; debug("ipc send to : IPC_MSG_RENEW(%u, %u)\n", base, size); ret = send_ipc_message(msg, port); @@ -1164,7 +1164,7 @@ int ipc_renew_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { int ipc_sublease_send(IDTYPE tenant, IDTYPE idx, const char* uri, LEASETYPE* lease) { IDTYPE leader; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; if ((ret = connect_ns(&leader, &port)) < 0) goto out; @@ -1210,7 +1210,7 @@ int ipc_query_send(IDTYPE idx) { struct ipc_range range; IDTYPE leader; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; memset(&range, 0, sizeof(struct ipc_range)); if (!get_ipc_range(idx, &range, NULL)) @@ -1258,13 +1258,13 @@ int ipc_query_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { assert(!qstrempty(&range.uri)); struct ipc_ns_offered ans; - ans.base = range.base; - ans.size = range.size; - ans.lease = range.lease; - ans.owner_offset = 0; - size_t ownerdatasz = sizeof(struct ipc_ns_client) + range.uri.len; + ans.base = range.base; + ans.size = range.size; + ans.lease = range.lease; + ans.owner_offset = 0; + size_t ownerdatasz = sizeof(struct ipc_ns_client) + range.uri.len; struct ipc_ns_client* owner = __alloca(ownerdatasz); - owner->vmid = range.owner; + owner->vmid = range.owner; assert(!qstrempty(&range.uri)); memcpy(owner->uri, qstrgetstr(&range.uri), range.uri.len + 1); @@ -1276,7 +1276,7 @@ int ipc_query_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { int ipc_queryall_send(void) { IDTYPE leader; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; if ((ret = connect_ns(&leader, &port)) < 0) goto out; @@ -1307,22 +1307,22 @@ int ipc_queryall_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) size_t maxanswers = nowned + noffered + nsubed; size_t answers_cnt = 0, owners_cnt = 0, i; - struct ipc_ns_offered* answers = __alloca(sizeof(struct ipc_ns_offered) * maxanswers); + struct ipc_ns_offered* answers = __alloca(sizeof(struct ipc_ns_offered) * maxanswers); struct ipc_ns_client** ownerdata = __alloca(sizeof(struct ipc_ns_client*) * maxanswers); - size_t* ownerdatasz = __alloca(sizeof(size_t) * maxanswers); - size_t owner_offset = 0; + size_t* ownerdatasz = __alloca(sizeof(size_t) * maxanswers); + size_t owner_offset = 0; retry: LISTP_FOR_EACH_ENTRY(r, list, list) { - struct shim_ipc_info* p = r->owner; - size_t datasz = sizeof(struct ipc_ns_client) + p->uri.len; + struct shim_ipc_info* p = r->owner; + size_t datasz = sizeof(struct ipc_ns_client) + p->uri.len; struct ipc_ns_client* owner = __alloca(datasz); assert(!qstrempty(&p->uri)); owner->vmid = p->vmid; memcpy(owner->uri, qstrgetstr(&p->uri), p->uri.len + 1); - IDTYPE base = r->offset * RANGE_SIZE + 1; + IDTYPE base = r->offset * RANGE_SIZE + 1; answers[answers_cnt].base = base; answers[answers_cnt].size = RANGE_SIZE; answers[answers_cnt].lease = r->lease; @@ -1343,9 +1343,9 @@ int ipc_queryall_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) continue; struct subrange* s = r->subranges->map[i]; - p = s->owner; - datasz = sizeof(struct ipc_ns_client) + p->uri.len; - owner = __alloca(datasz); + p = s->owner; + datasz = sizeof(struct ipc_ns_client) + p->uri.len; + owner = __alloca(datasz); assert(!qstrempty(&p->uri)); owner->vmid = p->vmid; @@ -1381,13 +1381,14 @@ int ipc_queryall_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) int ipc_answer_send(struct shim_ipc_port* port, IDTYPE dest, size_t answers_cnt, struct ipc_ns_offered* answers, size_t owners_cnt, struct ipc_ns_client** ownerdata, size_t* ownerdatasz, unsigned long seq) { - size_t owner_offset = sizeof(struct shim_ipc_answer) + sizeof(struct ipc_ns_offered) * answers_cnt; + size_t owner_offset = sizeof(struct shim_ipc_answer) + + sizeof(struct ipc_ns_offered) * answers_cnt; size_t total_ownerdatasz = 0; for (size_t i = 0; i < owners_cnt; i++) { total_ownerdatasz += ownerdatasz[i]; } - size_t total_msg_size = get_ipc_msg_size(owner_offset + total_ownerdatasz); + size_t total_msg_size = get_ipc_msg_size(owner_offset + total_ownerdatasz); struct shim_ipc_msg* msg = __alloca(total_msg_size); init_ipc_msg(msg, IPC_MSG_ANSWER, total_msg_size, dest); @@ -1416,8 +1417,8 @@ int ipc_answer_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) { struct shim_ipc_answer* msgin = (void*)&msg->msg; if (msgin->answers_cnt == 1) - debug("ipc callback from %u: IPC_MSG_ANSWER([%u, %u])\n", msg->src, - msgin->answers[0].base, msgin->answers[0].size); + debug("ipc callback from %u: IPC_MSG_ANSWER([%u, %u])\n", msg->src, msgin->answers[0].base, + msgin->answers[0].size); else if (msgin->answers_cnt) debug("ipc callback from %u: IPC_MSG_ANSWER([%u, %u], ...)\n", msg->src, msgin->answers[0].base, msgin->answers[0].size); @@ -1452,7 +1453,7 @@ int get_all_pid_status(struct pid_status** status) { ipc_queryall_send(); size_t statuses_cnt = 0; - size_t bufsize = RANGE_SIZE; + size_t bufsize = RANGE_SIZE; struct pid_status* status_buf = malloc(bufsize); if (!status_buf) @@ -1476,8 +1477,8 @@ int get_all_pid_status(struct pid_status** status) { #define UNDEF_IDX ((IDTYPE)-1) next_range: - idx = UNDEF_IDX; - off = r->offset; + idx = UNDEF_IDX; + off = r->offset; base = off * RANGE_SIZE + 1; next_sub: @@ -1502,10 +1503,10 @@ int get_all_pid_status(struct pid_status** status) { } if (!p->port) { - IDTYPE type = IPC_PORT_OWNER | IPC_PORT_LISTEN; - IDTYPE owner = p->vmid; + IDTYPE type = IPC_PORT_OWNER | IPC_PORT_LISTEN; + IDTYPE owner = p->vmid; struct shim_ipc_port* port = NULL; - size_t uri_len = p->uri.len; + size_t uri_len = p->uri.len; char uri[uri_len + 1]; memcpy(&uri, qstrgetstr(&p->uri), uri_len); @@ -1665,4 +1666,3 @@ int sysv_get_key(struct sysv_key* key, bool delete) { unlock(&range_map_lock); return id; } - diff --git a/LibOS/shim/src/ipc/shim_ipc_sysv.c b/LibOS/shim/src/ipc/shim_ipc_sysv.c index 710557c7e1..ceaa8267b9 100644 --- a/LibOS/shim/src/ipc/shim_ipc_sysv.c +++ b/LibOS/shim/src/ipc/shim_ipc_sysv.c @@ -74,7 +74,7 @@ int ipc_sysv_findkey_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* po int ipc_sysv_tellkey_send(struct shim_ipc_port* port, IDTYPE dest, struct sysv_key* key, IDTYPE id, unsigned long seq) { bool owned = true; - int ret = 0; + int ret = 0; if (!dest) { if ((ret = sysv_add_key(key, id)) < 0) @@ -98,7 +98,7 @@ int ipc_sysv_tellkey_send(struct shim_ipc_port* port, IDTYPE dest, struct sysv_k msgin->key.key = key->key; msgin->key.type = key->type; msgin->id = id; - msg->seq = seq; + msg->seq = seq; debug("ipc send to %u: IPC_MSG_SYSV_TELLKEY(%lu, %u)\n", dest, key->key, id); @@ -147,7 +147,7 @@ int ipc_sysv_tellkey_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* po int ipc_sysv_delres_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE resid, enum sysv_type type) { - int ret = 0; + int ret = 0; bool owned = false; if (!port) { @@ -198,14 +198,14 @@ int ipc_sysv_delres_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* por SYSV_TYPE_STR(msgin->type)); bool owned = false; - ret = -ENOENT; + ret = -ENOENT; switch (msgin->type) { case SYSV_MSGQ: { struct shim_msg_handle* msgq = get_msg_handle_by_id(msgin->resid); if (!msgq) goto out; owned = msgq->owned; - ret = del_msg_handle(msgq); + ret = del_msg_handle(msgq); break; } case SYSV_SEM: { @@ -213,7 +213,7 @@ int ipc_sysv_delres_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* por if (!sem) goto out; owned = sem->owned; - ret = del_sem_handle(sem); + ret = del_sem_handle(sem); break; } default: @@ -280,7 +280,7 @@ int ipc_sysv_movres_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* por int ipc_sysv_msgsnd_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE msgid, long msgtype, const void* buf, size_t size, unsigned long seq) { - int ret = 0; + int ret = 0; bool owned = true; if (!dest) { @@ -349,7 +349,7 @@ int ipc_sysv_msgsnd_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* por src.port = port; src.vmid = msg->src; src.seq = msg->seq; - ret = add_sysv_msg(msgq, msgin->msgtype, size, msgin->msg, &src); + ret = add_sysv_msg(msgq, msgin->msgtype, size, msgin->msg, &src); } out: @@ -359,7 +359,7 @@ int ipc_sysv_msgsnd_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* por int ipc_sysv_msgrcv_send(IDTYPE msgid, long msgtype, int flags, void* buf, size_t size) { IDTYPE owner; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; if ((ret = connect_owner(msgid, &port, &owner)) < 0) goto out; @@ -426,8 +426,8 @@ int ipc_sysv_semop_send(IDTYPE semid, struct sembuf* sops, int nsops, unsigned l unsigned long* seq) { IDTYPE owner; struct shim_ipc_port* port = NULL; - int ret = 0; - bool waitforreply = false; + int ret = 0; + bool waitforreply = false; for (int i = 0; i < nsops; i++) if (sops[i].sem_op <= 0) { @@ -502,7 +502,7 @@ int ipc_sysv_semop_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port client.port = port; client.vmid = msg->src; client.seq = msg->seq; - ret = submit_sysv_sem(sem, msgin->sops, msgin->nsops, msgin->timeout, &client); + ret = submit_sysv_sem(sem, msgin->sops, msgin->nsops, msgin->timeout, &client); put_sem_handle(sem); out: return ret; @@ -511,7 +511,7 @@ int ipc_sysv_semop_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port int ipc_sysv_semctl_send(IDTYPE semid, int semnum, int cmd, void* vals, size_t valsize) { IDTYPE owner; struct shim_ipc_port* port = NULL; - int ret = 0; + int ret = 0; if ((ret = connect_owner(semid, &port, &owner)) < 0) goto out; diff --git a/LibOS/shim/src/shim_async.c b/LibOS/shim/src/shim_async.c index 5d7abc916a..8d46250964 100644 --- a/LibOS/shim/src/shim_async.c +++ b/LibOS/shim/src/shim_async.c @@ -7,23 +7,23 @@ * This file contains functions to add asyncronous events triggered by timer. */ -#include -#include -#include -#include -#include +#include "list.h" +#include "pal.h" +#include "shim_internal.h" +#include "shim_thread.h" +#include "shim_utils.h" #define IDLE_SLEEP_TIME 1000000 #define MAX_IDLE_CYCLES 10000 DEFINE_LIST(async_event); struct async_event { - IDTYPE caller; /* thread installing this event */ + IDTYPE caller; /* thread installing this event */ LIST_TYPE(async_event) list; void (*callback)(IDTYPE caller, void* arg); void* arg; - PAL_HANDLE object; /* handle (async IO) to wait on */ - uint64_t expire_time; /* alarm/timer to wait on */ + PAL_HANDLE object; /* handle (async IO) to wait on */ + uint64_t expire_time; /* alarm/timer to wait on */ }; DEFINE_LISTP(async_event); static LISTP_TYPE(async_event) async_list; @@ -70,11 +70,11 @@ int64_t install_async_event(PAL_HANDLE object, uint64_t time, return -ENOMEM; } - event->callback = callback; - event->arg = arg; - event->caller = get_cur_tid(); - event->object = object; - event->expire_time = time ? now + time : 0; + event->callback = callback; + event->arg = arg; + event->caller = get_cur_tid(); + event->object = object; + event->expire_time = time ? now + time : 0; lock(&async_helper_lock); @@ -184,7 +184,7 @@ static void shim_async_helper(void* arg) { PAL_FLG* ret_events = pal_events + 1 + pals_max_cnt; PAL_HANDLE install_new_event_pal = event_handle(&install_new_event); - pals[0] = install_new_event_pal; + pals[0] = install_new_event_pal; pal_events[0] = PAL_WAIT_READ; ret_events[0] = 0; @@ -203,7 +203,7 @@ static void shim_async_helper(void* arg) { } uint64_t next_expire_time = 0; - size_t pals_cnt = 0; + size_t pals_cnt = 0; struct async_event* tmp; struct async_event* n; @@ -218,7 +218,8 @@ static void shim_async_helper(void* arg) { debug("tmp_pals allocation failed\n"); goto out_err_unlock; } - PAL_FLG* tmp_pal_events = malloc(sizeof(*tmp_pal_events) * (2 + pals_max_cnt * 4)); + PAL_FLG* tmp_pal_events = + malloc(sizeof(*tmp_pal_events) * (2 + pals_max_cnt * 4)); if (!tmp_pal_events) { debug("tmp_pal_events allocation failed\n"); goto out_err_unlock; @@ -226,8 +227,10 @@ static void shim_async_helper(void* arg) { PAL_FLG* tmp_ret_events = tmp_pal_events + 1 + pals_max_cnt * 2; memcpy(tmp_pals, pals, sizeof(*tmp_pals) * (1 + pals_max_cnt)); - memcpy(tmp_pal_events, pal_events, sizeof(*tmp_pal_events) * (1 + pals_max_cnt)); - memcpy(tmp_ret_events, ret_events, sizeof(*tmp_ret_events) * (1 + pals_max_cnt)); + memcpy(tmp_pal_events, pal_events, + sizeof(*tmp_pal_events) * (1 + pals_max_cnt)); + memcpy(tmp_ret_events, ret_events, + sizeof(*tmp_ret_events) * (1 + pals_max_cnt)); pals_max_cnt *= 2; @@ -277,7 +280,8 @@ static void shim_async_helper(void* arg) { unlock(&async_helper_lock); /* wait on async IO events + install_new_event + next expiring alarm/timer */ - PAL_BOL polled = DkStreamsWaitEvents(pals_cnt + 1, pals, pal_events, ret_events, sleep_time); + PAL_BOL polled = DkStreamsWaitEvents(pals_cnt + 1, pals, pal_events, ret_events, + sleep_time); now = DkSystemTimeQuery(); if ((int64_t)now < 0) { diff --git a/LibOS/shim/src/shim_checkpoint.c b/LibOS/shim/src/shim_checkpoint.c index bd6886925b..a7d54d2da1 100644 --- a/LibOS/shim/src/shim_checkpoint.c +++ b/LibOS/shim/src/shim_checkpoint.c @@ -7,6 +7,8 @@ * This file contains implementation of checkpoint and restore. */ +#include "shim_checkpoint.h" + #include #include #include @@ -15,8 +17,6 @@ #include "list.h" #include "pal.h" #include "pal_error.h" - -#include "shim_checkpoint.h" #include "shim_fs.h" #include "shim_handle.h" #include "shim_internal.h" @@ -25,9 +25,9 @@ #include "shim_utils.h" #include "shim_vma.h" -#define CP_MMAP_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL) +#define CP_MMAP_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | VMA_INTERNAL) #define CP_MAP_ENTRY_NUM 64 -#define CP_HASH_SIZE 256 +#define CP_HASH_SIZE 256 DEFINE_LIST(cp_map_entry); struct cp_map_entry { @@ -129,10 +129,10 @@ struct shim_cp_map_entry* get_cp_map_entry(void* _map, void* addr, bool create) BEGIN_CP_FUNC(memory) { struct shim_mem_entry* entry = (void*)(base + ADD_CP_OFFSET(sizeof(*entry))); - entry->addr = obj; - entry->size = size; - entry->prot = PAL_PROT_READ | PAL_PROT_WRITE; - entry->next = store->first_mem_entry; + entry->addr = obj; + entry->size = size; + entry->prot = PAL_PROT_READ | PAL_PROT_WRITE; + entry->next = store->first_mem_entry; store->first_mem_entry = entry; store->mem_entries_cnt++; @@ -147,10 +147,10 @@ BEGIN_CP_FUNC(palhdl) { size_t off = ADD_CP_OFFSET(sizeof(struct shim_palhdl_entry)); struct shim_palhdl_entry* entry = (void*)(base + off); - entry->handle = (PAL_HANDLE) obj; - entry->uri = NULL; + entry->handle = (PAL_HANDLE)obj; + entry->uri = NULL; entry->phandle = NULL; - entry->prev = store->last_palhdl_entry; + entry->prev = store->last_palhdl_entry; store->last_palhdl_entry = entry; store->palhdl_entries_cnt++; @@ -526,8 +526,7 @@ static void* cp_alloc(void* addr, size_t size) { debug("extending checkpoint store: %p-%p (size = %lu)\n", addr, addr + size, size); if (bkeep_mmap_fixed(addr, size, PROT_READ | PROT_WRITE, - CP_MMAP_FLAGS | MAP_FIXED_NOREPLACE, - NULL, 0, "cpstore") < 0) + CP_MMAP_FLAGS | MAP_FIXED_NOREPLACE, NULL, 0, "cpstore") < 0) return NULL; } else { /* FIXME: It is unclear if the below strategy helps */ @@ -541,8 +540,8 @@ static void* cp_alloc(void* addr, size_t size) { debug("allocating checkpoint store (size = %ld, reserve = %ld)\n", size, reserve_size); - int ret = bkeep_mmap_any(size + reserve_size, PROT_READ | PROT_WRITE, CP_MMAP_FLAGS, - NULL, 0, "cpstore", &addr); + int ret = bkeep_mmap_any(size + reserve_size, PROT_READ | PROT_WRITE, CP_MMAP_FLAGS, NULL, + 0, "cpstore", &addr); if (ret < 0) { return NULL; } @@ -603,8 +602,8 @@ int create_process_and_send_checkpoint(migrate_func_t migrate_func, struct shim_ /* allocate a space for dumping the checkpoint data */ struct shim_cp_store cpstore; memset(&cpstore, 0, sizeof(cpstore)); - cpstore.alloc = cp_alloc; - cpstore.bound = CP_INIT_VMA_SIZE; + cpstore.alloc = cp_alloc; + cpstore.bound = CP_INIT_VMA_SIZE; while (1) { /* try allocating checkpoint; if allocation fails, try with smaller sizes */ @@ -760,7 +759,7 @@ int receive_checkpoint_and_restore(struct checkpoint_hdr* hdr) { if (!base) { /* address used by parent process is occupied; allocate checkpoint anywhere */ - ret = bkeep_mmap_any(ALLOC_ALIGN_UP(hdr->size), PROT_READ|PROT_WRITE, CP_MMAP_FLAGS, NULL, + ret = bkeep_mmap_any(ALLOC_ALIGN_UP(hdr->size), PROT_READ | PROT_WRITE, CP_MMAP_FLAGS, NULL, 0, "cpstore", &base); if (ret < 0) { return ret; @@ -801,7 +800,7 @@ int receive_checkpoint_and_restore(struct checkpoint_hdr* hdr) { } migrated_memory_start = (void*)mapaddr; - migrated_memory_end = (void*)mapaddr + mapsize; + migrated_memory_end = (void*)mapaddr + mapsize; ret = restore_checkpoint(hdr, (uintptr_t)base); if (ret < 0) { diff --git a/LibOS/shim/src/shim_context-x86_64.c b/LibOS/shim/src/shim_context-x86_64.c index 79b06b320d..fd8e20c87f 100644 --- a/LibOS/shim/src/shim_context-x86_64.c +++ b/LibOS/shim/src/shim_context-x86_64.c @@ -1,8 +1,6 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* - * shim_context-x86_64.c - * * This file contains code for x86-specific CPU context manipulation. */ @@ -66,6 +64,6 @@ void fixup_child_context(struct shim_regs* regs) { */ /* regs->rsp += RED_ZONE_SIZE; */ regs->rflags = regs->r11; - regs->rip = regs->rcx; + regs->rip = regs->rcx; } } diff --git a/LibOS/shim/src/shim_debug.c b/LibOS/shim/src/shim_debug.c index b372673dc4..2499e33ef2 100644 --- a/LibOS/shim/src/shim_debug.c +++ b/LibOS/shim/src/shim_debug.c @@ -2,20 +2,18 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_debug.c - * - * This file contains codes for registering libraries to GDB. + * This file contains code for registering libraries to GDB. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_tcb.h" +#include "shim_vma.h" #ifndef DEBUG diff --git a/LibOS/shim/src/shim_init.c b/LibOS/shim/src/shim_init.c index 4d34966e04..4cb281bdf5 100644 --- a/LibOS/shim/src/shim_init.c +++ b/LibOS/shim/src/shim_init.c @@ -7,31 +7,29 @@ * This file contains entry and exit functions of library OS. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include "hex.h" #include "pal.h" #include "pal_debug.h" #include "pal_error.h" - -#include -#include -#include +#include "shim_checkpoint.h" +#include "shim_context.h" +#include "shim_defs.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_table.h" +#include "shim_tcb.h" +#include "shim_thread.h" +#include "shim_vdso.h" +#include "shim_vma.h" static_assert(sizeof(shim_tcb_t) <= PAL_LIBOS_TCB_SIZE, - "shim_tcb_t does not fit into PAL_TCB; " - "please increase PAL_LIBOS_TCB_SIZE"); + "shim_tcb_t does not fit into PAL_TCB; please increase PAL_LIBOS_TCB_SIZE"); size_t g_pal_alloc_align; @@ -41,12 +39,11 @@ size_t g_pal_alloc_align; const unsigned int glibc_version = GLIBC_VERSION; -static void handle_failure (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context) -{ +static void handle_failure(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { __UNUSED(event); __UNUSED(context); - if ((arg <= PAL_ERROR_NATIVE_COUNT) || (arg >= PAL_ERROR_CRYPTO_START && - arg <= PAL_ERROR_CRYPTO_END)) + if ((arg <= PAL_ERROR_NATIVE_COUNT) || + (arg >= PAL_ERROR_CRYPTO_START && arg <= PAL_ERROR_CRYPTO_END)) shim_get_tcb()->pal_errno = arg; else shim_get_tcb()->pal_errno = PAL_ERROR_DENIED; @@ -57,48 +54,45 @@ noreturn void __abort(void) { shim_clean_and_exit(-ENOTRECOVERABLE); } -void warn (const char *format, ...) -{ +void warn(const char* format, ...) { va_list args; - va_start (args, format); + va_start(args, format); __SYS_VPRINTF(format, args); - va_end (args); + va_end(args); } -static int pal_errno_to_unix_errno [PAL_ERROR_NATIVE_COUNT + 1] = { - /* reserved */ 0, - /* PAL_ERROR_NOTIMPLEMENTED */ ENOSYS, - /* PAL_ERROR_NOTDEFINED */ ENOSYS, - /* PAL_ERROR_NOTSUPPORT */ EACCES, - /* PAL_ERROR_INVAL */ EINVAL, - /* PAL_ERROR_TOOLONG */ ENAMETOOLONG, - /* PAL_ERROR_DENIED */ EACCES, - /* PAL_ERROR_BADHANDLE */ EFAULT, - /* PAL_ERROR_STREAMEXIST */ EEXIST, - /* PAL_ERROR_STREAMNOTEXIST */ ENOENT, - /* PAL_ERROR_STREAMISFILE */ ENOTDIR, - /* PAL_ERROR_STREAMISDIR */ EISDIR, - /* PAL_ERROR_STREAMISDEVICE */ ESPIPE, - /* PAL_ERROR_INTERRUPTED */ EINTR, - /* PAL_ERROR_OVERFLOW */ EFAULT, - /* PAL_ERROR_BADADDR */ EFAULT, - /* PAL_ERROR_NOMEM */ ENOMEM, - /* PAL_ERROR_NOTKILLABLE */ EACCES, - /* PAL_ERROR_INCONSIST */ EFAULT, - /* PAL_ERROR_TRYAGAIN */ EAGAIN, - /* PAL_ERROR_ENDOFSTREAM */ 0, - /* PAL_ERROR_NOTSERVER */ EINVAL, - /* PAL_ERROR_NOTCONNECTION */ ENOTCONN, - /* PAL_ERROR_CONNFAILED */ ECONNRESET, - /* PAL_ERROR_ADDRNOTEXIST */ EADDRNOTAVAIL, - /* PAL_ERROR_AFNOSUPPORT */ EAFNOSUPPORT, - /* PAL_ERROR_CONNFAILED_PIPE */ EPIPE, - }; - -long convert_pal_errno (long err) -{ - return (err >= 0 && err <= PAL_ERROR_NATIVE_COUNT) ? - pal_errno_to_unix_errno[err] : EACCES; +static int pal_errno_to_unix_errno[PAL_ERROR_NATIVE_COUNT + 1] = { + [0] = 0, + [PAL_ERROR_NOTIMPLEMENTED] = ENOSYS, + [PAL_ERROR_NOTDEFINED] = ENOSYS, + [PAL_ERROR_NOTSUPPORT] = EACCES, + [PAL_ERROR_INVAL] = EINVAL, + [PAL_ERROR_TOOLONG] = ENAMETOOLONG, + [PAL_ERROR_DENIED] = EACCES, + [PAL_ERROR_BADHANDLE] = EFAULT, + [PAL_ERROR_STREAMEXIST] = EEXIST, + [PAL_ERROR_STREAMNOTEXIST] = ENOENT, + [PAL_ERROR_STREAMISFILE] = ENOTDIR, + [PAL_ERROR_STREAMISDIR] = EISDIR, + [PAL_ERROR_STREAMISDEVICE] = ESPIPE, + [PAL_ERROR_INTERRUPTED] = EINTR, + [PAL_ERROR_OVERFLOW] = EFAULT, + [PAL_ERROR_BADADDR] = EFAULT, + [PAL_ERROR_NOMEM] = ENOMEM, + [PAL_ERROR_NOTKILLABLE] = EACCES, + [PAL_ERROR_INCONSIST] = EFAULT, + [PAL_ERROR_TRYAGAIN] = EAGAIN, + [PAL_ERROR_ENDOFSTREAM] = 0, + [PAL_ERROR_NOTSERVER] = EINVAL, + [PAL_ERROR_NOTCONNECTION] = ENOTCONN, + [PAL_ERROR_CONNFAILED] = ECONNRESET, + [PAL_ERROR_ADDRNOTEXIST] = EADDRNOTAVAIL, + [PAL_ERROR_AFNOSUPPORT] = EAFNOSUPPORT, + [PAL_ERROR_CONNFAILED_PIPE] = EPIPE, +}; + +long convert_pal_errno(long err) { + return (err >= 0 && err <= PAL_ERROR_NATIVE_COUNT) ? pal_errno_to_unix_errno[err] : EACCES; } /*! @@ -150,8 +144,8 @@ unsigned long parse_int (const char * str) return num; } -void * migrated_memory_start; -void * migrated_memory_end; +void* migrated_memory_start; +void* migrated_memory_end; const char** migrated_argv __attribute_migratable; const char** migrated_envp __attribute_migratable; @@ -160,7 +154,7 @@ const char** migrated_envp __attribute_migratable; * initialization and is used in __load_interp_object() to search for ELF * program interpreter in specific paths. Once allocated, its memory is * never freed or updated. */ -char ** library_paths = NULL; +char** library_paths = NULL; struct shim_lock __master_lock; bool lock_enabled; @@ -216,15 +210,19 @@ static int populate_stack(void* stack, size_t stack_size, const char** argv, con void* stack_low_addr = stack; void* stack_high_addr = stack + stack_size; -#define ALLOCATE_FROM_HIGH_ADDR(size) \ - ({ if ((stack_high_addr -= (size)) < stack_low_addr) \ - return -ENOMEM; \ - stack_high_addr; }) +#define ALLOCATE_FROM_HIGH_ADDR(size) \ + ({ \ + if ((stack_high_addr -= (size)) < stack_low_addr) \ + return -ENOMEM; \ + stack_high_addr; \ + }) -#define ALLOCATE_FROM_LOW_ADDR(size) \ - ({ if ((stack_low_addr += (size)) > stack_high_addr) \ - return -ENOMEM; \ - stack_low_addr - (size); }) +#define ALLOCATE_FROM_LOW_ADDR(size) \ + ({ \ + if ((stack_low_addr += (size)) > stack_high_addr) \ + return -ENOMEM; \ + stack_low_addr - (size); \ + }) /* create stack layout as follows for ld.so: * @@ -348,8 +346,8 @@ int init_stack(const char** argv, const char** envp, const char*** out_argp, return -ENOMEM; /* if there are argv/envp inherited from parent, use them */ - argv = migrated_argv ? : argv; - envp = migrated_envp ? : envp; + argv = migrated_argv ?: argv; + envp = migrated_envp ?: envp; int ret = populate_stack(stack, stack_size, argv, envp, out_argp, out_auxv); if (ret < 0) @@ -362,26 +360,25 @@ int init_stack(const char** argv, const char** envp, const char*** out_argp, } static int read_environs(const char** envp) { - for (const char ** e = envp ; *e ; e++) { + for (const char** e = envp; *e; e++) { if (strstartswith_static(*e, "LD_LIBRARY_PATH=")) { /* populate library_paths with entries from LD_LIBRARY_PATH envvar */ - const char * s = *e + static_strlen("LD_LIBRARY_PATH="); - size_t npaths = 2; // One for the first entry, one for the last - // NULL. - for (const char * tmp = s ; *tmp ; tmp++) + const char* s = *e + static_strlen("LD_LIBRARY_PATH="); + size_t npaths = 2; // One for the first entry, one for the last NULL. + for (const char* tmp = s; *tmp; tmp++) if (*tmp == ':') npaths++; - char** paths = malloc(sizeof(const char *) * - npaths); + char** paths = malloc(sizeof(const char*) * npaths); if (!paths) return -ENOMEM; size_t cnt = 0; while (*s) { - const char * next; - for (next = s ; *next && *next != ':' ; next++); + const char* next; + for (next = s; *next && *next != ':'; next++) + ; size_t len = next - s; - char * str = malloc(len + 1); + char* str = malloc(len + 1); if (!str) { for (size_t i = 0; i < cnt; i++) free(paths[i]); @@ -405,19 +402,17 @@ static int read_environs(const char** envp) { return 0; } -struct config_store * root_config = NULL; +struct config_store* root_config = NULL; -static void * __malloc (size_t size) -{ +static void* __malloc(size_t size) { return malloc(size); } -static void __free (void * mem) -{ +static void __free(void* mem) { free(mem); } -int init_manifest (PAL_HANDLE manifest_handle) { +int init_manifest(PAL_HANDLE manifest_handle) { int ret = 0; void* addr = NULL; size_t size = 0, map_size = 0; @@ -458,10 +453,10 @@ int init_manifest (PAL_HANDLE manifest_handle) { new_root_config->raw_data = addr; new_root_config->raw_size = size; - new_root_config->malloc = __malloc; - new_root_config->free = __free; + new_root_config->malloc = __malloc; + new_root_config->free = __free; - const char * errstring = "Unexpected error"; + const char* errstring = "Unexpected error"; if ((ret = read_config(new_root_config, NULL, &errstring)) < 0) { SYS_PRINTF("Unable to read manifest file: %s\n", errstring); @@ -487,22 +482,22 @@ int init_manifest (PAL_HANDLE manifest_handle) { return ret; } -#define CALL_INIT(func, args ...) func(args) +#define CALL_INIT(func, args...) func(args) -#define RUN_INIT(func, ...) \ - do { \ - int _err = CALL_INIT(func, ##__VA_ARGS__); \ - if (_err < 0) { \ - SYS_PRINTF("shim_init() in " #func " (%d)\n", _err); \ - DkProcessExit(_err); \ - } \ +#define RUN_INIT(func, ...) \ + do { \ + int _err = CALL_INIT(func, ##__VA_ARGS__); \ + if (_err < 0) { \ + SYS_PRINTF("shim_init() in " #func " (%d)\n", _err); \ + DkProcessExit(_err); \ + } \ } while (0) extern PAL_HANDLE thread_start_event; noreturn void* shim_init(int argc, void* args) { debug_handle = PAL_CB(debug_stream); - cur_process.vmid = (IDTYPE) PAL_CB(process_id); + cur_process.vmid = (IDTYPE)PAL_CB(process_id); /* create the initial TCB, shim can not be run without a tcb */ shim_tcb_init(); @@ -598,8 +593,8 @@ noreturn void* shim_init(int argc, void* args) { if (thread_start_event) DkEventSet(thread_start_event); - shim_tcb_t * cur_tcb = shim_get_tcb(); - struct shim_thread * cur_thread = (struct shim_thread *) cur_tcb->tp; + shim_tcb_t* cur_tcb = shim_get_tcb(); + struct shim_thread* cur_thread = (struct shim_thread*)cur_tcb->tp; if (cur_tcb->context.regs && shim_context_get_sp(&cur_tcb->context)) { vdso_map_migrate(); @@ -611,13 +606,9 @@ noreturn void* shim_init(int argc, void* args) { shim_do_exit(0); } -static int create_unique (int (*mkname) (char *, size_t, void *), - int (*create) (const char *, void *), - int (*output) (char *, size_t, const void *, - struct shim_qstr *), - char * name, size_t size, void * id, void * obj, - struct shim_qstr * qstr) -{ +static int create_unique(int (*mkname)(char*, size_t, void*), int (*create)(const char*, void*), + int (*output)(char*, size_t, const void*, struct shim_qstr*), char* name, + size_t size, void* id, void* obj, struct shim_qstr* qstr) { int ret, len; while (1) { len = mkname(name, size, id); @@ -636,7 +627,7 @@ static int create_unique (int (*mkname) (char *, size_t, void *), } static int get_256b_random_hex_string(char* buf, size_t size) { - char random[32]; /* 256-bit random value, sufficiently crypto secure */ + char random[32]; /* 256-bit random value, sufficiently crypto secure */ if (size < sizeof(random) * 2 + 1) return -ENOMEM; @@ -717,8 +708,7 @@ int create_pipe(char* name, char* uri, size_t size, PAL_HANDLE* hdl, struct shim return ret; } -static int name_path (char * path, size_t size, void * id) -{ +static int name_path(char* path, size_t size, void* id) { unsigned int suffix; int prefix_len = strlen(path); size_t len; @@ -728,13 +718,12 @@ static int name_path (char * path, size_t size, void * id) len = snprintf(path + prefix_len, size - prefix_len, "%08x", suffix); if (len == size) return -ERANGE; - *((unsigned int *) id) = suffix; + *((unsigned int*)id) = suffix; return prefix_len + len; } -static int open_dir (const char * path, void * obj) -{ - struct shim_handle * dir = NULL; +static int open_dir(const char* path, void* obj) { + struct shim_handle* dir = NULL; if (obj) { dir = get_new_handle(); @@ -742,19 +731,17 @@ static int open_dir (const char * path, void * obj) return -ENOMEM; } - int ret = open_namei(dir, NULL, path, O_CREAT|O_EXCL|O_DIRECTORY, 0700, - NULL); + int ret = open_namei(dir, NULL, path, O_CREAT | O_EXCL | O_DIRECTORY, 0700, NULL); if (ret < 0) return ret = -EEXIST ? 1 : ret; if (obj) - *((struct shim_handle **) obj) = dir; + *((struct shim_handle**)obj) = dir; return 0; } -static int open_file (const char * path, void * obj) -{ - struct shim_handle * file = NULL; +static int open_file(const char* path, void* obj) { + struct shim_handle* file = NULL; if (obj) { file = get_new_handle(); @@ -762,31 +749,24 @@ static int open_file (const char * path, void * obj) return -ENOMEM; } - int ret = open_namei(file, NULL, path, O_CREAT|O_EXCL|O_RDWR, 0600, - NULL); + int ret = open_namei(file, NULL, path, O_CREAT | O_EXCL | O_RDWR, 0600, NULL); if (ret < 0) return ret = -EEXIST ? 1 : ret; if (obj) - *((struct shim_handle **) obj) = file; + *((struct shim_handle**)obj) = file; return 0; } -static int open_pal_handle (const char * uri, void * obj) -{ +static int open_pal_handle(const char* uri, void* obj) { PAL_HANDLE hdl; if (strstartswith_static(uri, URI_PREFIX_DEV)) - hdl = DkStreamOpen(uri, 0, - PAL_SHARE_OWNER_X|PAL_SHARE_OWNER_W| - PAL_SHARE_OWNER_R, - PAL_CREATE_TRY|PAL_CREATE_ALWAYS, - 0); + hdl = DkStreamOpen(uri, 0, PAL_SHARE_OWNER_X | PAL_SHARE_OWNER_W | PAL_SHARE_OWNER_R, + PAL_CREATE_TRY | PAL_CREATE_ALWAYS, 0); else - hdl = DkStreamOpen(uri, PAL_ACCESS_RDWR, - PAL_SHARE_OWNER_W|PAL_SHARE_OWNER_R, - PAL_CREATE_TRY|PAL_CREATE_ALWAYS, - 0); + hdl = DkStreamOpen(uri, PAL_ACCESS_RDWR, PAL_SHARE_OWNER_W | PAL_SHARE_OWNER_R, + PAL_CREATE_TRY | PAL_CREATE_ALWAYS, 0); if (!hdl) { if (PAL_NATIVE_ERRNO() == PAL_ERROR_STREAMEXIST) @@ -796,7 +776,7 @@ static int open_pal_handle (const char * uri, void * obj) } if (obj) { - *((PAL_HANDLE *) obj) = hdl; + *((PAL_HANDLE*)obj) = hdl; } else { DkObjectClose(hdl); } @@ -804,9 +784,7 @@ static int open_pal_handle (const char * uri, void * obj) return 0; } -static int output_path (char * path, size_t size, const void * id, - struct shim_qstr * qstr) -{ +static int output_path(char* path, size_t size, const void* id, struct shim_qstr* qstr) { size_t len = strlen(path); // API compatibility __UNUSED(size); @@ -817,9 +795,7 @@ static int output_path (char * path, size_t size, const void * id, return len; } -int create_dir (const char * prefix, char * path, size_t size, - struct shim_handle ** hdl) -{ +int create_dir(const char* prefix, char* path, size_t size, struct shim_handle** hdl) { unsigned int suffix; if (prefix) { @@ -829,13 +805,10 @@ int create_dir (const char * prefix, char * path, size_t size, memcpy(path, prefix, len + 1); } - return create_unique(&name_path, &open_dir, &output_path, path, size, - &suffix, hdl, NULL); + return create_unique(&name_path, &open_dir, &output_path, path, size, &suffix, hdl, NULL); } -int create_file (const char * prefix, char * path, size_t size, - struct shim_handle ** hdl) -{ +int create_file(const char* prefix, char* path, size_t size, struct shim_handle** hdl) { unsigned int suffix; if (prefix) { @@ -845,13 +818,10 @@ int create_file (const char * prefix, char * path, size_t size, memcpy(path, prefix, len + 1); } - return create_unique(&name_path, &open_file, &output_path, path, size, - &suffix, hdl, NULL); + return create_unique(&name_path, &open_file, &output_path, path, size, &suffix, hdl, NULL); } -int create_handle (const char * prefix, char * uri, size_t size, - PAL_HANDLE * hdl, unsigned int * id) -{ +int create_handle(const char* prefix, char* uri, size_t size, PAL_HANDLE* hdl, unsigned int* id) { unsigned int suffix; if (prefix) { @@ -861,8 +831,8 @@ int create_handle (const char * prefix, char * uri, size_t size, memcpy(uri, prefix, len + 1); } - return create_unique(&name_path, &open_pal_handle, &output_path, uri, size, - id ? : &suffix, hdl, NULL); + return create_unique(&name_path, &open_pal_handle, &output_path, uri, size, id ?: &suffix, hdl, + NULL); } noreturn void shim_clean_and_exit(int exit_code) { @@ -877,7 +847,7 @@ noreturn void shim_clean_and_exit(int exit_code) { store_all_msg_persist(); del_all_ipc_ports(); - if (shim_stdio && shim_stdio != (PAL_HANDLE) -1) + if (shim_stdio && shim_stdio != (PAL_HANDLE)-1) DkObjectClose(shim_stdio); shim_stdio = NULL; @@ -892,16 +862,16 @@ noreturn void shim_clean_and_exit(int exit_code) { DkProcessExit(cur_process.exit_code); } -int message_confirm (const char * message, const char * options) -{ +int message_confirm(const char* message, const char* options) { char answer; int noptions = strlen(options); - char * option_str = __alloca(noptions * 2 + 3), * str = option_str; + char* option_str = __alloca(noptions * 2 + 3); + char* str = option_str; int ret = 0; *(str++) = ' '; *(str++) = '['; - for (int i = 0 ; i < noptions ; i++) { + for (int i = 0; i < noptions; i++) { *(str++) = options[i]; *(str++) = '/'; } diff --git a/LibOS/shim/src/shim_malloc.c b/LibOS/shim/src/shim_malloc.c index 35c0013199..453b643dae 100644 --- a/LibOS/shim/src/shim_malloc.c +++ b/LibOS/shim/src/shim_malloc.c @@ -12,12 +12,13 @@ */ #include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_debug.h" +#include "shim_checkpoint.h" +#include "shim_internal.h" +#include "shim_utils.h" +#include "shim_vma.h" static struct shim_lock slab_mgr_lock; @@ -28,7 +29,7 @@ static struct shim_lock slab_mgr_lock; #define SLAB_CANARY #define STARTUP_SIZE 16 -#include +#include "slabmgr.h" static SLAB_MGR slab_mgr = NULL; @@ -145,7 +146,6 @@ void* realloc(void* ptr, size_t new_size) { EXTERN_ALIAS(realloc); #endif - // Copies data from `mem` to a newly allocated buffer of a specified size. void* malloc_copy(const void* mem, size_t size) { void* buff = malloc(size); diff --git a/LibOS/shim/src/shim_object.c b/LibOS/shim/src/shim_object.c index 07e8acaca9..c4558042d5 100644 --- a/LibOS/shim/src/shim_object.c +++ b/LibOS/shim/src/shim_object.c @@ -1,13 +1,12 @@ -#include -#include +#include "pal.h" +#include "shim_internal.h" int object_wait_with_retry(PAL_HANDLE handle) { PAL_BOL ret; do { ret = DkSynchronizationObjectWait(handle, NO_TIMEOUT); - } while (!ret && - (PAL_NATIVE_ERRNO() == PAL_ERROR_INTERRUPTED - || PAL_NATIVE_ERRNO() == PAL_ERROR_TRYAGAIN)); + } while (!ret && (PAL_NATIVE_ERRNO() == PAL_ERROR_INTERRUPTED || + PAL_NATIVE_ERRNO() == PAL_ERROR_TRYAGAIN)); if (!ret) { debug("waiting on %p resulted in error %s", handle, pal_strerror(PAL_NATIVE_ERRNO())); diff --git a/LibOS/shim/src/shim_parser.c b/LibOS/shim/src/shim_parser.c index 9c65b12272..7a5a94d499 100644 --- a/LibOS/shim/src/shim_parser.c +++ b/LibOS/shim/src/shim_parser.c @@ -2,8 +2,6 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * shim_parser.c - * * This file contains code for parsing system call arguments for debug purpose. */ @@ -24,7 +22,6 @@ #include "api.h" #include "pal.h" #include "pal_error.h" - #include "shim_internal.h" #include "shim_table.h" #include "shim_tcb.h" diff --git a/LibOS/shim/src/shim_syscalls.c b/LibOS/shim/src/shim_syscalls.c index ad6d79f69c..9db24529d3 100644 --- a/LibOS/shim/src/shim_syscalls.c +++ b/LibOS/shim/src/shim_syscalls.c @@ -13,14 +13,15 @@ #endif #include #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_tcb.h" +#include "shim_thread.h" +#include "shim_unistd.h" +#include "shim_utils.h" ////////////////////////////////////////////////// // Mappings from system calls to shim calls @@ -527,8 +528,8 @@ DEFINE_SHIM_SYSCALL(sched_setparam, 2, shim_do_sched_setparam, int, pid_t, pid, DEFINE_SHIM_SYSCALL(sched_getparam, 2, shim_do_sched_getparam, int, pid_t, pid, struct __kernel_sched_param*, param) -DEFINE_SHIM_SYSCALL(sched_setscheduler, 3, shim_do_sched_setscheduler, int, pid_t, pid, - int, policy, struct __kernel_sched_param*, param) +DEFINE_SHIM_SYSCALL(sched_setscheduler, 3, shim_do_sched_setscheduler, int, pid_t, pid, int, policy, + struct __kernel_sched_param*, param) DEFINE_SHIM_SYSCALL(sched_getscheduler, 1, shim_do_sched_getscheduler, int, pid_t, pid) @@ -648,15 +649,15 @@ SHIM_SYSCALL_RETURN_ENOSYS(nfsservctl, 3, int, int, cmd, struct nfsctl_arg*, arg this? */ /* shim_afs_syscall MISSING - TODO: afs_syscall is not implemented (kernel always returns -ENOSYS), how should we handle + TODO: afs_syscall is not implemented (kernel always returns -ENOSYS), how should we handle this? */ /* shim_tuxcall MISSING - TODO: tuxcall syscall is not implemented (kernel always returns -ENOSYS), how should we handle + TODO: tuxcall syscall is not implemented (kernel always returns -ENOSYS), how should we handle this? */ /* shim_security MISSING - TODO: security syscall is not implemented (kernel always returns -ENOSYS), how should we handle + TODO: security syscall is not implemented (kernel always returns -ENOSYS), how should we handle this? */ /* gettid: sys/shim_getpid.c */ @@ -812,8 +813,8 @@ DEFINE_SHIM_SYSCALL(mbind, 6, shim_do_mbind, int, void*, start, unsigned long, l SHIM_SYSCALL_RETURN_ENOSYS(set_mempolicy, 3, int, int, mode, unsigned long*, nmask, unsigned long, maxnode) -SHIM_SYSCALL_RETURN_ENOSYS(get_mempolicy, 5, int, int*, policy, unsigned long*, nmask, unsigned long, - maxnode, unsigned long, addr, unsigned long, flags) +SHIM_SYSCALL_RETURN_ENOSYS(get_mempolicy, 5, int, int*, policy, unsigned long*, nmask, + unsigned long, maxnode, unsigned long, addr, unsigned long, flags) SHIM_SYSCALL_RETURN_ENOSYS(mq_open, 4, int, const char*, name, int, oflag, mode_t, mode, struct __kernel_mq_attr*, attr) @@ -968,15 +969,15 @@ SHIM_SYSCALL_RETURN_ENOSYS(timerfd_settime, 4, int, int, ufd, int, flags, SHIM_SYSCALL_RETURN_ENOSYS(timerfd_gettime, 2, int, int, ufd, struct __kernel_itimerspec*, otmr) /* accept4: sys/shim_socket.c */ -DEFINE_SHIM_SYSCALL(accept4, 4, shim_do_accept4, int, int, sockfd, struct sockaddr*, addr, - int*, addrlen, int, flags) +DEFINE_SHIM_SYSCALL(accept4, 4, shim_do_accept4, int, int, sockfd, struct sockaddr*, addr, int*, + addrlen, int, flags) SHIM_SYSCALL_RETURN_ENOSYS(signalfd4, 4, int, int, ufd, __sigset_t*, user_mask, size_t, sizemask, int, flags) DEFINE_SHIM_SYSCALL(eventfd, 1, shim_do_eventfd, int, unsigned int, count) -DEFINE_SHIM_SYSCALL (eventfd2, 2, shim_do_eventfd2, int, unsigned int, count, int, flags) +DEFINE_SHIM_SYSCALL(eventfd2, 2, shim_do_eventfd2, int, unsigned int, count, int, flags) /* epoll_create1: sys/shim_epoll.c */ DEFINE_SHIM_SYSCALL(epoll_create1, 1, shim_do_epoll_create1, int, int, flags) diff --git a/LibOS/shim/src/shim_table-x86_64.c b/LibOS/shim/src/shim_table-x86_64.c index 0676fb3bf1..d10afda7dd 100644 --- a/LibOS/shim/src/shim_table-x86_64.c +++ b/LibOS/shim/src/shim_table-x86_64.c @@ -7,8 +7,8 @@ * This file contains the system call table used by application libraries. */ -#include -#include +#include "shim_internal.h" +#include "shim_table.h" void debug_unsupp(int num) { debug("Unsupported system call %d\n", num); diff --git a/LibOS/shim/src/sys/shim_access.c b/LibOS/shim/src/sys/shim_access.c index 343d3f0edd..3ba1aa6854 100644 --- a/LibOS/shim/src/sys/shim_access.c +++ b/LibOS/shim/src/sys/shim_access.c @@ -10,13 +10,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" int shim_do_access(const char* file, mode_t mode) { if (!file) diff --git a/LibOS/shim/src/sys/shim_alarm.c b/LibOS/shim/src/sys/shim_alarm.c index da2b652923..f9a9249c6f 100644 --- a/LibOS/shim/src/sys/shim_alarm.c +++ b/LibOS/shim/src/sys/shim_alarm.c @@ -28,7 +28,7 @@ int shim_do_alarm(unsigned int seconds) { return ret; uint64_t usecs_left = (uint64_t)ret; - int secs = usecs_left / 1000000ULL; + int secs = usecs_left / 1000000ULL; if (usecs_left % 1000000ULL) secs++; return secs; @@ -74,16 +74,18 @@ int shim_do_setitimer(int which, struct __kernel_itimerval* value, uint64_t setup_time = DkSystemTimeQuery(); uint64_t next_value = value->it_value.tv_sec * (uint64_t)1000000 + value->it_value.tv_usec; - uint64_t next_reset = value->it_interval.tv_sec * (uint64_t)1000000 + value->it_interval.tv_usec; + uint64_t next_reset = value->it_interval.tv_sec * (uint64_t)1000000 + + value->it_interval.tv_usec; MASTER_LOCK(); - uint64_t current_timeout = - real_itimer.timeout > setup_time ? real_itimer.timeout - setup_time : 0; + uint64_t current_timeout = real_itimer.timeout > setup_time + ? real_itimer.timeout - setup_time + : 0; uint64_t current_reset = real_itimer.reset; - int64_t ret = - install_async_event(NULL, next_value, &signal_itimer, (void*)(setup_time + next_value)); + int64_t ret = install_async_event(NULL, next_value, &signal_itimer, + (void*)(setup_time + next_value)); if (ret < 0) { MASTER_UNLOCK(); @@ -117,8 +119,9 @@ int shim_do_getitimer(int which, struct __kernel_itimerval* value) { uint64_t setup_time = DkSystemTimeQuery(); MASTER_LOCK(); - uint64_t current_timeout = - real_itimer.timeout > setup_time ? real_itimer.timeout - setup_time : 0; + uint64_t current_timeout = real_itimer.timeout > setup_time + ? real_itimer.timeout - setup_time + : 0; uint64_t current_reset = real_itimer.reset; MASTER_UNLOCK(); diff --git a/LibOS/shim/src/sys/shim_brk.c b/LibOS/shim/src/sys/shim_brk.c index 958f40eb41..e522f0202a 100644 --- a/LibOS/shim/src/sys/shim_brk.c +++ b/LibOS/shim/src/sys/shim_brk.c @@ -25,7 +25,7 @@ static struct { char* brk_end; } brk_region; -static struct shim_lock brk_lock = { .lock = NULL }; +static struct shim_lock brk_lock = {.lock = NULL}; int init_brk_region(void* brk_start, size_t data_segment_size) { if (!create_lock(&brk_lock)) { @@ -71,7 +71,7 @@ int init_brk_region(void* brk_start, size_t data_segment_size) { /* Linux randomizes brk at offset from 0 to 0x2000000 from main executable data section * https://elixir.bootlin.com/linux/v5.6.3/source/arch/x86/kernel/process.c#L914 */ offset %= MIN((size_t)0x2000000, (size_t)((char*)PAL_CB(user_address.end) - - brk_max_size - (char*)brk_start)); + brk_max_size - (char*)brk_start)); offset = ALLOC_ALIGN_DOWN(offset); } @@ -101,9 +101,9 @@ int init_brk_region(void* brk_start, size_t data_segment_size) { } } - brk_region.brk_start = brk_start; - brk_region.brk_current = brk_region.brk_start; - brk_region.brk_end = (char*)brk_start + brk_max_size; + brk_region.brk_start = brk_start; + brk_region.brk_current = brk_region.brk_start; + brk_region.brk_end = (char*)brk_start + brk_max_size; brk_region.data_segment_size = data_segment_size; set_rlimit_cur(RLIMIT_DATA, brk_max_size + data_segment_size); @@ -124,9 +124,9 @@ void reset_brk(void) { DkVirtualMemoryFree(brk_region.brk_start, allocated_size); bkeep_remove_tmp_vma(tmp_vma); - brk_region.brk_start = NULL; - brk_region.brk_current = NULL; - brk_region.brk_end = NULL; + brk_region.brk_start = NULL; + brk_region.brk_current = NULL; + brk_region.brk_end = NULL; brk_region.data_segment_size = 0; unlock(&brk_lock); @@ -175,8 +175,7 @@ void* shim_do_brk(void* _brk) { assert(size); if (bkeep_mmap_fixed(brk_current, size, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, - NULL, 0, "heap") < 0) { + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, NULL, 0, "heap") < 0) { goto out; } diff --git a/LibOS/shim/src/sys/shim_clone.c b/LibOS/shim/src/sys/shim_clone.c index 16cbef01cc..60afb62264 100644 --- a/LibOS/shim/src/sys/shim_clone.c +++ b/LibOS/shim/src/sys/shim_clone.c @@ -8,25 +8,23 @@ * implemented yet.) */ +#include +#include +#include +#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" #include "shim_context.h" #include "shim_fork.h" -#include "shim_types.h" #include "shim_internal.h" #include "shim_table.h" #include "shim_thread.h" +#include "shim_types.h" #include "shim_utils.h" -#include "shim_checkpoint.h" - -#include "pal.h" -#include "pal_error.h" - -#include -#include -#include -#include -void __attribute__((weak)) syscall_wrapper_after_syscalldb(void) -{ +void __attribute__((weak)) syscall_wrapper_after_syscalldb(void) { /* * workaround for linking. * syscalldb.S is excluded for libsysdb_debug.so so it fails to link @@ -74,11 +72,10 @@ void __attribute__((weak)) syscall_wrapper_after_syscalldb(void) * 7.In the wrapper function ,we just do the stack switch to user * Provided stack and execute the user Provided function. */ -static int clone_implementation_wrapper(struct shim_clone_args * arg) -{ - //The child thread created by PAL is now running on the - //PAL allocated stack. We need to switch the stack to use - //the user provided stack. +static int clone_implementation_wrapper(struct shim_clone_args* arg) { + // The child thread created by PAL is now running on the + // PAL allocated stack. We need to switch the stack to use + // the user provided stack. /* We acquired ownership of arg->thread from the caller, hence there is * no need to call get_thread. */ @@ -88,7 +85,7 @@ static int clone_implementation_wrapper(struct shim_clone_args * arg) shim_tcb_init(); set_cur_thread(my_thread); update_fs_base(arg->fs_base); - shim_tcb_t * tcb = my_thread->shim_tcb; + shim_tcb_t* tcb = my_thread->shim_tcb; /* only now we can call LibOS/PAL functions because they require a set-up TCB; * do not move the below functions before shim_tcb_init/set_cur_thread()! */ @@ -109,7 +106,7 @@ static int clone_implementation_wrapper(struct shim_clone_args * arg) my_thread->set_child_tid = NULL; } - void * stack = arg->stack; + void* stack = arg->stack; struct shim_vma_info vma_info; if (lookup_vma(ALLOC_ALIGN_DOWN_PTR(stack), &vma_info) < 0) { @@ -130,11 +127,11 @@ static int clone_implementation_wrapper(struct shim_clone_args * arg) /***** From here down, we are switching to the user-provided stack ****/ - //user_stack_addr[0] ==> user provided function address - //user_stack_addr[1] ==> arguments to user provided function. + // user_stack_addr[0] ==> user provided function address + // user_stack_addr[1] ==> arguments to user provided function. - debug("child swapping stack to %p return 0x%lx: %d\n", - stack, shim_regs_get_ip(®s), my_thread->tid); + debug("child swapping stack to %p return 0x%lx: %d\n", stack, shim_regs_get_ip(®s), + my_thread->tid); tcb->context.regs = ®s; fixup_child_context(tcb->context.regs); @@ -150,14 +147,13 @@ static int clone_implementation_wrapper(struct shim_clone_args * arg) * long int __arg1 - 16 bytes ( 2 words ) offset into the child stack allocated * by the parent */ -int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, - int * child_tidptr, void * tls) -{ - //The Clone Implementation in glibc has setup the child's stack - //with the function pointer and the argument to the funciton. - struct shim_thread * self = get_cur_thread(); +int shim_do_clone(int flags, void* user_stack_addr, int* parent_tidptr, int* child_tidptr, + void* tls) { + // The Clone Implementation in glibc has setup the child's stack + // with the function pointer and the argument to the funciton. + struct shim_thread* self = get_cur_thread(); assert(self); - int * set_parent_tid = NULL; + int* set_parent_tid = NULL; int ret = 0; /* special case of vfork: call shim_do_vfork() */ @@ -192,7 +188,7 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, "Additional parameters are ignored:", user_stack_addr); if (flags & CLONE_PARENT_SETTID) debug(" parent_tidptr = %p", parent_tidptr); - if (flags & (CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID)) + if (flags & (CLONE_CHILD_CLEARTID | CLONE_CHILD_SETTID)) debug(" child_tidptr = %p", child_tidptr); if (flags & CLONE_SETTLS) debug(" tls = %p", tls); @@ -281,7 +277,7 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, disable_preempt(NULL); - struct shim_thread * thread = get_new_thread(0); + struct shim_thread* thread = get_new_thread(0); if (!thread) { ret = -ENOMEM; goto failed; @@ -312,14 +308,14 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, if (!(flags & CLONE_THREAD)) thread->tgid = thread->tid; - struct shim_handle_map * handle_map = get_cur_handle_map(self); + struct shim_handle_map* handle_map = get_cur_handle_map(self); if (flags & CLONE_FILES) { set_handle_map(thread, handle_map); } else { /* if CLONE_FILES is not given, the new thread should receive a copy of current descriptor table */ - struct shim_handle_map * new_map = NULL; + struct shim_handle_map* new_map = NULL; dup_handle_map(&new_map, handle_map); set_handle_map(thread, new_map); @@ -327,7 +323,7 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, } if (!(flags & CLONE_VM)) { - void * parent_stack = NULL; + void* parent_stack = NULL; if (!fs_base) { fs_base = self->shim_tcb->context.fs_base; @@ -355,7 +351,7 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, } thread->is_alive = true; - thread->in_vm = false; + thread->in_vm = false; add_thread(thread); set_as_child(self, thread); @@ -403,10 +399,10 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, /* Increasing refcount due to copy below. Passing ownership of the new copy * of this pointer to the new thread (receiver of new_args). */ get_thread(thread); - new_args.thread = thread; - new_args.parent = self; - new_args.stack = user_stack_addr; - new_args.fs_base = fs_base; + new_args.thread = thread; + new_args.parent = self; + new_args.stack = user_stack_addr; + new_args.fs_base = fs_base; // Invoke DkThreadCreate to spawn off a child process using the actual // "clone" system call. DkThreadCreate allocates a stack for the child @@ -414,8 +410,7 @@ int shim_do_clone (int flags, void * user_stack_addr, int * parent_tidptr, // child to run on the Parent allocated stack , so once the DkThreadCreate // returns .The parent comes back here - however, the child is Happily // running the function we gave to DkThreadCreate. - PAL_HANDLE pal_handle = thread_create(clone_implementation_wrapper, - &new_args); + PAL_HANDLE pal_handle = thread_create(clone_implementation_wrapper, &new_args); if (!pal_handle) { ret = -PAL_ERRNO(); put_thread(new_args.thread); diff --git a/LibOS/shim/src/sys/shim_dup.c b/LibOS/shim/src/sys/shim_dup.c index d888f74975..c5904d900c 100644 --- a/LibOS/shim/src/sys/shim_dup.c +++ b/LibOS/shim/src/sys/shim_dup.c @@ -8,14 +8,15 @@ */ #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" int shim_do_dup(unsigned int fd) { struct shim_handle_map* handle_map = get_cur_handle_map(NULL); diff --git a/LibOS/shim/src/sys/shim_epoll.c b/LibOS/shim/src/sys/shim_epoll.c index af6726ab7a..1b1de93014 100644 --- a/LibOS/shim/src/sys/shim_epoll.c +++ b/LibOS/shim/src/sys/shim_epoll.c @@ -10,14 +10,15 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" /* Avoid duplicated definitions */ #ifndef EPOLLIN @@ -47,8 +48,8 @@ int shim_do_epoll_create1(int flags) { hdl->type = TYPE_EPOLL; set_handle_fs(hdl, &epoll_builtin_fs); - epoll->pal_cnt = 0; - epoll->waiter_cnt = 0; + epoll->pal_cnt = 0; + epoll->waiter_cnt = 0; create_event(&epoll->event); INIT_LISTP(&epoll->fds); @@ -120,7 +121,7 @@ void delete_from_epoll_handles(struct shim_handle* handle) { int shim_do_epoll_ctl(int epfd, int op, int fd, struct __kernel_epoll_event* event) { struct shim_thread* cur = get_cur_thread(); - int ret = 0; + int ret = 0; if (epfd == fd) return -EINVAL; @@ -176,7 +177,6 @@ int shim_do_epoll_ctl(int epfd, int op, int fd, struct __kernel_epoll_event* eve ret = -ENOMEM; put_handle(hdl); goto out; - } debug("add fd %d (handle %p) to epoll handle %p\n", fd, hdl, epoll); @@ -309,9 +309,13 @@ int shim_do_epoll_wait(int epfd, struct __kernel_epoll_event* events, int maxeve continue; pal_handles[pal_cnt] = epoll_item->handle->pal_handle; - pal_events[pal_cnt] = (epoll_item->events & (EPOLLIN | EPOLLRDNORM)) ? PAL_WAIT_READ : 0; - pal_events[pal_cnt] |= (epoll_item->events & (EPOLLOUT | EPOLLWRNORM)) ? PAL_WAIT_WRITE : 0; - ret_events[pal_cnt] = 0; + pal_events[pal_cnt] = (epoll_item->events & (EPOLLIN | EPOLLRDNORM)) + ? PAL_WAIT_READ + : 0; + pal_events[pal_cnt] |= (epoll_item->events & (EPOLLOUT | EPOLLWRNORM)) + ? PAL_WAIT_WRITE + : 0; + ret_events[pal_cnt] = 0; pal_cnt++; } @@ -321,11 +325,12 @@ int shim_do_epoll_wait(int epfd, struct __kernel_epoll_event* events, int maxeve pal_events[pal_cnt] = PAL_WAIT_READ; ret_events[pal_cnt] = 0; - epoll->waiter_cnt++; /* mark epoll as being waited on (so epoll-update signal is sent) */ + epoll->waiter_cnt++; /* mark epoll as being waited on (so epoll-update signal is sent) */ unlock(&epoll_hdl->lock); /* TODO: Timeout must be updated in case of retries; otherwise, we may wait for too long */ - PAL_BOL polled = DkStreamsWaitEvents(pal_cnt + 1, pal_handles, pal_events, ret_events, timeout_ms * 1000); + PAL_BOL polled = DkStreamsWaitEvents(pal_cnt + 1, pal_handles, pal_events, ret_events, + timeout_ms * 1000); lock(&epoll_hdl->lock); epoll->waiter_cnt--; @@ -454,12 +459,12 @@ BEGIN_CP_FUNC(epoll_item) { struct shim_epoll_item* new_epoll_item = (struct shim_epoll_item*)(base + off); - new_epoll_item->fd = epoll_item->fd; - new_epoll_item->events = epoll_item->events; - new_epoll_item->data = epoll_item->data; - new_epoll_item->revents = epoll_item->revents; - new_epoll_item->connected = epoll_item->connected; - new_epoll_item->epoll = NULL; // To be filled by epoll handle RS_FUNC + new_epoll_item->fd = epoll_item->fd; + new_epoll_item->events = epoll_item->events; + new_epoll_item->data = epoll_item->data; + new_epoll_item->revents = epoll_item->revents; + new_epoll_item->connected = epoll_item->connected; + new_epoll_item->epoll = NULL; // To be filled by epoll handle RS_FUNC LISTP_ADD(new_epoll_item, new_list, list); @@ -484,8 +489,9 @@ BEGIN_RS_FUNC(epoll_item) { CP_REBASE(epoll_item->back); CP_REBASE(epoll_item->list); - DEBUG_RS("fd=%d,path=%s,type=%s,uri=%s", epoll_item->fd, qstrgetstr(&epoll_item->handle->path), - epoll_item->handle->fs_type, qstrgetstr(&epoll_item->handle->uri)); + DEBUG_RS("fd=%d,path=%s,type=%s,uri=%s", epoll_item->fd, + qstrgetstr(&epoll_item->handle->path), epoll_item->handle->fs_type, + qstrgetstr(&epoll_item->handle->uri)); } } END_RS_FUNC(epoll_item) diff --git a/LibOS/shim/src/sys/shim_eventfd.c b/LibOS/shim/src/sys/shim_eventfd.c index caddd14c31..333f8b7028 100644 --- a/LibOS/shim/src/sys/shim_eventfd.c +++ b/LibOS/shim/src/sys/shim_eventfd.c @@ -12,13 +12,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_utils.h" static int create_eventfd(PAL_HANDLE* efd, unsigned count, int flags) { if (!root_config) { diff --git a/LibOS/shim/src/sys/shim_exec.c b/LibOS/shim/src/sys/shim_exec.c index 708370d495..c2a641c678 100644 --- a/LibOS/shim/src/sys/shim_exec.c +++ b/LibOS/shim/src/sys/shim_exec.c @@ -12,13 +12,14 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_fs.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_table.h" +#include "shim_thread.h" /* returns 0 if normalized URIs are the same; assumes file URIs */ static int normalize_and_cmp_uris(const char* uri1, const char* uri2) { @@ -156,8 +157,6 @@ static int shim_do_execve_rtld(struct shim_handle* hdl, const char** argv, const return 0; } -#include - static BEGIN_MIGRATION_DEF(execve, struct shim_thread* thread, struct shim_process* proc, const char** argv, const char** envp) { DEFINE_MIGRATE(process, proc, sizeof(struct shim_process)); diff --git a/LibOS/shim/src/sys/shim_exit.c b/LibOS/shim/src/sys/shim_exit.c index f4d58c715e..d689ed41b0 100644 --- a/LibOS/shim/src/sys/shim_exit.c +++ b/LibOS/shim/src/sys/shim_exit.c @@ -9,7 +9,6 @@ #include "pal.h" #include "pal_error.h" - #include "shim_handle.h" #include "shim_internal.h" #include "shim_ipc.h" @@ -41,11 +40,11 @@ int thread_destroy(struct shim_thread* thread, bool send_ipc) { int exit_code = thread->exit_code; - struct shim_handle_map * handle_map = thread->handle_map; - struct shim_handle * exec = thread->exec; - struct shim_thread * parent = thread->parent; + struct shim_handle_map* handle_map = thread->handle_map; + struct shim_handle* exec = thread->exec; + struct shim_thread* parent = thread->parent; thread->handle_map = NULL; - thread->exec = NULL; + thread->exec = NULL; if (parent) { assert(parent != thread); @@ -58,14 +57,13 @@ int thread_destroy(struct shim_thread* thread, bool send_ipc) { unlock(&parent->lock); if (!thread->in_vm) { - debug("deliver SIGCHLD (thread = %d, exitval = %d)\n", - thread->tid, exit_code); + debug("deliver SIGCHLD (thread = %d, exitval = %d)\n", thread->tid, exit_code); siginfo_t info; memset(&info, 0, sizeof(siginfo_t)); - info.si_signo = SIGCHLD; - info.si_pid = thread->tid; - info.si_uid = thread->uid; + info.si_signo = SIGCHLD; + info.si_pid = thread->tid; + info.si_uid = thread->uid; info.si_status = (exit_code & 0xff) << 8; if (append_signal(parent, &info) >= 0) { diff --git a/LibOS/shim/src/sys/shim_fcntl.c b/LibOS/shim/src/sys/shim_fcntl.c index e112e3635e..bb39e3bb69 100644 --- a/LibOS/shim/src/sys/shim_fcntl.c +++ b/LibOS/shim/src/sys/shim_fcntl.c @@ -9,14 +9,15 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" #define FCNTL_SETFL_MASK (O_APPEND | O_NONBLOCK) diff --git a/LibOS/shim/src/sys/shim_fs.c b/LibOS/shim/src/sys/shim_fs.c index ac1d5653a6..ca019fb3ff 100644 --- a/LibOS/shim/src/sys/shim_fs.c +++ b/LibOS/shim/src/sys/shim_fs.c @@ -16,14 +16,14 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" /* The kernel would look up the parent directory, and remove the child from the inode. But we are * working with the PAL, so we open the file, truncate and close it. */ @@ -323,8 +323,8 @@ int shim_do_fchown(int fd, uid_t uid, gid_t gid) { return 0; } -#define MAP_SIZE (g_pal_alloc_align * 256) /* mmap/memcpy in 1MB chunks for sendfile() */ -#define BUF_SIZE 2048 /* read/write in 2KB chunks for sendfile() */ +#define MAP_SIZE (g_pal_alloc_align * 256) /* mmap/memcpy in 1MB chunks for sendfile() */ +#define BUF_SIZE 2048 /* read/write in 2KB chunks for sendfile() */ /* TODO: The below implementation needs to be refactored: (1) remove offseto, it is always zero; * (2) simplify handling of non-blocking handles, (3) instead of relying on PAL to mmap diff --git a/LibOS/shim/src/sys/shim_futex.c b/LibOS/shim/src/sys/shim_futex.c index b975cbb28c..05592777dc 100644 --- a/LibOS/shim/src/sys/shim_futex.c +++ b/LibOS/shim/src/sys/shim_futex.c @@ -210,8 +210,7 @@ static void maybe_dequeue_two_futexes(struct shim_futex* futex1, struct shim_fut * and of `futex` by 1. * `futex->lock` needs to be held. */ -static void add_futex_waiter(struct futex_waiter* waiter, - struct shim_futex* futex, +static void add_futex_waiter(struct futex_waiter* waiter, struct shim_futex* futex, uint32_t bitset) { assert(spinlock_is_locked(&futex->lock)); @@ -243,8 +242,7 @@ static struct shim_thread* remove_futex_waiter(struct futex_waiter* waiter, * * `futex1->lock` and `futex2->lock` need to be held. */ -static void move_futex_waiter(struct futex_waiter* waiter, - struct shim_futex* futex1, +static void move_futex_waiter(struct futex_waiter* waiter, struct shim_futex* futex1, struct shim_futex* futex2) { assert(spinlock_is_locked(&futex1->lock)); assert(spinlock_is_locked(&futex2->lock)); @@ -332,7 +330,7 @@ static int futex_wait(uint32_t* uaddr, uint32_t val, uint64_t timeout, uint32_t goto out_with_futex_lock; } - struct futex_waiter waiter = { 0 }; + struct futex_waiter waiter = {0}; add_futex_waiter(&waiter, futex, bitset); spinlock_unlock_signal_on(&futex->lock); @@ -367,7 +365,7 @@ static int futex_wait(uint32_t* uaddr, uint32_t val, uint64_t timeout, uint32_t * NB: actually `futex` and this point to the same futex, so this won't call free. */ put_futex(waiter.futex); -out_with_futex_lock: ; // C is awesome! +out_with_futex_lock:; // C is awesome! /* Because dequeuing a futex requires `g_futex_list_lock` which we do not hold at this moment, * we check if we actually need to do it now (locks acquisition and dequeuing). */ bool needs_dequeue = check_dequeue_futex(futex); @@ -429,7 +427,7 @@ static int move_to_wake_queue(struct shim_futex* futex, uint32_t bitset, int to_ static int futex_wake(uint32_t* uaddr, int to_wake, uint32_t bitset) { struct shim_futex* futex; - struct wake_queue_head queue = { .first = WAKE_QUEUE_TAIL }; + struct wake_queue_head queue = {.first = WAKE_QUEUE_TAIL}; int woken = 0; if (!bitset) { @@ -472,10 +470,11 @@ static int wakeop_arg_extend(int x) { return x; } -static int futex_wake_op(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake1, int to_wake2, uint32_t val3) { +static int futex_wake_op(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake1, int to_wake2, + uint32_t val3) { struct shim_futex* futex1 = NULL; struct shim_futex* futex2 = NULL; - struct wake_queue_head queue = { .first = WAKE_QUEUE_TAIL }; + struct wake_queue_head queue = {.first = WAKE_QUEUE_TAIL}; int ret = 0; bool needs_dequeue1 = false; bool needs_dequeue2 = false; @@ -582,11 +581,12 @@ static int futex_wake_op(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake1, int t return ret; } -static int futex_requeue(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake, int to_requeue, uint32_t* val) { +static int futex_requeue(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake, int to_requeue, + uint32_t* val) { struct shim_futex* futex1 = NULL; struct shim_futex* futex2 = NULL; struct shim_futex* tmp = NULL; - struct wake_queue_head queue = { .first = WAKE_QUEUE_TAIL }; + struct wake_queue_head queue = {.first = WAKE_QUEUE_TAIL}; int ret = 0; int woken = 0; int requeued = 0; @@ -679,7 +679,7 @@ static int futex_requeue(uint32_t* uaddr1, uint32_t* uaddr2, int to_wake, int to return ret; } -#define FUTEX_CHECK_READ false +#define FUTEX_CHECK_READ false #define FUTEX_CHECK_WRITE true static int is_valid_futex_ptr(uint32_t* ptr, bool check_write) { if (!IS_ALIGNED_PTR(ptr, alignof(*ptr))) { @@ -691,13 +691,14 @@ static int is_valid_futex_ptr(uint32_t* ptr, bool check_write) { return 0; } -static int _shim_do_futex(uint32_t* uaddr, int op, uint32_t val, void* utime, uint32_t* uaddr2, uint32_t val3) { +static int _shim_do_futex(uint32_t* uaddr, int op, uint32_t val, void* utime, uint32_t* uaddr2, + uint32_t val3) { int cmd = op & FUTEX_CMD_MASK; uint64_t timeout = NO_TIMEOUT; uint32_t val2 = 0; - if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_WAIT_BITSET || - cmd == FUTEX_LOCK_PI || cmd == FUTEX_WAIT_REQUEUE_PI)) { + if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_WAIT_BITSET || cmd == FUTEX_LOCK_PI || + cmd == FUTEX_WAIT_REQUEUE_PI)) { if (test_user_memory(utime, sizeof(struct timespec), /*write=*/false)) { return -EFAULT; } @@ -786,7 +787,8 @@ static int _shim_do_futex(uint32_t* uaddr, int op, uint32_t val, void* utime, ui int shim_do_futex(int* uaddr, int op, int val, void* utime, int* uaddr2, int val3) { static_assert(sizeof(int) == 4, "futexes are defined to be 32-bit"); - return _shim_do_futex((uint32_t*)uaddr, op, (uint32_t)val, utime, (uint32_t*)uaddr2, (uint32_t)val3); + return _shim_do_futex((uint32_t*)uaddr, op, (uint32_t)val, utime, (uint32_t*)uaddr2, + (uint32_t)val3); } int shim_do_set_robust_list(struct robust_list_head* head, size_t len) { @@ -813,7 +815,8 @@ int shim_do_get_robust_list(pid_t pid, struct robust_list_head** head, size_t* l get_thread(thread); } - if (test_user_memory(head, sizeof(*head), /*write=*/true) || test_user_memory(len, sizeof(*len), /*write=*/true)) { + if (test_user_memory(head, sizeof(*head), /*write=*/true) || + test_user_memory(len, sizeof(*len), /*write=*/true)) { ret = -EFAULT; goto out; } diff --git a/LibOS/shim/src/sys/shim_getcwd.c b/LibOS/shim/src/sys/shim_getcwd.c index 1008202dba..799ddd22ed 100644 --- a/LibOS/shim/src/sys/shim_getcwd.c +++ b/LibOS/shim/src/sys/shim_getcwd.c @@ -8,14 +8,15 @@ */ #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" #ifndef ERANGE #define ERANGE 34 diff --git a/LibOS/shim/src/sys/shim_getpid.c b/LibOS/shim/src/sys/shim_getpid.c index 3347594a3d..527247948d 100644 --- a/LibOS/shim/src/sys/shim_getpid.c +++ b/LibOS/shim/src/sys/shim_getpid.c @@ -11,16 +11,17 @@ */ #include -#include -#include -#include -#include -#include -#include -#include #include #include +#include "pal.h" +#include "pal_error.h" +#include "shim_checkpoint.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_table.h" +#include "shim_thread.h" + pid_t shim_do_getpid(void) { struct shim_thread* cur = get_cur_thread(); return cur ? cur->tgid : 0; diff --git a/LibOS/shim/src/sys/shim_getrlimit.c b/LibOS/shim/src/sys/shim_getrlimit.c index c98a050981..1b0b1a3c57 100644 --- a/LibOS/shim/src/sys/shim_getrlimit.c +++ b/LibOS/shim/src/sys/shim_getrlimit.c @@ -8,11 +8,12 @@ */ #include -#include -#include -#include -#include -#include + +#include "shim_checkpoint.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_utils.h" +#include "shim_vma.h" /* * TODO: implement actual limitation on each resource. diff --git a/LibOS/shim/src/sys/shim_ioctl.c b/LibOS/shim/src/sys/shim_ioctl.c index f2f0152b30..1810c9bb50 100644 --- a/LibOS/shim/src/sys/shim_ioctl.c +++ b/LibOS/shim/src/sys/shim_ioctl.c @@ -415,7 +415,7 @@ int shim_do_ioctl(int fd, unsigned long cmd, unsigned long arg) { } *(int*)arg = size - offset; - ret = 0; + ret = 0; break; } diff --git a/LibOS/shim/src/sys/shim_mmap.c b/LibOS/shim/src/sys/shim_mmap.c index de9de5985e..309785a69e 100644 --- a/LibOS/shim/src/sys/shim_mmap.c +++ b/LibOS/shim/src/sys/shim_mmap.c @@ -23,9 +23,9 @@ #include "shim_vma.h" #ifdef MAP_32BIT /* x86_64-specific */ -#define MAP_32BIT_IF_SUPPORTED MAP_32BIT +#define MAP_32BIT_IF_SUPPORTED MAP_32BIT #else -#define MAP_32BIT_IF_SUPPORTED 0 +#define MAP_32BIT_IF_SUPPORTED 0 #endif #define LEGACY_MAP_MASK (MAP_SHARED \ @@ -48,7 +48,7 @@ void* shim_do_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { struct shim_handle* hdl = NULL; - long ret = 0; + long ret = 0; if (!(flags & MAP_FIXED) && addr) addr = ALLOC_ALIGN_DOWN_PTR(addr); @@ -203,8 +203,8 @@ void* shim_do_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t } int shim_do_mprotect(void* addr, size_t length, int prot) { - if (prot & ~(PROT_NONE | PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN | PROT_GROWSUP - | PROT_SEM)) { + if (prot & ~(PROT_NONE | PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN | PROT_GROWSUP | + PROT_SEM)) { return -EINVAL; } @@ -231,7 +231,6 @@ int shim_do_mprotect(void* addr, size_t length, int prot) { if (!IS_ALLOC_ALIGNED(length)) length = ALLOC_ALIGN_UP(length); - if (!access_ok(addr, length)) { return -EINVAL; } @@ -245,7 +244,7 @@ int shim_do_mprotect(void* addr, size_t length, int prot) { } if (prot & PROT_GROWSDOWN) { - struct shim_vma_info vma_info = { 0 }; + struct shim_vma_info vma_info = {0}; if (lookup_vma(addr, &vma_info) >= 0) { addr = vma_info.addr; if (vma_info.file) { @@ -324,7 +323,6 @@ int shim_do_mincore(void* addr, size_t len, unsigned char* vec) { return 0; } - int shim_do_mbind(void* start, unsigned long len, int mode, unsigned long* nmask, unsigned long maxnode, int flags) { /* dummy implementation, always return success */ diff --git a/LibOS/shim/src/sys/shim_msgget.c b/LibOS/shim/src/sys/shim_msgget.c index f4d9b37356..eab66fa806 100644 --- a/LibOS/shim/src/sys/shim_msgget.c +++ b/LibOS/shim/src/sys/shim_msgget.c @@ -12,16 +12,17 @@ */ #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "list.h" +#include "pal.h" +#include "pal_error.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_sysv.h" +#include "shim_table.h" +#include "shim_unistd.h" +#include "shim_utils.h" #define MSGQ_HASH_LEN 8 #define MSGQ_HASH_NUM (1 << MSGQ_HASH_LEN) @@ -695,9 +696,8 @@ static int __store_msg_persist(struct shim_msg_handle* msgq) { if (DkStreamSetLength(file, expected_size)) goto err_file; - void* mem = - (void*)DkStreamMap(file, NULL, PAL_PROT_READ | PAL_PROT_WRITE, 0, - ALLOC_ALIGN_UP(expected_size)); + void* mem = (void*)DkStreamMap(file, NULL, PAL_PROT_READ | PAL_PROT_WRITE, 0, + ALLOC_ALIGN_UP(expected_size)); if (!mem) { ret = -EFAULT; goto err_file; @@ -743,7 +743,7 @@ static int __store_msg_persist(struct shim_msg_handle* msgq) { } msgq->owned = false; - ret = 0; + ret = 0; goto out; err_file: diff --git a/LibOS/shim/src/sys/shim_open.c b/LibOS/shim/src/sys/shim_open.c index 273b7e2034..597fdb34ee 100644 --- a/LibOS/shim/src/sys/shim_open.c +++ b/LibOS/shim/src/sys/shim_open.c @@ -4,33 +4,32 @@ /* * shim_open.c * - * Implementation of system call "read", "write", "open", "creat", "openat", + * Implementation of system calls: "read", "write", "open", "creat", "openat", * "close", "lseek", "pread64", "pwrite64", "getdents", "getdents64", * "fsync", "truncate" and "ftruncate". */ -#include -#include -#include -#include -#include -#include +// FIXME: Moving Linux includes first causes a bunch of "error: ‘S_IFLNK’ undeclared" errors. +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" -#include -#include +#include "pal.h" +#include "pal_error.h" #include #include - #include #include -int do_handle_read (struct shim_handle * hdl, void * buf, int count) -{ +int do_handle_read(struct shim_handle* hdl, void* buf, int count) { if (!(hdl->acc_mode & MAY_READ)) return -EACCES; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; assert(fs && fs->fs_ops); if (!fs->fs_ops->read) @@ -42,12 +41,11 @@ int do_handle_read (struct shim_handle * hdl, void * buf, int count) return fs->fs_ops->read(hdl, buf, count); } -size_t shim_do_read (int fd, void * buf, size_t count) -{ +size_t shim_do_read(int fd, void* buf, size_t count) { if (!buf || test_user_memory(buf, count, true)) return -EFAULT; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; @@ -62,12 +60,11 @@ size_t shim_do_read (int fd, void * buf, size_t count) return ret; } -int do_handle_write (struct shim_handle * hdl, const void * buf, int count) -{ +int do_handle_write(struct shim_handle* hdl, const void* buf, int count) { if (!(hdl->acc_mode & MAY_WRITE)) return -EACCES; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; assert(fs && fs->fs_ops); if (!fs->fs_ops->write) @@ -79,12 +76,11 @@ int do_handle_write (struct shim_handle * hdl, const void * buf, int count) return fs->fs_ops->write(hdl, buf, count); } -size_t shim_do_write (int fd, const void * buf, size_t count) -{ - if (!buf || test_user_memory((void *) buf, count, false)) +size_t shim_do_write(int fd, const void* buf, size_t count) { + if (!buf || test_user_memory((void*)buf, count, false)) return -EFAULT; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; @@ -93,8 +89,7 @@ size_t shim_do_write (int fd, const void * buf, size_t count) return ret; } -int shim_do_open (const char * file, int flags, mode_t mode) -{ +int shim_do_open(const char* file, int flags, mode_t mode) { if (!file || test_user_string(file)) return -EFAULT; @@ -106,7 +101,7 @@ int shim_do_open (const char * file, int flags, mode_t mode) mode &= 07777; } - struct shim_handle * hdl = get_new_handle(); + struct shim_handle* hdl = get_new_handle(); if (!hdl) return -ENOMEM; @@ -121,13 +116,11 @@ int shim_do_open (const char * file, int flags, mode_t mode) return ret; } -int shim_do_creat (const char * path, mode_t mode) -{ - return shim_do_open(path, O_CREAT|O_TRUNC|O_WRONLY, mode); +int shim_do_creat(const char* path, mode_t mode) { + return shim_do_open(path, O_CREAT | O_TRUNC | O_WRONLY, mode); } -int shim_do_openat (int dfd, const char * filename, int flags, int mode) -{ +int shim_do_openat(int dfd, const char* filename, int flags, int mode) { if (!filename || test_user_string(filename)) return -EFAULT; @@ -139,13 +132,13 @@ int shim_do_openat (int dfd, const char * filename, int flags, int mode) mode &= 07777; } - struct shim_dentry * dir = NULL; + struct shim_dentry* dir = NULL; int ret = 0; if ((ret = get_dirfd_dentry(dfd, &dir)) < 0) return ret; - struct shim_handle * hdl = get_new_handle(); + struct shim_handle* hdl = get_new_handle(); if (!hdl) { ret = -ENOMEM; goto out; @@ -164,9 +157,8 @@ int shim_do_openat (int dfd, const char * filename, int flags, int mode) return ret; } -int shim_do_close (int fd) -{ - struct shim_handle * handle = detach_fd_handle(fd, NULL, NULL); +int shim_do_close(int fd) { + struct shim_handle* handle = detach_fd_handle(fd, NULL, NULL); if (!handle) return -EBADF; @@ -175,17 +167,16 @@ int shim_do_close (int fd) } /* lseek is simply doing arithmetic on the offset, no PAL call here */ -off_t shim_do_lseek (int fd, off_t offset, int origin) -{ +off_t shim_do_lseek(int fd, off_t offset, int origin) { if (origin != SEEK_SET && origin != SEEK_CUR && origin != SEEK_END) return -EINVAL; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; int ret = 0; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; assert(fs && fs->fs_ops); if (!fs->fs_ops->seek) { @@ -205,19 +196,18 @@ off_t shim_do_lseek (int fd, off_t offset, int origin) return ret; } -ssize_t shim_do_pread64 (int fd, char * buf, size_t count, loff_t pos) -{ +ssize_t shim_do_pread64(int fd, char* buf, size_t count, loff_t pos) { if (!buf || test_user_memory(buf, count, true)) return -EFAULT; if (pos < 0) return -EINVAL; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; ssize_t ret = -EACCES; if (!fs || !fs->fs_ops) @@ -256,19 +246,18 @@ ssize_t shim_do_pread64 (int fd, char * buf, size_t count, loff_t pos) return ret; } -ssize_t shim_do_pwrite64 (int fd, char * buf, size_t count, loff_t pos) -{ +ssize_t shim_do_pwrite64(int fd, char* buf, size_t count, loff_t pos) { if (!buf || test_user_memory(buf, count, false)) return -EFAULT; if (pos < 0) return -EINVAL; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; ssize_t ret = -EACCES; if (!fs || !fs->fs_ops) @@ -307,8 +296,7 @@ ssize_t shim_do_pwrite64 (int fd, char * buf, size_t count, loff_t pos) return ret; } -static inline int get_dirent_type (mode_t type) -{ +static inline int get_dirent_type(mode_t type) { switch (type) { case S_IFLNK: return LINUX_DT_LNK; @@ -329,12 +317,11 @@ static inline int get_dirent_type (mode_t type) } } -size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) -{ +size_t shim_do_getdents(int fd, struct linux_dirent* buf, size_t count) { if (!buf || test_user_memory(buf, count, true)) return -EFAULT; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; @@ -355,9 +342,9 @@ size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) updated */ lock(&hdl->lock); - struct shim_dir_handle * dirhdl = &hdl->dir_info; - struct shim_dentry * dent = hdl->dentry; - struct linux_dirent * b = buf; + struct shim_dir_handle* dirhdl = &hdl->dir_info; + struct shim_dentry* dent = hdl->dentry; + struct linux_dirent* b = buf; int bytes = 0; /* If we haven't listed the directory, do this first */ @@ -367,31 +354,29 @@ size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) goto out; } -#define DIRENT_SIZE(len) (sizeof(struct linux_dirent) + \ - sizeof(struct linux_dirent_tail) + (len) + 1) - -#define ASSIGN_DIRENT(dent, name, type) \ - do { \ - int len = strlen(name); \ - if (bytes + DIRENT_SIZE(len) > count) \ - goto done; \ - \ - struct linux_dirent_tail * bt \ - = (void *) b + sizeof(struct linux_dirent) + len + 1; \ - \ - b->d_ino = (dent)->ino; \ - b->d_off = ++dirhdl->offset; \ - b->d_reclen = DIRENT_SIZE(len); \ - \ - memcpy(b->d_name, name, len + 1); \ - \ - bt->pad = 0; \ - bt->d_type = (type); \ - \ - b = (void *) bt + sizeof(struct linux_dirent_tail); \ - bytes += DIRENT_SIZE(len); \ - } while(0) - +#define DIRENT_SIZE(len) \ + (sizeof(struct linux_dirent) + sizeof(struct linux_dirent_tail) + (len) + 1) + +#define ASSIGN_DIRENT(dent, name, type) \ + do { \ + int len = strlen(name); \ + if (bytes + DIRENT_SIZE(len) > count) \ + goto done; \ + \ + struct linux_dirent_tail* bt = (void*)b + sizeof(struct linux_dirent) + len + 1; \ + \ + b->d_ino = (dent)->ino; \ + b->d_off = ++dirhdl->offset; \ + b->d_reclen = DIRENT_SIZE(len); \ + \ + memcpy(b->d_name, name, len + 1); \ + \ + bt->pad = 0; \ + bt->d_type = (type); \ + \ + b = (void*)bt + sizeof(struct linux_dirent_tail); \ + bytes += DIRENT_SIZE(len); \ + } while (0) if (dirhdl->dot) { ASSIGN_DIRENT(dirhdl->dot, ".", LINUX_DT_DIR); @@ -405,7 +390,7 @@ size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) dirhdl->dotdot = NULL; } - if (dirhdl->ptr == (void *) -1) { + if (dirhdl->ptr == (void*)-1) { ret = list_directory_handle(dent, hdl); if (ret < 0) goto out; @@ -427,8 +412,7 @@ size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) ret = bytes; /* DEP 3/3/17: Properly detect EINVAL case, where buffer is too small to * hold anything */ - if (bytes == 0 && (dirhdl->dot || dirhdl->dotdot || - (dirhdl->ptr && *dirhdl->ptr))) + if (bytes == 0 && (dirhdl->dot || dirhdl->dotdot || (dirhdl->ptr && *dirhdl->ptr))) ret = -EINVAL; out: unlock(&hdl->lock); @@ -437,12 +421,11 @@ size_t shim_do_getdents (int fd, struct linux_dirent * buf, size_t count) return ret; } -size_t shim_do_getdents64 (int fd, struct linux_dirent64 * buf, size_t count) -{ +size_t shim_do_getdents64(int fd, struct linux_dirent64* buf, size_t count) { if (!buf || test_user_memory(buf, count, true)) return -EFAULT; - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; @@ -461,35 +444,36 @@ size_t shim_do_getdents64 (int fd, struct linux_dirent64 * buf, size_t count) lock(&hdl->lock); - struct shim_dir_handle * dirhdl = &hdl->dir_info; - struct shim_dentry * dent = hdl->dentry; - struct linux_dirent64 * b = buf; + struct shim_dir_handle* dirhdl = &hdl->dir_info; + struct shim_dentry* dent = hdl->dentry; + struct linux_dirent64* b = buf; int bytes = 0; /* If we haven't listed the directory, do this first */ if (!(dent->state & DENTRY_LISTED)) { ret = list_directory_dentry(dent); - if (ret) goto out; + if (ret) + goto out; } -#define DIRENT_SIZE(len) (sizeof(struct linux_dirent64) + (len) + 1) - -#define ASSIGN_DIRENT(dent, name, type) \ - do { \ - int len = strlen(name); \ - if (bytes + DIRENT_SIZE(len) > count) \ - goto done; \ - \ - b->d_ino = (dent)->ino; \ - b->d_off = ++dirhdl->offset; \ - b->d_reclen = DIRENT_SIZE(len); \ - b->d_type = (type); \ - \ - memcpy(b->d_name, name, len + 1); \ - \ - b = (void *) b + DIRENT_SIZE(len); \ - bytes += DIRENT_SIZE(len); \ - } while(0) +#define DIRENT_SIZE(len) (sizeof(struct linux_dirent64) + (len) + 1) + +#define ASSIGN_DIRENT(dent, name, type) \ + do { \ + int len = strlen(name); \ + if (bytes + DIRENT_SIZE(len) > count) \ + goto done; \ + \ + b->d_ino = (dent)->ino; \ + b->d_off = ++dirhdl->offset; \ + b->d_reclen = DIRENT_SIZE(len); \ + b->d_type = (type); \ + \ + memcpy(b->d_name, name, len + 1); \ + \ + b = (void*)b + DIRENT_SIZE(len); \ + bytes += DIRENT_SIZE(len); \ + } while (0) if (dirhdl->dot) { ASSIGN_DIRENT(dirhdl->dot, ".", LINUX_DT_DIR); @@ -503,9 +487,10 @@ size_t shim_do_getdents64 (int fd, struct linux_dirent64 * buf, size_t count) dirhdl->dotdot = NULL; } - if (dirhdl->ptr == (void *) -1) { + if (dirhdl->ptr == (void*)-1) { ret = list_directory_handle(dent, hdl); - if (ret) goto out; + if (ret) + goto out; } while (dirhdl->ptr && *dirhdl->ptr) { @@ -524,8 +509,7 @@ size_t shim_do_getdents64 (int fd, struct linux_dirent64 * buf, size_t count) ret = bytes; /* DEP 3/3/17: Properly detect EINVAL case, where buffer is too small to * hold anything */ - if (bytes == 0 && (dirhdl->dot || dirhdl->dotdot || - (dirhdl->ptr && *dirhdl->ptr))) + if (bytes == 0 && (dirhdl->dot || dirhdl->dotdot || (dirhdl->ptr && *dirhdl->ptr))) ret = -EINVAL; unlock(&hdl->lock); out: @@ -533,14 +517,13 @@ size_t shim_do_getdents64 (int fd, struct linux_dirent64 * buf, size_t count) return ret; } -int shim_do_fsync (int fd) -{ - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); +int shim_do_fsync(int fd) { + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; int ret = -EACCES; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; if (!fs || !fs->fs_ops) goto out; @@ -559,18 +542,14 @@ int shim_do_fsync (int fd) return ret; } - // DEP 10/20/16: Assuming fsync >> fdatasync for now // and no app depends on only syncing data for correctness. -int shim_do_fdatasync (int fd) -{ +int shim_do_fdatasync(int fd) { return shim_do_fsync(fd); } - -int shim_do_truncate (const char * path, loff_t length) -{ - struct shim_dentry * dent = NULL; +int shim_do_truncate(const char* path, loff_t length) { + struct shim_dentry* dent = NULL; int ret = 0; if (!path || test_user_string(path)) @@ -579,7 +558,7 @@ int shim_do_truncate (const char * path, loff_t length) if ((ret = path_lookupat(NULL, path, 0, &dent, NULL)) < 0) return ret; - struct shim_mount * fs = dent->fs; + struct shim_mount* fs = dent->fs; if (!fs || !fs->d_ops || !fs->d_ops->open) { ret = -EBADF; @@ -591,7 +570,7 @@ int shim_do_truncate (const char * path, loff_t length) goto out; } - struct shim_handle * hdl = get_new_handle(); + struct shim_handle* hdl = get_new_handle(); if (!hdl) { ret = -ENOMEM; @@ -611,20 +590,18 @@ int shim_do_truncate (const char * path, loff_t length) return ret; } -int shim_do_ftruncate (int fd, loff_t length) -{ - struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL); +int shim_do_ftruncate(int fd, loff_t length) { + struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL); if (!hdl) return -EBADF; - struct shim_mount * fs = hdl->fs; + struct shim_mount* fs = hdl->fs; int ret = -EINVAL; if (!fs || !fs->fs_ops) goto out; - if (hdl->type == TYPE_DIR || - !fs->fs_ops->truncate) + if (hdl->type == TYPE_DIR || !fs->fs_ops->truncate) goto out; ret = fs->fs_ops->truncate(hdl, length); diff --git a/LibOS/shim/src/sys/shim_pipe.c b/LibOS/shim/src/sys/shim_pipe.c index 4c3cf9b5d3..949bd2c5bb 100644 --- a/LibOS/shim/src/sys/shim_pipe.c +++ b/LibOS/shim/src/sys/shim_pipe.c @@ -25,9 +25,9 @@ static int create_pipes(struct shim_handle* srv, struct shim_handle* cli, int fl int ret = 0; char uri[PIPE_URI_SIZE]; - PAL_HANDLE hdl0 = NULL; /* server pipe (temporary, waits for connect from hdl2) */ - PAL_HANDLE hdl1 = NULL; /* one pipe end (accepted connect from hdl2) */ - PAL_HANDLE hdl2 = NULL; /* other pipe end (connects to hdl0 and talks to hdl1) */ + PAL_HANDLE hdl0 = NULL; /* server pipe (temporary, waits for connect from hdl2) */ + PAL_HANDLE hdl1 = NULL; /* one pipe end (accepted connect from hdl2) */ + PAL_HANDLE hdl2 = NULL; /* other pipe end (connects to hdl0 and talks to hdl1) */ if ((ret = create_pipe(name, uri, PIPE_URI_SIZE, &hdl0, qstr, /*use_vmid_for_name=*/false)) < 0) { @@ -241,7 +241,7 @@ int shim_do_socketpair(int domain, int type, int protocol, int* sv) { return ret; } -int shim_do_mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev) { +int shim_do_mknodat(int dirfd, const char* pathname, mode_t mode, dev_t dev) { int ret = 0; __UNUSED(dev); @@ -251,7 +251,7 @@ int shim_do_mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev) { /* FIXME: Graphene assumes that file is at least readable by owner, in particular, see * unlink() emulation that uses DkStreamOpen(). We change empty mode to readable * by user here to allow a consequent unlink. Was detected on LTP mknod tests. */ - int fd = shim_do_openat(dirfd, pathname, O_CREAT | O_EXCL, mode ? : S_IRUSR); + int fd = shim_do_openat(dirfd, pathname, O_CREAT | O_EXCL, mode ?: S_IRUSR); if (fd < 0) return fd; return shim_do_close(fd); @@ -376,6 +376,6 @@ int shim_do_mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev) { return ret; } -int shim_do_mknod(const char *pathname, mode_t mode, dev_t dev) { +int shim_do_mknod(const char* pathname, mode_t mode, dev_t dev) { return shim_do_mknodat(AT_FDCWD, pathname, mode, dev); } diff --git a/LibOS/shim/src/sys/shim_poll.c b/LibOS/shim/src/sys/shim_poll.c index 424de2c93d..c9298f4c87 100644 --- a/LibOS/shim/src/sys/shim_poll.c +++ b/LibOS/shim/src/sys/shim_poll.c @@ -9,14 +9,15 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" typedef long int __fd_mask; diff --git a/LibOS/shim/src/sys/shim_sched.c b/LibOS/shim/src/sys/shim_sched.c index 5812363fce..c1e691b510 100644 --- a/LibOS/shim/src/sys/shim_sched.c +++ b/LibOS/shim/src/sys/shim_sched.c @@ -10,13 +10,14 @@ * "sched_setaffinity", "sched_getaffinity", "getcpu". */ -#include #include #include #include -#include -#include -#include + +#include "api.h" +#include "pal.h" +#include "shim_internal.h" +#include "shim_table.h" int shim_do_sched_yield(void) { DkThreadYieldExecution(); @@ -71,18 +72,19 @@ int shim_do_sched_setscheduler(pid_t pid, int policy, struct __kernel_sched_para return -EINVAL; /* fail on unrecognized policies */ - if (policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE && /* non-real-time */ - policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) + if (policy != SCHED_NORMAL && policy != SCHED_BATCH && + policy != SCHED_IDLE && /* non-real-time */ + policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) return -EINVAL; /* non-real-time policies must have priority of 0 */ if ((policy == SCHED_NORMAL || policy == SCHED_BATCH || policy == SCHED_IDLE) && - (param->__sched_priority != 0)) + (param->__sched_priority != 0)) return -EINVAL; /* real-time policies must have priority in range [1, 99] */ if ((policy == SCHED_FIFO || policy == SCHED_RR) && - (param->__sched_priority < 1 || param->__sched_priority > 99)) + (param->__sched_priority < 1 || param->__sched_priority > 99)) return -EINVAL; return 0; @@ -98,8 +100,9 @@ int shim_do_sched_getscheduler(pid_t pid) { int shim_do_sched_get_priority_max(int policy) { /* fail on unrecognized policies */ - if (policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE && /* non-real-time */ - policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) + if (policy != SCHED_NORMAL && policy != SCHED_BATCH && + policy != SCHED_IDLE && /* non-real-time */ + policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) return -EINVAL; /* real-time policies have max priority of 99 */ @@ -112,8 +115,9 @@ int shim_do_sched_get_priority_max(int policy) { int shim_do_sched_get_priority_min(int policy) { /* fail on unrecognized policies */ - if (policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE && /* non-real-time */ - policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) + if (policy != SCHED_NORMAL && policy != SCHED_BATCH && + policy != SCHED_IDLE && /* non-real-time */ + policy != SCHED_FIFO && policy != SCHED_RR /* real-time */) return -EINVAL; /* real-time policies have min priority of 1 */ diff --git a/LibOS/shim/src/sys/shim_semget.c b/LibOS/shim/src/sys/shim_semget.c index 7c70125ad9..dd82220f85 100644 --- a/LibOS/shim/src/sys/shim_semget.c +++ b/LibOS/shim/src/sys/shim_semget.c @@ -8,15 +8,16 @@ */ #include -#include -#include -#include -#include -#include -#include -#include -#include -#include + +#include "list.h" +#include "pal.h" +#include "pal_error.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_ipc.h" +#include "shim_sysv.h" +#include "shim_table.h" +#include "shim_utils.h" #define SEM_HASH_LEN 8 #define SEM_HASH_NUM (1 << SEM_HASH_LEN) diff --git a/LibOS/shim/src/sys/shim_sigaction.c b/LibOS/shim/src/sys/shim_sigaction.c index a35e1d104e..eb64c2b89a 100644 --- a/LibOS/shim/src/sys/shim_sigaction.c +++ b/LibOS/shim/src/sys/shim_sigaction.c @@ -285,11 +285,11 @@ int do_kill_proc(IDTYPE sender, IDTYPE tgid, int sig, bool use_ipc) { /* This might be called by an internal thread (like IPC), so we cannot inspect `cur_thread` ids * to check whether `sig` is targetted at it, but need to do a full search. */ struct signal_thread_arg arg = { - .sig = sig, - .sender = sender, - .cmp_val = tgid, + .sig = sig, + .sender = sender, + .cmp_val = tgid, .cmp_type = TGID, - .sent = false, + .sent = false, }; int ret = walk_thread_list(_signal_one_thread, &arg, /*one_shot=*/true); if (ret < 0 && ret != -ESRCH) { @@ -336,11 +336,11 @@ int do_kill_pgroup(IDTYPE sender, IDTYPE pgid, int sig, bool use_ipc) { /* This might be called by an internal thread (like IPC), so we cannot inspect `cur_thread` ids * to check whether `sig` is targetted at it, but need to do a full search. */ struct signal_thread_arg arg = { - .sig = sig, - .sender = sender, - .cmp_val = pgid, + .sig = sig, + .sender = sender, + .cmp_val = pgid, .cmp_type = PGID, - .sent = false, + .sent = false, }; ret = walk_thread_list(_signal_one_thread, &arg, /*one_shot=*/true); diff --git a/LibOS/shim/src/sys/shim_sleep.c b/LibOS/shim/src/sys/shim_sleep.c index 50eb2bde29..d650e1acc0 100644 --- a/LibOS/shim/src/sys/shim_sleep.c +++ b/LibOS/shim/src/sys/shim_sleep.c @@ -9,14 +9,14 @@ #include -#include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" +#include "shim_vma.h" int shim_do_pause(void) { /* ~0ULL micro sec ~= 805675 years */ diff --git a/LibOS/shim/src/sys/shim_socket.c b/LibOS/shim/src/sys/shim_socket.c index 5ca7b585e0..c7da5a7a79 100644 --- a/LibOS/shim/src/sys/shim_socket.c +++ b/LibOS/shim/src/sys/shim_socket.c @@ -192,8 +192,8 @@ static ssize_t inet_translate_addr(int domain, char* uri, size_t count, struct a if (domain == AF_INET6) { unsigned short* ad = (void*)&addr->addr.v6.s6_addr; return snprintf(uri, count, "[%04x:%04x:%x:%04x:%04x:%04x:%04x:%04x]:%u", __ntohs(ad[0]), - __ntohs(ad[1]), __ntohs(ad[2]), __ntohs(ad[3]), __ntohs(ad[4]), __ntohs(ad[5]), - __ntohs(ad[6]), __ntohs(ad[7]), addr->ext_port); + __ntohs(ad[1]), __ntohs(ad[2]), __ntohs(ad[3]), __ntohs(ad[4]), + __ntohs(ad[5]), __ntohs(ad[6]), __ntohs(ad[7]), addr->ext_port); } return -EPROTONOSUPPORT; @@ -336,26 +336,26 @@ static size_t inet_copy_addr(int domain, struct sockaddr* saddr, size_t saddr_le size_t len = 0; switch (domain) { - case AF_INET: - in = (struct sockaddr_in*)&ss; - in->sin_family = AF_INET; - in->sin_port = __htons(addr->port); - in->sin_addr = addr->addr.v4; + case AF_INET: + in = (struct sockaddr_in*)&ss; + in->sin_family = AF_INET; + in->sin_port = __htons(addr->port); + in->sin_addr = addr->addr.v4; - len = MIN(saddr_len, sizeof(struct sockaddr_in)); - break; + len = MIN(saddr_len, sizeof(struct sockaddr_in)); + break; - case AF_INET6: - in6 = (struct sockaddr_in6*)&ss; - in6->sin6_family = AF_INET6; - in6->sin6_port = __htons(addr->port); - in6->sin6_addr = addr->addr.v6; + case AF_INET6: + in6 = (struct sockaddr_in6*)&ss; + in6->sin6_family = AF_INET6; + in6->sin6_port = __htons(addr->port); + in6->sin6_addr = addr->addr.v6; - len = MIN(saddr_len, sizeof(struct sockaddr_in6)); - break; + len = MIN(saddr_len, sizeof(struct sockaddr_in6)); + break; - default: - __abort(); /* this function must accept only AF_INET/AF_INET6 */ + default: + __abort(); /* this function must accept only AF_INET/AF_INET6 */ } memcpy(saddr, &ss, len); @@ -373,8 +373,8 @@ static void inet_save_addr(int domain, struct addr_inet* addr, const struct sock if (domain == AF_INET6) { if (saddr->sa_family == AF_INET) { - const struct sockaddr_in* in = (const struct sockaddr_in*)saddr; - addr->port = __ntohs(in->sin_port); + const struct sockaddr_in* in = (const struct sockaddr_in*)saddr; + addr->port = __ntohs(in->sin_port); addr->addr.v6.s6_addr32[0] = __htonl(0); addr->addr.v6.s6_addr32[1] = __htonl(0); addr->addr.v6.s6_addr32[2] = __htonl(0x0000ffff); @@ -382,8 +382,8 @@ static void inet_save_addr(int domain, struct addr_inet* addr, const struct sock addr->addr.v6.s6_addr32[3] = in->sin_addr.s_addr; } else { const struct sockaddr_in6* in6 = (const struct sockaddr_in6*)saddr; - addr->port = __ntohs(in6->sin6_port); - addr->addr.v6 = in6->sin6_addr; + addr->port = __ntohs(in6->sin6_port); + addr->addr.v6 = in6->sin6_addr; } return; } @@ -458,7 +458,6 @@ static int hash_to_hex_string(HASHTYPE hash, char* buf, size_t size) { return 0; } - int shim_do_bind(int sockfd, struct sockaddr* addr, int _addrlen) { if (_addrlen < 0) return -EINVAL; @@ -467,7 +466,7 @@ int shim_do_bind(int sockfd, struct sockaddr* addr, int _addrlen) { return -EFAULT; struct shim_handle* hdl = get_fd_handle(sockfd, NULL, NULL); - int ret = -EINVAL; + int ret = -EINVAL; if (!hdl) return -EBADF; @@ -728,7 +727,7 @@ int shim_do_connect(int sockfd, struct sockaddr* addr, int _addrlen) { struct shim_sock_handle* sock = &hdl->info.sock; lock(&hdl->lock); enum shim_sock_state state = sock->sock_state; - int ret = -EINVAL; + int ret = -EINVAL; if (state == SOCK_CONNECTED) { if (addr->sa_family == AF_UNSPEC) { @@ -1106,9 +1105,7 @@ static ssize_t do_sendmsg(int fd, struct iovec* bufs, int nbufs, int flags, inet_rebase_port(false, sock->domain, &addr_buf, false); size_t prefix_len = static_strlen(URI_PREFIX_UDP); memcpy(uri, URI_PREFIX_UDP, prefix_len + 1); - if ((ret = inet_translate_addr(sock->domain, - uri + prefix_len, - SOCK_URI_SIZE - prefix_len, + if ((ret = inet_translate_addr(sock->domain, uri + prefix_len, SOCK_URI_SIZE - prefix_len, &addr_buf)) < 0) { lock(&hdl->lock); goto out_locked; @@ -1118,7 +1115,7 @@ static ssize_t do_sendmsg(int fd, struct iovec* bufs, int nbufs, int flags, } int bytes = 0; - ret = 0; + ret = 0; for (int i = 0; i < nbufs; i++) { PAL_NUM pal_ret = DkStreamWrite(pal_hdl, 0, bufs[i].iov_len, bufs[i].iov_base, uri); @@ -1340,10 +1337,12 @@ static ssize_t do_recvmsg(int fd, struct iovec* bufs, size_t nbufs, int flags, /* some data left to read from peek buffer */ assert(total_bytes < peek_buffer->end - peek_buffer->start); iov_bytes = MIN(bufs[i].iov_len, peek_buffer->end - peek_buffer->start - total_bytes); - memcpy(bufs[i].iov_base, &peek_buffer->buf[peek_buffer->start + total_bytes], iov_bytes); + memcpy(bufs[i].iov_base, &peek_buffer->buf[peek_buffer->start + total_bytes], + iov_bytes); uri = peek_buffer->uri; } else { - PAL_NUM pal_ret = DkStreamRead(pal_hdl, 0, bufs[i].iov_len, bufs[i].iov_base, uri, uri ? SOCK_URI_SIZE : 0); + PAL_NUM pal_ret = DkStreamRead(pal_hdl, 0, bufs[i].iov_len, bufs[i].iov_base, uri, + uri ? SOCK_URI_SIZE : 0); if (pal_ret == PAL_STREAM_ERROR) { ret = PAL_NATIVE_ERRNO() == PAL_ERROR_STREAMNOTEXIST ? -ECONNABORTED @@ -1365,7 +1364,8 @@ static ssize_t do_recvmsg(int fd, struct iovec* bufs, size_t nbufs, int flags, if (uri) { struct addr_inet conn; - if ((ret = inet_parse_addr(sock->domain, sock->sock_type, uri, &conn, NULL)) < 0) { + if ((ret = inet_parse_addr(sock->domain, sock->sock_type, uri, &conn, NULL)) + < 0) { lock(&hdl->lock); goto out_locked; } @@ -1623,8 +1623,8 @@ struct __kernel_linger { static void __populate_addr_with_defaults(PAL_STREAM_ATTR* attr) { /* Linux default recv/send buffer sizes for new sockets */ - attr->socket.receivebuf = 212992; - attr->socket.sendbuf = 212992; + attr->socket.receivebuf = 212992; + attr->socket.sendbuf = 212992; attr->socket.linger = 0; attr->socket.receivetimeout = 0; @@ -2000,8 +2000,8 @@ int shim_do_getsockopt(int fd, int level, int optname, char* optval, int* optlen return ret; unknown_level: - ret = -EOPNOTSUPP; /* Kernel seems to return this value despite `man` saying that it can - * return only ENOPROTOOPT. */ + ret = -EOPNOTSUPP; /* Kernel seems to return this value despite `man` saying that it can + * return only ENOPROTOOPT. */ goto out; unknown_opt: ret = -ENOPROTOOPT; diff --git a/LibOS/shim/src/sys/shim_stat.c b/LibOS/shim/src/sys/shim_stat.c index 2c5ae7e0bd..ce255e3d21 100644 --- a/LibOS/shim/src/sys/shim_stat.c +++ b/LibOS/shim/src/sys/shim_stat.c @@ -10,13 +10,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" int shim_do_stat(const char* file, struct stat* stat) { if (!file || test_user_string(file)) diff --git a/LibOS/shim/src/sys/shim_time.c b/LibOS/shim/src/sys/shim_time.c index 2d17e507c4..b468792cb9 100644 --- a/LibOS/shim/src/sys/shim_time.c +++ b/LibOS/shim/src/sys/shim_time.c @@ -8,12 +8,13 @@ */ #include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" int shim_do_gettimeofday(struct __kernel_timeval* tv, struct __kernel_timezone* tz) { if (!tv) diff --git a/LibOS/shim/src/sys/shim_uname.c b/LibOS/shim/src/sys/shim_uname.c index 2af04153d1..16111c7878 100644 --- a/LibOS/shim/src/sys/shim_uname.c +++ b/LibOS/shim/src/sys/shim_uname.c @@ -15,20 +15,19 @@ #include "shim_internal.h" #include "shim_table.h" - /* This structure is *not* shared between Graphene processes, despite it should. As a result, * effects of set{host,domain}name in process A will not be visible in process B. * These syscalls are rarely used and are implemented in Graphene mainly to enable LTP to test * our `uname` implementation. */ static struct new_utsname g_current_uname = { - .sysname = "Linux", - .nodename = "localhost", - .release = "3.10.0", - .version = "1", + .sysname = "Linux", + .nodename = "localhost", + .release = "3.10.0", + .version = "1", #ifdef __x86_64__ - .machine = "x86_64", + .machine = "x86_64", #else - #error "Not implemented" +#error "Not implemented" #endif .domainname = "(none)", /* this seems to be the default on Linux */ }; diff --git a/LibOS/shim/src/sys/shim_wait.c b/LibOS/shim/src/sys/shim_wait.c index b6a3256ba0..f6a8ccb787 100644 --- a/LibOS/shim/src/sys/shim_wait.c +++ b/LibOS/shim/src/sys/shim_wait.c @@ -9,19 +9,20 @@ #include #include -#include -#include -#include -#include -#include -#include #include #include +#include "pal.h" +#include "pal_error.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_thread.h" +#include "shim_utils.h" + pid_t shim_do_wait4(pid_t pid, int* status, int option, struct __kernel_rusage* ru) { struct shim_thread* cur = get_cur_thread(); struct shim_thread* thread = NULL; - int ret = 0; + int ret = 0; __UNUSED(ru); if (option & ~(WNOHANG | WUNTRACED | WCONTINUED | __WNOTHREAD | __WCLONE | __WALL)) { diff --git a/LibOS/shim/src/sys/shim_wrappers.c b/LibOS/shim/src/sys/shim_wrappers.c index 5398be46fb..f6f7997261 100644 --- a/LibOS/shim/src/sys/shim_wrappers.c +++ b/LibOS/shim/src/sys/shim_wrappers.c @@ -8,13 +8,14 @@ */ #include -#include -#include -#include -#include -#include -#include -#include + +#include "pal.h" +#include "pal_error.h" +#include "shim_fs.h" +#include "shim_handle.h" +#include "shim_internal.h" +#include "shim_table.h" +#include "shim_utils.h" ssize_t shim_do_readv(int fd, const struct iovec* vec, int vlen) { if (!vec || test_user_memory((void*)vec, sizeof(*vec) * vlen, false)) diff --git a/LibOS/shim/src/syscallas-x86_64.S b/LibOS/shim/src/syscallas-x86_64.S index 83cd074b7e..23532941d5 100644 --- a/LibOS/shim/src/syscallas-x86_64.S +++ b/LibOS/shim/src/syscallas-x86_64.S @@ -7,8 +7,8 @@ * This file contains the entry point of system call table in library OS. */ -#include "shim_defs.h" #include "asm-offsets.h" +#include "shim_defs.h" .global syscalldb .type syscalldb, @function diff --git a/LibOS/shim/src/utils/md5.c b/LibOS/shim/src/utils/md5.c index c87da8275f..6f0dc4ca0a 100644 --- a/LibOS/shim/src/utils/md5.c +++ b/LibOS/shim/src/utils/md5.c @@ -31,8 +31,8 @@ ********************************************************************** */ -#include -#include +#include "shim_internal.h" +#include "shim_utils.h" /* forward declaration */ static void __transform(UINT4* buf, UINT4* in); diff --git a/LibOS/shim/src/utils/printf.c b/LibOS/shim/src/utils/printf.c index 46ca4d5074..200737b555 100644 --- a/LibOS/shim/src/utils/printf.c +++ b/LibOS/shim/src/utils/printf.c @@ -1,14 +1,15 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2014 Stony Brook University */ -#include -#include -#include -#include -#include #include #include +#include "api.h" +#include "pal.h" +#include "shim_defs.h" +#include "shim_internal.h" +#include "shim_ipc.h" + PAL_HANDLE debug_handle = NULL; static inline int debug_fputs(const char* buf, int len) { @@ -24,7 +25,7 @@ static int debug_fputch(void* f, int ch, void* b) { buf->buf[buf->end++] = ch; if (ch == '\n') { - int ret = debug_fputs(buf->buf, buf->end); + int ret = debug_fputs(buf->buf, buf->end); buf->end = buf->start; return ret; } diff --git a/LibOS/shim/src/utils/strobjs.c b/LibOS/shim/src/utils/strobjs.c index f3e407409c..678a184c4e 100644 --- a/LibOS/shim/src/utils/strobjs.c +++ b/LibOS/shim/src/utils/strobjs.c @@ -7,8 +7,8 @@ * This file contain functions to allocate / free a fixed-size string object. */ -#include -#include +#include "shim_internal.h" +#include "shim_utils.h" static struct shim_lock str_mgr_lock; diff --git a/LibOS/shim/test/benchmark/sig_latency.c b/LibOS/shim/test/benchmark/sig_latency.c index dde39ddebf..06bff347c3 100644 --- a/LibOS/shim/test/benchmark/sig_latency.c +++ b/LibOS/shim/test/benchmark/sig_latency.c @@ -158,7 +158,8 @@ int main(int argc, char** argv) { close(pipes[0]); - if (write(pipes[5], timevals, sizeof(struct timeval) * 2) != sizeof(struct timeval) * 2) { + if (write(pipes[5], timevals, sizeof(struct timeval) * 2) != + sizeof(struct timeval) * 2) { perror("write error"); return 1; } diff --git a/LibOS/shim/test/fs/common.c b/LibOS/shim/test/fs/common.c index 3c993dbc23..19f4f2f90f 100644 --- a/LibOS/shim/test/fs/common.c +++ b/LibOS/shim/test/fs/common.c @@ -58,7 +58,7 @@ off_t tell_fd(const char* path, int fd) { } int open_output_fd(const char* path, bool rdwr) { - int fd = open(path, rdwr ? O_RDWR|O_CREAT : O_WRONLY|O_CREAT, 0664); + int fd = open(path, rdwr ? O_RDWR | O_CREAT : O_WRONLY | O_CREAT, 0664); if (fd < 0) fatal_error("Failed to open output file %s: %s\n", path, strerror(errno)); return fd; diff --git a/LibOS/shim/test/fs/copy_mmap_seq.c b/LibOS/shim/test/fs/copy_mmap_seq.c index fc173f194f..e22e40d7c2 100644 --- a/LibOS/shim/test/fs/copy_mmap_seq.c +++ b/LibOS/shim/test/fs/copy_mmap_seq.c @@ -22,7 +22,8 @@ void copy_data(int fi, int fo, const char* input_path, const char* output_path, step = size - offset; if (ftruncate(fo, offset + step) != 0) - fatal_error("ftruncate(%s, %zu) failed: %s\n", output_path, offset + step, strerror(errno)); + fatal_error("ftruncate(%s, %zu) failed: %s\n", output_path, offset + step, + strerror(errno)); memcpy(out + offset, in + offset, step); offset += step; diff --git a/LibOS/shim/test/fs/delete.c b/LibOS/shim/test/fs/delete.c index 6e6139600e..7b626af2b5 100644 --- a/LibOS/shim/test/fs/delete.c +++ b/LibOS/shim/test/fs/delete.c @@ -24,8 +24,7 @@ static void file_delete(const char* file_path_1, const char* file_path_2, bool w printf("close(%s) %s 2 OK\n", file_path_2, type); } -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { if (argc < 6) fatal_error("Usage: %s \n", argv[0]); diff --git a/LibOS/shim/test/fs/open_flags.c b/LibOS/shim/test/fs/open_flags.c index 95aacbf9c2..171d64d167 100644 --- a/LibOS/shim/test/fs/open_flags.c +++ b/LibOS/shim/test/fs/open_flags.c @@ -43,15 +43,15 @@ int main(int argc, char* argv[]) { setup(); // doesn't exist - should create - OPEN_TEST(argv[1], O_CREAT|O_EXCL|O_RDWR, /*exists=*/false, /*expect_success=*/true, + OPEN_TEST(argv[1], O_CREAT | O_EXCL | O_RDWR, /*exists=*/false, /*expect_success=*/true, /*do_write=*/true); // exists - open should fail - OPEN_TEST(argv[1], O_CREAT|O_EXCL|O_RDWR, /*exists=*/true, /*expect_success=*/false, + OPEN_TEST(argv[1], O_CREAT | O_EXCL | O_RDWR, /*exists=*/true, /*expect_success=*/false, /*do_write=*/false); // exists - should open existing and NOT truncate - OPEN_TEST(argv[1], O_CREAT|O_RDWR, /*exists=*/true, /*expect_success=*/true, + OPEN_TEST(argv[1], O_CREAT | O_RDWR, /*exists=*/true, /*expect_success=*/true, /*do_write=*/false); if (get_file_size(argv[1]) != 1) fatal_error("File was truncated\n"); @@ -60,18 +60,18 @@ int main(int argc, char* argv[]) { fatal_error("unlink(%s) failed: %s\n", argv[1], strerror(errno)); // doesn't exist - should create new - OPEN_TEST(argv[1], O_CREAT|O_RDWR, /*exists=*/false, /*expect_success=*/true, + OPEN_TEST(argv[1], O_CREAT | O_RDWR, /*exists=*/false, /*expect_success=*/true, /*do_write=*/false); if (unlink(argv[1]) < 0) fatal_error("unlink(%s) failed: %s\n", argv[1], strerror(errno)); // doesn't exist - should create new - OPEN_TEST(argv[1], O_CREAT|O_TRUNC|O_RDWR, /*exists=*/false, /*expect_success=*/true, + OPEN_TEST(argv[1], O_CREAT | O_TRUNC | O_RDWR, /*exists=*/false, /*expect_success=*/true, /*do_write=*/true); // exists - should truncate - OPEN_TEST(argv[1], O_CREAT|O_TRUNC|O_RDWR, /*exists=*/true, /*expect_success=*/true, + OPEN_TEST(argv[1], O_CREAT | O_TRUNC | O_RDWR, /*exists=*/true, /*expect_success=*/true, /*do_write=*/false); if (get_file_size(argv[1]) != 0) fatal_error("File was not truncated\n"); diff --git a/LibOS/shim/test/fs/read_write.c b/LibOS/shim/test/fs/read_write.c index ee2b84719c..7c74ef4f8b 100644 --- a/LibOS/shim/test/fs/read_write.c +++ b/LibOS/shim/test/fs/read_write.c @@ -27,7 +27,8 @@ static void read_write(const char* file_path) { seek_fd(file_path, fd, offset, SEEK_SET); read_fd(file_path, fd, buf2, chunk_size); if (memcmp(buf1, buf2, chunk_size) != 0) - fatal_error("Chunk data is different from what was written (offset %zu, size %zu)\n", offset, chunk_size); + fatal_error("Chunk data is different from what was written (offset %zu, size %zu)\n", + offset, chunk_size); } close_fd(file_path, fd); diff --git a/LibOS/shim/test/fs/seek_tell.c b/LibOS/shim/test/fs/seek_tell.c index 03fdd6b524..25b4c7dfea 100644 --- a/LibOS/shim/test/fs/seek_tell.c +++ b/LibOS/shim/test/fs/seek_tell.c @@ -52,7 +52,7 @@ static void seek_output_fd(const char* path) { seek_fd(path, f, -EXTEND_SIZE - 1, SEEK_CUR); // rewind to former end printf("seek(%s) output end 3 OK\n", path); read_fd(path, f, buf, EXTEND_SIZE + 1); - for (size_t i=0; i -#include + +#include "shim_table.h" int main(int argc, char** argv) { pid_t pid = shim_fork(); diff --git a/LibOS/shim/test/inline/helloworld.c b/LibOS/shim/test/inline/helloworld.c index e3151bf249..1f07ba1cb9 100644 --- a/LibOS/shim/test/inline/helloworld.c +++ b/LibOS/shim/test/inline/helloworld.c @@ -1,4 +1,4 @@ -#include +#include "shim_table.h" int main(int argc, char** argv) { shim_write(1, "Hello world\n", 12); diff --git a/LibOS/shim/test/inline/vfork.c b/LibOS/shim/test/inline/vfork.c index 03098ef3c1..97835e4619 100644 --- a/LibOS/shim/test/inline/vfork.c +++ b/LibOS/shim/test/inline/vfork.c @@ -1,5 +1,6 @@ #include -#include + +#include "shim_table.h" int main(int argc, char** argv) { pid_t pid = shim_vfork(); diff --git a/LibOS/shim/test/native/epoll_socket.c b/LibOS/shim/test/native/epoll_socket.c index 861870e26d..157515307e 100644 --- a/LibOS/shim/test/native/epoll_socket.c +++ b/LibOS/shim/test/native/epoll_socket.c @@ -158,9 +158,8 @@ int main(int argc, char* argv[]) { s = getnameinfo(&in_addr, in_len, hbuf, sizeof hbuf, sbuf, sizeof sbuf, NI_NUMERICHOST | NI_NUMERICSERV); if (s == 0) - printf( - "Accepted connection on descriptor %d (host=%s, port=%s)\n", - infd, hbuf, sbuf); + printf("Accepted connection on descriptor %d (host=%s, port=%s)\n", infd, + hbuf, sbuf); /* Make the incoming socket non-blocking and add it to the list of fds to monitor. */ diff --git a/LibOS/shim/test/native/malloc.c b/LibOS/shim/test/native/malloc.c index a165871f4a..63bb075552 100644 --- a/LibOS/shim/test/native/malloc.c +++ b/LibOS/shim/test/native/malloc.c @@ -1,7 +1,7 @@ #include #include -static const size_t sizes[] = { 16, 32, 64, 128, 256, 512 }; +static const size_t sizes[] = {16, 32, 64, 128, 256, 512}; int main(int argc, char** argv) { for (int i = 0; i < 100000; i++) { for (int j = 0; j < sizeof(sizes) / sizeof(sizes[0]); j++) { diff --git a/LibOS/shim/test/native/pid_alloc.c b/LibOS/shim/test/native/pid_alloc.c index e456f3e426..9e3c229c57 100644 --- a/LibOS/shim/test/native/pid_alloc.c +++ b/LibOS/shim/test/native/pid_alloc.c @@ -1,10 +1,10 @@ #define _GNU_SOURCE +#include #include #include -#include -#include #include #include +#include static int func(void* arg) { return 0; diff --git a/LibOS/shim/test/native/pipe_latency.c b/LibOS/shim/test/native/pipe_latency.c index 2bdea57299..26dc0e9705 100644 --- a/LibOS/shim/test/native/pipe_latency.c +++ b/LibOS/shim/test/native/pipe_latency.c @@ -163,7 +163,7 @@ int main(int argc, char** argv) { close(pipes[4]); if (write(pipes[3], bytes, times * 2) != times * 2) { - perror ("write error"); + perror("write error"); return 1; } close(pipes[3]); diff --git a/LibOS/shim/test/regression/abort_multithread.c b/LibOS/shim/test/regression/abort_multithread.c index 732fcab0ab..f2e1e6ce8f 100644 --- a/LibOS/shim/test/regression/abort_multithread.c +++ b/LibOS/shim/test/regression/abort_multithread.c @@ -7,7 +7,7 @@ static void* thread_abort(void* arg) { abort(); - return NULL; /* not reached */ + return NULL; /* not reached */ } int main(int argc, char* arvg[]) { diff --git a/LibOS/shim/test/regression/attestation.c b/LibOS/shim/test/regression/attestation.c index 9b67c8006e..c65982bc01 100644 --- a/LibOS/shim/test/regression/attestation.c +++ b/LibOS/shim/test/regression/attestation.c @@ -140,7 +140,7 @@ static int verify_report_mac(sgx_report_t* report) { memcpy(&key_request.key_id, &report->key_id, sizeof(key_request.key_id)); /* retrieve key via EGETKEY instruction leaf */ - __sgx_mem_aligned uint8_t key[128/8]; + __sgx_mem_aligned uint8_t key[128 / 8]; memset(key, 0, sizeof(key)); sgx_getkey(&key_request, (sgx_key_128bit_t*)key); @@ -303,8 +303,8 @@ static int test_quote_interface(void) { /* 3. verify report data read from `quote` */ if (bytes < sizeof(sgx_quote_t)) { - fprintf(stderr, "obtained SGX quote is too small: %ldB (must be at least %ldB)\n", - bytes, sizeof(sgx_quote_t)); + fprintf(stderr, "obtained SGX quote is too small: %ldB (must be at least %ldB)\n", bytes, + sizeof(sgx_quote_t)); return FAILURE; } diff --git a/LibOS/shim/test/regression/cpuid.c b/LibOS/shim/test/regression/cpuid.c index 8265395794..8a5f39fedb 100644 --- a/LibOS/shim/test/regression/cpuid.c +++ b/LibOS/shim/test/regression/cpuid.c @@ -13,8 +13,9 @@ struct regs { } __attribute__((packed)); static void cpuid(uint32_t leaf, uint32_t subleaf, struct regs* r) { - __asm__ volatile("cpuid" : "=a"(r->eax), "=b"(r->ebx), "=c"(r->ecx), "=d"(r->edx) - : "0"(leaf), "2"(subleaf)); + __asm__ volatile("cpuid" + : "=a"(r->eax), "=b"(r->ebx), "=c"(r->ecx), "=d"(r->edx) + : "0"(leaf), "2"(subleaf)); } static void test_cpuid_leaf_0xd(void) { @@ -22,11 +23,10 @@ static void test_cpuid_leaf_0xd(void) { const uint32_t leaf = 0xd; // Sub-leaf IDs for the various extensions. - enum cpu_extension { - x87 = 0, SSE, AVX, MPX_1, MPX_2, AVX512_1, AVX512_2, AVX512_3, PKRU = 9 }; - const uint32_t extension_sizes_bytes[] = - { [AVX] = 256, [MPX_1] = 64, [MPX_2] = 64, [AVX512_1] = 64, [AVX512_2] = 512, - [AVX512_3] = 1024, [PKRU] = 8}; + enum cpu_extension { x87 = 0, SSE, AVX, MPX_1, MPX_2, AVX512_1, AVX512_2, AVX512_3, PKRU = 9 }; + const uint32_t extension_sizes_bytes[] = { + [AVX] = 256, [MPX_1] = 64, [MPX_2] = 64, [AVX512_1] = 64, + [AVX512_2] = 512, [AVX512_3] = 1024, [PKRU] = 8}; enum register_index { EAX = 0, EBX, ECX, EDX }; @@ -69,7 +69,6 @@ static void test_cpuid_leaf_0xd(void) { } int main(int argc, char** argv, char** envp) { - test_cpuid_leaf_0xd(); printf("CPUID test passed.\n"); return 0; diff --git a/LibOS/shim/test/regression/eventfd.c b/LibOS/shim/test/regression/eventfd.c index 05ffeb34ef..c7e5faed22 100644 --- a/LibOS/shim/test/regression/eventfd.c +++ b/LibOS/shim/test/regression/eventfd.c @@ -65,9 +65,9 @@ static void* write_eventfd_thread(void* arg) { static int eventfd_using_poll(void) { int ret = 0; struct pollfd pollfds[MAX_EFDS]; - pthread_t tid = 0; - uint64_t count = 0; - int poll_ret = 0; + pthread_t tid = 0; + uint64_t count = 0; + int poll_ret = 0; int nread_events = 0; for (int i = 0; i < MAX_EFDS; i++) { @@ -199,8 +199,7 @@ static int eventfd_using_various_flags(void) { errno = 0; ssize_t ret = read(efd, &count, sizeof(count)); if (ret != -1 || errno != EAGAIN) { - printf("read that should return -1 with EAGAIN returned: %ld with errno=%d\n", - ret, + printf("read that should return -1 with EAGAIN returned: %ld with errno=%d\n", ret, errno); close(efd); return 1; diff --git a/LibOS/shim/test/regression/exec_same.c b/LibOS/shim/test/regression/exec_same.c index dade7e6a96..9ab172263d 100644 --- a/LibOS/shim/test/regression/exec_same.c +++ b/LibOS/shim/test/regression/exec_same.c @@ -41,11 +41,11 @@ int main(int argc, char** argv) { */ (void)thread_func; // to satisfy compiler /* Creating another thread and doing a race on execve. Only one thread should survive. */ - //pthread_t th; - //if (pthread_create(&th, NULL, thread_func, NULL) != 0) { - // perror("pthread_create failed"); - // return 1; - //} + // pthread_t th; + // if (pthread_create(&th, NULL, thread_func, NULL) != 0) { + // perror("pthread_create failed"); + // return 1; + // } do_exec(); } diff --git a/LibOS/shim/test/regression/file_size.c b/LibOS/shim/test/regression/file_size.c index 8bb8b9fb38..59b43bd245 100644 --- a/LibOS/shim/test/regression/file_size.c +++ b/LibOS/shim/test/regression/file_size.c @@ -9,7 +9,7 @@ #include #define STR_HELPER(x) #x -#define STR(x) STR_HELPER(x) +#define STR(x) STR_HELPER(x) #define BUF_LENGTH 4096 #define HOLE_LENGTH 8192 @@ -57,13 +57,14 @@ int main(int argc, const char** argv) { return 1; } - rv = unlink(TEST_DIR"/"TEST_FILE); + rv = unlink(TEST_DIR "/" TEST_FILE); if (rv < 0 && errno != ENOENT) { perror("unlink failed"); return 1; } - fd = open(TEST_DIR"/"TEST_FILE, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + fd = open(TEST_DIR "/" TEST_FILE, O_CREAT | O_RDWR | O_EXCL, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (fd < 0) { perror("open failed"); return 1; @@ -106,7 +107,7 @@ int main(int argc, const char** argv) { return 1; } - fd = open(TEST_DIR"/"TEST_FILE, O_RDONLY); + fd = open(TEST_DIR "/" TEST_FILE, O_RDONLY); if (fd < 0) { perror("open failed"); return 1; @@ -131,7 +132,7 @@ int main(int argc, const char** argv) { return 1; } - rv = unlink(TEST_DIR"/"TEST_FILE); + rv = unlink(TEST_DIR "/" TEST_FILE); if (rv < 0) { perror("unlink failed"); return 1; diff --git a/LibOS/shim/test/regression/futex_requeue.c b/LibOS/shim/test/regression/futex_requeue.c index 92062cb9c4..0cf53a4814 100644 --- a/LibOS/shim/test/regression/futex_requeue.c +++ b/LibOS/shim/test/regression/futex_requeue.c @@ -6,11 +6,11 @@ #include #include #include -#include +#include #include - -static int futex(int* uaddr, int futex_op, int val, const struct timespec* timeout, int* uaddr2, int val3) { +static int futex(int* uaddr, int futex_op, int val, const struct timespec* timeout, int* uaddr2, + int val3) { return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3); } @@ -22,8 +22,10 @@ static int futex_wake(int* uaddr, int to_wake) { return futex(uaddr, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, to_wake, NULL, NULL, 0); } -static int futex_cmp_requeue(int* uaddr, int val, int to_wake, int* uaddr2, unsigned int max_requeue) { - return futex(uaddr, FUTEX_CMP_REQUEUE | FUTEX_PRIVATE_FLAG, to_wake, (struct timespec*)(unsigned long)max_requeue, uaddr2, val); +static int futex_cmp_requeue(int* uaddr, int val, int to_wake, int* uaddr2, + unsigned int max_requeue) { + return futex(uaddr, FUTEX_CMP_REQUEUE | FUTEX_PRIVATE_FLAG, to_wake, + (struct timespec*)(unsigned long)max_requeue, uaddr2, val); } static void fail(const char* msg, int x) { @@ -47,11 +49,11 @@ static int load(int* ptr) { static int futex1 = 0; static int futex2 = 0; -#define THREADS 9 -#define THREADS_WAKE 2 +#define THREADS 9 +#define THREADS_WAKE 2 #define THREADS_REQUEUE 3 -static int thread_state[THREADS] = { 0 }; +static int thread_state[THREADS] = {0}; static void* thread_func(void* arg) { unsigned long i = (unsigned long)arg; @@ -92,7 +94,8 @@ int main(void) { fail("futex_cmp_requeue", errno); } if (ret != THREADS_WAKE + THREADS_REQUEUE) { - printf("futex_cmp_requeue returned %d instead of %d!\n", ret, THREADS_WAKE + THREADS_REQUEUE); + printf("futex_cmp_requeue returned %d instead of %d!\n", ret, + THREADS_WAKE + THREADS_REQUEUE); return 1; } @@ -117,7 +120,8 @@ int main(void) { fail("futex_wake(&futex1)", errno); } if (ret != (THREADS - THREADS_WAKE - THREADS_REQUEUE)) { - printf("futex_wake on futex1 woke-up %d threads instead of %d!\n", ret, THREADS - THREADS_WAKE - THREADS_REQUEUE); + printf("futex_wake on futex1 woke-up %d threads instead of %d!\n", ret, + THREADS - THREADS_WAKE - THREADS_REQUEUE); return 1; } diff --git a/LibOS/shim/test/regression/futex_timeout.c b/LibOS/shim/test/regression/futex_timeout.c index 802c2cddb9..220bc09b7c 100644 --- a/LibOS/shim/test/regression/futex_timeout.c +++ b/LibOS/shim/test/regression/futex_timeout.c @@ -15,8 +15,8 @@ int main(int argc, const char** argv) { int futex_errno = 0; struct timespec t = {.tv_sec = SLEEP_SEC, .tv_nsec = 0}; - struct timeval tv1 = { 0 }; - struct timeval tv2 = { 0 }; + struct timeval tv1 = {0}; + struct timeval tv2 = {0}; printf("invoke futex syscall with a %d second timeout\n", SLEEP_SEC); if (gettimeofday(&tv1, NULL)) { @@ -31,7 +31,8 @@ int main(int argc, const char** argv) { } if (ret != -1 || futex_errno != ETIMEDOUT) { - printf("futex syscall returned: %d with errno: %d (%s)\n", ret, futex_errno, strerror(futex_errno)); + printf("futex syscall returned: %d with errno: %d (%s)\n", ret, futex_errno, + strerror(futex_errno)); return 1; } diff --git a/LibOS/shim/test/regression/futex_wake_op.c b/LibOS/shim/test/regression/futex_wake_op.c index 58816a0611..edf958e524 100644 --- a/LibOS/shim/test/regression/futex_wake_op.c +++ b/LibOS/shim/test/regression/futex_wake_op.c @@ -6,11 +6,11 @@ #include #include #include -#include +#include #include - -static int futex(int* uaddr, int futex_op, int val, const struct timespec* timeout, int* uaddr2, int val3) { +static int futex(int* uaddr, int futex_op, int val, const struct timespec* timeout, int* uaddr2, + int val3) { return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3); } @@ -23,7 +23,8 @@ static int futex_wake(int* uaddr, int to_wake) { } static int futex_wake_op(int* uaddr1, int to_wake1, int* uaddr2, int to_wake2, int op) { - return futex(uaddr1, FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG, to_wake1, (struct timespec*)(unsigned long)to_wake2, uaddr2, op); + return futex(uaddr1, FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG, to_wake1, + (struct timespec*)(unsigned long)to_wake2, uaddr2, op); } static void fail(const char* msg, int x) { @@ -54,12 +55,12 @@ static int wakeop_arg_extend(int x) { static int futex1 = 0; static int futex2 = 0; -#define THREADS1 4 -#define THREADS2 5 +#define THREADS1 4 +#define THREADS2 5 #define THREADS_WAKE1 2 #define THREADS_WAKE2 3 -static int thread_state[THREADS1 + THREADS2] = { 0 }; +static int thread_state[THREADS1 + THREADS2] = {0}; static void* thread_func(void* arg) { unsigned long i = (unsigned long)arg; @@ -112,7 +113,10 @@ int main(void) { op = load(&futex2); if (op != (arg1 ^ arg2)) { - printf("futex_wake_op did not set futex2 value correctly: current value: 0x%x, expected: 0x%x\n", op, arg1 ^ arg2); + printf( + "futex_wake_op did not set futex2 value correctly: current value: 0x%x, expected: " + "0x%x\n", + op, arg1 ^ arg2); return 1; } @@ -158,7 +162,8 @@ int main(void) { fail("futex_wake(&futex1)", errno); } if (ret != (THREADS1 - THREADS_WAKE1)) { - printf("futex_wake on futex1 woke-up %d threads instead of %d!\n", ret, THREADS1 - THREADS_WAKE1); + printf("futex_wake on futex1 woke-up %d threads instead of %d!\n", ret, + THREADS1 - THREADS_WAKE1); return 1; } @@ -167,7 +172,8 @@ int main(void) { fail("futex_wake(&futex2)", errno); } if (ret != (THREADS2 - THREADS_WAKE2)) { - printf("futex_wake on futex2 woke-up %d threads instead of %d!\n", ret, THREADS2 - THREADS_WAKE2); + printf("futex_wake on futex2 woke-up %d threads instead of %d!\n", ret, + THREADS2 - THREADS_WAKE2); return 1; } diff --git a/LibOS/shim/test/regression/mmap_file.c b/LibOS/shim/test/regression/mmap_file.c index 655f5bb9d3..eddd640976 100644 --- a/LibOS/shim/test/regression/mmap_file.c +++ b/LibOS/shim/test/regression/mmap_file.c @@ -41,7 +41,7 @@ int main(int argc, const char** argv) { a[1023] = 0xff; a[4095] = 0xff; - __asm__ volatile ("nop" ::: "memory"); + __asm__ volatile("nop" ::: "memory"); int pid = fork(); if (pid == -1) { @@ -56,14 +56,14 @@ int main(int argc, const char** argv) { } } - __asm__ volatile ("nop" ::: "memory"); + __asm__ volatile("nop" ::: "memory"); a[0] = 0xff; printf(pid == 0 ? "mmap test 1 passed\n" : "mmap test 6 passed\n"); a[1024] = 0xff; printf(pid == 0 ? "mmap test 2 passed\n" : "mmap test 7 passed\n"); - __asm__ volatile ("nop" ::: "memory"); + __asm__ volatile("nop" ::: "memory"); if (pid == 0) { if (a[1023] == 0xff) @@ -72,7 +72,7 @@ int main(int argc, const char** argv) { printf("mmap test 4 passed\n"); } - __asm__ volatile ("nop" ::: "memory"); + __asm__ volatile("nop" ::: "memory"); if (signal(SIGBUS, SIGBUS_handler) == SIG_ERR) { perror("signal"); @@ -81,7 +81,7 @@ int main(int argc, const char** argv) { message = pid == 0 ? "mmap test 5 passed\n" : "mmap test 8 passed\n"; /* need a barrier to assign message before SIGBUS due to a[4096] */ - __asm__ volatile ("nop" ::: "memory"); + __asm__ volatile("nop" ::: "memory"); a[4096] = 0xff; if (signal(SIGBUS, SIG_DFL) == SIG_ERR) { diff --git a/LibOS/shim/test/regression/mprotect_file_fork.c b/LibOS/shim/test/regression/mprotect_file_fork.c index e3960512bc..d7dddaf02c 100644 --- a/LibOS/shim/test/regression/mprotect_file_fork.c +++ b/LibOS/shim/test/regression/mprotect_file_fork.c @@ -15,7 +15,7 @@ int main(void) { int fd; - void *ptr; + void* ptr; if (mkdir("/tmp", S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) { err(1, "mkdir"); diff --git a/LibOS/shim/test/regression/pipe_nonblocking.c b/LibOS/shim/test/regression/pipe_nonblocking.c index 064e6e7910..bb8fc09d28 100644 --- a/LibOS/shim/test/regression/pipe_nonblocking.c +++ b/LibOS/shim/test/regression/pipe_nonblocking.c @@ -39,4 +39,3 @@ int main(void) { puts("TEST OK"); return 0; } - diff --git a/LibOS/shim/test/regression/pipe_ocloexec.c b/LibOS/shim/test/regression/pipe_ocloexec.c index 58ade99267..aae267741a 100644 --- a/LibOS/shim/test/regression/pipe_ocloexec.c +++ b/LibOS/shim/test/regression/pipe_ocloexec.c @@ -36,7 +36,7 @@ int main(int argc, char* argv[]) { if (pid < 0) { err(1, "fork"); } else if (pid == 0) { - char* arg[] = { argv[0], "xxx", NULL }; + char* arg[] = {argv[0], "xxx", NULL}; execv(argv[0], arg); err(1, "execve"); } @@ -77,4 +77,3 @@ int main(int argc, char* argv[]) { puts("TEST OK"); return 0; } - diff --git a/LibOS/shim/test/regression/poll_closed_fd.c b/LibOS/shim/test/regression/poll_closed_fd.c index ea57c86c5c..a0235bb709 100644 --- a/LibOS/shim/test/regression/poll_closed_fd.c +++ b/LibOS/shim/test/regression/poll_closed_fd.c @@ -52,7 +52,7 @@ int main(int argc, char** argv) { if (infds[0].revents & POLLIN) { bytes = read(pipefds[0], &buffer, bufsize - 1); - if (bytes < 0) { + if (bytes < 0) { perror("read error\n"); close(pipefds[0]); return 1; @@ -71,7 +71,7 @@ int main(int argc, char** argv) { perror("wait error\n"); close(pipefds[0]); return 1; - } else if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus)){ + } else if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus)) { perror("child process didn't exit successfully\n"); close(pipefds[0]); return 1; diff --git a/LibOS/shim/test/regression/proc_common.c b/LibOS/shim/test/regression/proc_common.c index 6c573259fa..4eaf82130d 100644 --- a/LibOS/shim/test/regression/proc_common.c +++ b/LibOS/shim/test/regression/proc_common.c @@ -61,7 +61,8 @@ int main(int argc, char** argv) { f = fopen("/proc/self/dummy", "r"); if (f != NULL || errno != ENOENT) { - perror("(sanity check) fopen of /proc/self/dummy (non-existing file) did not fail with ENOENT"); + perror("(sanity check) fopen of /proc/self/dummy (non-existing file) did not fail with " + "ENOENT"); return 1; } diff --git a/LibOS/shim/test/regression/rdtsc.c b/LibOS/shim/test/regression/rdtsc.c index f399343d5a..9780c7258b 100644 --- a/LibOS/shim/test/regression/rdtsc.c +++ b/LibOS/shim/test/regression/rdtsc.c @@ -6,18 +6,22 @@ static uint64_t rdtsc_start(void) { uint32_t low, high; __asm__ volatile( - "mfence; lfence;" /* memory barriers to sync RDTSC */ - "rdtsc;" - : "=d"(high), "=a"(low) : : "memory"); + "mfence; lfence;" /* memory barriers to sync RDTSC */ + "rdtsc;" + : "=d"(high), "=a"(low) + : + : "memory"); return (low | ((uint64_t)high) << 32); } static uint64_t rdtsc_end(void) { uint32_t low, high; __asm__ volatile( - "rdtscp;" /* use RDTSCP instead of RDTSC, just for testing */ - "lfence;" /* memory barrier to sync RDTSCP */ - : "=d"(high), "=a"(low) : : "%rcx", "memory"); + "rdtscp;" /* use RDTSCP instead of RDTSC, just for testing */ + "lfence;" /* memory barrier to sync RDTSCP */ + : "=d"(high), "=a"(low) + : + : "%rcx", "memory"); return (low | ((uint64_t)high) << 32); } diff --git a/LibOS/shim/test/regression/readdir.c b/LibOS/shim/test/regression/readdir.c index 350aedbff5..d515f38bb2 100644 --- a/LibOS/shim/test/regression/readdir.c +++ b/LibOS/shim/test/regression/readdir.c @@ -53,7 +53,7 @@ int main(int argc, const char** argv) { return 1; } - rv = unlink(TEST_DIR"/"TEST_FILE); + rv = unlink(TEST_DIR "/" TEST_FILE); if (rv < 0 && errno != ENOENT) { perror("unlink failed"); return 1; @@ -65,7 +65,8 @@ int main(int argc, const char** argv) { return 1; } - fd = open(TEST_DIR"/"TEST_FILE, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + fd = open(TEST_DIR "/" TEST_FILE, O_CREAT | O_RDWR | O_EXCL, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (fd < 0) { perror("open failed"); return 1; @@ -82,7 +83,7 @@ int main(int argc, const char** argv) { return 1; } - rv = unlink(TEST_DIR"/"TEST_FILE); + rv = unlink(TEST_DIR "/" TEST_FILE); if (rv < 0) { perror("unlink failed"); return 1; diff --git a/LibOS/shim/test/regression/sigaction_per_process.c b/LibOS/shim/test/regression/sigaction_per_process.c index 85e90510c7..cd41d22a86 100644 --- a/LibOS/shim/test/regression/sigaction_per_process.c +++ b/LibOS/shim/test/regression/sigaction_per_process.c @@ -27,8 +27,8 @@ static pid_t who2 = 0; static void sigterm_handler(int signum) { pid_t v = 0; pid_t my_tid = mygettid(); - if (!__atomic_compare_exchange_n(&who1, &v, my_tid, /*weak=*/0, - __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) { + if (!__atomic_compare_exchange_n(&who1, &v, my_tid, /*weak=*/0, __ATOMIC_SEQ_CST, + __ATOMIC_SEQ_CST)) { __atomic_store_n(&who2, my_tid, __ATOMIC_SEQ_CST); } printf("sigterm_handler called in: %d\n", my_tid); @@ -48,7 +48,7 @@ static void wait_for(int x) { static void* f(void* x) { printf("thread id: %d\n", mygettid()); - struct sigaction action = { 0 }; + struct sigaction action = {0}; action.sa_handler = sigterm_handler; int ret = sigaction(SIGTERM, &action, NULL); diff --git a/LibOS/shim/test/regression/sigaltstack.c b/LibOS/shim/test/regression/sigaltstack.c index 7f2d162615..7d4638fc90 100644 --- a/LibOS/shim/test/regression/sigaltstack.c +++ b/LibOS/shim/test/regression/sigaltstack.c @@ -82,7 +82,7 @@ int main(int argc, char** argv) { act.sa_sigaction = handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO | SA_NODEFER | SA_ONSTACK; - ret = sigaction(SIGALRM, &act, NULL); + ret = sigaction(SIGALRM, &act, NULL); if (ret < 0) { err(EXIT_FAILURE, "sigaction"); } diff --git a/LibOS/shim/test/regression/sighandler_reset.c b/LibOS/shim/test/regression/sighandler_reset.c index 07b8165cf3..1e8f94cf5a 100644 --- a/LibOS/shim/test/regression/sighandler_reset.c +++ b/LibOS/shim/test/regression/sighandler_reset.c @@ -1,11 +1,10 @@ #define _XOPEN_SOURCE 700 +#include #include #include - -#include -#include #include #include +#include static int count = 0; diff --git a/LibOS/shim/test/regression/signal_multithread.c b/LibOS/shim/test/regression/signal_multithread.c index 5cae585908..0dccb45d64 100644 --- a/LibOS/shim/test/regression/signal_multithread.c +++ b/LibOS/shim/test/regression/signal_multithread.c @@ -33,7 +33,7 @@ int main() { setbuf(stdout, NULL); setbuf(stderr, NULL); - struct sigaction action = { 0 }; + struct sigaction action = {0}; action.sa_handler = sigterm_handler; int ret = sigaction(SIGTERM, &action, NULL); diff --git a/LibOS/shim/test/regression/sigprocmask_pending.c b/LibOS/shim/test/regression/sigprocmask_pending.c index 45f95d0a51..be80a73a7c 100644 --- a/LibOS/shim/test/regression/sigprocmask_pending.c +++ b/LibOS/shim/test/regression/sigprocmask_pending.c @@ -7,12 +7,13 @@ #include #include -#define CHECK(x) do { \ - if (x) { \ - perror(#x); \ - exit(1); \ - } \ -} while (0) +#define CHECK(x) \ + do { \ + if (x) { \ + perror(#x); \ + exit(1); \ + } \ + } while (0) static int seen_signal_cnt = 0; @@ -141,7 +142,7 @@ static void test_execve_start(char* self) { CHECK(kill(getpid(), SIGALRM) < 0); - char* argv[] = { self, "cont", NULL }; + char* argv[] = {self, "cont", NULL}; CHECK(execve(self, argv, NULL)); } diff --git a/LibOS/shim/test/regression/system.c b/LibOS/shim/test/regression/system.c index 9c441b5fee..6ecc7ce323 100644 --- a/LibOS/shim/test/regression/system.c +++ b/LibOS/shim/test/regression/system.c @@ -1,7 +1,7 @@ #include #include -int main(int argc, char const *argv[]) { +int main(int argc, char const* argv[]) { int ret = system("echo hello from system"); if (ret) { /* something went wrong with system() execution */ diff --git a/LibOS/shim/test/regression/tcp_ipv6_v6only.c b/LibOS/shim/test/regression/tcp_ipv6_v6only.c index a66d926dd1..b47237e00c 100644 --- a/LibOS/shim/test/regression/tcp_ipv6_v6only.c +++ b/LibOS/shim/test/regression/tcp_ipv6_v6only.c @@ -11,7 +11,7 @@ /* use the same loopback address and port for both IPV6 and IPV4 */ #define SRV_IPV6 "::1/128" #define SRV_IPV4 "127.0.0.1" -#define PORT 11112 +#define PORT 11112 int main(int argc, char** argv) { int socket_ipv4; @@ -61,7 +61,8 @@ int main(int argc, char** argv) { return 1; } - /* we must start listening on IPV6 socket to make it active and kick in Linux rules for bind() */ + /* we must start listening on IPV6 socket to make it active and kick in Linux rules for bind() + */ if (listen(socket_ipv6, 3) < 0) { perror("listen(ipv6)"); return 1; @@ -69,8 +70,8 @@ int main(int argc, char** argv) { struct sockaddr_in address_ipv4; memset(&address_ipv4, 0, sizeof(address_ipv4)); - address_ipv4.sin_family = AF_INET; - address_ipv4.sin_port = htons(PORT); /* note the same port! */ + address_ipv4.sin_family = AF_INET; + address_ipv4.sin_port = htons(PORT); /* note the same port! */ if (inet_pton(AF_INET, SRV_IPV4, &address_ipv4.sin_addr) < 0) { perror("inet_pton(ipv4)"); @@ -79,7 +80,8 @@ int main(int argc, char** argv) { ret = bind(socket_ipv4, (struct sockaddr*)&address_ipv4, sizeof(address_ipv4)); if (ret != -1 || errno != EADDRINUSE) { - fprintf(stderr, "bind(ipv4) was successful even though there is no IPV6_V6ONLY on same port\n"); + fprintf(stderr, + "bind(ipv4) was successful even though there is no IPV6_V6ONLY on same port\n"); return 1; } diff --git a/LibOS/shim/test/regression/tcp_msg_peek.c b/LibOS/shim/test/regression/tcp_msg_peek.c index 1acb2f7bef..c385272cdd 100644 --- a/LibOS/shim/test/regression/tcp_msg_peek.c +++ b/LibOS/shim/test/regression/tcp_msg_peek.c @@ -13,7 +13,7 @@ #include #define SRV_IP "127.0.0.1" -#define PORT 11111 +#define PORT 11111 #define BUFLEN 512 enum { SINGLE, PARALLEL } mode = PARALLEL; diff --git a/Pal/include/arch/x86_64/Linux-SGX/sigcontext.h b/Pal/include/arch/x86_64/Linux-SGX/sigcontext.h index 782e38323e..28f2c0965f 100644 --- a/Pal/include/arch/x86_64/Linux-SGX/sigcontext.h +++ b/Pal/include/arch/x86_64/Linux-SGX/sigcontext.h @@ -9,6 +9,6 @@ #ifndef _LINUX_SGX_SIGCONTEXT_H #define _LINUX_SGX_SIGCONTEXT_H -#include +#include "Linux/sigcontext.h" #endif /* _LINUX_SGX_SIGCONTEXT_H */ diff --git a/Pal/include/arch/x86_64/Linux-SGX/ucontext.h b/Pal/include/arch/x86_64/Linux-SGX/ucontext.h index da317f57d4..00dd2ab8ed 100644 --- a/Pal/include/arch/x86_64/Linux-SGX/ucontext.h +++ b/Pal/include/arch/x86_64/Linux-SGX/ucontext.h @@ -9,6 +9,6 @@ #ifndef _LINUX_SGX_UCONTEXT_H #define _LINUX_SGX_UCONTEXT_H -#include +#include "Linux/ucontext.h" #endif /* _LINUX_SGX_UCONTEXT_H */ diff --git a/Pal/include/arch/x86_64/Linux/elf-arch.h b/Pal/include/arch/x86_64/Linux/elf-arch.h index a5dc144a0e..fa1e279e39 100644 --- a/Pal/include/arch/x86_64/Linux/elf-arch.h +++ b/Pal/include/arch/x86_64/Linux/elf-arch.h @@ -1,20 +1,13 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2014 Stony Brook University */ -/* - * dl-machine-x86_64.h - * - * This files contain architecture-specific implementation of ELF dynamic - * relocation function. - * The source code is imported and modified from the GNU C Library. - */ +#ifndef ELF_ARCH_H_ +#define ELF_ARCH_H_ #define ELF_MACHINE_NAME "x86_64" -#include -#include - #include "pal_internal.h" +#include "sysdeps/generic/ldsodefs.h" /* Return the link-time address of _DYNAMIC. Conveniently, this is the first element of the GOT. This must be inlined in a function which @@ -60,3 +53,5 @@ static inline Elf64_Addr __attribute__((unused)) elf_machine_load_address(void) return addr; } + +#endif /* ELF_ARCH_H_ */ diff --git a/Pal/include/arch/x86_64/Linux/pal_linux_defs.h b/Pal/include/arch/x86_64/Linux/pal_linux_defs.h index e9e4901c7e..b741149bfd 100644 --- a/Pal/include/arch/x86_64/Linux/pal_linux_defs.h +++ b/Pal/include/arch/x86_64/Linux/pal_linux_defs.h @@ -3,8 +3,8 @@ #define USER_ADDRESS_LOWEST 0x10000 -#define THREAD_STACK_SIZE (PRESET_PAGESIZE * 2) /* 8KB initial stack (grows automatically) */ -#define ALT_STACK_SIZE (PRESET_PAGESIZE * 16) /* 64KB signal stack */ +#define THREAD_STACK_SIZE (PRESET_PAGESIZE * 2) /* 8KB initial stack (grows automatically) */ +#define ALT_STACK_SIZE (PRESET_PAGESIZE * 16) /* 64KB signal stack */ #define USE_VSYSCALL_GETTIME 0 #define USE_VDSO_GETTIME 1 diff --git a/Pal/include/arch/x86_64/Linux/sysdep-arch.h b/Pal/include/arch/x86_64/Linux/sysdep-arch.h index 55d5b2451b..f5eb6b278c 100644 --- a/Pal/include/arch/x86_64/Linux/sysdep-arch.h +++ b/Pal/include/arch/x86_64/Linux/sysdep-arch.h @@ -7,7 +7,8 @@ #define _LINUX_X86_64_SYSDEP_ARCH_H 1 #include -#include + +#include "sysdeps/generic/sysdep.h" /* For Linux we can use the system call table in the header file /usr/include/asm/unistd.h diff --git a/Pal/include/arch/x86_64/Linux/ucontext.h b/Pal/include/arch/x86_64/Linux/ucontext.h index 729b885584..a64ddd30b3 100644 --- a/Pal/include/arch/x86_64/Linux/ucontext.h +++ b/Pal/include/arch/x86_64/Linux/ucontext.h @@ -19,15 +19,16 @@ #ifndef _LINUX_X86_64_UCONTEXT_H #define _LINUX_X86_64_UCONTEXT_H 1 -#include #include #include /* We need the signal context definitions even if they are not used included in . */ -#include +#include "sigcontext.h" -#include "pal-arch.h" +#include "api.h" +#include "assert.h" +#include "pal.h" #if __WORDSIZE == 64 @@ -156,9 +157,9 @@ static inline uint64_t pal_ucontext_get_ip(ucontext_t* uc) { return uc->uc_mcontext.gregs[REG_RIP]; } -static inline void pal_ucontext_set_function_parameters(ucontext_t* uc, void* func, - size_t count, ...) { - const unsigned int param_regs[] = { REG_RDI, REG_RSI, REG_RDX, REG_RCX }; +static inline void pal_ucontext_set_function_parameters(ucontext_t* uc, void* func, size_t count, + ...) { + const unsigned int param_regs[] = {REG_RDI, REG_RSI, REG_RDX, REG_RCX}; va_list ap; assert(count <= ARRAY_SIZE(param_regs)); diff --git a/Pal/include/arch/x86_64/Skeleton/pal_host-arch.h b/Pal/include/arch/x86_64/Skeleton/pal_host-arch.h index a9d904abad..78bd767e0c 100644 --- a/Pal/include/arch/x86_64/Skeleton/pal_host-arch.h +++ b/Pal/include/arch/x86_64/Skeleton/pal_host-arch.h @@ -5,4 +5,3 @@ * * This file contains Skeleton-specific functions related to the PAL. */ - diff --git a/Pal/include/arch/x86_64/Skeleton/ucontext.h b/Pal/include/arch/x86_64/Skeleton/ucontext.h index f1f04a2fca..99286d6fdf 100644 --- a/Pal/include/arch/x86_64/Skeleton/ucontext.h +++ b/Pal/include/arch/x86_64/Skeleton/ucontext.h @@ -9,6 +9,6 @@ #ifndef _SKELETON_UCONTEXT_H #define _SKELETON_UCONTEXT_H -#include +#include "Linux/ucontext.h" #endif /* _SKELETON_UCONTEXT_H */ diff --git a/Pal/include/arch/x86_64/cpu.h b/Pal/include/arch/x86_64/cpu.h index 3a73271f90..7e41e6ff66 100644 --- a/Pal/include/arch/x86_64/cpu.h +++ b/Pal/include/arch/x86_64/cpu.h @@ -20,27 +20,26 @@ enum PAL_CPUID_WORD { #define INTEL_SGX_LEAF 0x12 /* Intel SGX Capabilities: CPUID Leaf 12H */ static inline void cpuid(unsigned int leaf, unsigned int subleaf, unsigned int words[]) { - __asm__ ("cpuid" - : "=a" (words[PAL_CPUID_WORD_EAX]), - "=b" (words[PAL_CPUID_WORD_EBX]), - "=c" (words[PAL_CPUID_WORD_ECX]), - "=d" (words[PAL_CPUID_WORD_EDX]) - : "a" (leaf), - "c" (subleaf)); + __asm__("cpuid" + : "=a"(words[PAL_CPUID_WORD_EAX]), + "=b"(words[PAL_CPUID_WORD_EBX]), + "=c"(words[PAL_CPUID_WORD_ECX]), + "=d"(words[PAL_CPUID_WORD_EDX]) + : "a"(leaf), + "c"(subleaf)); } - static inline uint64_t get_tsc(void) { unsigned long lo, hi; - __asm__ volatile("rdtsc" : "=a" (lo), "=d" (hi)); + __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi)); return lo | ((uint64_t)hi << 32); } #define CPU_RELAX() __asm__ __volatile__("rep; nop" ::: "memory") /* some non-Intel clones support out of order store; WMB() ceases to be a nop for these */ -# define MB() __asm__ __volatile__ ("mfence" ::: "memory") -# define RMB() __asm__ __volatile__ ("lfence" ::: "memory") -# define WMB() __asm__ __volatile__ ("sfence" ::: "memory") +#define MB() __asm__ __volatile__("mfence" ::: "memory") +#define RMB() __asm__ __volatile__("lfence" ::: "memory") +#define WMB() __asm__ __volatile__("sfence" ::: "memory") #endif /* CPU_H */ diff --git a/Pal/include/arch/x86_64/dl-machine.h b/Pal/include/arch/x86_64/dl-machine.h index c4c23ac7e4..b03b7d2c79 100644 --- a/Pal/include/arch/x86_64/dl-machine.h +++ b/Pal/include/arch/x86_64/dl-machine.h @@ -14,10 +14,9 @@ #define ELF_MACHINE_NAME "x86_64" -#include - #include "pal_internal.h" #include "pal_rtld.h" +#include "sysdeps/generic/ldsodefs.h" /* The x86-64 never uses Elf64_Rel relocations. */ #define ELF_MACHINE_NO_REL 1 diff --git a/Pal/include/arch/x86_64/pal-arch.h b/Pal/include/arch/x86_64/pal-arch.h index 551f08d567..b2200f19b5 100644 --- a/Pal/include/arch/x86_64/pal-arch.h +++ b/Pal/include/arch/x86_64/pal-arch.h @@ -7,12 +7,18 @@ * This file contains definition of x86_64-specific aspects of PAL. */ +#ifndef PAL_H +// TODO: fix this +#error This header is usable only inside pal.h (due to a cyclic dependency). +#endif + #ifndef PAL_ARCH_H #define PAL_ARCH_H #include #include "cpu.h" +#include "pal.h" #define PAGE_SIZE (1 << 12) #define PRESET_PAGESIZE PAGE_SIZE @@ -30,12 +36,9 @@ typedef struct pal_tcb { #include "pal_host-arch.h" -static inline PAL_TCB * pal_get_tcb (void) -{ - PAL_TCB * tcb; - __asm__ ("movq %%gs:%c1,%q0" - : "=r" (tcb) - : "i" (offsetof(struct pal_tcb, self))); +static inline PAL_TCB* pal_get_tcb(void) { + PAL_TCB* tcb; + __asm__("movq %%gs:%c1,%q0" : "=r"(tcb) : "i"(offsetof(struct pal_tcb, self))); return tcb; } @@ -53,9 +56,9 @@ union pal_csgsfs { * Because self-contained definition is needed for Pal definition, * same layout is defined with PAL prefix. */ -#define PAL_FP_XSTATE_MAGIC1 0x46505853U -#define PAL_FP_XSTATE_MAGIC2 0x46505845U -#define PAL_FP_XSTATE_MAGIC2_SIZE (sizeof(PAL_FP_XSTATE_MAGIC2)) +#define PAL_FP_XSTATE_MAGIC1 0x46505853U +#define PAL_FP_XSTATE_MAGIC2 0x46505845U +#define PAL_FP_XSTATE_MAGIC2_SIZE (sizeof(PAL_FP_XSTATE_MAGIC2)) enum PAL_XFEATURE { PAL_XFEATURE_FP, @@ -72,22 +75,22 @@ enum PAL_XFEATURE { PAL_XFEATURE_MAX, }; -#define PAL_XFEATURE_MASK_FP (1UL << PAL_XFEATURE_FP) -#define PAL_XFEATURE_MASK_SSE (1UL << PAL_XFEATURE_SSE) -#define PAL_XFEATURE_MASK_YMM (1UL << PAL_XFEATURE_YMM) -#define PAL_XFEATURE_MASK_BNDREGS (1UL << PAL_XFEATURE_BNDREGS) -#define PAL_XFEATURE_MASK_BNDCSR (1UL << PAL_XFEATURE_BNDCSR) -#define PAL_XFEATURE_MASK_OPMASK (1UL << PAL_XFEATURE_OPMASK) -#define PAL_XFEATURE_MASK_ZMM_Hi256 (1UL << PAL_XFEATURE_ZMM_Hi256) -#define PAL_XFEATURE_MASK_Hi16_ZMM (1UL << PAL_XFEATURE_Hi16_ZMM) -#define PAL_XFEATURE_MASK_PT (1UL << PAL_XFEATURE_PT) -#define PAL_XFEATURE_MASK_PKRU (1UL << PAL_XFEATURE_PKRU) - -#define PAL_XFEATURE_MASK_FPSSE (PAL_XFEATURE_MASK_FP \ - | PAL_XFEATURE_MASK_SSE) -#define PAL_XFEATURE_MASK_AVX512 (PAL_XFEATURE_MASK_OPMASK \ - | PAL_XFEATURE_MASK_ZMM_Hi256 \ - | PAL_XFEATURE_MASK_Hi16_ZMM) +#define PAL_XFEATURE_MASK_FP (1UL << PAL_XFEATURE_FP) +#define PAL_XFEATURE_MASK_SSE (1UL << PAL_XFEATURE_SSE) +#define PAL_XFEATURE_MASK_YMM (1UL << PAL_XFEATURE_YMM) +#define PAL_XFEATURE_MASK_BNDREGS (1UL << PAL_XFEATURE_BNDREGS) +#define PAL_XFEATURE_MASK_BNDCSR (1UL << PAL_XFEATURE_BNDCSR) +#define PAL_XFEATURE_MASK_OPMASK (1UL << PAL_XFEATURE_OPMASK) +#define PAL_XFEATURE_MASK_ZMM_Hi256 (1UL << PAL_XFEATURE_ZMM_Hi256) +#define PAL_XFEATURE_MASK_Hi16_ZMM (1UL << PAL_XFEATURE_Hi16_ZMM) +#define PAL_XFEATURE_MASK_PT (1UL << PAL_XFEATURE_PT) +#define PAL_XFEATURE_MASK_PKRU (1UL << PAL_XFEATURE_PKRU) + +#define PAL_XFEATURE_MASK_FPSSE (PAL_XFEATURE_MASK_FP \ + | PAL_XFEATURE_MASK_SSE) +#define PAL_XFEATURE_MASK_AVX512 (PAL_XFEATURE_MASK_OPMASK \ + | PAL_XFEATURE_MASK_ZMM_Hi256 \ + | PAL_XFEATURE_MASK_Hi16_ZMM) typedef struct { uint32_t magic1; /*!< PAL_FP_XSTATE_MAGIC1 */ diff --git a/Pal/include/elf/elf.h b/Pal/include/elf/elf.h index 342b8f6f45..e114880121 100644 --- a/Pal/include/elf/elf.h +++ b/Pal/include/elf/elf.h @@ -22,13 +22,12 @@ #define _ELF_H 1 #include +#include __BEGIN_DECLS /* Standard ELF types. */ -#include - #define __ELF_NATIVE_CLASS 64 /* Type for a 16-bit quantity. */ diff --git a/Pal/include/lib/api.h b/Pal/include/lib/api.h index 9d343e4550..8c630ffc4d 100644 --- a/Pal/include/lib/api.h +++ b/Pal/include/lib/api.h @@ -4,11 +4,13 @@ #ifndef API_H #define API_H -#include +#include #include #include #include -#include + +#include "assert.h" +#include "list.h" /* WARNING: this declaration may conflict with some header files */ #ifndef ssize_t @@ -18,43 +20,53 @@ typedef ptrdiff_t ssize_t; /* Macros */ #ifndef MIN -#define MIN(a,b) \ - ({ __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ - _a < _b ? _a : _b; }) +#define MIN(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a < _b ? _a : _b; \ + }) #endif #ifndef MAX -#define MAX(a,b) \ - ({ __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ - _a > _b ? _a : _b; }) +#define MAX(a, b) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a > _b ? _a : _b; \ + }) #endif -#define SATURATED_ADD(a, b, limit) \ - ({ __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ - __typeof__(limit) _limit = (limit); \ - _b > _limit ? _limit : (_a > _limit - _b ? _limit : _a + _b); }) - -#define SATURATED_SUB(a, b, limit) \ - ({ __typeof__(a) _a = (a); \ - __typeof__(b) _b = (b); \ - __typeof__(limit) _limit = (limit); \ - _a < _limit ? _limit : (_b > _a - _limit ? _limit : _a - _b); }) +#define SATURATED_ADD(a, b, limit) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + __typeof__(limit) _limit = (limit); \ + _b > _limit ? _limit : (_a > _limit - _b ? _limit : _a + _b); \ + }) + +#define SATURATED_SUB(a, b, limit) \ + ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + __typeof__(limit) _limit = (limit); \ + _a < _limit ? _limit : (_b > _a - _limit ? _limit : _a - _b); \ + }) #define SATURATED_P_ADD(ptr_a, b, limit) \ - ((__typeof__(ptr_a))SATURATED_ADD((uintptr_t)(ptr_a), (uintptr_t)(b), (uintptr_t)(limit))) + ((__typeof__(ptr_a))SATURATED_ADD((uintptr_t)(ptr_a), (uintptr_t)(b), (uintptr_t)(limit))) #define SATURATED_P_SUB(ptr_a, b, limit) \ - ((__typeof__(ptr_a))SATURATED_SUB((uintptr_t)(ptr_a), (uintptr_t)(b), (uintptr_t)(limit))) + ((__typeof__(ptr_a))SATURATED_SUB((uintptr_t)(ptr_a), (uintptr_t)(b), (uintptr_t)(limit))) -#define IS_POWER_OF_2(x) \ - ({ assert((x) != 0); \ - (((x) & ((x) - 1)) == 0); }) +#define IS_POWER_OF_2(x) \ + ({ \ + assert((x) != 0); \ + (((x) & ((x) - 1)) == 0); \ + }) -#define IS_ALIGNED(val, alignment) ((val) % (alignment) == 0) -#define ALIGN_DOWN(val, alignment) ((val) - (val) % (alignment)) -#define ALIGN_UP(val, alignment) ALIGN_DOWN((val) + (alignment) - 1, alignment) +#define IS_ALIGNED(val, alignment) ((val) % (alignment) == 0) +#define ALIGN_DOWN(val, alignment) ((val) - (val) % (alignment)) +#define ALIGN_UP(val, alignment) ALIGN_DOWN((val) + (alignment) - 1, alignment) #define IS_ALIGNED_PTR(val, alignment) IS_ALIGNED((uintptr_t)(val), alignment) #define ALIGN_DOWN_PTR(ptr, alignment) ((__typeof__(ptr))(ALIGN_DOWN((uintptr_t)(ptr), alignment))) #define ALIGN_UP_PTR(ptr, alignment) ((__typeof__(ptr))(ALIGN_UP((uintptr_t)(ptr), alignment))) @@ -66,20 +78,23 @@ typedef ptrdiff_t ssize_t; // than `val` and unsigned. #define ALIGN_UP_POW2(val, alignment) ALIGN_DOWN_POW2((val) + (alignment) - 1, alignment) #define IS_ALIGNED_PTR_POW2(val, alignment) IS_ALIGNED_POW2((uintptr_t)(val), alignment) -#define ALIGN_DOWN_PTR_POW2(ptr, alignment) ((__typeof__(ptr))(ALIGN_DOWN_POW2((uintptr_t)(ptr), \ - alignment))) -#define ALIGN_UP_PTR_POW2(ptr, alignment) ((__typeof__(ptr))(ALIGN_UP_POW2((uintptr_t)(ptr), \ - alignment))) +#define ALIGN_DOWN_PTR_POW2(ptr, alignment) \ + ((__typeof__(ptr))(ALIGN_DOWN_POW2((uintptr_t)(ptr), alignment))) +#define ALIGN_UP_PTR_POW2(ptr, alignment) \ + ((__typeof__(ptr))(ALIGN_UP_POW2((uintptr_t)(ptr), alignment))) -#define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b)) -#define IS_STATIC_ARRAY(a) (!SAME_TYPE(a, &*(a))) +#define SAME_TYPE(a, b) __builtin_types_compatible_p(__typeof__(a), __typeof__(b)) +#define IS_STATIC_ARRAY(a) (!SAME_TYPE(a, &*(a))) #define FORCE_STATIC_ARRAY(a) sizeof(int[IS_STATIC_ARRAY(a) - 1]) // evaluates to 0 #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (FORCE_STATIC_ARRAY(a) + sizeof(a) / sizeof(a[0])) #endif -#define DEBUG_BREAK() do { __asm__ volatile ("int $3"); } while (0) +#define DEBUG_BREAK() \ + do { \ + __asm__ volatile("int $3"); \ + } while (0) #ifndef container_of /** @@ -89,18 +104,21 @@ typedef ptrdiff_t ssize_t; * @member: the name of the member within the struct. * */ -# define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) +#define container_of(ptr, type, member) ((type*)((char*)(ptr) - offsetof(type, member))) #endif #define __alloca __builtin_alloca #define XSTRINGIFY(x) STRINGIFY(x) -#define STRINGIFY(x) #x +#define STRINGIFY(x) #x /* fail build if str is not a static string */ #define FORCE_LITERAL_CSTR(str) ("" str "") -#define __UNUSED(x) do { (void)(x); } while (0) +#define __UNUSED(x) \ + do { \ + (void)(x); \ + } while (0) #define static_strlen(str) (ARRAY_SIZE(FORCE_LITERAL_CSTR(str)) - 1) /* LibC functions */ @@ -125,9 +143,9 @@ int memcmp(const void* lhs, const void* rhs, size_t count); bool strendswith(const char* haystack, const char* needle); /* Libc memory allocation functions */ -void *malloc(size_t size); -void free(void *ptr); -void *calloc(size_t nmemb, size_t size); +void* malloc(size_t size); +void free(void* ptr); +void* calloc(size_t nmemb, size_t size); /* check if `var` is exactly the same as a static string */ #define strcmp_static(var, str) \ @@ -147,61 +165,65 @@ void *calloc(size_t nmemb, size_t size); : memcpy(var, str, static_strlen(str) + 1) + static_strlen(str)) /* Copy a fixed size array. */ -#define COPY_ARRAY(dst, src) \ - do { \ - /* Using pointers because otherwise the compiler would try to allocate \ - * memory for the fixed size arrays and complain about invalid \ - * initializers. \ - */ \ - __typeof__(src)* _s = &(src); \ - __typeof__(dst)* _d = &(dst); \ - \ - static_assert(SAME_TYPE((*_s)[0], (*_d)[0]), "types must match"); \ - static_assert(ARRAY_SIZE(*_s) == ARRAY_SIZE(*_d), "sizes must match"); \ - \ - memcpy(*_d, *_s, sizeof(*_d)); \ +#define COPY_ARRAY(dst, src) \ + do { \ + /* Using pointers because otherwise the compiler would try to allocate \ + * memory for the fixed size arrays and complain about invalid \ + * initializers. \ + */ \ + __typeof__(src)* _s = &(src); \ + __typeof__(dst)* _d = &(dst); \ + \ + static_assert(SAME_TYPE((*_s)[0], (*_d)[0]), "types must match"); \ + static_assert(ARRAY_SIZE(*_s) == ARRAY_SIZE(*_d), "sizes must match"); \ + \ + memcpy(*_d, *_s, sizeof(*_d)); \ } while (0) #ifdef __x86_64__ -#define COMPILER_BARRIER() ({ __asm__ __volatile__ ("" ::: "memory"); }) +#define COMPILER_BARRIER() ({ __asm__ __volatile__("" ::: "memory"); }) #endif // __x86_64__ /* Idea taken from: https://elixir.bootlin.com/linux/v5.6/source/include/linux/compiler.h */ -#define READ_ONCE(x) ({ \ - __typeof__(x) _y; \ - COMPILER_BARRIER(); \ - __builtin_memcpy(&_y, &(x), sizeof(x)); \ - COMPILER_BARRIER(); \ - _y; }) - -#define WRITE_ONCE(x, y) ({ \ - __typeof__(x) _y = (__typeof__(x))(y); \ - COMPILER_BARRIER(); \ - __builtin_memcpy(&(x), &_y, sizeof(x)); \ - COMPILER_BARRIER(); \ - _y; }) +#define READ_ONCE(x) \ + ({ \ + __typeof__(x) _y; \ + COMPILER_BARRIER(); \ + __builtin_memcpy(&_y, &(x), sizeof(x)); \ + COMPILER_BARRIER(); \ + _y; \ + }) + +#define WRITE_ONCE(x, y) \ + ({ \ + __typeof__(x) _y = (__typeof__(x))(y); \ + COMPILER_BARRIER(); \ + __builtin_memcpy(&(x), &_y, sizeof(x)); \ + COMPILER_BARRIER(); \ + _y; \ + }) /* Libc printf functions. stdio.h/stdarg.h. */ -void fprintfmt (int (*_fputch)(void *, int, void *), void * f, void * putdat, - const char * fmt, ...) __attribute__((format(printf, 4, 5))); +void fprintfmt(int (*_fputch)(void*, int, void*), void* f, void* putdat, const char* fmt, ...) + __attribute__((format(printf, 4, 5))); -void vfprintfmt (int (*_fputch)(void *, int, void *), void * f, void * putdat, - const char * fmt, va_list ap) __attribute__((format(printf, 4, 0))); +void vfprintfmt(int (*_fputch)(void*, int, void*), void* f, void* putdat, const char* fmt, + va_list ap) __attribute__((format(printf, 4, 0))); int vsnprintf(char* buf, size_t n, const char* fmt, va_list ap); int snprintf(char* buf, size_t n, const char* fmt, ...) __attribute__((format(printf, 3, 4))); /* Miscelleneous */ -int inet_pton4 (const char *src, size_t len, void *dst); -int inet_pton6 (const char *src, size_t len, void *dst); +int inet_pton4(const char* src, size_t len, void* dst); +int inet_pton6(const char* src, size_t len, void* dst); -uint32_t __htonl (uint32_t x); -uint32_t __ntohl (uint32_t x); -uint16_t __htons (uint16_t x); -uint16_t __ntohs (uint16_t x); +uint32_t __htonl(uint32_t x); +uint32_t __ntohl(uint32_t x); +uint16_t __htons(uint16_t x); +uint16_t __ntohs(uint16_t x); -extern const char * const * sys_errlist_internal; +extern const char* const* sys_errlist_internal; /* Graphene functions */ @@ -210,59 +232,55 @@ int get_base_name(const char* path, char* buf, size_t* size); /* Loading configs / manifests */ -#include - struct config; DEFINE_LISTP(config); struct config_store { LISTP_TYPE(config) root; LISTP_TYPE(config) entries; - void * raw_data; - int raw_size; - void * (*malloc) (size_t); - void (*free) (void *); + void* raw_data; + int raw_size; + void* (*malloc)(size_t); + void (*free)(void*); }; int read_config(struct config_store* store, bool (*filter)(const char*, size_t), const char** errstring); -int free_config (struct config_store * store); -int copy_config (struct config_store * store, struct config_store * new_store); -int write_config (void * file, int (*write) (void *, void *, int), - struct config_store * store); -ssize_t get_config (struct config_store * cfg, const char * key, - char * val_buf, size_t buf_size); -int get_config_entries (struct config_store * cfg, const char * key, - char * key_buf, size_t key_bufsize); -ssize_t get_config_entries_size (struct config_store * cfg, const char * key); -int set_config (struct config_store * cfg, const char * key, const char * val); - -#define CONFIG_MAX 4096 - -#define URI_PREFIX_SEPARATOR ":" - -#define URI_TYPE_DIR "dir" -#define URI_TYPE_TCP "tcp" -#define URI_TYPE_TCP_SRV "tcp.srv" -#define URI_TYPE_UDP "udp" -#define URI_TYPE_UDP_SRV "udp.srv" -#define URI_TYPE_PIPE "pipe" -#define URI_TYPE_PIPE_SRV "pipe.srv" -#define URI_TYPE_DEV "dev" -#define URI_TYPE_EVENTFD "eventfd" -#define URI_TYPE_FILE "file" - -#define URI_PREFIX_DIR URI_TYPE_DIR URI_PREFIX_SEPARATOR -#define URI_PREFIX_TCP URI_TYPE_TCP URI_PREFIX_SEPARATOR -#define URI_PREFIX_TCP_SRV URI_TYPE_TCP_SRV URI_PREFIX_SEPARATOR -#define URI_PREFIX_UDP URI_TYPE_UDP URI_PREFIX_SEPARATOR -#define URI_PREFIX_UDP_SRV URI_TYPE_UDP_SRV URI_PREFIX_SEPARATOR -#define URI_PREFIX_PIPE URI_TYPE_PIPE URI_PREFIX_SEPARATOR -#define URI_PREFIX_PIPE_SRV URI_TYPE_PIPE_SRV URI_PREFIX_SEPARATOR -#define URI_PREFIX_DEV URI_TYPE_DEV URI_PREFIX_SEPARATOR -#define URI_PREFIX_EVENTFD URI_TYPE_EVENTFD URI_PREFIX_SEPARATOR -#define URI_PREFIX_FILE URI_TYPE_FILE URI_PREFIX_SEPARATOR - -#define URI_PREFIX_FILE_LEN (static_strlen(URI_PREFIX_FILE)) +int free_config(struct config_store* store); +int copy_config(struct config_store* store, struct config_store* new_store); +int write_config(void* file, int (*write)(void*, void*, int), struct config_store* store); +ssize_t get_config(struct config_store* cfg, const char* key, char* val_buf, size_t buf_size); +int get_config_entries(struct config_store* cfg, const char* key, char* key_buf, + size_t key_bufsize); +ssize_t get_config_entries_size(struct config_store* cfg, const char* key); +int set_config(struct config_store* cfg, const char* key, const char* val); + +#define CONFIG_MAX 4096 + +#define URI_PREFIX_SEPARATOR ":" + +#define URI_TYPE_DIR "dir" +#define URI_TYPE_TCP "tcp" +#define URI_TYPE_TCP_SRV "tcp.srv" +#define URI_TYPE_UDP "udp" +#define URI_TYPE_UDP_SRV "udp.srv" +#define URI_TYPE_PIPE "pipe" +#define URI_TYPE_PIPE_SRV "pipe.srv" +#define URI_TYPE_DEV "dev" +#define URI_TYPE_EVENTFD "eventfd" +#define URI_TYPE_FILE "file" + +#define URI_PREFIX_DIR URI_TYPE_DIR URI_PREFIX_SEPARATOR +#define URI_PREFIX_TCP URI_TYPE_TCP URI_PREFIX_SEPARATOR +#define URI_PREFIX_TCP_SRV URI_TYPE_TCP_SRV URI_PREFIX_SEPARATOR +#define URI_PREFIX_UDP URI_TYPE_UDP URI_PREFIX_SEPARATOR +#define URI_PREFIX_UDP_SRV URI_TYPE_UDP_SRV URI_PREFIX_SEPARATOR +#define URI_PREFIX_PIPE URI_TYPE_PIPE URI_PREFIX_SEPARATOR +#define URI_PREFIX_PIPE_SRV URI_TYPE_PIPE_SRV URI_PREFIX_SEPARATOR +#define URI_PREFIX_DEV URI_TYPE_DEV URI_PREFIX_SEPARATOR +#define URI_PREFIX_EVENTFD URI_TYPE_EVENTFD URI_PREFIX_SEPARATOR +#define URI_PREFIX_FILE URI_TYPE_FILE URI_PREFIX_SEPARATOR + +#define URI_PREFIX_FILE_LEN (static_strlen(URI_PREFIX_FILE)) #ifdef __x86_64__ static inline bool __range_not_ok(uintptr_t addr, size_t size) { @@ -281,7 +299,7 @@ static inline bool access_ok(const volatile void* addr, size_t size) { } #else -# error "Unsupported architecture" +#error "Unsupported architecture" #endif /* __x86_64__ */ #endif /* API_H */ diff --git a/Pal/include/lib/assert.h b/Pal/include/lib/assert.h index db7debb8fa..0d28bf5f4d 100644 --- a/Pal/include/lib/assert.h +++ b/Pal/include/lib/assert.h @@ -37,4 +37,4 @@ noreturn void __abort(void); #define assert(expr) ((void)0) #endif -#endif /* ASSERT_H */ +#endif /* ASSERT_H */ diff --git a/Pal/include/lib/avl_tree.h b/Pal/include/lib/avl_tree.h index 1dbc3fd76f..5120f4e3d3 100644 --- a/Pal/include/lib/avl_tree.h +++ b/Pal/include/lib/avl_tree.h @@ -91,8 +91,7 @@ struct avl_tree_node* avl_tree_find(struct avl_tree* tree, struct avl_tree_node* * It must also be compatible with tree->cmp i.e. cmp(f(a), b) == tree->cmp(a, b) for all a, b, * where f is some function changing a tree node to whatever the type of first argument to `cmp` is. */ -struct avl_tree_node* avl_tree_lower_bound_fn(struct avl_tree* tree, - void* cmp_arg, +struct avl_tree_node* avl_tree_lower_bound_fn(struct avl_tree* tree, void* cmp_arg, bool cmp(void*, struct avl_tree_node*)); struct avl_tree_node* avl_tree_lower_bound(struct avl_tree* tree, struct avl_tree_node* cmp_arg); diff --git a/Pal/include/lib/hex.h b/Pal/include/lib/hex.h index 6a842ae633..0ca97e3a37 100644 --- a/Pal/include/lib/hex.h +++ b/Pal/include/lib/hex.h @@ -6,11 +6,12 @@ #ifndef HEX_H #define HEX_H -#include -#include #include #include +#include "api.h" +#include "assert.h" + /* This function is a helper for debug printing. * It accepts a pointer to a numerical value, and * formats it as a hex string, for printing. @@ -23,9 +24,9 @@ static inline char* __bytes2hexstr(void* hex, size_t size, char* str, size_t len __UNUSED(len); assert(len >= size * 2 + 1); - for (size_t i = 0 ; i < size ; i++) { - unsigned char h = ((unsigned char *) hex)[i]; - str[i * 2] = ch[h / 16]; + for (size_t i = 0; i < size; i++) { + unsigned char h = ((unsigned char*)hex)[i]; + str[i * 2] = ch[h / 16]; str[i * 2 + 1] = ch[h % 16]; } diff --git a/Pal/include/lib/pal_crypto.h b/Pal/include/lib/pal_crypto.h index 5f55efeecb..2bd9fa3958 100644 --- a/Pal/include/lib/pal_crypto.h +++ b/Pal/include/lib/pal_crypto.h @@ -10,9 +10,9 @@ #ifndef PAL_CRYPTO_H #define PAL_CRYPTO_H +#include #include #include -#include #include #define SHA256_DIGEST_LEN 32 @@ -47,7 +47,7 @@ typedef struct { mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ssl_config conf; mbedtls_ssl_context ssl; - int ciphersuites[2]; /* [0] is actual ciphersuite, [1] must be 0 to indicate end of array */ + int ciphersuites[2]; /* [0] is actual ciphersuite, [1] must be 0 to indicate end of array */ ssize_t (*pal_recv_cb)(int fd, void* buf, size_t buf_size); ssize_t (*pal_send_cb)(int fd, const void* buf, size_t buf_size); int stream_fd; @@ -56,7 +56,7 @@ typedef struct { #endif /* CRYPTO_USE_MBEDTLS */ #ifndef CRYPTO_PROVIDER_SPECIFIED -# error "Unknown crypto provider. Set CRYPTO_PROVIDER in Makefile" +#error "Unknown crypto provider. Set CRYPTO_PROVIDER in Makefile" #endif /* SHA256 */ @@ -72,7 +72,7 @@ int lib_DhCalcSecret(LIB_DH_CONTEXT* context, uint8_t* peer, size_t peer_size, u void lib_DhFinal(LIB_DH_CONTEXT* context); /* AES-CMAC */ -int lib_AESCMAC(const uint8_t* key, size_t key_size, const uint8_t *input, size_t input_size, +int lib_AESCMAC(const uint8_t* key, size_t key_size, const uint8_t* input, size_t input_size, uint8_t* mac, size_t mac_size); /* GCM encrypt, iv is assumed to be 12 bytes (and is changed by this call). * input_size doesn't have to be a multiple of 16. @@ -125,9 +125,8 @@ int lib_Base64Encode(const uint8_t* src, size_t src_size, char* dst, size_t* dst int lib_Base64Decode(const char* src, size_t src_size, uint8_t* dst, size_t* dst_size); /* SSL/TLS */ -int lib_SSLInit(LIB_SSL_CONTEXT* ssl_ctx, int stream_fd, bool is_server, - const uint8_t* psk, size_t psk_size, - ssize_t (*pal_recv_cb)(int fd, void* buf, size_t buf_size), +int lib_SSLInit(LIB_SSL_CONTEXT* ssl_ctx, int stream_fd, bool is_server, const uint8_t* psk, + size_t psk_size, ssize_t (*pal_recv_cb)(int fd, void* buf, size_t buf_size), ssize_t (*pal_send_cb)(int fd, const void* buf, size_t buf_size), const uint8_t* buf_load_ssl_ctx, size_t buf_size); int lib_SSLFree(LIB_SSL_CONTEXT* ssl_ctx); diff --git a/Pal/include/lib/slabmgr.h b/Pal/include/lib/slabmgr.h index 921c48c1b6..60286d93bf 100644 --- a/Pal/include/lib/slabmgr.h +++ b/Pal/include/lib/slabmgr.h @@ -10,21 +10,21 @@ #ifndef SLABMGR_H #define SLABMGR_H -#include #include -#include #include #include "api.h" +#include "assert.h" #include "list.h" +#include "pal_debug.h" // Before calling any of `system_malloc` and `system_free` this library will // acquire `SYSTEM_LOCK` (the systen_* implementation must not do it). #ifndef system_malloc -#error "macro \"void * system_malloc(int size)\" not declared" +#error "macro \"void* system_malloc(size_t size)\" not declared" #endif #ifndef system_free -#error "macro \"void * system_free(void * ptr, int size)\" not declared" +#error "macro \"void* system_free(void* ptr, size_t size)\" not declared" #endif #ifndef SYSTEM_LOCK #define SYSTEM_LOCK() ({}) @@ -86,7 +86,7 @@ typedef struct __attribute__((packed)) slab_area { #define SLAB_HDR_SIZE \ ALIGN_UP(sizeof(SLAB_OBJ_TYPE) - sizeof(LIST_TYPE(slab_obj)) + SLAB_CANARY_SIZE, \ - MIN_MALLOC_ALIGNMENT) + MIN_MALLOC_ALIGNMENT) #ifndef SLAB_LEVEL #define SLAB_LEVEL 8 diff --git a/Pal/include/lib/spinlock.h b/Pal/include/lib/spinlock.h index 8c731a68de..859db53f68 100644 --- a/Pal/include/lib/spinlock.h +++ b/Pal/include/lib/spinlock.h @@ -7,15 +7,15 @@ #ifndef _SPINLOCK_H #define _SPINLOCK_H -#include -#include +#include "api.h" +#include "cpu.h" #ifdef DEBUG #define DEBUG_SPINLOCKS #endif // DEBUG #ifdef IN_SHIM -#include +#include "shim_internal.h" #ifdef DEBUG_SPINLOCKS #define DEBUG_SPINLOCKS_SHIM @@ -35,8 +35,8 @@ typedef struct { * important due to atomic-decrement in unlock logic. */ #define SPINLOCK_UNLOCKED 0 #define SPINLOCK_LOCKED 1 -#define SPINLOCK_LOCKED_NO_WAITERS 1 /* used for futex implementation */ -#define SPINLOCK_LOCKED_WITH_WAITERS 2 /* used for futex implementation */ +#define SPINLOCK_LOCKED_NO_WAITERS 1 /* used for futex implementation */ +#define SPINLOCK_LOCKED_WITH_WAITERS 2 /* used for futex implementation */ /*! * \brief Initialize spinlock with *static* storage duration. diff --git a/Pal/include/pal/pal.h b/Pal/include/pal/pal.h index 0748e98b0f..55ff44abb2 100644 --- a/Pal/include/pal/pal.h +++ b/Pal/include/pal/pal.h @@ -19,11 +19,11 @@ #include "cpu.h" #endif -typedef uint64_t PAL_NUM; /*!< a number */ -typedef const char * PAL_STR; /*!< a pointer to a C-string */ -typedef void * PAL_PTR; /*!< a pointer to memory or buffer (something other than string) */ -typedef uint32_t PAL_FLG; /*!< a set of flags */ -typedef uint32_t PAL_IDX; /*!< an index */ +typedef uint64_t PAL_NUM; /*!< a number */ +typedef const char* PAL_STR; /*!< a pointer to a C-string */ +typedef void* PAL_PTR; /*!< a pointer to memory or buffer (something other than string) */ +typedef uint32_t PAL_FLG; /*!< a set of flags */ +typedef uint32_t PAL_IDX; /*!< an index */ /*! * \brief a boolean value (either #PAL_TRUE or #PAL_FALSE) @@ -31,12 +31,12 @@ typedef uint32_t PAL_IDX; /*!< an index */ * This data type is commonly used as the return value of * a PAL API to determine whether the call succeeded */ -typedef bool PAL_BOL; +typedef bool PAL_BOL; /*! * True value for #PAL_BOL. */ -#define PAL_TRUE true +#define PAL_TRUE true /*! * False value for #PAL_BOL. @@ -51,7 +51,7 @@ typedef bool PAL_BOL; #define PIPE_NAME_MAX 96 #ifdef IN_PAL -#include +#include "atomic.h" typedef struct atomic_int PAL_REF; typedef struct { @@ -59,32 +59,31 @@ typedef struct { PAL_FLG flags; } PAL_HDR; -# include "pal_host.h" +#include "pal_host.h" -# ifndef HANDLE_HDR -# define HANDLE_HDR(handle) (&((handle)->hdr)) -# endif +#ifndef HANDLE_HDR +#define HANDLE_HDR(handle) (&((handle)->hdr)) +#endif -static inline void init_handle_hdr(PAL_HDR *hdr, int pal_type) { - hdr->type = pal_type; +static inline void init_handle_hdr(PAL_HDR* hdr, int pal_type) { + hdr->type = pal_type; hdr->flags = 0; } -# define SET_HANDLE_TYPE(handle, t) init_handle_hdr(HANDLE_HDR(handle), pal_type_##t) -# define IS_HANDLE_TYPE(handle, t) (HANDLE_HDR(handle)->type == pal_type_##t) +#define SET_HANDLE_TYPE(handle, t) init_handle_hdr(HANDLE_HDR(handle), pal_type_##t) +#define IS_HANDLE_TYPE(handle, t) (HANDLE_HDR(handle)->type == pal_type_##t) #else -typedef union pal_handle -{ +typedef union pal_handle { struct { PAL_IDX type; /* the PAL-level reference counting is deprecated */ } hdr; }* PAL_HANDLE; -# ifndef HANDLE_HDR -# define HANDLE_HDR(handle) (&((handle)->hdr)) -# endif +#ifndef HANDLE_HDR +#define HANDLE_HDR(handle) (&((handle)->hdr)) +#endif #endif /* !IN_PAL */ @@ -111,12 +110,14 @@ enum { PAL_HANDLE_TYPE_BOUND, }; -#define PAL_IDX_POISON ((PAL_IDX)-1) /* PAL identifier poison value */ -#define PAL_GET_TYPE(h) (HANDLE_HDR(h)->type) -#define PAL_CHECK_TYPE(h, t) (PAL_GET_TYPE(h) == pal_type_##t) -#define UNKNOWN_HANDLE(handle) (PAL_GET_TYPE(handle) >= PAL_HANDLE_TYPE_BOUND) +#define PAL_IDX_POISON ((PAL_IDX)-1) /* PAL identifier poison value */ +#define PAL_GET_TYPE(h) (HANDLE_HDR(h)->type) +#define PAL_CHECK_TYPE(h, t) (PAL_GET_TYPE(h) == pal_type_##t) +#define UNKNOWN_HANDLE(handle) (PAL_GET_TYPE(handle) >= PAL_HANDLE_TYPE_BOUND) -typedef struct PAL_PTR_RANGE_ { PAL_PTR start, end; } PAL_PTR_RANGE; +typedef struct PAL_PTR_RANGE_ { + PAL_PTR start, end; +} PAL_PTR_RANGE; typedef struct PAL_MEM_INFO_ { PAL_NUM mem_total; @@ -132,15 +133,15 @@ typedef struct PAL_CONTROL_ { * Handles and executables */ PAL_HANDLE manifest_handle; /*!< program manifest */ - PAL_STR executable; /*!< executable name */ - PAL_HANDLE parent_process; /*!< handle of parent process */ - PAL_HANDLE first_thread; /*!< handle of first thread */ - PAL_HANDLE debug_stream; /*!< debug stream */ + PAL_STR executable; /*!< executable name */ + PAL_HANDLE parent_process; /*!< handle of parent process */ + PAL_HANDLE first_thread; /*!< handle of first thread */ + PAL_HANDLE debug_stream; /*!< debug stream */ /* * Memory layout */ - PAL_BOL disable_aslr; /*!< disable ASLR (may be necessary for restricted environments) */ + PAL_BOL disable_aslr; /*!< disable ASLR (may be necessary for restricted environments) */ PAL_PTR_RANGE user_address; /*!< The range of user addresses */ PAL_PTR_RANGE executable_range; /*!< address where executable is loaded */ @@ -164,7 +165,7 @@ typedef struct PAL_CONTROL_ { } PAL_CONTROL; #define pal_control (*pal_control_addr()) -PAL_CONTROL * pal_control_addr (void); +PAL_CONTROL* pal_control_addr(void); /* * MEMORY ALLOCATION @@ -189,7 +190,6 @@ enum PAL_PROT { PAL_PROT_MASK = 0xF, }; - /*! * \brief Allocate virtual memory for the library OS and zero it out. * @@ -202,8 +202,7 @@ enum PAL_PROT { * \param alloc_type can be a combination of any of the #PAL_ALLOC flags * \param prot can be a combination of the #PAL_PROT flags */ -PAL_PTR -DkVirtualMemoryAlloc(PAL_PTR addr, PAL_NUM size, PAL_FLG alloc_type, PAL_FLG prot); +PAL_PTR DkVirtualMemoryAlloc(PAL_PTR addr, PAL_NUM size, PAL_FLG alloc_type, PAL_FLG prot); /*! * \brief This API deallocates a previously allocated memory mapping. @@ -213,9 +212,7 @@ DkVirtualMemoryAlloc(PAL_PTR addr, PAL_NUM size, PAL_FLG alloc_type, PAL_FLG pro * * Both `addr` and `size` must be non-zero and aligned at the allocation alignment. */ -void -DkVirtualMemoryFree(PAL_PTR addr, PAL_NUM size); - +void DkVirtualMemoryFree(PAL_PTR addr, PAL_NUM size); /*! * \brief Modify the permissions of a previously allocated memory mapping. @@ -226,24 +223,21 @@ DkVirtualMemoryFree(PAL_PTR addr, PAL_NUM size); * * Both `addr` and `size` must be non-zero and aligned at the allocation alignment. */ -PAL_BOL -DkVirtualMemoryProtect(PAL_PTR addr, PAL_NUM size, PAL_FLG prot); - +PAL_BOL DkVirtualMemoryProtect(PAL_PTR addr, PAL_NUM size, PAL_FLG prot); /* * PROCESS CREATION */ -#define PAL_PROCESS_MASK 0x0 +#define PAL_PROCESS_MASK 0x0 /*! -* \brief Create a new process to run a separate executable. -* -* \param uri the URI of the manifest file or the executable to be loaded in the new process. -* \param args an array of strings -- the arguments to be passed to the new process. -*/ -PAL_HANDLE -DkProcessCreate(PAL_STR uri, PAL_STR* args); + * \brief Create a new process to run a separate executable. + * + * \param uri the URI of the manifest file or the executable to be loaded in the new process. + * \param args an array of strings -- the arguments to be passed to the new process. + */ +PAL_HANDLE DkProcessCreate(PAL_STR uri, PAL_STR* args); /*! * \brief Magic exit code that instructs the exiting process to wait for its children @@ -260,8 +254,7 @@ DkProcessCreate(PAL_STR uri, PAL_STR* args); * * \param exitCode the exit value returned to the host. */ -noreturn void -DkProcessExit(PAL_NUM exitCode); +noreturn void DkProcessExit(PAL_NUM exitCode); /* * STREAMS @@ -298,9 +291,9 @@ enum PAL_SHARE { /*! Stream Create Flags */ enum PAL_CREATE { - PAL_CREATE_TRY = 1, /*!< Create file if file does not exist */ - PAL_CREATE_ALWAYS = 2, /*!< Create file and fail if file already exists */ - PAL_CREATE_DUALSTACK = 4, /*!< Create dual-stack socket (opposite of IPV6_V6ONLY) */ + PAL_CREATE_TRY = 1, /*!< Create file if file does not exist */ + PAL_CREATE_ALWAYS = 2, /*!< Create file and fail if file already exists */ + PAL_CREATE_DUALSTACK = 4, /*!< Create dual-stack socket (opposite of IPV6_V6ONLY) */ PAL_CREATE_MASK = 7, }; @@ -314,11 +307,10 @@ enum PAL_OPTION { PAL_OPTION_MASK = 7, }; - /*! error value of read/write */ -#define PAL_STREAM_ERROR ((PAL_NUM)-1L) +#define PAL_STREAM_ERROR ((PAL_NUM)-1L) -#define WITHIN_MASK(val, mask) (((val)|(mask)) == (mask)) +#define WITHIN_MASK(val, mask) (((val) | (mask)) == (mask)) /*! * \brief Open/create a stream resource specified by `uri` @@ -344,8 +336,8 @@ enum PAL_OPTION { * * `udp.srv::`, `udp::`: Open a UDP socket to listen or connect to * a remote UDP socket. */ -PAL_HANDLE -DkStreamOpen(PAL_STR uri, PAL_FLG access, PAL_FLG share_flags, PAL_FLG create, PAL_FLG options); +PAL_HANDLE DkStreamOpen(PAL_STR uri, PAL_FLG access, PAL_FLG share_flags, PAL_FLG create, + PAL_FLG options); /*! * \brief Blocks until a new connection is accepted and returns the PAL handle for the connection. @@ -353,8 +345,7 @@ DkStreamOpen(PAL_STR uri, PAL_FLG access, PAL_FLG share_flags, PAL_FLG create, P * This API is only available for handles that are opened with `pipe.srv:...`, `tcp.srv:...`, and * `udp.srv:...`. */ -PAL_HANDLE -DkStreamWaitForClient(PAL_HANDLE handle); +PAL_HANDLE DkStreamWaitForClient(PAL_HANDLE handle); /*! * \brief Read data from an open stream. @@ -364,9 +355,8 @@ DkStreamWaitForClient(PAL_HANDLE handle); * handle is a directory, DkStreamRead fills the buffer with the names (NULL-ended) of the files or * subdirectories inside of this directory. */ -PAL_NUM -DkStreamRead(PAL_HANDLE handle, PAL_NUM offset, PAL_NUM count, PAL_PTR buffer, PAL_PTR source, - PAL_NUM size); +PAL_NUM DkStreamRead(PAL_HANDLE handle, PAL_NUM offset, PAL_NUM count, PAL_PTR buffer, + PAL_PTR source, PAL_NUM size); /*! * \brief Write data to an open stream. @@ -374,8 +364,8 @@ DkStreamRead(PAL_HANDLE handle, PAL_NUM offset, PAL_NUM count, PAL_PTR buffer, P * If the handle is a file, `offset` must be specified at each call of DkStreamWrite. `dest` can be * used to specify the remote socket address if the handle is a UDP socket. */ -PAL_NUM -DkStreamWrite(PAL_HANDLE handle, PAL_NUM offset, PAL_NUM count, PAL_PTR buffer, PAL_STR dest); +PAL_NUM DkStreamWrite(PAL_HANDLE handle, PAL_NUM offset, PAL_NUM count, PAL_PTR buffer, + PAL_STR dest); enum PAL_DELETE { PAL_DELETE_RD = 1, /*!< shut down the read side only */ @@ -397,31 +387,26 @@ void DkStreamDelete(PAL_HANDLE handle, PAL_FLG access); * * `offset` and `size` have to be non-zero and aligned at the allocation alignment */ -PAL_PTR -DkStreamMap(PAL_HANDLE handle, PAL_PTR address, PAL_FLG prot, - PAL_NUM offset, PAL_NUM size); +PAL_PTR DkStreamMap(PAL_HANDLE handle, PAL_PTR address, PAL_FLG prot, PAL_NUM offset, PAL_NUM size); /*! * \brief Unmap virtual memory that is backed by a file stream. * * `addr` and `size` must be aligned at the allocation alignment */ -void -DkStreamUnmap(PAL_PTR addr, PAL_NUM size); +void DkStreamUnmap(PAL_PTR addr, PAL_NUM size); /*! * \brief Set the length of the file referenced by handle to `length`. * * \return Returns the 0 on success, a _positive_ errno on failure. */ -PAL_NUM -DkStreamSetLength(PAL_HANDLE handle, PAL_NUM length); +PAL_NUM DkStreamSetLength(PAL_HANDLE handle, PAL_NUM length); /*! * \brief Flush the buffer of a file stream. */ -PAL_BOL -DkStreamFlush(PAL_HANDLE handle); +PAL_BOL DkStreamFlush(PAL_HANDLE handle); /*! * \brief Send a PAL handle over another handle. @@ -430,14 +415,12 @@ DkStreamFlush(PAL_HANDLE handle); * * \param cargo the handle being sent */ -PAL_BOL -DkSendHandle(PAL_HANDLE handle, PAL_HANDLE cargo); +PAL_BOL DkSendHandle(PAL_HANDLE handle, PAL_HANDLE cargo); /*! * \brief This API receives a handle over another handle. */ -PAL_HANDLE -DkReceiveHandle(PAL_HANDLE handle); +PAL_HANDLE DkReceiveHandle(PAL_HANDLE handle); /* stream attribute structure */ typedef struct _PAL_STREAM_ATTR { @@ -467,41 +450,35 @@ typedef struct _PAL_STREAM_ATTR { * * This API only applies for URIs such as `%file:...`, `dir:...`, and `dev:...`. */ -PAL_BOL -DkStreamAttributesQuery(PAL_STR uri, PAL_STREAM_ATTR* attr); +PAL_BOL DkStreamAttributesQuery(PAL_STR uri, PAL_STREAM_ATTR* attr); /*! * \brief Query the attributes of an open stream. * * This API applies to any stream handle. */ -PAL_BOL -DkStreamAttributesQueryByHandle(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); +PAL_BOL DkStreamAttributesQueryByHandle(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); /*! * \brief Set the attributes of an open stream. */ -PAL_BOL -DkStreamAttributesSetByHandle(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); +PAL_BOL DkStreamAttributesSetByHandle(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); /*! * \brief Query the name of an open stream. */ -PAL_NUM -DkStreamGetName(PAL_HANDLE handle, PAL_PTR buffer, PAL_NUM size); +PAL_NUM DkStreamGetName(PAL_HANDLE handle, PAL_PTR buffer, PAL_NUM size); /*! * \brief This API changes the name of an open stream. */ -PAL_BOL -DkStreamChangeName(PAL_HANDLE handle, PAL_STR uri); - +PAL_BOL DkStreamChangeName(PAL_HANDLE handle, PAL_STR uri); /* * Thread creation */ -#define PAL_THREAD_MASK 0 +#define PAL_THREAD_MASK 0 /*! * \brief Create a thread in the current process. @@ -509,22 +486,19 @@ DkStreamChangeName(PAL_HANDLE handle, PAL_STR uri); * \param addr is the address of an entry point of execution for the new thread * \param param is the pointer argument that is passed to the new thread */ -PAL_HANDLE -DkThreadCreate(PAL_PTR addr, PAL_PTR param); +PAL_HANDLE DkThreadCreate(PAL_PTR addr, PAL_PTR param); /*! * \brief Suspend the current thread for a certain duration * * \param duration the duration in microseconds */ -PAL_NUM -DkThreadDelayExecution(PAL_NUM duration); +PAL_NUM DkThreadDelayExecution(PAL_NUM duration); /*! * \brief Yield the current thread such that the host scheduler can reschedule it. */ -void -DkThreadYieldExecution(void); +void DkThreadYieldExecution(void); /*! * \brief Terminate the current thread. @@ -538,8 +512,7 @@ noreturn void DkThreadExit(PAL_PTR clear_child_tid); /*! * \brief Resume a thread. */ -PAL_BOL -DkThreadResume(PAL_HANDLE thread); +PAL_BOL DkThreadResume(PAL_HANDLE thread); /* * Exception Handling @@ -564,15 +537,14 @@ enum PAL_EVENT { PAL_EVENT_NUM_BOUND = 8, }; -typedef void (*PAL_EVENT_HANDLER) (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT*); +typedef void (*PAL_EVENT_HANDLER)(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT*); /*! * \brief Set the handler for the specific exception event. * * \param event can be one of #PAL_EVENT values */ -PAL_BOL -DkSetExceptionHandler(PAL_EVENT_HANDLER handler, PAL_NUM event); +PAL_BOL DkSetExceptionHandler(PAL_EVENT_HANDLER handler, PAL_NUM event); /*! * \brief Exit an exception handler and restore the context. @@ -584,7 +556,6 @@ void DkExceptionReturn(PAL_PTR event); * or threadHandle. */ - /* * Synchronization */ @@ -596,15 +567,12 @@ void DkExceptionReturn(PAL_PTR event); * * \param initialCount 0 is unlocked, 1 is locked */ -PAL_HANDLE -DkMutexCreate(PAL_NUM initialCount); +PAL_HANDLE DkMutexCreate(PAL_NUM initialCount); /*! * \brief Unlock the given mutex. */ -void -DkMutexRelease(PAL_HANDLE mutexHandle); - +void DkMutexRelease(PAL_HANDLE mutexHandle); /*! * \brief Creates a notification event with the given `initialState`. @@ -613,8 +581,7 @@ DkMutexRelease(PAL_HANDLE mutexHandle); * a notification event is set to the signaled state it remains in that state * until it is explicitly cleared. */ -PAL_HANDLE -DkNotificationEventCreate(PAL_BOL initialState); +PAL_HANDLE DkNotificationEventCreate(PAL_BOL initialState); /*! * \brief Creates a synchronization event with the given `initialState`. @@ -624,20 +591,17 @@ DkNotificationEventCreate(PAL_BOL initialState); * execution that was waiting for the event is released, and the event is * automatically reset to the not-signaled state. */ -PAL_HANDLE -DkSynchronizationEventCreate(PAL_BOL initialState); +PAL_HANDLE DkSynchronizationEventCreate(PAL_BOL initialState); /*! * \brief Set (signal) a notification event or a synchronization event. */ -void -DkEventSet(PAL_HANDLE eventHandle); +void DkEventSet(PAL_HANDLE eventHandle); /*! * \brief Clear a notification event or a synchronization event. */ -void -DkEventClear(PAL_HANDLE eventHandle); +void DkEventClear(PAL_HANDLE eventHandle); /*! * \brief Wait for an event. @@ -701,14 +665,12 @@ PAL_NUM DkSystemTimeQuery(void); * \param[in] size buffer size * \return 0 on success, negative on failure */ -PAL_NUM -DkRandomBitsRead(PAL_PTR buffer, PAL_NUM size); +PAL_NUM DkRandomBitsRead(PAL_PTR buffer, PAL_NUM size); /*! * \todo document DkInstructionCacheFlush */ -PAL_BOL -DkInstructionCacheFlush(PAL_PTR addr, PAL_NUM size); +PAL_BOL DkInstructionCacheFlush(PAL_PTR addr, PAL_NUM size); enum PAL_SEGMENT { PAL_SEGMENT_FS = 0x1, @@ -763,8 +725,8 @@ PAL_NUM DkMemoryAvailableQuota(void); * PAL-enforced size of `report` (432B in case of SGX PAL). */ PAL_BOL DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size); + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size); /*! * \brief Obtain the attestation quote with `user_report_data` embedded into it. @@ -781,8 +743,8 @@ PAL_BOL DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_ * \param[in,out] quote_size Caller specifies maximum size allocated for `quote`; on * return, contains actual size of obtained quote. */ -PAL_BOL DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, - PAL_PTR quote, PAL_NUM* quote_size); +PAL_BOL DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, PAL_PTR quote, + PAL_NUM* quote_size); /*! * \brief Set wrap key (master key) for protected files. @@ -796,10 +758,10 @@ PAL_BOL DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_si PAL_BOL DkSetProtectedFilesKey(PAL_PTR pf_key_hex); #ifdef __GNUC__ -# define symbol_version_default(real, name, version) \ - __asm__ (".symver " #real "," #name "@@" #version "\n") +#define symbol_version_default(real, name, version) \ + __asm__(".symver " #real "," #name "@@" #version "\n") #else -# define symbol_version_default(real, name, version) +#define symbol_version_default(real, name, version) #endif #if defined(__i386__) || defined(__x86_64__) diff --git a/Pal/include/pal/pal_debug.h b/Pal/include/pal/pal_debug.h index 74385f9f82..30808246a8 100644 --- a/Pal/include/pal/pal_debug.h +++ b/Pal/include/pal/pal_debug.h @@ -12,10 +12,10 @@ #include "pal.h" -int pal_printf (const char *fmt, ...) __attribute__((format(printf, 1, 2))); +int pal_printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); void warn(const char* format, ...); -void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr); -void DkDebugDetachBinary (PAL_PTR start_addr); +void DkDebugAttachBinary(PAL_STR uri, PAL_PTR start_addr); +void DkDebugDetachBinary(PAL_PTR start_addr); #endif /* PAL_DEBUG_H */ diff --git a/Pal/include/pal/pal_error.h b/Pal/include/pal/pal_error.h index 36d1d8c0b6..c18a05f973 100644 --- a/Pal/include/pal/pal_error.h +++ b/Pal/include/pal/pal_error.h @@ -2,8 +2,6 @@ /* Copyright (C) 2014 Stony Brook University */ /* - * pal_error.h - * * This file contains definitions of PAL error codes. */ diff --git a/Pal/include/sysdeps/generic/ldsodefs.h b/Pal/include/sysdeps/generic/ldsodefs.h index 2ea0d762f8..a292b4a331 100644 --- a/Pal/include/sysdeps/generic/ldsodefs.h +++ b/Pal/include/sysdeps/generic/ldsodefs.h @@ -20,13 +20,12 @@ #ifndef _LDSODEFS_H #define _LDSODEFS_H 1 -#include -#define __need_size_t -#define __need_NULL -#include -#include #include +#include "elf/elf.h" +#include "stdbool.h" +#include "stddef.h" + /* We use this macro to refer to ELF types independent of the native wordsize. `ElfW(TYPE)' is used in place of `Elf32_TYPE' or `Elf64_TYPE'. */ #define ElfW(type) _ElfW(Elf, __ELF_NATIVE_CLASS, type) diff --git a/Pal/lib/avl_tree.c b/Pal/lib/avl_tree.c index dfff0a7ab2..56f1dbbe59 100644 --- a/Pal/lib/avl_tree.c +++ b/Pal/lib/avl_tree.c @@ -3,16 +3,17 @@ * Borys PopÅ‚awski */ +#include "avl_tree.h" + #include #include "api.h" #include "assert.h" -#include "avl_tree.h" static void avl_tree_init_node(struct avl_tree_node* node) { - node->left = NULL; - node->right = NULL; - node->parent = NULL; + node->left = NULL; + node->right = NULL; + node->parent = NULL; node->balance = 0; } @@ -49,8 +50,7 @@ static void avl_tree_insert_unbalanced(struct avl_tree* tree, /* Replaces `old_node` with `new_node` fixing all necessary links. `parent` must be the parent of * `old_node` before call to this. */ -static void fixup_link(struct avl_tree_node* old_node, - struct avl_tree_node* new_node, +static void fixup_link(struct avl_tree_node* old_node, struct avl_tree_node* new_node, struct avl_tree_node* parent) { if (parent) { if (parent->left == old_node) { @@ -283,9 +283,9 @@ static struct avl_tree_node* avl_tree_balance(struct avl_tree_node* node, enum s assert(-2 <= node->balance && node->balance <= 2); if (node->balance == -2 || node->balance == 2) { - height_changed = avl_tree_do_balance(node, &node); - /* On inserting height never changes. */ - height_changed = height_increased ? false : height_changed; + height_changed = avl_tree_do_balance(node, &node); + /* On inserting height never changes. */ + height_changed = height_increased ? false : height_changed; } /* This sub-tree is balanced, but its height might have changed. */ @@ -489,10 +489,10 @@ void avl_tree_delete(struct avl_tree* tree, struct avl_tree_node* node) { } } -static struct avl_tree_node* - avl_tree_find_fn_to(struct avl_tree* tree, - struct avl_tree_node* cmp_arg, - bool cmp(struct avl_tree_node*, struct avl_tree_node*)) { +static struct avl_tree_node* avl_tree_find_fn_to(struct avl_tree* tree, + struct avl_tree_node* cmp_arg, + bool cmp(struct avl_tree_node*, + struct avl_tree_node*)) { struct avl_tree_node* node = tree->root; while (node) { @@ -514,8 +514,7 @@ struct avl_tree_node* avl_tree_find(struct avl_tree* tree, struct avl_tree_node* return avl_tree_find_fn_to(tree, node, tree->cmp); } -struct avl_tree_node* avl_tree_lower_bound_fn(struct avl_tree* tree, - void* cmp_arg, +struct avl_tree_node* avl_tree_lower_bound_fn(struct avl_tree* tree, void* cmp_arg, bool cmp(void*, struct avl_tree_node*)) { struct avl_tree_node* node = tree->root; struct avl_tree_node* ret = NULL; @@ -532,12 +531,10 @@ struct avl_tree_node* avl_tree_lower_bound_fn(struct avl_tree* tree, return ret; } -struct avl_tree_node* avl_tree_lower_bound(struct avl_tree* tree, - struct avl_tree_node* cmp_arg) { +struct avl_tree_node* avl_tree_lower_bound(struct avl_tree* tree, struct avl_tree_node* cmp_arg) { static_assert(SAME_TYPE(tree->cmp, bool (*)(struct avl_tree_node*, struct avl_tree_node*)), "If you change this function type, make sure the code below works properly!"); - return avl_tree_lower_bound_fn(tree, - cmp_arg, + return avl_tree_lower_bound_fn(tree, cmp_arg, (bool (*)(void*, struct avl_tree_node*))tree->cmp); } diff --git a/Pal/lib/crypto/adapters/mbedtls_adapter.c b/Pal/lib/crypto/adapters/mbedtls_adapter.c index 003f35c79b..8cc291a101 100644 --- a/Pal/lib/crypto/adapters/mbedtls_adapter.c +++ b/Pal/lib/crypto/adapters/mbedtls_adapter.c @@ -8,10 +8,6 @@ #include #include "api.h" -#include "pal.h" -#include "pal_crypto.h" -#include "pal_error.h" -#include "pal_debug.h" #include "assert.h" #include "mbedtls/aes.h" #include "mbedtls/cmac.h" @@ -21,10 +17,14 @@ #include "mbedtls/net_sockets.h" #include "mbedtls/rsa.h" #include "mbedtls/sha256.h" +#include "pal.h" +#include "pal_crypto.h" +#include "pal_debug.h" +#include "pal_error.h" #include "rng-arch.h" int mbedtls_to_pal_error(int error) { - switch(error) { + switch (error) { case 0: return 0; @@ -44,7 +44,7 @@ int mbedtls_to_pal_error(int error) { case MBEDTLS_ERR_MD_BAD_INPUT_DATA: case MBEDTLS_ERR_MPI_BAD_INPUT_DATA: case MBEDTLS_ERR_RSA_BAD_INPUT_DATA: - case MBEDTLS_ERR_RSA_PUBLIC_FAILED: // see mbedtls_rsa_public() + case MBEDTLS_ERR_RSA_PUBLIC_FAILED: // see mbedtls_rsa_public() case MBEDTLS_ERR_RSA_PRIVATE_FAILED: // see mbedtls_rsa_private() return -PAL_ERROR_CRYPTO_BAD_INPUT_DATA; @@ -174,7 +174,7 @@ int lib_AESGCMEncrypt(const uint8_t* key, size_t key_size, const uint8_t* iv, co out: mbedtls_gcm_free(&gcm); return ret; - } +} int lib_AESGCMDecrypt(const uint8_t* key, size_t key_size, const uint8_t* iv, const uint8_t* input, size_t input_size, const uint8_t* aad, size_t aad_size, uint8_t* output, @@ -202,27 +202,27 @@ int lib_AESGCMDecrypt(const uint8_t* key, size_t key_size, const uint8_t* iv, co out: mbedtls_gcm_free(&gcm); return ret; - } +} int lib_AESCMAC(const uint8_t* key, size_t key_size, const uint8_t* input, size_t input_size, uint8_t* mac, size_t mac_size) { mbedtls_cipher_type_t cipher; switch (key_size) { - case 16: - cipher = MBEDTLS_CIPHER_AES_128_ECB; - break; - case 24: - cipher = MBEDTLS_CIPHER_AES_192_ECB; - break; - case 32: - cipher = MBEDTLS_CIPHER_AES_256_ECB; - break; - default: - return -PAL_ERROR_INVAL; + case 16: + cipher = MBEDTLS_CIPHER_AES_128_ECB; + break; + case 24: + cipher = MBEDTLS_CIPHER_AES_192_ECB; + break; + case 32: + cipher = MBEDTLS_CIPHER_AES_256_ECB; + break; + default: + return -PAL_ERROR_INVAL; } - const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(cipher); + const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(cipher); if (mac_size < cipher_info->block_size) { return -PAL_ERROR_INVAL; @@ -235,20 +235,20 @@ int lib_AESCMAC(const uint8_t* key, size_t key_size, const uint8_t* input, size_ int lib_AESCMACInit(LIB_AESCMAC_CONTEXT* context, const uint8_t* key, size_t key_size) { switch (key_size) { - case 16: - context->cipher = MBEDTLS_CIPHER_AES_128_ECB; - break; - case 24: - context->cipher = MBEDTLS_CIPHER_AES_192_ECB; - break; - case 32: - context->cipher = MBEDTLS_CIPHER_AES_256_ECB; - break; - default: - return -PAL_ERROR_INVAL; + case 16: + context->cipher = MBEDTLS_CIPHER_AES_128_ECB; + break; + case 24: + context->cipher = MBEDTLS_CIPHER_AES_192_ECB; + break; + case 32: + context->cipher = MBEDTLS_CIPHER_AES_256_ECB; + break; + default: + return -PAL_ERROR_INVAL; } - const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(context->cipher); + const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(context->cipher); int ret = mbedtls_cipher_setup(&context->ctx, cipher_info); if (ret != 0) @@ -264,7 +264,7 @@ int lib_AESCMACUpdate(LIB_AESCMAC_CONTEXT* context, const uint8_t* input, size_t } int lib_AESCMACFinish(LIB_AESCMAC_CONTEXT* context, uint8_t* mac, size_t mac_size) { - const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(context->cipher); + const mbedtls_cipher_info_t* cipher_info = mbedtls_cipher_info_from_type(context->cipher); int ret = -PAL_ERROR_INVAL; if (mac_size < cipher_info->block_size) @@ -295,7 +295,7 @@ int lib_RSAGenerateKey(LIB_RSA_KEY* key, uint64_t length_in_bits, uint64_t expon if (length_in_bits > UINT_MAX) return -PAL_ERROR_INVAL; - if (exponent > UINT_MAX || (int) exponent < 0) + if (exponent > UINT_MAX || (int)exponent < 0) return -PAL_ERROR_INVAL; int ret = mbedtls_rsa_gen_key(key, RandomWrapper, NULL, length_in_bits, exponent); @@ -336,7 +336,6 @@ int lib_RSAImportPublicKey(LIB_RSA_KEY* key, const uint8_t* e, size_t e_size, co int lib_RSAVerifySHA256(LIB_RSA_KEY* key, const uint8_t* hash, size_t hash_size, const uint8_t* signature, size_t signature_size) { - /* The mbedtls decrypt API assumes that you have a memory buffer that * is as large as the key size and take the length as a parameter. We * check, so that in the event the caller makes a mistake, you'll get @@ -417,9 +416,8 @@ static int send_cb(void* ctx, uint8_t const* buf, size_t buf_size) { } /*! This function is not thread-safe; caller is responsible for proper synchronization. */ -int lib_SSLInit(LIB_SSL_CONTEXT* ssl_ctx, int stream_fd, bool is_server, - const uint8_t* psk, size_t psk_size, - ssize_t (*pal_recv_cb)(int fd, void* buf, size_t buf_size), +int lib_SSLInit(LIB_SSL_CONTEXT* ssl_ctx, int stream_fd, bool is_server, const uint8_t* psk, + size_t psk_size, ssize_t (*pal_recv_cb)(int fd, void* buf, size_t buf_size), ssize_t (*pal_send_cb)(int fd, const void* buf, size_t buf_size), const uint8_t* buf_load_ssl_ctx, size_t buf_size) { int ret; @@ -445,8 +443,7 @@ int lib_SSLInit(LIB_SSL_CONTEXT* ssl_ctx, int stream_fd, bool is_server, ret = mbedtls_ssl_config_defaults(&ssl_ctx->conf, is_server ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) return mbedtls_to_pal_error(ret); @@ -507,7 +504,7 @@ int lib_SSLRead(LIB_SSL_CONTEXT* ssl_ctx, uint8_t* buf, size_t buf_size) { int lib_SSLWrite(LIB_SSL_CONTEXT* ssl_ctx, const uint8_t* buf, size_t buf_size) { int ret = mbedtls_ssl_write(&ssl_ctx->ssl, buf, buf_size); if (ret <= 0) - return mbedtls_to_pal_error(ret); + return mbedtls_to_pal_error(ret); return ret; } diff --git a/Pal/lib/crypto/adapters/mbedtls_encoding.c b/Pal/lib/crypto/adapters/mbedtls_encoding.c index 0523564942..5fec8b4c80 100644 --- a/Pal/lib/crypto/adapters/mbedtls_encoding.c +++ b/Pal/lib/crypto/adapters/mbedtls_encoding.c @@ -2,9 +2,10 @@ /* Copyright (C) 2019, Texas A&M University. */ #include + +#include "mbedtls/base64.h" #include "pal_crypto.h" #include "pal_error.h" -#include "mbedtls/base64.h" /*! * \brief Encode a byte array into a Base64 string diff --git a/Pal/lib/graphene/config.c b/Pal/lib/graphene/config.c index 4554ea7e2a..ca172176fc 100644 --- a/Pal/lib/graphene/config.c +++ b/Pal/lib/graphene/config.c @@ -8,9 +8,9 @@ * a tree to lookup / access config values. */ -#include -#include -#include +#include "api.h" +#include "list.h" +#include "pal_error.h" DEFINE_LIST(config); struct config { diff --git a/Pal/lib/graphene/path.c b/Pal/lib/graphene/path.c index 2c2c3ba1d2..a530725c06 100644 --- a/Pal/lib/graphene/path.c +++ b/Pal/lib/graphene/path.c @@ -8,8 +8,8 @@ * lookup / access config values. */ -#include -#include +#include "api.h" +#include "pal_error.h" /* * Finds next '/' in `path`. @@ -69,7 +69,7 @@ int get_norm_path(const char* path, char* buf, size_t* size_ptr) { size_t offset = 0, ret_size = 0; /* accounts for undiscardable bytes written to `buf` * i.e. `buf - ret_size` points to original `buf` */ - bool need_slash = false; // is '/' needed before next token + bool need_slash = false; // is '/' needed before next token bool is_absolute_path = *path == '/'; /* handle an absolute path */ diff --git a/Pal/lib/network/hton.c b/Pal/lib/network/hton.c index e8e79f31d6..157f2d05a5 100644 --- a/Pal/lib/network/hton.c +++ b/Pal/lib/network/hton.c @@ -16,9 +16,8 @@ Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ -#include - #include "api.h" +#include "host_endian.h" static uint16_t __bswap_16(uint16_t x) { return __builtin_bswap32(x) >> 16; diff --git a/Pal/lib/stdlib/printfmt.c b/Pal/lib/stdlib/printfmt.c index 17f343c48d..2e22ad0daa 100644 --- a/Pal/lib/stdlib/printfmt.c +++ b/Pal/lib/stdlib/printfmt.c @@ -180,7 +180,7 @@ void vfprintfmt(int (*_fputch)(void*, int, void*), void* f, void* putdat, const // (unsigned) octal case 'o': - num_u = GET_UINT(ap, lflag); + num_u = GET_UINT(ap, lflag); base = 8; goto print_unsigned; diff --git a/Pal/lib/string/strchr.c b/Pal/lib/string/strchr.c index f6761a7e2b..853bacfb05 100644 --- a/Pal/lib/string/strchr.c +++ b/Pal/lib/string/strchr.c @@ -22,7 +22,7 @@ Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ -#include +#include "api.h" /* Find the first occurrence of C in S. */ char* strchr(const char* s, int c_in) { diff --git a/Pal/lib/string/strendswith.c b/Pal/lib/string/strendswith.c index cd3507f90b..ee2492f5eb 100644 --- a/Pal/lib/string/strendswith.c +++ b/Pal/lib/string/strendswith.c @@ -1,4 +1,4 @@ -#include +#include "api.h" bool strendswith(const char* haystack, const char* needle) { size_t haystack_len = strlen(haystack); diff --git a/Pal/regression/AttestationReport.c b/Pal/regression/AttestationReport.c index b7a79bd12b..5b87ace883 100644 --- a/Pal/regression/AttestationReport.c +++ b/Pal/regression/AttestationReport.c @@ -3,7 +3,7 @@ #include "pal_debug.h" #include "sgx_arch.h" -#define ALLOC_ALIGN_UP(addr) ALIGN_UP_POW2(addr, pal_control.alloc_align) +#define ALLOC_ALIGN_UP(addr) ALIGN_UP_POW2(addr, pal_control.alloc_align) char zerobuf[sizeof(sgx_report_t)] = {0}; @@ -64,9 +64,8 @@ int main(int argc, char** argv) { memset(target_info, 0, target_info_size); memset(report, 0, report_size); - ret = DkAttestationReport(user_report_data, &user_report_data_size, - target_info, &target_info_size, - report, &report_size); + ret = DkAttestationReport(user_report_data, &user_report_data_size, target_info, + &target_info_size, report, &report_size); if (!ret) { pal_printf("ERROR: DkAttestationReport() to get SGX report failed\n"); return -1; @@ -74,7 +73,7 @@ int main(int argc, char** argv) { sgx_report_t* sgx_report = (sgx_report_t*)report; if (memcmp(&sgx_report->body.report_data.d, user_report_data, - sizeof(sgx_report->body.report_data.d))) { + sizeof(sgx_report->body.report_data.d))) { pal_printf("ERROR: DkAttestationReport() returned SGX report with wrong report_data\n"); return -1; } diff --git a/Pal/regression/Exception.c b/Pal/regression/Exception.c index 67449f1128..6305a8ce6e 100644 --- a/Pal/regression/Exception.c +++ b/Pal/regression/Exception.c @@ -1,7 +1,7 @@ /* This Hello World simply print out "Hello World" */ -#include #include +#include #include "pal.h" #include "pal_debug.h" @@ -12,36 +12,30 @@ static void* get_stack(void) { return stack; } -static void handler1(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) -{ - pal_printf("Arithmetic Exception Handler 1: 0x%08lx, rip = 0x%08lx\n", - arg, context->rip); +static void handler1(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + pal_printf("Arithmetic Exception Handler 1: 0x%08lx, rip = 0x%08lx\n", arg, context->rip); pal_printf("Stack in handler: %p\n", get_stack()); - while (*(unsigned char *) context->rip != 0x90) + while (*(unsigned char*)context->rip != 0x90) context->rip++; DkExceptionReturn(event); } -static void handler2(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) -{ - pal_printf("Arithmetic Exception Handler 2: 0x%08lx, rip = 0x%08lx\n", - arg, context->rip); +static void handler2(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + pal_printf("Arithmetic Exception Handler 2: 0x%08lx, rip = 0x%08lx\n", arg, context->rip); - while (*(unsigned char *) context->rip != 0x90) + while (*(unsigned char*)context->rip != 0x90) context->rip++; DkExceptionReturn(event); } -static void handler3(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) -{ - pal_printf("Memory Fault Exception Handler: 0x%08lx, rip = 0x%08lx\n", - arg, context->rip); +static void handler3(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + pal_printf("Memory Fault Exception Handler: 0x%08lx, rip = 0x%08lx\n", arg, context->rip); - while (*(unsigned char *) context->rip != 0x90) + while (*(unsigned char*)context->rip != 0x90) context->rip++; DkExceptionReturn(event); @@ -49,11 +43,11 @@ static void handler3(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) atomic_bool handler4_called = false; -static void handler4(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) -{ - pal_printf("Arithmetic Exception Handler 4: 0x%" PRIx64 ", rip = 0x%" PRIx64 "\n", arg, context->rip); +static void handler4(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) { + pal_printf("Arithmetic Exception Handler 4: 0x%" PRIx64 ", rip = 0x%" PRIx64 "\n", arg, + context->rip); - while (*(unsigned char *) context->rip != 0x90) + while (*(unsigned char*)context->rip != 0x90) context->rip++; handler4_called = true; @@ -68,36 +62,36 @@ static void red_zone_test(void) { // itself. pal_printf("Testing red zone...\n"); - __asm__ volatile ( - // Fill the red zone with a pattern (0xaa 0xa9 0xa8 ...) - "movq $-128, %%rax\n" - "movq $0xaa, %%rbx\n" - "1:\n" - "movb %%bl, (%%rsp, %%rax, 1)\n" - "decq %%rbx\n" - "incq %%rax\n" - "jnz 1b\n" - - // Trigger exception - "movq $1, %%rax\n" - "cqo\n" - "movq $0, %%rbx\n" - "divq %%rbx\n" - "nop\n" - - // Calculate sum of pattern - "movq $-128, %%rax\n" - "movq $0, %%rbx\n" - "movq $0, %%rcx\n" - "1:\n" - "movb (%%rsp, %%rax, 1), %%bl\n" - "addq %%rbx, %%rcx\n" - "incq %%rax\n" - "jnz 1b\n" - "movq %%rcx, %q0\n" - : "=rm"(res) - : - : "rax", "rbx", "rcx", "rdx", "cc", "memory"); + __asm__ volatile( + // Fill the red zone with a pattern (0xaa 0xa9 0xa8 ...) + "movq $-128, %%rax\n" + "movq $0xaa, %%rbx\n" + "1:\n" + "movb %%bl, (%%rsp, %%rax, 1)\n" + "decq %%rbx\n" + "incq %%rax\n" + "jnz 1b\n" + + // Trigger exception + "movq $1, %%rax\n" + "cqo\n" + "movq $0, %%rbx\n" + "divq %%rbx\n" + "nop\n" + + // Calculate sum of pattern + "movq $-128, %%rax\n" + "movq $0, %%rbx\n" + "movq $0, %%rcx\n" + "1:\n" + "movb (%%rsp, %%rax, 1), %%bl\n" + "addq %%rbx, %%rcx\n" + "incq %%rax\n" + "jnz 1b\n" + "movq %%rcx, %q0\n" + : "=rm"(res) + : + : "rax", "rbx", "rcx", "rdx", "cc", "memory"); if (!handler4_called) { pal_printf("Exception handler was not called!\n"); @@ -112,8 +106,7 @@ static void red_zone_test(void) { pal_printf("Red zone test ok.\n"); } -int main (void) -{ +int main(void) { volatile long i; pal_printf("Stack in main: %p\n", get_stack()); @@ -129,7 +122,7 @@ int main (void) __asm__ volatile("nop"); DkSetExceptionHandler(handler3, PAL_EVENT_MEMFAULT); - *(volatile long *) 0x1000 = 0; + *(volatile long*)0x1000 = 0; __asm__ volatile("nop"); DkSetExceptionHandler(handler4, PAL_EVENT_ARITHMETIC_ERROR); diff --git a/Pal/regression/File.c b/Pal/regression/File.c index 56ad63353d..0112c75808 100644 --- a/Pal/regression/File.c +++ b/Pal/regression/File.c @@ -3,7 +3,7 @@ #include "pal_debug.h" #define NUM_TO_HEX(num) ((num) >= 10 ? 'a' + ((num) - 10) : '0' + (num)) -#define BUF_SIZE 40 +#define BUF_SIZE 40 char buffer1[BUF_SIZE]; char buffer2[BUF_SIZE]; @@ -14,8 +14,8 @@ static void print_hex(char* fmt, const void* data, int len) { hex_buf[len * 2] = '\0'; for (int i = 0; i < len; i++) { unsigned char b = ((unsigned char*)data)[i]; - hex_buf[i * 2] = NUM_TO_HEX(b >> 4); - hex_buf[i * 2 + 1] = NUM_TO_HEX(b & 0xf); + hex_buf[i * 2] = NUM_TO_HEX(b >> 4); + hex_buf[i * 2 + 1] = NUM_TO_HEX(b & 0xf); } pal_printf(fmt, hex_buf); } @@ -58,7 +58,8 @@ int main(int argc, char** argv, char** envp) { /* test file map */ - void* mem1 = (void*)DkStreamMap(file1, NULL, PAL_PROT_READ | PAL_PROT_WRITECOPY, 0, PAGE_SIZE); + void* mem1 = (void*)DkStreamMap(file1, NULL, PAL_PROT_READ | PAL_PROT_WRITECOPY, 0, + PAGE_SIZE); if (mem1) { memcpy(buffer1, mem1, 40); print_hex("Map Test 1 (0th - 40th): %s\n", buffer1, 40); @@ -105,15 +106,13 @@ int main(int argc, char** argv, char** envp) { /* test regular file creation */ - PAL_HANDLE file4 = - DkStreamOpen("file:file_nonexist.tmp", PAL_ACCESS_RDWR, - PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); + PAL_HANDLE file4 = DkStreamOpen("file:file_nonexist.tmp", PAL_ACCESS_RDWR, + PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); if (file4) pal_printf("File Creation Test 1 OK\n"); - PAL_HANDLE file5 = - DkStreamOpen("file:file_nonexist.tmp", PAL_ACCESS_RDWR, - PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); + PAL_HANDLE file5 = DkStreamOpen("file:file_nonexist.tmp", PAL_ACCESS_RDWR, + PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); if (file5) { DkObjectClose(file5); } else { @@ -127,9 +126,8 @@ int main(int argc, char** argv, char** envp) { DkObjectClose(file6); } - file6 = - DkStreamOpen("file:file_nonexist_disallowed.tmp", PAL_ACCESS_RDWR, - PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); + file6 = DkStreamOpen("file:file_nonexist_disallowed.tmp", PAL_ACCESS_RDWR, + PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_ALWAYS, 0); if (!file6) { pal_printf("File Creation Test 4 OK\n"); } else { diff --git a/Pal/regression/Hex.c b/Pal/regression/Hex.c index b88161fb13..000d4e42b0 100644 --- a/Pal/regression/Hex.c +++ b/Pal/regression/Hex.c @@ -1,10 +1,9 @@ #include -#include "pal_debug.h" - -#include "hex.h" #include "api.h" +#include "hex.h" #include "pal.h" +#include "pal_debug.h" char x[] = {0xde, 0xad, 0xbe, 0xef}; char y[] = {0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd}; diff --git a/Pal/regression/avl_tree_test.c b/Pal/regression/avl_tree_test.c index bc3c10c6b6..58971d84a5 100644 --- a/Pal/regression/avl_tree_test.c +++ b/Pal/regression/avl_tree_test.c @@ -1,22 +1,24 @@ -#include "api.h" -#include "assert.h" #include "avl_tree.h" -#include "pal.h" -#include "pal_debug.h" #include #include #include +#include "api.h" +#include "assert.h" +#include "pal.h" +#include "pal_debug.h" + noreturn void __abort(void) { warn("ABORTED\n"); DkProcessExit(1); } -#define EXIT_UNBALANCED() do { \ - pal_printf("Unbalanced tree at: %u\n", __LINE__); \ - DkProcessExit(1); \ - } while(0) +#define EXIT_UNBALANCED() \ + do { \ + pal_printf("Unbalanced tree at: %u\n", __LINE__); \ + DkProcessExit(1); \ + } while (0) static uint32_t _seed; @@ -65,10 +67,9 @@ static bool cmp_gen(void* x, struct avl_tree_node* y) { #define ELEMENTS_COUNT 0x1000 #define RAND_DEL_COUNT 0x100 -static struct avl_tree tree = { .root = NULL, .cmp = cmp }; +static struct avl_tree tree = {.root = NULL, .cmp = cmp}; static struct A t[ELEMENTS_COUNT]; - __attribute__((unused)) static void debug_print(struct avl_tree_node* node) { if (!node) { pal_printf("LEAF"); @@ -91,8 +92,8 @@ static size_t get_tree_size(struct avl_tree_node* node) { static void try_node_swap(struct avl_tree_node* node, struct avl_tree_node* swap_node) { avl_tree_swap_node(&tree, node, swap_node); - node->left = (void*)1; - node->right = (void*)2; + node->left = (void*)1; + node->right = (void*)2; node->parent = (void*)3; if (!debug_avl_tree_is_balanced(&tree)) { EXIT_UNBALANCED(); @@ -104,8 +105,8 @@ static void try_node_swap(struct avl_tree_node* node, struct avl_tree_node* swap } avl_tree_swap_node(&tree, swap_node, node); - swap_node->left = (void*)1; - swap_node->right = (void*)2; + swap_node->left = (void*)1; + swap_node->right = (void*)2; swap_node->parent = (void*)3; if (!debug_avl_tree_is_balanced(&tree)) { EXIT_UNBALANCED(); @@ -121,7 +122,7 @@ static void do_test(int32_t (*get_num)(void)) { size_t i; for (i = 0; i < ELEMENTS_COUNT; i++) { - t[i].key = get_num(); + t[i].key = get_num(); t[i].freed = false; avl_tree_insert(&tree, &t[i].node); if (!debug_avl_tree_is_balanced(&tree)) { @@ -166,15 +167,15 @@ static void do_test(int32_t (*get_num)(void)) { size++; } if (size != ELEMENTS_COUNT) { - pal_printf("Tree iteration from the end walked through %lu elements instead of %u!", - size, ELEMENTS_COUNT); + pal_printf("Tree iteration from the end walked through %lu elements instead of %u!", size, + ELEMENTS_COUNT); DkProcessExit(1); } static_assert(ELEMENTS_COUNT >= 3, "This code needs at least 3 elements in the tree!"); node = tree.root->left; - struct A swap_node = { .key = node2struct(node)->key }; + struct A swap_node = {.key = node2struct(node)->key}; try_node_swap(node, &swap_node.node); node = tree.root; @@ -200,7 +201,7 @@ static void do_test(int32_t (*get_num)(void)) { } /* get_num returns int32_t, but tmp.key is a int64_t, so this cannot overflow. */ - struct A tmp = { .key = val + 100 }; + struct A tmp = {.key = val + 100}; avl_tree_insert(&tree, &tmp.node); if (!debug_avl_tree_is_balanced(&tree)) { EXIT_UNBALANCED(); @@ -257,7 +258,8 @@ static void do_test(int32_t (*get_num)(void)) { #define DIFF_ELEMENTS 0x10 #define _STR(x) #x static void test_ordering(void) { - static_assert(ELEMENTS_COUNT > DIFF_ELEMENTS, "This test requires more than " _STR(DIFF_ELEMENTS) " elements!"); + static_assert(ELEMENTS_COUNT > DIFF_ELEMENTS, + "This test requires more than " _STR(DIFF_ELEMENTS) " elements!"); ssize_t i; /* The newer node will be on the left, so we need to insert them in reverse order. */ diff --git a/Pal/regression/normalize_path.c b/Pal/regression/normalize_path.c index 15b1e987a3..43fcbeefca 100644 --- a/Pal/regression/normalize_path.c +++ b/Pal/regression/normalize_path.c @@ -38,10 +38,10 @@ static const char* get_base_name_cases[][2] = { {"a/b/c", "c"}, }; -#define print_err(name, i, ...) \ - do { \ +#define print_err(name, i, ...) \ + do { \ pal_printf("%s: case %lu (\"%s\") ", name, i, cases[i][0]); \ - pal_printf(__VA_ARGS__); \ + pal_printf(__VA_ARGS__); \ } while (0) static const char* (*cases)[2]; @@ -54,7 +54,7 @@ char buf[URI_MAX] = {0}; static int run_test(void) { for (size_t i = 0; i < cases_len; i++) { size_t size = sizeof(buf); - int ret = func_to_test(cases[i][0], buf, &size); + int ret = func_to_test(cases[i][0], buf, &size); if (ret < 0) { print_err(func_name, i, "failed with error: %s\n", pal_strerror(ret)); diff --git a/Pal/src/db_events.c b/Pal/src/db_events.c index 431f6f26d5..de4671f042 100644 --- a/Pal/src/db_events.c +++ b/Pal/src/db_events.c @@ -17,7 +17,7 @@ PAL_HANDLE DkNotificationEventCreate(PAL_BOL initialState) { ENTER_PAL_CALL(DkNotificationEventCreate); PAL_HANDLE handle = NULL; - int ret = _DkEventCreate(&handle, initialState, true); + int ret = _DkEventCreate(&handle, initialState, true); if (ret < 0) { _DkRaiseFailure(-ret); @@ -31,7 +31,7 @@ PAL_HANDLE DkSynchronizationEventCreate(PAL_BOL initialState) { ENTER_PAL_CALL(DkSynchronizationEventCreate); PAL_HANDLE handle = NULL; - int ret = _DkEventCreate(&handle, initialState, false); + int ret = _DkEventCreate(&handle, initialState, false); if (ret < 0) { _DkRaiseFailure(-ret); diff --git a/Pal/src/db_exception.c b/Pal/src/db_exception.c index 95a3b7861d..89e419b694 100644 --- a/Pal/src/db_exception.c +++ b/Pal/src/db_exception.c @@ -18,7 +18,7 @@ #include "pal_error.h" #include "pal_internal.h" -PAL_EVENT_HANDLER g_handlers[PAL_EVENT_NUM_BOUND] = { 0 }; +PAL_EVENT_HANDLER g_handlers[PAL_EVENT_NUM_BOUND] = {0}; PAL_EVENT_HANDLER _DkGetExceptionHandler(PAL_NUM event) { return __atomic_load_n(&g_handlers[event], __ATOMIC_ACQUIRE); diff --git a/Pal/src/db_main.c b/Pal/src/db_main.c index 1ea4d696c7..ffefaa0f6a 100644 --- a/Pal/src/db_main.c +++ b/Pal/src/db_main.c @@ -10,16 +10,15 @@ #include -#include "pal_defs.h" +#include "api.h" +#include "elf/elf.h" #include "pal.h" -#include "pal_internal.h" #include "pal_debug.h" +#include "pal_defs.h" #include "pal_error.h" +#include "pal_internal.h" #include "pal_rtld.h" -#include "api.h" - -#include -#include +#include "sysdeps/generic/ldsodefs.h" PAL_CONTROL g_pal_control; @@ -101,8 +100,7 @@ static int insert_envs_from_manifest(const char*** envpp) { int noverwrite = 0; for (const char** e = *envpp; *e; e++, nenvs++) for (int i = 0; i < setenvs_cnt; i++) - if (!memcmp(setenvs[i].str, *e, setenvs[i].len) && - (*e)[setenvs[i].len] == '=') { + if (!memcmp(setenvs[i].str, *e, setenvs[i].len) && (*e)[setenvs[i].len] == '=') { setenvs[i].idx = nenvs; noverwrite++; break; @@ -143,8 +141,7 @@ static int insert_envs_from_manifest(const char*** envpp) { return 0; } -static void set_debug_type (void) -{ +static void set_debug_type(void) { char cfgbuf[CONFIG_MAX]; ssize_t ret = 0; @@ -164,9 +161,7 @@ static void set_debug_type (void) if (ret <= 0) INIT_FAIL(PAL_ERROR_INVAL, "debug file not specified"); - ret = _DkStreamOpen(&handle, cfgbuf, - PAL_ACCESS_RDWR, - PAL_SHARE_OWNER_R|PAL_SHARE_OWNER_W, + ret = _DkStreamOpen(&handle, cfgbuf, PAL_ACCESS_RDWR, PAL_SHARE_OWNER_R | PAL_SHARE_OWNER_W, PAL_CREATE_TRY, 0); } else if (!strcmp_static(cfgbuf, "none")) { ret = 0; @@ -244,15 +239,14 @@ static int load_cstring_array(const char* uri, const char*** res) { } /* 'pal_main' must be called by the host-specific bootloader */ -noreturn void pal_main( - PAL_NUM instance_id, /* current instance id */ - PAL_HANDLE manifest_handle, /* manifest handle if opened */ - PAL_HANDLE exec_handle, /* executable handle if opened */ - PAL_PTR exec_loaded_addr, /* executable addr if loaded */ - PAL_HANDLE parent_process, /* parent process if it's a child */ - PAL_HANDLE first_thread, /* first thread handle */ - PAL_STR* arguments, /* application arguments */ - PAL_STR* environments /* environment variables */) { +noreturn void pal_main(PAL_NUM instance_id, /* current instance id */ + PAL_HANDLE manifest_handle, /* manifest handle if opened */ + PAL_HANDLE exec_handle, /* executable handle if opened */ + PAL_PTR exec_loaded_addr, /* executable addr if loaded */ + PAL_HANDLE parent_process, /* parent process if it's a child */ + PAL_HANDLE first_thread, /* first thread handle */ + PAL_STR* arguments, /* application arguments */ + PAL_STR* environments /* environment variables */) { char cfgbuf[CONFIG_MAX]; g_pal_state.instance_id = instance_id; g_pal_state.alloc_align = _DkGetAllocationAlignment(); @@ -263,7 +257,8 @@ noreturn void pal_main( g_pal_state.parent_process = parent_process; char uri_buf[URI_MAX]; - char * manifest_uri = NULL, * exec_uri = NULL; + char* manifest_uri = NULL; + char* exec_uri = NULL; ssize_t ret; if (exec_handle) { @@ -296,8 +291,7 @@ noreturn void pal_main( if (ret) { /* try open "file:manifest" */ manifest_uri = URI_PREFIX_FILE "manifest"; - ret = _DkStreamOpen(&manifest_handle, manifest_uri, PAL_ACCESS_RDONLY, - 0, 0, 0); + ret = _DkStreamOpen(&manifest_handle, manifest_uri, PAL_ACCESS_RDONLY, 0, 0, 0); if (ret) { INIT_FAIL(PAL_ERROR_DENIED, "cannot find manifest file"); } @@ -311,22 +305,20 @@ noreturn void pal_main( if (ret < 0) INIT_FAIL(-ret, "cannot open manifest file"); - void * cfg_addr = NULL; + void* cfg_addr = NULL; int cfg_size = attr.pending_size; - ret = _DkStreamMap(manifest_handle, &cfg_addr, - PAL_PROT_READ, 0, - ALLOC_ALIGN_UP(cfg_size)); + ret = _DkStreamMap(manifest_handle, &cfg_addr, PAL_PROT_READ, 0, ALLOC_ALIGN_UP(cfg_size)); if (ret < 0) INIT_FAIL(-ret, "cannot open manifest file"); - struct config_store * root_config = malloc(sizeof(struct config_store)); + struct config_store* root_config = malloc(sizeof(struct config_store)); root_config->raw_data = cfg_addr; root_config->raw_size = cfg_size; - root_config->malloc = malloc; - root_config->free = free; + root_config->malloc = malloc; + root_config->free = free; - const char * errstring = NULL; + const char* errstring = NULL; if ((ret = read_config(root_config, loader_filter, &errstring)) < 0) { INIT_FAIL(-ret, errstring); } @@ -339,8 +331,7 @@ noreturn void pal_main( ret = get_config(g_pal_state.root_config, "loader.exec", uri_buf, URI_MAX); if (ret > 0) { exec_uri = malloc_copy(uri_buf, ret + 1); - ret = _DkStreamOpen(&exec_handle, exec_uri, PAL_ACCESS_RDONLY, - 0, 0, 0); + ret = _DkStreamOpen(&exec_handle, exec_uri, PAL_ACCESS_RDONLY, 0, 0, 0); if (ret < 0) INIT_FAIL(-ret, "cannot open executable"); } @@ -366,10 +357,9 @@ noreturn void pal_main( exec_uri = malloc(exec_strlen + 1); if (!exec_uri) INIT_FAIL(PAL_ERROR_NOMEM, "Cannot allocate URI buf"); - memcpy (exec_uri, manifest_uri, exec_strlen); + memcpy(exec_uri, manifest_uri, exec_strlen); exec_uri[exec_strlen] = '\0'; - ret = _DkStreamOpen(&exec_handle, exec_uri, PAL_ACCESS_RDONLY, - 0, 0, 0); + ret = _DkStreamOpen(&exec_handle, exec_uri, PAL_ACCESS_RDONLY, 0, 0, 0); // DEP 3/20/17: There are cases where we want to let // the PAL start up without a main executable. Don't // die here, just free the exec_uri buffer. @@ -427,9 +417,10 @@ noreturn void pal_main( } } - if (get_config(g_pal_state.root_config, "loader.insecure__use_cmdline_argv", - cfgbuf, CONFIG_MAX) > 0) { - printf("WARNING: Using insecure argv source. Don't use this configuration in production!\n"); + if (get_config(g_pal_state.root_config, "loader.insecure__use_cmdline_argv", cfgbuf, + CONFIG_MAX) > 0) { + printf("WARNING: Using insecure argv source. Don't use this configuration in " + "production!\n"); } else if (get_config(g_pal_state.root_config, "loader.argv_src_file", cfgbuf, CONFIG_MAX) > 0) { /* Load argv from a file and discard cmdline argv. We trust the file contents (this can be @@ -442,13 +433,14 @@ noreturn void pal_main( if (ret < 0) INIT_FAIL(-ret, "can't load loader.argv_src_file"); } else if (!argv0_overridden || (arguments[0] && arguments[1])) { - INIT_FAIL(PAL_ERROR_INVAL, "argv handling wasn't configured in the manifest, but cmdline " + INIT_FAIL(PAL_ERROR_INVAL, + "argv handling wasn't configured in the manifest, but cmdline " "arguments were specified."); } bool using_host_env = false; - if (get_config(g_pal_state.root_config, "loader.insecure__use_host_env", - cfgbuf, CONFIG_MAX) > 0) { + if (get_config(g_pal_state.root_config, "loader.insecure__use_host_env", cfgbuf, CONFIG_MAX) + > 0) { using_host_env = true; printf("WARNING: Forwarding host environment variables to the app is enabled. Don't use " "this configuration in production!\n"); @@ -494,19 +486,19 @@ noreturn void pal_main( set_debug_type(); - g_pal_control.host_type = XSTRINGIFY(HOST_TYPE); - g_pal_control.process_id = _DkGetProcessId(); - g_pal_control.host_id = _DkGetHostId(); - g_pal_control.manifest_handle = manifest_handle; - g_pal_control.executable = exec_uri; - g_pal_control.parent_process = parent_process; - g_pal_control.first_thread = first_thread; - g_pal_control.disable_aslr = disable_aslr; + g_pal_control.host_type = XSTRINGIFY(HOST_TYPE); + g_pal_control.process_id = _DkGetProcessId(); + g_pal_control.host_id = _DkGetHostId(); + g_pal_control.manifest_handle = manifest_handle; + g_pal_control.executable = exec_uri; + g_pal_control.parent_process = parent_process; + g_pal_control.first_thread = first_thread; + g_pal_control.disable_aslr = disable_aslr; _DkGetAvailableUserAddressRange(&g_pal_control.user_address.start, &g_pal_control.user_address.end); - g_pal_control.alloc_align = g_pal_state.alloc_align; + g_pal_control.alloc_align = g_pal_state.alloc_align; if (_DkGetCPUInfo(&g_pal_control.cpu_info) < 0) { goto out_fail; @@ -516,7 +508,7 @@ noreturn void pal_main( /* Now we will start the execution */ start_execution(arguments, environments); - out_fail: +out_fail: /* We wish we will never reached here */ INIT_FAIL(PAL_ERROR_DENIED, "unexpected termination"); } diff --git a/Pal/src/db_misc.c b/Pal/src/db_misc.c index 974786bda8..2427f0758c 100644 --- a/Pal/src/db_misc.c +++ b/Pal/src/db_misc.c @@ -102,8 +102,8 @@ DkCpuIdRetrieve(PAL_IDX leaf, PAL_IDX subleaf, PAL_IDX values[4]) { } PAL_BOL DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size) { + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size) { ENTER_PAL_CALL(DkAttestationReport); int ret = _DkAttestationReport(user_report_data, user_report_data_size, target_info, @@ -115,8 +115,8 @@ PAL_BOL DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_ LEAVE_PAL_CALL_RETURN(PAL_TRUE); } -PAL_BOL DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, - PAL_PTR quote, PAL_NUM* quote_size) { +PAL_BOL DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, PAL_PTR quote, + PAL_NUM* quote_size) { ENTER_PAL_CALL(DkAttestationQuote); int ret = _DkAttestationQuote(user_report_data, user_report_data_size, quote, quote_size); diff --git a/Pal/src/db_mutex.c b/Pal/src/db_mutex.c index b4db7e5db4..2c27674b20 100644 --- a/Pal/src/db_mutex.c +++ b/Pal/src/db_mutex.c @@ -18,7 +18,7 @@ DkMutexCreate(PAL_NUM initialCount) { ENTER_PAL_CALL(DkMutexCreate); PAL_HANDLE handle = NULL; - int ret = _DkMutexCreate(&handle, initialCount); + int ret = _DkMutexCreate(&handle, initialCount); if (ret < 0) { _DkRaiseFailure(-ret); diff --git a/Pal/src/db_process.c b/Pal/src/db_process.c index 28ab607726..8367370024 100644 --- a/Pal/src/db_process.c +++ b/Pal/src/db_process.c @@ -31,7 +31,7 @@ DkProcessCreate(PAL_STR uri, PAL_STR* args) { uri = pal_control.executable; PAL_HANDLE handle = NULL; - int ret = _DkProcessCreate(&handle, uri, args); + int ret = _DkProcessCreate(&handle, uri, args); if (ret < 0) { _DkRaiseFailure(-ret); diff --git a/Pal/src/db_rtld.c b/Pal/src/db_rtld.c index 9200112285..ab30c6b9a7 100644 --- a/Pal/src/db_rtld.c +++ b/Pal/src/db_rtld.c @@ -12,29 +12,27 @@ #include -#include "pal_defs.h" +#include "api.h" +#include "elf/elf.h" #include "pal.h" -#include "pal_internal.h" #include "pal_debug.h" +#include "pal_defs.h" #include "pal_error.h" +#include "pal_internal.h" #include "pal_rtld.h" -#include "api.h" - -#include -#include +#include "sysdeps/generic/ldsodefs.h" struct link_map* g_loaded_maps = NULL; struct link_map* g_exec_map = NULL; -struct link_map * lookup_symbol (const char *undef_name, ElfW(Sym) **ref); +struct link_map* lookup_symbol(const char* undef_name, ElfW(Sym)** ref); /* This macro is used as a callback from the ELF_DYNAMIC_RELOCATE code. */ -static struct link_map * resolve_map (const char **strtab, ElfW(Sym) ** ref) -{ - if (ELFW(ST_BIND) ((*ref)->st_info) != STB_LOCAL) { - struct link_map * l = lookup_symbol((*strtab) + (*ref)->st_name, ref); +static struct link_map* resolve_map(const char** strtab, ElfW(Sym)** ref) { + if (ELFW(ST_BIND)((*ref)->st_info) != STB_LOCAL) { + struct link_map* l = lookup_symbol((*strtab) + (*ref)->st_name, ref); if (l) { - *strtab = (const void *) D_PTR (l->l_info[DT_STRTAB]); + *strtab = (const void*)D_PTR(l->l_info[DT_STRTAB]); return l; } } @@ -43,44 +41,38 @@ static struct link_map * resolve_map (const char **strtab, ElfW(Sym) ** ref) /* Define RESOLVE_RTLD as 0 since we rely on resolve_map on * all current PAL platforms */ -#define RESOLVE_RTLD(sym_name) 0 -#define RESOLVE_MAP(strtab, ref) resolve_map(strtab, ref) +#define RESOLVE_RTLD(sym_name) 0 +#define RESOLVE_MAP(strtab, ref) resolve_map(strtab, ref) -#include "dynamic_link.h" #include "dl-machine.h" +#include "dynamic_link.h" /* Allocate a `struct link_map' for a new object being loaded, and enter it into the _dl_loaded list. */ -struct link_map * -new_elf_object (const char * realname, enum object_type type) -{ - struct link_map *new; +struct link_map* new_elf_object(const char* realname, enum object_type type) { + struct link_map* new; - new = (struct link_map *) malloc(sizeof (struct link_map)); + new = (struct link_map*)malloc(sizeof(struct link_map)); if (new == NULL) return NULL; /* We apparently expect this to be zeroed. */ memset(new, 0, sizeof(struct link_map)); - new->l_name = realname ? - malloc_copy(realname, strlen(realname) + 1) : - NULL; + new->l_name = realname ? malloc_copy(realname, strlen(realname) + 1) : NULL; new->l_type = type; return new; } /* Cache the location of MAP's hash table. */ -void setup_elf_hash (struct link_map *map) -{ - Elf_Symndx * hash; +void setup_elf_hash(struct link_map* map) { + Elf_Symndx* hash; if (map->l_info[DT_ADDRTAGIDX(DT_GNU_HASH) + DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM + DT_EXTRANUM + DT_VALNUM] != NULL) { - Elf32_Word *hash32 - = (void *) D_PTR (map->l_info[DT_ADDRTAGIDX (DT_GNU_HASH) + DT_NUM - + DT_THISPROCNUM + DT_VERSIONTAGNUM - + DT_EXTRANUM + DT_VALNUM]); + Elf32_Word* hash32 = + (void*)D_PTR(map->l_info[DT_ADDRTAGIDX(DT_GNU_HASH) + DT_NUM + DT_THISPROCNUM + + DT_VERSIONTAGNUM + DT_EXTRANUM + DT_VALNUM]); map->l_nbuckets = *hash32++; @@ -91,7 +83,7 @@ void setup_elf_hash (struct link_map *map) map->l_gnu_bitmask_idxbits = bitmask_nwords - 1; map->l_gnu_shift = *hash32++; - map->l_gnu_bitmask = (ElfW(Addr) *) hash32; + map->l_gnu_bitmask = (ElfW(Addr)*)hash32; hash32 += __ELF_NATIVE_CLASS / 32 * bitmask_nwords; map->l_gnu_buckets = hash32; @@ -104,7 +96,7 @@ void setup_elf_hash (struct link_map *map) if (!map->l_info[DT_HASH]) return; - hash = (void *) D_PTR (map->l_info[DT_HASH]); + hash = (void*)D_PTR(map->l_info[DT_HASH]); /* Structure of DT_HASH: The bucket array forms the hast table itself. The entries in the @@ -127,12 +119,9 @@ void setup_elf_hash (struct link_map *map) /* Map in the shared object NAME, actually located in REALNAME, and already opened on FD */ -static struct link_map* -map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, - void * fbp, size_t fbp_len, - bool do_copy_dyn) -{ - struct link_map * l = new_elf_object(_DkStreamRealpath(handle), type); +static struct link_map* map_elf_object_by_handle(PAL_HANDLE handle, enum object_type type, + void* fbp, size_t fbp_len, bool do_copy_dyn) { + struct link_map* l = new_elf_object(_DkStreamRealpath(handle), type); int ret; if (handle == NULL) { @@ -141,7 +130,7 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, } /* This is the ELF header. We read it in `open_verify'. */ - const ElfW(Ehdr) * header = (void *) fbp; + const ElfW(Ehdr)* header = (void*)fbp; /* Extract the remaining details we need from the ELF header and then read in the program header table. */ @@ -149,23 +138,22 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, l->l_entry = header->e_entry; l->l_phnum = header->e_phnum; - size_t maplength = header->e_phnum * sizeof (ElfW(Phdr)); - ElfW(Phdr) * phdr; + size_t maplength = header->e_phnum * sizeof(ElfW(Phdr)); + ElfW(Phdr)* phdr; if (header->e_phoff + maplength <= fbp_len) { - phdr = (void *) ((char *) fbp + header->e_phoff); + phdr = (void*)((char*)fbp + header->e_phoff); } else { - phdr = (ElfW(Phdr) *) malloc (maplength); + phdr = (ElfW(Phdr)*)malloc(maplength); - if ((ret = _DkStreamRead(handle, header->e_phoff, maplength, phdr, - NULL, 0)) < 0) { + if ((ret = _DkStreamRead(handle, header->e_phoff, maplength, phdr, NULL, 0)) < 0) { print_error("cannot read file data", ret); return NULL; } } /* Presumed absent PT_GNU_STACK. */ - //uint_fast16_t stack_flags = PF_R|PF_W|PF_X; + // uint_fast16_t stack_flags = PF_R | PF_W | PF_X; /* Scan the program header table, collecting its load commands. */ struct loadcmd { @@ -183,28 +171,26 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, l->l_phdr = 0; l->l_addr = 0; */ - const ElfW(Phdr) * ph; + const ElfW(Phdr)* ph; for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph) - switch (ph->p_type) - { + switch (ph->p_type) { /* These entries tell us where to find things once the file's segments are mapped in. We record the addresses it says verbatim, and later correct for the run-time load address. */ case PT_DYNAMIC: - l->l_ld = (void *) ph->p_vaddr; - l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn)); + l->l_ld = (void*)ph->p_vaddr; + l->l_ldnum = ph->p_memsz / sizeof(ElfW(Dyn)); break; case PT_PHDR: - l->l_phdr = (void *) ph->p_vaddr; + l->l_phdr = (void*)ph->p_vaddr; break; case PT_LOAD: /* A load command tells us to map in part of the file. We record the load commands and process them all later. */ if (!IS_ALLOC_ALIGNED(ph->p_align)) { - print_error("ELF load command alignment not aligned", - -PAL_ERROR_NOMEM); + print_error("ELF load command alignment not aligned", -PAL_ERROR_NOMEM); return NULL; } @@ -216,10 +202,10 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, c = &loadcmds[nloadcmds++]; c->mapstart = ALLOC_ALIGN_DOWN(ph->p_vaddr); - c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_filesz); - c->dataend = ph->p_vaddr + ph->p_filesz; + c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_filesz); + c->dataend = ph->p_vaddr + ph->p_filesz; c->allocend = ph->p_vaddr + ph->p_memsz; - c->mapoff = ALLOC_ALIGN_DOWN(ph->p_offset); + c->mapoff = ALLOC_ALIGN_DOWN(ph->p_offset); /* Determine whether there is a gap between the last segment and this one. */ @@ -242,7 +228,7 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, break; case PT_GNU_STACK: - //stack_flags = ph->p_flags; + // stack_flags = ph->p_flags; break; case PT_GNU_RELRO: @@ -265,7 +251,7 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, /* Length of the sections to be loaded. */ maplength = loadcmds[nloadcmds - 1].allocend - c->mapstart; -#define APPEND_WRITECOPY(prot) ((prot)|PAL_PROT_WRITECOPY) +#define APPEND_WRITECOPY(prot) ((prot) | PAL_PROT_WRITECOPY) if (e_type == ET_DYN) { /* This is a position-independent shared object. Graphene allows @@ -276,17 +262,16 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, * addresses across forks: simply use a predefined base address. */ void* mapaddr = type == OBJECT_EXEC ? DEFAULT_OBJECT_EXEC_ADDR : NULL; - ret = _DkStreamMap(handle, (void **) &mapaddr, - APPEND_WRITECOPY(c->prot), c->mapoff, maplength); + ret = _DkStreamMap(handle, (void**)&mapaddr, APPEND_WRITECOPY(c->prot), c->mapoff, + maplength); if (ret < 0) { - print_error("failed to map dynamic segment from shared object", - ret); + print_error("failed to map dynamic segment from shared object", ret); return NULL; } - l->l_map_start = (ElfW(Addr)) mapaddr; - l->l_map_end = (ElfW(Addr)) mapaddr + maplength; - l->l_addr = l->l_map_start - c->mapstart; + l->l_map_start = (ElfW(Addr))mapaddr; + l->l_map_end = (ElfW(Addr))mapaddr + maplength; + l->l_addr = l->l_map_start - c->mapstart; if (has_holes) /* Change protection on the excess portion to disallow all access; @@ -294,36 +279,35 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, unallocated. Then jump into the normal segment-mapping loop to handle the portion of the segment past the end of the file mapping. */ - _DkVirtualMemoryProtect((void *) (l->l_addr + c->mapend), - loadcmds[nloadcmds - 1].mapstart - c->mapend, - PAL_PROT_NONE); + _DkVirtualMemoryProtect((void*)(l->l_addr + c->mapend), + loadcmds[nloadcmds - 1].mapstart - c->mapend, PAL_PROT_NONE); goto postmap; } /* Remember which part of the address space this object uses. */ l->l_map_start = c->mapstart + l->l_addr; - l->l_map_end = l->l_map_start + maplength; + l->l_map_end = l->l_map_start + maplength; while (c < &loadcmds[nloadcmds]) { if (c->mapend > c->mapstart) { /* Map the segment contents from the file. */ - void * mapaddr = (void *) (l->l_addr + c->mapstart); + void* mapaddr = (void*)(l->l_addr + c->mapstart); - if ((ret = _DkStreamMap(handle, &mapaddr, APPEND_WRITECOPY(c->prot), - c->mapoff, c->mapend - c->mapstart)) < 0) { + if ((ret = _DkStreamMap(handle, &mapaddr, APPEND_WRITECOPY(c->prot), c->mapoff, + c->mapend - c->mapstart)) < 0) { print_error("failed to map segment from shared object", ret); return NULL; } } -postmap: + postmap: if (l->l_phdr == 0 - && (ElfW(Off)) c->mapoff <= header->e_phoff + && (ElfW(Off))c->mapoff <= header->e_phoff && ((c->mapend - c->mapstart + c->mapoff) - >= header->e_phoff + header->e_phnum * sizeof (ElfW(Phdr)))) + >= header->e_phoff + header->e_phnum * sizeof(ElfW(Phdr)))) /* Found the program header in this segment. */ - l->l_phdr = (void *) (c->mapstart + header->e_phoff - c->mapoff); + l->l_phdr = (void*)(c->mapstart + header->e_phoff - c->mapoff); if (c->allocend > c->dataend) { /* Extra zero pages should appear at the end of this segment, @@ -341,28 +325,26 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, if (zerosec > zero) { /* Zero the final part of the last section of the segment. */ - if ((c->prot & PAL_PROT_WRITE) == 0) - { + if ((c->prot & PAL_PROT_WRITE) == 0) { /* Dag nab it. */ - ret = _DkVirtualMemoryProtect( - (void*)ALLOC_ALIGN_DOWN(zero), g_pal_state.alloc_align, - c->prot | PAL_PROT_WRITE); + ret = + _DkVirtualMemoryProtect((void*)ALLOC_ALIGN_DOWN(zero), + g_pal_state.alloc_align, c->prot | PAL_PROT_WRITE); if (ret < 0) { print_error("cannot change memory protections", ret); return NULL; } } - memset ((void *) zero, '\0', zerosec - zero); + memset((void*)zero, '\0', zerosec - zero); if ((c->prot & PAL_PROT_WRITE) == 0) - _DkVirtualMemoryProtect((void*)ALLOC_ALIGN_DOWN(zero), - g_pal_state.alloc_align, c->prot); + _DkVirtualMemoryProtect((void*)ALLOC_ALIGN_DOWN(zero), g_pal_state.alloc_align, + c->prot); } if (zeroend > zerosec) { /* Map the remaining zero pages in from the zero fill FD. */ - void * mapat = (void *) zerosec; - ret = _DkVirtualMemoryAlloc(&mapat, zeroend - zerosec, - 0, c->prot); + void* mapat = (void*)zerosec; + ret = _DkVirtualMemoryAlloc(&mapat, zeroend - zerosec, 0, c->prot); if (ret < 0) { print_error("cannot map zero-fill allocation", ret); return NULL; @@ -375,13 +357,11 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, if (l->l_ld == 0) { if (e_type == ET_DYN) { - print_error("object file has no dynamic section", - -PAL_ERROR_INVAL); + print_error("object file has no dynamic section", -PAL_ERROR_INVAL); return NULL; } } else { - l->l_real_ld = l->l_ld = - (ElfW(Dyn) *) ((ElfW(Addr)) l->l_ld + l->l_addr); + l->l_real_ld = l->l_ld = (ElfW(Dyn)*)((ElfW(Addr))l->l_ld + l->l_addr); if (do_copy_dyn) l->l_ld = malloc_copy(l->l_ld, sizeof(ElfW(Dyn)) * l->l_ldnum); @@ -393,25 +373,22 @@ map_elf_object_by_handle (PAL_HANDLE handle, enum object_type type, /* The program header is not contained in any of the segments. We have to allocate memory ourself and copy it over from out temporary place. */ - ElfW(Phdr) * newp = (ElfW(Phdr) *) malloc (header->e_phnum - * sizeof (ElfW(Phdr))); + ElfW(Phdr)* newp = (ElfW(Phdr)*)malloc(header->e_phnum * sizeof(ElfW(Phdr))); if (!newp) { - print_error("cannot allocate memory for program header", - -PAL_ERROR_NOMEM); + print_error("cannot allocate memory for program header", -PAL_ERROR_NOMEM); return NULL; } - l->l_phdr = memcpy(newp, phdr, - header->e_phnum * sizeof (ElfW(Phdr))); + l->l_phdr = memcpy(newp, phdr, header->e_phnum * sizeof(ElfW(Phdr))); } else { /* Adjust the PT_PHDR value by the runtime load address. */ - l->l_phdr = (ElfW(Phdr) *) ((ElfW(Addr)) l->l_phdr + l->l_addr); + l->l_phdr = (ElfW(Phdr)*)((ElfW(Addr))l->l_phdr + l->l_addr); } l->l_entry += l->l_addr; /* Set up the symbol hash table. */ - setup_elf_hash (l); + setup_elf_hash(l); return l; } @@ -429,10 +406,8 @@ bool is_elf_object(PAL_HANDLE handle) { return has_elf_magic(buffer, len); } -void free_elf_object (struct link_map * map) -{ - _DkVirtualMemoryFree((void *) map->l_map_start, - map->l_map_end - map->l_map_start); +void free_elf_object(struct link_map* map) { + _DkVirtualMemoryFree((void*)map->l_map_start, map->l_map_end - map->l_map_start); if (map->l_prev) map->l_prev->l_next = map->l_next; @@ -450,12 +425,10 @@ void free_elf_object (struct link_map * map) } /* Map in the shared object file loaded from URI. */ -int load_elf_object (const char * uri, enum object_type type) -{ +int load_elf_object(const char* uri, enum object_type type) { PAL_HANDLE handle; /* First we open the file by uri, as the regular file handles */ - int ret = _DkStreamOpen(&handle, uri, PAL_ACCESS_RDONLY, - 0, 0, 0); + int ret = _DkStreamOpen(&handle, uri, PAL_ACCESS_RDONLY, 0, 0, 0); if (ret < 0) return ret; @@ -465,35 +438,34 @@ int load_elf_object (const char * uri, enum object_type type) return ret; } -int add_elf_object(void * addr, PAL_HANDLE handle, int type) -{ +int add_elf_object(void* addr, PAL_HANDLE handle, int type) { if (!addr) return -PAL_ERROR_INVAL; - struct link_map * map = new_elf_object(_DkStreamRealpath(handle), type); + struct link_map* map = new_elf_object(_DkStreamRealpath(handle), type); if (!map) return -PAL_ERROR_NOMEM; - const ElfW(Ehdr) * header = (void *) addr; - const ElfW(Phdr) * ph, * phdr = - (ElfW(Phdr) *) ((char *) addr + header->e_phoff); + const ElfW(Ehdr)* header = (void*)addr; + const ElfW(Phdr)* ph; + const ElfW(Phdr)* phdr = (ElfW(Phdr)*)((char*)addr + header->e_phoff); - map->l_phdr = (void *) header->e_phoff; + map->l_phdr = (void*)header->e_phoff; map->l_phnum = header->e_phnum; - ElfW(Addr) mapstart = ~0; /* start with the highest possible address */ - ElfW(Addr) mapend = 0; /* start with the lowest possible address */ + ElfW(Addr) mapstart = ~0; /* start with the highest possible address */ + ElfW(Addr) mapend = 0; /* start with the lowest possible address */ - for (ph = phdr; ph < &phdr[map->l_phnum]; ++ph) + for (ph = phdr; ph < &phdr[map->l_phnum]; ph++) switch (ph->p_type) { case PT_DYNAMIC: - map->l_ld = (void *) ph->p_vaddr; - map->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn)); + map->l_ld = (void*)ph->p_vaddr; + map->l_ldnum = ph->p_memsz / sizeof(ElfW(Dyn)); break; case PT_LOAD: { ElfW(Addr) start = (ElfW(Addr))ALLOC_ALIGN_DOWN(map->l_addr + ph->p_vaddr); - ElfW(Addr) end = (ElfW(Addr)) - ALLOC_ALIGN_UP(map->l_addr + ph->p_vaddr + ph->p_memsz); + ElfW(Addr) end = + (ElfW(Addr))ALLOC_ALIGN_UP(map->l_addr + ph->p_vaddr + ph->p_memsz); if (start < mapstart) mapstart = start; if (end > mapend) @@ -501,14 +473,13 @@ int add_elf_object(void * addr, PAL_HANDLE handle, int type) } } - map->l_addr = (ElfW(Addr)) addr - mapstart; - map->l_entry = header->e_entry; - map->l_map_start = (ElfW(Addr)) addr; - map->l_map_end = (ElfW(Addr)) addr + (mapend - mapstart); + map->l_addr = (ElfW(Addr))addr - mapstart; + map->l_entry = header->e_entry; + map->l_map_start = (ElfW(Addr))addr; + map->l_map_end = (ElfW(Addr))addr + (mapend - mapstart); - map->l_real_ld = (ElfW(Dyn) *) - ((char *) map->l_addr + (unsigned long) map->l_ld); - map->l_ld = malloc_copy(map->l_real_ld, sizeof(ElfW(Dyn)) * map->l_ldnum); + map->l_real_ld = (ElfW(Dyn)*)((char*)map->l_addr + (unsigned long)map->l_ld); + map->l_ld = malloc_copy(map->l_real_ld, sizeof(ElfW(Dyn)) * map->l_ldnum); elf_get_dynamic_info(map->l_ld, map->l_info, map->l_addr); setup_elf_hash(map); @@ -539,18 +510,18 @@ int add_elf_object(void * addr, PAL_HANDLE handle, int type) return 0; } -static int relocate_elf_object (struct link_map *l); +static int relocate_elf_object(struct link_map* l); -int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type) -{ - struct link_map * map = NULL; - char fb[FILEBUF_SIZE], * errstring; +int load_elf_object_by_handle(PAL_HANDLE handle, enum object_type type) { + struct link_map* map = NULL; + char fb[FILEBUF_SIZE]; + char* errstring; int ret = 0; /* Now we will start verify the file as a ELF header. This part of code is borrow from open_verify() */ - ElfW(Ehdr) * ehdr = (ElfW(Ehdr) *) &fb; - ElfW(Phdr) * phdr = NULL; + ElfW(Ehdr)* ehdr = (ElfW(Ehdr)*)&fb; + ElfW(Phdr)* phdr = NULL; int phdr_malloced = 0; int len = _DkStreamRead(handle, 0, FILEBUF_SIZE, &fb, NULL, 0); @@ -567,8 +538,7 @@ int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type) #define ELF32_CLASS ELFCLASS32 #define ELF64_CLASS ELFCLASS64 - static const unsigned char expected[EI_NIDENT] = - { + static const unsigned char expected[EI_NIDENT] = { [EI_MAG0] = ELFMAG0, [EI_MAG1] = ELFMAG1, [EI_MAG2] = ELFMAG2, @@ -579,7 +549,7 @@ int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type) [EI_OSABI] = 0, }; -#define ELFOSABI_LINUX 3 /* Linux. */ +#define ELFOSABI_LINUX 3 /* Linux. */ /* See whether the ELF header is what we expect. */ if (memcmp(ehdr->e_ident, expected, EI_OSABI) != 0 || ( @@ -593,14 +563,14 @@ int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type) /* Chia-Che 11/23/13: Removing other checks, comparing the header should be enough */ - size_t maplength = ehdr->e_phnum * sizeof (ElfW(Phdr)); + size_t maplength = ehdr->e_phnum * sizeof(ElfW(Phdr)); /* if e_phoff + maplength is smaller than the data read */ - if (ehdr->e_phoff + maplength <= (size_t) len) { - phdr = (void *) (&fb + ehdr->e_phoff); + if (ehdr->e_phoff + maplength <= (size_t)len) { + phdr = (void*)(&fb + ehdr->e_phoff); } else { /* ...otherwise, we have to read again */ - phdr = malloc (maplength); + phdr = malloc(maplength); phdr_malloced = 1; ret = _DkStreamRead(handle, ehdr->e_phoff, maplength, phdr, NULL, 0); @@ -654,16 +624,15 @@ int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type) } struct sym_val { - ElfW(Sym) *s; - struct link_map *m; + ElfW(Sym)* s; + struct link_map* m; }; /* This is the hashing function specified by the ELF ABI. In the first five operations no overflow is possible so we optimized it a bit. */ -unsigned long int elf_hash (const char *name_arg) -{ - const unsigned char *name = (const unsigned char *) name_arg; +unsigned long int elf_hash(const char* name_arg) { + const unsigned char* name = (const unsigned char*)name_arg; unsigned long int hash = 0; if (*name == '\0') @@ -708,9 +677,8 @@ unsigned long int elf_hash (const char *name_arg) /* Nested routine to check whether the symbol matches. */ static inline __attribute_always_inline -ElfW(Sym) * check_match(ElfW(Sym) * sym, ElfW(Sym) * ref, const char * undef_name, - const char * strtab) -{ +ElfW(Sym)* check_match(ElfW(Sym)* sym, ElfW(Sym)* ref, const char* undef_name, + const char* strtab) { unsigned int stt = ELFW(ST_TYPE) (sym->st_info); static_assert(ELF_RTYPE_CLASS_PLT == 1, "ELF_RTYPE_CLASS_PLT != 1 is not supported"); @@ -720,15 +688,14 @@ ElfW(Sym) * check_match(ElfW(Sym) * sym, ElfW(Sym) * ref, const char * undef_nam /* Ignore all but STT_NOTYPE, STT_OBJECT, STT_FUNC, STT_COMMON, STT_TLS, and STT_GNU_IFUNC since these are no code/data definitions. */ -#define ALLOWED_STT \ - ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) \ - | (1 << STT_COMMON) | (1 << STT_TLS) | (1 << STT_GNU_IFUNC)) + #define ALLOWED_STT \ + ((1 << STT_NOTYPE) | (1 << STT_OBJECT) | (1 << STT_FUNC) | (1 << STT_COMMON) | \ + (1 << STT_TLS) | (1 << STT_GNU_IFUNC)) if (((1 << stt) & ALLOWED_STT) == 0) return NULL; - if (sym != ref && memcmp(strtab + sym->st_name, undef_name, - strlen(undef_name))) + if (sym != ref && memcmp(strtab + sym->st_name, undef_name, strlen(undef_name))) /* Not the symbol we are looking for. */ return NULL; @@ -736,39 +703,32 @@ ElfW(Sym) * check_match(ElfW(Sym) * sym, ElfW(Sym) * ref, const char * undef_nam return sym; } - -ElfW(Sym) * -do_lookup_map (ElfW(Sym) * ref, const char * undef_name, - const uint_fast32_t hash, unsigned long int elf_hash, - const struct link_map * map) -{ +ElfW(Sym)* do_lookup_map(ElfW(Sym)* ref, const char* undef_name, const uint_fast32_t hash, + unsigned long int elf_hash, const struct link_map* map) { /* These variables are used in the nested function. */ Elf_Symndx symidx; - ElfW(Sym) * sym; + ElfW(Sym)* sym; /* The tables for this map. */ - ElfW(Sym) * symtab = (void *) D_PTR (map->l_info[DT_SYMTAB]); - const char * strtab = (const void *) D_PTR (map->l_info[DT_STRTAB]); - const ElfW(Addr) * bitmask = map->l_gnu_bitmask; + ElfW(Sym)* symtab = (void*)D_PTR(map->l_info[DT_SYMTAB]); + const char* strtab = (const void*)D_PTR(map->l_info[DT_STRTAB]); + const ElfW(Addr)* bitmask = map->l_gnu_bitmask; if (bitmask != NULL) { - ElfW(Addr) bitmask_word = bitmask[(hash / __ELF_NATIVE_CLASS) - & map->l_gnu_bitmask_idxbits]; + ElfW(Addr) bitmask_word = bitmask[(hash / __ELF_NATIVE_CLASS) & map->l_gnu_bitmask_idxbits]; unsigned int hashbit1 = hash & (__ELF_NATIVE_CLASS - 1); - unsigned int hashbit2 = (hash >> map->l_gnu_shift) - & (__ELF_NATIVE_CLASS - 1); + unsigned int hashbit2 = (hash >> map->l_gnu_shift) & (__ELF_NATIVE_CLASS - 1); if ((bitmask_word >> hashbit1) & (bitmask_word >> hashbit2) & 1) { - Elf32_Word bucket = map->l_gnu_buckets - [hash % map->l_nbuckets]; + Elf32_Word bucket = map->l_gnu_buckets[hash % map->l_nbuckets]; if (bucket != 0) { - const Elf32_Word *hasharr = &map->l_gnu_chain_zero[bucket]; + const Elf32_Word* hasharr = &map->l_gnu_chain_zero[bucket]; do if (((*hasharr ^ hash) >> 1) == 0) { symidx = hasharr - map->l_gnu_chain_zero; - sym = check_match (&symtab[symidx], ref, undef_name, strtab); + sym = check_match(&symtab[symidx], ref, undef_name, strtab); if (sym != NULL) return sym; } @@ -782,10 +742,9 @@ do_lookup_map (ElfW(Sym) * ref, const char * undef_name, /* Use the old SysV-style hash table. Search the appropriate hash bucket in this object's symbol table for a definition for the same symbol name. */ - for (symidx = map->l_buckets[elf_hash % map->l_nbuckets]; - symidx != STN_UNDEF; + for (symidx = map->l_buckets[elf_hash % map->l_nbuckets]; symidx != STN_UNDEF; symidx = map->l_chain[symidx]) { - sym = check_match (&symtab[symidx], ref, undef_name, strtab); + sym = check_match(&symtab[symidx], ref, undef_name, strtab); if (sym != NULL) return sym; } @@ -797,16 +756,14 @@ do_lookup_map (ElfW(Sym) * ref, const char * undef_name, /* Inner part of the lookup functions. We return a value > 0 if we found the symbol, the value 0 if nothing is found and < 0 if something bad happened. */ -static int do_lookup (const char * undef_name, ElfW(Sym) * ref, - struct sym_val * result) -{ +static int do_lookup(const char* undef_name, ElfW(Sym)* ref, struct sym_val* result) { const uint_fast32_t fast_hash = elf_fast_hash(undef_name); const long int hash = elf_hash(undef_name); - ElfW(Sym) * sym; + ElfW(Sym)* sym; struct link_map* map = g_loaded_maps; - struct sym_val weak_result = { .s = NULL, .m = NULL }; + struct sym_val weak_result = {.s = NULL, .m = NULL}; - for (; map ; map = map->l_next) { + for (; map; map = map->l_next) { sym = do_lookup_map(ref, undef_name, fast_hash, hash, map); if (!sym) continue; @@ -816,7 +773,7 @@ static int do_lookup (const char * undef_name, ElfW(Sym) * ref, /* Weak definition. Use this value if we don't find another. */ if (!weak_result.s) { weak_result.s = sym; - weak_result.m = (struct link_map *) map; + weak_result.m = (struct link_map*)map; } break; /* FALLTHROUGH */ @@ -825,7 +782,7 @@ static int do_lookup (const char * undef_name, ElfW(Sym) * ref, /* success: */ /* Global definition. Just what we need. */ result->s = sym; - result->m = (struct link_map *) map; + result->m = (struct link_map*)map; return 1; default: /* Local symbols are ignored. */ @@ -848,9 +805,8 @@ static int do_lookup (const char * undef_name, ElfW(Sym) * ref, We must never have calls to the audit functions inside this function or in any function which gets called. If this would happen the audit code might create a thread which can throw off all the scope locking. */ -struct link_map * lookup_symbol (const char * undef_name, ElfW(Sym) ** ref) -{ - struct sym_val current_value = { NULL, NULL }; +struct link_map* lookup_symbol(const char* undef_name, ElfW(Sym)** ref) { + struct sym_val current_value = {NULL, NULL}; do_lookup(undef_name, *ref, ¤t_value); @@ -863,37 +819,32 @@ struct link_map * lookup_symbol (const char * undef_name, ElfW(Sym) ** ref) return current_value.m; } -static int protect_relro (struct link_map * l) -{ +static int protect_relro(struct link_map* l) { ElfW(Addr) start = ALLOC_ALIGN_DOWN(l->l_addr + l->l_relro_addr); - ElfW(Addr) end = ALLOC_ALIGN_UP(l->l_addr + l->l_relro_addr + - l->l_relro_size); + ElfW(Addr) end = ALLOC_ALIGN_UP(l->l_addr + l->l_relro_addr + l->l_relro_size); if (start != end) - _DkVirtualMemoryProtect((void *) start, end - start, PAL_PROT_READ); + _DkVirtualMemoryProtect((void*)start, end - start, PAL_PROT_READ); return 0; } -static int relocate_elf_object (struct link_map * l) -{ - struct textrels { +static int relocate_elf_object(struct link_map* l) { + struct textrels { ElfW(Addr) start; ElfW(Addr) len; int prot; - struct textrels * next; - } * textrels = NULL; + struct textrels* next; + }* textrels = NULL; int ret; - const ElfW(Phdr) * ph; + const ElfW(Phdr)* ph; - for (ph = l->l_phdr ; ph < &l->l_phdr[l->l_phnum] ; ph++) + for (ph = l->l_phdr; ph < &l->l_phdr[l->l_phnum]; ph++) if (ph->p_type == PT_LOAD && (ph->p_flags & PF_W) == 0) { - struct textrels * r = malloc(sizeof(struct textrels)); + struct textrels* r = malloc(sizeof(struct textrels)); r->start = ALLOC_ALIGN_DOWN(ph->p_vaddr) + l->l_addr; - r->len = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_memsz) - - ALLOC_ALIGN_DOWN(ph->p_vaddr); + r->len = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_memsz) - ALLOC_ALIGN_DOWN(ph->p_vaddr); - ret = _DkVirtualMemoryProtect((void *) r->start, r->len, - PAL_PROT_READ|PAL_PROT_WRITE); + ret = _DkVirtualMemoryProtect((void*)r->start, r->len, PAL_PROT_READ | PAL_PROT_WRITE); if (ret < 0) return ret; @@ -912,12 +863,11 @@ static int relocate_elf_object (struct link_map * l) ELF_DYNAMIC_RELOCATE(l); while (textrels) { - ret = _DkVirtualMemoryProtect((void *) textrels->start, textrels->len, - textrels->prot); + ret = _DkVirtualMemoryProtect((void*)textrels->start, textrels->len, textrels->prot); if (ret < 0) return ret; - struct textrels * next = textrels->next; + struct textrels* next = textrels->next; free(textrels); textrels = next; } @@ -931,8 +881,7 @@ static int relocate_elf_object (struct link_map * l) return 0; } -void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr) -{ +void DkDebugAttachBinary(PAL_STR uri, PAL_PTR start_addr) { #ifndef DEBUG __UNUSED(uri); __UNUSED(start_addr); @@ -940,20 +889,20 @@ void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr) if (!strstartswith_static(uri, URI_PREFIX_FILE) || !start_addr) return; - const char * realname = uri + URI_PREFIX_FILE_LEN; - struct link_map * l = new_elf_object(realname, OBJECT_EXTERNAL); + const char* realname = uri + URI_PREFIX_FILE_LEN; + struct link_map* l = new_elf_object(realname, OBJECT_EXTERNAL); if (!l) return; /* This is the ELF header. We read it in `open_verify'. */ - const ElfW(Ehdr) * header = (ElfW(Ehdr) *) start_addr; + const ElfW(Ehdr)* header = (ElfW(Ehdr)*)start_addr; - l->l_entry = header->e_entry; - l->l_phnum = header->e_phnum; - l->l_map_start = (ElfW(Addr)) start_addr; + l->l_entry = header->e_entry; + l->l_phnum = header->e_phnum; + l->l_map_start = (ElfW(Addr))start_addr; - ElfW(Phdr) * phdr = (void *) ((char *) start_addr + header->e_phoff); - const ElfW(Phdr) * ph; + ElfW(Phdr)* phdr = (void*)((char*)start_addr + header->e_phoff); + const ElfW(Phdr)* ph; ElfW(Addr) map_start = 0, map_end = 0; for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph) @@ -964,7 +913,7 @@ void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr) map_end = ph->p_vaddr + ph->p_memsz; } - l->l_addr = l->l_map_start - map_start; + l->l_addr = l->l_map_start - map_start; l->l_map_end = l->l_addr + map_end; for (ph = phdr; ph < &phdr[l->l_phnum]; ++ph) @@ -973,13 +922,12 @@ void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr) segments are mapped in. We record the addresses it says verbatim, and later correct for the run-time load address. */ case PT_DYNAMIC: - l->l_ld = l->l_real_ld = (ElfW(Dyn) *) - ((char *) l->l_addr + ph->p_vaddr); - l->l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn)); + l->l_ld = l->l_real_ld = (ElfW(Dyn)*)((char*)l->l_addr + ph->p_vaddr); + l->l_ldnum = ph->p_memsz / sizeof(ElfW(Dyn)); break; case PT_PHDR: - l->l_phdr = (ElfW(Phdr) *) ((char *) l->l_addr + ph->p_vaddr); + l->l_phdr = (ElfW(Phdr)*)((char*)l->l_addr + ph->p_vaddr); break; case PT_GNU_RELRO: @@ -993,13 +941,12 @@ void DkDebugAttachBinary (PAL_STR uri, PAL_PTR start_addr) #endif } -void DkDebugDetachBinary (PAL_PTR start_addr) -{ +void DkDebugDetachBinary(PAL_PTR start_addr) { #ifndef DEBUG __UNUSED(start_addr); #else for (struct link_map* l = g_loaded_maps; l; l = l->l_next) - if (l->l_map_start == (ElfW(Addr)) start_addr) { + if (l->l_map_start == (ElfW(Addr))start_addr) { _DkDebugDelMap(l); if (l->l_type == OBJECT_EXTERNAL) @@ -1011,25 +958,27 @@ void DkDebugDetachBinary (PAL_PTR start_addr) #ifndef CALL_ENTRY #ifdef __x86_64__ -void * stack_before_call __attribute_unused = NULL; - -#define CALL_ENTRY(l, cookies) \ - ({ long ret; \ - __asm__ volatile( \ - "pushq $0\r\n" \ - "popfq\r\n" \ - "movq %%rsp, stack_before_call(%%rip)\r\n" \ - "leaq 1f(%%rip), %%rdx\r\n" \ - "movq %2, %%rsp\r\n" \ - "jmp *%1\r\n" \ - "1: movq stack_before_call(%%rip), %%rsp\r\n" \ - \ - : "=a"(ret) : "a"((l)->l_entry), "b"(cookies) \ - : "rcx", "rdx", "rdi", "rsi", "r8", "r9", \ - "r10", "r11", "memory", "cc"); \ - ret; }) +void* stack_before_call __attribute_unused = NULL; + +#define CALL_ENTRY(l, cookies) \ + ({ \ + long ret; \ + __asm__ volatile( \ + "pushq $0\r\n" \ + "popfq\r\n" \ + "movq %%rsp, stack_before_call(%%rip)\r\n" \ + "leaq 1f(%%rip), %%rdx\r\n" \ + "movq %2, %%rsp\r\n" \ + "jmp *%1\r\n" \ + "1: movq stack_before_call(%%rip), %%rsp\r\n" \ + \ + : "=a"(ret) \ + : "a"((l)->l_entry), "b"(cookies) \ + : "rcx", "rdx", "rdi", "rsi", "r8", "r9", "r10", "r11", "memory", "cc"); \ + ret; \ + }) #else -# error "unsupported architecture" +#error "unsupported architecture" #endif #endif /* !CALL_ENTRY */ @@ -1042,7 +991,8 @@ noreturn void start_execution(const char** arguments, const char** environs) { } int narguments = 0; - for (const char** a = arguments; *a ; a++, narguments++); + for (const char** a = arguments; *a; a++, narguments++) + ; /* Let's count the number of cookies, first we will have argc & argv */ int ncookies = narguments + 3; /* 1 for argc, argc + 2 for argv */ @@ -1055,26 +1005,26 @@ noreturn void start_execution(const char** arguments, const char** environs) { int cookiesz = sizeof(unsigned long int) * ncookies + sizeof(ElfW(auxv_t)) * 1 /* only AT_NULL */ - + sizeof(void *) * 4 + 16; + + sizeof(void*) * 4 + 16; unsigned long int* cookies = __alloca(cookiesz); int cnt = 0; /* Let's copy the cookies */ - cookies[cnt++] = (unsigned long int) narguments; + cookies[cnt++] = (unsigned long int)narguments; - for (int i = 0 ; arguments[i] ; i++) - cookies[cnt++] = (unsigned long int) arguments[i]; + for (int i = 0; arguments[i]; i++) + cookies[cnt++] = (unsigned long int)arguments[i]; cookies[cnt++] = 0; - for (int i = 0 ; environs[i]; i++) - cookies[cnt++] = (unsigned long int) environs[i]; + for (int i = 0; environs[i]; i++) + cookies[cnt++] = (unsigned long int)environs[i]; cookies[cnt++] = 0; /* NOTE: LibOS implements its own ELF aux vectors. Any info from host's * aux vectors must be passed in PAL_CONTROL. Here we pass an empty list * of aux vectors for sanity. */ - ElfW(auxv_t) * auxv = (ElfW(auxv_t) *) &cookies[cnt]; - auxv[0].a_type = AT_NULL; + ElfW(auxv_t)* auxv = (ElfW(auxv_t)*)&cookies[cnt]; + auxv[0].a_type = AT_NULL; auxv[0].a_un.a_val = 0; for (struct link_map* l = g_loaded_maps; l; l = l->l_next) diff --git a/Pal/src/db_threading.c b/Pal/src/db_threading.c index c2d12247d3..2369de300c 100644 --- a/Pal/src/db_threading.c +++ b/Pal/src/db_threading.c @@ -21,7 +21,7 @@ DkThreadCreate(PAL_PTR addr, PAL_PTR param) { ENTER_PAL_CALL(DkThreadCreate); PAL_HANDLE handle = NULL; - int ret = _DkThreadCreate(&handle, (int (*)(void*))addr, (const void*)param); + int ret = _DkThreadCreate(&handle, (int (*)(void*))addr, (const void*)param); if (ret < 0) { _DkRaiseFailure(-ret); @@ -38,7 +38,7 @@ DkThreadDelayExecution(PAL_NUM duration) { ENTER_PAL_CALL(DkThreadDelayExecution); unsigned long dur = duration; - int ret = _DkThreadDelayExecution(&dur); + int ret = _DkThreadDelayExecution(&dur); if (ret < 0) { _DkRaiseFailure(PAL_ERROR_INTERRUPTED); diff --git a/Pal/src/do-rel.h b/Pal/src/do-rel.h index 513cd51542..80ce1ac12c 100644 --- a/Pal/src/do-rel.h +++ b/Pal/src/do-rel.h @@ -9,9 +9,8 @@ * The source code is imported and modified from the GNU C Library. */ -#include - #include "dl-machine.h" +#include "pal_rtld.h" #define elf_dynamic_do_rel elf_dynamic_do_rela #define RELCOUNT_IDX VERSYMIDX(DT_RELACOUNT) diff --git a/Pal/src/dynamic_link.h b/Pal/src/dynamic_link.h index 7966464f5a..0c7478a671 100644 --- a/Pal/src/dynamic_link.h +++ b/Pal/src/dynamic_link.h @@ -8,10 +8,10 @@ * The source code is imported and modified from the GNU C Library. */ -#include -#include -#include -#include +#include "dl-machine.h" +#include "elf/elf.h" +#include "pal_internal.h" +#include "pal_rtld.h" /* We pass reloc_addr as a pointer to void, as opposed to a pointer to ElfW(Addr), because not all architectures can assume that the diff --git a/Pal/src/host/Linux-SGX/db_devices.c b/Pal/src/host/Linux-SGX/db_devices.c index 929d5e9bf2..bc649dba8b 100644 --- a/Pal/src/host/Linux-SGX/db_devices.c +++ b/Pal/src/host/Linux-SGX/db_devices.c @@ -214,8 +214,8 @@ static int dev_open(PAL_HANDLE* handle, const char* type, const char* uri, int a return -PAL_ERROR_INVAL; struct handle_ops* ops = NULL; - char* dev_type = NULL; - int ret = 0; + char* dev_type = NULL; + int ret = 0; ret = parse_device_uri(&uri, &dev_type, &ops); @@ -323,8 +323,8 @@ static int dev_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* att return -PAL_ERROR_INVAL; struct handle_ops* ops = NULL; - char* dev_type = NULL; - int ret = 0; + char* dev_type = NULL; + int ret = 0; ret = parse_device_uri(&uri, &dev_type, &ops); diff --git a/Pal/src/host/Linux-SGX/db_events.c b/Pal/src/host/Linux-SGX/db_events.c index 95722a8c44..7f479c0fa2 100644 --- a/Pal/src/host/Linux-SGX/db_events.c +++ b/Pal/src/host/Linux-SGX/db_events.c @@ -7,11 +7,11 @@ * This file contains implementation of Drawbridge event synchronization APIs. */ -#include #include #include #include "api.h" +#include "atomic.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" @@ -73,9 +73,7 @@ int _DkEventWaitTimeout(PAL_HANDLE event, int64_t timeout_us) { if (timeout_us < 0) return _DkEventWait(event); - if (!event->event.isnotification || - !__atomic_load_n(event->event.signaled, __ATOMIC_SEQ_CST)) { - + if (!event->event.isnotification || !__atomic_load_n(event->event.signaled, __ATOMIC_SEQ_CST)) { __atomic_add_fetch(&event->event.nwaiters.counter, 1, __ATOMIC_SEQ_CST); do { @@ -101,9 +99,7 @@ int _DkEventWaitTimeout(PAL_HANDLE event, int64_t timeout_us) { int _DkEventWait(PAL_HANDLE event) { int ret = 0; - if (!event->event.isnotification || - !__atomic_load_n(event->event.signaled, __ATOMIC_SEQ_CST)) { - + if (!event->event.isnotification || !__atomic_load_n(event->event.signaled, __ATOMIC_SEQ_CST)) { __atomic_add_fetch(&event->event.nwaiters.counter, 1, __ATOMIC_SEQ_CST); do { diff --git a/Pal/src/host/Linux-SGX/db_exception.c b/Pal/src/host/Linux-SGX/db_exception.c index 9aca85d34e..dd7570854f 100644 --- a/Pal/src/host/Linux-SGX/db_exception.c +++ b/Pal/src/host/Linux-SGX/db_exception.c @@ -9,6 +9,12 @@ * This file contains APIs to set up signal handlers. */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + +#include + #include "api.h" #include "cpu.h" #include "ecall_types.h" @@ -19,41 +25,38 @@ #include "pal_linux.h" #include "pal_linux_defs.h" #include "pal_security.h" - -#include -#include -#include +#include "sigset.h" +#include "ucontext.h" #define ADDR_IN_PAL(addr) ((void*)(addr) > TEXT_START && (void*)(addr) < TEXT_END) /* Restore an sgx_cpu_context_t as generated by .Lhandle_exception. Execution will * continue as specified by the rip in the context. */ -noreturn static void restore_sgx_context(sgx_cpu_context_t* uc, - PAL_XREGS_STATE* xregs_state) { +noreturn static void restore_sgx_context(sgx_cpu_context_t* uc, PAL_XREGS_STATE* xregs_state) { if (xregs_state == NULL) xregs_state = (PAL_XREGS_STATE*)g_xsave_reset_state; _restore_sgx_context(uc, xregs_state); } noreturn static void restore_pal_context(sgx_cpu_context_t* uc, PAL_CONTEXT* ctx) { - uc->rax = ctx->rax; - uc->rbx = ctx->rbx; - uc->rcx = ctx->rcx; - uc->rdx = ctx->rdx; - uc->rsp = ctx->rsp; - uc->rbp = ctx->rbp; - uc->rsi = ctx->rsi; - uc->rdi = ctx->rdi; - uc->r8 = ctx->r8; - uc->r9 = ctx->r9; - uc->r10 = ctx->r10; - uc->r11 = ctx->r11; - uc->r12 = ctx->r12; - uc->r13 = ctx->r13; - uc->r14 = ctx->r14; - uc->r15 = ctx->r15; + uc->rax = ctx->rax; + uc->rbx = ctx->rbx; + uc->rcx = ctx->rcx; + uc->rdx = ctx->rdx; + uc->rsp = ctx->rsp; + uc->rbp = ctx->rbp; + uc->rsi = ctx->rsi; + uc->rdi = ctx->rdi; + uc->r8 = ctx->r8; + uc->r9 = ctx->r9; + uc->r10 = ctx->r10; + uc->r11 = ctx->r11; + uc->r12 = ctx->r12; + uc->r13 = ctx->r13; + uc->r14 = ctx->r14; + uc->r15 = ctx->r15; uc->rflags = ctx->efl; - uc->rip = ctx->rip; + uc->rip = ctx->rip; restore_sgx_context(uc, ctx->fpregs); } @@ -96,9 +99,9 @@ static void save_pal_context(PAL_CONTEXT* ctx, sgx_cpu_context_t* uc, * https://elixir.bootlin.com/linux/v5.4.13/source/arch/x86/kernel/fpu/signal.c#L459 */ PAL_FPX_SW_BYTES* fpx_sw = &xregs_state->fpstate.sw_reserved; - fpx_sw->magic1 = PAL_FP_XSTATE_MAGIC1; + fpx_sw->magic1 = PAL_FP_XSTATE_MAGIC1; fpx_sw->extended_size = g_xsave_size; - fpx_sw->xfeatures = g_xsave_features; + fpx_sw->xfeatures = g_xsave_features; memset(fpx_sw->padding, 0, sizeof(fpx_sw->padding)); if (g_xsave_enabled) { fpx_sw->xstate_size = g_xsave_size + PAL_FP_XSTATE_MAGIC2_SIZE; @@ -147,7 +150,7 @@ static bool handle_ud(sgx_cpu_context_t* uc) { emulate_rdtsc_and_print_warning(uc); uc->rip += 2; return true; - } else if (instr[0] == 0x0f && instr[1] == 0x01 && instr[2] == 0xf9) { + } else if (instr[0] == 0x0f && instr[1] == 0x01 && instr[2] == 0xf9) { /* rdtscp */ emulate_rdtsc_and_print_warning(uc); uc->rip += 3; @@ -175,7 +178,7 @@ void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, union { sgx_arch_exit_info_t info; unsigned int intval; - } ei = { .intval = exit_info }; + } ei = {.intval = exit_info}; int event_num; @@ -183,29 +186,29 @@ void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, event_num = exit_info; } else { switch (ei.info.vector) { - case SGX_EXCEPTION_VECTOR_BR: - event_num = PAL_EVENT_NUM_BOUND; - break; - case SGX_EXCEPTION_VECTOR_UD: - if (handle_ud(uc)) { + case SGX_EXCEPTION_VECTOR_BR: + event_num = PAL_EVENT_NUM_BOUND; + break; + case SGX_EXCEPTION_VECTOR_UD: + if (handle_ud(uc)) { + restore_sgx_context(uc, xregs_state); + /* NOTREACHED */ + } + event_num = PAL_EVENT_ILLEGAL; + break; + case SGX_EXCEPTION_VECTOR_DE: + case SGX_EXCEPTION_VECTOR_MF: + case SGX_EXCEPTION_VECTOR_XM: + event_num = PAL_EVENT_ARITHMETIC_ERROR; + break; + case SGX_EXCEPTION_VECTOR_AC: + event_num = PAL_EVENT_MEMFAULT; + break; + case SGX_EXCEPTION_VECTOR_DB: + case SGX_EXCEPTION_VECTOR_BP: + default: restore_sgx_context(uc, xregs_state); /* NOTREACHED */ - } - event_num = PAL_EVENT_ILLEGAL; - break; - case SGX_EXCEPTION_VECTOR_DE: - case SGX_EXCEPTION_VECTOR_MF: - case SGX_EXCEPTION_VECTOR_XM: - event_num = PAL_EVENT_ARITHMETIC_ERROR; - break; - case SGX_EXCEPTION_VECTOR_AC: - event_num = PAL_EVENT_MEMFAULT; - break; - case SGX_EXCEPTION_VECTOR_DB: - case SGX_EXCEPTION_VECTOR_BP: - default: - restore_sgx_context(uc, xregs_state); - /* NOTREACHED */ } } @@ -219,8 +222,8 @@ void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, if (ei.info.valid) { /* EXITINFO field: vector = exception number, exit_type = 0x3 for HW / 0x6 for SW */ - printf("(SGX HW reported AEX vector 0x%x with exit_type = 0x%x)\n", - ei.info.vector, ei.info.exit_type); + printf("(SGX HW reported AEX vector 0x%x with exit_type = 0x%x)\n", ei.info.vector, + ei.info.exit_type); } else { printf("(untrusted PAL sent PAL event 0x%x)\n", ei.intval); } @@ -243,22 +246,22 @@ void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, save_pal_context(&ctx, uc, xregs_state); /* TODO: save EXINFO from MISC region and populate below fields */ - ctx.err = 0; - ctx.trapno = ei.info.valid ? ei.info.vector : event_num; + ctx.err = 0; + ctx.trapno = ei.info.valid ? ei.info.vector : event_num; ctx.oldmask = 0; - ctx.cr2 = 0; + ctx.cr2 = 0; PAL_NUM arg = 0; switch (event_num) { - case PAL_EVENT_ILLEGAL: - arg = uc->rip; - break; - case PAL_EVENT_MEMFAULT: - /* TODO: SGX1 doesn't provide fault address but SGX2 does (with lower bits masked) */ - break; - default: - /* nothing */ - break; + case PAL_EVENT_ILLEGAL: + arg = uc->rip; + break; + case PAL_EVENT_MEMFAULT: + /* TODO: SGX1 doesn't provide fault address but SGX2 does (with lower bits masked) */ + break; + default: + /* nothing */ + break; } PAL_EVENT_HANDLER upcall = _DkGetExceptionHandler(event_num); @@ -291,10 +294,10 @@ noreturn void _DkHandleExternalEvent(PAL_NUM event, sgx_cpu_context_t* uc, PAL_CONTEXT ctx; save_pal_context(&ctx, uc, xregs_state); - ctx.err = 0; - ctx.trapno = event; /* TODO: event is a PAL event; is that what LibOS/app wants to see? */ + ctx.err = 0; + ctx.trapno = event; /* TODO: event is a PAL event; is that what LibOS/app wants to see? */ ctx.oldmask = 0; - ctx.cr2 = 0; + ctx.cr2 = 0; PAL_EVENT_HANDLER upcall = _DkGetExceptionHandler(event); if (upcall) { diff --git a/Pal/src/host/Linux-SGX/db_files.c b/Pal/src/host/Linux-SGX/db_files.c index 56a76924b6..f9e3a9abfa 100644 --- a/Pal/src/host/Linux-SGX/db_files.c +++ b/Pal/src/host/Linux-SGX/db_files.c @@ -206,14 +206,14 @@ static int64_t file_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, voi map_end = ALLOC_ALIGN_UP(total); ret = copy_and_verify_trusted_file(handle->file.realpath, handle->file.umem + map_start, - map_start, map_end, buffer, offset, end - offset, stubs, total); + map_start, map_end, buffer, offset, end - offset, stubs, + total); if (ret < 0) return ret; return end - offset; } - static int64_t pf_file_write(struct protected_file* pf, PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer) { int fd = handle->file.fd; @@ -235,7 +235,7 @@ static int64_t pf_file_write(struct protected_file* pf, PAL_HANDLE handle, uint6 /* 'write' operation for file streams. */ static int64_t file_write(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer) { - struct protected_file *pf = find_protected_file_handle(handle); + struct protected_file* pf = find_protected_file_handle(handle); if (pf) return pf_file_write(pf, handle, offset, count, buffer); @@ -341,8 +341,8 @@ static int pf_file_map(struct protected_file* pf, PAL_HANDLE handle, void** addr __UNUSED(pfs); assert(PF_SUCCESS(pfs)); - SGX_DBG(DBG_D, "pf_file_map(PF fd %d): pf %p, addr %p, prot %d, offset %lu, size %lu\n", - fd, pf, *addr, prot, offset, size); + SGX_DBG(DBG_D, "pf_file_map(PF fd %d): pf %p, addr %p, prot %d, offset %lu, size %lu\n", fd, pf, + *addr, prot, offset, size); if (*addr == NULL) { /* LibOS didn't provide address at which to map, can happen on sendfile() */ @@ -373,8 +373,8 @@ static int pf_file_map(struct protected_file* pf, PAL_HANDLE handle, void** addr if (prot & PAL_PROT_READ) { /* we don't check this on writes since file size may be extended then */ if (offset >= pf_size) { - SGX_DBG(DBG_E, "pf_file_map(PF fd %d): offset (%lu) >= file size (%lu)\n", - fd, offset, pf_size); + SGX_DBG(DBG_E, "pf_file_map(PF fd %d): offset (%lu) >= file size (%lu)\n", fd, offset, + pf_size); ret = -PAL_ERROR_INVAL; goto out; } @@ -478,13 +478,13 @@ static int file_map(PAL_HANDLE handle, void** addr, int prot, uint64_t offset, u return 0; } -static int64_t pf_file_setlength(struct protected_file *pf, PAL_HANDLE handle, uint64_t length) { +static int64_t pf_file_setlength(struct protected_file* pf, PAL_HANDLE handle, uint64_t length) { int fd = handle->file.fd; pf_status_t pfs = pf_set_size(pf->context, length); if (PF_FAILURE(pfs)) { - SGX_DBG(DBG_E, "pf_file_setlength(PF fd %d, %lu): pf_set_size returned %d\n", - fd, length, pfs); + SGX_DBG(DBG_E, "pf_file_setlength(PF fd %d, %lu): pf_set_size returned %d\n", fd, length, + pfs); return -PAL_ERROR_DENIED; } return length; @@ -492,7 +492,7 @@ static int64_t pf_file_setlength(struct protected_file *pf, PAL_HANDLE handle, u /* 'setlength' operation for file stream. */ static int64_t file_setlength(PAL_HANDLE handle, uint64_t length) { - struct protected_file *pf = find_protected_file_handle(handle); + struct protected_file* pf = find_protected_file_handle(handle); if (pf) return pf_file_setlength(pf, handle, length); @@ -507,7 +507,7 @@ static int64_t file_setlength(PAL_HANDLE handle, uint64_t length) { /* 'flush' operation for file stream. */ static int file_flush(PAL_HANDLE handle) { int fd = handle->file.fd; - struct protected_file *pf = find_protected_file_handle(handle); + struct protected_file* pf = find_protected_file_handle(handle); if (pf) { int ret = flush_pf_maps(pf, /*buffer=*/NULL, /*remove=*/false); if (ret < 0) { @@ -590,8 +590,8 @@ static int file_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* at if (strcmp_static(type, URI_TYPE_FILE) && strcmp_static(type, URI_TYPE_DIR)) return -PAL_ERROR_INVAL; - /* open the file with O_NONBLOCK to avoid blocking the current thread if it is actually a FIFO pipe; - * O_NONBLOCK will be reset below if it is a regular file */ + /* open the file with O_NONBLOCK to avoid blocking the current thread if it is actually a FIFO + * pipe; O_NONBLOCK will be reset below if it is a regular file */ int fd = ocall_open(uri, O_NONBLOCK, 0); if (IS_ERR(fd)) return unix_to_pal_error(ERRNO(fd)); @@ -624,7 +624,8 @@ static int file_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* at goto out; } - /* reset O_NONBLOCK because pf_file_attrquery() may issue reads which don't expect non-blocking mode */ + /* reset O_NONBLOCK because pf_file_attrquery() may issue reads which don't expect + * non-blocking mode */ ret = ocall_fsetnonblock(fd, 0); if (IS_ERR(ret)) { ret = unix_to_pal_error(ERRNO(ret)); @@ -632,9 +633,9 @@ static int file_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* at } ret = pf_file_attrquery(pf, fd, path, stat_buf.st_size, attr); - } - else + } else { ret = 0; + } out: ocall_close(fd); diff --git a/Pal/src/host/Linux-SGX/db_main-x86_64.c b/Pal/src/host/Linux-SGX/db_main-x86_64.c index f106f76081..5cc798da12 100644 --- a/Pal/src/host/Linux-SGX/db_main-x86_64.c +++ b/Pal/src/host/Linux-SGX/db_main-x86_64.c @@ -116,7 +116,7 @@ uint64_t get_tsc_hz(void) { return 0; } -int _DkGetCPUInfo (PAL_CPU_INFO* ci) { +int _DkGetCPUInfo(PAL_CPU_INFO* ci) { unsigned int words[PAL_CPUID_WORD_NUM]; int rv = 0; @@ -131,8 +131,8 @@ int _DkGetCPUInfo (PAL_CPU_INFO* ci) { ci->cpu_vendor = vendor_id; // Must be an Intel CPU if (memcmp(vendor_id, "GenuineIntel", 12)) { - free(vendor_id); - return -PAL_ERROR_INVAL; + free(vendor_id); + return -PAL_ERROR_INVAL; } const size_t BRAND_SIZE = 49; @@ -160,7 +160,7 @@ int _DkGetCPUInfo (PAL_CPU_INFO* ci) { int flen = 0, fmax = 80; char* flags = malloc(fmax); - for (int i = 0 ; i < 32 ; i++) { + for (int i = 0; i < 32; i++) { if (!g_cpu_flags[i]) continue; @@ -184,7 +184,8 @@ int _DkGetCPUInfo (PAL_CPU_INFO* ci) { ci->cpu_bogomips = get_bogomips(); if (ci->cpu_bogomips == 0.0) { - SGX_DBG(DBG_E, "Warning: bogomips could not be retrieved, passing 0.0 to the application\n"); + SGX_DBG(DBG_E, + "Warning: bogomips could not be retrieved, passing 0.0 to the application\n"); } return rv; diff --git a/Pal/src/host/Linux-SGX/db_main.c b/Pal/src/host/Linux-SGX/db_main.c index 453563650b..12fcd5aad6 100644 --- a/Pal/src/host/Linux-SGX/db_main.c +++ b/Pal/src/host/Linux-SGX/db_main.c @@ -8,7 +8,16 @@ * processes environment, arguments and manifest. */ +#include +#include +#include +#include +#include + #include "api.h" +#include "ecall_types.h" +#include "elf/elf.h" +#include "enclave_pages.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" @@ -18,16 +27,7 @@ #include "pal_linux_defs.h" #include "pal_security.h" #include "protected_files.h" - -#include -#include -#include -#include -#include -#include - -#include "ecall_types.h" -#include "enclave_pages.h" +#include "sysdeps/generic/ldsodefs.h" #define RTLD_BOOTSTRAP #define _ENTRY enclave_entry @@ -39,8 +39,7 @@ PAL_SESSION_KEY g_master_key = {0}; size_t g_page_size = PRESET_PAGESIZE; -unsigned long _DkGetAllocationAlignment (void) -{ +unsigned long _DkGetAllocationAlignment(void) { return g_page_size; } @@ -51,26 +50,23 @@ void _DkGetAvailableUserAddressRange(PAL_PTR* start, PAL_PTR* end) { /* FIXME: hack to keep some heap for internal PAL objects allocated at runtime (recall that * LibOS does not keep track of PAL memory, so without this hack it could overwrite internal * PAL memory). This hack is probabilistic and brittle. */ - *end = SATURATED_P_SUB(*end, 2 * 1024 * g_page_size, *start); /* 8MB reserved for PAL stuff */ + *end = SATURATED_P_SUB(*end, 2 * 1024 * g_page_size, *start); /* 8MB reserved for PAL stuff */ if (*end <= *start) { SGX_DBG(DBG_E, "Not enough enclave memory, please increase enclave size!\n"); ocall_exit(1, /*is_exitgroup=*/true); } } -PAL_NUM _DkGetProcessId (void) -{ +PAL_NUM _DkGetProcessId(void) { return g_linux_state.process_id; } -PAL_NUM _DkGetHostId (void) -{ +PAL_NUM _DkGetHostId(void) { return 0; } -#include "elf-x86_64.h" #include "dynamic_link.h" -#include +#include "elf-x86_64.h" static struct link_map g_pal_map; @@ -80,8 +76,7 @@ static struct link_map g_pal_map; * The handle is not backed by any file. Reads will return EOF and writes will * fail. */ -static PAL_HANDLE setup_dummy_file_handle (const char * name) -{ +static PAL_HANDLE setup_dummy_file_handle(const char* name) { if (!strstartswith_static(name, URI_PREFIX_FILE)) return NULL; @@ -92,7 +87,7 @@ static PAL_HANDLE setup_dummy_file_handle (const char * name) HANDLE_HDR(handle)->flags |= RFD(0); handle->file.fd = PAL_IDX_POISON; - char * path = (void *) handle + HANDLE_SIZE(file); + char* path = (void*)handle + HANDLE_SIZE(file); int ret = get_norm_path(name, path, &len); if (ret < 0) { SGX_DBG(DBG_E, "Could not normalize path (%s): %s\n", name, pal_strerror(ret)); @@ -101,8 +96,8 @@ static PAL_HANDLE setup_dummy_file_handle (const char * name) } handle->file.realpath = path; - handle->file.total = 0; - handle->file.stubs = NULL; + handle->file.total = 0; + handle->file.stubs = NULL; return handle; } @@ -380,18 +375,18 @@ noreturn void pal_linux_main(char* uptr_libpal_uri, size_t libpal_uri_len, char* struct config_store* root_config = malloc(sizeof(struct config_store)); root_config->raw_data = manifest_addr; root_config->raw_size = manifest_size; - root_config->malloc = malloc; - root_config->free = free; + root_config->malloc = malloc; + root_config->free = free; - const char * errstring = NULL; + const char* errstring = NULL; if ((rv = read_config(root_config, loader_filter, &errstring)) < 0) { SGX_DBG(DBG_E, "Can't read manifest: %s, error code %d\n", errstring, rv); ocall_exit(1, /*is_exitgroup=*/true); } g_pal_state.root_config = root_config; - g_pal_control.manifest_preload.start = (PAL_PTR) manifest_addr; - g_pal_control.manifest_preload.end = (PAL_PTR) manifest_addr + manifest_size; + g_pal_control.manifest_preload.start = (PAL_PTR)manifest_addr; + g_pal_control.manifest_preload.end = (PAL_PTR)manifest_addr + manifest_size; if ((rv = init_trusted_files()) < 0) { SGX_DBG(DBG_E, "Failed to load the checksums of trusted files: %d\n", rv); diff --git a/Pal/src/host/Linux-SGX/db_memory.c b/Pal/src/host/Linux-SGX/db_memory.c index 7e8748468f..40c83af456 100644 --- a/Pal/src/host/Linux-SGX/db_memory.c +++ b/Pal/src/host/Linux-SGX/db_memory.c @@ -83,8 +83,8 @@ int _DkVirtualMemoryProtect(void* addr, uint64_t size, int prot) { static struct atomic_int at_cnt = {.counter = 0}; int64_t t = 0; - if (__atomic_compare_exchange_n(&at_cnt.counter, &t, 1, /*weak=*/false, - __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n(&at_cnt.counter, &t, 1, /*weak=*/false, __ATOMIC_SEQ_CST, + __ATOMIC_RELAXED)) SGX_DBG(DBG_M, "[Warning] DkVirtualMemoryProtect is unimplemented in Linux-SGX PAL"); return 0; } diff --git a/Pal/src/host/Linux-SGX/db_misc.c b/Pal/src/host/Linux-SGX/db_misc.c index 8f5c6fb7fe..e0054d0e3e 100644 --- a/Pal/src/host/Linux-SGX/db_misc.c +++ b/Pal/src/host/Linux-SGX/db_misc.c @@ -210,104 +210,100 @@ void init_cpuid(void) { * through xfrm what extensions are enabled inside the enclave. */ static void sanity_check_cpuid(uint32_t leaf, uint32_t subleaf, uint32_t values[4]) { - uint64_t xfrm = report.body.attributes.xfrm; - enum cpu_extension { - x87 = 0, SSE, AVX, MPX_1, MPX_2, AVX512_1, AVX512_2, AVX512_3, PKRU = 9 }; - const uint32_t extension_sizes_bytes[] = - { [AVX] = 256, [MPX_1] = 64, [MPX_2] = 64, [AVX512_1] = 64, [AVX512_2] = 512, - [AVX512_3] = 1024, [PKRU] = 8}; + enum cpu_extension { x87 = 0, SSE, AVX, MPX_1, MPX_2, AVX512_1, AVX512_2, AVX512_3, PKRU = 9 }; + const uint32_t extension_sizes_bytes[] = { + [AVX] = 256, [MPX_1] = 64, [MPX_2] = 64, [AVX512_1] = 64, + [AVX512_2] = 512, [AVX512_3] = 1024, [PKRU] = 8}; /* Note that AVX offset is 576 bytes and MPX_1 starts at 960. The AVX state size is 256, leaving * 128 bytes unaccounted for. */ - const uint32_t extension_offset_bytes[] = - { [AVX] = 576, [MPX_1] = 960, [MPX_2] = 1024, [AVX512_1] = 1088, [AVX512_2] = 1152, - [AVX512_3] = 1664, [PKRU] = 2688}; - enum register_index { - EAX = 0, EBX, ECX, EDX - }; + const uint32_t extension_offset_bytes[] = { + [AVX] = 576, [MPX_1] = 960, [MPX_2] = 1024, [AVX512_1] = 1088, + [AVX512_2] = 1152, [AVX512_3] = 1664, [PKRU] = 2688}; + enum register_index { EAX = 0, EBX, ECX, EDX }; const uint32_t EXTENDED_STATE_LEAF = 0xd; if (leaf == EXTENDED_STATE_LEAF) { switch (subleaf) { - case 0x0: - /* From the SDM: "EDX:EAX is a bitmap of all the user state components that can be - * managed using the XSAVE feature set. A bit can be set in XCR0 if and only if the - * corresponding bit is set in this bitmap. Every processor that supports the XSAVE - * feature set will set EAX[0] (x87 state) and EAX[1] (SSE state)." - * - * On EENTER/ERESUME, the system installs xfrm into XCR0. Hence, we return xfrm here in - * EAX. - */ - values[EAX] = xfrm; - - /* From the SDM: "EBX enumerates the size (in bytes) required by the XSAVE instruction - * for an XSAVE area containing all the user state components corresponding to bits - * currently set in XCR0." - */ - uint32_t xsave_size = 0; - /* Start from AVX since x87 and SSE are always captured using XSAVE. Also, x87 and SSE - * state size is implicitly included in the extension's offset, e.g., AVX's offset is - * 576 which includes x87 and SSE state as well as the XSAVE header. */ - for (int i = AVX; i <= PKRU; i++) { - if (extension_enabled(xfrm, i)) { - xsave_size = extension_offset_bytes[i] + extension_sizes_bytes[i]; + case 0x0: + /* From the SDM: "EDX:EAX is a bitmap of all the user state components that can be + * managed using the XSAVE feature set. A bit can be set in XCR0 if and only if the + * corresponding bit is set in this bitmap. Every processor that supports the XSAVE + * feature set will set EAX[0] (x87 state) and EAX[1] (SSE state)." + * + * On EENTER/ERESUME, the system installs xfrm into XCR0. Hence, we return xfrm here + * in EAX. + */ + values[EAX] = xfrm; + + /* From the SDM: "EBX enumerates the size (in bytes) required by the XSAVE + * instruction for an XSAVE area containing all the user state components + * corresponding to bits currently set in XCR0." + */ + uint32_t xsave_size = 0; + /* Start from AVX since x87 and SSE are always captured using XSAVE. Also, x87 and + * SSE state size is implicitly included in the extension's offset, e.g., AVX's + * offset is 576 which includes x87 and SSE state as well as the XSAVE header. */ + for (int i = AVX; i <= PKRU; i++) { + if (extension_enabled(xfrm, i)) { + xsave_size = extension_offset_bytes[i] + extension_sizes_bytes[i]; + } } - } - values[EBX] = xsave_size; - - /* From the SDM: "ECX enumerates the size (in bytes) required by the XSAVE instruction - * for an XSAVE area containing all the user state components supported by this - * processor." - * - * We are assuming here that inside the enclave, ECX and EBX for leaf 0xD and subleaf - * 0x1 should always be identical, while outside they can potentially be - * different. Also, outside of SGX EBX can change at runtime, while ECX is a static - * property. - */ - values[ECX] = values[EBX]; - values[EDX] = 0; - - break; - case 0x1: { - const uint32_t xsave_legacy_size = 512; - const uint32_t xsave_header = 64; - uint32_t save_size_bytes = xsave_legacy_size + xsave_header; - - /* Start with AVX, since x87 and SSE state is already included when initializing - * `save_size_bytes`. */ - for (int i = AVX; i <= PKRU; i++) { - if (extension_enabled(xfrm, i)) { - save_size_bytes += extension_sizes_bytes[i]; + values[EBX] = xsave_size; + + /* From the SDM: "ECX enumerates the size (in bytes) required by the XSAVE + * instruction for an XSAVE area containing all the user state components supported + * by this processor." + * + * We are assuming here that inside the enclave, ECX and EBX for leaf 0xD and + * subleaf 0x1 should always be identical, while outside they can potentially be + * different. Also, outside of SGX EBX can change at runtime, while ECX is a static + * property. + */ + values[ECX] = values[EBX]; + values[EDX] = 0; + + break; + case 0x1: { + const uint32_t xsave_legacy_size = 512; + const uint32_t xsave_header = 64; + uint32_t save_size_bytes = xsave_legacy_size + xsave_header; + + /* Start with AVX, since x87 and SSE state is already included when initializing + * `save_size_bytes`. */ + for (int i = AVX; i <= PKRU; i++) { + if (extension_enabled(xfrm, i)) { + save_size_bytes += extension_sizes_bytes[i]; + } } - } - /* EBX reports the actual size occupied by those extensions irrespective of their - * offsets within the xsave area. - */ - values[EBX] = save_size_bytes; + /* EBX reports the actual size occupied by those extensions irrespective of their + * offsets within the xsave area. + */ + values[EBX] = save_size_bytes; - break; - } - case AVX: - case MPX_1: - case MPX_2: - case AVX512_1: - case AVX512_2: - case AVX512_3: - case PKRU: - if (extension_enabled(xfrm, subleaf)) { - if (values[EAX] != extension_sizes_bytes[subleaf]) { - SGX_DBG(DBG_E, "Unexpected value in host CPUID. Exiting...\n"); - _DkProcessExit(1); - } - } else { - if (values[EAX] != 0) { - SGX_DBG(DBG_E, "Unexpected value in host CPUID. Exiting...\n"); - _DkProcessExit(1); - } + break; } - break; + case AVX: + case MPX_1: + case MPX_2: + case AVX512_1: + case AVX512_2: + case AVX512_3: + case PKRU: + if (extension_enabled(xfrm, subleaf)) { + if (values[EAX] != extension_sizes_bytes[subleaf]) { + SGX_DBG(DBG_E, "Unexpected value in host CPUID. Exiting...\n"); + _DkProcessExit(1); + } + } else { + if (values[EAX] != 0) { + SGX_DBG(DBG_E, "Unexpected value in host CPUID. Exiting...\n"); + _DkProcessExit(1); + } + } + break; } } } @@ -326,11 +322,11 @@ int _DkCpuIdRetrieve(unsigned int leaf, unsigned int subleaf, unsigned int value } int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size) { + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size) { __sgx_mem_aligned sgx_report_data_t stack_report_data = {0}; __sgx_mem_aligned sgx_target_info_t stack_target_info = {0}; - __sgx_mem_aligned sgx_report_t stack_report = {0}; + __sgx_mem_aligned sgx_report_t stack_report = {0}; if (!user_report_data_size || !target_info_size || !report_size) return -PAL_ERROR_INVAL; @@ -413,7 +409,7 @@ int _DkAttestationQuote(const PAL_PTR user_report_data, PAL_NUM user_report_data SGX_DBG(DBG_E, "Malformed sgx.ra_client_spid value in the manifest: %s\n", spid_hex); return -PAL_ERROR_INVAL; } - spid[i/2] = spid[i/2] * 16 + (uint8_t)val; + spid[i / 2] = spid[i / 2] * 16 + (uint8_t)val; } char buf[2]; diff --git a/Pal/src/host/Linux-SGX/db_mutex.c b/Pal/src/host/Linux-SGX/db_mutex.c index baabe748a0..bd93670709 100644 --- a/Pal/src/host/Linux-SGX/db_mutex.c +++ b/Pal/src/host/Linux-SGX/db_mutex.c @@ -10,13 +10,13 @@ */ #include -#include #include #include #include #include #include "api.h" +#include "atomic.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" @@ -48,8 +48,8 @@ int _DkMutexLockTimeout(struct mutex_handle* m, int64_t timeout_us) { int ret = 0; uint32_t t = MUTEX_UNLOCKED; - if (__atomic_compare_exchange_n(m->locked, &t, MUTEX_LOCKED, /*weak=*/false, - __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) + if (__atomic_compare_exchange_n(m->locked, &t, MUTEX_LOCKED, /*weak=*/false, __ATOMIC_ACQUIRE, + __ATOMIC_RELAXED)) goto success; if (timeout_us == 0) { @@ -117,7 +117,7 @@ int _DkMutexUnlock(struct mutex_handle* m) { void _DkMutexRelease(PAL_HANDLE handle) { struct mutex_handle* mut = &handle->mutex.mut; - int ret = _DkMutexUnlock(mut); + int ret = _DkMutexUnlock(mut); if (ret < 0) _DkRaiseFailure(ret); return; diff --git a/Pal/src/host/Linux-SGX/db_object.c b/Pal/src/host/Linux-SGX/db_object.c index cfcb8816ab..89bac820f8 100644 --- a/Pal/src/host/Linux-SGX/db_object.c +++ b/Pal/src/host/Linux-SGX/db_object.c @@ -35,8 +35,8 @@ int _DkSynchronizationObjectWait(PAL_HANDLE handle, int64_t timeout_us) { /* Wait for specific events on all handles in the handle array and return multiple events * (including errors) reported by the host. Return 0 on success, PAL error on failure. */ -int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events, - int64_t timeout_us) { +int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, + PAL_FLG* ret_events, int64_t timeout_us) { int ret; if (count == 0) @@ -96,7 +96,8 @@ int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events if (!nfds) { if (ret_events_updated > 0) { - /* we skip actual ppoll, but there was at least one PAL handle with updated ret_events */ + /* we skip actual ppoll, but there was at least one PAL handle with updated ret_events + */ ret = 0; } else { /* did not find any waitable FDs (LibOS supplied closed/errored FDs or empty events) */ @@ -146,7 +147,7 @@ int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events for (size_t k = 0; k < MAX_FDS; k++) { if (hdl->generic.fds[k] != (PAL_IDX)fds[i].fd) continue; - if (fds[i].revents & (POLLHUP|POLLERR|POLLNVAL)) + if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) HANDLE_HDR(hdl)->flags |= ERROR(k); } } diff --git a/Pal/src/host/Linux-SGX/db_pipes.c b/Pal/src/host/Linux-SGX/db_pipes.c index e9bfe99ba8..eb3102f16c 100644 --- a/Pal/src/host/Linux-SGX/db_pipes.c +++ b/Pal/src/host/Linux-SGX/db_pipes.c @@ -90,9 +90,9 @@ static int thread_handshake_func(void* param) { /*! * \brief Create a listening abstract UNIX socket as preparation for connecting two ends of a pipe. * - * An abstract UNIX socket with name "@/graphene/" is opened for listening. A corresponding - * PAL handle with type `pipesrv` is created. This PAL handle typically serves only as an - * intermediate step to connect two ends of the pipe (`pipecli` and `pipe`). As soon as the other + * An abstract UNIX socket with name "@/graphene/" is opened for listening. A + * corresponding PAL handle with type `pipesrv` is created. This PAL handle typically serves only as + * an intermediate step to connect two ends of the pipe (`pipecli` and `pipe`). As soon as the other * end of the pipe connects to this listening socket, a new accepted socket and the corresponding * PAL handle are created, and this `pipesrv` handle can be closed. * @@ -125,9 +125,9 @@ static int pipe_listen(PAL_HANDLE* handle, const char* name, int options) { } SET_HANDLE_TYPE(hdl, pipesrv); - HANDLE_HDR(hdl)->flags |= RFD(0); /* cannot write to a listening socket */ - hdl->pipe.fd = ret; - hdl->pipe.nonblocking = options & PAL_OPTION_NONBLOCK ? PAL_TRUE : PAL_FALSE; + HANDLE_HDR(hdl)->flags |= RFD(0); /* cannot write to a listening socket */ + hdl->pipe.fd = ret; + hdl->pipe.nonblocking = options & PAL_OPTION_NONBLOCK ? PAL_TRUE : PAL_FALSE; /* padding with zeros is because the whole buffer is used in key derivation */ memset(&hdl->pipe.name.str, 0, sizeof(hdl->pipe.name.str)); @@ -136,7 +136,7 @@ static int pipe_listen(PAL_HANDLE* handle, const char* name, int options) { /* pipesrv handle is only intermediate so it doesn't need SSL context or session key */ hdl->pipe.ssl_ctx = NULL; hdl->pipe.is_server = false; - hdl->pipe.handshake_done = 1; /* pipesrv doesn't do any handshake so consider it done */ + hdl->pipe.handshake_done = 1; /* pipesrv doesn't do any handshake so consider it done */ memset(hdl->pipe.session_key, 0, sizeof(hdl->pipe.session_key)); *handle = hdl; @@ -176,9 +176,9 @@ static int pipe_waitforclient(PAL_HANDLE handle, PAL_HANDLE* client) { SET_HANDLE_TYPE(clnt, pipecli); HANDLE_HDR(clnt)->flags |= RFD(0) | WFD(0); - clnt->pipe.fd = ret; - clnt->pipe.name = handle->pipe.name; - clnt->pipe.nonblocking = PAL_FALSE; /* FIXME: must set nonblocking based on `handle` value */ + clnt->pipe.fd = ret; + clnt->pipe.name = handle->pipe.name; + clnt->pipe.nonblocking = PAL_FALSE; /* FIXME: must set nonblocking based on `handle` value */ /* create the SSL pre-shared key for this end of the pipe; note that SSL context is initialized * lazily on first read/write on this pipe */ @@ -210,9 +210,9 @@ static int pipe_waitforclient(PAL_HANDLE handle, PAL_HANDLE* client) { * \brief Connect to the other end of the pipe and create PAL handle for our end of the pipe. * * This function connects to the other end of the pipe, represented as an abstract UNIX socket - * "@/graphene/" opened for listening. When the connection succeeds, a new `pipe` PAL handle - * is created with the corresponding underlying socket and is returned in `handle`. The other end of - * the pipe is typically of type `pipecli`. + * "@/graphene/" opened for listening. When the connection succeeds, a new `pipe` PAL + * handle is created with the corresponding underlying socket and is returned in `handle`. The other + * end of the pipe is typically of type `pipecli`. * * \param[out] handle PAL handle of type `pipe` with abstract UNIX socket connected to another end. * \param[in] name String uniquely identifying the pipe. @@ -232,8 +232,7 @@ static int pipe_connect(PAL_HANDLE* handle, const char* name, int options) { int nonblock = options & PAL_OPTION_NONBLOCK ? SOCK_NONBLOCK : 0; ret = ocall_connect(AF_UNIX, SOCK_STREAM | nonblock, 0, /*ipv6_v6only=*/0, - (const struct sockaddr*)&addr, - addrlen, NULL, NULL, &sock_options); + (const struct sockaddr*)&addr, addrlen, NULL, NULL, &sock_options); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); diff --git a/Pal/src/host/Linux-SGX/db_process.c b/Pal/src/host/Linux-SGX/db_process.c index cc7235aee9..4be1b765e3 100644 --- a/Pal/src/host/Linux-SGX/db_process.c +++ b/Pal/src/host/Linux-SGX/db_process.c @@ -12,6 +12,10 @@ * at creation. */ +#include +#include +#include + #include "api.h" #include "pal.h" #include "pal_crypto.h" @@ -25,10 +29,6 @@ #include "pal_security.h" #include "protected-files/protected_files.h" #include "spinlock.h" - -#include -#include -#include typedef __kernel_pid_t pid_t; #include @@ -43,9 +43,9 @@ DEFINE_LISTP(trusted_child); static LISTP_TYPE(trusted_child) trusted_children = LISTP_INIT; static spinlock_t trusted_children_lock = INIT_SPINLOCK_UNLOCKED; -int register_trusted_child(const char * uri, const char * mr_enclave_str) -{ - struct trusted_child * tc = NULL, * new; +int register_trusted_child(const char* uri, const char* mr_enclave_str) { + struct trusted_child* tc = NULL; + struct trusted_child* new; int uri_len = strlen(uri); spinlock_lock(&trusted_children_lock); @@ -67,7 +67,7 @@ int register_trusted_child(const char * uri, const char * mr_enclave_str) char mr_enclave_text[sizeof(sgx_measurement_t) * 2 + 1] = "\0"; size_t nbytes = 0; - for (; nbytes < sizeof(sgx_measurement_t) ; nbytes++) { + for (; nbytes < sizeof(sgx_measurement_t); nbytes++) { char byte1 = mr_enclave_str[nbytes * 2]; char byte2 = mr_enclave_str[nbytes * 2 + 1]; unsigned char val = 0; @@ -75,12 +75,10 @@ int register_trusted_child(const char * uri, const char * mr_enclave_str) if (byte1 == 0 || byte2 == 0) { break; } - if (!(byte1 >= '0' && byte1 <= '9') && - !(byte1 >= 'a' && byte1 <= 'f')) { + if (!(byte1 >= '0' && byte1 <= '9') && !(byte1 >= 'a' && byte1 <= 'f')) { break; } - if (!(byte2 >= '0' && byte2 <= '9') && - !(byte2 >= 'a' && byte2 <= 'f')) { + if (!(byte2 >= '0' && byte2 <= '9') && !(byte2 >= 'a' && byte2 <= 'f')) { break; } @@ -185,7 +183,7 @@ static int generate_sign_data(const PAL_SESSION_KEY* session_key, uint64_t encla if (ret < 0) return ret; - SGX_DBG(DBG_P|DBG_S, "Enclave identifier: %016lx -> %s\n", enclave_id, + SGX_DBG(DBG_P | DBG_S, "Enclave identifier: %016lx -> %s\n", enclave_id, ALLOCA_BYTES2HEXSTR(data.eid_mac)); /* Copy proc_data into sgx_sign_data_t */ @@ -202,8 +200,7 @@ static int check_child_mr_enclave(PAL_HANDLE child, sgx_measurement_t* mr_enclav return 1; sgx_sign_data_t sign_data; - int ret = generate_sign_data(&child->process.session_key, remote_state->enclave_id, - &sign_data); + int ret = generate_sign_data(&child->process.session_key, remote_state->enclave_id, &sign_data); if (ret < 0) return ret; @@ -218,7 +215,7 @@ static int check_child_mr_enclave(PAL_HANDLE child, sgx_measurement_t* mr_enclav return 0; } - struct trusted_child * tc; + struct trusted_child* tc; spinlock_lock(&trusted_children_lock); /* Try to find a matching mr_enclave from the manifest */ @@ -234,8 +231,7 @@ static int check_child_mr_enclave(PAL_HANDLE child, sgx_measurement_t* mr_enclav return 1; } -int _DkProcessCreate (PAL_HANDLE * handle, const char * uri, const char ** args) -{ +int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { /* only access creating process with regular file */ if (!strstartswith_static(uri, URI_PREFIX_FILE)) return -PAL_ERROR_INVAL; @@ -245,7 +241,7 @@ int _DkProcessCreate (PAL_HANDLE * handle, const char * uri, const char ** args) int nargs = 0, ret; if (args) - for (const char ** a = args ; *a ; a++) + for (const char** a = args; *a; a++) nargs++; ret = ocall_create_process(uri, nargs, args, &stream_fd, &child_pid); @@ -254,7 +250,7 @@ int _DkProcessCreate (PAL_HANDLE * handle, const char * uri, const char ** args) PAL_HANDLE child = malloc(HANDLE_SIZE(process)); SET_HANDLE_TYPE(child, process); - HANDLE_HDR(child)->flags |= RFD(0)|WFD(0); + HANDLE_HDR(child)->flags |= RFD(0) | WFD(0); child->process.stream = stream_fd; child->process.pid = child_pid; child->process.nonblocking = PAL_FALSE; @@ -325,11 +321,10 @@ static int check_parent_mr_enclave(PAL_HANDLE parent, sgx_measurement_t* mr_encl return 0; } -int init_child_process (PAL_HANDLE * parent_handle) -{ +int init_child_process(PAL_HANDLE* parent_handle) { PAL_HANDLE parent = malloc(HANDLE_SIZE(process)); SET_HANDLE_TYPE(parent, process); - HANDLE_HDR(parent)->flags |= RFD(0)|WFD(0); + HANDLE_HDR(parent)->flags |= RFD(0) | WFD(0); parent->process.stream = g_pal_sec.stream_fd; parent->process.pid = g_pal_sec.ppid; @@ -383,8 +378,7 @@ int init_child_process (PAL_HANDLE * parent_handle) return 0; } -noreturn void _DkProcessExit (int exitcode) -{ +noreturn void _DkProcessExit(int exitcode) { if (exitcode) SGX_DBG(DBG_I, "DkProcessExit: Returning exit code %d\n", exitcode); ocall_exit(exitcode, /*is_exitgroup=*/true); @@ -393,9 +387,7 @@ noreturn void _DkProcessExit (int exitcode) } } -static int64_t proc_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buffer) -{ +static int64_t proc_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer) { if (offset) return -PAL_ERROR_INVAL; @@ -413,9 +405,7 @@ static int64_t proc_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, return bytes; } -static int64_t proc_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buffer) -{ +static int64_t proc_write(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer) { if (offset) return -PAL_ERROR_INVAL; @@ -433,8 +423,7 @@ static int64_t proc_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, return bytes; } -static int proc_close (PAL_HANDLE handle) -{ +static int proc_close(PAL_HANDLE handle) { if (handle->process.stream != PAL_IDX_POISON) { ocall_close(handle->process.stream); handle->process.stream = PAL_IDX_POISON; @@ -448,8 +437,7 @@ static int proc_close (PAL_HANDLE handle) return 0; } -static int proc_delete (PAL_HANDLE handle, int access) -{ +static int proc_delete(PAL_HANDLE handle, int access) { int shutdown; switch (access) { case 0: @@ -480,7 +468,7 @@ static int proc_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { attr->handle_type = HANDLE_HDR(handle)->type; attr->nonblocking = handle->process.nonblocking; attr->disconnected = HANDLE_HDR(handle)->flags & ERROR(0); - attr->secure = handle->process.ssl_ctx ? PAL_TRUE : PAL_FALSE; + attr->secure = handle->process.ssl_ctx ? PAL_TRUE : PAL_FALSE; /* get number of bytes available for reading */ ret = ocall_fionread(handle->process.stream); @@ -500,14 +488,12 @@ static int proc_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { return 0; } -static int proc_attrsetbyhdl (PAL_HANDLE handle, PAL_STREAM_ATTR * attr) -{ +static int proc_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (handle->process.stream == PAL_IDX_POISON) return -PAL_ERROR_BADHANDLE; if (attr->nonblocking != handle->process.nonblocking) { - int ret = ocall_fsetnonblock(handle->process.stream, - handle->process.nonblocking); + int ret = ocall_fsetnonblock(handle->process.stream, handle->process.nonblocking); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); diff --git a/Pal/src/host/Linux-SGX/db_rtld.c b/Pal/src/host/Linux-SGX/db_rtld.c index a620bead0e..afb2bbc64b 100644 --- a/Pal/src/host/Linux-SGX/db_rtld.c +++ b/Pal/src/host/Linux-SGX/db_rtld.c @@ -10,40 +10,35 @@ * Library. */ -#include "pal_defs.h" -#include "pal_linux_defs.h" +#include "api.h" +#include "elf-x86_64.h" +#include "elf/elf.h" #include "pal.h" -#include "pal_internal.h" -#include "pal_linux.h" #include "pal_debug.h" +#include "pal_defs.h" #include "pal_error.h" -#include "pal_security.h" +#include "pal_internal.h" +#include "pal_linux.h" +#include "pal_linux_defs.h" #include "pal_rtld.h" -#include "api.h" - -#include -#include - -#include "elf-x86_64.h" +#include "pal_security.h" +#include "sysdeps/generic/ldsodefs.h" -void _DkDebugAddMap (struct link_map * map) -{ - const ElfW(Ehdr) * ehdr = (void *) map->l_map_start; +void _DkDebugAddMap(struct link_map* map) { + const ElfW(Ehdr)* ehdr = (void*)map->l_map_start; int shdrsz = sizeof(ElfW(Shdr)) * ehdr->e_shnum; - ElfW(Shdr) * shdr = NULL; - ElfW(Phdr) * phdr = (void *) (map->l_map_start + ehdr->e_phoff); - const ElfW(Phdr) * ph; + ElfW(Shdr)* shdr = NULL; + ElfW(Phdr)* phdr = (void*)(map->l_map_start + ehdr->e_phoff); + const ElfW(Phdr)* ph; int fd = ocall_open(map->l_name, O_RDONLY, 0); if (IS_ERR(fd)) return; for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph) - if (ph->p_type == PT_LOAD && - ehdr->e_shoff >= ph->p_offset && + if (ph->p_type == PT_LOAD && ehdr->e_shoff >= ph->p_offset && ehdr->e_shoff < ph->p_offset + ph->p_filesz) { - shdr = (void *) map->l_addr + ph->p_vaddr + - (ehdr->e_shoff - ph->p_offset); + shdr = (void*)map->l_addr + ph->p_vaddr + (ehdr->e_shoff - ph->p_offset); break; } @@ -51,23 +46,21 @@ void _DkDebugAddMap (struct link_map * map) shdr = __alloca(shdrsz); unsigned long s = ALLOC_ALIGN_DOWN(ehdr->e_shoff); unsigned long e = ALLOC_ALIGN_UP(ehdr->e_shoff + shdrsz); - void * umem; + void* umem; ocall_mmap_untrusted(fd, s, e - s, PROT_READ, &umem); memcpy(shdr, umem + ehdr->e_shoff - s, shdrsz); ocall_munmap_untrusted(umem, e - s); } - ElfW(Shdr) * shdrend = (void *) shdr + shdrsz; + ElfW(Shdr)* shdrend = (void*)shdr + shdrsz; size_t shstroff = shdr[ehdr->e_shstrndx].sh_offset; size_t shstrsz = shdr[ehdr->e_shstrndx].sh_size; - const char * shstrtab = NULL; + const char* shstrtab = NULL; for (ph = phdr; ph < &phdr[ehdr->e_phnum]; ++ph) - if (ph->p_type == PT_LOAD && - shstroff >= ph->p_offset && - shstroff < ph->p_offset + ph->p_filesz) { - shstrtab = (void *) map->l_addr + ph->p_vaddr + - (shstroff - ph->p_offset); + if (ph->p_type == PT_LOAD && shstroff >= ph->p_offset && + shstroff < ph->p_offset + ph->p_filesz) { + shstrtab = (void*)map->l_addr + ph->p_vaddr + (shstroff - ph->p_offset); break; } @@ -75,16 +68,16 @@ void _DkDebugAddMap (struct link_map * map) shstrtab = __alloca(shstrsz); unsigned long s = ALLOC_ALIGN_DOWN(shstroff); unsigned long e = ALLOC_ALIGN_UP(shstroff + shstrsz); - void * umem; + void* umem; ocall_mmap_untrusted(fd, s, e - s, PROT_READ, &umem); - memcpy((void *) shstrtab, umem + shstroff - s, shstrsz); + memcpy((void*)shstrtab, umem + shstroff - s, shstrsz); ocall_munmap_untrusted(umem, e - s); } ocall_close(fd); ElfW(Addr) text_addr = 0; - for (ElfW(Shdr) * s = shdr ; s < shdrend ; s++) + for (ElfW(Shdr)* s = shdr; s < shdrend; s++) if (!strcmp_static(shstrtab + s->sh_name, ".text")) { text_addr = map->l_addr + s->sh_addr; break; @@ -95,13 +88,14 @@ void _DkDebugAddMap (struct link_map * map) #define BUFFER_LENGTH 4096 - char buffer[BUFFER_LENGTH], * ptr = buffer; + char buffer[BUFFER_LENGTH]; + char* ptr = buffer; - snprintf(ptr, BUFFER_LENGTH - (ptr - buffer), - "add-symbol-file %s 0x%016lx -readnow", map->l_name, text_addr); + snprintf(ptr, BUFFER_LENGTH - (ptr - buffer), "add-symbol-file %s 0x%016lx -readnow", + map->l_name, text_addr); ptr += strlen(ptr); - for (ElfW(Shdr) * s = shdr ; s < shdrend ; s++) { + for (ElfW(Shdr)* s = shdr; s < shdrend; s++) { if (!s->sh_name || !s->sh_addr) continue; if (!strcmp_static(shstrtab + s->sh_name, ".text")) @@ -111,8 +105,7 @@ void _DkDebugAddMap (struct link_map * map) if (strstartswith_static(shstrtab + s->sh_name, ".debug_")) continue; - snprintf(ptr, BUFFER_LENGTH - (ptr - buffer), - " -s %s 0x%016lx", shstrtab + s->sh_name, + snprintf(ptr, BUFFER_LENGTH - (ptr - buffer), " -s %s 0x%016lx", shstrtab + s->sh_name, map->l_addr + s->sh_addr); ptr += strlen(ptr); } @@ -120,8 +113,7 @@ void _DkDebugAddMap (struct link_map * map) ocall_load_debug(buffer); } -void _DkDebugDelMap (struct link_map * map) -{ +void _DkDebugDelMap(struct link_map* map) { char buffer[BUFFER_LENGTH]; snprintf(buffer, BUFFER_LENGTH, "remove-symbol-file %s", map->l_name); ocall_load_debug(buffer); @@ -133,23 +125,21 @@ extern void* g_section_dynamic; extern void* g_section_data; extern void* g_section_bss; -void setup_pal_map (struct link_map * pal_map) -{ - const ElfW(Ehdr) * header = (void *) pal_map->l_addr; +void setup_pal_map(struct link_map* pal_map) { + const ElfW(Ehdr)* header = (void*)pal_map->l_addr; - pal_map->l_real_ld = pal_map->l_ld = (void *) elf_machine_dynamic(); - pal_map->l_type = OBJECT_RTLD; - pal_map->l_entry = header->e_entry; - pal_map->l_phdr = (void *) (pal_map->l_addr + header->e_phoff); - pal_map->l_phnum = header->e_phnum; + pal_map->l_real_ld = pal_map->l_ld = (void*)elf_machine_dynamic(); + pal_map->l_type = OBJECT_RTLD; + pal_map->l_entry = header->e_entry; + pal_map->l_phdr = (void*)(pal_map->l_addr + header->e_phoff); + pal_map->l_phnum = header->e_phnum; setup_elf_hash(pal_map); char buffer[BUFFER_LENGTH]; snprintf(buffer, BUFFER_LENGTH, "add-symbol-file %s %p -readnow -s .rodata %p " "-s .dynamic %p -s .data %p -s .bss %p", - pal_map->l_name, - &g_section_text, &g_section_rodata, &g_section_dynamic, + pal_map->l_name, &g_section_text, &g_section_rodata, &g_section_dynamic, &g_section_data, &g_section_bss); ocall_load_debug(buffer); diff --git a/Pal/src/host/Linux-SGX/db_sockets.c b/Pal/src/host/Linux-SGX/db_sockets.c index 5a38fb8c5e..66036b1b25 100644 --- a/Pal/src/host/Linux-SGX/db_sockets.c +++ b/Pal/src/host/Linux-SGX/db_sockets.c @@ -575,8 +575,8 @@ static int64_t udp_receivebyaddr(PAL_HANDLE handle, uint64_t offset, uint64_t le struct sockaddr_storage conn_addr; size_t conn_addrlen = sizeof(conn_addr); - ssize_t bytes = ocall_recv(handle->sock.fd, buf, len, - (struct sockaddr*)&conn_addr, &conn_addrlen, NULL, NULL); + ssize_t bytes = ocall_recv(handle->sock.fd, buf, len, (struct sockaddr*)&conn_addr, + &conn_addrlen, NULL, NULL); if (IS_ERR(bytes)) return unix_to_pal_error(ERRNO(bytes)); @@ -585,8 +585,8 @@ static int64_t udp_receivebyaddr(PAL_HANDLE handle, uint64_t offset, uint64_t le if (!addr_uri) return -PAL_ERROR_OVERFLOW; - int ret = inet_create_uri(addr_uri, addr + addrlen - addr_uri, - (struct sockaddr*)&conn_addr, conn_addrlen); + int ret = inet_create_uri(addr_uri, addr + addrlen - addr_uri, (struct sockaddr*)&conn_addr, + conn_addrlen); if (ret < 0) return ret; @@ -643,8 +643,8 @@ static int64_t udp_sendbyaddr(PAL_HANDLE handle, uint64_t offset, uint64_t len, if (ret < 0) return ret; - ssize_t bytes = ocall_send(handle->sock.fd, buf, len, - (struct sockaddr*)&conn_addr, conn_addrlen, NULL, 0); + ssize_t bytes = ocall_send(handle->sock.fd, buf, len, (struct sockaddr*)&conn_addr, + conn_addrlen, NULL, 0); if (IS_ERR(bytes)) return unix_to_pal_error(ERRNO(bytes)); diff --git a/Pal/src/host/Linux-SGX/db_streams.c b/Pal/src/host/Linux-SGX/db_streams.c index 3c1f750b41..1776267bca 100644 --- a/Pal/src/host/Linux-SGX/db_streams.c +++ b/Pal/src/host/Linux-SGX/db_streams.c @@ -33,7 +33,7 @@ typedef __kernel_pid_t pid_t; #include #include -#define DUMMYPAYLOAD "dummypayload" +#define DUMMYPAYLOAD "dummypayload" #define DUMMYPAYLOADSIZE (sizeof(DUMMYPAYLOAD)) struct hdl_header { @@ -285,7 +285,8 @@ int _DkSendHandle(PAL_HANDLE hdl, PAL_HANDLE cargo) { memcpy(CMSG_DATA(control_hdr), fds, fds_size); /* next send FDs-to-transfer as ancillary data */ - ret = ocall_send(fd, DUMMYPAYLOAD, DUMMYPAYLOADSIZE, NULL, 0, control_hdr, control_hdr->cmsg_len); + ret = ocall_send(fd, DUMMYPAYLOAD, DUMMYPAYLOADSIZE, NULL, 0, control_hdr, + control_hdr->cmsg_len); if (IS_ERR(ret)) { free(hdl_data); return unix_to_pal_error(ERRNO(ret)); @@ -345,7 +346,8 @@ int _DkReceiveHandle(PAL_HANDLE hdl, PAL_HANDLE* cargo) { /* next receive FDs-to-transfer as ancillary data */ char dummypayload[DUMMYPAYLOADSIZE]; - ret = ocall_recv(fd, dummypayload, DUMMYPAYLOADSIZE, NULL, NULL, control_buf, &control_buf_size); + ret = ocall_recv(fd, dummypayload, DUMMYPAYLOADSIZE, NULL, NULL, control_buf, + &control_buf_size); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); diff --git a/Pal/src/host/Linux-SGX/db_threading.c b/Pal/src/host/Linux-SGX/db_threading.c index 2878ee8c25..b54bdef03d 100644 --- a/Pal/src/host/Linux-SGX/db_threading.c +++ b/Pal/src/host/Linux-SGX/db_threading.c @@ -7,8 +7,19 @@ * This file contain APIs to create, exit and yield a thread. */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + +#include +#include +#include +#include +#include + #include "api.h" #include "ecall_types.h" +#include "list.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" @@ -18,21 +29,13 @@ #include "pal_linux_defs.h" #include "pal_linux_error.h" -#include -#include -#include -#include -#include - -#include - static PAL_LOCK g_thread_list_lock = LOCK_INIT; DEFINE_LISTP(pal_handle_thread); static LISTP_TYPE(pal_handle_thread) g_thread_list = LISTP_INIT; struct thread_param { - int (*callback) (void *); - const void * param; + int (*callback)(void*); + const void* param; }; extern void* g_enclave_base; @@ -43,14 +46,12 @@ extern void* g_enclave_base; * uniqueness is not required; the tid is only used for debugging. We could * ensure uniqueness if needed in the future */ -static PAL_IDX pal_assign_tid(void) -{ +static PAL_IDX pal_assign_tid(void) { static struct atomic_int tid = ATOMIC_INIT(0); return __atomic_add_fetch(&tid.counter, 1, __ATOMIC_SEQ_CST); } -void pal_start_thread (void) -{ +void pal_start_thread(void) { struct pal_handle_thread *new_thread = NULL, *tmp; _DkInternalLock(&g_thread_list_lock); @@ -66,17 +67,16 @@ void pal_start_thread (void) if (!new_thread) return; - struct thread_param * thread_param = - (struct thread_param *) new_thread->param; - int (*callback) (void *) = thread_param->callback; - const void * param = thread_param->param; + struct thread_param* thread_param = (struct thread_param*)new_thread->param; + int (*callback)(void*) = thread_param->callback; + const void* param = thread_param->param; free(thread_param); new_thread->param = NULL; SET_ENCLAVE_TLS(thread, new_thread); SET_ENCLAVE_TLS(ready_for_exceptions, 1UL); PAL_TCB* pal_tcb = pal_get_tcb(); memset(&pal_tcb->libos_tcb, 0, sizeof(pal_tcb->libos_tcb)); - callback((void *) param); + callback((void*)param); _DkThreadExit(/*clear_child_tid=*/NULL); /* UNREACHABLE */ } @@ -84,9 +84,7 @@ void pal_start_thread (void) /* _DkThreadCreate for internal use. Create an internal thread inside the current process. The arguments callback and param specify the starting function and parameters */ -int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), - const void * param) -{ +int _DkThreadCreate(PAL_HANDLE* handle, int (*callback)(void*), const void* param) { PAL_HANDLE new_thread = malloc(HANDLE_SIZE(thread)); SET_HANDLE_TYPE(new_thread, thread); /* @@ -96,10 +94,10 @@ int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), new_thread->thread.tid = 0; new_thread->thread.tcs = NULL; INIT_LIST_HEAD(&new_thread->thread, list); - struct thread_param * thread_param = malloc(sizeof(struct thread_param)); + struct thread_param* thread_param = malloc(sizeof(struct thread_param)); thread_param->callback = callback; - thread_param->param = param; - new_thread->thread.param = (void *) thread_param; + thread_param->param = param; + new_thread->thread.param = (void*)thread_param; _DkInternalLock(&g_thread_list_lock); LISTP_ADD_TAIL(&new_thread->thread, &g_thread_list, list); @@ -120,8 +118,7 @@ int _DkThreadDelayExecution(uint64_t* duration_us) { /* PAL call DkThreadYieldExecution. Yield the execution of the current thread. */ -void _DkThreadYieldExecution (void) -{ +void _DkThreadYieldExecution(void) { ocall_sleep(NULL); } @@ -133,10 +130,10 @@ noreturn void _DkThreadExit(int* clear_child_tid) { * note that we don't do it now (because this thread still occupies SGX * TCS slot) but during handle_thread_reset in assembly code */ SET_ENCLAVE_TLS(clear_child_tid, clear_child_tid); - static_assert(sizeof(*clear_child_tid) == 4, "unexpected clear_child_tid size"); + static_assert(sizeof(*clear_child_tid) == 4, "unexpected clear_child_tid size"); /* main thread is not part of the g_thread_list */ - if(exiting_thread != &pal_control.first_thread->thread) { + if (exiting_thread != &pal_control.first_thread->thread) { _DkInternalLock(&g_thread_list_lock); LISTP_DEL(exiting_thread, &g_thread_list, list); _DkInternalUnlock(&g_thread_list_lock); @@ -145,8 +142,7 @@ noreturn void _DkThreadExit(int* clear_child_tid) { ocall_exit(0, /*is_exitgroup=*/false); } -int _DkThreadResume (PAL_HANDLE threadHandle) -{ +int _DkThreadResume(PAL_HANDLE threadHandle) { int ret = ocall_resume_thread(threadHandle->thread.tcs); return IS_ERR(ret) ? unix_to_pal_error(ERRNO(ret)) : ret; } diff --git a/Pal/src/host/Linux-SGX/debugger/sgx_gdb.c b/Pal/src/host/Linux-SGX/debugger/sgx_gdb.c index 25eeb205ac..bee5763a37 100644 --- a/Pal/src/host/Linux-SGX/debugger/sgx_gdb.c +++ b/Pal/src/host/Linux-SGX/debugger/sgx_gdb.c @@ -1,7 +1,6 @@ #define _GNU_SOURCE #include "sgx_gdb.h" -#include #include #include #include @@ -16,6 +15,7 @@ #include #include +#include "assert.h" #include "../sgx_arch.h" //#define DEBUG_GDB_PTRACE 1 @@ -150,8 +150,8 @@ static long int host_ptrace(enum __ptrace_request request, pid_t tid, void* addr data = &res; } - errno = 0; - ret = syscall((long int)SYS_ptrace, (long int)request, (long int)tid, (long int)addr, + errno = 0; + ret = syscall((long int)SYS_ptrace, (long int)request, (long int)tid, (long int)addr, (long int)data); ptrace_errno = errno; @@ -187,7 +187,7 @@ static int update_thread_tids(struct enclave_dbginfo* ei) { for (int off = 0; off < sizeof(ei->thread_tids); off += sizeof(long)) { errno = 0; - res = host_ptrace(PTRACE_PEEKDATA, ei->pid, src + off, NULL); + res = host_ptrace(PTRACE_PEEKDATA, ei->pid, src + off, NULL); if (res < 0 && errno != 0) { /* benign failure: enclave is not yet initialized */ return -1; @@ -342,7 +342,7 @@ static int open_memdevice(pid_t tid, int* memdev, struct enclave_dbginfo** ei) { for (int off = 0; off < sizeof(eib); off += sizeof(long)) { errno = 0; - ret = host_ptrace(PTRACE_PEEKDATA, tid, (void*)DBGINFO_ADDR + off, NULL); + ret = host_ptrace(PTRACE_PEEKDATA, tid, (void*)DBGINFO_ADDR + off, NULL); if (ret < 0 && errno != 0) { /* benign failure: enclave is not yet initialized */ return -1; @@ -631,8 +631,8 @@ pid_t waitpid(pid_t tid, int* status, int options) { DEBUG("[GDB %d] Intercepted waitpid(%d)\n", getpid(), tid); - errno = 0; - wait_res = syscall((long int)SYS_wait4, (long int)tid, (long int)status, (long int)options, + errno = 0; + wait_res = syscall((long int)SYS_wait4, (long int)tid, (long int)status, (long int)options, (long int)NULL); wait_errno = errno; diff --git a/Pal/src/host/Linux-SGX/debugger/sgx_gdb.h b/Pal/src/host/Linux-SGX/debugger/sgx_gdb.h index 1a17e55646..c595897dc2 100644 --- a/Pal/src/host/Linux-SGX/debugger/sgx_gdb.h +++ b/Pal/src/host/Linux-SGX/debugger/sgx_gdb.h @@ -20,5 +20,5 @@ struct __attribute__((aligned(__alignof__(uint64_t)))) enclave_dbginfo { void* eresume; int thread_tids[MAX_DBG_THREADS]; void* tcs_addrs[MAX_DBG_THREADS]; - uint64_t thread_stepping[MAX_DBG_THREADS/64]; /* bit vector */ + uint64_t thread_stepping[MAX_DBG_THREADS / 64]; /* bit vector */ }; diff --git a/Pal/src/host/Linux-SGX/elf-x86_64.h b/Pal/src/host/Linux-SGX/elf-x86_64.h index eafe796828..375bc4f4dd 100644 --- a/Pal/src/host/Linux-SGX/elf-x86_64.h +++ b/Pal/src/host/Linux-SGX/elf-x86_64.h @@ -11,10 +11,9 @@ #define ELF_MACHINE_NAME "x86_64" -#include -#include - #include "pal_internal.h" +#include "sysdep.h" +#include "sysdeps/generic/ldsodefs.h" /* Return the link-time address of _DYNAMIC. Conveniently, this is the first element of the GOT. This must be inlined in a function which diff --git a/Pal/src/host/Linux-SGX/enclave_ecalls.c b/Pal/src/host/Linux-SGX/enclave_ecalls.c index a1db16b5c1..0ec3fef541 100644 --- a/Pal/src/host/Linux-SGX/enclave_ecalls.c +++ b/Pal/src/host/Linux-SGX/enclave_ecalls.c @@ -1,8 +1,9 @@ +#include "enclave_ecalls.h" + #include #include "api.h" #include "ecall_types.h" -#include "enclave_ecalls.h" #include "pal_internal.h" #include "pal_linux.h" #include "pal_security.h" @@ -63,7 +64,7 @@ void handle_ecall(long ecall_index, void* ecall_args, void* exit_target, void* e if (!g_enclave_top) { g_enclave_base = enclave_base_addr; - g_enclave_top = enclave_base_addr + GET_ENCLAVE_TLS(enclave_size); + g_enclave_top = enclave_base_addr + GET_ENCLAVE_TLS(enclave_size); } /* disallow malicious URSP (that points into the enclave) */ @@ -104,7 +105,7 @@ void handle_ecall(long ecall_index, void* ecall_args, void* exit_target, void* e // TODO: This eats 1KB of a stack frame which lives for the whole lifespan of this enclave. // We should move it somewhere else and deallocate right after use. __sgx_mem_aligned sgx_target_info_t target_info; - alignas(128) char report_data[64] = { 0 }; + alignas(128) char report_data[64] = {0}; __sgx_mem_aligned sgx_report_t report; memset(&report, 0, sizeof(report)); memset(&target_info, 0, sizeof(target_info)); @@ -113,9 +114,8 @@ void handle_ecall(long ecall_index, void* ecall_args, void* exit_target, void* e /* pal_linux_main is responsible to check the passed arguments */ pal_linux_main(READ_ONCE(ms->ms_libpal_uri), READ_ONCE(ms->ms_libpal_uri_len), - READ_ONCE(ms->ms_args), READ_ONCE(ms->ms_args_size), - READ_ONCE(ms->ms_env), READ_ONCE(ms->ms_env_size), - pal_sec); + READ_ONCE(ms->ms_args), READ_ONCE(ms->ms_args_size), READ_ONCE(ms->ms_env), + READ_ONCE(ms->ms_env_size), pal_sec); } else { // ENCLAVE_START already called (maybe successfully, maybe not), so // only valid ecall is THREAD_START. diff --git a/Pal/src/host/Linux-SGX/enclave_framework.c b/Pal/src/host/Linux-SGX/enclave_framework.c index 1a12e8efe0..17cb0b3743 100644 --- a/Pal/src/host/Linux-SGX/enclave_framework.c +++ b/Pal/src/host/Linux-SGX/enclave_framework.c @@ -1,17 +1,17 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include "api.h" #include "enclave_pages.h" #include "hex.h" +#include "list.h" +#include "pal_crypto.h" +#include "pal_debug.h" +#include "pal_error.h" +#include "pal_internal.h" +#include "pal_linux.h" +#include "pal_linux_error.h" +#include "pal_security.h" +#include "spinlock.h" __sgx_mem_aligned struct pal_enclave_state g_pal_enclave_state; @@ -139,8 +139,7 @@ int sgx_get_report(const sgx_target_info_t* target_info, const sgx_report_data_t return 0; } -int sgx_verify_report (sgx_report_t* report) -{ +int sgx_verify_report(sgx_report_t* report) { __sgx_mem_aligned sgx_key_request_t keyrequest; memset(&keyrequest, 0, sizeof(sgx_key_request_t)); keyrequest.key_name = REPORT_KEY; @@ -182,8 +181,7 @@ int sgx_verify_report (sgx_report_t* report) return 0; } -int init_enclave_key (void) -{ +int init_enclave_key(void) { __sgx_mem_aligned sgx_key_request_t keyrequest; memset(&keyrequest, 0, sizeof(sgx_key_request_t)); keyrequest.key_name = SEAL_KEY; @@ -237,8 +235,7 @@ static bool g_allow_file_creation = 0; static int g_file_check_policy = FILE_CHECK_POLICY_STRICT; /* Assumes `path` is normalized */ -static bool path_is_equal_or_subpath(const struct trusted_file* tf, - const char* path, +static bool path_is_equal_or_subpath(const struct trusted_file* tf, const char* path, size_t path_len) { if (tf->uri_len > path_len || memcmp(tf->uri, path, tf->uri_len)) { /* tf->uri is not prefix of `path` */ @@ -252,7 +249,8 @@ static bool path_is_equal_or_subpath(const struct trusted_file* tf, /* tf->uri is a subpath of `path` */ return true; } - if (tf->uri_len == URI_PREFIX_FILE_LEN && !memcmp(tf->uri, URI_PREFIX_FILE, URI_PREFIX_FILE_LEN)) { + if (tf->uri_len == URI_PREFIX_FILE_LEN && + !memcmp(tf->uri, URI_PREFIX_FILE, URI_PREFIX_FILE_LEN)) { /* Empty path is a prefix of everything */ return true; } @@ -270,14 +268,14 @@ static bool path_is_equal_or_subpath(const struct trusted_file* tf, * * Returns 0 if succeeded, or an error code otherwise. */ -int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, - uint64_t * sizeptr, int create, void** umem) -{ +int load_trusted_file(PAL_HANDLE file, sgx_stub_t** stubptr, uint64_t* sizeptr, int create, + void** umem) { *stubptr = NULL; *sizeptr = 0; *umem = NULL; - struct trusted_file * tf = NULL, * tmp; + struct trusted_file* tf = NULL; + struct trusted_file* tmp; char uri[URI_MAX]; char normpath[URI_MAX]; int ret, fd = file->file.fd; @@ -293,8 +291,8 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, /* Allow to create the file when g_allow_file_creation is turned on; The created file is added to allowed_file list for later access */ if (create && g_allow_file_creation) { - register_trusted_file(uri, NULL, /*check_duplicates=*/true); - return 0; + register_trusted_file(uri, NULL, /*check_duplicates=*/true); + return 0; } /* Normalize the uri */ @@ -307,9 +305,7 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, size_t len = sizeof(normpath) - URI_PREFIX_FILE_LEN; ret = get_norm_path(uri + URI_PREFIX_FILE_LEN, normpath + URI_PREFIX_FILE_LEN, &len); if (ret < 0) { - SGX_DBG(DBG_E, - "Path (%s) normalization failed: %s\n", - uri + URI_PREFIX_FILE_LEN, + SGX_DBG(DBG_E, "Path (%s) normalization failed: %s\n", uri + URI_PREFIX_FILE_LEN, pal_strerror(ret)); return ret; } @@ -389,7 +385,7 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, goto failed; } - sgx_stub_t * s = stubs; /* stubs is an array of 128bit values */ + sgx_stub_t* s = stubs; /* stubs is an array of 128bit values */ uint64_t offset = 0; LIB_SHA256_CONTEXT sha; @@ -397,7 +393,7 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, if (ret < 0) goto failed; - for (; offset < tf->size ; offset += TRUSTED_STUB_SIZE, s++) { + for (; offset < tf->size; offset += TRUSTED_STUB_SIZE, s++) { /* For each stub, generate a 128bit hash of a file chunk with * AES-CMAC, and then update the SHA256 digest. */ uint64_t mapping_size = MIN(tf->size - offset, TRUSTED_STUB_SIZE); @@ -437,7 +433,7 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, } /* Store the checksum for one file chunk for checking */ - ret = lib_AESCMACFinish(&aes_cmac, (uint8_t *) s, sizeof *s); + ret = lib_AESCMACFinish(&aes_cmac, (uint8_t*)s, sizeof(*s)); if (ret < 0) goto failed; } @@ -447,7 +443,7 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, /* Finalize and checking if the checksum of the whole file matches * with record given in the manifest. */ - ret = lib_SHA256Final(&sha, (uint8_t *) hash.bytes); + ret = lib_SHA256Final(&sha, (uint8_t*)hash.bytes); if (ret < 0) goto failed; @@ -477,13 +473,11 @@ int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr, return ret; } -int get_file_check_policy(void) -{ +int get_file_check_policy(void) { return g_file_check_policy; } -static void set_file_check_policy (int policy) -{ +static void set_file_check_policy(int policy) { g_file_check_policy = policy; } @@ -517,11 +511,9 @@ static void set_file_check_policy (int policy) * for copying into the buffer. 'size' is the size of the in-enclave buffer. * 'stubs' contain the checksums of all the chunks in a file. */ -int copy_and_verify_trusted_file (const char * path, const void * umem, - uint64_t umem_start, uint64_t umem_end, - void * buffer, uint64_t offset, uint64_t size, - sgx_stub_t * stubs, uint64_t total_size) -{ +int copy_and_verify_trusted_file(const char* path, const void* umem, uint64_t umem_start, + uint64_t umem_end, void* buffer, uint64_t offset, uint64_t size, + sgx_stub_t* stubs, uint64_t total_size) { /* Check that the untrusted mapping is aligned to TRUSTED_STUB_SIZE * and includes the range for copying into the buffer */ assert(IS_ALIGNED(umem_start, TRUSTED_STUB_SIZE)); @@ -534,10 +526,10 @@ int copy_and_verify_trusted_file (const char * path, const void * umem, /* The stubs is an array of 128-bit hash values of the file chunks. * from the beginning of the file. 's' points to the stub that needs to * be checked for the current offset. */ - sgx_stub_t * s = stubs + checking / TRUSTED_STUB_SIZE; + sgx_stub_t* s = stubs + checking / TRUSTED_STUB_SIZE; int ret = 0; - for (; checking < umem_end ; checking += TRUSTED_STUB_SIZE, s++) { + for (; checking < umem_end; checking += TRUSTED_STUB_SIZE, s++) { /* Check one chunk at a time. */ uint64_t checking_size = MIN(total_size - checking, TRUSTED_STUB_SIZE); uint64_t checking_end = checking + checking_size; @@ -547,13 +539,12 @@ int copy_and_verify_trusted_file (const char * path, const void * umem, /* If the checking chunk completely overlaps with the region * needed for copying into the buffer, simplying use the buffer * for checking */ - memcpy(buffer + checking - offset, umem + checking - umem_start, - checking_size); + memcpy(buffer + checking - offset, umem + checking - umem_start, checking_size); /* Storing the checksum (using AES-CMAC) inside hash. */ ret = lib_AESCMAC((uint8_t*)&g_enclave_key, sizeof(g_enclave_key), - buffer + checking - offset, checking_size, - (uint8_t*)&hash, sizeof(hash)); + buffer + checking - offset, checking_size, (uint8_t*)&hash, + sizeof(hash)); } else { /* If the checking chunk only partially overlaps with the region, * read the file content in smaller chunks and only copy the part @@ -566,14 +557,11 @@ int copy_and_verify_trusted_file (const char * path, const void * umem, uint8_t small_chunk[FILE_CHUNK_SIZE]; /* A small buffer */ uint64_t chunk_offset = checking; - for (; chunk_offset < checking_end - ; chunk_offset += FILE_CHUNK_SIZE) { - uint64_t chunk_size = MIN(checking_end - chunk_offset, - FILE_CHUNK_SIZE); + for (; chunk_offset < checking_end; chunk_offset += FILE_CHUNK_SIZE) { + uint64_t chunk_size = MIN(checking_end - chunk_offset, FILE_CHUNK_SIZE); /* Copy into the small buffer before hashing the content */ - memcpy(small_chunk, umem + (chunk_offset - umem_start), - chunk_size); + memcpy(small_chunk, umem + (chunk_offset - umem_start), chunk_size); /* Update the hash for the current chunk */ ret = lib_AESCMACUpdate(&aes_cmac, small_chunk, chunk_size); @@ -613,8 +601,9 @@ int copy_and_verify_trusted_file (const char * path, const void * umem, * XXX: Maybe we should zero the buffer after denying the access? */ if (memcmp(s, &hash, sizeof(sgx_stub_t))) { - SGX_DBG(DBG_E, "Accesing file:%s is denied. Does not match with MAC" - " at chunk starting at %lu-%lu.\n", + SGX_DBG(DBG_E, + "Accesing file:%s is denied. Does not match with MAC at chunk starting at " + "%lu-%lu.\n", path, checking, checking_end); return -PAL_ERROR_DENIED; } @@ -713,9 +702,9 @@ static int register_trusted_file(const char* uri, const char* checksum_str, bool return 0; } -static int init_trusted_file (const char * key, const char * uri) -{ - char cskey[URI_MAX], * tmp; +static int init_trusted_file(const char* key, const char* uri) { + char cskey[URI_MAX]; + char* tmp; char checksum[URI_MAX]; char normpath[URI_MAX]; @@ -736,9 +725,7 @@ static int init_trusted_file (const char * key, const char * uri) size_t len = sizeof(normpath) - URI_PREFIX_FILE_LEN; ret = get_norm_path(uri + URI_PREFIX_FILE_LEN, normpath + URI_PREFIX_FILE_LEN, &len); if (ret < 0) { - SGX_DBG(DBG_E, - "Path (%s) normalization failed: %s\n", - uri + URI_PREFIX_FILE_LEN, + SGX_DBG(DBG_E, "Path (%s) normalization failed: %s\n", uri + URI_PREFIX_FILE_LEN, pal_strerror(ret)); return ret; } @@ -746,7 +733,7 @@ static int init_trusted_file (const char * key, const char * uri) return register_trusted_file(normpath, checksum, /*check_duplicates=*/false); } -int init_trusted_files (void) { +int init_trusted_files(void) { struct config_store* store = g_pal_state.root_config; char* cfgbuf = NULL; ssize_t cfgsize; @@ -772,10 +759,12 @@ int init_trusted_files (void) { if (len > 0) { int npreload = 0; char key[10]; - const char * start, * end; + const char* start; + const char* end; - for (start = cfgbuf ; start < cfgbuf + len ; start = end + 1) { - for (end = start ; end < cfgbuf + len && *end && *end != ',' ; end++); + for (start = cfgbuf; start < cfgbuf + len; start = end + 1) { + for (end = start; end < cfgbuf + len && *end && *end != ','; end++) + ; if (end > start) { char uri[end - start + 1]; memcpy(uri, start, end - start); @@ -800,7 +789,6 @@ int init_trusted_files (void) { goto out; } - nuris = get_config_entries(store, "sgx.trusted_files", cfgbuf, cfgsize); if (nuris <= 0) goto no_trusted; @@ -809,7 +797,7 @@ int init_trusted_files (void) { k = cfgbuf; - for (int i = 0 ; i < nuris ; i++) { + for (int i = 0; i < nuris; i++) { len = strlen(k); memcpy(tmp, k, len + 1); k += len + 1; @@ -842,7 +830,7 @@ int init_trusted_files (void) { k = cfgbuf; - for (int i = 0 ; i < nuris ; i++) { + for (int i = 0; i < nuris; i++) { len = strlen(k); memcpy(tmp, k, len + 1); k += len + 1; @@ -864,13 +852,10 @@ int init_trusted_files (void) { size_t norm_path_len = sizeof(norm_path) - URI_PREFIX_FILE_LEN; - ret = get_norm_path(uri + URI_PREFIX_FILE_LEN, - norm_path + URI_PREFIX_FILE_LEN, + ret = get_norm_path(uri + URI_PREFIX_FILE_LEN, norm_path + URI_PREFIX_FILE_LEN, &norm_path_len); if (ret < 0) { - SGX_DBG(DBG_E, - "Path (%s) normalization failed: %s\n", - uri + URI_PREFIX_FILE_LEN, + SGX_DBG(DBG_E, "Path (%s) normalization failed: %s\n", uri + URI_PREFIX_FILE_LEN, pal_strerror(ret)); goto out; } @@ -891,29 +876,27 @@ int init_trusted_files (void) { return ret; } -int init_trusted_children (void) -{ - struct config_store * store = g_pal_state.root_config; +int init_trusted_children(void) { + struct config_store* store = g_pal_state.root_config; char key[CONFIG_MAX], mrkey[CONFIG_MAX]; char uri[CONFIG_MAX], mr_enclave[CONFIG_MAX]; - char * tmp1 = strcpy_static(key, "sgx.trusted_children.", sizeof(key)); - char * tmp2 = strcpy_static(mrkey, "sgx.trusted_mrenclave.", sizeof(mrkey)); + char* tmp1 = strcpy_static(key, "sgx.trusted_children.", sizeof(key)); + char* tmp2 = strcpy_static(mrkey, "sgx.trusted_mrenclave.", sizeof(mrkey)); ssize_t cfgsize = get_config_entries_size(store, "sgx.trusted_mrenclave"); if (cfgsize <= 0) return 0; - char * cfgbuf = malloc(cfgsize); + char* cfgbuf = malloc(cfgsize); if (!cfgbuf) return -PAL_ERROR_NOMEM; - int nuris = get_config_entries(store, "sgx.trusted_mrenclave", - cfgbuf, cfgsize); + int nuris = get_config_entries(store, "sgx.trusted_mrenclave", cfgbuf, cfgsize); if (nuris > 0) { - char * k = cfgbuf; - for (int i = 0 ; i < nuris ; i++) { + char* k = cfgbuf; + for (int i = 0; i < nuris; i++) { int len = strlen(k); memcpy(tmp1, k, len + 1); memcpy(tmp2, k, len + 1); @@ -932,8 +915,7 @@ int init_trusted_children (void) return 0; } -int init_file_check_policy (void) -{ +int init_file_check_policy(void) { char cfgbuf[CONFIG_MAX]; ssize_t ret = get_config(g_pal_state.root_config, "sgx.file_check_policy", cfgbuf, sizeof(cfgbuf)); @@ -952,8 +934,7 @@ int init_file_check_policy (void) return 0; } -int init_enclave (void) -{ +int init_enclave(void) { // Get report to initialize info (MR_ENCLAVE, etc.) about this enclave from // a trusted source. @@ -1033,7 +1014,7 @@ int _DkStreamKeyExchange(PAL_HANDLE stream, PAL_SESSION_KEY* key) { } } - for (bytes = 0, ret = 0 ; bytes < DH_SIZE ; bytes += ret) { + for (bytes = 0, ret = 0; bytes < DH_SIZE; bytes += ret) { ret = _DkStreamRead(stream, 0, DH_SIZE - bytes, pub + bytes, NULL, 0); if (ret < 0) { if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) { @@ -1069,7 +1050,6 @@ int _DkStreamKeyExchange(PAL_HANDLE stream, PAL_SESSION_KEY* key) { goto out; } - SGX_DBG(DBG_S, "Key exchange succeeded: %s\n", ALLOCA_BYTES2HEXSTR(*key)); ret = 0; out: @@ -1111,9 +1091,8 @@ int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data, } /* B -> A: report[B -> A] */ - for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) { - ret = _DkStreamRead(stream, 0, sizeof(report) - bytes, - ((void*)&report) + bytes, NULL, 0); + for (bytes = 0, ret = 0; bytes < sizeof(report); bytes += ret) { + ret = _DkStreamRead(stream, 0, sizeof(report) - bytes, ((void*)&report) + bytes, NULL, 0); if (ret < 0) { if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) { ret = 0; @@ -1142,7 +1121,9 @@ int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data, } if (ret == 1) { - SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n", + SGX_DBG(DBG_E, + "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in " + "the manifest file?\n", ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m)); ret = -PAL_ERROR_DENIED; goto out; @@ -1151,7 +1132,7 @@ int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data, SGX_DBG(DBG_S, "Local attestation succeeded!\n"); /* A -> B: report[A -> B] */ - memcpy(&target_info.mr_enclave , &report.body.mr_enclave, sizeof(sgx_measurement_t)); + memcpy(&target_info.mr_enclave, &report.body.mr_enclave, sizeof(sgx_measurement_t)); memcpy(&target_info.attributes, &report.body.attributes, sizeof(sgx_attributes_t)); ret = __sgx_get_report(&target_info, data, &report); @@ -1160,9 +1141,8 @@ int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data, goto out; } - for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) { - ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes, - ((void*)&report) + bytes, NULL, 0); + for (bytes = 0, ret = 0; bytes < sizeof(report); bytes += ret) { + ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes, ((void*)&report) + bytes, NULL, 0); if (ret < 0) { if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) { ret = 0; @@ -1196,7 +1176,7 @@ int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data, memset(&target_info, 0, sizeof(target_info)); /* A -> B: targetinfo[A] */ - for (bytes = 0, ret = 0 ; bytes < SGX_TARGETINFO_FILLED_SIZE ; bytes += ret) { + for (bytes = 0, ret = 0; bytes < SGX_TARGETINFO_FILLED_SIZE; bytes += ret) { ret = _DkStreamRead(stream, 0, SGX_TARGETINFO_FILLED_SIZE - bytes, ((void*)&target_info) + bytes, NULL, 0); if (ret < 0) { @@ -1216,9 +1196,8 @@ int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data, goto out; } - for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) { - ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes, - ((void*)&report) + bytes, NULL, 0); + for (bytes = 0, ret = 0; bytes < sizeof(report); bytes += ret) { + ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes, ((void*)&report) + bytes, NULL, 0); if (ret < 0) { if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) { ret = 0; @@ -1230,9 +1209,8 @@ int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data, } /* A -> B: report[A -> B] */ - for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) { - ret = _DkStreamRead(stream, 0, sizeof(report) - bytes, - ((void*)&report) + bytes, NULL, 0); + for (bytes = 0, ret = 0; bytes < sizeof(report); bytes += ret) { + ret = _DkStreamRead(stream, 0, sizeof(report) - bytes, ((void*)&report) + bytes, NULL, 0); if (ret < 0) { if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) { ret = 0; @@ -1261,7 +1239,9 @@ int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data, } if (ret == 1) { - SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n", + SGX_DBG(DBG_E, + "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in " + "the manifest file?\n", ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m)); ret = -PAL_ERROR_DENIED; goto out; @@ -1287,7 +1267,6 @@ int _DkStreamSecureInit(PAL_HANDLE stream, bool is_server, PAL_SESSION_KEY* sess else return -PAL_ERROR_BADHANDLE; - LIB_SSL_CONTEXT* ssl_ctx = malloc(sizeof(*ssl_ctx)); if (!ssl_ctx) return -PAL_ERROR_NOMEM; diff --git a/Pal/src/host/Linux-SGX/enclave_ocalls.c b/Pal/src/host/Linux-SGX/enclave_ocalls.c index 228dea3614..ad6d08cd45 100644 --- a/Pal/src/host/Linux-SGX/enclave_ocalls.c +++ b/Pal/src/host/Linux-SGX/enclave_ocalls.c @@ -2,15 +2,16 @@ * This is for enclave to make ocalls to untrusted runtime. */ -#include +#include "enclave_ocalls.h" + #include #include #include #include #include +#include "api.h" #include "ecall_types.h" -#include "enclave_ocalls.h" #include "ocall_types.h" #include "pal_debug.h" #include "pal_internal.h" @@ -27,7 +28,8 @@ * size of 8MB. Thus, 512KB limit also works well for the main thread. */ #define MAX_UNTRUSTED_STACK_BUF (THREAD_STACK_SIZE / 4) -/* global pointer to a single untrusted queue, all accesses must be protected by g_rpc_queue->lock */ +/* global pointer to a single untrusted queue, all accesses must be protected by g_rpc_queue->lock + */ rpc_queue_t* g_rpc_queue; static long sgx_exitless_ocall(uint64_t code, void* ms) { @@ -122,9 +124,8 @@ static long sgx_exitless_ocall(uint64_t code, void* ms) { return READ_ONCE(req->result); } -noreturn void ocall_exit(int exitcode, int is_exitgroup) -{ - ms_ocall_exit_t * ms; +noreturn void ocall_exit(int exitcode, int is_exitgroup) { + ms_ocall_exit_t* ms; sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -211,8 +212,8 @@ static int ocall_mmap_untrusted_cache(size_t size, void** mem, bool* need_munmap *need_munmap = false; struct untrusted_area* cache = &get_tcb_trts()->untrusted_area_cache; uint64_t in_use = 0; - if (!__atomic_compare_exchange_n(&cache->in_use, &in_use, 1, /*weak=*/false, - __ATOMIC_RELAXED, __ATOMIC_RELAXED)) { + if (!__atomic_compare_exchange_n(&cache->in_use, &in_use, 1, /*weak=*/false, __ATOMIC_RELAXED, + __ATOMIC_RELAXED)) { /* AEX signal handling case: cache is in use, so make explicit mmap/munmap */ int retval = ocall_mmap_untrusted(-1, 0, size, PROT_READ | PROT_WRITE, mem); if (IS_ERR(retval)) { @@ -242,8 +243,8 @@ static int ocall_mmap_untrusted_cache(size_t size, void** mem, bool* need_munmap __atomic_store_n(&cache->in_use, 0, __ATOMIC_RELAXED); } else { cache->valid = true; - cache->mem = *mem; - cache->size = size; + cache->mem = *mem; + cache->size = size; } return retval; } @@ -258,11 +259,9 @@ static void ocall_munmap_untrusted_cache(void* mem, size_t size, bool need_munma } } -int ocall_cpuid (unsigned int leaf, unsigned int subleaf, - unsigned int values[4]) -{ +int ocall_cpuid(unsigned int leaf, unsigned int subleaf, unsigned int values[4]) { int retval = 0; - ms_ocall_cpuid_t * ms; + ms_ocall_cpuid_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -287,11 +286,10 @@ int ocall_cpuid (unsigned int leaf, unsigned int subleaf, return retval; } -int ocall_open (const char * pathname, int flags, unsigned short mode) -{ +int ocall_open(const char* pathname, int flags, unsigned short mode) { int retval = 0; int len = pathname ? strlen(pathname) + 1 : 0; - ms_ocall_open_t * ms; + ms_ocall_open_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -315,10 +313,9 @@ int ocall_open (const char * pathname, int flags, unsigned short mode) return retval; } -int ocall_close (int fd) -{ +int ocall_close(int fd) { int retval = 0; - ms_ocall_close_t *ms; + ms_ocall_close_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -558,10 +555,9 @@ ssize_t ocall_pwrite(int fd, const void* buf, size_t count, off_t offset) { return retval; } -int ocall_fstat (int fd, struct stat * buf) -{ +int ocall_fstat(int fd, struct stat* buf) { int retval = 0; - ms_ocall_fstat_t * ms; + ms_ocall_fstat_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -582,10 +578,9 @@ int ocall_fstat (int fd, struct stat * buf) return retval; } -int ocall_fionread (int fd) -{ +int ocall_fionread(int fd) { int retval = 0; - ms_ocall_fionread_t * ms; + ms_ocall_fionread_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -602,10 +597,9 @@ int ocall_fionread (int fd) return retval; } -int ocall_fsetnonblock (int fd, int nonblocking) -{ +int ocall_fsetnonblock(int fd, int nonblocking) { int retval = 0; - ms_ocall_fsetnonblock_t * ms; + ms_ocall_fsetnonblock_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -623,10 +617,9 @@ int ocall_fsetnonblock (int fd, int nonblocking) return retval; } -int ocall_fchmod (int fd, unsigned short mode) -{ +int ocall_fchmod(int fd, unsigned short mode) { int retval = 0; - ms_ocall_fchmod_t * ms; + ms_ocall_fchmod_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -644,10 +637,9 @@ int ocall_fchmod (int fd, unsigned short mode) return retval; } -int ocall_fsync (int fd) -{ +int ocall_fsync(int fd) { int retval = 0; - ms_ocall_fsync_t * ms; + ms_ocall_fsync_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -664,10 +656,9 @@ int ocall_fsync (int fd) return retval; } -int ocall_ftruncate (int fd, uint64_t length) -{ +int ocall_ftruncate(int fd, uint64_t length) { int retval = 0; - ms_ocall_ftruncate_t * ms; + ms_ocall_ftruncate_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -685,11 +676,10 @@ int ocall_ftruncate (int fd, uint64_t length) return retval; } -int ocall_mkdir (const char * pathname, unsigned short mode) -{ +int ocall_mkdir(const char* pathname, unsigned short mode) { int retval = 0; int len = pathname ? strlen(pathname) + 1 : 0; - ms_ocall_mkdir_t * ms; + ms_ocall_mkdir_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -767,21 +757,20 @@ int ocall_getdents(int fd, struct linux_dirent64* dirp, size_t dirp_size) { return retval; } -int ocall_resume_thread (void * tcs) -{ +int ocall_resume_thread(void* tcs) { return sgx_exitless_ocall(OCALL_RESUME_THREAD, tcs); } -int ocall_clone_thread (void) -{ +int ocall_clone_thread(void) { void* dummy = NULL; return sgx_exitless_ocall(OCALL_CLONE_THREAD, dummy); } -int ocall_create_process(const char* uri, int nargs, const char** args, int* stream_fd, unsigned int* pid) { +int ocall_create_process(const char* uri, int nargs, const char** args, int* stream_fd, + unsigned int* pid) { int retval = 0; int ulen = uri ? strlen(uri) + 1 : 0; - ms_ocall_create_process_t * ms; + ms_ocall_create_process_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms) + nargs * sizeof(char*), alignof(*ms)); @@ -798,7 +787,7 @@ int ocall_create_process(const char* uri, int nargs, const char** args, int* str WRITE_ONCE(ms->ms_uri, untrusted_uri); WRITE_ONCE(ms->ms_nargs, nargs); - for (int i = 0 ; i < nargs ; i++) { + for (int i = 0; i < nargs; i++) { int len = args[i] ? strlen(args[i]) + 1 : 0; void* unstrusted_arg = args[i] ? sgx_copy_to_ustack(args[i], len) : NULL; @@ -824,7 +813,7 @@ int ocall_create_process(const char* uri, int nargs, const char** args, int* str int ocall_futex(uint32_t* futex, int op, int val, int64_t timeout_us) { int retval = 0; - ms_ocall_futex_t * ms; + ms_ocall_futex_t* ms; if (!sgx_is_completely_outside_enclave(futex, sizeof(uint32_t))) { return -EINVAL; @@ -848,11 +837,9 @@ int ocall_futex(uint32_t* futex, int op, int val, int64_t timeout_us) { return retval; } -int ocall_socketpair (int domain, int type, int protocol, - int sockfds[2]) -{ +int ocall_socketpair(int domain, int type, int protocol, int sockfds[2]) { int retval = 0; - ms_ocall_socketpair_t * ms; + ms_ocall_socketpair_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -876,8 +863,8 @@ int ocall_socketpair (int domain, int type, int protocol, return retval; } -int ocall_listen(int domain, int type, int protocol, int ipv6_v6only, - struct sockaddr* addr, size_t* addrlen, struct sockopt* sockopt) { +int ocall_listen(int domain, int type, int protocol, int ipv6_v6only, struct sockaddr* addr, + size_t* addrlen, struct sockopt* sockopt) { int retval = 0; size_t len = addrlen ? *addrlen : 0; ms_ocall_listen_t* ms; @@ -1022,7 +1009,7 @@ ssize_t ocall_recv(int sockfd, void* buf, size_t count, struct sockaddr* addr, s void* obuf = NULL; bool is_obuf_mapped = false; size_t addrlen = addrlenptr ? *addrlenptr : 0; - size_t controllen = controllenptr ? *controllenptr : 0; + size_t controllen = controllenptr ? *controllenptr : 0; ms_ocall_recv_t* ms; bool need_munmap = false; @@ -1202,10 +1189,9 @@ int ocall_setsockopt(int sockfd, int level, int optname, const void* optval, siz return retval; } -int ocall_shutdown (int sockfd, int how) -{ +int ocall_shutdown(int sockfd, int how) { int retval = 0; - ms_ocall_shutdown_t * ms; + ms_ocall_shutdown_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -1236,7 +1222,7 @@ int ocall_gettime(uint64_t* microsec) { do { retval = sgx_exitless_ocall(OCALL_GETTIME, ms); - } while(retval == -EINTR); + } while (retval == -EINTR); if (!retval) *microsec = READ_ONCE(ms->ms_microsec); @@ -1246,7 +1232,7 @@ int ocall_gettime(uint64_t* microsec) { int ocall_sleep(uint64_t* microsec) { int retval = 0; - ms_ocall_sleep_t * ms; + ms_ocall_sleep_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -1315,12 +1301,11 @@ int ocall_poll(struct pollfd* fds, size_t nfds, int64_t timeout_us) { return retval; } -int ocall_rename (const char * oldpath, const char * newpath) -{ +int ocall_rename(const char* oldpath, const char* newpath) { int retval = 0; int oldlen = oldpath ? strlen(oldpath) + 1 : 0; int newlen = newpath ? strlen(newpath) + 1 : 0; - ms_ocall_rename_t * ms; + ms_ocall_rename_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -1344,11 +1329,10 @@ int ocall_rename (const char * oldpath, const char * newpath) return retval; } -int ocall_delete (const char * pathname) -{ +int ocall_delete(const char* pathname) { int retval = 0; int len = pathname ? strlen(pathname) + 1 : 0; - ms_ocall_delete_t * ms; + ms_ocall_delete_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); @@ -1370,28 +1354,26 @@ int ocall_delete (const char * pathname) return retval; } -int ocall_load_debug(const char * command) -{ +int ocall_load_debug(const char* command) { int retval = 0; int len = strlen(command) + 1; void* old_ustack = sgx_prepare_ustack(); - const char * ms = sgx_copy_to_ustack(command, len); + const char* ms = sgx_copy_to_ustack(command, len); if (!ms) { sgx_reset_ustack(old_ustack); return -EPERM; } - retval = sgx_exitless_ocall(OCALL_LOAD_DEBUG, (void *) ms); + retval = sgx_exitless_ocall(OCALL_LOAD_DEBUG, (void*)ms); sgx_reset_ustack(old_ustack); return retval; } -int ocall_eventfd (unsigned int initval, int flags) -{ +int ocall_eventfd(unsigned int initval, int flags) { int retval = 0; - ms_ocall_eventfd_t * ms; + ms_ocall_eventfd_t* ms; void* old_ustack = sgx_prepare_ustack(); ms = sgx_alloc_on_ustack_aligned(sizeof(*ms), alignof(*ms)); diff --git a/Pal/src/host/Linux-SGX/enclave_ocalls.h b/Pal/src/host/Linux-SGX/enclave_ocalls.h index 0c612fec5f..126ad1a258 100644 --- a/Pal/src/host/Linux-SGX/enclave_ocalls.h +++ b/Pal/src/host/Linux-SGX/enclave_ocalls.h @@ -2,27 +2,26 @@ * This is for enclave to make ocalls to untrusted runtime. */ -#include "pal_linux.h" - #include -#include #include +#include #include -noreturn void ocall_exit (int exitcode, int is_exitgroup); +#include "linux_types.h" +#include "pal_linux.h" +#include "sgx_attest.h" + +noreturn void ocall_exit(int exitcode, int is_exitgroup); -int ocall_mmap_untrusted (int fd, uint64_t offset, - uint64_t size, unsigned short prot, - void ** mem); +int ocall_mmap_untrusted(int fd, uint64_t offset, uint64_t size, unsigned short prot, void** mem); -int ocall_munmap_untrusted (const void * mem, uint64_t size); +int ocall_munmap_untrusted(const void* mem, uint64_t size); -int ocall_cpuid (unsigned int leaf, unsigned int subleaf, - unsigned int values[4]); +int ocall_cpuid(unsigned int leaf, unsigned int subleaf, unsigned int values[4]); -int ocall_open (const char * pathname, int flags, unsigned short mode); +int ocall_open(const char* pathname, int flags, unsigned short mode); -int ocall_close (int fd); +int ocall_close(int fd); ssize_t ocall_read(int fd, void* buf, size_t count); @@ -32,19 +31,19 @@ ssize_t ocall_pread(int fd, void* buf, size_t count, off_t offset); ssize_t ocall_pwrite(int fd, const void* buf, size_t count, off_t offset); -int ocall_fstat (int fd, struct stat * buf); +int ocall_fstat(int fd, struct stat* buf); -int ocall_fionread (int fd); +int ocall_fionread(int fd); -int ocall_fsetnonblock (int fd, int nonblocking); +int ocall_fsetnonblock(int fd, int nonblocking); -int ocall_fchmod (int fd, unsigned short mode); +int ocall_fchmod(int fd, unsigned short mode); -int ocall_fsync (int fd); +int ocall_fsync(int fd); -int ocall_ftruncate (int fd, uint64_t length); +int ocall_ftruncate(int fd, uint64_t length); -int ocall_mkdir (const char *pathname, unsigned short mode); +int ocall_mkdir(const char* pathname, unsigned short mode); int ocall_getdents(int fd, struct linux_dirent64* dirp, size_t size); @@ -65,31 +64,32 @@ ssize_t ocall_send(int sockfd, const void* buf, size_t count, const struct socka int ocall_setsockopt(int sockfd, int level, int optname, const void* optval, size_t optlen); -int ocall_shutdown (int sockfd, int how); +int ocall_shutdown(int sockfd, int how); -int ocall_resume_thread (void * tcs); +int ocall_resume_thread(void* tcs); -int ocall_clone_thread (void); +int ocall_clone_thread(void); -int ocall_create_process(const char* uri, int nargs, const char** args, int* stream_fd, unsigned int* pid); +int ocall_create_process(const char* uri, int nargs, const char** args, int* stream_fd, + unsigned int* pid); -int ocall_futex(uint32_t *uaddr, int op, int val, int64_t timeout_us); +int ocall_futex(uint32_t* uaddr, int op, int val, int64_t timeout_us); int ocall_gettime(uint64_t* microsec); int ocall_sleep(uint64_t* microsec); -int ocall_socketpair (int domain, int type, int protocol, int sockfds[2]); +int ocall_socketpair(int domain, int type, int protocol, int sockfds[2]); int ocall_poll(struct pollfd* fds, size_t nfds, int64_t timeout_us); -int ocall_rename (const char * oldpath, const char * newpath); +int ocall_rename(const char* oldpath, const char* newpath); -int ocall_delete (const char * pathname); +int ocall_delete(const char* pathname); -int ocall_load_debug (const char * command); +int ocall_load_debug(const char* command); -int ocall_eventfd (unsigned int initval, int flags); +int ocall_eventfd(unsigned int initval, int flags); /*! * \brief Execute untrusted code in PAL to obtain a quote from the Quoting Enclave. diff --git a/Pal/src/host/Linux-SGX/enclave_pages.c b/Pal/src/host/Linux-SGX/enclave_pages.c index a7a58ca26c..a120f82b74 100644 --- a/Pal/src/host/Linux-SGX/enclave_pages.c +++ b/Pal/src/host/Linux-SGX/enclave_pages.c @@ -1,5 +1,6 @@ -#include "api.h" #include "enclave_pages.h" + +#include "api.h" #include "list.h" #include "pal_error.h" #include "pal_internal.h" @@ -93,8 +94,8 @@ int init_enclave_pages(void) { goto out; } - exec_vma->bottom = g_pal_sec.exec_addr; - exec_vma->top = g_pal_sec.exec_addr + g_pal_sec.exec_size; + exec_vma->bottom = g_pal_sec.exec_addr; + exec_vma->top = g_pal_sec.exec_addr + g_pal_sec.exec_size; exec_vma->is_pal_internal = false; INIT_LIST_HEAD(exec_vma, list); LISTP_ADD(exec_vma, &g_heap_vma_list, list); @@ -133,9 +134,9 @@ static void* __create_vma_and_merge(void* addr, size_t size, bool is_pal_interna struct heap_vma* check_vma_above = vma_above; while (check_vma_above && addr + size > check_vma_above->bottom) { if (check_vma_above->is_pal_internal != is_pal_internal) { - SGX_DBG(DBG_M, "VMA %p-%p (internal=%d) overlaps with %p-%p (internal=%d)\n", - addr, addr + size, is_pal_internal, check_vma_above->bottom, - check_vma_above->top, check_vma_above->is_pal_internal); + SGX_DBG(DBG_M, "VMA %p-%p (internal=%d) overlaps with %p-%p (internal=%d)\n", addr, + addr + size, is_pal_internal, check_vma_above->bottom, check_vma_above->top, + check_vma_above->is_pal_internal); return NULL; } check_vma_above = LISTP_PREV_ENTRY(check_vma_above, &g_heap_vma_list, list); @@ -145,9 +146,9 @@ static void* __create_vma_and_merge(void* addr, size_t size, bool is_pal_interna struct heap_vma* check_vma_below = vma_below; while (check_vma_below && addr < check_vma_below->top) { if (check_vma_below->is_pal_internal != is_pal_internal) { - SGX_DBG(DBG_M, "VMA %p-%p (internal=%d) overlaps with %p-%p (internal=%d)\n", - addr, addr + size, is_pal_internal, check_vma_below->bottom, - check_vma_below->top, check_vma_below->is_pal_internal); + SGX_DBG(DBG_M, "VMA %p-%p (internal=%d) overlaps with %p-%p (internal=%d)\n", addr, + addr + size, is_pal_internal, check_vma_below->bottom, check_vma_below->top, + check_vma_below->is_pal_internal); return NULL; } check_vma_below = LISTP_NEXT_ENTRY(check_vma_below, &g_heap_vma_list, list); @@ -172,8 +173,8 @@ static void* __create_vma_and_merge(void* addr, size_t size, bool is_pal_interna while (vma_above && vma_above->bottom <= vma->top && vma_above->is_pal_internal == vma->is_pal_internal) { /* newly created VMA grows into above VMA; expand newly created VMA and free above-VMA */ - SGX_DBG(DBG_M, "Merge %p-%p and %p-%p\n", vma->bottom, vma->top, - vma_above->bottom, vma_above->top); + SGX_DBG(DBG_M, "Merge %p-%p and %p-%p\n", vma->bottom, vma->top, vma_above->bottom, + vma_above->top); freed += vma_above->top - vma_above->bottom; struct heap_vma* vma_above_above = LISTP_PREV_ENTRY(vma_above, &g_heap_vma_list, list); @@ -189,8 +190,8 @@ static void* __create_vma_and_merge(void* addr, size_t size, bool is_pal_interna while (vma_below && vma_below->top >= vma->bottom && vma_below->is_pal_internal == vma->is_pal_internal) { /* newly created VMA grows into below VMA; expand newly create VMA and free below-VMA */ - SGX_DBG(DBG_M, "Merge %p-%p and %p-%p\n", vma->bottom, vma->top, - vma_below->bottom, vma_below->top); + SGX_DBG(DBG_M, "Merge %p-%p and %p-%p\n", vma->bottom, vma->top, vma_below->bottom, + vma_below->top); freed += vma_below->top - vma_below->bottom; struct heap_vma* vma_below_below = LISTP_NEXT_ENTRY(vma_below, &g_heap_vma_list, list); @@ -256,7 +257,8 @@ void* get_enclave_pages(void* addr, size_t size, bool is_pal_internal) { LISTP_FOR_EACH_ENTRY(vma, &g_heap_vma_list, list) { if (vma->top < vma_above_bottom - size) { - ret = __create_vma_and_merge(vma_above_bottom - size, size, is_pal_internal, vma_above); + ret = __create_vma_and_merge(vma_above_bottom - size, size, is_pal_internal, + vma_above); goto out; } vma_above = vma; @@ -281,8 +283,8 @@ int free_enclave_pages(void* addr, size_t size) { size = ALIGN_UP(size, g_page_size); - if (!access_ok(addr, size) || !IS_ALIGNED_PTR(addr, g_page_size) || - addr < g_heap_bottom || addr + size > g_heap_top) { + if (!access_ok(addr, size) || !IS_ALIGNED_PTR(addr, g_page_size) || addr < g_heap_bottom || + addr + size > g_heap_top) { return -PAL_ERROR_INVAL; } @@ -313,8 +315,10 @@ int free_enclave_pages(void* addr, size_t size) { } if (is_pal_internal != vma->is_pal_internal) { - SGX_DBG(DBG_E, "*** Area to free (address %p, size %lu) overlaps with both normal and " - "pal-internal VMAs ***\n", addr, size); + SGX_DBG(DBG_E, + "*** Area to free (address %p, size %lu) overlaps with both normal and " + "pal-internal VMAs ***\n", + addr, size); ret = -PAL_ERROR_INVAL; goto out; } diff --git a/Pal/src/host/Linux-SGX/enclave_pf.c b/Pal/src/host/Linux-SGX/enclave_pf.c index 20e927e425..7a50f94a1a 100644 --- a/Pal/src/host/Linux-SGX/enclave_pf.c +++ b/Pal/src/host/Linux-SGX/enclave_pf.c @@ -40,8 +40,8 @@ static pf_status_t cb_read(pf_handle_t handle, void* buffer, uint64_t offset, si continue; if (read < 0) { - SGX_DBG(DBG_E, "cb_read(%d, %p, %lu, %lu): read failed: %ld\n", - fd, buffer, offset, size, read); + SGX_DBG(DBG_E, "cb_read(%d, %p, %lu, %lu): read failed: %ld\n", fd, buffer, offset, + size, read); return PF_STATUS_CALLBACK_FAILED; } @@ -68,8 +68,8 @@ static pf_status_t cb_write(pf_handle_t handle, const void* buffer, uint64_t off continue; if (written < 0) { - SGX_DBG(DBG_E, "cb_write(%d, %p, %lu, %lu): write failed: %ld\n", - fd, buffer, offset, size, written); + SGX_DBG(DBG_E, "cb_write(%d, %p, %lu, %lu): write failed: %ld\n", fd, buffer, offset, + size, written); return PF_STATUS_CALLBACK_FAILED; } @@ -101,10 +101,9 @@ static void cb_debug(const char* msg) { } #endif -static pf_status_t cb_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - pf_mac_t* mac) { +static pf_status_t cb_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, pf_mac_t* mac) { int ret = lib_AESGCMEncrypt((const uint8_t*)key, sizeof(*key), (const uint8_t*)iv, input, input_size, aad, aad_size, output, (uint8_t*)mac, sizeof(*mac)); if (ret != 0) { @@ -114,10 +113,9 @@ static pf_status_t cb_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, return PF_STATUS_SUCCESS; } -static pf_status_t cb_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - const pf_mac_t* mac) { +static pf_status_t cb_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, const pf_mac_t* mac) { int ret = lib_AESGCMDecrypt((const uint8_t*)key, sizeof(*key), (const uint8_t*)iv, input, input_size, aad, aad_size, output, (const uint8_t*)mac, sizeof(*mac)); @@ -175,8 +173,7 @@ static struct protected_file* find_protected_dir(const char* path) { pf_lock(); // TODO: avoid linear lookup for (tmp = g_protected_dirs; tmp != NULL; tmp = tmp->hh.next) { - if (tmp->path_len < len && - !memcmp(tmp->path, path, tmp->path_len) && + if (tmp->path_len < len && !memcmp(tmp->path, path, tmp->path_len) && (!path[tmp->path_len] || path[tmp->path_len] == '/')) { pf = tmp; break; @@ -311,7 +308,7 @@ static int register_protected_dir(const char* path) { goto out; } free(sub_path); -next: + next: pos += dir->d_reclen; } } while (returned != 0); @@ -456,7 +453,7 @@ static int register_protected_files(const char* key_prefix) { return ret; } -#define PF_MANIFEST_KEY_PREFIX "sgx.protected_files_key" +#define PF_MANIFEST_KEY_PREFIX "sgx.protected_files_key" #define PF_MANIFEST_PATH_PREFIX "sgx.protected_files" /* Initialize the PF library, register PFs from the manifest */ @@ -489,7 +486,7 @@ int init_protected_files(void) { SGX_DBG(DBG_E, "Malformed " PF_MANIFEST_KEY_PREFIX " value in the manifest\n"); return -PAL_ERROR_INVAL; } - g_pf_wrap_key[i/2] = g_pf_wrap_key[i/2] * 16 + (uint8_t)val; + g_pf_wrap_key[i / 2] = g_pf_wrap_key[i / 2] * 16 + (uint8_t)val; } g_pf_wrap_key_set = true; } @@ -525,8 +522,8 @@ static int open_protected_file(const char* path, struct protected_file* pf, pf_h struct protected_file* load_protected_file(const char* path, int* fd, uint64_t size, pf_file_mode_t mode, bool create, struct protected_file* pf) { - SGX_DBG(DBG_D, "load_protected_file: %s, fd %d, size %lu, mode %d, create %d, pf %p\n", - path, *fd, size, mode, create, pf); + SGX_DBG(DBG_D, "load_protected_file: %s, fd %d, size %lu, mode %d, create %d, pf %p\n", path, + *fd, size, mode, create, pf); if (!pf) pf = get_protected_file(path); @@ -572,8 +569,8 @@ int flush_pf_maps(struct protected_file* pf, void* buffer, bool remove) { pfs = pf_get_size(map_pf->context, &pf_size); assert(PF_SUCCESS(pfs)); - SGX_DBG(DBG_D, "flush_pf_maps: pf %p, buf %p, map size %lu, offset %lu\n", - map_pf, map->buffer, map_size, map->offset); + SGX_DBG(DBG_D, "flush_pf_maps: pf %p, buf %p, map size %lu, offset %lu\n", map_pf, + map->buffer, map_size, map->offset); assert(pf_size >= map->offset); if (map->offset + map_size > pf_size) @@ -628,7 +625,7 @@ int set_protected_files_key(const char* pf_key_hex) { pf_unlock(); return -PAL_ERROR_INVAL; } - g_pf_wrap_key[i/2] = g_pf_wrap_key[i/2] * 16 + (uint8_t)val; + g_pf_wrap_key[i / 2] = g_pf_wrap_key[i / 2] * 16 + (uint8_t)val; } g_pf_wrap_key_set = true; pf_unlock(); diff --git a/Pal/src/host/Linux-SGX/enclave_platform.c b/Pal/src/host/Linux-SGX/enclave_platform.c index 4ed7e25b72..90d15c0037 100644 --- a/Pal/src/host/Linux-SGX/enclave_platform.c +++ b/Pal/src/host/Linux-SGX/enclave_platform.c @@ -1,14 +1,14 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2019, Texas A&M University */ -#include -#include -#include -#include +#include "pal_internal.h" +#include "pal_linux.h" +#include "pal_linux_error.h" +#include "pal_security.h" int sgx_get_quote(const sgx_spid_t* spid, const sgx_quote_nonce_t* nonce, - const sgx_report_data_t* report_data, bool linkable, - char** quote, size_t* quote_len) { + const sgx_report_data_t* report_data, bool linkable, char** quote, + size_t* quote_len) { /* must align all arguments to sgx_report() so that EREPORT doesn't complain */ __sgx_mem_aligned sgx_report_t report; __sgx_mem_aligned sgx_target_info_t targetinfo = g_pal_sec.qe_targetinfo; @@ -26,4 +26,4 @@ int sgx_get_quote(const sgx_spid_t* spid, const sgx_quote_nonce_t* nonce, return unix_to_pal_error(ERRNO(ret)); } return 0; - } +} diff --git a/Pal/src/host/Linux-SGX/enclave_untrusted.c b/Pal/src/host/Linux-SGX/enclave_untrusted.c index 26d9e6836b..70c956678c 100644 --- a/Pal/src/host/Linux-SGX/enclave_untrusted.c +++ b/Pal/src/host/Linux-SGX/enclave_untrusted.c @@ -1,13 +1,12 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2014 Stony Brook University */ -#include -#include -#include -#include -#include - +#include "api.h" #include "enclave_ocalls.h" +#include "pal_error.h" +#include "pal_internal.h" +#include "pal_security.h" +#include "spinlock.h" static spinlock_t g_malloc_lock = INIT_SPINLOCK_UNLOCKED; static size_t g_page_size = PRESET_PAGESIZE; diff --git a/Pal/src/host/Linux-SGX/enclave_xstate.c b/Pal/src/host/Linux-SGX/enclave_xstate.c index 449313ced3..594bad4810 100644 --- a/Pal/src/host/Linux-SGX/enclave_xstate.c +++ b/Pal/src/host/Linux-SGX/enclave_xstate.c @@ -35,46 +35,47 @@ * */ -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include "api.h" #include "enclave_pages.h" +#include "list.h" +#include "pal_crypto.h" +#include "pal_debug.h" +#include "pal_error.h" +#include "pal_internal.h" +#include "pal_linux.h" +#include "pal_linux_error.h" +#include "pal_security.h" int g_xsave_enabled = 0; uint64_t g_xsave_features = 0; uint32_t g_xsave_size = 0; -//FXRSTOR only cares about the first 512 bytes, while -//XRSTOR in compacted mode will ignore the first 512 bytes. -const uint32_t g_xsave_reset_state[XSAVE_RESET_STATE_SIZE/sizeof(uint32_t)] -__attribute__((aligned(PAL_XSTATE_ALIGN))) = { - 0x037F, 0, 0, 0, 0, 0, 0x1F80, 0xFFFF, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // XCOMP_BV[63] = 1, compaction mode +// FXRSTOR only cares about the first 512 bytes, while XRSTOR in compacted mode will ignore +// the first 512 bytes. +const uint32_t g_xsave_reset_state[XSAVE_RESET_STATE_SIZE / sizeof(uint32_t)] __attribute__(( + aligned(PAL_XSTATE_ALIGN))) = { + 0x037F, 0, 0, 0, 0, 0, 0x1F80, 0xFFFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // XCOMP_BV[63] = 1, compaction mode }; void init_xsave_size(uint64_t xfrm) { const struct { uint64_t bits; uint32_t size; - } xsave_size_table[] = { // Note that the g_xsave_size should be in ascending order - {SGX_XFRM_LEGACY, 512 + 64}, // 512 for legacy features, 64 for xsave header + } xsave_size_table[] = { + // Note that the g_xsave_size should be in ascending order + {SGX_XFRM_LEGACY, 512 + 64}, // 512 for legacy features, 64 for xsave + // header {SGX_XFRM_AVX, 512 + 64 + 256}, // 256 for YMM0_H - YMM15_H registers {SGX_XFRM_MPX, 512 + 64 + 256 + 256}, // 256 for MPX - {SGX_XFRM_AVX512, 512 + 64 + 256 + 256 + 1600}, // 1600 for k0 - k7, ZMM0_H - ZMM15_H, ZMM16 - ZMM31 + {SGX_XFRM_AVX512, 512 + 64 + 256 + 256 + 1600}, // 1600 for k0 - k7, ZMM0_H - ZMM15_H, + // ZMM16 - ZMM31 }; /* fxsave/fxrstore as fallback */ diff --git a/Pal/src/host/Linux-SGX/generated-offsets.c b/Pal/src/host/Linux-SGX/generated-offsets.c index 55b734ee25..a012bf36ea 100644 --- a/Pal/src/host/Linux-SGX/generated-offsets.c +++ b/Pal/src/host/Linux-SGX/generated-offsets.c @@ -1,7 +1,8 @@ -#include #include +#include #include "ecall_types.h" +#include "generated-offsets-build.h" #include "ocall_types.h" #include "pal.h" #include "pal_linux.h" @@ -17,13 +18,7 @@ #include "sgx.h" #undef __packed -#include - -/* required due to -Wmissing-prototypes */ -void dummy(void); - -void dummy(void) -{ +__attribute__((__used__)) static void dummy(void) { /* defines in sgx_arch.h */ DEFINE(SGX_FLAGS_DEBUG, SGX_FLAGS_DEBUG); DEFINE(SGX_FLAGS_MODE64BIT, SGX_FLAGS_MODE64BIT); @@ -79,8 +74,7 @@ void dummy(void) OFFSET_T(SGX_CPU_CONTEXT_RFLAGS, sgx_cpu_context_t, rflags); OFFSET_T(SGX_CPU_CONTEXT_RIP, sgx_cpu_context_t, rip); DEFINE(SGX_CPU_CONTEXT_SIZE, sizeof(sgx_cpu_context_t)); - DEFINE(SGX_CPU_CONTEXT_XSTATE_ALIGN_SUB, - sizeof(sgx_cpu_context_t) % PAL_XSTATE_ALIGN); + DEFINE(SGX_CPU_CONTEXT_XSTATE_ALIGN_SUB, sizeof(sgx_cpu_context_t) % PAL_XSTATE_ALIGN); /* struct enclave_tls */ OFFSET(SGX_COMMON_SELF, enclave_tls, common.self); diff --git a/Pal/src/host/Linux-SGX/linux_types.h b/Pal/src/host/Linux-SGX/linux_types.h index 952a542bb3..23d03b9bfc 100644 --- a/Pal/src/host/Linux-SGX/linux_types.h +++ b/Pal/src/host/Linux-SGX/linux_types.h @@ -10,9 +10,11 @@ #include #include #include -#include +#include #include +#include "sigset.h" + #ifndef size_t typedef __kernel_size_t size_t; #endif @@ -116,8 +118,6 @@ struct cmsghdr { #define CMSG_SPACE(len) (CMSG_ALIGN(len) + CMSG_ALIGN(sizeof(struct cmsghdr))) #define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr)) + (len)) -#include - struct sockopt { int receivebuf, sendbuf; int receivetimeout, sendtimeout; @@ -142,7 +142,7 @@ typedef unsigned short int sa_family_t; /* Structure large enough to hold any socket address (with the historical exception of AF_UNIX). */ struct sockaddr_storage { - __SOCKADDR_COMMON(ss_); /* Address family, etc. */ + __SOCKADDR_COMMON(ss_); /* Address family, etc. */ char __ss_padding[128 - sizeof(sa_family_t)]; }; diff --git a/Pal/src/host/Linux-SGX/ocall_types.h b/Pal/src/host/Linux-SGX/ocall_types.h index 554d3415eb..c5d479f3d7 100644 --- a/Pal/src/host/Linux-SGX/ocall_types.h +++ b/Pal/src/host/Linux-SGX/ocall_types.h @@ -5,6 +5,7 @@ #include #include #include + #include "linux_types.h" #include "pal.h" #include "sgx_arch.h" @@ -87,7 +88,7 @@ typedef struct { } ms_ocall_cpuid_t; typedef struct { - const char * ms_pathname; + const char* ms_pathname; int ms_flags; unsigned short ms_mode; } ms_ocall_open_t; @@ -98,13 +99,13 @@ typedef struct { typedef struct { int ms_fd; - void * ms_buf; + void* ms_buf; unsigned int ms_count; } ms_ocall_read_t; typedef struct { int ms_fd; - const void * ms_buf; + const void* ms_buf; unsigned int ms_count; } ms_ocall_write_t; @@ -151,22 +152,22 @@ typedef struct { } ms_ocall_ftruncate_t; typedef struct { - const char * ms_pathname; + const char* ms_pathname; unsigned short ms_mode; } ms_ocall_mkdir_t; typedef struct { int ms_fd; - struct linux_dirent64 * ms_dirp; + struct linux_dirent64* ms_dirp; size_t ms_size; } ms_ocall_getdents_t; typedef struct { unsigned int ms_pid; - const char * ms_uri; + const char* ms_uri; int ms_stream_fd; int ms_nargs; - const char * ms_args[]; + const char* ms_args[]; } ms_ocall_create_process_t; typedef struct { @@ -257,12 +258,12 @@ typedef struct { } ms_ocall_poll_t; typedef struct { - const char * ms_oldpath; - const char * ms_newpath; + const char* ms_oldpath; + const char* ms_newpath; } ms_ocall_rename_t; typedef struct { - const char * ms_pathname; + const char* ms_pathname; } ms_ocall_delete_t; typedef struct { diff --git a/Pal/src/host/Linux-SGX/pal_host.h b/Pal/src/host/Linux-SGX/pal_host.h index e29bd82481..46cfbc1f56 100644 --- a/Pal/src/host/Linux-SGX/pal_host.h +++ b/Pal/src/host/Linux-SGX/pal_host.h @@ -11,23 +11,22 @@ #define PAL_HOST_H #ifndef IN_PAL -# error "cannot be included outside PAL" +#error "cannot be included outside PAL" #endif -#include -#include +#include "atomic.h" +#include "list.h" +#include "spinlock.h" typedef spinlock_t PAL_LOCK; -#define LOCK_INIT INIT_SPINLOCK_UNLOCKED -#define _DkInternalLock spinlock_lock -#define _DkInternalUnlock spinlock_unlock +#define LOCK_INIT INIT_SPINLOCK_UNLOCKED +#define _DkInternalLock spinlock_lock +#define _DkInternalUnlock spinlock_unlock #define _DkInternalIsLocked spinlock_is_locked -void * malloc_untrusted (int size); -void free_untrusted (void * mem); - -#include +void* malloc_untrusted(int size); +void free_untrusted(void* mem); /* Simpler mutex design: a single variable that tracks whether the * mutex is locked. State is 1 (locked) or 0 (unlocked). @@ -44,8 +43,12 @@ struct mutex_handle { }; /* Initializer of Mutexes */ -#define MUTEX_HANDLE_INIT { .u = 0 } -#define INIT_MUTEX_HANDLE(m) do { (m)->u = 0; } while (0) +#define MUTEX_HANDLE_INIT \ + { .u = 0 } +#define INIT_MUTEX_HANDLE(m) \ + do { \ + (m)->u = 0; \ + } while (0) DEFINE_LIST(pal_handle_thread); struct pal_handle_thread { @@ -53,7 +56,7 @@ struct pal_handle_thread { PAL_IDX tid; PAL_PTR tcs; LIST_TYPE(pal_handle_thread) list; - void * param; + void* param; }; typedef struct { @@ -63,8 +66,7 @@ typedef struct { /* RPC streams are encrypted with 256-bit AES keys */ typedef uint8_t PAL_SESSION_KEY[32]; -typedef struct pal_handle -{ +typedef struct pal_handle { /* * Here we define the internal structure of PAL_HANDLE. * user has no access to the content inside these handles. @@ -162,12 +164,12 @@ typedef struct pal_handle } event; }; }; -} * PAL_HANDLE; +}* PAL_HANDLE; -#define RFD(n) (1 << (MAX_FDS*0 + (n))) -#define WFD(n) (1 << (MAX_FDS*1 + (n))) -#define ERROR(n) (1 << (MAX_FDS*2 + (n))) +#define RFD(n) (1 << (MAX_FDS * 0 + (n))) +#define WFD(n) (1 << (MAX_FDS * 1 + (n))) +#define ERROR(n) (1 << (MAX_FDS * 2 + (n))) -#define HANDLE_TYPE(handle) ((handle)->hdr.type) +#define HANDLE_TYPE(handle) ((handle)->hdr.type) #endif /* PAL_HOST_H */ diff --git a/Pal/src/host/Linux-SGX/pal_linux.h b/Pal/src/host/Linux-SGX/pal_linux.h index 2262429713..be43931853 100644 --- a/Pal/src/host/Linux-SGX/pal_linux.h +++ b/Pal/src/host/Linux-SGX/pal_linux.h @@ -4,84 +4,79 @@ #ifndef PAL_LINUX_H #define PAL_LINUX_H +#include +#include + #include "api.h" #include "assert.h" +#include "enclave_ocalls.h" +#include "linux_types.h" #include "pal.h" #include "pal_crypto.h" #include "pal_defs.h" #include "pal_linux_defs.h" - -#include "linux_types.h" +#include "protected_files.h" #include "sgx_api.h" #include "sgx_arch.h" #include "sgx_attest.h" #include "sgx_tls.h" - -#include "enclave_ocalls.h" -#include "protected_files.h" -#include "uthash.h" - -#include - #include "sysdep-arch.h" +#include "uthash.h" -#define IS_ERR INTERNAL_SYSCALL_ERROR +#define IS_ERR INTERNAL_SYSCALL_ERROR #define IS_ERR_P INTERNAL_SYSCALL_ERROR_P -#define ERRNO INTERNAL_SYSCALL_ERRNO -#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P +#define ERRNO INTERNAL_SYSCALL_ERRNO +#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P extern struct pal_linux_state { - PAL_NUM parent_process_id; - PAL_NUM process_id; + PAL_NUM parent_process_id; + PAL_NUM process_id; - const char** host_environ; + const char** host_environ; /* credentials */ - unsigned int uid, gid; + unsigned int uid, gid; /* currently enabled signals */ - __sigset_t sigset; - __sigset_t blocked_signals; + __sigset_t sigset; + __sigset_t blocked_signals; /* enclave */ - const char * runtime_dir; + const char* runtime_dir; } g_linux_state; -#include - #define DEFAULT_BACKLOG 2048 -#define ACCESS_R 4 -#define ACCESS_W 2 -#define ACCESS_X 1 +#define ACCESS_R 4 +#define ACCESS_W 2 +#define ACCESS_X 1 struct stat; -bool stataccess (struct stat * stats, int acc); +bool stataccess(struct stat* stats, int acc); int init_child_process(PAL_HANDLE* parent); #ifdef IN_ENCLAVE struct pal_sec; -noreturn void pal_linux_main(char* uptr_libpal_uri, size_t libpal_uri_len, - char* uptr_args, size_t args_size, - char* uptr_env, size_t env_size, +noreturn void pal_linux_main(char* uptr_libpal_uri, size_t libpal_uri_len, char* uptr_args, + size_t args_size, char* uptr_env, size_t env_size, struct pal_sec* uptr_sec_info); -void pal_start_thread (void); +void pal_start_thread(void); struct link_map; void setup_pal_map(struct link_map* map); /* Locking and unlocking of Mutexes */ -int __DkMutexCreate (struct mutex_handle * mut); -int _DkMutexAtomicCreate (struct mutex_handle * mut); -int __DkMutexDestroy (struct mutex_handle * mut); +int __DkMutexCreate(struct mutex_handle* mut); +int _DkMutexAtomicCreate(struct mutex_handle* mut); +int __DkMutexDestroy(struct mutex_handle* mut); int _DkMutexLock(struct mutex_handle* mut); int _DkMutexLockTimeout(struct mutex_handle* mut, int64_t timeout_us); -int _DkMutexUnlock (struct mutex_handle * mut); +int _DkMutexUnlock(struct mutex_handle* mut); -int * get_futex (void); -void free_futex (int * futex); +int* get_futex(void); +void free_futex(int* futex); extern char __text_start, __text_end, __data_start, __data_end; #define TEXT_START ((void*)(&__text_start)) @@ -89,8 +84,12 @@ extern char __text_start, __text_end, __data_start, __data_end; #define DATA_START ((void*)(&__text_start)) #define DATA_END ((void*)(&__text_end)) -typedef struct { char bytes[32]; } sgx_checksum_t; -typedef struct { char bytes[16]; } sgx_stub_t; +typedef struct { + char bytes[32]; +} sgx_checksum_t; +typedef struct { + char bytes[16]; +} sgx_stub_t; extern int g_xsave_enabled; extern uint64_t g_xsave_features; @@ -103,11 +102,11 @@ void save_xregs(PAL_XREGS_STATE* xsave_area); void restore_xregs(const PAL_XREGS_STATE* xsave_area); noreturn void _restore_sgx_context(sgx_cpu_context_t* uc, PAL_XREGS_STATE* xsave_area); -void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, PAL_XREGS_STATE* xregs_state); +void _DkExceptionHandler(unsigned int exit_info, sgx_cpu_context_t* uc, + PAL_XREGS_STATE* xregs_state); void _DkHandleExternalEvent(PAL_NUM event, sgx_cpu_context_t* uc, PAL_XREGS_STATE* xregs_state); - -int init_trusted_files (void); +int init_trusted_files(void); void init_cpuid(void); bool is_tsc_usable(void); @@ -134,17 +133,16 @@ enum { FILE_CHECK_POLICY_ALLOW_ALL_BUT_LOG, }; -int init_file_check_policy (void); +int init_file_check_policy(void); -int get_file_check_policy (void); +int get_file_check_policy(void); -int copy_and_verify_trusted_file (const char * path, const void * umem, - uint64_t umem_start, uint64_t umem_end, - void * buffer, uint64_t offset, uint64_t size, - sgx_stub_t * stubs, uint64_t total_size); +int copy_and_verify_trusted_file(const char* path, const void* umem, uint64_t umem_start, + uint64_t umem_end, void* buffer, uint64_t offset, uint64_t size, + sgx_stub_t* stubs, uint64_t total_size); -int init_trusted_children (void); -int register_trusted_child (const char * uri, const char * mr_enclave_str); +int init_trusted_children(void); +int register_trusted_child(const char* uri, const char* mr_enclave_str); int init_enclave(void); int init_enclave_key(void); @@ -230,9 +228,9 @@ extern PAL_SESSION_KEY g_master_key; /* enclave state used for generating report */ extern struct pal_enclave_state { - uint64_t enclave_flags; // Reserved for flags - uint64_t enclave_id; // Unique identifier for authentication - sgx_sign_data_t enclave_data; // Reserved for signing other data + uint64_t enclave_flags; // Reserved for flags + uint64_t enclave_id; // Unique identifier for authentication + sgx_sign_data_t enclave_data; // Reserved for signing other data } __attribute__((packed)) g_pal_enclave_state; static_assert(sizeof(struct pal_enclave_state) == sizeof(sgx_report_data_t), "incorrect struct size"); @@ -243,7 +241,6 @@ static_assert(sizeof(struct pal_enclave_state) == sizeof(sgx_report_data_t), */ int sgx_verify_report(sgx_report_t* report); - /*! * \brief Obtain a CPU-signed report for local attestation. * @@ -282,63 +279,68 @@ int _DkStreamSecureSave(LIB_SSL_CONTEXT* ssl_ctx, const uint8_t** obuf, size_t* #include "sgx_arch.h" -#define PAL_ENCLAVE_INITIALIZED 0x0001ULL +#define PAL_ENCLAVE_INITIALIZED 0x0001ULL -#include +#include "hex.h" #else int sgx_create_process(const char* uri, int nargs, const char** args, int* stream_fd); #ifdef DEBUG -# ifndef SIGCHLD -# define SIGCHLD 17 -# endif - -# define ARCH_VFORK() \ - (g_pal_enclave.pal_sec.in_gdb ? \ - INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK|SIGCHLD, 0, NULL, NULL) :\ - INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK, 0, NULL, NULL)) +#ifndef SIGCHLD +#define SIGCHLD 17 +#endif + +#define ARCH_VFORK() \ + (g_pal_enclave.pal_sec.in_gdb \ + ? INLINE_SYSCALL(clone, 4, CLONE_VM | CLONE_VFORK | SIGCHLD, 0, NULL, NULL) \ + : INLINE_SYSCALL(clone, 4, CLONE_VM | CLONE_VFORK, 0, NULL, NULL)) #else -# define ARCH_VFORK() \ +#define ARCH_VFORK() \ (INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK, 0, NULL, NULL)) #endif #endif /* IN_ENCLAVE */ -#define DBG_E 0x01 -#define DBG_I 0x02 -#define DBG_D 0x04 -#define DBG_S 0x08 -#define DBG_P 0x10 -#define DBG_M 0x20 +#define DBG_E 0x01 +#define DBG_I 0x02 +#define DBG_D 0x04 +#define DBG_S 0x08 +#define DBG_P 0x10 +#define DBG_M 0x20 #ifdef DEBUG -# define DBG_LEVEL (DBG_E|DBG_I|DBG_D|DBG_S) +#define DBG_LEVEL (DBG_E | DBG_I | DBG_D | DBG_S) #else -# define DBG_LEVEL (DBG_E) +#define DBG_LEVEL DBG_E #endif #ifdef IN_ENCLAVE #undef uthash_fatal -#define uthash_fatal(msg) \ - do { \ - __UNUSED(msg); \ +#define uthash_fatal(msg) \ + do { \ + __UNUSED(msg); \ DkProcessExit(-PAL_ERROR_NOMEM); \ } while (0) -#define SGX_DBG(class, fmt...) \ - do { if ((class) & DBG_LEVEL) printf(fmt); } while (0) +#define SGX_DBG(class, fmt...) \ + do { \ + if ((class) & DBG_LEVEL) \ + printf(fmt); \ + } while (0) #else -#include +#include "pal_debug.h" -#define SGX_DBG(class, fmt...) \ - do { if ((class) & DBG_LEVEL) pal_printf(fmt); } while (0) +#define SGX_DBG(class, fmt...) \ + do { \ + if ((class) & DBG_LEVEL) \ + pal_printf(fmt); \ + } while (0) #endif #ifndef IN_ENCLAVE -int clone(int (*__fn) (void* __arg), void* __child_stack, - int __flags, const void* __arg, ...); +int clone(int (*__fn)(void* __arg), void* __child_stack, int __flags, const void* __arg, ...); #endif #endif /* PAL_LINUX_H */ diff --git a/Pal/src/host/Linux-SGX/pal_linux_defs.h b/Pal/src/host/Linux-SGX/pal_linux_defs.h index f09857a1d9..9c14369be4 100644 --- a/Pal/src/host/Linux-SGX/pal_linux_defs.h +++ b/Pal/src/host/Linux-SGX/pal_linux_defs.h @@ -1,30 +1,30 @@ #ifndef PAL_LINUX_DEFS_H #define PAL_LINUX_DEFS_H -#define THREAD_STACK_SIZE (PRESET_PAGESIZE * 512) /* 2MB untrusted stack */ -#define ALT_STACK_SIZE (PRESET_PAGESIZE * 16) /* 64KB untrusted signal stack */ +#define THREAD_STACK_SIZE (PRESET_PAGESIZE * 512) /* 2MB untrusted stack */ +#define ALT_STACK_SIZE (PRESET_PAGESIZE * 16) /* 64KB untrusted signal stack */ #define RPC_STACK_SIZE (PRESET_PAGESIZE * 2) -#define ENCLAVE_HIGH_ADDRESS 0x800000000 -#define SSAFRAMENUM 2 -#define ENCLAVE_STACK_SIZE (PRESET_PAGESIZE * 64) +#define ENCLAVE_HIGH_ADDRESS 0x800000000 +#define SSAFRAMENUM 2 +#define ENCLAVE_STACK_SIZE (PRESET_PAGESIZE * 64) #define ENCLAVE_SIG_STACK_SIZE (PRESET_PAGESIZE * 16) -#define DEFAULT_HEAP_MIN 0x10000 -#define TRACE_ECALL 1 -#define TRACE_OCALL 1 +#define DEFAULT_HEAP_MIN 0x10000 +#define TRACE_ECALL 1 +#define TRACE_OCALL 1 -#define DEBUG_ECALL 0 -#define DEBUG_OCALL 0 +#define DEBUG_ECALL 0 +#define DEBUG_OCALL 0 -#define TRUSTED_STUB_SIZE (PRESET_PAGESIZE * 4UL) +#define TRUSTED_STUB_SIZE (PRESET_PAGESIZE * 4UL) //#define USE_AES_NI 1 -#define PRINT_ENCLAVE_STAT 0 +#define PRINT_ENCLAVE_STAT 0 -#define MAX_ARGS_SIZE 10000000 -#define MAX_ENV_SIZE 10000000 +#define MAX_ARGS_SIZE 10000000 +#define MAX_ENV_SIZE 10000000 -#define RED_ZONE_SIZE 128 +#define RED_ZONE_SIZE 128 #endif /* PAL_LINUX_DEFS_H */ diff --git a/Pal/src/host/Linux-SGX/pal_linux_error.h b/Pal/src/host/Linux-SGX/pal_linux_error.h index f1f0795170..ea81a0c678 100644 --- a/Pal/src/host/Linux-SGX/pal_linux_error.h +++ b/Pal/src/host/Linux-SGX/pal_linux_error.h @@ -4,7 +4,8 @@ #ifdef IN_PAL #include -#include + +#include "pal_error.h" static inline __attribute__((unused)) int unix_to_pal_error(int unix_errno) { switch (unix_errno) { diff --git a/Pal/src/host/Linux-SGX/pal_security.h b/Pal/src/host/Linux-SGX/pal_security.h index acfc80f649..6e0ee3517e 100644 --- a/Pal/src/host/Linux-SGX/pal_security.h +++ b/Pal/src/host/Linux-SGX/pal_security.h @@ -11,40 +11,40 @@ typedef char PAL_SEC_STR[255]; struct pal_sec { /* host credentials */ - PAL_NUM instance_id; - PAL_IDX ppid, pid, uid, gid; + PAL_NUM instance_id; + PAL_IDX ppid, pid, uid, gid; /* enclave information */ - sgx_target_info_t qe_targetinfo; - sgx_measurement_t mr_enclave; - sgx_measurement_t mr_signer; - sgx_attributes_t enclave_attributes; + sgx_target_info_t qe_targetinfo; + sgx_measurement_t mr_enclave; + sgx_measurement_t mr_signer; + sgx_attributes_t enclave_attributes; /* remaining heap usable by application */ - PAL_PTR heap_min, heap_max; + PAL_PTR heap_min, heap_max; /* executable name, addr and size */ - PAL_SEC_STR exec_name; - PAL_PTR exec_addr; - PAL_NUM exec_size; + PAL_SEC_STR exec_name; + PAL_PTR exec_addr; + PAL_NUM exec_size; - PAL_SEC_STR manifest_name; + PAL_SEC_STR manifest_name; /* child's stream FD created and sent over by parent */ - PAL_IDX stream_fd; + PAL_IDX stream_fd; /* additional information */ - PAL_SEC_STR pipe_prefix; + PAL_SEC_STR pipe_prefix; /* Need to pass in the number of cores */ - PAL_NUM num_cpus; + PAL_NUM num_cpus; #ifdef DEBUG - PAL_BOL in_gdb; + PAL_BOL in_gdb; #endif #if PRINT_ENCLAVE_STAT == 1 - PAL_NUM start_time; + PAL_NUM start_time; #endif }; @@ -52,7 +52,7 @@ struct pal_sec { extern struct pal_sec g_pal_sec; #endif -#define GRAPHENE_TEMPDIR "/tmp/graphene" -#define GRAPHENE_PIPEDIR (GRAPHENE_TEMPDIR "/pipes") +#define GRAPHENE_TEMPDIR "/tmp/graphene" +#define GRAPHENE_PIPEDIR (GRAPHENE_TEMPDIR "/pipes") #endif /* PAL_SECURITY_H */ diff --git a/Pal/src/host/Linux-SGX/protected-files/lru_cache.c b/Pal/src/host/Linux-SGX/protected-files/lru_cache.c index a19578c4c7..1b1e57061b 100644 --- a/Pal/src/host/Linux-SGX/protected-files/lru_cache.c +++ b/Pal/src/host/Linux-SGX/protected-files/lru_cache.c @@ -8,17 +8,17 @@ #include "lru_cache.h" -#include - #include "api.h" #include "list.h" #include "uthash.h" #ifdef IN_PAL - #include "pal_linux.h" +#include "assert.h" +#include "pal_linux.h" #else - #include - #include +#include +#include +#include #endif DEFINE_LIST(_lruc_list_node); @@ -50,7 +50,7 @@ lruc_context_t* lruc_create(void) { return NULL; INIT_LISTP(&lruc->list); - lruc->map = NULL; + lruc->map = NULL; lruc->current = NULL; return lruc; } @@ -98,7 +98,7 @@ bool lruc_add(lruc_context_t* lruc, uint64_t key, void* data) { list_node->key = key; map_node->key = key; LISTP_ADD(list_node, &lruc->list, list); - map_node->data = data; + map_node->data = data; map_node->list_ptr = list_node; HASH_ADD(hh, lruc->map, key, sizeof(key), map_node); return true; @@ -131,7 +131,7 @@ void* lruc_get_first(lruc_context_t* lruc) { if (LISTP_EMPTY(&lruc->list)) return NULL; - lruc->current = LISTP_FIRST_ENTRY(&lruc->list, /*unused*/0, list); + lruc->current = LISTP_FIRST_ENTRY(&lruc->list, /*unused*/ 0, list); lruc_map_node_t* mn = get_map_node(lruc, lruc->current->key); assert(mn != NULL); return mn->data; @@ -154,7 +154,7 @@ void* lruc_get_last(lruc_context_t* lruc) { if (LISTP_EMPTY(&lruc->list)) return NULL; - lruc_list_node_t* ln = LISTP_LAST_ENTRY(&lruc->list, /*unused*/0, list); + lruc_list_node_t* ln = LISTP_LAST_ENTRY(&lruc->list, /*unused*/ 0, list); lruc_map_node_t* mn = get_map_node(lruc, ln->key); assert(mn != NULL); return mn->data; @@ -164,7 +164,7 @@ void lruc_remove_last(lruc_context_t* lruc) { if (LISTP_EMPTY(&lruc->list)) return; - lruc_list_node_t* ln = LISTP_LAST_ENTRY(&lruc->list, /*unused*/0, list); + lruc_list_node_t* ln = LISTP_LAST_ENTRY(&lruc->list, /*unused*/ 0, list); LISTP_DEL(ln, &lruc->list, list); lruc_map_node_t* mn = get_map_node(lruc, ln->key); assert(mn != NULL); diff --git a/Pal/src/host/Linux-SGX/protected-files/lru_cache.h b/Pal/src/host/Linux-SGX/protected-files/lru_cache.h index 41c9e1e53f..750aaaf0be 100644 --- a/Pal/src/host/Linux-SGX/protected-files/lru_cache.h +++ b/Pal/src/host/Linux-SGX/protected-files/lru_cache.h @@ -21,7 +21,8 @@ lruc_context_t* lruc_create(void); void lruc_destroy(lruc_context_t* context); bool lruc_add(lruc_context_t* context, uint64_t key, void* data); // key must not already exist void* lruc_get(lruc_context_t* context, uint64_t key); -void* lruc_find(lruc_context_t* context, uint64_t key); // only returns the object, does not bump it to the head +void* lruc_find(lruc_context_t* context, + uint64_t key); // only returns the object, does not bump it to the head size_t lruc_size(lruc_context_t* context); void* lruc_get_first(lruc_context_t* context); void* lruc_get_next(lruc_context_t* context); diff --git a/Pal/src/host/Linux-SGX/protected-files/protected_files.c b/Pal/src/host/Linux-SGX/protected-files/protected_files.c index c5f0f64baa..4f0c59ba23 100644 --- a/Pal/src/host/Linux-SGX/protected-files/protected_files.c +++ b/Pal/src/host/Linux-SGX/protected-files/protected_files.c @@ -4,8 +4,8 @@ * Copyright (C) 2011-2019 Intel Corporation */ -#include "protected_files_internal.h" #include "api.h" +#include "protected_files_internal.h" #ifndef IN_PAL #include @@ -19,8 +19,8 @@ * replace with a better one. * TODO: is this really needed? Intel's implementation uses similar function as "defense in depth". */ - static void erase_memory(void *buffer, size_t size) { - volatile unsigned char *p = buffer; +static void erase_memory(void* buffer, size_t size) { + volatile unsigned char* p = buffer; while (size--) *p++ = 0; } @@ -39,23 +39,23 @@ static pf_random_f g_cb_random = NULL; #define PF_DEBUG_PRINT_SIZE_MAX 4096 /* Debug print without function name prefix. Implicit param: pf (context pointer). */ -#define __DEBUG_PF(format, ...) \ - do { \ - if (g_cb_debug) { \ +#define __DEBUG_PF(format, ...) \ + do { \ + if (g_cb_debug) { \ snprintf(pf->debug_buffer, PF_DEBUG_PRINT_SIZE_MAX, format, ##__VA_ARGS__); \ - g_cb_debug(pf->debug_buffer); \ - } \ - } while(0) + g_cb_debug(pf->debug_buffer); \ + } \ + } while (0) /* Debug print with function name prefix. Implicit param: pf (context pointer). */ -#define DEBUG_PF(format, ...) \ - do { \ - if (g_cb_debug) { \ +#define DEBUG_PF(format, ...) \ + do { \ + if (g_cb_debug) { \ snprintf(pf->debug_buffer, PF_DEBUG_PRINT_SIZE_MAX, "%s: " format, __FUNCTION__, \ - ##__VA_ARGS__); \ - g_cb_debug(pf->debug_buffer); \ - } \ - } while(0) + ##__VA_ARGS__); \ + g_cb_debug(pf->debug_buffer); \ + } \ + } while (0) #else /* DEBUG */ #define DEBUG_PF(...) @@ -65,8 +65,8 @@ static pf_random_f g_cb_random = NULL; static pf_iv_t g_empty_iv = {0}; static bool g_initialized = false; -#define METADATA_KEY_NAME "SGX-PROTECTED-FS-METADATA-KEY" -#define MAX_LABEL_SIZE 64 +#define METADATA_KEY_NAME "SGX-PROTECTED-FS-METADATA-KEY" +#define MAX_LABEL_SIZE 64 static_assert(sizeof(METADATA_KEY_NAME) <= MAX_LABEL_SIZE, "label too long"); @@ -152,27 +152,26 @@ static bool ipf_init_fields(pf_context_t* pf) { memset(&g_empty_iv, 0, sizeof(g_empty_iv)); memset(&pf->root_mht, 0, sizeof(pf->root_mht)); - pf->root_mht.type = FILE_MHT_NODE_TYPE; + pf->root_mht.type = FILE_MHT_NODE_TYPE; pf->root_mht.physical_node_number = 1; - pf->root_mht.node_number = 0; - pf->root_mht.new_node = true; - pf->root_mht.need_writing = false; - - pf->offset = 0; - pf->file = NULL; - pf->end_of_file = false; - pf->need_writing = false; - pf->file_status = PF_STATUS_UNINITIALIZED; - pf->last_error = PF_STATUS_SUCCESS; + pf->root_mht.node_number = 0; + pf->root_mht.new_node = true; + pf->root_mht.need_writing = false; + + pf->offset = 0; + pf->file = NULL; + pf->end_of_file = false; + pf->need_writing = false; + pf->file_status = PF_STATUS_UNINITIALIZED; + pf->last_error = PF_STATUS_SUCCESS; pf->real_file_size = 0; pf->cache = lruc_create(); return true; } -static pf_context_t* ipf_open(const char* path, pf_file_mode_t mode, bool create, - pf_handle_t file, uint64_t real_size, const pf_key_t* kdk_key, - pf_status_t* status) { +static pf_context_t* ipf_open(const char* path, pf_file_mode_t mode, bool create, pf_handle_t file, + uint64_t real_size, const pf_key_t* kdk_key, pf_status_t* status) { *status = PF_STATUS_NO_MEMORY; pf_context_t* pf = calloc(1, sizeof(*pf)); @@ -182,8 +181,8 @@ static pf_context_t* ipf_open(const char* path, pf_file_mode_t mode, bool create if (!ipf_init_fields(pf)) goto out; - DEBUG_PF("handle: %d, path: '%s', real size: %lu, mode: 0x%x\n", - *(int*)file, path, real_size, mode); + DEBUG_PF("handle: %d, path: '%s', real size: %lu, mode: 0x%x\n", *(int*)file, path, real_size, + mode); if (kdk_key == NULL) { DEBUG_PF("no key specified\n"); @@ -346,7 +345,7 @@ static bool ipf_init_existing_file(pf_context_t* pf, const char* path) { } static bool ipf_init_new_file(pf_context_t* pf, const char* path) { - pf->file_metadata.plain_part.file_id = PF_FILE_ID; + pf->file_metadata.plain_part.file_id = PF_FILE_ID; pf->file_metadata.plain_part.major_version = PF_MAJOR_VERSION; pf->file_metadata.plain_part.minor_version = PF_MINOR_VERSION; @@ -487,19 +486,18 @@ static bool ipf_update_all_data_and_mht_nodes(pf_context_t* pf) { file_node_t* data_node = (file_node_t*)data; if (data_node->need_writing) { - - gcm_crypto_data_t* gcm_crypto_data = &data_node->parent->decrypted.mht - .data_nodes_crypto[data_node->node_number % ATTACHED_DATA_NODES_COUNT]; + gcm_crypto_data_t* gcm_crypto_data = + &data_node->parent->decrypted.mht + .data_nodes_crypto[data_node->node_number % ATTACHED_DATA_NODES_COUNT]; if (!ipf_generate_random_key(pf, &gcm_crypto_data->key)) goto out; - // encrypt the data, this also saves the gmac of the operation in the mht crypto node - status = g_cb_aes_gcm_encrypt(&gcm_crypto_data->key, &g_empty_iv, - NULL, 0, // aad + // encrypt the data, this also saves the gmac of the operation in the mht crypto + // node + status = g_cb_aes_gcm_encrypt(&gcm_crypto_data->key, &g_empty_iv, NULL, 0, // aad data_node->decrypted.data.data, PF_NODE_SIZE, - data_node->encrypted.cipher, - &gcm_crypto_data->gmac); + data_node->encrypted.cipher, &gcm_crypto_data->gmac); if (PF_FAILURE(status)) { pf->last_error = status; goto out; @@ -557,18 +555,17 @@ static bool ipf_update_all_data_and_mht_nodes(pf_context_t* pf) { for (dirty_idx = dirty_count; dirty_idx > 0; dirty_idx--) { file_mht_node = mht_array[dirty_idx - 1]; - gcm_crypto_data_t* gcm_crypto_data = &file_mht_node->parent->decrypted.mht - .mht_nodes_crypto[(file_mht_node->node_number - 1) % CHILD_MHT_NODES_COUNT]; + gcm_crypto_data_t* gcm_crypto_data = + &file_mht_node->parent->decrypted.mht + .mht_nodes_crypto[(file_mht_node->node_number - 1) % CHILD_MHT_NODES_COUNT]; if (!ipf_generate_random_key(pf, &gcm_crypto_data->key)) { goto out; } - status = g_cb_aes_gcm_encrypt(&gcm_crypto_data->key, &g_empty_iv, - NULL, 0, + status = g_cb_aes_gcm_encrypt(&gcm_crypto_data->key, &g_empty_iv, NULL, 0, &file_mht_node->decrypted.mht, PF_NODE_SIZE, - &file_mht_node->encrypted.cipher, - &gcm_crypto_data->gmac); + &file_mht_node->encrypted.cipher, &gcm_crypto_data->gmac); if (PF_FAILURE(status)) { pf->last_error = status; goto out; @@ -607,10 +604,8 @@ static bool ipf_update_metadata_node(pf_context_t* pf) { } // encrypt meta data encrypted part, also updates the gmac in the meta data plain part - status = g_cb_aes_gcm_encrypt(&key, &g_empty_iv, - NULL, 0, - &pf->encrypted_part_plain, sizeof(metadata_encrypted_t), - &pf->file_metadata.encrypted_part, + status = g_cb_aes_gcm_encrypt(&key, &g_empty_iv, NULL, 0, &pf->encrypted_part_plain, + sizeof(metadata_encrypted_t), &pf->file_metadata.encrypted_part, &pf->file_metadata.plain_part.metadata_gmac); if (PF_FAILURE(status)) { pf->last_error = status; @@ -964,7 +959,7 @@ static file_node_t* ipf_get_data_node(pf_context_t* pf) { assert(pf->file_status != PF_STATUS_SUCCESS); if (pf->file_status == PF_STATUS_SUCCESS) pf->file_status = PF_STATUS_FLUSH_ERROR; // for release set this anyway - return NULL; // even if we got the data_node! + return NULL; // even if we got the data_node! } } } @@ -1035,15 +1030,14 @@ static file_node_t* ipf_read_data_node(pf_context_t* pf) { return NULL; } - gcm_crypto_data_t* gcm_crypto_data = &file_data_node->parent->decrypted.mht - .data_nodes_crypto[file_data_node->node_number % ATTACHED_DATA_NODES_COUNT]; + gcm_crypto_data_t* gcm_crypto_data = + &file_data_node->parent->decrypted.mht + .data_nodes_crypto[file_data_node->node_number % ATTACHED_DATA_NODES_COUNT]; // this function decrypt the data _and_ checks the integrity of the data against the gmac - status = g_cb_aes_gcm_decrypt(&gcm_crypto_data->key, &g_empty_iv, - NULL, 0, + status = g_cb_aes_gcm_decrypt(&gcm_crypto_data->key, &g_empty_iv, NULL, 0, file_data_node->encrypted.cipher, PF_NODE_SIZE, - file_data_node->decrypted.data.data, - &gcm_crypto_data->gmac); + file_data_node->decrypted.data.data, &gcm_crypto_data->gmac); if (PF_FAILURE(status)) { free(file_data_node); @@ -1082,7 +1076,7 @@ static file_node_t* ipf_get_mht_node(pf_context_t* pf) { // file is constructed from (ATTACHED_DATA_NODES_COUNT + CHILD_MHT_NODES_COUNT) * PF_NODE_SIZE // bytes per MHT node if ((pf->offset - MD_USER_DATA_SIZE) % (ATTACHED_DATA_NODES_COUNT * PF_NODE_SIZE) == 0 && - pf->offset == pf->encrypted_part_plain.size) { + pf->offset == pf->encrypted_part_plain.size) { file_mht_node = ipf_append_mht_node(pf, mht_node_number); } else { file_mht_node = ipf_read_mht_node(pf, mht_node_number); @@ -1151,10 +1145,10 @@ static file_node_t* ipf_read_mht_node(pf_context_t* pf, uint64_t mht_node_number return NULL; } - file_mht_node->type = FILE_MHT_NODE_TYPE; - file_mht_node->node_number = mht_node_number; + file_mht_node->type = FILE_MHT_NODE_TYPE; + file_mht_node->node_number = mht_node_number; file_mht_node->physical_node_number = physical_node_number; - file_mht_node->parent = parent_file_mht_node; + file_mht_node->parent = parent_file_mht_node; if (!ipf_read_node(pf, pf->file, file_mht_node->physical_node_number, file_mht_node->encrypted.cipher, PF_NODE_SIZE)) { @@ -1162,15 +1156,14 @@ static file_node_t* ipf_read_mht_node(pf_context_t* pf, uint64_t mht_node_number return NULL; } - gcm_crypto_data_t* gcm_crypto_data = &file_mht_node->parent->decrypted.mht - .mht_nodes_crypto[(file_mht_node->node_number - 1) % CHILD_MHT_NODES_COUNT]; + gcm_crypto_data_t* gcm_crypto_data = + &file_mht_node->parent->decrypted.mht + .mht_nodes_crypto[(file_mht_node->node_number - 1) % CHILD_MHT_NODES_COUNT]; // this function decrypt the data _and_ checks the integrity of the data against the gmac - status = g_cb_aes_gcm_decrypt(&gcm_crypto_data->key, &g_empty_iv, - NULL, 0, + status = g_cb_aes_gcm_decrypt(&gcm_crypto_data->key, &g_empty_iv, NULL, 0, file_mht_node->encrypted.cipher, PF_NODE_SIZE, - &file_mht_node->decrypted.mht, - &gcm_crypto_data->gmac); + &file_mht_node->decrypted.mht, &gcm_crypto_data->gmac); if (PF_FAILURE(status)) { free(file_mht_node); pf->last_error = status; @@ -1206,8 +1199,7 @@ void pf_set_callbacks(pf_read_f read_f, pf_write_f write_f, pf_truncate_f trunca } pf_status_t pf_open(pf_handle_t handle, const char* path, uint64_t underlying_size, - pf_file_mode_t mode, bool create, const pf_key_t* key, - pf_context_t** context) { + pf_file_mode_t mode, bool create, const pf_key_t* key, pf_context_t** context) { if (!g_initialized) return PF_STATUS_UNINITIALIZED; diff --git a/Pal/src/host/Linux-SGX/protected-files/protected_files.h b/Pal/src/host/Linux-SGX/protected-files/protected_files.h index a6e2f96a82..4319d62902 100644 --- a/Pal/src/host/Linux-SGX/protected-files/protected_files.h +++ b/Pal/src/host/Linux-SGX/protected-files/protected_files.h @@ -14,13 +14,13 @@ #include /*! Size of the AES-GCM encryption key */ -#define PF_KEY_SIZE 16 +#define PF_KEY_SIZE 16 /*! Size of IV for AES-GCM */ -#define PF_IV_SIZE 12 +#define PF_IV_SIZE 12 /*! Size of MAC fields */ -#define PF_MAC_SIZE 16 +#define PF_MAC_SIZE 16 typedef uint8_t pf_iv_t[PF_IV_SIZE]; typedef uint8_t pf_mac_t[PF_MAC_SIZE]; @@ -117,9 +117,8 @@ typedef void (*pf_debug_f)(const char* msg); * \param [out] mac MAC computed for \a input and \a aad * \return PF status */ -typedef pf_status_t (*pf_aes_gcm_encrypt_f)(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, +typedef pf_status_t (*pf_aes_gcm_encrypt_f)(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, void* output, pf_mac_t* mac); /*! @@ -135,9 +134,8 @@ typedef pf_status_t (*pf_aes_gcm_encrypt_f)(const pf_key_t* key, const pf_iv_t* * \param [in] mac Expected MAC * \return PF status */ -typedef pf_status_t (*pf_aes_gcm_decrypt_f)(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, +typedef pf_status_t (*pf_aes_gcm_decrypt_f)(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, void* output, const pf_mac_t* mac); /*! diff --git a/Pal/src/host/Linux-SGX/protected-files/protected_files_internal.h b/Pal/src/host/Linux-SGX/protected-files/protected_files_internal.h index 3c7e002a96..4a31261d58 100644 --- a/Pal/src/host/Linux-SGX/protected-files/protected_files_internal.h +++ b/Pal/src/host/Linux-SGX/protected-files/protected_files_internal.h @@ -7,9 +7,9 @@ #ifndef PROTECTED_FILES_INTERNAL_H_ #define PROTECTED_FILES_INTERNAL_H_ -#include #include +#include "assert.h" #include "list.h" #include "lru_cache.h" #include "protected_files.h" @@ -28,11 +28,11 @@ typedef struct _metadata_plain { pf_mac_t metadata_gmac; /* GCM mac */ } metadata_plain_t; -#define PATH_MAX_SIZE (260 + 512) +#define PATH_MAX_SIZE (260 + 512) // these are all defined as relative to node size, so we can decrease node size in tests // and have deeper tree -#define MD_USER_DATA_SIZE (PF_NODE_SIZE*3/4) // 3072 +#define MD_USER_DATA_SIZE (PF_NODE_SIZE * 3 / 4) // 3072 static_assert(MD_USER_DATA_SIZE == 3072, "bad struct size"); typedef struct _metadata_encrypted { @@ -47,8 +47,8 @@ typedef uint8_t metadata_encrypted_blob_t[sizeof(metadata_encrypted_t)]; #define METADATA_NODE_SIZE PF_NODE_SIZE -typedef uint8_t metadata_padding_t[METADATA_NODE_SIZE - - (sizeof(metadata_plain_t) + sizeof(metadata_encrypted_blob_t))]; +typedef uint8_t metadata_padding_t[METADATA_NODE_SIZE - + (sizeof(metadata_plain_t) + sizeof(metadata_encrypted_blob_t))]; typedef struct _metadata_node { metadata_plain_t plain_part; @@ -67,10 +67,10 @@ typedef struct _data_node_crypto { // for PF_NODE_SIZE == 2048, we have 48 attached data nodes and 16 mht child nodes // for PF_NODE_SIZE == 1024, we have 24 attached data nodes and 8 mht child nodes // 3/4 of the node size is dedicated to data nodes -#define ATTACHED_DATA_NODES_COUNT ((PF_NODE_SIZE/sizeof(gcm_crypto_data_t))*3/4) +#define ATTACHED_DATA_NODES_COUNT ((PF_NODE_SIZE / sizeof(gcm_crypto_data_t)) * 3 / 4) static_assert(ATTACHED_DATA_NODES_COUNT == 96, "ATTACHED_DATA_NODES_COUNT"); // 1/4 of the node size is dedicated to child mht nodes -#define CHILD_MHT_NODES_COUNT ((PF_NODE_SIZE/sizeof(gcm_crypto_data_t))*1/4) +#define CHILD_MHT_NODES_COUNT ((PF_NODE_SIZE / sizeof(gcm_crypto_data_t)) * 1 / 4) static_assert(CHILD_MHT_NODES_COUNT == 32, "CHILD_MHT_NODES_COUNT"); typedef struct _mht_node { @@ -95,7 +95,7 @@ static_assert(sizeof(encrypted_node_t) == PF_NODE_SIZE, "sizeof(encrypted_node_t #define MAX_PAGES_IN_CACHE 48 typedef enum { - FILE_MHT_NODE_TYPE = 1, + FILE_MHT_NODE_TYPE = 1, FILE_DATA_NODE_TYPE = 2, } mht_node_type_e; diff --git a/Pal/src/host/Linux-SGX/rpc_queue.h b/Pal/src/host/Linux-SGX/rpc_queue.h index 89111f2ec2..5e3870d442 100644 --- a/Pal/src/host/Linux-SGX/rpc_queue.h +++ b/Pal/src/host/Linux-SGX/rpc_queue.h @@ -53,11 +53,11 @@ * works well in practice. */ #define RPC_SPINLOCK_TIMEOUT 1000000 -#define RPC_QUEUE_SIZE 1024 /* max # of requests in RPC queue */ -#define MAX_RPC_THREADS 256 /* max number of RPC threads */ +#define RPC_QUEUE_SIZE 1024 /* max # of requests in RPC queue */ +#define MAX_RPC_THREADS 256 /* max number of RPC threads */ typedef struct { - spinlock_t lock; /* can be UNLOCKED / LOCKED_NO_WAITERS / LOCKED_WITH_WAITERS */ + spinlock_t lock; /* can be UNLOCKED / LOCKED_NO_WAITERS / LOCKED_WITH_WAITERS */ long result; uint64_t ocall_index; void* buffer; @@ -119,7 +119,8 @@ static inline bool rpc_enqueue(rpc_queue_t* q, rpc_request_t* req) { * This function is called only from the untrusted code and thus has no security implications. */ static inline rpc_request_t* rpc_dequeue(rpc_queue_t* q) { - if (__atomic_load_n(&q->front, __ATOMIC_RELAXED) == __atomic_load_n(&q->rear, __ATOMIC_RELAXED)) { + if (__atomic_load_n(&q->front, __ATOMIC_RELAXED) == + __atomic_load_n(&q->rear, __ATOMIC_RELAXED)) { /* quick check that queue is empty; this doesn't acquire a spinlock and thus lowers latency * on rpc_enqueue() performed by enclave threads (they don't have to wait for spinlock * release); note that untrusted RPC threads will simply retry again if this check fails */ diff --git a/Pal/src/host/Linux-SGX/sgx_api.h b/Pal/src/host/Linux-SGX/sgx_api.h index 0a27967376..428fbee642 100644 --- a/Pal/src/host/Linux-SGX/sgx_api.h +++ b/Pal/src/host/Linux-SGX/sgx_api.h @@ -27,8 +27,8 @@ bool sgx_copy_to_enclave(const void* ptr, size_t maxsize, const void* uptr, size * Caller is responsible for parameter alignment: 512B for `targetinfo`, 128B for `reportdata`, * and 512B for `report`. */ -static inline int sgx_report(const sgx_target_info_t* targetinfo, - const void* reportdata, sgx_report_t* report) { +static inline int sgx_report(const sgx_target_info_t* targetinfo, const void* reportdata, + sgx_report_t* report) { __asm__ volatile( ENCLU "\n" :: "a"(EREPORT), "b"(targetinfo), "c"(reportdata), "d"(report) diff --git a/Pal/src/host/Linux-SGX/sgx_arch.h b/Pal/src/host/Linux-SGX/sgx_arch.h index 77baaeb324..8159fadcde 100644 --- a/Pal/src/host/Linux-SGX/sgx_arch.h +++ b/Pal/src/host/Linux-SGX/sgx_arch.h @@ -62,10 +62,10 @@ typedef uint8_t sgx_isvfamily_id_t[SGX_ISV_FAMILY_ID_SIZE]; #define SGX_FLAGS_PROVISION_KEY 0x10ULL #define SGX_FLAGS_LICENSE_KEY 0x20ULL -#define SGX_XFRM_LEGACY 0x03ULL -#define SGX_XFRM_AVX 0x06ULL -#define SGX_XFRM_MPX 0x18ULL -#define SGX_XFRM_AVX512 0xe6ULL +#define SGX_XFRM_LEGACY 0x03ULL +#define SGX_XFRM_AVX 0x06ULL +#define SGX_XFRM_MPX 0x18ULL +#define SGX_XFRM_AVX512 0xe6ULL #define SGX_XFRM_RESERVED (~(SGX_XFRM_LEGACY | SGX_XFRM_AVX | SGX_XFRM_MPX | SGX_XFRM_AVX512)) #define SGX_MISCSELECT_EXINFO 0x01UL @@ -156,7 +156,7 @@ typedef struct { // Required by _restore_sgx_context, see enclave_entry.S. static_assert(offsetof(sgx_cpu_context_t, rip) - offsetof(sgx_cpu_context_t, rflags) == - sizeof(((sgx_cpu_context_t){0}).rflags), + sizeof(((sgx_cpu_context_t){0}).rflags), "rip must be directly after rflags in sgx_cpu_context_t"); static_assert(offsetof(sgx_cpu_context_t, rip) - offsetof(sgx_cpu_context_t, r15) <= RED_ZONE_SIZE, "r15 needs to be within red zone distance from rip"); diff --git a/Pal/src/host/Linux-SGX/sgx_attest.h b/Pal/src/host/Linux-SGX/sgx_attest.h index 2c020e98ed..2919cb7c40 100644 --- a/Pal/src/host/Linux-SGX/sgx_attest.h +++ b/Pal/src/host/Linux-SGX/sgx_attest.h @@ -87,8 +87,8 @@ enum { * \return 0 on success, negative PAL error code otherwise. */ int sgx_get_quote(const sgx_spid_t* spid, const sgx_quote_nonce_t* nonce, - const sgx_report_data_t* report_data, bool linkable, - char** quote, size_t* quote_len); + const sgx_report_data_t* report_data, bool linkable, char** quote, + size_t* quote_len); #pragma pack(pop) diff --git a/Pal/src/host/Linux-SGX/sgx_enclave.c b/Pal/src/host/Linux-SGX/sgx_enclave.c index 124d2991cd..267b04cf1e 100644 --- a/Pal/src/host/Linux-SGX/sgx_enclave.c +++ b/Pal/src/host/Linux-SGX/sgx_enclave.c @@ -1,12 +1,4 @@ -#include "cpu.h" -#include "ecall_types.h" -#include "ocall_types.h" -#include "pal_linux_error.h" -#include "pal_security.h" -#include "rpc_queue.h" #include "sgx_enclave.h" -#include "sgx_internal.h" -#include "sgx_tls.h" #include #include @@ -18,14 +10,24 @@ #include #include #include -#include #include -#define ODEBUG(code, ms) do {} while (0) +#include "cpu.h" +#include "ecall_types.h" +#include "ocall_types.h" +#include "pal_linux_error.h" +#include "pal_security.h" +#include "rpc_queue.h" +#include "sgx_internal.h" +#include "sgx_tls.h" +#include "sigset.h" + +#define ODEBUG(code, ms) \ + do { \ + } while (0) -static long sgx_ocall_exit(void* pms) -{ - ms_ocall_exit_t * ms = (ms_ocall_exit_t *) pms; +static long sgx_ocall_exit(void* pms) { + ms_ocall_exit_t* ms = (ms_ocall_exit_t*)pms; ODEBUG(OCALL_EXIT, NULL); if (ms->ms_is_exitgroup && ms->ms_exitcode == PAL_WAIT_FOR_CHILDREN_EXIT) { @@ -34,10 +36,13 @@ static long sgx_ocall_exit(void* pms) SGX_DBG(DBG_I, "Temporary process exits after emulating execve, wait for child to exit\n"); int wstatus; - int ret = INLINE_SYSCALL(wait4, 4, /*any child*/-1, &wstatus, /*options=*/0, /*rusage=*/NULL); + int ret = INLINE_SYSCALL(wait4, 4, /*any child*/ -1, &wstatus, /*options=*/0, + /*rusage=*/NULL); if (IS_ERR(ret)) { - /* it's too late to recover from errors, just log it and set some reasonable exit code */ - SGX_DBG(DBG_I, "Temporary process waited for child to exit but received error %d\n", ret); + /* it's too late to recover from errors, just log it and set some reasonable exit code + */ + SGX_DBG(DBG_I, "Temporary process waited for child to exit but received error %d\n", + ret); ms->ms_exitcode = ECHILD; } else { /* Linux expects 0..127 for normal termination and 128..255 for signal termination */ @@ -50,9 +55,9 @@ static long sgx_ocall_exit(void* pms) } } - if (ms->ms_exitcode != (int) ((uint8_t) ms->ms_exitcode)) { + if (ms->ms_exitcode != (int)((uint8_t)ms->ms_exitcode)) { SGX_DBG(DBG_E, "Saturation error in exit code %d, getting rounded down to %u\n", - ms->ms_exitcode, (uint8_t) ms->ms_exitcode); + ms->ms_exitcode, (uint8_t)ms->ms_exitcode); ms->ms_exitcode = 255; } @@ -99,21 +104,20 @@ static long sgx_ocall_munmap_untrusted(void* pms) { ms_ocall_munmap_untrusted_t* ms = (ms_ocall_munmap_untrusted_t*)pms; ODEBUG(OCALL_MUNMAP_UNTRUSTED, ms); INLINE_SYSCALL(munmap, 2, ALLOC_ALIGN_DOWN_PTR(ms->ms_mem), - ALLOC_ALIGN_UP_PTR(ms->ms_mem + ms->ms_size) - - ALLOC_ALIGN_DOWN_PTR(ms->ms_mem)); + ALLOC_ALIGN_UP_PTR(ms->ms_mem + ms->ms_size) - ALLOC_ALIGN_DOWN_PTR(ms->ms_mem)); return 0; } -static long sgx_ocall_cpuid(void * pms) -{ - ms_ocall_cpuid_t * ms = (ms_ocall_cpuid_t *) pms; +static long sgx_ocall_cpuid(void* pms) { + ms_ocall_cpuid_t* ms = (ms_ocall_cpuid_t*)pms; ODEBUG(OCALL_CPUID, ms); - __asm__ volatile ("cpuid" - : "=a"(ms->ms_values[0]), - "=b"(ms->ms_values[1]), - "=c"(ms->ms_values[2]), - "=d"(ms->ms_values[3]) - : "a"(ms->ms_leaf), "c"(ms->ms_subleaf) : "memory"); + __asm__ volatile("cpuid" + : "=a"(ms->ms_values[0]), + "=b"(ms->ms_values[1]), + "=c"(ms->ms_values[2]), + "=d"(ms->ms_values[3]) + : "a"(ms->ms_leaf), "c"(ms->ms_subleaf) + : "memory"); return 0; } @@ -127,26 +131,23 @@ static long sgx_ocall_open(void* pms) { return ret; } -static long sgx_ocall_close(void * pms) -{ - ms_ocall_close_t * ms = (ms_ocall_close_t *) pms; +static long sgx_ocall_close(void* pms) { + ms_ocall_close_t* ms = (ms_ocall_close_t*)pms; ODEBUG(OCALL_CLOSE, ms); INLINE_SYSCALL(close, 1, ms->ms_fd); return 0; } -static long sgx_ocall_read(void * pms) -{ - ms_ocall_read_t * ms = (ms_ocall_read_t *) pms; +static long sgx_ocall_read(void* pms) { + ms_ocall_read_t* ms = (ms_ocall_read_t*)pms; long ret; ODEBUG(OCALL_READ, ms); ret = INLINE_SYSCALL(read, 3, ms->ms_fd, ms->ms_buf, ms->ms_count); return ret; } -static long sgx_ocall_write(void * pms) -{ - ms_ocall_write_t * ms = (ms_ocall_write_t *) pms; +static long sgx_ocall_write(void* pms) { + ms_ocall_write_t* ms = (ms_ocall_write_t*)pms; long ret; ODEBUG(OCALL_WRITE, ms); ret = INLINE_SYSCALL(write, 3, ms->ms_fd, ms->ms_buf, ms->ms_count); @@ -169,18 +170,16 @@ static long sgx_ocall_pwrite(void* pms) { return ret; } -static long sgx_ocall_fstat(void * pms) -{ - ms_ocall_fstat_t * ms = (ms_ocall_fstat_t *) pms; +static long sgx_ocall_fstat(void* pms) { + ms_ocall_fstat_t* ms = (ms_ocall_fstat_t*)pms; long ret; ODEBUG(OCALL_FSTAT, ms); ret = INLINE_SYSCALL(fstat, 2, ms->ms_fd, &ms->ms_stat); return ret; } -static long sgx_ocall_fionread(void * pms) -{ - ms_ocall_fionread_t * ms = (ms_ocall_fionread_t *) pms; +static long sgx_ocall_fionread(void* pms) { + ms_ocall_fionread_t* ms = (ms_ocall_fionread_t*)pms; long ret; int val; ODEBUG(OCALL_FIONREAD, ms); @@ -188,9 +187,8 @@ static long sgx_ocall_fionread(void * pms) return IS_ERR(ret) ? ret : val; } -static long sgx_ocall_fsetnonblock(void * pms) -{ - ms_ocall_fsetnonblock_t * ms = (ms_ocall_fsetnonblock_t *) pms; +static long sgx_ocall_fsetnonblock(void* pms) { + ms_ocall_fsetnonblock_t* ms = (ms_ocall_fsetnonblock_t*)pms; long ret; int flags; ODEBUG(OCALL_FSETNONBLOCK, ms); @@ -202,46 +200,40 @@ static long sgx_ocall_fsetnonblock(void * pms) flags = ret; if (ms->ms_nonblocking) { if (!(flags & O_NONBLOCK)) - ret = INLINE_SYSCALL(fcntl, 3, ms->ms_fd, F_SETFL, - flags | O_NONBLOCK); + ret = INLINE_SYSCALL(fcntl, 3, ms->ms_fd, F_SETFL, flags | O_NONBLOCK); } else { if (flags & O_NONBLOCK) - ret = INLINE_SYSCALL(fcntl, 3, ms->ms_fd, F_SETFL, - flags & ~O_NONBLOCK); + ret = INLINE_SYSCALL(fcntl, 3, ms->ms_fd, F_SETFL, flags & ~O_NONBLOCK); } return ret; } -static long sgx_ocall_fchmod(void * pms) -{ - ms_ocall_fchmod_t * ms = (ms_ocall_fchmod_t *) pms; +static long sgx_ocall_fchmod(void* pms) { + ms_ocall_fchmod_t* ms = (ms_ocall_fchmod_t*)pms; long ret; ODEBUG(OCALL_FCHMOD, ms); ret = INLINE_SYSCALL(fchmod, 2, ms->ms_fd, ms->ms_mode); return ret; } -static long sgx_ocall_fsync(void * pms) -{ - ms_ocall_fsync_t * ms = (ms_ocall_fsync_t *) pms; +static long sgx_ocall_fsync(void* pms) { + ms_ocall_fsync_t* ms = (ms_ocall_fsync_t*)pms; ODEBUG(OCALL_FSYNC, ms); INLINE_SYSCALL(fsync, 1, ms->ms_fd); return 0; } -static long sgx_ocall_ftruncate(void * pms) -{ - ms_ocall_ftruncate_t * ms = (ms_ocall_ftruncate_t *) pms; +static long sgx_ocall_ftruncate(void* pms) { + ms_ocall_ftruncate_t* ms = (ms_ocall_ftruncate_t*)pms; long ret; ODEBUG(OCALL_FTRUNCATE, ms); ret = INLINE_SYSCALL(ftruncate, 2, ms->ms_fd, ms->ms_length); return ret; } -static long sgx_ocall_mkdir(void * pms) -{ - ms_ocall_mkdir_t * ms = (ms_ocall_mkdir_t *) pms; +static long sgx_ocall_mkdir(void* pms) { + ms_ocall_mkdir_t* ms = (ms_ocall_mkdir_t*)pms; long ret; ODEBUG(OCALL_MKDIR, ms); ret = INLINE_SYSCALL(mkdir, 2, ms->ms_pathname, ms->ms_mode); @@ -257,22 +249,19 @@ static long sgx_ocall_getdents(void* pms) { return ret; } -static long sgx_ocall_resume_thread(void * pms) -{ +static long sgx_ocall_resume_thread(void* pms) { ODEBUG(OCALL_RESUME_THREAD, pms); return interrupt_thread(pms); } -static long sgx_ocall_clone_thread(void * pms) -{ +static long sgx_ocall_clone_thread(void* pms) { __UNUSED(pms); ODEBUG(OCALL_CLONE_THREAD, pms); return clone_thread(); } -static long sgx_ocall_create_process(void * pms) -{ - ms_ocall_create_process_t * ms = (ms_ocall_create_process_t *) pms; +static long sgx_ocall_create_process(void* pms) { + ms_ocall_create_process_t* ms = (ms_ocall_create_process_t*)pms; ODEBUG(OCALL_CREATE_PROCESS, ms); long ret = sgx_create_process(ms->ms_uri, ms->ms_nargs, ms->ms_args, &ms->ms_stream_fd); if (ret < 0) @@ -281,35 +270,30 @@ static long sgx_ocall_create_process(void * pms) return 0; } -static long sgx_ocall_futex(void * pms) -{ - ms_ocall_futex_t * ms = (ms_ocall_futex_t *) pms; +static long sgx_ocall_futex(void* pms) { + ms_ocall_futex_t* ms = (ms_ocall_futex_t*)pms; long ret; ODEBUG(OCALL_FUTEX, ms); struct timespec* ts = NULL; if (ms->ms_timeout_us >= 0) { ts = __alloca(sizeof(struct timespec)); - ts->tv_sec = ms->ms_timeout_us / 1000000; + ts->tv_sec = ms->ms_timeout_us / 1000000; ts->tv_nsec = (ms->ms_timeout_us - ts->tv_sec * 1000000) * 1000; } - ret = INLINE_SYSCALL(futex, 6, ms->ms_futex, ms->ms_op, ms->ms_val, - ts, NULL, 0); + ret = INLINE_SYSCALL(futex, 6, ms->ms_futex, ms->ms_op, ms->ms_val, ts, NULL, 0); return ret; } -static long sgx_ocall_socketpair(void * pms) -{ - ms_ocall_socketpair_t * ms = (ms_ocall_socketpair_t *) pms; +static long sgx_ocall_socketpair(void* pms) { + ms_ocall_socketpair_t* ms = (ms_ocall_socketpair_t*)pms; long ret; ODEBUG(OCALL_SOCKETPAIR, ms); - ret = INLINE_SYSCALL(socketpair, 4, ms->ms_domain, - ms->ms_type|SOCK_CLOEXEC, - ms->ms_protocol, &ms->ms_sockfds); + ret = INLINE_SYSCALL(socketpair, 4, ms->ms_domain, ms->ms_type | SOCK_CLOEXEC, ms->ms_protocol, + &ms->ms_sockfds); return ret; } -static long sock_getopt(int fd, struct sockopt * opt) -{ +static long sock_getopt(int fd, struct sockopt* opt) { SGX_DBG(DBG_M, "sock_getopt (fd = %d, sockopt addr = %p) is not implemented \ always returns 0\n", fd, opt); /* initialize *opt with constant */ @@ -337,7 +321,8 @@ static long sgx_ocall_listen(void* pms) { /* must set the socket to be reuseable */ int reuseaddr = 1; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, + sizeof(reuseaddr)); if (IS_ERR(ret)) goto err_fd; @@ -445,7 +430,11 @@ static long sgx_ocall_connect(void* pms) { if (IS_ERR(ret) && ERRNO(ret) == EINPROGRESS) { do { - struct pollfd pfd = { .fd = fd, .events = POLLOUT, .revents = 0, }; + struct pollfd pfd = { + .fd = fd, + .events = POLLOUT, + .revents = 0, + }; ret = INLINE_SYSCALL(ppoll, 4, &pfd, 1, NULL, NULL); } while (IS_ERR(ret) && ERRNO(ret) == -EWOULDBLOCK); } @@ -553,17 +542,15 @@ static long sgx_ocall_setsockopt(void* pms) { return ret; } -static long sgx_ocall_shutdown(void * pms) -{ - ms_ocall_shutdown_t * ms = (ms_ocall_shutdown_t *) pms; +static long sgx_ocall_shutdown(void* pms) { + ms_ocall_shutdown_t* ms = (ms_ocall_shutdown_t*)pms; ODEBUG(OCALL_SHUTDOWN, ms); INLINE_SYSCALL(shutdown, 2, ms->ms_sockfd, ms->ms_how); return 0; } -static long sgx_ocall_gettime(void * pms) -{ - ms_ocall_gettime_t * ms = (ms_ocall_gettime_t *) pms; +static long sgx_ocall_gettime(void* pms) { + ms_ocall_gettime_t* ms = (ms_ocall_gettime_t*)pms; ODEBUG(OCALL_GETTIME, ms); struct timeval tv; INLINE_SYSCALL(gettimeofday, 2, &tv, NULL); @@ -571,8 +558,7 @@ static long sgx_ocall_gettime(void * pms) return 0; } -static long sgx_ocall_sleep(void * pms) -{ +static long sgx_ocall_sleep(void* pms) { ms_ocall_sleep_t* ms = (ms_ocall_sleep_t*)pms; long ret; ODEBUG(OCALL_SLEEP, ms); @@ -588,7 +574,7 @@ static long sgx_ocall_sleep(void * pms) req.tv_sec = VERY_LONG_TIME_IN_US / 1000000; req.tv_nsec = 0; } else { - req.tv_sec = ms->ms_microsec / 1000000; + req.tv_sec = ms->ms_microsec / 1000000; req.tv_nsec = (microsec - req.tv_sec * (uint64_t)1000000) * 1000; } @@ -598,33 +584,30 @@ static long sgx_ocall_sleep(void * pms) return ret; } -static long sgx_ocall_poll(void * pms) -{ - ms_ocall_poll_t * ms = (ms_ocall_poll_t *) pms; +static long sgx_ocall_poll(void* pms) { + ms_ocall_poll_t* ms = (ms_ocall_poll_t*)pms; long ret; ODEBUG(OCALL_POLL, ms); - struct timespec * ts = NULL; + struct timespec* ts = NULL; if (ms->ms_timeout_us >= 0) { ts = __alloca(sizeof(struct timespec)); - ts->tv_sec = ms->ms_timeout_us / 1000000; + ts->tv_sec = ms->ms_timeout_us / 1000000; ts->tv_nsec = (ms->ms_timeout_us - ts->tv_sec * 1000000) * 1000; } ret = INLINE_SYSCALL(ppoll, 4, ms->ms_fds, ms->ms_nfds, ts, NULL); return ret; } -static long sgx_ocall_rename(void * pms) -{ - ms_ocall_rename_t * ms = (ms_ocall_rename_t *) pms; +static long sgx_ocall_rename(void* pms) { + ms_ocall_rename_t* ms = (ms_ocall_rename_t*)pms; long ret; ODEBUG(OCALL_RENAME, ms); ret = INLINE_SYSCALL(rename, 2, ms->ms_oldpath, ms->ms_newpath); return ret; } -static long sgx_ocall_delete(void * pms) -{ - ms_ocall_delete_t * ms = (ms_ocall_delete_t *) pms; +static long sgx_ocall_delete(void* pms) { + ms_ocall_delete_t* ms = (ms_ocall_delete_t*)pms; long ret; ODEBUG(OCALL_DELETE, ms); @@ -636,9 +619,8 @@ static long sgx_ocall_delete(void * pms) return ret; } -static long sgx_ocall_eventfd (void * pms) -{ - ms_ocall_eventfd_t * ms = (ms_ocall_eventfd_t *) pms; +static long sgx_ocall_eventfd(void* pms) { + ms_ocall_eventfd_t* ms = (ms_ocall_eventfd_t*)pms; long ret; ODEBUG(OCALL_EVENTFD, ms); @@ -647,10 +629,9 @@ static long sgx_ocall_eventfd (void * pms) return ret; } -static long sgx_ocall_load_debug(void * pms) -{ - const char * command = (const char *) pms; - ODEBUG(OCALL_LOAD_DEBUG, (void *) command); +static long sgx_ocall_load_debug(void* pms) { + const char* command = (const char*)pms; + ODEBUG(OCALL_LOAD_DEBUG, (void*)command); load_gdb_command(command); return 0; } @@ -663,47 +644,49 @@ static long sgx_ocall_get_quote(void* pms) { } sgx_ocall_fn_t ocall_table[OCALL_NR] = { - [OCALL_EXIT] = sgx_ocall_exit, - [OCALL_MMAP_UNTRUSTED] = sgx_ocall_mmap_untrusted, - [OCALL_MUNMAP_UNTRUSTED] = sgx_ocall_munmap_untrusted, - [OCALL_CPUID] = sgx_ocall_cpuid, - [OCALL_OPEN] = sgx_ocall_open, - [OCALL_CLOSE] = sgx_ocall_close, - [OCALL_READ] = sgx_ocall_read, - [OCALL_WRITE] = sgx_ocall_write, - [OCALL_PREAD] = sgx_ocall_pread, - [OCALL_PWRITE] = sgx_ocall_pwrite, - [OCALL_FSTAT] = sgx_ocall_fstat, - [OCALL_FIONREAD] = sgx_ocall_fionread, - [OCALL_FSETNONBLOCK] = sgx_ocall_fsetnonblock, - [OCALL_FCHMOD] = sgx_ocall_fchmod, - [OCALL_FSYNC] = sgx_ocall_fsync, - [OCALL_FTRUNCATE] = sgx_ocall_ftruncate, - [OCALL_MKDIR] = sgx_ocall_mkdir, - [OCALL_GETDENTS] = sgx_ocall_getdents, - [OCALL_RESUME_THREAD] = sgx_ocall_resume_thread, - [OCALL_CLONE_THREAD] = sgx_ocall_clone_thread, - [OCALL_CREATE_PROCESS] = sgx_ocall_create_process, - [OCALL_FUTEX] = sgx_ocall_futex, - [OCALL_SOCKETPAIR] = sgx_ocall_socketpair, - [OCALL_LISTEN] = sgx_ocall_listen, - [OCALL_ACCEPT] = sgx_ocall_accept, - [OCALL_CONNECT] = sgx_ocall_connect, - [OCALL_RECV] = sgx_ocall_recv, - [OCALL_SEND] = sgx_ocall_send, - [OCALL_SETSOCKOPT] = sgx_ocall_setsockopt, - [OCALL_SHUTDOWN] = sgx_ocall_shutdown, - [OCALL_GETTIME] = sgx_ocall_gettime, - [OCALL_SLEEP] = sgx_ocall_sleep, - [OCALL_POLL] = sgx_ocall_poll, - [OCALL_RENAME] = sgx_ocall_rename, - [OCALL_DELETE] = sgx_ocall_delete, - [OCALL_LOAD_DEBUG] = sgx_ocall_load_debug, - [OCALL_EVENTFD] = sgx_ocall_eventfd, - [OCALL_GET_QUOTE] = sgx_ocall_get_quote, - }; - -#define EDEBUG(code, ms) do {} while (0) + [OCALL_EXIT] = sgx_ocall_exit, + [OCALL_MMAP_UNTRUSTED] = sgx_ocall_mmap_untrusted, + [OCALL_MUNMAP_UNTRUSTED] = sgx_ocall_munmap_untrusted, + [OCALL_CPUID] = sgx_ocall_cpuid, + [OCALL_OPEN] = sgx_ocall_open, + [OCALL_CLOSE] = sgx_ocall_close, + [OCALL_READ] = sgx_ocall_read, + [OCALL_WRITE] = sgx_ocall_write, + [OCALL_PREAD] = sgx_ocall_pread, + [OCALL_PWRITE] = sgx_ocall_pwrite, + [OCALL_FSTAT] = sgx_ocall_fstat, + [OCALL_FIONREAD] = sgx_ocall_fionread, + [OCALL_FSETNONBLOCK] = sgx_ocall_fsetnonblock, + [OCALL_FCHMOD] = sgx_ocall_fchmod, + [OCALL_FSYNC] = sgx_ocall_fsync, + [OCALL_FTRUNCATE] = sgx_ocall_ftruncate, + [OCALL_MKDIR] = sgx_ocall_mkdir, + [OCALL_GETDENTS] = sgx_ocall_getdents, + [OCALL_RESUME_THREAD] = sgx_ocall_resume_thread, + [OCALL_CLONE_THREAD] = sgx_ocall_clone_thread, + [OCALL_CREATE_PROCESS] = sgx_ocall_create_process, + [OCALL_FUTEX] = sgx_ocall_futex, + [OCALL_SOCKETPAIR] = sgx_ocall_socketpair, + [OCALL_LISTEN] = sgx_ocall_listen, + [OCALL_ACCEPT] = sgx_ocall_accept, + [OCALL_CONNECT] = sgx_ocall_connect, + [OCALL_RECV] = sgx_ocall_recv, + [OCALL_SEND] = sgx_ocall_send, + [OCALL_SETSOCKOPT] = sgx_ocall_setsockopt, + [OCALL_SHUTDOWN] = sgx_ocall_shutdown, + [OCALL_GETTIME] = sgx_ocall_gettime, + [OCALL_SLEEP] = sgx_ocall_sleep, + [OCALL_POLL] = sgx_ocall_poll, + [OCALL_RENAME] = sgx_ocall_rename, + [OCALL_DELETE] = sgx_ocall_delete, + [OCALL_LOAD_DEBUG] = sgx_ocall_load_debug, + [OCALL_EVENTFD] = sgx_ocall_eventfd, + [OCALL_GET_QUOTE] = sgx_ocall_get_quote, +}; + +#define EDEBUG(code, ms) \ + do { \ + } while (0) rpc_queue_t* g_rpc_queue = NULL; /* pointer to untrusted queue */ @@ -722,9 +705,9 @@ static int rpc_thread_loop(void* arg) { g_rpc_queue->rpc_threads_cnt++; spinlock_unlock(&g_rpc_queue->lock); - static const uint64_t SPIN_ATTEMPTS_MAX = 10000; /* rather arbitrary */ - static const uint64_t SLEEP_TIME_MAX = 100000000; /* nanoseconds (0.1 seconds) */ - static const uint64_t SLEEP_TIME_STEP = 1000000; /* 100 steps before capped */ + static const uint64_t SPIN_ATTEMPTS_MAX = 10000; /* rather arbitrary */ + static const uint64_t SLEEP_TIME_MAX = 100000000; /* nanoseconds (0.1 seconds) */ + static const uint64_t SLEEP_TIME_STEP = 1000000; /* 100 steps before capped */ /* no races possible since vars are thread-local and RPC threads don't receive signals */ uint64_t spin_attempts = 0; @@ -782,8 +765,7 @@ static int start_rpc(size_t num_of_threads) { rpc_queue_init(g_rpc_queue); for (size_t i = 0; i < num_of_threads; i++) { - void* stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, RPC_STACK_SIZE, - PROT_READ | PROT_WRITE, + void* stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, RPC_STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (IS_ERR_P(stack)) return -ENOMEM; @@ -816,7 +798,6 @@ static int start_rpc(size_t num_of_threads) { return 0; } - int ecall_enclave_start(char* libpal_uri, char* args, size_t args_size, char* env, size_t env_size) { g_rpc_queue = NULL; @@ -831,20 +812,19 @@ int ecall_enclave_start(char* libpal_uri, char* args, size_t args_size, char* en } ms_ecall_enclave_start_t ms; - ms.ms_libpal_uri = libpal_uri; + ms.ms_libpal_uri = libpal_uri; ms.ms_libpal_uri_len = strlen(ms.ms_libpal_uri); - ms.ms_args = args; - ms.ms_args_size = args_size; - ms.ms_env = env; - ms.ms_env_size = env_size; - ms.ms_sec_info = &g_pal_enclave.pal_sec; - ms.rpc_queue = g_rpc_queue; + ms.ms_args = args; + ms.ms_args_size = args_size; + ms.ms_env = env; + ms.ms_env_size = env_size; + ms.ms_sec_info = &g_pal_enclave.pal_sec; + ms.rpc_queue = g_rpc_queue; EDEBUG(ECALL_ENCLAVE_START, &ms); return sgx_ecall(ECALL_ENCLAVE_START, &ms); } -int ecall_thread_start (void) -{ +int ecall_thread_start(void) { EDEBUG(ECALL_THREAD_START, NULL); return sgx_ecall(ECALL_THREAD_START, NULL); } diff --git a/Pal/src/host/Linux-SGX/sgx_exception.c b/Pal/src/host/Linux-SGX/sgx_exception.c index 7f2ea64623..67afd8c6ab 100644 --- a/Pal/src/host/Linux-SGX/sgx_exception.c +++ b/Pal/src/host/Linux-SGX/sgx_exception.c @@ -9,6 +9,21 @@ * This file contains APIs to set up signal handlers. */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + +#include "sigset.h" /* FIXME: this include can't be sorted, otherwise we get: + * In file included from sgx_exception.c:19:0: + * ../../../include/arch/x86_64/Linux/ucontext.h:136:5: error: unknown type name ‘__sigset_t’ + * __sigset_t uc_sigmask; + */ + + +#include +#include +#include + #include "api.h" #include "ecall_types.h" #include "ocall_types.h" @@ -16,38 +31,34 @@ #include "rpc_queue.h" #include "sgx_enclave.h" #include "sgx_internal.h" - -#include -#include -#include -#include -#include +#include "ucontext.h" #if defined(__x86_64__) /* in x86_64 kernels, sigaction is required to have a user-defined restorer */ #define DEFINE_RESTORE_RT(syscall) DEFINE_RESTORE_RT2(syscall) -#define DEFINE_RESTORE_RT2(syscall) \ - __asm__ ( \ - " nop\n" \ - ".align 16\n" \ - ".LSTART_restore_rt:\n" \ - " .type __restore_rt,@function\n" \ - "__restore_rt:\n" \ - " movq $" #syscall ", %rax\n" \ - " syscall\n"); +#define DEFINE_RESTORE_RT2(syscall) \ + __asm__( \ + " nop\n" \ + ".align 16\n" \ + ".LSTART_restore_rt:\n" \ + " .type __restore_rt,@function\n" \ + "__restore_rt:\n" \ + " movq $" #syscall \ + ", %rax\n" \ + " syscall\n"); DEFINE_RESTORE_RT(__NR_rt_sigreturn) /* workaround for an old GAS (2.27) bug that incorrectly omits relocations when referencing this * symbol */ __attribute__((visibility("hidden"))) void __restore_rt(void); -#endif /* defined(__x86_64__) */ +#endif /* defined(__x86_64__) */ void sgx_entry_return(void); static const int ASYNC_SIGNALS[] = {SIGTERM, SIGINT, SIGCONT}; static int block_signal(int sig, bool block) { - int how = block? SIG_BLOCK: SIG_UNBLOCK; + int how = block ? SIG_BLOCK : SIG_UNBLOCK; __sigset_t mask; __sigemptyset(&mask); @@ -85,7 +96,7 @@ int block_async_signals(bool block) { } static int get_pal_event(int sig) { - switch(sig) { + switch (sig) { case SIGFPE: return PAL_EVENT_ARITHMETIC_ERROR; case SIGSEGV: diff --git a/Pal/src/host/Linux-SGX/sgx_framework.c b/Pal/src/host/Linux-SGX/sgx_framework.c index 099c5bfec4..11f8fa5534 100644 --- a/Pal/src/host/Linux-SGX/sgx_framework.c +++ b/Pal/src/host/Linux-SGX/sgx_framework.c @@ -1,9 +1,9 @@ #include -#include -#include -#include #include "gsgx.h" +#include "hex.h" +#include "pal_linux.h" +#include "pal_rtld.h" #include "sgx_arch.h" #include "sgx_enclave.h" #include "sgx_internal.h" @@ -29,8 +29,8 @@ int open_sgx_driver(bool need_gsgx) { g_isgx_device = INLINE_SYSCALL(open, 3, ISGX_FILE, O_RDWR | O_CLOEXEC, 0); if (IS_ERR(g_isgx_device)) { - SGX_DBG(DBG_E, "Cannot open device " ISGX_FILE ". Please make sure the" - " Intel SGX kernel module is loaded.\n"); + SGX_DBG(DBG_E, "Cannot open device " ISGX_FILE ". " + "Please make sure the Intel SGX kernel module is loaded.\n"); if (need_gsgx) { INLINE_SYSCALL(close, 1, g_gsgx_device); g_gsgx_device = -1; @@ -41,8 +41,7 @@ int open_sgx_driver(bool need_gsgx) { return 0; } -int read_enclave_token(int token_file, sgx_arch_token_t * token) -{ +int read_enclave_token(int token_file, sgx_arch_token_t* token) { struct stat stat; int ret; ret = INLINE_SYSCALL(fstat, 2, token_file, &stat); @@ -65,7 +64,8 @@ int read_enclave_token(int token_file, sgx_arch_token_t * token) SGX_DBG(DBG_I, " valid: 0x%08x\n", token->body.valid); SGX_DBG(DBG_I, " attr.flags: 0x%016lx\n", token->body.attributes.flags); SGX_DBG(DBG_I, " attr.xfrm: 0x%016lx\n", token->body.attributes.xfrm); - SGX_DBG(DBG_I, " mr_enclave: %s\n", ALLOCA_BYTES2HEXSTR(token->body.mr_enclave.m)); + SGX_DBG(DBG_I, " mr_enclave: %s\n", + ALLOCA_BYTES2HEXSTR(token->body.mr_enclave.m)); SGX_DBG(DBG_I, " mr_signer: %s\n", ALLOCA_BYTES2HEXSTR(token->body.mr_signer.m)); SGX_DBG(DBG_I, " LE cpu_svn: %s\n", ALLOCA_BYTES2HEXSTR(token->cpu_svn_le.svn)); SGX_DBG(DBG_I, " LE isv_prod_id: %02x\n", token->isv_prod_id_le); @@ -78,8 +78,7 @@ int read_enclave_token(int token_file, sgx_arch_token_t * token) return 0; } -int read_enclave_sigstruct(int sigfile, sgx_arch_enclave_css_t * sig) -{ +int read_enclave_sigstruct(int sigfile, sgx_arch_enclave_css_t* sig) { struct stat stat; int ret; ret = INLINE_SYSCALL(fstat, 2, sigfile, &stat); @@ -98,14 +97,13 @@ int read_enclave_sigstruct(int sigfile, sgx_arch_enclave_css_t * sig) return 0; } -static size_t get_ssaframesize (uint64_t xfrm) -{ +static size_t get_ssaframesize(uint64_t xfrm) { uint32_t cpuinfo[4]; uint64_t xfrm_ex; size_t xsave_size = 0; cpuid(INTEL_SGX_LEAF, 1, cpuinfo); - xfrm_ex = ((uint64_t) cpuinfo[3] << 32) + cpuinfo[2]; + xfrm_ex = ((uint64_t)cpuinfo[3] << 32) + cpuinfo[2]; for (int i = 2; i < 64; i++) if ((xfrm & (1ULL << i)) || (xfrm_ex & (1ULL << i))) { @@ -117,29 +115,26 @@ static size_t get_ssaframesize (uint64_t xfrm) return ALLOC_ALIGN_UP(xsave_size + sizeof(sgx_pal_gpr_t) + 1); } -bool is_wrfsbase_supported (void) -{ +bool is_wrfsbase_supported(void) { uint32_t cpuinfo[4]; cpuid(7, 0, cpuinfo); if (!(cpuinfo[1] & 0x1)) { - SGX_DBG(DBG_E, "The WRFSBASE instruction is not permitted on this" - " platform. Please make sure the Graphene SGX kernel module" - " is loaded properly.\n"); + SGX_DBG(DBG_E, + "The WRFSBASE instruction is not permitted on this platform. Please make sure the " + "Graphene SGX kernel module is loaded properly.\n"); return false; } return true; } -int create_enclave(sgx_arch_secs_t * secs, - sgx_arch_token_t * token) -{ +int create_enclave(sgx_arch_secs_t* secs, sgx_arch_token_t* token) { assert(secs->size && IS_POWER_OF_2(secs->size)); assert(IS_ALIGNED(secs->base, secs->size)); secs->ssa_frame_size = get_ssaframesize(token->body.attributes.xfrm) / g_page_size; - secs->misc_select = token->masked_misc_select_le; + secs->misc_select = token->masked_misc_select_le; memcpy(&secs->attributes, &token->body.attributes, sizeof(sgx_attributes_t)); /* Do not initialize secs->mr_signer and secs->mr_enclave here as they are @@ -181,7 +176,7 @@ int create_enclave(sgx_arch_secs_t * secs, assert(addr == request_mmap_addr); struct sgx_enclave_create param = { - .src = (uint64_t) secs, + .src = (uint64_t)secs, }; int ret = INLINE_SYSCALL(ioctl, 3, g_isgx_device, SGX_IOC_ENCLAVE_CREATE, ¶m); @@ -210,13 +205,9 @@ int create_enclave(sgx_arch_secs_t * secs, return 0; } -int add_pages_to_enclave(sgx_arch_secs_t * secs, - void * addr, void * user_addr, - unsigned long size, - enum sgx_page_type type, int prot, - bool skip_eextend, - const char * comment) -{ +int add_pages_to_enclave(sgx_arch_secs_t* secs, void* addr, void* user_addr, unsigned long size, + enum sgx_page_type type, int prot, bool skip_eextend, + const char* comment) { sgx_arch_sec_info_t secinfo; int ret; @@ -251,8 +242,8 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, } char p[4] = "---"; - const char * t = (type == SGX_PAGE_TCS) ? "TCS" : "REG"; - const char * m = skip_eextend ? "" : " measured"; + const char* t = (type == SGX_PAGE_TCS) ? "TCS" : "REG"; + const char* m = skip_eextend ? "" : " measured"; if (type == SGX_PAGE_REG) { if (prot & PROT_READ) @@ -264,11 +255,10 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, } if (size == g_page_size) - SGX_DBG(DBG_I, "adding page to enclave: %p [%s:%s] (%s)%s\n", - addr, t, p, comment, m); + SGX_DBG(DBG_I, "adding page to enclave: %p [%s:%s] (%s)%s\n", addr, t, p, comment, m); else - SGX_DBG(DBG_I, "adding pages to enclave: %p-%p [%s:%s] (%s)%s\n", - addr, addr + size, t, p, comment, m); + SGX_DBG(DBG_I, "adding pages to enclave: %p-%p [%s:%s] (%s)%s\n", addr, addr + size, t, p, + comment, m); #ifdef SGX_DCAP_16_OR_LATER if (!user_addr && g_zero_pages_size < size) { @@ -290,12 +280,12 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, /* newer DCAP driver (version 1.6+) allows adding a range of pages for performance, use it */ struct sgx_enclave_add_pages param = { - .offset = (uint64_t)addr, - .src = (uint64_t)(user_addr ? : g_zero_pages), - .length = size, - .secinfo = (uint64_t)&secinfo, - .flags = skip_eextend ? 0 : SGX_PAGE_MEASURE, - .count = 0, /* output parameter, will be checked after IOCTL */ + .offset = (uint64_t)addr, + .src = (uint64_t)(user_addr ?: g_zero_pages), + .length = size, + .secinfo = (uint64_t)&secinfo, + .flags = skip_eextend ? 0 : SGX_PAGE_MEASURE, + .count = 0, /* output parameter, will be checked after IOCTL */ }; ret = INLINE_SYSCALL(ioctl, 3, g_isgx_device, SGX_IOC_ENCLAVE_ADD_PAGES, ¶m); @@ -310,8 +300,8 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, } /* ask Intel SGX driver to actually mmap the added enclave pages */ - uint64_t mapped = INLINE_SYSCALL(mmap, 6, secs->base + addr, size, prot, - MAP_FIXED | MAP_SHARED, g_isgx_device, 0); + uint64_t mapped = INLINE_SYSCALL(mmap, 6, secs->base + addr, size, prot, MAP_FIXED | MAP_SHARED, + g_isgx_device, 0); if (IS_ERR_P(mapped)) { SGX_DBG(DBG_I, "Cannot map enclave pages %ld\n", ERRNO_P(mapped)); return -EACCES; @@ -319,10 +309,10 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, #else /* older drivers (DCAP v1.5- and old out-of-tree) only supports adding one page at a time */ struct sgx_enclave_add_page param = { - .addr = secs->base + (uint64_t) addr, - .src = (uint64_t) (user_addr ? : g_zero_pages), - .secinfo = (uint64_t) &secinfo, - .mrmask = skip_eextend ? 0 : (uint16_t) -1, + .addr = secs->base + (uint64_t)addr, + .src = (uint64_t)(user_addr ?: g_zero_pages), + .secinfo = (uint64_t)&secinfo, + .mrmask = skip_eextend ? 0 : (uint16_t)-1, }; uint64_t added_size = 0; @@ -350,10 +340,8 @@ int add_pages_to_enclave(sgx_arch_secs_t * secs, return 0; } -int init_enclave(sgx_arch_secs_t * secs, - sgx_arch_enclave_css_t * sigstruct, - sgx_arch_token_t * token) -{ +int init_enclave(sgx_arch_secs_t* secs, sgx_arch_enclave_css_t* sigstruct, + sgx_arch_token_t* token) { #ifdef SGX_DCAP __UNUSED(token); #endif @@ -365,11 +353,11 @@ int init_enclave(sgx_arch_secs_t * secs, struct sgx_enclave_init param = { #ifndef SGX_DCAP_16_OR_LATER - .addr = enclave_valid_addr, + .addr = enclave_valid_addr, #endif - .sigstruct = (uint64_t) sigstruct, + .sigstruct = (uint64_t)sigstruct, #ifndef SGX_DCAP - .einittoken = (uint64_t) token, + .einittoken = (uint64_t)token, #endif }; int ret = INLINE_SYSCALL(ioctl, 3, g_isgx_device, SGX_IOC_ENCLAVE_INIT, ¶m); @@ -379,23 +367,30 @@ int init_enclave(sgx_arch_secs_t * secs, } if (ret) { - const char * error; + const char* error; /* DEP 3/22/17: Try to improve error messages */ - switch(ret) { - case SGX_INVALID_SIG_STRUCT: - error = "Invalid SIGSTRUCT"; break; - case SGX_INVALID_ATTRIBUTE: - error = "Invalid enclave attribute"; break; - case SGX_INVALID_MEASUREMENT: - error = "Invalid measurement"; break; - case SGX_INVALID_SIGNATURE: - error = "Invalid signature"; break; - case SGX_INVALID_LICENSE: - error = "Invalid EINIT token"; break; - case SGX_INVALID_CPUSVN: - error = "Invalid CPU SVN"; break; - default: - error = "Unknown reason"; break; + switch (ret) { + case SGX_INVALID_SIG_STRUCT: + error = "Invalid SIGSTRUCT"; + break; + case SGX_INVALID_ATTRIBUTE: + error = "Invalid enclave attribute"; + break; + case SGX_INVALID_MEASUREMENT: + error = "Invalid measurement"; + break; + case SGX_INVALID_SIGNATURE: + error = "Invalid signature"; + break; + case SGX_INVALID_LICENSE: + error = "Invalid EINIT token"; + break; + case SGX_INVALID_CPUSVN: + error = "Invalid CPU SVN"; + break; + default: + error = "Unknown reason"; + break; } SGX_DBG(DBG_I, "enclave EINIT failed - %s\n", error); return -EPERM; @@ -411,9 +406,7 @@ int init_enclave(sgx_arch_secs_t * secs, return 0; } -int destroy_enclave(void * base_addr, size_t length) -{ - +int destroy_enclave(void* base_addr, size_t length) { SGX_DBG(DBG_I, "destroying enclave...\n"); int ret = INLINE_SYSCALL(munmap, 2, base_addr, length); diff --git a/Pal/src/host/Linux-SGX/sgx_graphene.c b/Pal/src/host/Linux-SGX/sgx_graphene.c index 5d27c460e5..18ec318f0d 100644 --- a/Pal/src/host/Linux-SGX/sgx_graphene.c +++ b/Pal/src/host/Linux-SGX/sgx_graphene.c @@ -1,26 +1,23 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2014 Stony Brook University */ -#include -#include -#include - -#include #include +#include +#include "atomic.h" +#include "pal.h" +#include "pal_error.h" #include "sgx_internal.h" -#define PRINTBUF_SIZE 256 +#define PRINTBUF_SIZE 256 struct printbuf { - int idx; // current buffer index - int cnt; // total bytes printed so far + int idx; // current buffer index + int cnt; // total bytes printed so far char buf[PRINTBUF_SIZE]; }; -static int -fputch(void * f, int ch, struct printbuf * b) -{ +static int fputch(void* f, int ch, struct printbuf* b) { __UNUSED(f); b->buf[b->idx++] = ch; @@ -32,22 +29,18 @@ fputch(void * f, int ch, struct printbuf * b) return 0; } -static int -vprintf(const char * fmt, va_list ap) -{ +static int vprintf(const char* fmt, va_list ap) { struct printbuf b; b.idx = 0; b.cnt = 0; - vfprintfmt((void *) &fputch, NULL, &b, fmt, ap); + vfprintfmt((void*)&fputch, NULL, &b, fmt, ap); INLINE_SYSCALL(write, 3, 2, b.buf, b.idx); return b.cnt; } -int -pal_printf(const char * fmt, ...) -{ +int pal_printf(const char* fmt, ...) { va_list ap; int cnt; diff --git a/Pal/src/host/Linux-SGX/sgx_internal.h b/Pal/src/host/Linux-SGX/sgx_internal.h index 5c7b1559a7..5ee16cf8bd 100644 --- a/Pal/src/host/Linux-SGX/sgx_internal.h +++ b/Pal/src/host/Linux-SGX/sgx_internal.h @@ -11,20 +11,20 @@ #ifndef SGX_INTERNAL_H #define SGX_INTERNAL_H +#include + +#include "api.h" #include "pal_linux.h" #include "pal_security.h" -#include "api.h" - #include "sysdep-arch.h" -#include -#define IS_ERR INTERNAL_SYSCALL_ERROR +#define IS_ERR INTERNAL_SYSCALL_ERROR #define IS_ERR_P INTERNAL_SYSCALL_ERROR_P -#define ERRNO INTERNAL_SYSCALL_ERRNO -#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P +#define ERRNO INTERNAL_SYSCALL_ERRNO +#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P -int printf(const char * fmt, ...) __attribute__((format(printf, 1, 2))); -int snprintf(char * str, size_t size, const char * fmt, ...) __attribute__((format(printf, 3, 4))); +int printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); +int snprintf(char* str, size_t size, const char* fmt, ...) __attribute__((format(printf, 3, 4))); /* constants and macros to help rounding addresses to page boundaries */ @@ -44,10 +44,10 @@ extern size_t g_page_size; #define ALLOC_ALIGN_DOWN(addr) ALIGN_DOWN_POW2(addr, g_page_size) #define ALLOC_ALIGN_DOWN_PTR(addr) ALIGN_DOWN_PTR_POW2(addr, g_page_size) -uint32_t htonl (uint32_t longval); -uint16_t htons (uint16_t shortval); -uint32_t ntohl (uint32_t longval); -uint16_t ntohs (uint16_t shortval); +uint32_t htonl(uint32_t longval); +uint16_t htons(uint16_t shortval); +uint32_t ntohl(uint32_t longval); +uint16_t ntohs(uint16_t shortval); extern struct pal_enclave { /* attributes */ @@ -64,7 +64,7 @@ extern struct pal_enclave { int token; /* manifest */ - struct config_store * config; + struct config_store* config; /* Path to the PAL binary */ char* libpal_uri; @@ -74,21 +74,16 @@ extern struct pal_enclave { } g_pal_enclave; int open_sgx_driver(bool need_gsgx); -bool is_wrfsbase_supported (void); +bool is_wrfsbase_supported(void); -int read_enclave_token (int token_file, sgx_arch_token_t * token); -int read_enclave_sigstruct (int sigfile, sgx_arch_enclave_css_t * sig); +int read_enclave_token(int token_file, sgx_arch_token_t* token); +int read_enclave_sigstruct(int sigfile, sgx_arch_enclave_css_t* sig); -int create_enclave(sgx_arch_secs_t * secs, - sgx_arch_token_t * token); +int create_enclave(sgx_arch_secs_t* secs, sgx_arch_token_t* token); enum sgx_page_type { SGX_PAGE_SECS, SGX_PAGE_TCS, SGX_PAGE_REG }; -int add_pages_to_enclave(sgx_arch_secs_t * secs, - void * addr, void * user_addr, - unsigned long size, - enum sgx_page_type type, int prot, - bool skip_eextend, - const char * comment); +int add_pages_to_enclave(sgx_arch_secs_t* secs, void* addr, void* user_addr, unsigned long size, + enum sgx_page_type type, int prot, bool skip_eextend, const char* comment); /*! * \brief Retrieve Quoting Enclave's sgx_target_info_t by talking to AESMD. @@ -113,37 +108,35 @@ int init_quoting_enclave_targetinfo(sgx_target_info_t* qe_targetinfo); int retrieve_quote(const sgx_spid_t* spid, bool linkable, const sgx_report_t* report, const sgx_quote_nonce_t* nonce, char** quote, size_t* quote_len); -int init_enclave(sgx_arch_secs_t * secs, - sgx_arch_enclave_css_t * sigstruct, - sgx_arch_token_t * token); +int init_enclave(sgx_arch_secs_t* secs, sgx_arch_enclave_css_t* sigstruct, sgx_arch_token_t* token); -int destroy_enclave(void * base_addr, size_t length); -void exit_process (int status, uint64_t start_exiting); +int destroy_enclave(void* base_addr, size_t length); +void exit_process(int status, uint64_t start_exiting); -int sgx_ecall (long ecall_no, void * ms); -int sgx_raise (int event); +int sgx_ecall(long ecall_no, void* ms); +int sgx_raise(int event); void async_exit_pointer(void); void eresume_pointer(void); void async_exit_pointer_end(void); -int interrupt_thread (void * tcs); -int clone_thread (void); +int interrupt_thread(void* tcs); +int clone_thread(void); -void create_tcs_mapper (void * tcs_base, unsigned int thread_num); +void create_tcs_mapper(void* tcs_base, unsigned int thread_num); int pal_thread_init(void* tcbptr); void map_tcs(unsigned int tid); void unmap_tcs(void); int current_enclave_thread_cnt(void); void thread_exit(int status); -uint64_t sgx_edbgrd (void * addr); -void sgx_edbgwr (void * addr, uint64_t data); +uint64_t sgx_edbgrd(void* addr); +void sgx_edbgwr(void* addr, uint64_t data); int sgx_init_child_process(int parent_pipe_fd, struct pal_sec* pal_sec); -int sgx_signal_setup (void); -int block_signals (bool block, const int * sigs, int nsig); -int block_async_signals (bool block); +int sgx_signal_setup(void); +int block_signals(bool block, const int* sigs, int nsig); +int block_async_signals(bool block); void load_gdb_command(const char* command); diff --git a/Pal/src/host/Linux-SGX/sgx_main.c b/Pal/src/host/Linux-SGX/sgx_main.c index fa1ff6f82b..a4381a1786 100644 --- a/Pal/src/host/Linux-SGX/sgx_main.c +++ b/Pal/src/host/Linux-SGX/sgx_main.c @@ -1,7 +1,12 @@ -#include -#include -#include -#include +/* FIXME: Sorting+re-grouping includes here causes tons of + * "../../../include/sysdeps/generic/ldsodefs.h:30:32: error: unknown type name ‘Elf__ELF_NATIVE_CLASS_Addr’ + * #define ElfW(type) _ElfW(Elf, __ELF_NATIVE_CLASS, type)" + * errors. + */ +#include "pal_linux.h" +#include "pal_linux_error.h" +#include "pal_rtld.h" +#include "hex.h" #include "debugger/sgx_gdb.h" #include "linux_utils.h" @@ -19,8 +24,9 @@ #include #include #include -#include -#include + +#include "sysdep.h" +#include "sysdeps/generic/ldsodefs.h" size_t g_page_size = PRESET_PAGESIZE; @@ -29,14 +35,11 @@ char* g_libpal_path = NULL; struct pal_enclave g_pal_enclave; -static inline -char * alloc_concat(const char * p, size_t plen, - const char * s, size_t slen) -{ +static inline char* alloc_concat(const char* p, size_t plen, const char* s, size_t slen) { plen = (plen != (size_t)-1) ? plen : (p ? strlen(p) : 0); slen = (slen != (size_t)-1) ? slen : (s ? strlen(s) : 0); - char * buf = malloc(plen + slen + 1); + char* buf = malloc(plen + slen + 1); if (!buf) return NULL; @@ -83,8 +86,7 @@ static unsigned long parse_int (const char * str) return num; } -static char * resolve_uri (const char * uri, const char ** errstring) -{ +static char* resolve_uri(const char* uri, const char** errstring) { if (!strstartswith_static(uri, URI_PREFIX_FILE)) { *errstring = "Invalid URI"; return NULL; @@ -101,10 +103,8 @@ static char * resolve_uri (const char * uri, const char ** errstring) return alloc_concat(URI_PREFIX_FILE, URI_PREFIX_FILE_LEN, path_buf, len); } -static -int scan_enclave_binary (int fd, unsigned long * base, unsigned long * size, - unsigned long * entry) -{ +static int scan_enclave_binary(int fd, unsigned long* base, unsigned long* size, + unsigned long* entry) { int ret = 0; if (IS_ERR(ret = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_SET))) @@ -118,9 +118,9 @@ int scan_enclave_binary (int fd, unsigned long * base, unsigned long * size, if ((size_t)ret < sizeof(ElfW(Ehdr))) return -ENOEXEC; - const ElfW(Ehdr) * header = (void *) filebuf; - const ElfW(Phdr) * phdr = (void *) filebuf + header->e_phoff; - const ElfW(Phdr) * ph; + const ElfW(Ehdr)* header = (void*)filebuf; + const ElfW(Phdr)* phdr = (void*)filebuf + header->e_phoff; + const ElfW(Phdr)* ph; if (memcmp(header->e_ident, ELFMAG, SELFMAG) != 0) return -ENOEXEC; @@ -130,14 +130,14 @@ int scan_enclave_binary (int fd, unsigned long * base, unsigned long * size, } loadcmds[16], *c; int nloadcmds = 0; - for (ph = phdr ; ph < &phdr[header->e_phnum] ; ph++) + for (ph = phdr; ph < &phdr[header->e_phnum]; ph++) if (ph->p_type == PT_LOAD) { if (nloadcmds == 16) return -EINVAL; c = &loadcmds[nloadcmds++]; c->mapstart = ALLOC_ALIGN_DOWN(ph->p_vaddr); - c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_memsz); + c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_memsz); } *base = loadcmds[0].mapstart; @@ -147,10 +147,8 @@ int scan_enclave_binary (int fd, unsigned long * base, unsigned long * size, return 0; } -static -int load_enclave_binary (sgx_arch_secs_t * secs, int fd, - unsigned long base, unsigned long prot) -{ +static int load_enclave_binary(sgx_arch_secs_t* secs, int fd, unsigned long base, + unsigned long prot) { int ret = 0; if (IS_ERR(ret = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_SET))) @@ -161,9 +159,9 @@ int load_enclave_binary (sgx_arch_secs_t * secs, int fd, if (IS_ERR(ret)) return -ERRNO(ret); - const ElfW(Ehdr) * header = (void *) filebuf; - const ElfW(Phdr) * phdr = (void *) filebuf + header->e_phoff; - const ElfW(Phdr) * ph; + const ElfW(Ehdr)* header = (void*)filebuf; + const ElfW(Phdr)* phdr = (void*)filebuf + header->e_phoff; + const ElfW(Phdr)* ph; struct loadcmd { ElfW(Addr) mapstart, mapend, datastart, dataend, allocend; @@ -172,38 +170,35 @@ int load_enclave_binary (sgx_arch_secs_t * secs, int fd, } loadcmds[16], *c; int nloadcmds = 0; - for (ph = phdr ; ph < &phdr[header->e_phnum] ; ph++) + for (ph = phdr; ph < &phdr[header->e_phnum]; ph++) if (ph->p_type == PT_LOAD) { if (nloadcmds == 16) return -EINVAL; c = &loadcmds[nloadcmds++]; - c->mapstart = ALLOC_ALIGN_DOWN(ph->p_vaddr); - c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_filesz); + c->mapstart = ALLOC_ALIGN_DOWN(ph->p_vaddr); + c->mapend = ALLOC_ALIGN_UP(ph->p_vaddr + ph->p_filesz); c->datastart = ph->p_vaddr; - c->dataend = ph->p_vaddr + ph->p_filesz; - c->allocend = ph->p_vaddr + ph->p_memsz; - c->mapoff = ALLOC_ALIGN_DOWN(ph->p_offset); - c->prot = (ph->p_flags & PF_R ? PROT_READ : 0)| - (ph->p_flags & PF_W ? PROT_WRITE : 0)| - (ph->p_flags & PF_X ? PROT_EXEC : 0)|prot; + c->dataend = ph->p_vaddr + ph->p_filesz; + c->allocend = ph->p_vaddr + ph->p_memsz; + c->mapoff = ALLOC_ALIGN_DOWN(ph->p_offset); + c->prot = (ph->p_flags & PF_R ? PROT_READ : 0) | (ph->p_flags & PF_W ? PROT_WRITE : 0) | + (ph->p_flags & PF_X ? PROT_EXEC : 0) | prot; } base -= loadcmds[0].mapstart; - for (c = loadcmds; c < &loadcmds[nloadcmds] ; c++) { - ElfW(Addr) zero = c->dataend; - ElfW(Addr) zeroend = ALLOC_ALIGN_UP(c->allocend); + for (c = loadcmds; c < &loadcmds[nloadcmds]; c++) { + ElfW(Addr) zero = c->dataend; + ElfW(Addr) zeroend = ALLOC_ALIGN_UP(c->allocend); ElfW(Addr) zeropage = ALLOC_ALIGN_UP(zero); if (zeroend < zeropage) zeropage = zeroend; if (c->mapend > c->mapstart) { - void * addr = (void *) INLINE_SYSCALL(mmap, 6, NULL, - c->mapend - c->mapstart, - PROT_READ|PROT_WRITE, - MAP_PRIVATE | MAP_FILE, - fd, c->mapoff); + void* addr = (void*)INLINE_SYSCALL(mmap, 6, NULL, c->mapend - c->mapstart, + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, fd, + c->mapoff); if (IS_ERR_P(addr)) return -ERRNO_P(addr); @@ -214,7 +209,7 @@ int load_enclave_binary (sgx_arch_secs_t * secs, int fd, if (zeropage > zero) memset(addr + zero - c->mapstart, 0, zeropage - zero); - ret = add_pages_to_enclave(secs, (void *) base + c->mapstart, addr, + ret = add_pages_to_enclave(secs, (void*)base + c->mapstart, addr, c->mapend - c->mapstart, SGX_PAGE_REG, c->prot, /*skip_eextend=*/false, (c->prot & PROT_EXEC) ? "code" : "data"); @@ -226,8 +221,7 @@ int load_enclave_binary (sgx_arch_secs_t * secs, int fd, } if (zeroend > zeropage) { - ret = add_pages_to_enclave(secs, (void *) base + zeropage, NULL, - zeroend - zeropage, + ret = add_pages_to_enclave(secs, (void*)base + zeropage, NULL, zeroend - zeropage, SGX_PAGE_REG, c->prot, false, "bss"); if (ret < 0) return ret; @@ -239,20 +233,19 @@ int load_enclave_binary (sgx_arch_secs_t * secs, int fd, static int initialize_enclave(struct pal_enclave* enclave) { int ret = 0; - int enclave_image = -1; - sgx_arch_token_t enclave_token; + int enclave_image = -1; + sgx_arch_token_t enclave_token; sgx_arch_enclave_css_t enclave_sigstruct; - sgx_arch_secs_t enclave_secs; - unsigned long enclave_entry_addr; - unsigned long heap_min = DEFAULT_HEAP_MIN; + sgx_arch_secs_t enclave_secs; + unsigned long enclave_entry_addr; + unsigned long heap_min = DEFAULT_HEAP_MIN; int enclave_mem = -1; /* this array may overflow the stack, so we allocate it in BSS */ static void* tcs_addrs[MAX_DBG_THREADS]; - enclave_image = INLINE_SYSCALL(open, 3, enclave->libpal_uri + URI_PREFIX_FILE_LEN, O_RDONLY, - 0); + enclave_image = INLINE_SYSCALL(open, 3, enclave->libpal_uri + URI_PREFIX_FILE_LEN, O_RDONLY, 0); if (IS_ERR(enclave_image)) { SGX_DBG(DBG_E, "Cannot find enclave image: %s\n", enclave->libpal_uri); ret = -ERRNO(enclave_image); @@ -298,15 +291,17 @@ static int initialize_enclave(struct pal_enclave* enclave) { } if (enclave->rpc_thread_num && enclave->thread_num > RPC_QUEUE_SIZE) { - SGX_DBG(DBG_E, "Too many threads for exitless feature (more than capacity of RPC queue)\n"); + SGX_DBG(DBG_E, + "Too many threads for exitless feature (more than capacity of RPC queue)\n"); ret = -EINVAL; goto out; } } else { - enclave->rpc_thread_num = 0; /* by default, do not use exitless feature */ + enclave->rpc_thread_num = 0; /* by default, do not use exitless feature */ } - if (get_config(enclave->config, "sgx.static_address", cfgbuf, sizeof(cfgbuf)) > 0 && cfgbuf[0] == '1') { + if (get_config(enclave->config, "sgx.static_address", cfgbuf, sizeof(cfgbuf)) > 0 + && cfgbuf[0] == '1') { enclave->baseaddr = ALIGN_DOWN_POW2(heap_min, enclave->size); } else { enclave->baseaddr = ENCLAVE_HIGH_ADDRESS; @@ -353,7 +348,7 @@ static int initialize_enclave(struct pal_enclave* enclave) { /* Start populating enclave memory */ struct mem_area { - const char * desc; + const char* desc; bool skip_eextend; int fd; bool is_binary; /* only meaningful if fd != -1 */ @@ -367,66 +362,87 @@ static int initialize_enclave(struct pal_enclave* enclave) { * + enclave->thread_num for signal stack */ int area_num_max = 10 + enclave->thread_num * 2; - struct mem_area * areas = __alloca(sizeof(areas[0]) * area_num_max); + struct mem_area* areas = __alloca(sizeof(areas[0]) * area_num_max); int area_num = 0; /* The manifest needs to be allocated at the upper end of the enclave * memory. That's used by pal_linux_main to find the manifest area. So add * it first to the list with memory areas. */ - areas[area_num] = (struct mem_area) { - .desc = "manifest", .skip_eextend = false, .fd = enclave->manifest, - .is_binary = false, .addr = 0, .size = ALLOC_ALIGN_UP(manifest_size), - .prot = PROT_READ, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "manifest", + .skip_eextend = false, + .fd = enclave->manifest, + .is_binary = false, + .addr = 0, + .size = ALLOC_ALIGN_UP(manifest_size), + .prot = PROT_READ, + .type = SGX_PAGE_REG}; area_num++; - areas[area_num] = (struct mem_area) { - .desc = "ssa", .skip_eextend = false, .fd = -1, - .is_binary = false, .addr = 0, - .size = enclave->thread_num * enclave->ssaframesize * SSAFRAMENUM, - .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG - }; + areas[area_num] = + (struct mem_area){.desc = "ssa", + .skip_eextend = false, + .fd = -1, + .is_binary = false, + .addr = 0, + .size = enclave->thread_num * enclave->ssaframesize * SSAFRAMENUM, + .prot = PROT_READ | PROT_WRITE, + .type = SGX_PAGE_REG}; struct mem_area* ssa_area = &areas[area_num++]; - areas[area_num] = (struct mem_area) { - .desc = "tcs", .skip_eextend = false, .fd = -1, - .is_binary = false, .addr = 0, .size = enclave->thread_num * g_page_size, - .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_TCS - }; + areas[area_num] = (struct mem_area){.desc = "tcs", + .skip_eextend = false, + .fd = -1, + .is_binary = false, + .addr = 0, + .size = enclave->thread_num * g_page_size, + .prot = PROT_READ | PROT_WRITE, + .type = SGX_PAGE_TCS}; struct mem_area* tcs_area = &areas[area_num++]; - areas[area_num] = (struct mem_area) { - .desc = "tls", .skip_eextend = false, .fd = -1, - .is_binary = false, .addr = 0, .size = enclave->thread_num * g_page_size, - .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "tls", + .skip_eextend = false, + .fd = -1, + .is_binary = false, + .addr = 0, + .size = enclave->thread_num * g_page_size, + .prot = PROT_READ | PROT_WRITE, + .type = SGX_PAGE_REG}; struct mem_area* tls_area = &areas[area_num++]; struct mem_area* stack_areas = &areas[area_num]; /* memorize for later use */ for (uint32_t t = 0; t < enclave->thread_num; t++) { - areas[area_num] = (struct mem_area) { - .desc = "stack", .skip_eextend = false, .fd = -1, - .is_binary = false, .addr = 0, .size = ENCLAVE_STACK_SIZE, - .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "stack", + .skip_eextend = false, + .fd = -1, + .is_binary = false, + .addr = 0, + .size = ENCLAVE_STACK_SIZE, + .prot = PROT_READ | PROT_WRITE, + .type = SGX_PAGE_REG}; area_num++; } struct mem_area* sig_stack_areas = &areas[area_num]; /* memorize for later use */ for (uint32_t t = 0; t < enclave->thread_num; t++) { - areas[area_num] = (struct mem_area) { - .desc = "sig_stack", .skip_eextend = false, .fd = -1, - .is_binary = false, .addr = 0, .size = ENCLAVE_SIG_STACK_SIZE, - .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "sig_stack", + .skip_eextend = false, + .fd = -1, + .is_binary = false, + .addr = 0, + .size = ENCLAVE_SIG_STACK_SIZE, + .prot = PROT_READ | PROT_WRITE, + .type = SGX_PAGE_REG}; area_num++; } - areas[area_num] = (struct mem_area) { - .desc = "pal", .skip_eextend = false, .fd = enclave_image, - .is_binary = true, .addr = 0, .size = 0 /* set below */, - .prot = 0, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "pal", + .skip_eextend = false, + .fd = enclave_image, + .is_binary = true, + .addr = 0, + .size = 0 /* set below */, + .prot = 0, + .type = SGX_PAGE_REG}; struct mem_area* pal_area = &areas[area_num++]; ret = scan_enclave_binary(enclave_image, &pal_area->addr, &pal_area->size, &enclave_entry_addr); @@ -437,11 +453,14 @@ static int initialize_enclave(struct pal_enclave* enclave) { struct mem_area* exec_area = NULL; if (enclave->exec != -1) { - areas[area_num] = (struct mem_area) { - .desc = "exec", .skip_eextend = false, .fd = enclave->exec, - .is_binary = true, .addr = 0, .size = 0 /* set below */, - .prot = PROT_WRITE, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "exec", + .skip_eextend = false, + .fd = enclave->exec, + .is_binary = true, + .addr = 0, + .size = 0 /* set below */, + .prot = PROT_WRITE, + .type = SGX_PAGE_REG}; exec_area = &areas[area_num++]; ret = scan_enclave_binary(enclave->exec, &exec_area->addr, &exec_area->size, NULL); @@ -474,11 +493,14 @@ static int initialize_enclave(struct pal_enclave* enclave) { if (addr < heap_min) addr = heap_min; - areas[area_num] = (struct mem_area) { - .desc = "free", .skip_eextend = true, .fd = -1, - .is_binary = false, .addr = addr, .size = populating - addr, - .prot = PROT_READ | PROT_WRITE | PROT_EXEC, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "free", + .skip_eextend = true, + .fd = -1, + .is_binary = false, + .addr = addr, + .size = populating - addr, + .prot = PROT_READ | PROT_WRITE | PROT_EXEC, + .type = SGX_PAGE_REG}; area_num++; } @@ -487,15 +509,18 @@ static int initialize_enclave(struct pal_enclave* enclave) { } if (populating > heap_min) { - areas[area_num] = (struct mem_area) { - .desc = "free", .skip_eextend = true, .fd = -1, - .is_binary = false, .addr = heap_min, .size = populating - heap_min, - .prot = PROT_READ | PROT_WRITE | PROT_EXEC, .type = SGX_PAGE_REG - }; + areas[area_num] = (struct mem_area){.desc = "free", + .skip_eextend = true, + .fd = -1, + .is_binary = false, + .addr = heap_min, + .size = populating - heap_min, + .prot = PROT_READ | PROT_WRITE | PROT_EXEC, + .type = SGX_PAGE_REG}; area_num++; } - for (int i = 0 ; i < area_num ; i++) { + for (int i = 0; i < area_num; i++) { if (areas[i].fd != -1 && areas[i].is_binary) { ret = load_enclave_binary(&enclave_secs, areas[i].fd, areas[i].addr, areas[i].prot); if (ret < 0) { @@ -505,75 +530,64 @@ static int initialize_enclave(struct pal_enclave* enclave) { continue; } - void * data = NULL; + void* data = NULL; if (!strcmp_static(areas[i].desc, "tls")) { - data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, - PROT_READ|PROT_WRITE, - MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); + data = (void*)INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (IS_ERR_P(data) || data == NULL) { /* Note that Graphene currently doesn't handle 0x0 addresses */ SGX_DBG(DBG_E, "Allocating memory for tls pages failed\n"); goto out; } - for (uint32_t t = 0 ; t < enclave->thread_num ; t++) { - struct enclave_tls * gs = data + g_page_size * t; + for (uint32_t t = 0; t < enclave->thread_num; t++) { + struct enclave_tls* gs = data + g_page_size * t; memset(gs, 0, g_page_size); assert(sizeof(*gs) <= g_page_size); - gs->common.self = (PAL_TCB *)( - tls_area->addr + g_page_size * t + enclave_secs.base); + gs->common.self = (PAL_TCB*)(tls_area->addr + g_page_size * t + enclave_secs.base); gs->enclave_size = enclave->size; gs->tcs_offset = tcs_area->addr + g_page_size * t; - gs->initial_stack_offset = - stack_areas[t].addr + ENCLAVE_STACK_SIZE; - gs->sig_stack_low = - sig_stack_areas[t].addr + enclave_secs.base; + gs->initial_stack_offset = stack_areas[t].addr + ENCLAVE_STACK_SIZE; + gs->sig_stack_low = sig_stack_areas[t].addr + enclave_secs.base; gs->sig_stack_high = - sig_stack_areas[t].addr + ENCLAVE_SIG_STACK_SIZE + - enclave_secs.base; - gs->ssa = (void *) ssa_area->addr + - enclave->ssaframesize * SSAFRAMENUM * t + - enclave_secs.base; - gs->gpr = gs->ssa + - enclave->ssaframesize - sizeof(sgx_pal_gpr_t); + sig_stack_areas[t].addr + ENCLAVE_SIG_STACK_SIZE + enclave_secs.base; + gs->ssa = (void*)ssa_area->addr + enclave->ssaframesize * SSAFRAMENUM * t + + enclave_secs.base; + gs->gpr = gs->ssa + enclave->ssaframesize - sizeof(sgx_pal_gpr_t); gs->manifest_size = manifest_size; gs->heap_min = (void*)enclave_secs.base + heap_min; gs->heap_max = (void*)enclave_secs.base + pal_area->addr; if (exec_area) { - gs->exec_addr = (void *) enclave_secs.base + exec_area->addr; + gs->exec_addr = (void*)enclave_secs.base + exec_area->addr; gs->exec_size = exec_area->size; } gs->thread = NULL; } } else if (!strcmp_static(areas[i].desc, "tcs")) { - data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, - PROT_READ|PROT_WRITE, - MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); + data = (void*)INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, PROT_READ | PROT_WRITE, + MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (IS_ERR_P(data) || data == NULL) { /* Note that Graphene currently doesn't handle 0x0 addresses */ SGX_DBG(DBG_E, "Allocating memory for tcs pages failed\n"); goto out; } - for (uint32_t t = 0 ; t < enclave->thread_num ; t++) { - sgx_arch_tcs_t * tcs = data + g_page_size * t; + for (uint32_t t = 0; t < enclave->thread_num; t++) { + sgx_arch_tcs_t* tcs = data + g_page_size * t; memset(tcs, 0, g_page_size); - tcs->ossa = ssa_area->addr + - enclave->ssaframesize * SSAFRAMENUM * t; - tcs->nssa = SSAFRAMENUM; - tcs->oentry = enclave_entry_addr; - tcs->ofs_base = 0; - tcs->ogs_base = tls_area->addr + t * g_page_size; + tcs->ossa = ssa_area->addr + enclave->ssaframesize * SSAFRAMENUM * t; + tcs->nssa = SSAFRAMENUM; + tcs->oentry = enclave_entry_addr; + tcs->ofs_base = 0; + tcs->ogs_base = tls_area->addr + t * g_page_size; tcs->ofs_limit = 0xfff; tcs->ogs_limit = 0xfff; - tcs_addrs[t] = (void *) enclave_secs.base + tcs_area->addr + g_page_size * t; + tcs_addrs[t] = (void*)enclave_secs.base + tcs_area->addr + g_page_size * t; } } else if (areas[i].fd != -1) { - data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, - PROT_READ, - MAP_FILE|MAP_PRIVATE, - areas[i].fd, 0); + data = (void*)INLINE_SYSCALL(mmap, 6, NULL, areas[i].size, PROT_READ, + MAP_FILE | MAP_PRIVATE, areas[i].fd, 0); if (IS_ERR_P(data) || data == NULL) { /* Note that Graphene currently doesn't handle 0x0 addresses */ SGX_DBG(DBG_E, "Allocating memory for file %s failed\n", areas[i].desc); @@ -581,8 +595,9 @@ static int initialize_enclave(struct pal_enclave* enclave) { } } - ret = add_pages_to_enclave(&enclave_secs, (void *) areas[i].addr, data, areas[i].size, - areas[i].type, areas[i].prot, areas[i].skip_eextend, areas[i].desc); + ret = add_pages_to_enclave(&enclave_secs, (void*)areas[i].addr, data, areas[i].size, + areas[i].type, areas[i].prot, areas[i].skip_eextend, + areas[i].desc); if (data) INLINE_SYSCALL(munmap, 2, data, areas[i].size); @@ -599,25 +614,22 @@ static int initialize_enclave(struct pal_enclave* enclave) { goto out; } - create_tcs_mapper((void *) enclave_secs.base + tcs_area->addr, enclave->thread_num); + create_tcs_mapper((void*)enclave_secs.base + tcs_area->addr, enclave->thread_num); - struct enclave_dbginfo * dbg = (void *) - INLINE_SYSCALL(mmap, 6, DBGINFO_ADDR, - sizeof(struct enclave_dbginfo), - PROT_READ|PROT_WRITE, - MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, - -1, 0); + struct enclave_dbginfo* dbg = (void*)INLINE_SYSCALL( + mmap, 6, DBGINFO_ADDR, sizeof(struct enclave_dbginfo), PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); if (IS_ERR_P(dbg)) { SGX_DBG(DBG_E, "Cannot allocate debug information (GDB will not work)\n"); } else { - dbg->pid = INLINE_SYSCALL(getpid, 0); - dbg->base = enclave->baseaddr; - dbg->size = enclave->size; + dbg->pid = INLINE_SYSCALL(getpid, 0); + dbg->base = enclave->baseaddr; + dbg->size = enclave->size; dbg->ssaframesize = enclave->ssaframesize; dbg->aep = async_exit_pointer; dbg->eresume = eresume_pointer; dbg->thread_tids[0] = dbg->pid; - for (int i = 0 ; i < MAX_DBG_THREADS ; i++) + for (int i = 0; i < MAX_DBG_THREADS; i++) dbg->tcs_addrs[i] = tcs_addrs[i]; } @@ -662,15 +674,13 @@ static int initialize_enclave(struct pal_enclave* enclave) { return ret; } -static void create_instance (struct pal_sec * pal_sec) -{ +static void create_instance(struct pal_sec* pal_sec) { PAL_NUM id = ((uint64_t)rdrand() << 32) | rdrand(); snprintf(pal_sec->pipe_prefix, sizeof(pal_sec->pipe_prefix), "/graphene/%016lx/", id); pal_sec->instance_id = id; } -static int load_manifest (int fd, struct config_store ** config_ptr) -{ +static int load_manifest(int fd, struct config_store** config_ptr) { int ret = 0; int nbytes = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_END); @@ -679,14 +689,13 @@ static int load_manifest (int fd, struct config_store ** config_ptr) return -ERRNO(nbytes); } - struct config_store * config = malloc(sizeof(struct config_store)); + struct config_store* config = malloc(sizeof(struct config_store)); if (!config) { SGX_DBG(DBG_E, "Not enough memory for config_store of manifest\n"); return -ENOMEM; } - void * config_raw = (void *) - INLINE_SYSCALL(mmap, 6, NULL, nbytes, PROT_READ, MAP_PRIVATE, fd, 0); + void* config_raw = (void*)INLINE_SYSCALL(mmap, 6, NULL, nbytes, PROT_READ, MAP_PRIVATE, fd, 0); if (IS_ERR_P(config_raw)) { SGX_DBG(DBG_E, "Cannot mmap manifest file\n"); ret = -ERRNO_P(config_raw); @@ -698,7 +707,7 @@ static int load_manifest (int fd, struct config_store ** config_ptr) config->malloc = malloc; config->free = NULL; - const char * errstring = NULL; + const char* errstring = NULL; ret = read_config(config, NULL, &errstring); if (ret < 0) { SGX_DBG(DBG_E, "Cannot read manifest: %s\n", errstring); @@ -722,7 +731,7 @@ static int load_manifest (int fd, struct config_store ** config_ptr) * Understands complex formats like "1,3-5,6". */ static int get_cpu_count(void) { - int fd = INLINE_SYSCALL(open, 3, "/sys/devices/system/cpu/online", O_RDONLY|O_CLOEXEC, 0); + int fd = INLINE_SYSCALL(open, 3, "/sys/devices/system/cpu/online", O_RDONLY | O_CLOEXEC, 0); if (fd < 0) return unix_to_pal_error(ERRNO(fd)); @@ -768,7 +777,7 @@ static int get_cpu_count(void) { static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* manifest_uri, char* exec_uri, char* args, size_t args_size, char* env, size_t env_size, bool exec_uri_inferred, bool need_gsgx) { - struct pal_sec * pal_sec = &enclave->pal_sec; + struct pal_sec* pal_sec = &enclave->pal_sec; int ret; #if PRINT_ENCLAVE_STAT == 1 @@ -853,10 +862,12 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani // from the manifest file name, but it doesn't exist, and let // the enclave go a bit further. Go ahead and warn the user, // though. - SGX_DBG(DBG_I, "Inferred executable cannot be opened: %s. This may be ok, " + SGX_DBG(DBG_I, + "Inferred executable cannot be opened: %s. This may be ok, " "or may represent a manifest misconfiguration. This typically " "represents advanced usage, and if it is not what you intended, " - "try setting the loader.exec field in the manifest.\n", exec_uri); + "try setting the loader.exec field in the manifest.\n", + exec_uri); enclave->exec = -1; } else { SGX_DBG(DBG_E, "Cannot open executable %s\n", exec_uri); @@ -869,7 +880,7 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani return -EINVAL; } - char * sig_uri = resolve_uri(cfgbuf, &errstring); + char* sig_uri = resolve_uri(cfgbuf, &errstring); if (!sig_uri) { SGX_DBG(DBG_E, "%s: %s\n", errstring, cfgbuf); return -EINVAL; @@ -889,17 +900,18 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani return -EINVAL; } - char * token_uri = alloc_concat(sig_uri, strlen(sig_uri) - static_strlen(".sig"), ".token", -1); + char* token_uri = alloc_concat(sig_uri, strlen(sig_uri) - static_strlen(".sig"), ".token", -1); free(sig_uri); if (!token_uri) { INLINE_SYSCALL(close, 1, enclave->sigfile); return -ENOMEM; } - enclave->token = INLINE_SYSCALL(open, 3, token_uri + URI_PREFIX_FILE_LEN, - O_RDONLY|O_CLOEXEC, 0); + enclave->token = INLINE_SYSCALL(open, 3, token_uri + URI_PREFIX_FILE_LEN, O_RDONLY | O_CLOEXEC, + 0); if (IS_ERR(enclave->token)) { - SGX_DBG(DBG_E, "Cannot open token \'%s\'. Use \'" + SGX_DBG(DBG_E, + "Cannot open token \'%s\'. Use \'" "Pal/src/host/Linux-SGX/signer/pal-sgx-get-token" "\' on the runtime host or run \'make SGX=1 sgx-tokens\' in the Graphene source to " "create the token file.\n", @@ -932,7 +944,8 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani if (get_config(enclave->config, "sgx.remote_attestation", cfgbuf, sizeof(cfgbuf)) < 0 && (get_config(enclave->config, "sgx.ra_client_spid", cfgbuf, sizeof(cfgbuf)) > 0 || get_config(enclave->config, "sgx.ra_client_linkable", cfgbuf, sizeof(cfgbuf)) > 0)) { - SGX_DBG(DBG_E, "Detected EPID remote attestation parameters \'ra_client_spid\' and/or " + SGX_DBG(DBG_E, + "Detected EPID remote attestation parameters \'ra_client_spid\' and/or " "\'ra_client_linkable\' in the manifest but no \'remote_attestation\' parameter. " "Please add \'sgx.remote_attestation = 1\' to the manifest.\n"); return -EINVAL; @@ -945,16 +958,15 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani return ret; } - void* alt_stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, ALT_STACK_SIZE, - PROT_READ | PROT_WRITE, + void* alt_stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, ALT_STACK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (IS_ERR_P(alt_stack)) return -ENOMEM; /* initialize TCB at the top of the alternative stack */ PAL_TCB_URTS* tcb = alt_stack + ALT_STACK_SIZE - sizeof(PAL_TCB_URTS); - pal_tcb_urts_init( - tcb, /*stack=*/NULL, alt_stack); /* main thread uses the stack provided by Linux */ + pal_tcb_urts_init(tcb, /*stack=*/NULL, + alt_stack); /* main thread uses the stack provided by Linux */ ret = pal_thread_init(tcb); if (ret < 0) return ret; @@ -972,13 +984,16 @@ static int load_enclave(struct pal_enclave* enclave, int manifest_fd, char* mani * each stack page (Linux dynamically grows the stack of the main thread but gets confused with * huge-jump stack accesses coming from within the enclave). Note that other, non-main threads * are created manually via clone(.., THREAD_STACK_SIZE, ..) and thus do not need this hack. */ -static void __attribute__ ((noinline)) force_linux_to_grow_stack(void) { +static void __attribute__((noinline)) force_linux_to_grow_stack(void) { char dummy[THREAD_STACK_SIZE]; for (uint64_t i = 0; i < sizeof(dummy); i += PRESET_PAGESIZE) { /* touch each page on the stack just to make it is not optimized away */ - __asm__ volatile("movq %0, %%rbx\r\n" - "movq (%%rbx), %%rbx\r\n" - : : "r"(&dummy[i]) : "%rbx"); + __asm__ volatile( + "movq %0, %%rbx\r\n" + "movq (%%rbx), %%rbx\r\n" + : + : "r"(&dummy[i]) + : "%rbx"); } } @@ -987,9 +1002,8 @@ int main(int argc, char* argv[], char* envp[]) { char* exec_uri = NULL; int fd = -1; int ret = 0; - bool exec_uri_inferred = false; // Handle the case where the exec uri is - // inferred from the manifest name somewhat - // differently + bool exec_uri_inferred = false; // Handle the case where the exec uri is inferred from + // the manifest name somewhat differently bool need_gsgx = true; force_linux_to_grow_stack(); @@ -1038,7 +1052,7 @@ int main(int argc, char* argv[], char* envp[]) { goto out; } - fd = INLINE_SYSCALL(open, 3, exec_uri + URI_PREFIX_FILE_LEN, O_RDONLY|O_CLOEXEC, 0); + fd = INLINE_SYSCALL(open, 3, exec_uri + URI_PREFIX_FILE_LEN, O_RDONLY | O_CLOEXEC, 0); if (IS_ERR(fd)) { SGX_DBG(DBG_E, "Input file not found: %s\n", exec_uri); goto usage; @@ -1102,7 +1116,7 @@ int main(int argc, char* argv[], char* envp[]) { if (manifest_fd == -1) { INLINE_SYSCALL(close, 1, fd); - fd = manifest_fd = INLINE_SYSCALL(open, 3, manifest_base_name, O_RDONLY|O_CLOEXEC, 0); + fd = manifest_fd = INLINE_SYSCALL(open, 3, manifest_base_name, O_RDONLY | O_CLOEXEC, 0); if (IS_ERR(fd)) { SGX_DBG(DBG_E, "Cannot open manifest file: %s\n", manifest_base_name); goto usage; @@ -1141,7 +1155,7 @@ int main(int argc, char* argv[], char* envp[]) { envc++; } char* env = envp[0]; - size_t env_size = envc > 0 ? (envp[envc - 1] - envp[0]) + strlen(envp[envc - 1]) + 1: 0; + size_t env_size = envc > 0 ? (envp[envc - 1] - envp[0]) + strlen(envp[envc - 1]) + 1 : 0; ret = load_enclave(&g_pal_enclave, manifest_fd, manifest_uri, exec_uri, args, args_size, env, env_size, exec_uri_inferred, need_gsgx); diff --git a/Pal/src/host/Linux-SGX/sgx_platform.c b/Pal/src/host/Linux-SGX/sgx_platform.c index 440fbf755b..412f035fe9 100644 --- a/Pal/src/host/Linux-SGX/sgx_platform.c +++ b/Pal/src/host/Linux-SGX/sgx_platform.c @@ -89,7 +89,7 @@ static int request_aesm_service(Request* req, Response** res) { if (aesm_socket < 0) return aesm_socket; - uint32_t req_len = (uint32_t) request__get_packed_size(req); + uint32_t req_len = (uint32_t)request__get_packed_size(req); uint8_t* req_buf = __alloca(req_len); request__pack(req, req_buf); diff --git a/Pal/src/host/Linux-SGX/sgx_process.c b/Pal/src/host/Linux-SGX/sgx_process.c index b7e6d74024..90c476e121 100644 --- a/Pal/src/host/Linux-SGX/sgx_process.c +++ b/Pal/src/host/Linux-SGX/sgx_process.c @@ -12,25 +12,25 @@ * at creation. */ -#include -#include -#include "sgx_internal.h" -#include "sgx_tls.h" -#include "sgx_enclave.h" - -#include #include +#include #include +#include "pal_linux.h" +#include "pal_rtld.h" +#include "sgx_enclave.h" +#include "sgx_internal.h" +#include "sgx_tls.h" + extern char* g_pal_loader_path; extern char* g_libpal_path; struct proc_args { - PAL_SEC_STR exec_name; - unsigned int instance_id; - unsigned int parent_process_id; - int stream_fd; - PAL_SEC_STR pipe_prefix; + PAL_SEC_STR exec_name; + unsigned int instance_id; + unsigned int parent_process_id; + int stream_fd; + PAL_SEC_STR pipe_prefix; }; /* @@ -57,7 +57,7 @@ static int __attribute_noinline vfork_exec(int parent_stream, const char** argv) /* shouldn't get to here */ SGX_DBG(DBG_E, "unexpected failure of execve\n"); - __asm__ volatile ("hlt"); + __asm__ volatile("hlt"); return 0; } @@ -79,7 +79,7 @@ int sgx_create_process(const char* uri, int nargs, const char** args, int* strea char parent_fd_str[16]; snprintf(parent_fd_str, sizeof(parent_fd_str), "%u", fds[0]); argv[3] = parent_fd_str; - memcpy(argv + 4, args, sizeof(const char *) * nargs); + memcpy(argv + 4, args, sizeof(const char*) * nargs); argv[nargs + 4] = NULL; /* child's signal handler may mess with parent's memory during vfork(), so block signals */ @@ -105,7 +105,7 @@ int sgx_create_process(const char* uri, int nargs, const char** args, int* strea INLINE_SYSCALL(close, 1, fds[0]); /* child stream */ - struct pal_sec * pal_sec = &g_pal_enclave.pal_sec; + struct pal_sec* pal_sec = &g_pal_enclave.pal_sec; struct proc_args proc_args; memcpy(proc_args.exec_name, uri, sizeof(PAL_SEC_STR)); proc_args.instance_id = pal_sec->instance_id; @@ -163,9 +163,9 @@ int sgx_init_child_process(int parent_pipe_fd, struct pal_sec* pal_sec) { return ret; memcpy(pal_sec->exec_name, proc_args.exec_name, sizeof(PAL_SEC_STR)); - pal_sec->instance_id = proc_args.instance_id; - pal_sec->ppid = proc_args.parent_process_id; - pal_sec->stream_fd = proc_args.stream_fd; + pal_sec->instance_id = proc_args.instance_id; + pal_sec->ppid = proc_args.parent_process_id; + pal_sec->stream_fd = proc_args.stream_fd; memcpy(pal_sec->pipe_prefix, proc_args.pipe_prefix, sizeof(PAL_SEC_STR)); return 1; diff --git a/Pal/src/host/Linux-SGX/sgx_rtld.c b/Pal/src/host/Linux-SGX/sgx_rtld.c index 7ca33260ae..f536aede97 100644 --- a/Pal/src/host/Linux-SGX/sgx_rtld.c +++ b/Pal/src/host/Linux-SGX/sgx_rtld.c @@ -10,15 +10,15 @@ * Library. */ -#include -#include - +#include "api.h" +#include "pal_internal.h" #include "sgx_internal.h" -__asm__(".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\r\n" - ".byte 1\r\n" - ".asciz \"debugger/pal-gdb.py\"\r\n" - ".popsection\r\n"); +__asm__( + ".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\r\n" + ".byte 1\r\n" + ".asciz \"debugger/pal-gdb.py\"\r\n" + ".popsection\r\n"); /* This function is hooked by our gdb integration script and should be * left as is. */ diff --git a/Pal/src/host/Linux-SGX/sgx_thread.c b/Pal/src/host/Linux-SGX/sgx_thread.c index 292450cc49..01592c5533 100644 --- a/Pal/src/host/Linux-SGX/sgx_thread.c +++ b/Pal/src/host/Linux-SGX/sgx_thread.c @@ -1,8 +1,8 @@ -#include "assert.h" -#include "pal_internal.h" -#include "pal_security.h" -#include "sgx_internal.h" -#include "spinlock.h" +/* SPDX-License-Identifier: LGPL-3.0-or-later */ + +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ #include #include @@ -10,12 +10,17 @@ #include #include -#include "sgx_enclave.h" +#include "assert.h" #include "debugger/sgx_gdb.h" +#include "pal_internal.h" +#include "pal_security.h" +#include "sgx_enclave.h" +#include "sgx_internal.h" +#include "spinlock.h" struct thread_map { - unsigned int tid; - sgx_arch_tcs_t * tcs; + unsigned int tid; + sgx_arch_tcs_t* tcs; }; static sgx_arch_tcs_t* g_enclave_tcs; @@ -84,8 +89,7 @@ void pal_tcb_urts_init(PAL_TCB_URTS* tcb, void* stack, void* alt_stack) { static spinlock_t tcs_lock = INIT_SPINLOCK_UNLOCKED; -void create_tcs_mapper (void * tcs_base, unsigned int thread_num) -{ +void create_tcs_mapper(void* tcs_base, unsigned int thread_num) { size_t thread_map_size = ALIGN_UP_POW2(sizeof(struct thread_map) * thread_num, PRESET_PAGESIZE); g_enclave_tcs = tcs_base; @@ -94,7 +98,7 @@ void create_tcs_mapper (void * tcs_base, unsigned int thread_num) PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - for (uint32_t i = 0 ; i < thread_num ; i++) { + for (uint32_t i = 0; i < thread_num; i++) { g_enclave_thread_map[i].tid = 0; g_enclave_thread_map[i].tcs = &g_enclave_tcs[i]; } @@ -102,7 +106,7 @@ void create_tcs_mapper (void * tcs_base, unsigned int thread_num) void map_tcs(unsigned int tid) { spinlock_lock(&tcs_lock); - for (int i = 0 ; i < g_enclave_thread_num ; i++) + for (int i = 0; i < g_enclave_thread_num; i++) if (!g_enclave_thread_map[i].tid) { g_enclave_thread_map[i].tid = tid; get_tcb_urts()->tcs = g_enclave_thread_map[i].tcs; @@ -121,7 +125,7 @@ void unmap_tcs(void) { assert(index < g_enclave_thread_num); get_tcb_urts()->tcs = NULL; - ((struct enclave_dbginfo *) DBGINFO_ADDR)->thread_tids[index] = 0; + ((struct enclave_dbginfo*)DBGINFO_ADDR)->thread_tids[index] = 0; map->tid = 0; spinlock_unlock(&tcs_lock); } @@ -168,13 +172,14 @@ int pal_thread_init(void* tcbptr) { } int tid = INLINE_SYSCALL(gettid, 0); - map_tcs(tid); /* updates tcb->tcs */ + map_tcs(tid); /* updates tcb->tcs */ if (!tcb->tcs) { SGX_DBG(DBG_E, "There are no available TCS pages left for a new thread!\n" "Please try to increase sgx.thread_num in the manifest.\n" - "The current value is %d\n", g_enclave_thread_num); + "The current value is %d\n", + g_enclave_thread_num); ret = -ENOMEM; goto out; } @@ -239,8 +244,7 @@ int clone_thread(void) { int ret = 0; void* stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, THREAD_STACK_SIZE + ALT_STACK_SIZE, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (IS_ERR_P(stack)) return -ENOMEM; @@ -270,8 +274,8 @@ int clone_thread(void) { // TODO: pal_thread_init() may fail during initialization (e.g. on TCS exhaustion), we should // check its result (but this happens asynchronously, so it's not trivial to do). ret = clone(pal_thread_init, child_stack_top, - CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_THREAD | - CLONE_SIGHAND | CLONE_PARENT_SETTID, + CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_THREAD | CLONE_SIGHAND | + CLONE_PARENT_SETTID, (void*)tcb, &dummy_parent_tid_field, NULL); if (IS_ERR(ret)) { @@ -281,8 +285,7 @@ int clone_thread(void) { return 0; } -int interrupt_thread (void * tcs) -{ +int interrupt_thread(void* tcs) { int index = (sgx_arch_tcs_t*)tcs - g_enclave_tcs; struct thread_map* map = &g_enclave_thread_map[index]; if (index >= g_enclave_thread_num) diff --git a/Pal/src/host/Linux-SGX/sgx_tls.h b/Pal/src/host/Linux-SGX/sgx_tls.h index 6fcc2c29ce..3a0029aa3d 100644 --- a/Pal/src/host/Linux-SGX/sgx_tls.h +++ b/Pal/src/host/Linux-SGX/sgx_tls.h @@ -54,33 +54,28 @@ struct enclave_tls { extern uint64_t dummy_debug_variable; #endif -# ifdef IN_ENCLAVE +#ifdef IN_ENCLAVE static inline struct enclave_tls* get_tcb_trts(void) { return (struct enclave_tls*)pal_get_tcb(); } -# define GET_ENCLAVE_TLS(member) \ - ({ \ - struct enclave_tls * tmp; \ - uint64_t val; \ - static_assert(sizeof(tmp->member) == 8, \ - "sgx_tls member should have 8-byte type"); \ - __asm__ ("movq %%gs:%c1, %q0": "=r" (val) \ - : "i" (offsetof(struct enclave_tls, member))); \ - (__typeof(tmp->member)) val; \ +#define GET_ENCLAVE_TLS(member) \ + ({ \ + struct enclave_tls* tmp; \ + uint64_t val; \ + static_assert(sizeof(tmp->member) == 8, "sgx_tls member should have 8-byte type"); \ + __asm__("movq %%gs:%c1, %q0" : "=r"(val) : "i"(offsetof(struct enclave_tls, member))); \ + (__typeof(tmp->member))val; \ }) -# define SET_ENCLAVE_TLS(member, value) \ - do { \ - struct enclave_tls * tmp; \ - static_assert(sizeof(tmp->member) == 8, \ - "sgx_tls member should have 8-byte type"); \ - static_assert(sizeof(value) == 8, \ - "only 8-byte type can be set to sgx_tls"); \ - __asm__ ("movq %q0, %%gs:%c1":: "r" (value), \ - "i" (offsetof(struct enclave_tls, member))); \ +#define SET_ENCLAVE_TLS(member, value) \ + do { \ + struct enclave_tls* tmp; \ + static_assert(sizeof(tmp->member) == 8, "sgx_tls member should have 8-byte type"); \ + static_assert(sizeof(value) == 8, "only 8-byte type can be set to sgx_tls"); \ + __asm__("movq %q0, %%gs:%c1" ::"r"(value), "i"(offsetof(struct enclave_tls, member))); \ } while (0) -# else +#else /* private to untrusted Linux PAL, unique to each untrusted thread */ typedef struct pal_tcb_urts { struct pal_tcb_urts* self; @@ -98,14 +93,14 @@ extern void pal_tcb_urts_init(PAL_TCB_URTS* tcb, void* stack, void* alt_stack); static inline PAL_TCB_URTS* get_tcb_urts(void) { PAL_TCB_URTS* tcb; - __asm__ ("movq %%gs:%c1, %q0\n" - : "=r" (tcb) - : "i" (offsetof(PAL_TCB_URTS, self))); + __asm__("movq %%gs:%c1, %q0\n" + : "=r" (tcb) + : "i" (offsetof(PAL_TCB_URTS, self))); return tcb; } extern bool g_sgx_enable_stats; void update_and_print_stats(bool process_wide); -# endif +#endif #endif /* __SGX_TLS_H__ */ diff --git a/Pal/src/host/Linux-SGX/tools/common/attestation.c b/Pal/src/host/Linux-SGX/tools/common/attestation.c index fa3620c300..831ed0246f 100644 --- a/Pal/src/host/Linux-SGX/tools/common/attestation.c +++ b/Pal/src/host/Linux-SGX/tools/common/attestation.c @@ -3,13 +3,14 @@ * Rafal Wojdyla */ +#include "attestation.h" + #include #include #include #include #include -#include "attestation.h" #include "cJSON.h" #include "pal_crypto.h" #include "sgx_arch.h" @@ -18,15 +19,15 @@ /*! This is the public RSA key of the IAS (PEM). It's used to verify IAS report signatures. */ const char* g_ias_public_key_pem = -"-----BEGIN PUBLIC KEY-----\n" -"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXot4OZuphR8nudFrAFi\n" -"aGxxkgma/Es/BA+tbeCTUR106AL1ENcWA4FX3K+E9BBL0/7X5rj5nIgX/R/1ubhk\n" -"KWw9gfqPG3KeAtIdcv/uTO1yXv50vqaPvE1CRChvzdS/ZEBqQ5oVvLTPZ3VEicQj\n" -"lytKgN9cLnxbwtuvLUK7eyRPfJW/ksddOzP8VBBniolYnRCD2jrMRZ8nBM2ZWYwn\n" -"XnwYeOAHV+W9tOhAImwRwKF/95yAsVwd21ryHMJBcGH70qLagZ7Ttyt++qO/6+KA\n" -"XJuKwZqjRlEtSEz8gZQeFfVYgcwSfo96oSMAzVr7V0L6HSDLRnpb6xxmbPdqNol4\n" -"tQIDAQAB\n" -"-----END PUBLIC KEY-----\n"; + "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqXot4OZuphR8nudFrAFi\n" + "aGxxkgma/Es/BA+tbeCTUR106AL1ENcWA4FX3K+E9BBL0/7X5rj5nIgX/R/1ubhk\n" + "KWw9gfqPG3KeAtIdcv/uTO1yXv50vqaPvE1CRChvzdS/ZEBqQ5oVvLTPZ3VEicQj\n" + "lytKgN9cLnxbwtuvLUK7eyRPfJW/ksddOzP8VBBniolYnRCD2jrMRZ8nBM2ZWYwn\n" + "XnwYeOAHV+W9tOhAImwRwKF/95yAsVwd21ryHMJBcGH70qLagZ7Ttyt++qO/6+KA\n" + "XJuKwZqjRlEtSEz8gZQeFfVYgcwSfo96oSMAzVr7V0L6HSDLRnpb6xxmbPdqNol4\n" + "tQIDAQAB\n" + "-----END PUBLIC KEY-----\n"; // Copied from Graphene's api.h. // TODO: Remove after Graphene's C utils get refactored into a separate module/header (we can't diff --git a/Pal/src/host/Linux-SGX/tools/common/ias.c b/Pal/src/host/Linux-SGX/tools/common/ias.c index f1a5d64849..612a9d4518 100644 --- a/Pal/src/host/Linux-SGX/tools/common/ias.c +++ b/Pal/src/host/Linux-SGX/tools/common/ias.c @@ -5,7 +5,6 @@ #include "ias.h" -#include #include #include #include @@ -14,15 +13,15 @@ #include #include +#include "assert.h" #include "pal_crypto.h" #include "util.h" -#define CURL_FAIL(action, ret) \ - (((ret) == CURLE_OK) ? false : \ - ({ \ - ERROR("curl call (%s) failed: %s\n", action, curl_easy_strerror(ret)); \ - true; \ - })) +#define CURL_FAIL(action, ret) \ + (((ret) == CURLE_OK) ? false : ({ \ + ERROR("curl call (%s) failed: %s\n", action, curl_easy_strerror(ret)); \ + true; \ + })) /*! Context used in ias_*() calls */ struct ias_context_t { @@ -57,7 +56,7 @@ static void urldecode(const char* src, char* dst) { while (*src) { if (*src == '%' && (a = src[1]) && (b = src[2]) && isxdigit(a) && isxdigit(b)) { if (a >= 'a') - a -= 'a'-'A'; + a -= 'a' - 'A'; if (a >= 'A') a -= ('A' - 10); @@ -65,7 +64,7 @@ static void urldecode(const char* src, char* dst) { a -= '0'; if (b >= 'a') - b -= 'a'-'A'; + b -= 'a' - 'A'; if (b >= 'A') b -= ('A' - 10); @@ -98,7 +97,8 @@ static void urldecode(const char* src, char* dst) { */ static size_t header_callback(char* buffer, size_t size, size_t count, void* context) { const char* sig_hdr = "x-iasreport-signature: "; // header containing IAS signature - const char* cert_hdr = "x-iasreport-signing-certificate: "; // header containing IAS certificate + const char* cert_hdr = + "x-iasreport-signing-certificate: "; // header containing IAS certificate const char* adv_url_hdr = "Advisory-URL: "; // header containing URL to IAS security advisories const char* adv_ids_hdr = "Advisory-IDs: "; // header containing security advisory IDs size_t total_size = size * count; @@ -294,8 +294,8 @@ int ias_get_sigrl(struct ias_context_t* context, uint8_t gid[4], size_t* sigrl_s goto out; /* gid must be big-endian */ - snprintf(url, url_size, "%s/%02x%02x%02x%02x", context->ias_sigrl_url, gid[3], gid[2], - gid[1], gid[0]); + snprintf(url, url_size, "%s/%02x%02x%02x%02x", context->ias_sigrl_url, gid[3], gid[2], gid[1], + gid[0]); DBG("IAS URL: %s\n", url); @@ -368,8 +368,8 @@ static int ias_send_request(struct ias_context_t* context, struct ias_request_re size_t quote_b64_size = 0; char* quote_json = NULL; size_t quote_json_size = 0; - const char* json_fmt = nonce ? "{\"isvEnclaveQuote\":\"%s\",\"nonce\":\"%s\"}" : - "{\"isvEnclaveQuote\":\"%s\"}"; + const char* json_fmt = nonce ? "{\"isvEnclaveQuote\":\"%s\",\"nonce\":\"%s\"}" + : "{\"isvEnclaveQuote\":\"%s\"}"; if (nonce && strlen(nonce) > 32) { ERROR("Nonce too long\n"); @@ -466,7 +466,7 @@ int ias_verify_quote(struct ias_context_t* context, const void* quote, size_t qu const char* nonce, const char* report_path, const char* sig_path, const char* cert_path, const char* advisory_path) { int ret; - struct ias_request_resp ias_resp = { 0 }; + struct ias_request_resp ias_resp = {0}; ret = ias_send_request(context, &ias_resp, quote, quote_size, nonce); if (ret < 0) { @@ -555,7 +555,7 @@ int ias_verify_quote_raw(struct ias_context_t* context, const void* quote, size_ size_t* cert_data_size, char** advisory_data_ptr, size_t* advisory_data_size) { int ret; - struct ias_request_resp ias_resp = { 0 }; + struct ias_request_resp ias_resp = {0}; char* report_data = NULL; char* sig_data = NULL; @@ -630,7 +630,7 @@ int ias_verify_quote_raw(struct ias_context_t* context, const void* quote, size_ if (ias_resp.advisory_url_size > 0 || ias_resp.advisory_ids_size > 0) { size_t dummy_size_t_int; if (__builtin_add_overflow(ias_resp.advisory_url_size, ias_resp.advisory_ids_size, - &dummy_size_t_int)) { + &dummy_size_t_int)) { ERROR("Sum of sizes of IAS advisory URL and advisory IDs overflows\n"); goto out; } diff --git a/Pal/src/host/Linux-SGX/tools/common/pf_util.c b/Pal/src/host/Linux-SGX/tools/common/pf_util.c index 5d71023a0c..338ddb3c29 100644 --- a/Pal/src/host/Linux-SGX/tools/common/pf_util.c +++ b/Pal/src/host/Linux-SGX/tools/common/pf_util.c @@ -5,23 +5,22 @@ #define _LARGEFILE64_SOURCE +#include "pf_util.h" + #include #include #include #include -#include -#include - #include #include #include - +#include #include #include #include +#include #include "api.h" -#include "pf_util.h" #include "util.h" /* High-level protected files helper functions. */ @@ -94,7 +93,7 @@ static pf_status_t linux_write(pf_handle_t handle, const void* buffer, uint64_t } static pf_status_t linux_truncate(pf_handle_t handle, uint64_t size) { - int fd = *(int*)handle; + int fd = *(int*)handle; DBG("linux_truncate: fd %d, size %zu\n", fd, size); int ret = ftruncate64(fd, size); if (ret < 0) { @@ -107,10 +106,9 @@ static pf_status_t linux_truncate(pf_handle_t handle, uint64_t size) { /* Crypto callbacks for mbedTLS */ -pf_status_t mbedtls_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - pf_mac_t* mac) { +pf_status_t mbedtls_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, pf_mac_t* mac) { pf_status_t status = PF_STATUS_CALLBACK_FAILED; mbedtls_gcm_context gcm; @@ -137,10 +135,9 @@ pf_status_t mbedtls_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, return status; } -pf_status_t mbedtls_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - const pf_mac_t* mac) { +pf_status_t mbedtls_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, const pf_mac_t* mac) { pf_status_t status = PF_STATUS_CALLBACK_FAILED; mbedtls_gcm_context gcm; @@ -266,7 +263,7 @@ int pf_encrypt_file(const char* input_path, const char* output_path, const pf_ke goto out; } - output = open(output_path, O_RDWR|O_CREAT, 0664); + output = open(output_path, O_RDWR | O_CREAT, 0664); if (output < 0) { ERROR("Failed to create output file '%s': %s\n", output_path, strerror(errno)); goto out; @@ -350,7 +347,7 @@ int pf_decrypt_file(const char* input_path, const char* output_path, bool verify goto out; } - output = open(output_path, O_RDWR|O_CREAT, 0664); + output = open(output_path, O_RDWR | O_CREAT, 0664); if (output < 0) { ERROR("Failed to create output file '%s': %s\n", output_path, strerror(errno)); goto out; diff --git a/Pal/src/host/Linux-SGX/tools/common/pf_util.h b/Pal/src/host/Linux-SGX/tools/common/pf_util.h index 7a89d392c5..ca04e1d36f 100644 --- a/Pal/src/host/Linux-SGX/tools/common/pf_util.h +++ b/Pal/src/host/Linux-SGX/tools/common/pf_util.h @@ -33,16 +33,14 @@ int pf_decrypt_files(const char* input_dir, const char* output_dir, bool verify_ const char* wrap_key_path); /*! AES-GCM encrypt */ -pf_status_t mbedtls_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - pf_mac_t* mac); +pf_status_t mbedtls_aes_gcm_encrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, pf_mac_t* mac); /*! AES-GCM decrypt */ -pf_status_t mbedtls_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, - const void* aad, size_t aad_size, - const void* input, size_t input_size, void* output, - const pf_mac_t* mac); +pf_status_t mbedtls_aes_gcm_decrypt(const pf_key_t* key, const pf_iv_t* iv, const void* aad, + size_t aad_size, const void* input, size_t input_size, + void* output, const pf_mac_t* mac); /*! Load PF wrap key from file */ int load_wrap_key(const char* wrap_key_path, pf_key_t* wrap_key); diff --git a/Pal/src/host/Linux-SGX/tools/common/util.c b/Pal/src/host/Linux-SGX/tools/common/util.c index 6a73a2fc44..c2959f65eb 100644 --- a/Pal/src/host/Linux-SGX/tools/common/util.c +++ b/Pal/src/host/Linux-SGX/tools/common/util.c @@ -5,13 +5,13 @@ #define _LARGEFILE64_SOURCE +#include "util.h" + #include #include #include #include -#include "util.h" - /*! Console stdout fd */ int g_stdout_fd = 1; diff --git a/Pal/src/host/Linux-SGX/tools/common/util.h b/Pal/src/host/Linux-SGX/tools/common/util.h index 2d548ee599..d0ab2a2d1c 100644 --- a/Pal/src/host/Linux-SGX/tools/common/util.h +++ b/Pal/src/host/Linux-SGX/tools/common/util.h @@ -26,9 +26,21 @@ extern bool g_verbose; extern endianness_t g_endianness; /* Print functions */ -#define DBG(fmt, ...) do { if (g_verbose) dprintf(g_stdout_fd, fmt, ##__VA_ARGS__); } while (0) -#define INFO(fmt, ...) do { dprintf(g_stdout_fd, fmt, ##__VA_ARGS__); } while (0) -#define ERROR(fmt, ...) do { dprintf(g_stderr_fd, "%s: " fmt, __FUNCTION__, ##__VA_ARGS__); } while (0) +#define DBG(fmt, ...) \ + do { \ + if (g_verbose) \ + dprintf(g_stdout_fd, fmt, ##__VA_ARGS__); \ + } while (0) + +#define INFO(fmt, ...) \ + do { \ + dprintf(g_stdout_fd, fmt, ##__VA_ARGS__); \ + } while (0) + +#define ERROR(fmt, ...) \ + do { \ + dprintf(g_stderr_fd, "%s: " fmt, __FUNCTION__, ##__VA_ARGS__); \ + } while (0) /*! Set verbosity level */ void set_verbose(bool verbose); @@ -82,9 +94,4 @@ int parse_hex(const char* hex, void* buffer, size_t buffer_size); /*! abort */ void __abort(void); -/* For PAL's assert compatibility */ -#ifndef warn -#define warn ERROR -#endif - #endif /* UTIL_H */ diff --git a/Pal/src/host/Linux-SGX/tools/pf_crypt/pf_crypt.c b/Pal/src/host/Linux-SGX/tools/pf_crypt/pf_crypt.c index d986ed2544..c89b5f2869 100644 --- a/Pal/src/host/Linux-SGX/tools/pf_crypt/pf_crypt.c +++ b/Pal/src/host/Linux-SGX/tools/pf_crypt/pf_crypt.c @@ -42,14 +42,14 @@ static void usage(void) { INFO(" --verify, -V (optional) Verify that input path matches PF's allowed paths\n"); } -int main(int argc, char *argv[]) { - int ret = -1; - int this_option = 0; - char* input_path = NULL; - char* output_path = NULL; +int main(int argc, char* argv[]) { + int ret = -1; + int this_option = 0; + char* input_path = NULL; + char* output_path = NULL; char* wrap_key_path = NULL; - char* mode = NULL; - bool verify = false; + char* mode = NULL; + bool verify = false; while (true) { this_option = getopt_long(argc, argv, "i:o:p:w:Vvh", g_options, NULL); @@ -100,31 +100,31 @@ int main(int argc, char *argv[]) { mode = argv[optind]; switch (mode[0]) { - case 'g': /* gen-key */ - ret = pf_generate_wrap_key(wrap_key_path); - break; + case 'g': /* gen-key */ + ret = pf_generate_wrap_key(wrap_key_path); + break; - case 'e': /* encrypt */ - if (!input_path || !output_path) { - ERROR("Input or output path not specified\n"); - usage(); - goto out; - } - ret = pf_encrypt_files(input_path, output_path, wrap_key_path); - break; + case 'e': /* encrypt */ + if (!input_path || !output_path) { + ERROR("Input or output path not specified\n"); + usage(); + goto out; + } + ret = pf_encrypt_files(input_path, output_path, wrap_key_path); + break; - case 'd': /* decrypt */ - if (!input_path || !output_path) { - ERROR("Input or output path not specified\n"); + case 'd': /* decrypt */ + if (!input_path || !output_path) { + ERROR("Input or output path not specified\n"); + usage(); + goto out; + } + ret = pf_decrypt_files(input_path, output_path, verify, wrap_key_path); + break; + + default: usage(); goto out; - } - ret = pf_decrypt_files(input_path, output_path, verify, wrap_key_path); - break; - - default: - usage(); - goto out; } out: diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls.h b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls.h index f46bba17e5..c676a96dd7 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls.h +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls.h @@ -17,20 +17,21 @@ #define RA_TLS_ISV_SVN "RA_TLS_ISV_SVN" #define RA_TLS_IAS_PUB_KEY_PEM "RA_TLS_IAS_PUB_KEY_PEM" -#define RA_TLS_IAS_REPORT_URL "RA_TLS_IAS_REPORT_URL" -#define RA_TLS_IAS_SIGRL_URL "RA_TLS_IAS_SIGRL_URL" +#define RA_TLS_IAS_REPORT_URL "RA_TLS_IAS_REPORT_URL" +#define RA_TLS_IAS_SIGRL_URL "RA_TLS_IAS_SIGRL_URL" #define RA_TLS_CERT_TIMESTAMP_NOT_BEFORE "RA_TLS_CERT_TIMESTAMP_NOT_BEFORE" #define RA_TLS_CERT_TIMESTAMP_NOT_AFTER "RA_TLS_CERT_TIMESTAMP_NOT_AFTER" -#define SHA256_DIGEST_SIZE 32 -#define RSA_PUB_3072_KEY_LEN 3072 +#define SHA256_DIGEST_SIZE 32 +#define RSA_PUB_3072_KEY_LEN 3072 #define RSA_PUB_3072_KEY_DER_LEN 422 -#define RSA_PUB_EXPONENT 65537 -#define PUB_KEY_SIZE_MAX 512 -#define IAS_REQUEST_NONCE_LEN 32 +#define RSA_PUB_EXPONENT 65537 +#define PUB_KEY_SIZE_MAX 512 +#define IAS_REQUEST_NONCE_LEN 32 -#define OID(N) {0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF8, 0x4D, 0x8A, 0x39, (N)} +#define OID(N) \ + { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF8, 0x4D, 0x8A, 0x39, (N) } static const uint8_t quote_oid[] = OID(0x06); static const size_t quote_oid_len = sizeof(quote_oid); #define QUOTE_MAX_SIZE 8192 diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_attest.c b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_attest.c index 1009987b38..edb1433ea5 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_attest.c +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_attest.c @@ -40,7 +40,7 @@ static ssize_t rw_file(const char* path, uint8_t* buf, size_t len, bool do_write) { ssize_t bytes = 0; - ssize_t ret = 0; + ssize_t ret = 0; int fd = open(path, do_write ? O_WRONLY : O_RDONLY); if (fd < 0) @@ -192,8 +192,8 @@ static int create_x509(mbedtls_pk_context* pk, mbedtls_x509write_cert* writecrt) return ret; } -static int create_key_and_crt(mbedtls_pk_context* key, mbedtls_x509_crt* crt, - uint8_t** crt_der, size_t* crt_der_size) { +static int create_key_and_crt(mbedtls_pk_context* key, mbedtls_x509_crt* crt, uint8_t** crt_der, + size_t* crt_der_size) { int ret; if (!key || !crt) @@ -208,9 +208,9 @@ static int create_key_and_crt(mbedtls_pk_context* key, mbedtls_x509_crt* crt, mbedtls_x509write_cert writecrt; mbedtls_x509write_crt_init(&writecrt); - uint8_t* crt_der_buf = NULL; - uint8_t* output_buf = NULL; - size_t output_buf_size = 16 * 1024; /* enough for any X.509 certificate */ + uint8_t* crt_der_buf = NULL; + uint8_t* output_buf = NULL; + size_t output_buf_size = 16 * 1024; /* enough for any X.509 certificate */ output_buf = malloc(output_buf_size); if (!output_buf) { @@ -229,8 +229,8 @@ static int create_key_and_crt(mbedtls_pk_context* key, mbedtls_x509_crt* crt, mbedtls_rsa_init((mbedtls_rsa_context*)key->pk_ctx, MBEDTLS_RSA_PKCS_V15, /*hash_id=*/0); - ret = mbedtls_rsa_gen_key((mbedtls_rsa_context*)key->pk_ctx, mbedtls_ctr_drbg_random, - &ctr_drbg, RSA_PUB_3072_KEY_LEN, RSA_PUB_EXPONENT); + ret = mbedtls_rsa_gen_key((mbedtls_rsa_context*)key->pk_ctx, mbedtls_ctr_drbg_random, &ctr_drbg, + RSA_PUB_3072_KEY_LEN, RSA_PUB_EXPONENT); if (ret < 0) goto out; @@ -280,8 +280,8 @@ int ra_tls_create_key_and_crt(mbedtls_pk_context* key, mbedtls_x509_crt* crt) { return create_key_and_crt(key, crt, NULL, NULL); } -int ra_tls_create_key_and_crt_der(uint8_t** der_key, size_t* der_key_size, - uint8_t** der_crt, size_t* der_crt_size) { +int ra_tls_create_key_and_crt_der(uint8_t** der_key, size_t* der_key_size, uint8_t** der_crt, + size_t* der_crt_size) { int ret; if (!der_key || !der_key_size || !der_crt || !der_crt_size) @@ -292,7 +292,7 @@ int ra_tls_create_key_and_crt_der(uint8_t** der_key, size_t* der_key_size, uint8_t* der_key_buf = NULL; uint8_t* output_buf = NULL; - size_t output_buf_size = 1024; /* enough for any public key */ + size_t output_buf_size = 1024; /* enough for any public key */ output_buf = malloc(output_buf_size); if (!output_buf) { diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap.c b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap.c index b5076c229c..83390f9988 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap.c +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap.c @@ -37,7 +37,7 @@ extern verify_measurements_cb_t g_verify_measurements_cb; * so we declare the used types and functions below */ /* QL stands for Quoting Library; QV stands for Quote Verification */ -#define SGX_QL_QV_MK_ERROR(x) (0x0000A000|(x)) +#define SGX_QL_QV_MK_ERROR(x) (0x0000A000 | (x)) typedef enum _sgx_ql_qv_result_t { /* quote verification passed and is at the latest TCB level */ SGX_QL_QV_RESULT_OK = 0x0000, @@ -71,7 +71,6 @@ int sgx_qv_verify_quote(const uint8_t* p_quote, uint32_t quote_size, void* p_quo sgx_ql_qv_result_t* p_quote_verification_result, void* p_qve_report_info, uint32_t supplemental_data_size, uint8_t* p_supplemental_data); - int ra_tls_verify_callback(void* data, mbedtls_x509_crt* crt, int depth, uint32_t* flags) { (void)data; diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap_urts.c b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap_urts.c index 6ef20c3c3b..ca24651b89 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap_urts.c +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/ra_tls_verify_dcap_urts.c @@ -7,8 +7,11 @@ * there are two workarounds to solve this: 1) load libsgx_urts.so or 2) create * dummy functions and always return failure. In this example we use 2). */ -#define DUMMY_FUNCTION(f) __attribute__ ((visibility ("default"))) int f(void); \ - int f(void) {return /*SGX_ERROR_UNEXPECTED*/1;} +#define DUMMY_FUNCTION(f) \ + __attribute__((visibility("default"))) int f(void); \ + int f(void) { \ + return /*SGX_ERROR_UNEXPECTED*/ 1; \ + } /* Provide these dummies since we are not using libsgx_urts.so. */ DUMMY_FUNCTION(sgx_create_enclave) @@ -20,4 +23,3 @@ DUMMY_FUNCTION(sgx_thread_set_untrusted_event_ocall) DUMMY_FUNCTION(sgx_thread_setwait_untrusted_events_ocall) DUMMY_FUNCTION(sgx_thread_set_multiple_untrusted_events_ocall) DUMMY_FUNCTION(sgx_thread_wait_untrusted_event_ocall) - diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_attest.c b/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_attest.c index 282f141b51..f710ba5393 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_attest.c +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_attest.c @@ -49,7 +49,7 @@ static mbedtls_ssl_context g_ssl; static mbedtls_pk_context g_my_ratls_key; static mbedtls_x509_crt g_my_ratls_cert; -static uint8_t* provisioned_secret = NULL; +static uint8_t* provisioned_secret = NULL; static size_t provisioned_secret_size = 0; int secret_provision_get(uint8_t** out_secret, size_t* out_secret_size) { @@ -235,8 +235,8 @@ int secret_provision_start(const char* in_servers, const char* in_ca_chain_path, "buffer must be sufficiently large to hold SECRET_PROVISION_RESPONSE + int32"); memset(buf, 0, sizeof(buf)); - ret = secret_provision_read(&ctx, buf, sizeof(SECRET_PROVISION_RESPONSE) + - sizeof(received_secret_size)); + ret = secret_provision_read(&ctx, buf, + sizeof(SECRET_PROVISION_RESPONSE) + sizeof(received_secret_size)); if (ret < 0) { goto out; } @@ -303,7 +303,7 @@ __attribute__((constructor)) static void secret_provision_constructor(void) { if (!strcmp(e, "1") || !strcmp(e, "true") || !strcmp(e, "TRUE")) { /* user wants to provision secret before application runs */ - uint8_t* secret = NULL; + uint8_t* secret = NULL; size_t secret_size = 0; unsetenv(SECRET_PROVISION_SECRET_STRING); diff --git a/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_verify.c b/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_verify.c index 94da61d721..7f18c0fda2 100644 --- a/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_verify.c +++ b/Pal/src/host/Linux-SGX/tools/ra-tls/secret_prov_verify.c @@ -107,8 +107,8 @@ static void* client_connection(void* data) { memcpy(buf, SECRET_PROVISION_RESPONSE, sizeof(SECRET_PROVISION_RESPONSE)); memcpy(buf + sizeof(SECRET_PROVISION_RESPONSE), &send_secret_size, sizeof(send_secret_size)); - ret = secret_provision_write(&ctx, buf, sizeof(SECRET_PROVISION_RESPONSE) + - sizeof(send_secret_size)); + ret = secret_provision_write(&ctx, buf, + sizeof(SECRET_PROVISION_RESPONSE) + sizeof(send_secret_size)); if (ret < 0) { goto out; } @@ -186,7 +186,7 @@ int secret_provision_start_server(uint8_t* secret, size_t secret_size, const cha goto out; } - ret = mbedtls_net_bind(&listen_fd, NULL, port ? : "4433", MBEDTLS_NET_PROTO_TCP); + ret = mbedtls_net_bind(&listen_fd, NULL, port ?: "4433", MBEDTLS_NET_PROTO_TCP); if (ret < 0) { goto out; } diff --git a/Pal/src/host/Linux/db_devices.c b/Pal/src/host/Linux/db_devices.c index fc351f626e..e289bf2904 100644 --- a/Pal/src/host/Linux/db_devices.c +++ b/Pal/src/host/Linux/db_devices.c @@ -214,8 +214,8 @@ static int dev_open(PAL_HANDLE* handle, const char* type, const char* uri, int a return -PAL_ERROR_INVAL; struct handle_ops* ops = NULL; - char* dev_type = NULL; - int ret = 0; + char* dev_type = NULL; + int ret = 0; ret = parse_device_uri(&uri, &dev_type, &ops); @@ -351,8 +351,8 @@ static int dev_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* att return -PAL_ERROR_INVAL; struct handle_ops* ops = NULL; - char* dev_type = NULL; - int ret = 0; + char* dev_type = NULL; + int ret = 0; ret = parse_device_uri(&uri, &dev_type, &ops); diff --git a/Pal/src/host/Linux/db_events.c b/Pal/src/host/Linux/db_events.c index bf15e71877..3b9bd75a20 100644 --- a/Pal/src/host/Linux/db_events.c +++ b/Pal/src/host/Linux/db_events.c @@ -8,11 +8,11 @@ */ #include -#include #include #include #include "api.h" +#include "atomic.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" diff --git a/Pal/src/host/Linux/db_exception.c b/Pal/src/host/Linux/db_exception.c index 7bdd040b0d..2a8f6f915a 100644 --- a/Pal/src/host/Linux/db_exception.c +++ b/Pal/src/host/Linux/db_exception.c @@ -9,6 +9,12 @@ * This file contains APIs to set up signal handlers. */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + +#include + #include "api.h" #include "pal.h" #include "pal_debug.h" @@ -18,23 +24,21 @@ #include "pal_linux.h" #include "pal_linux_defs.h" #include "pal_security.h" - -#include -#include -#include +#include "sigset.h" +#include "ucontext.h" #if defined(__x86_64__) /* in x86_64 kernels, sigaction is required to have a user-defined restorer */ #define DEFINE_RESTORE_RT(syscall) DEFINE_RESTORE_RT2(syscall) -#define DEFINE_RESTORE_RT2(syscall) \ - __asm__ ( \ - " nop\n" \ - ".align 16\n" \ - ".LSTART_restore_rt:\n" \ - " .type __restore_rt,@function\n" \ - "__restore_rt:\n" \ - " movq $" #syscall ", %rax\n" \ - " syscall\n"); +#define DEFINE_RESTORE_RT2(syscall) \ + __asm__( \ + " nop\n" \ + ".align 16\n" \ + ".LSTART_restore_rt:\n" \ + " .type __restore_rt,@function\n" \ + "__restore_rt:\n" \ + " movq $" #syscall ", %rax\n" \ + " syscall\n"); DEFINE_RESTORE_RT(__NR_rt_sigreturn) /* workaround for an old GAS (2.27) bug that incorrectly omits relocations when referencing this @@ -45,7 +49,7 @@ __attribute__((visibility("hidden"))) void __restore_rt(void); static const int ASYNC_SIGNALS[] = {SIGTERM, SIGINT, SIGCONT}; static int block_signal(int sig, bool block) { - int how = block? SIG_BLOCK: SIG_UNBLOCK; + int how = block ? SIG_BLOCK : SIG_UNBLOCK; __sigset_t mask; __sigemptyset(&mask); @@ -83,7 +87,7 @@ int block_async_signals(bool block) { } static int get_pal_event(int sig) { - switch(sig) { + switch (sig) { case SIGFPE: return PAL_EVENT_ARITHMETIC_ERROR; case SIGSEGV: @@ -151,8 +155,7 @@ static void handle_sync_signal(int signum, siginfo_t* info, struct ucontext* uc) } printf("*** Unexpected %s occurred inside PAL (PID = %ld, TID = %ld, RIP = +0x%08lx)! ***\n", - name, INLINE_SYSCALL(getpid, 0), INLINE_SYSCALL(gettid, 0), - rip - (uintptr_t)TEXT_START); + name, INLINE_SYSCALL(getpid, 0), INLINE_SYSCALL(gettid, 0), rip - (uintptr_t)TEXT_START); _DkProcessExit(1); return; diff --git a/Pal/src/host/Linux/db_files.c b/Pal/src/host/Linux/db_files.c index 328e0c2858..93c7b07ef9 100644 --- a/Pal/src/host/Linux/db_files.c +++ b/Pal/src/host/Linux/db_files.c @@ -8,22 +8,22 @@ * "file:" or "dir:". */ -#include "pal_defs.h" -#include "pal_linux_defs.h" +#include + +#include "api.h" #include "pal.h" +#include "pal_debug.h" +#include "pal_defs.h" +#include "pal_error.h" #include "pal_flags_conv.h" #include "pal_internal.h" #include "pal_linux.h" +#include "pal_linux_defs.h" #include "pal_linux_error.h" -#include "pal_debug.h" -#include "pal_error.h" -#include "api.h" - -#include typedef __kernel_pid_t pid_t; #undef __GLIBC__ -#include #include +#include /* 'open' operation for file streams */ static int file_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share, @@ -57,7 +57,7 @@ static int file_open(PAL_HANDLE* handle, const char* type, const char* uri, int } SET_HANDLE_TYPE(hdl, file); - HANDLE_HDR(hdl)->flags |= RFD(0)|WFD(0); + HANDLE_HDR(hdl)->flags |= RFD(0) | WFD(0); hdl->file.fd = ret; hdl->file.map_start = NULL; char* path = (void*)hdl + HANDLE_SIZE(file); @@ -85,9 +85,7 @@ static int file_open(PAL_HANDLE* handle, const char* type, const char* uri, int } /* 'read' operation for file streams. */ -static int64_t file_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buffer) -{ +static int64_t file_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer) { int fd = handle->file.fd; int64_t ret; @@ -104,9 +102,7 @@ static int64_t file_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, } /* 'write' operation for file streams. */ -static int64_t file_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buffer) -{ +static int64_t file_write(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer) { int fd = handle->file.fd; int64_t ret; @@ -124,16 +120,14 @@ static int64_t file_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, /* 'close' operation for file streams. In this case, it will only close the file withou deleting it. */ -static int file_close (PAL_HANDLE handle) -{ +static int file_close(PAL_HANDLE handle) { int fd = handle->file.fd; int ret = INLINE_SYSCALL(close, 1, fd); /* initial realpath is part of handle object and will be freed with it */ - if (handle->file.realpath && - handle->file.realpath != (void *) handle + HANDLE_SIZE(file)) { - free((void *) handle->file.realpath); + if (handle->file.realpath && handle->file.realpath != (void*)handle + HANDLE_SIZE(file)) { + free((void*)handle->file.realpath); } return IS_ERR(ret) ? unix_to_pal_error(ERRNO(ret)) : 0; @@ -141,8 +135,7 @@ static int file_close (PAL_HANDLE handle) /* 'delete' operation for file streams. It will actually delete the file if we can successfully close it. */ -static int file_delete (PAL_HANDLE handle, int access) -{ +static int file_delete(PAL_HANDLE handle, int access) { if (access) return -PAL_ERROR_INVAL; @@ -178,31 +171,28 @@ static int file_map(PAL_HANDLE handle, void** addr, int prot, uint64_t offset, u } /* 'setlength' operation for file stream. */ -static int64_t file_setlength (PAL_HANDLE handle, uint64_t length) -{ +static int64_t file_setlength(PAL_HANDLE handle, uint64_t length) { int ret = INLINE_SYSCALL(ftruncate, 2, handle->file.fd, length); if (IS_ERR(ret)) - return (ERRNO(ret) == EINVAL || ERRNO(ret) == EBADF) ? - -PAL_ERROR_BADHANDLE : -PAL_ERROR_DENIED; + return (ERRNO(ret) == EINVAL || ERRNO(ret) == EBADF) ? -PAL_ERROR_BADHANDLE + : -PAL_ERROR_DENIED; - return (int64_t) length; + return (int64_t)length; } /* 'flush' operation for file stream. */ -static int file_flush (PAL_HANDLE handle) -{ +static int file_flush(PAL_HANDLE handle) { int ret = INLINE_SYSCALL(fsync, 1, handle->file.fd); if (IS_ERR(ret)) - return (ERRNO(ret) == EINVAL || ERRNO(ret) == EBADF) ? - -PAL_ERROR_BADHANDLE : -PAL_ERROR_DENIED; + return (ERRNO(ret) == EINVAL || ERRNO(ret) == EBADF) ? -PAL_ERROR_BADHANDLE + : -PAL_ERROR_DENIED; return 0; } -static inline int file_stat_type (struct stat * stat) -{ +static inline int file_stat_type(struct stat* stat) { if (S_ISREG(stat->st_mode)) return pal_type_file; if (S_ISDIR(stat->st_mode)) @@ -218,9 +208,7 @@ static inline int file_stat_type (struct stat * stat) } /* copy attr content from POSIX stat struct to PAL_STREAM_ATTR */ -static inline void -file_attrcopy (PAL_STREAM_ATTR * attr, struct stat * stat) -{ +static inline void file_attrcopy(PAL_STREAM_ATTR* attr, struct stat* stat) { attr->handle_type = file_stat_type(stat); attr->disconnected = PAL_FALSE; attr->nonblocking = PAL_FALSE; @@ -232,9 +220,7 @@ file_attrcopy (PAL_STREAM_ATTR * attr, struct stat * stat) } /* 'attrquery' operation for file streams */ -static int file_attrquery (const char * type, const char * uri, - PAL_STREAM_ATTR * attr) -{ +static int file_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* attr) { if (strcmp_static(type, URI_TYPE_FILE) && strcmp_static(type, URI_TYPE_DIR)) return -PAL_ERROR_INVAL; @@ -251,9 +237,7 @@ static int file_attrquery (const char * type, const char * uri, } /* 'attrquerybyhdl' operation for file streams */ -static int file_attrquerybyhdl (PAL_HANDLE handle, - PAL_STREAM_ATTR * attr) -{ +static int file_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { int fd = handle->generic.fds[0]; struct stat stat_buf; @@ -266,9 +250,7 @@ static int file_attrquerybyhdl (PAL_HANDLE handle, return 0; } -static int file_attrsetbyhdl (PAL_HANDLE handle, - PAL_STREAM_ATTR * attr) -{ +static int file_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { int fd = handle->generic.fds[0], ret; ret = INLINE_SYSCALL(fchmod, 2, fd, attr->share_flags | 0600); @@ -278,9 +260,7 @@ static int file_attrsetbyhdl (PAL_HANDLE handle, return 0; } -static int file_rename (PAL_HANDLE handle, const char * type, - const char * uri) -{ +static int file_rename(PAL_HANDLE handle, const char* type, const char* uri) { if (strcmp_static(type, URI_TYPE_FILE)) return -PAL_ERROR_INVAL; @@ -295,22 +275,20 @@ static int file_rename (PAL_HANDLE handle, const char * type, } /* initial realpath is part of handle object and will be freed with it */ - if (handle->file.realpath && - handle->file.realpath != (void *) handle + HANDLE_SIZE(file)) { - free((void *) handle->file.realpath); + if (handle->file.realpath && handle->file.realpath != (void*)handle + HANDLE_SIZE(file)) { + free((void*)handle->file.realpath); } handle->file.realpath = tmp; return 0; } -static int file_getname (PAL_HANDLE handle, char * buffer, size_t count) -{ +static int file_getname(PAL_HANDLE handle, char* buffer, size_t count) { if (!handle->file.realpath) return 0; size_t len = strlen(handle->file.realpath); - char * tmp = strcpy_static(buffer, URI_PREFIX_FILE, count); + char* tmp = strcpy_static(buffer, URI_PREFIX_FILE, count); if (!tmp || buffer + count < tmp + len + 1) return -PAL_ERROR_TOOLONG; @@ -319,26 +297,25 @@ static int file_getname (PAL_HANDLE handle, char * buffer, size_t count) return tmp + len - buffer; } -static const char* file_getrealpath (PAL_HANDLE handle) -{ +static const char* file_getrealpath(PAL_HANDLE handle) { return handle->file.realpath; } struct handle_ops g_file_ops = { - .getname = &file_getname, - .getrealpath = &file_getrealpath, - .open = &file_open, - .read = &file_read, - .write = &file_write, - .close = &file_close, - .delete = &file_delete, - .map = &file_map, - .setlength = &file_setlength, - .flush = &file_flush, - .attrquery = &file_attrquery, - .attrquerybyhdl = &file_attrquerybyhdl, - .attrsetbyhdl = &file_attrsetbyhdl, - .rename = &file_rename, + .getname = &file_getname, + .getrealpath = &file_getrealpath, + .open = &file_open, + .read = &file_read, + .write = &file_write, + .close = &file_close, + .delete = &file_delete, + .map = &file_map, + .setlength = &file_setlength, + .flush = &file_flush, + .attrquery = &file_attrquery, + .attrquerybyhdl = &file_attrquerybyhdl, + .attrsetbyhdl = &file_attrsetbyhdl, + .rename = &file_rename, }; /* 'open' operation for directory stream. Directory stream does not have a @@ -378,10 +355,10 @@ static int dir_open(PAL_HANDLE* handle, const char* type, const char* uri, int a hdl->dir.fd = ret; char* path = (void*)hdl + HANDLE_SIZE(dir); memcpy(path, uri, len + 1); - hdl->dir.realpath = (PAL_STR) path; - hdl->dir.buf = (PAL_PTR) NULL; - hdl->dir.ptr = (PAL_PTR) NULL; - hdl->dir.end = (PAL_PTR) NULL; + hdl->dir.realpath = (PAL_STR)path; + hdl->dir.buf = (PAL_PTR)NULL; + hdl->dir.ptr = (PAL_PTR)NULL; + hdl->dir.end = (PAL_PTR)NULL; hdl->dir.endofstream = PAL_FALSE; *handle = hdl; return 0; @@ -395,17 +372,17 @@ struct linux_dirent64 { char d_name[]; }; -#define DT_UNKNOWN 0 -#define DT_FIFO 1 -#define DT_CHR 2 -#define DT_DIR 4 -#define DT_BLK 6 -#define DT_REG 8 -#define DT_LNK 10 -#define DT_SOCK 12 -#define DT_WHT 14 +#define DT_UNKNOWN 0 +#define DT_FIFO 1 +#define DT_CHR 2 +#define DT_DIR 4 +#define DT_BLK 6 +#define DT_REG 8 +#define DT_LNK 10 +#define DT_SOCK 12 +#define DT_WHT 14 -#define DIRBUF_SIZE 1024 +#define DIRBUF_SIZE 1024 static inline bool is_dot_or_dotdot(const char* name) { return (name[0] == '.' && !name[1]) || (name[0] == '.' && name[1] == '.' && !name[2]); @@ -449,7 +426,7 @@ static int64_t dir_read(PAL_HANDLE handle, uint64_t offset, size_t count, void* buf += len; bytes_written += len; count -= len; -skip: + skip: handle->dir.ptr = (char*)handle->dir.ptr + dirent->d_reclen; } @@ -485,25 +462,23 @@ static int64_t dir_read(PAL_HANDLE handle, uint64_t offset, size_t count, void* } out: - return (int64_t)bytes_written ? : -PAL_ERROR_ENDOFSTREAM; + return (int64_t)bytes_written ?: -PAL_ERROR_ENDOFSTREAM; } /* 'close' operation of directory streams */ -static int dir_close (PAL_HANDLE handle) -{ +static int dir_close(PAL_HANDLE handle) { int fd = handle->dir.fd; int ret = INLINE_SYSCALL(close, 1, fd); if (handle->dir.buf) { - free((void *) handle->dir.buf); - handle->dir.buf = handle->dir.ptr = handle->dir.end = (PAL_PTR) NULL; + free((void*)handle->dir.buf); + handle->dir.buf = handle->dir.ptr = handle->dir.end = (PAL_PTR)NULL; } /* initial realpath is part of handle object and will be freed with it */ - if (handle->dir.realpath && - handle->dir.realpath != (void *) handle + HANDLE_SIZE(dir)) { - free((void *) handle->dir.realpath); + if (handle->dir.realpath && handle->dir.realpath != (void*)handle + HANDLE_SIZE(dir)) { + free((void*)handle->dir.realpath); } if (IS_ERR(ret)) @@ -513,8 +488,7 @@ static int dir_close (PAL_HANDLE handle) } /* 'delete' operation of directoy streams */ -static int dir_delete (PAL_HANDLE handle, int access) -{ +static int dir_delete(PAL_HANDLE handle, int access) { if (access) return -PAL_ERROR_INVAL; @@ -525,13 +499,10 @@ static int dir_delete (PAL_HANDLE handle, int access) ret = INLINE_SYSCALL(rmdir, 1, handle->dir.realpath); - return (IS_ERR(ret) && ERRNO(ret) != ENOENT) ? - -PAL_ERROR_DENIED : 0; + return (IS_ERR(ret) && ERRNO(ret) != ENOENT) ? -PAL_ERROR_DENIED : 0; } -static int dir_rename (PAL_HANDLE handle, const char * type, - const char * uri) -{ +static int dir_rename(PAL_HANDLE handle, const char* type, const char* uri) { if (strcmp_static(type, URI_TYPE_DIR)) return -PAL_ERROR_INVAL; @@ -546,22 +517,20 @@ static int dir_rename (PAL_HANDLE handle, const char * type, } /* initial realpath is part of handle object and will be freed with it */ - if (handle->dir.realpath && - handle->dir.realpath != (void *) handle + HANDLE_SIZE(dir)) { - free((void *) handle->dir.realpath); + if (handle->dir.realpath && handle->dir.realpath != (void*)handle + HANDLE_SIZE(dir)) { + free((void*)handle->dir.realpath); } handle->dir.realpath = tmp; return 0; } -static int dir_getname (PAL_HANDLE handle, char * buffer, size_t count) -{ +static int dir_getname(PAL_HANDLE handle, char* buffer, size_t count) { if (!handle->dir.realpath) return 0; size_t len = strlen(handle->dir.realpath); - char * tmp = strcpy_static(buffer, URI_PREFIX_DIR, count); + char* tmp = strcpy_static(buffer, URI_PREFIX_DIR, count); if (!tmp || buffer + count < tmp + len + 1) return -PAL_ERROR_TOOLONG; @@ -570,20 +539,19 @@ static int dir_getname (PAL_HANDLE handle, char * buffer, size_t count) return tmp + len - buffer; } -static const char * dir_getrealpath (PAL_HANDLE handle) -{ +static const char* dir_getrealpath(PAL_HANDLE handle) { return handle->dir.realpath; } struct handle_ops g_dir_ops = { - .getname = &dir_getname, - .getrealpath = &dir_getrealpath, - .open = &dir_open, - .read = &dir_read, - .close = &dir_close, - .delete = &dir_delete, - .attrquery = &file_attrquery, - .attrquerybyhdl = &file_attrquerybyhdl, - .attrsetbyhdl = &file_attrsetbyhdl, - .rename = &dir_rename, + .getname = &dir_getname, + .getrealpath = &dir_getrealpath, + .open = &dir_open, + .read = &dir_read, + .close = &dir_close, + .delete = &dir_delete, + .attrquery = &file_attrquery, + .attrquerybyhdl = &file_attrquerybyhdl, + .attrsetbyhdl = &file_attrsetbyhdl, + .rename = &dir_rename, }; diff --git a/Pal/src/host/Linux/db_main-x86_64.c b/Pal/src/host/Linux/db_main-x86_64.c index 15ecd995fb..ecc4b24313 100644 --- a/Pal/src/host/Linux/db_main-x86_64.c +++ b/Pal/src/host/Linux/db_main-x86_64.c @@ -112,12 +112,11 @@ int _DkGetCPUInfo(PAL_CPU_INFO* ci) { ci->cpu_num = cores; cpuid(1, 0, words); - ci->cpu_family = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 8, 12); - ci->cpu_model = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 4, 8); - ci->cpu_stepping = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 0, 4); + ci->cpu_family = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 8, 12); + ci->cpu_model = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 4, 8); + ci->cpu_stepping = BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 0, 4); - if (!memcmp(vendor_id, "GenuineIntel", 12) || - !memcmp(vendor_id, "AuthenticAMD", 12)) { + if (!memcmp(vendor_id, "GenuineIntel", 12) || !memcmp(vendor_id, "AuthenticAMD", 12)) { ci->cpu_family += BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 20, 28); ci->cpu_model += BIT_EXTRACT_LE(words[PAL_CPUID_WORD_EAX], 16, 20) << 4; } @@ -125,7 +124,7 @@ int _DkGetCPUInfo(PAL_CPU_INFO* ci) { int flen = 0, fmax = 80; char* flags = malloc(fmax); - for (int i = 0 ; i < 32 ; i++) { + for (int i = 0; i < 32; i++) { if (!g_cpu_flags[i]) continue; diff --git a/Pal/src/host/Linux/db_main.c b/Pal/src/host/Linux/db_main.c index 3752e81414..3d743bfc71 100644 --- a/Pal/src/host/Linux/db_main.c +++ b/Pal/src/host/Linux/db_main.c @@ -8,7 +8,12 @@ * processes environment, arguments and manifest. */ +#include +#include +#include + #include "api.h" +#include "elf/elf.h" #include "linux_utils.h" #include "pal.h" #include "pal_debug.h" @@ -18,12 +23,7 @@ #include "pal_linux.h" #include "pal_linux_defs.h" #include "pal_security.h" - -#include -#include -#include -#include -#include +#include "sysdeps/generic/ldsodefs.h" #define RTLD_BOOTSTRAP @@ -32,10 +32,11 @@ /* use objfile-gdb convention instead of .debug_gdb_scripts */ #ifdef DEBUG -__asm__ (".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\r\n" - ".byte 1\r\n" - ".asciz \"pal-gdb.py\"\r\n" - ".popsection\r\n"); +__asm__( + ".pushsection \".debug_gdb_scripts\", \"MS\",@progbits,1\r\n" + ".byte 1\r\n" + ".asciz \"pal-gdb.py\"\r\n" + ".popsection\r\n"); #endif char* g_pal_loader_path = NULL; @@ -75,14 +76,14 @@ static void read_args_from_stack(void* initial_rsp, int* out_argc, const char*** assert(argv[argc] == NULL); const char** e = envp; - for (; *e ; e++) { + for (; *e; e++) { #ifdef DEBUG if (!strcmp_static(*e, "IN_GDB=1")) g_linux_state.in_gdb = true; #endif } - for (ElfW(auxv_t)* av = (ElfW(auxv_t)*)(e + 1); av->a_type != AT_NULL ; av++) { + for (ElfW(auxv_t)* av = (ElfW(auxv_t)*)(e + 1); av->a_type != AT_NULL; av++) { switch (av->a_type) { case AT_PAGESZ: g_page_size = av->a_un.a_val; @@ -107,8 +108,7 @@ static void read_args_from_stack(void* initial_rsp, int* out_argc, const char*** *out_envp = envp; } -unsigned long _DkGetAllocationAlignment (void) -{ +unsigned long _DkGetAllocationAlignment(void) { return g_page_size; } @@ -122,11 +122,8 @@ void _DkGetAvailableUserAddressRange(PAL_PTR* start, PAL_PTR* end) { if (start_addr >= end_addr) INIT_FAIL(PAL_ERROR_NOMEM, "no user memory available"); - void* mem = (void*)ARCH_MMAP(start_addr, - g_pal_state.alloc_align, - PROT_NONE, - MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, - -1, 0); + void* mem = (void*)ARCH_MMAP(start_addr, g_pal_state.alloc_align, PROT_NONE, + MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); if (!IS_ERR_P(mem)) { INLINE_SYSCALL(munmap, 2, mem, g_pal_state.alloc_align); if (mem == start_addr) @@ -144,15 +141,14 @@ PAL_NUM _DkGetProcessId(void) { return g_linux_state.process_id; } -PAL_NUM _DkGetHostId (void) -{ +PAL_NUM _DkGetHostId(void) { return 0; } #include "dynamic_link.h" #if USE_VDSO_GETTIME == 1 -void setup_vdso_map (ElfW(Addr) addr); +void setup_vdso_map(ElfW(Addr) addr); #endif static struct link_map g_pal_map; @@ -288,7 +284,7 @@ noreturn void pal_linux_main(void* initial_rsp, void* fini_callback) { * Understands complex formats like "1,3-5,6". */ int get_cpu_count(void) { - int fd = INLINE_SYSCALL(open, 3, "/sys/devices/system/cpu/online", O_RDONLY|O_CLOEXEC, 0); + int fd = INLINE_SYSCALL(open, 3, "/sys/devices/system/cpu/online", O_RDONLY | O_CLOEXEC, 0); if (fd < 0) return unix_to_pal_error(ERRNO(fd)); diff --git a/Pal/src/host/Linux/db_memory.c b/Pal/src/host/Linux/db_memory.c index 28522fb347..ed389ba5fa 100644 --- a/Pal/src/host/Linux/db_memory.c +++ b/Pal/src/host/Linux/db_memory.c @@ -7,6 +7,9 @@ * This files contains APIs that allocate, free or protect virtual memory. */ +#include +#include + #include "api.h" #include "pal.h" #include "pal_debug.h" @@ -17,9 +20,6 @@ #include "pal_linux.h" #include "pal_linux_defs.h" -#include -#include - bool _DkCheckMemoryMappable(const void* addr, size_t size) { return (addr < DATA_END && addr + size > TEXT_START); } @@ -44,8 +44,7 @@ int _DkVirtualMemoryAlloc(void** paddr, size_t size, int alloc_type, int prot) { return 0; } -int _DkVirtualMemoryFree (void * addr, size_t size) -{ +int _DkVirtualMemoryFree(void* addr, size_t size) { int ret = INLINE_SYSCALL(munmap, 2, addr, size); return IS_ERR(ret) ? unix_to_pal_error(ERRNO(ret)) : 0; @@ -56,8 +55,7 @@ int _DkVirtualMemoryProtect(void* addr, size_t size, int prot) { return IS_ERR(ret) ? unix_to_pal_error(ERRNO(ret)) : 0; } -static int read_proc_meminfo (const char * key, unsigned long * val) -{ +static int read_proc_meminfo(const char* key, unsigned long* val) { int fd = INLINE_SYSCALL(open, 3, "/proc/meminfo", O_RDONLY, 0); if (IS_ERR(fd)) @@ -77,7 +75,7 @@ static int read_proc_meminfo (const char * key, unsigned long * val) break; } - for (n = r ; n < r + ret ; n++) + for (n = r; n < r + ret; n++) if (buffer[n] == '\n') break; @@ -88,7 +86,7 @@ static int read_proc_meminfo (const char * key, unsigned long * val) } if (!memcmp(key, buffer, len) && buffer[len] == ':') { - for (size_t i = len + 1; i < n ; i++) + for (size_t i = len + 1; i < n; i++) if (buffer[i] != ' ') { *val = atol(buffer + i); break; @@ -121,8 +119,7 @@ unsigned long _DkMemoryQuota(void) { return (g_linux_state.memory_quota = quota * 1024); } -unsigned long _DkMemoryAvailableQuota (void) -{ +unsigned long _DkMemoryAvailableQuota(void) { unsigned long quota = 0; if (read_proc_meminfo("MemFree", "a) < 0) return 0; diff --git a/Pal/src/host/Linux/db_misc.c b/Pal/src/host/Linux/db_misc.c index 85a50901c7..37d6afd7fd 100644 --- a/Pal/src/host/Linux/db_misc.c +++ b/Pal/src/host/Linux/db_misc.c @@ -129,8 +129,8 @@ int _DkInstructionCacheFlush(const void* addr, int size) { } int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size) { + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size) { __UNUSED(user_report_data); __UNUSED(user_report_data_size); __UNUSED(target_info); @@ -140,8 +140,8 @@ int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_siz return -PAL_ERROR_NOTIMPLEMENTED; } -int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, - PAL_PTR quote, PAL_NUM* quote_size) { +int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, PAL_PTR quote, + PAL_NUM* quote_size) { __UNUSED(user_report_data); __UNUSED(user_report_data_size); __UNUSED(quote); diff --git a/Pal/src/host/Linux/db_mutex.c b/Pal/src/host/Linux/db_mutex.c index dacb0d91e0..f07f991c9d 100644 --- a/Pal/src/host/Linux/db_mutex.c +++ b/Pal/src/host/Linux/db_mutex.c @@ -10,13 +10,13 @@ */ #include -#include #include #include #include #include #include "api.h" +#include "atomic.h" #include "cpu.h" #include "pal.h" #include "pal_defs.h" diff --git a/Pal/src/host/Linux/db_object.c b/Pal/src/host/Linux/db_object.c index 0c5a998d12..fe12630c92 100644 --- a/Pal/src/host/Linux/db_object.c +++ b/Pal/src/host/Linux/db_object.c @@ -35,8 +35,8 @@ int _DkSynchronizationObjectWait(PAL_HANDLE handle, int64_t timeout_us) { /* Wait for specific events on all handles in the handle array and return multiple events * (including errors) reported by the host. Return 0 on success, PAL error on failure. */ -int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events, - int64_t timeout_us) { +int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, + PAL_FLG* ret_events, int64_t timeout_us) { int ret; if (count == 0) @@ -155,7 +155,7 @@ int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events for (size_t k = 0; k < MAX_FDS; k++) { if (hdl->generic.fds[k] != (PAL_IDX)fds[i].fd) continue; - if (fds[i].revents & (POLLHUP|POLLERR|POLLNVAL)) + if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL)) HANDLE_HDR(hdl)->flags |= ERROR(k); } } diff --git a/Pal/src/host/Linux/db_pipes.c b/Pal/src/host/Linux/db_pipes.c index 729335a694..e5dc4c926b 100644 --- a/Pal/src/host/Linux/db_pipes.c +++ b/Pal/src/host/Linux/db_pipes.c @@ -44,9 +44,9 @@ static int pipe_addr(const char* name, struct sockaddr_un* addr) { /*! * \brief Create a listening abstract UNIX socket as preparation for connecting two ends of a pipe. * - * An abstract UNIX socket with name "@/graphene/" is opened for listening. A corresponding - * PAL handle with type `pipesrv` is created. This PAL handle typically serves only as an - * intermediate step to connect two ends of the pipe (`pipecli` and `pipe`). As soon as the other + * An abstract UNIX socket with name "@/graphene/" is opened for listening. A + * corresponding PAL handle with type `pipesrv` is created. This PAL handle typically serves only as + * an intermediate step to connect two ends of the pipe (`pipecli` and `pipe`). As soon as the other * end of the pipe connects to this listening socket, a new accepted socket and the corresponding * PAL handle are created, and this `pipesrv` handle can be closed. * @@ -144,9 +144,9 @@ static int pipe_waitforclient(PAL_HANDLE handle, PAL_HANDLE* client) { * \brief Connect to the other end of the pipe and create PAL handle for our end of the pipe. * * This function connects to the other end of the pipe, represented as an abstract UNIX socket - * "@/graphene/" opened for listening. When the connection succeeds, a new `pipe` PAL handle - * is created with the corresponding underlying socket and is returned in `handle`. The other end of - * the pipe is typically of type `pipecli`. + * "@/graphene/" opened for listening. When the connection succeeds, a new `pipe` PAL + * handle is created with the corresponding underlying socket and is returned in `handle`. The other + * end of the pipe is typically of type `pipecli`. * * \param[out] handle PAL handle of type `pipe` with abstract UNIX socket connected to another end. * \param[in] name String uniquely identifying the pipe. diff --git a/Pal/src/host/Linux/db_process.c b/Pal/src/host/Linux/db_process.c index 5dc25286a3..8c04bc2293 100644 --- a/Pal/src/host/Linux/db_process.c +++ b/Pal/src/host/Linux/db_process.c @@ -56,7 +56,7 @@ static inline int create_process_handle(PAL_HANDLE* parent, PAL_HANDLE* child) { } SET_HANDLE_TYPE(phdl, process); - HANDLE_HDR(phdl)->flags |= RFD(0)|WFD(0); + HANDLE_HDR(phdl)->flags |= RFD(0) | WFD(0); phdl->process.stream = fds[0]; phdl->process.pid = g_linux_state.pid; phdl->process.nonblocking = PAL_FALSE; @@ -68,7 +68,7 @@ static inline int create_process_handle(PAL_HANDLE* parent, PAL_HANDLE* child) { } SET_HANDLE_TYPE(chdl, process); - HANDLE_HDR(chdl)->flags |= RFD(0)|WFD(0); + HANDLE_HDR(chdl)->flags |= RFD(0) | WFD(0); chdl->process.stream = fds[1]; chdl->process.pid = 0; /* unknown yet */ chdl->process.nonblocking = PAL_FALSE; @@ -124,9 +124,9 @@ static int __attribute_noinline child_process(struct proc_param* proc_param) { /* child */ if (proc_param->parent) - handle_set_cloexec(proc_param->parent, false); + handle_set_cloexec(proc_param->parent, false); if (proc_param->exec) - handle_set_cloexec(proc_param->exec, false); + handle_set_cloexec(proc_param->exec, false); if (proc_param->manifest) handle_set_cloexec(proc_param->manifest, false); @@ -135,7 +135,8 @@ static int __attribute_noinline child_process(struct proc_param* proc_param) { /* execve failed, but we're after vfork, so we can't do anything more than just exit */ INLINE_SYSCALL(exit_group, 1, ERRNO(res)); /* UNREACHABLE */ - while (1) {} + while (1) { + } } int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { @@ -160,12 +161,13 @@ int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { */ size_t len; const char* file_uri = URI_PREFIX_FILE; - if (g_exec_map && g_exec_map->l_name && - (len = strlen(uri)) >= URI_PREFIX_FILE_LEN && !memcmp(uri, file_uri, URI_PREFIX_FILE_LEN) && - /* skip "file:"*/ - strlen(g_exec_map->l_name) == len - URI_PREFIX_FILE_LEN && - /* + 1 for lasting * NUL */ - !memcmp(g_exec_map->l_name, uri + URI_PREFIX_FILE_LEN, len - URI_PREFIX_FILE_LEN + 1)) + if (g_exec_map && g_exec_map->l_name && (len = strlen(uri)) >= URI_PREFIX_FILE_LEN && + !memcmp(uri, file_uri, URI_PREFIX_FILE_LEN) && + /* skip "file:"*/ + strlen(g_exec_map->l_name) == len - URI_PREFIX_FILE_LEN && + /* + 1 for lasting * NUL */ + !memcmp(g_exec_map->l_name, + uri + URI_PREFIX_FILE_LEN, len - URI_PREFIX_FILE_LEN + 1)) exec->file.map_start = (PAL_PTR)g_exec_map->l_map_start; } @@ -176,8 +178,8 @@ int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { if (ret < 0) goto out; - param.parent = parent_handle; - param.exec = exec; + param.parent = parent_handle; + param.exec = exec; param.manifest = g_pal_state.manifest_handle; /* step 3: compose process parameters */ @@ -217,8 +219,8 @@ int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { proc_args->parent_process_id = g_linux_state.parent_process_id; memcpy(&proc_args->pal_sec, &g_pal_sec, sizeof(struct pal_sec)); proc_args->pal_sec._dl_debug_state = NULL; - proc_args->pal_sec._r_debug = NULL; - proc_args->memory_quota = g_linux_state.memory_quota; + proc_args->pal_sec._r_debug = NULL; + proc_args->memory_quota = g_linux_state.memory_quota; void* data = (void*)(proc_args + 1); @@ -247,7 +249,8 @@ int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { /* the first argument must be the PAL */ int argc = 0; if (args) - for (; args[argc] ; argc++); + for (; args[argc]; argc++) + ; param.argv = __alloca(sizeof(const char*) * (argc + 5)); param.argv[0] = g_pal_loader_path; param.argv[1] = g_libpal_path; @@ -282,9 +285,7 @@ int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) { /* step 4: send parameters over the process handle */ - ret = INLINE_SYSCALL(write, 3, - child_handle->process.stream, - proc_args, + ret = INLINE_SYSCALL(write, 3, child_handle->process.stream, proc_args, sizeof(struct proc_args) + datasz); if (IS_ERR(ret) || (size_t)ret < sizeof(struct proc_args) + datasz) { @@ -347,8 +348,7 @@ void init_child_process(int parent_pipe_fd, PAL_HANDLE* parent_handle, PAL_HANDL if (proc_args->exec_data_size) { PAL_HANDLE exec = NULL; - ret = handle_deserialize(&exec, data, - proc_args->exec_data_size); + ret = handle_deserialize(&exec, data, proc_args->exec_data_size); if (ret < 0) INIT_FAIL(-ret, "cannot deserialize executable handle"); @@ -360,8 +360,7 @@ void init_child_process(int parent_pipe_fd, PAL_HANDLE* parent_handle, PAL_HANDL if (proc_args->manifest_data_size) { PAL_HANDLE manifest = NULL; - ret = handle_deserialize(&manifest, data, - proc_args->manifest_data_size); + ret = handle_deserialize(&manifest, data, proc_args->manifest_data_size); if (ret < 0) INIT_FAIL(-ret, "cannot deserialize manifest handle"); @@ -373,13 +372,13 @@ void init_child_process(int parent_pipe_fd, PAL_HANDLE* parent_handle, PAL_HANDL memcpy(&g_pal_sec, &proc_args->pal_sec, sizeof(struct pal_sec)); } -noreturn void _DkProcessExit (int exitcode) -{ +noreturn void _DkProcessExit(int exitcode) { if (exitcode == PAL_WAIT_FOR_CHILDREN_EXIT) { /* this is a "temporary" process exiting after execve'ing a child process: it must still * be around until the child finally exits (because its parent in turn may wait on it) */ int wstatus; - int ret = INLINE_SYSCALL(wait4, 4, /*any child*/-1, &wstatus, /*options=*/0, /*rusage=*/NULL); + int ret = INLINE_SYSCALL(wait4, 4, /*any child*/ -1, &wstatus, /*options=*/0, + /*rusage=*/NULL); if (IS_ERR(ret)) { /* it's too late to recover from errors, just set some reasonable exit code */ exitcode = ECHILD; @@ -400,16 +399,14 @@ noreturn void _DkProcessExit (int exitcode) } } -static int64_t proc_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buffer) -{ +static int64_t proc_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer) { if (offset) return -PAL_ERROR_INVAL; int64_t bytes = INLINE_SYSCALL(read, 3, handle->process.stream, buffer, count); if (IS_ERR(bytes)) - switch(ERRNO(bytes)) { + switch (ERRNO(bytes)) { case EWOULDBLOCK: return -PAL_ERROR_TRYAGAIN; case EINTR: @@ -421,16 +418,14 @@ static int64_t proc_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, return bytes; } -static int64_t proc_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buffer) -{ +static int64_t proc_write(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer) { if (offset) return -PAL_ERROR_INVAL; int64_t bytes = INLINE_SYSCALL(write, 3, handle->process.stream, buffer, count); if (IS_ERR(bytes)) - switch(ERRNO(bytes)) { + switch (ERRNO(bytes)) { case EWOULDBLOCK: return -PAL_ERROR_TRYAGAIN; case EINTR: @@ -443,8 +438,7 @@ static int64_t proc_write (PAL_HANDLE handle, uint64_t offset, uint64_t count, return bytes; } -static int proc_close (PAL_HANDLE handle) -{ +static int proc_close(PAL_HANDLE handle) { if (handle->process.stream != PAL_IDX_POISON) { INLINE_SYSCALL(close, 1, handle->process.stream); handle->process.stream = PAL_IDX_POISON; @@ -453,8 +447,7 @@ static int proc_close (PAL_HANDLE handle) return 0; } -static int proc_delete (PAL_HANDLE handle, int access) -{ +static int proc_delete(PAL_HANDLE handle, int access) { int shutdown; switch (access) { case 0: @@ -506,8 +499,7 @@ static int proc_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { return 0; } -static int proc_attrsetbyhdl (PAL_HANDLE handle, PAL_STREAM_ATTR * attr) -{ +static int proc_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (handle->process.stream == PAL_IDX_POISON) return -PAL_ERROR_BADHANDLE; @@ -526,10 +518,10 @@ static int proc_attrsetbyhdl (PAL_HANDLE handle, PAL_STREAM_ATTR * attr) } struct handle_ops g_proc_ops = { - .read = &proc_read, - .write = &proc_write, - .close = &proc_close, - .delete = &proc_delete, - .attrquerybyhdl = &proc_attrquerybyhdl, - .attrsetbyhdl = &proc_attrsetbyhdl, - }; + .read = &proc_read, + .write = &proc_write, + .close = &proc_close, + .delete = &proc_delete, + .attrquerybyhdl = &proc_attrquerybyhdl, + .attrsetbyhdl = &proc_attrsetbyhdl, +}; diff --git a/Pal/src/host/Linux/db_rtld.c b/Pal/src/host/Linux/db_rtld.c index 1431a60d37..82c716486d 100644 --- a/Pal/src/host/Linux/db_rtld.c +++ b/Pal/src/host/Linux/db_rtld.c @@ -12,21 +12,19 @@ #include "db_rtld.h" -#include "pal_defs.h" -#include "pal_linux_defs.h" +#include "api.h" +#include "elf-arch.h" +#include "elf/elf.h" #include "pal.h" -#include "pal_internal.h" -#include "pal_linux.h" #include "pal_debug.h" +#include "pal_defs.h" #include "pal_error.h" -#include "pal_security.h" +#include "pal_internal.h" +#include "pal_linux.h" +#include "pal_linux_defs.h" #include "pal_rtld.h" -#include "api.h" - +#include "pal_security.h" #include "sysdeps/generic/ldsodefs.h" -#include "elf/elf.h" - -#include "elf-arch.h" /* This function exists solely to have a breakpoint set on it by the debugger. The debugger is * supposed to find this function's address by examining the r_brk member of struct r_debug, but GDB @@ -36,8 +34,7 @@ static void __attribute__((noinline)) pal_dl_debug_state(void) { g_pal_sec._dl_debug_state(); } -extern __typeof(pal_dl_debug_state) _dl_debug_state - __attribute((alias("pal_dl_debug_state"))); +extern __typeof(pal_dl_debug_state) _dl_debug_state __attribute((alias("pal_dl_debug_state"))); /* This structure communicates dl state to the debugger. The debugger normally finds it via the * DT_DEBUG entry in the dynamic section, but in a statically-linked program there is no dynamic @@ -45,31 +42,30 @@ extern __typeof(pal_dl_debug_state) _dl_debug_state struct r_debug g_pal_r_debug = {1, NULL, (ElfW(Addr))&pal_dl_debug_state, RT_CONSISTENT, 0}; symbol_version_default(g_pal_r_debug, _r_debug, PAL); -void _DkDebugAddMap (struct link_map * map) -{ +void _DkDebugAddMap(struct link_map* map) { #ifdef DEBUG - struct r_debug* dbg = g_pal_sec._r_debug ? : &g_pal_r_debug; + struct r_debug* dbg = g_pal_sec._r_debug ?: &g_pal_r_debug; int len = map->l_name ? strlen(map->l_name) + 1 : 0; - struct link_map ** prev = &dbg->r_map, * last = NULL, - * tmp = *prev; + struct link_map** prev = &dbg->r_map; + struct link_map* last = NULL; + struct link_map* tmp = *prev; while (tmp) { - if (tmp->l_addr == map->l_addr && - tmp->l_ld == map->l_ld && - !memcmp(tmp->l_name, map->l_name, len)) + if (tmp->l_addr == map->l_addr && tmp->l_ld == map->l_ld && + !memcmp(tmp->l_name, map->l_name, len)) return; last = tmp; tmp = *(prev = &last->l_next); } - struct link_gdb_map * m = malloc(sizeof(struct link_gdb_map) + len); + struct link_gdb_map* m = malloc(sizeof(struct link_gdb_map) + len); if (!m) return; if (len) { - m->l_name = (char *) m + sizeof(struct link_gdb_map); - memcpy((void *) m->l_name, map->l_name, len); + m->l_name = (char*)m + sizeof(struct link_gdb_map); + memcpy((void*)m->l_name, map->l_name, len); } else { m->l_name = NULL; } @@ -80,7 +76,7 @@ void _DkDebugAddMap (struct link_map * map) dbg->r_state = RT_ADD; pal_dl_debug_state(); - *prev = (struct link_map *) m; + *prev = (struct link_map*)m; m->l_prev = last; m->l_next = NULL; @@ -91,18 +87,18 @@ void _DkDebugAddMap (struct link_map * map) #endif } -void _DkDebugDelMap (struct link_map * map) -{ +void _DkDebugDelMap(struct link_map* map) { #ifdef DEBUG - struct r_debug* dbg = g_pal_sec._r_debug ? : &g_pal_r_debug; + struct r_debug* dbg = g_pal_sec._r_debug ?: &g_pal_r_debug; int len = map->l_name ? strlen(map->l_name) + 1 : 0; - struct link_map ** prev = &dbg->r_map, * last = NULL, - * tmp = *prev, * found = NULL; + struct link_map** prev = &dbg->r_map; + struct link_map* last = NULL; + struct link_map* tmp = *prev; + struct link_map* found = NULL; while (tmp) { - if (tmp->l_addr == map->l_addr && - tmp->l_ld == map->l_ld && - !memcmp(tmp->l_name, map->l_name, len)) { + if (tmp->l_addr == map->l_addr && tmp->l_ld == map->l_ld && + !memcmp(tmp->l_name, map->l_name, len)) { found = tmp; break; } @@ -134,15 +130,14 @@ void _DkDebugDelMap (struct link_map * map) #endif } -void setup_pal_map (struct link_map * pal_map) -{ - const ElfW(Ehdr) * header = (void *) pal_map->l_addr; +void setup_pal_map(struct link_map* pal_map) { + const ElfW(Ehdr)* header = (void*)pal_map->l_addr; - pal_map->l_real_ld = pal_map->l_ld = (void *) elf_machine_dynamic(); - pal_map->l_type = OBJECT_RTLD; - pal_map->l_entry = header->e_entry; - pal_map->l_phdr = (void *) (pal_map->l_addr + header->e_phoff); - pal_map->l_phnum = header->e_phnum; + pal_map->l_real_ld = pal_map->l_ld = (void*)elf_machine_dynamic(); + pal_map->l_type = OBJECT_RTLD; + pal_map->l_entry = header->e_entry; + pal_map->l_phdr = (void*)(pal_map->l_addr + header->e_phoff); + pal_map->l_phnum = header->e_phnum; setup_elf_hash(pal_map); _DkDebugAddMap(pal_map); @@ -151,37 +146,35 @@ void setup_pal_map (struct link_map * pal_map) } #if USE_VDSO_GETTIME == 1 -void setup_vdso_map (ElfW(Addr) addr) -{ - const ElfW(Ehdr) * header = (void *) addr; +void setup_vdso_map(ElfW(Addr) addr) { + const ElfW(Ehdr)* header = (void*)addr; struct link_map vdso_map; memset(&vdso_map, 0, sizeof(struct link_map)); - vdso_map.l_name = "vdso"; - vdso_map.l_type = OBJECT_RTLD; + vdso_map.l_name = "vdso"; + vdso_map.l_type = OBJECT_RTLD; vdso_map.l_addr = addr; vdso_map.l_entry = header->e_entry; - vdso_map.l_phdr = (void *) (addr + header->e_phoff); + vdso_map.l_phdr = (void*)(addr + header->e_phoff); vdso_map.l_phnum = header->e_phnum; ElfW(Addr) load_offset = 0; const ElfW(Phdr) * ph; - for (ph = vdso_map.l_phdr; ph < &vdso_map.l_phdr[vdso_map.l_phnum]; ++ph) + for (ph = vdso_map.l_phdr; ph < &vdso_map.l_phdr[vdso_map.l_phnum]; ph++) switch (ph->p_type) { case PT_LOAD: - load_offset = addr + (ElfW(Addr)) ph->p_offset - - (ElfW(Addr)) ph->p_vaddr; + load_offset = addr + (ElfW(Addr))ph->p_offset - (ElfW(Addr))ph->p_vaddr; break; case PT_DYNAMIC: - vdso_map.l_real_ld = vdso_map.l_ld = (void *) addr + ph->p_offset; - vdso_map.l_ldnum = ph->p_memsz / sizeof (ElfW(Dyn)); + vdso_map.l_real_ld = vdso_map.l_ld = (void*)addr + ph->p_offset; + vdso_map.l_ldnum = ph->p_memsz / sizeof(ElfW(Dyn)); break; } ElfW(Dyn) local_dyn[4]; int ndyn = 0; ElfW(Dyn) * dyn; - for (dyn = vdso_map.l_ld ; dyn < &vdso_map.l_ld[vdso_map.l_ldnum]; ++dyn) + for (dyn = vdso_map.l_ld; dyn < &vdso_map.l_ld[vdso_map.l_ldnum]; dyn++) switch(dyn->d_tag) { case DT_STRTAB: case DT_SYMTAB: @@ -190,7 +183,7 @@ void setup_vdso_map (ElfW(Addr) addr) vdso_map.l_info[dyn->d_tag] = &local_dyn[ndyn++]; break; case DT_HASH: { - ElfW(Word) * h = (ElfW(Word) *) (D_PTR(dyn) + load_offset); + ElfW(Word)* h = (ElfW(Word)*)(D_PTR(dyn) + load_offset); vdso_map.l_nbuckets = h[0]; vdso_map.l_buckets = &h[2]; vdso_map.l_chain = &h[vdso_map.l_nbuckets + 2]; @@ -205,13 +198,13 @@ void setup_vdso_map (ElfW(Addr) addr) } #if USE_CLOCK_GETTIME == 1 - const char * gettime = "__vdso_clock_gettime"; + const char* gettime = "__vdso_clock_gettime"; #else - const char * gettime = "__vdso_gettimeofday"; + const char* gettime = "__vdso_gettimeofday"; #endif uint_fast32_t fast_hash = elf_fast_hash(gettime); long int hash = elf_hash(gettime); - ElfW(Sym) * sym = NULL; + ElfW(Sym)* sym = NULL; sym = do_lookup_map(NULL, gettime, fast_hash, hash, &vdso_map); if (sym) diff --git a/Pal/src/host/Linux/db_sockets.c b/Pal/src/host/Linux/db_sockets.c index be4aaf506e..2e8be85cc6 100644 --- a/Pal/src/host/Linux/db_sockets.c +++ b/Pal/src/host/Linux/db_sockets.c @@ -294,14 +294,16 @@ static int tcp_listen(PAL_HANDLE* handle, char* uri, int create, int options) { /* must set the socket to be reuseable */ int reuseaddr = 1; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, + sizeof(reuseaddr)); if (IS_ERR(ret)) return -PAL_ERROR_INVAL; if (bind_addr->sa_family == AF_INET6) { /* IPV6_V6ONLY socket option can only be set before first bind */ int ipv6_v6only = create & PAL_CREATE_DUALSTACK ? 0 : 1; - ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_v6only, sizeof(ipv6_v6only)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_v6only, + sizeof(ipv6_v6only)); if (IS_ERR(ret)) return -PAL_ERROR_INVAL; } @@ -355,7 +357,7 @@ static int tcp_accept(PAL_HANDLE handle, PAL_HANDLE* client) { size_t bind_addrlen = addr_size(bind_addr); struct sockaddr_storage buffer; int addrlen = sizeof(buffer); - int ret = 0; + int ret = 0; int newfd = INLINE_SYSCALL(accept4, 4, handle->sock.fd, &buffer, &addrlen, SOCK_CLOEXEC); @@ -434,7 +436,7 @@ static int tcp_connect(PAL_HANDLE* handle, char* uri, int options) { if (IS_ERR(ret) && ERRNO(ret) == EINPROGRESS) { struct pollfd pfd = {.fd = fd, .events = POLLOUT, .revents = 0}; - ret = INLINE_SYSCALL(ppoll, 5, &pfd, 1, NULL, NULL, 0); + ret = INLINE_SYSCALL(ppoll, 5, &pfd, 1, NULL, NULL, 0); } if (IS_ERR(ret)) { @@ -584,7 +586,8 @@ static int udp_bind(PAL_HANDLE* handle, char* uri, int create, int options) { /* IPV6_V6ONLY socket option can only be set before first bind */ if (bind_addr->sa_family == AF_INET6) { int ipv6_v6only = create & PAL_CREATE_DUALSTACK ? 0 : 1; - ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_v6only, sizeof(ipv6_v6only)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_v6only, + sizeof(ipv6_v6only)); if (IS_ERR(ret)) return -PAL_ERROR_INVAL; } @@ -909,9 +912,9 @@ static int socket_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (handle->sock.fd == PAL_IDX_POISON) return -PAL_ERROR_BADHANDLE; - attr->handle_type = HANDLE_HDR(handle)->type; - attr->nonblocking = handle->sock.nonblocking; - attr->disconnected = HANDLE_HDR(handle)->flags & ERROR(0); + attr->handle_type = HANDLE_HDR(handle)->type; + attr->nonblocking = handle->sock.nonblocking; + attr->disconnected = HANDLE_HDR(handle)->flags & ERROR(0); attr->socket.linger = handle->sock.linger; attr->socket.receivebuf = handle->sock.receivebuf; @@ -965,7 +968,7 @@ static int socket_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { struct __kernel_linger l; l.l_onoff = attr->socket.linger ? 1 : 0; l.l_linger = attr->socket.linger; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_LINGER, &l, + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_LINGER, &l, sizeof(struct __kernel_linger)); if (IS_ERR(ret)) @@ -976,7 +979,7 @@ static int socket_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (attr->socket.receivebuf != handle->sock.receivebuf) { int val = attr->socket.receivebuf; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_RCVBUF, &val, sizeof(int)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_RCVBUF, &val, sizeof(int)); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); @@ -986,7 +989,7 @@ static int socket_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (attr->socket.sendbuf != handle->sock.sendbuf) { int val = attr->socket.sendbuf; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_SNDBUF, &val, sizeof(int)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_SNDBUF, &val, sizeof(int)); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); @@ -996,7 +999,7 @@ static int socket_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (attr->socket.receivetimeout != handle->sock.receivetimeout) { int val = attr->socket.receivetimeout; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_RCVTIMEO, &val, sizeof(int)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_RCVTIMEO, &val, sizeof(int)); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); @@ -1006,7 +1009,7 @@ static int socket_attrsetbyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) { if (attr->socket.sendtimeout != handle->sock.sendtimeout) { int val = attr->socket.sendtimeout; - ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_SNDTIMEO, &val, sizeof(int)); + ret = INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_SNDTIMEO, &val, sizeof(int)); if (IS_ERR(ret)) return unix_to_pal_error(ERRNO(ret)); diff --git a/Pal/src/host/Linux/db_streams.c b/Pal/src/host/Linux/db_streams.c index 0b9850d59a..09aaa6965d 100644 --- a/Pal/src/host/Linux/db_streams.c +++ b/Pal/src/host/Linux/db_streams.c @@ -71,7 +71,7 @@ int handle_set_cloexec(PAL_HANDLE handle, bool enable) { for (int i = 0; i < MAX_FDS; i++) if (HANDLE_HDR(handle)->flags & (RFD(i) | WFD(i))) { long flags = enable ? FD_CLOEXEC : 0; - int ret = INLINE_SYSCALL(fcntl, 3, handle->generic.fds[i], F_SETFD, flags); + int ret = INLINE_SYSCALL(fcntl, 3, handle->generic.fds[i], F_SETFD, flags); if (IS_ERR(ret) && ERRNO(ret) != EBADF) return -PAL_ERROR_DENIED; } diff --git a/Pal/src/host/Linux/db_threading.c b/Pal/src/host/Linux/db_threading.c index 5a913445f0..12da7f477d 100644 --- a/Pal/src/host/Linux/db_threading.c +++ b/Pal/src/host/Linux/db_threading.c @@ -7,6 +7,17 @@ * This file contain APIs to create, exit and yield a thread. */ +#include /* linux/signal.h misses this dependency (for size_t), at least on Ubuntu 16.04. + * We must include it ourselves before including linux/signal.h. + */ + +#include +#include +#include +#include +#include +#include + #include "api.h" #include "pal.h" #include "pal_debug.h" @@ -16,12 +27,6 @@ #include "pal_linux.h" #include "pal_linux_defs.h" #include "spinlock.h" -#include -#include -#include -#include -#include -#include /* Linux PAL cannot use mmap/unmap to manage thread stacks because this may overlap with * pal_control.user_address. Linux PAL also cannot just use malloc/free because DkThreadExit @@ -110,9 +115,7 @@ int pal_thread_init(void* tcbptr) { /* _DkThreadCreate for internal use. Create an internal thread inside the current process. The arguments callback and param specify the starting function and parameters */ -int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), - const void * param) -{ +int _DkThreadCreate(PAL_HANDLE* handle, int (*callback)(void*), const void* param) { int ret = 0; PAL_HANDLE hdl = NULL; void* stack = get_thread_stack(); @@ -138,7 +141,7 @@ int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), memset(stack + THREAD_STACK_SIZE - PRESET_PAGESIZE, 0, PRESET_PAGESIZE); memset(stack + THREAD_STACK_SIZE, 0, ALT_STACK_SIZE); - void * child_stack = stack + THREAD_STACK_SIZE; + void* child_stack = stack + THREAD_STACK_SIZE; hdl = malloc(HANDLE_SIZE(thread)); if (!hdl) { @@ -148,12 +151,12 @@ int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), SET_HANDLE_TYPE(hdl, thread); // Initialize TCB at the top of the alternative stack. - PAL_TCB_LINUX * tcb = child_stack + ALT_STACK_SIZE - sizeof(PAL_TCB_LINUX); + PAL_TCB_LINUX* tcb = child_stack + ALT_STACK_SIZE - sizeof(PAL_TCB_LINUX); tcb->common.self = &tcb->common; - tcb->handle = hdl; - tcb->alt_stack = child_stack; // Stack bottom - tcb->callback = callback; - tcb->param = (void *) param; + tcb->handle = hdl; + tcb->alt_stack = child_stack; // Stack bottom + tcb->callback = callback; + tcb->param = (void*)param; /* align child_stack to 16 */ child_stack = ALIGN_DOWN_PTR(child_stack, 16); @@ -161,8 +164,8 @@ int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), // TODO: pal_thread_init() may fail during initialization, we should check its result (but this // happens asynchronously, so it's not trivial to do). ret = clone(pal_thread_init, child_stack, - CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_THREAD | - CLONE_SIGHAND | CLONE_PARENT_SETTID, + CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_THREAD | CLONE_SIGHAND | + CLONE_PARENT_SETTID, (void*)tcb, &hdl->thread.tid, NULL); if (IS_ERR(ret)) { @@ -189,7 +192,7 @@ int _DkThreadDelayExecution(uint64_t* duration_us) { sleeptime.tv_sec = VERY_LONG_TIME_IN_US / 1000000; sleeptime.tv_nsec = 0; } else { - sleeptime.tv_sec = *duration_us / 1000000; + sleeptime.tv_sec = *duration_us / 1000000; sleeptime.tv_nsec = (*duration_us - sleeptime.tv_sec * (uint64_t)1000000) * 1000; } @@ -206,8 +209,7 @@ int _DkThreadDelayExecution(uint64_t* duration_us) { /* PAL call DkThreadYieldExecution. Yield the execution of the current thread. */ -void _DkThreadYieldExecution (void) -{ +void _DkThreadYieldExecution(void) { INLINE_SYSCALL(sched_yield, 0); } @@ -245,20 +247,23 @@ noreturn void _DkThreadExit(int* clear_child_tid) { * 2. Set *clear_child_tid = 0 if clear_child_tid != NULL * (we thus inform LibOS, where async helper thread is waiting on this to wake up parent) * 3. Exit thread */ - static_assert(sizeof(g_thread_stack_lock.lock) == 4, "unexpected g_thread_stack_lock.lock size"); - static_assert(offsetof(__typeof__(g_thread_stack_lock), lock) == 0, "unexpected offset of lock in g_thread_stack_lock"); - static_assert(sizeof(*clear_child_tid) == 4, "unexpected clear_child_tid size"); - - __asm__ volatile("movl $0, (%%rdx) \n\t" /* spinlock_unlock(&g_thread_stack_lock) */ - "cmpq $0, %%rbx \n\t" /* check if clear_child_tid != NULL */ - "je 1f \n\t" - "movl $0, (%%rbx) \n\t" /* set *clear_child_tid = 0 */ - "1: \n\t" - "syscall \n\t" /* rdi arg is already prepared, call exit */ - : /* no output regs since we don't return from exit */ - : "a"(__NR_exit), "D"(0), /* rdi = exit status == 0 */ - "d"(&g_thread_stack_lock.lock), "b"(clear_child_tid) - : "cc", "rcx", "r11", "memory" /* syscall instr clobbers cc, rcx, and r11 */ + static_assert(sizeof(g_thread_stack_lock.lock) == 4, + "unexpected g_thread_stack_lock.lock size"); + static_assert(offsetof(__typeof__(g_thread_stack_lock), lock) == 0, + "unexpected offset of lock in g_thread_stack_lock"); + static_assert(sizeof(*clear_child_tid) == 4, "unexpected clear_child_tid size"); + + __asm__ volatile( + "movl $0, (%%rdx) \n\t" /* spinlock_unlock(&g_thread_stack_lock) */ + "cmpq $0, %%rbx \n\t" /* check if clear_child_tid != NULL */ + "je 1f \n\t" + "movl $0, (%%rbx) \n\t" /* set *clear_child_tid = 0 */ + "1: \n\t" + "syscall \n\t" /* rdi arg is already prepared, call exit */ + : /* no output regs since we don't return from exit */ + : "a"(__NR_exit), "D"(0), /* rdi = exit status == 0 */ + "d"(&g_thread_stack_lock.lock), "b"(clear_child_tid) + : "cc", "rcx", "r11", "memory" /* syscall instr clobbers cc, rcx, and r11 */ ); while (true) { @@ -266,12 +271,8 @@ noreturn void _DkThreadExit(int* clear_child_tid) { } } -int _DkThreadResume (PAL_HANDLE threadHandle) -{ - int ret = INLINE_SYSCALL(tgkill, 3, - g_linux_state.pid, - threadHandle->thread.tid, - SIGCONT); +int _DkThreadResume(PAL_HANDLE threadHandle) { + int ret = INLINE_SYSCALL(tgkill, 3, g_linux_state.pid, threadHandle->thread.tid, SIGCONT); if (IS_ERR(ret)) return -PAL_ERROR_DENIED; diff --git a/Pal/src/host/Linux/pal_host.h b/Pal/src/host/Linux/pal_host.h index 23505af2b6..152c4f9789 100644 --- a/Pal/src/host/Linux/pal_host.h +++ b/Pal/src/host/Linux/pal_host.h @@ -11,10 +11,10 @@ #define PAL_HOST_H #ifndef IN_PAL -# error "cannot be included outside PAL" +#error "cannot be included outside PAL" #endif -#include +#include "atomic.h" /* Simpler mutex design: a single variable that tracks whether the * mutex is locked. State is 1 (locked) or 0 (unlocked). @@ -31,10 +31,15 @@ typedef struct mutex_handle { } PAL_LOCK; /* Initializer of Mutexes */ -#define MUTEX_HANDLE_INIT { .locked = 0, .nwaiters.counter = 0 } -#define INIT_MUTEX_HANDLE(m) do { (m)->locked = 0; atomic_set(&(m)->nwaiters, 0); } while (0) - -#define LOCK_INIT MUTEX_HANDLE_INIT +#define MUTEX_HANDLE_INIT \ + { .locked = 0, .nwaiters.counter = 0 } +#define INIT_MUTEX_HANDLE(m) \ + do { \ + (m)->locked = 0; \ + atomic_set(&(m)->nwaiters, 0); \ + } while (0) + +#define LOCK_INIT MUTEX_HANDLE_INIT #define INIT_LOCK(lock) INIT_MUTEX_HANDLE(lock) /* Locking and unlocking of Mutexes */ @@ -50,8 +55,7 @@ typedef struct { char str[PIPE_NAME_MAX]; } PAL_PIPE_NAME; -typedef struct pal_handle -{ +typedef struct pal_handle { /* TSAI: Here we define the internal types of PAL_HANDLE * in PAL design, user has not to access the content inside the * handle, also there is no need to allocate the internal @@ -148,17 +152,23 @@ typedef struct pal_handle }; } * PAL_HANDLE; -#define RFD(n) (1 << (MAX_FDS*0 + (n))) -#define WFD(n) (1 << (MAX_FDS*1 + (n))) -#define ERROR(n) (1 << (MAX_FDS*2 + (n))) +#define RFD(n) (1 << (MAX_FDS * 0 + (n))) +#define WFD(n) (1 << (MAX_FDS * 1 + (n))) +#define ERROR(n) (1 << (MAX_FDS * 2 + (n))) -#define HANDLE_TYPE(handle) ((handle)->hdr.type) +#define HANDLE_TYPE(handle) ((handle)->hdr.type) -extern void __check_pending_event (void); +extern void __check_pending_event(void); -#define LEAVE_PAL_CALL() do { __check_pending_event(); } while (0) +#define LEAVE_PAL_CALL() \ + do { \ + __check_pending_event(); \ + } while (0) #define LEAVE_PAL_CALL_RETURN(retval) \ - do { __check_pending_event(); return (retval); } while (0) + do { \ + __check_pending_event(); \ + return (retval); \ + } while (0) #endif /* PAL_HOST_H */ diff --git a/Pal/src/host/Linux/pal_linux.h b/Pal/src/host/Linux/pal_linux.h index b4fb482e5e..5a9b511b7c 100644 --- a/Pal/src/host/Linux/pal_linux.h +++ b/Pal/src/host/Linux/pal_linux.h @@ -4,28 +4,26 @@ #ifndef PAL_LINUX_H #define PAL_LINUX_H -#include "pal_defs.h" -#include "pal_linux_defs.h" -#include "pal.h" -#include "pal_internal.h" -#include "pal_linux_error.h" -#include "list.h" - +#include #include -#include #include - -#include #include +#include #include #include +#include "list.h" +#include "pal.h" +#include "pal_defs.h" +#include "pal_internal.h" +#include "pal_linux_defs.h" +#include "pal_linux_error.h" #include "sysdep-arch.h" -#define IS_ERR INTERNAL_SYSCALL_ERROR +#define IS_ERR INTERNAL_SYSCALL_ERROR #define IS_ERR_P INTERNAL_SYSCALL_ERROR_P -#define ERRNO INTERNAL_SYSCALL_ERRNO -#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P +#define ERRNO INTERNAL_SYSCALL_ERRNO +#define ERRNO_P INTERNAL_SYSCALL_ERRNO_P struct timespec; struct timeval; @@ -51,62 +49,60 @@ extern struct pal_linux_state { unsigned long memory_quota; #if USE_VDSO_GETTIME == 1 -# if USE_CLOCK_GETTIME == 1 - long int (*vdso_clock_gettime) (long int clk, struct timespec * tp); -# else - long int (*vdso_gettimeofday) (struct timeval *, void *); -# endif +#if USE_CLOCK_GETTIME == 1 + long int (*vdso_clock_gettime)(long int clk, struct timespec* tp); +#else + long int (*vdso_gettimeofday)(struct timeval*, void*); +#endif #endif } g_linux_state; - -#include - #ifdef INLINE_SYSCALL -# ifdef __i386__ -# define ARCH_MMAP(addr, len, prot, flags, fd, offset) \ - ({ \ - struct mmap_arg_struct { \ - unsigned long addr; \ - unsigned long len; \ - unsigned long prot; \ - unsigned long flags; \ - unsigned long fd; \ - unsigned long offset; \ - } args = { .addr = (unsigned long)(addr), \ - .len = (unsigned long)(len), \ - .prot = (unsigned long)(prot), \ - .flags = (unsigned long)(flags), \ - .fd = (unsigned long)(fd), \ - .offset = (unsigned long)(offset), }; \ - INLINE_SYSCALL(mmap, 1, &args); \ +#ifdef __i386__ +#define ARCH_MMAP(addr, len, prot, flags, fd, offset) \ + ({ \ + struct mmap_arg_struct { \ + unsigned long addr; \ + unsigned long len; \ + unsigned long prot; \ + unsigned long flags; \ + unsigned long fd; \ + unsigned long offset; \ + } args = { \ + .addr = (unsigned long)(addr), \ + .len = (unsigned long)(len), \ + .prot = (unsigned long)(prot), \ + .flags = (unsigned long)(flags), \ + .fd = (unsigned long)(fd), \ + .offset = (unsigned long)(offset), \ + }; \ + INLINE_SYSCALL(mmap, 1, &args); \ }) -# else -# define ARCH_MMAP(addr, len, prot, flags, fd, offset) \ +#else +#define ARCH_MMAP(addr, len, prot, flags, fd, offset) \ INLINE_SYSCALL(mmap, 6, addr, len, prot, flags, fd, offset) -# endif +#endif #else -# error "INLINE_SYSCALL not supported" +#error "INLINE_SYSCALL not supported" #endif #ifndef SIGCHLD -# define SIGCHLD 17 +#define SIGCHLD 17 #endif #ifdef DEBUG -# define ARCH_VFORK() \ - (g_linux_state.in_gdb ? \ - INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK|SIGCHLD, 0, NULL, NULL) :\ - INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK, 0, NULL, NULL)) +#define ARCH_VFORK() \ + (g_linux_state.in_gdb \ + ? INLINE_SYSCALL(clone, 4, CLONE_VM | CLONE_VFORK | SIGCHLD, 0, NULL, NULL) \ + : INLINE_SYSCALL(clone, 4, CLONE_VM | CLONE_VFORK, 0, NULL, NULL)) #else # define ARCH_VFORK() \ - (INLINE_SYSCALL(clone, 4, CLONE_VM|CLONE_VFORK, 0, NULL, NULL)) + (INLINE_SYSCALL(clone, 4, CLONE_VM | CLONE_VFORK, 0, NULL, NULL)) #endif #define DEFAULT_BACKLOG 2048 -int clone (int (*__fn) (void * __arg), void * __child_stack, - int __flags, const void * __arg, ...); +int clone(int (*__fn)(void* __arg), void* __child_stack, int __flags, const void* __arg, ...); /* PAL main function */ noreturn void pal_linux_main(void* initial_rsp, void* fini_callback); @@ -115,17 +111,17 @@ struct link_map; void setup_pal_map(struct link_map* map); /* set/unset CLOEXEC flags of all fds in a handle */ -int handle_set_cloexec (PAL_HANDLE handle, bool enable); +int handle_set_cloexec(PAL_HANDLE handle, bool enable); /* serialize/deserialize a handle into/from a malloc'ed buffer */ -int handle_serialize (PAL_HANDLE handle, void ** data); -int handle_deserialize (PAL_HANDLE * handle, const void * data, int size); +int handle_serialize(PAL_HANDLE handle, void** data); +int handle_deserialize(PAL_HANDLE* handle, const void* data, int size); -#define ACCESS_R 4 -#define ACCESS_W 2 -#define ACCESS_X 1 +#define ACCESS_R 4 +#define ACCESS_W 2 +#define ACCESS_X 1 -bool stataccess (struct stat * stats, int acc); +bool stataccess(struct stat* stats, int acc); void init_child_process(int parent_pipe_fd, PAL_HANDLE* parent, PAL_HANDLE* exec, PAL_HANDLE* manifest); @@ -133,12 +129,11 @@ void init_child_process(int parent_pipe_fd, PAL_HANDLE* parent, PAL_HANDLE* exec int get_cpu_count(void); ssize_t read_file_buffer(const char* filename, char* buf, size_t buf_size); -void cpuid (unsigned int leaf, unsigned int subleaf, - unsigned int words[]); -int block_async_signals (bool block); -void signal_setup (void); +void cpuid(unsigned int leaf, unsigned int subleaf, unsigned int words[]); +int block_async_signals(bool block); +void signal_setup(void); -unsigned long _DkSystemTimeQueryEarly (void); +unsigned long _DkSystemTimeQueryEarly(void); extern char __text_start, __text_end, __data_start, __data_end; #define TEXT_START ((void*)(&__text_start)) @@ -155,19 +150,18 @@ typedef struct pal_tcb_linux { PAL_TCB common; struct { /* private to Linux PAL */ - int pending_events[MAX_SIGNAL_LOG]; - int pending_events_num; - PAL_HANDLE handle; - void * alt_stack; - int (*callback) (void *); - void * param; + int pending_events[MAX_SIGNAL_LOG]; + int pending_events_num; + PAL_HANDLE handle; + void* alt_stack; + int (*callback)(void*); + void* param; }; } PAL_TCB_LINUX; int pal_thread_init(void* tcbptr); -static inline PAL_TCB_LINUX * get_tcb_linux (void) -{ +static inline PAL_TCB_LINUX* get_tcb_linux(void) { return (PAL_TCB_LINUX*)pal_get_tcb(); } diff --git a/Pal/src/host/Linux/pal_linux_error.h b/Pal/src/host/Linux/pal_linux_error.h index f1f0795170..ea81a0c678 100644 --- a/Pal/src/host/Linux/pal_linux_error.h +++ b/Pal/src/host/Linux/pal_linux_error.h @@ -4,7 +4,8 @@ #ifdef IN_PAL #include -#include + +#include "pal_error.h" static inline __attribute__((unused)) int unix_to_pal_error(int unix_errno) { switch (unix_errno) { diff --git a/Pal/src/host/Linux/pal_security.h b/Pal/src/host/Linux/pal_security.h index 7dc87439ac..acb1e86289 100644 --- a/Pal/src/host/Linux/pal_security.h +++ b/Pal/src/host/Linux/pal_security.h @@ -5,9 +5,9 @@ #define PAL_SECURITY_H #include -#include #include "pal.h" +#include "sysdeps/generic/ldsodefs.h" /* Rendezvous structure used by the run-time dynamic linker to communicate details of shared object loading to the debugger. If the executable's diff --git a/Pal/src/host/Skeleton/db_eventfd.c b/Pal/src/host/Skeleton/db_eventfd.c index a102f56825..5e057723b4 100644 --- a/Pal/src/host/Skeleton/db_eventfd.c +++ b/Pal/src/host/Skeleton/db_eventfd.c @@ -13,7 +13,7 @@ #include "pal_error.h" #include "pal_internal.h" -/* `type` must be eventfd, `uri` & `access` & `share` are unused, `create` holds eventfd's initval, +/* `type` must be eventfd, `uri` & `access` & `share` are unused, `create` holds eventfd's initval, * `options` holds eventfd's flags */ static int eventfd_pal_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share, int create, int options) { diff --git a/Pal/src/host/Skeleton/db_main.c b/Pal/src/host/Skeleton/db_main.c index da4eaab827..d70e221127 100644 --- a/Pal/src/host/Skeleton/db_main.c +++ b/Pal/src/host/Skeleton/db_main.c @@ -8,18 +8,17 @@ * processes environment, arguments and manifest. */ -#include "pal_defs.h" +#include "api.h" #include "pal.h" -#include "pal_internal.h" #include "pal_debug.h" +#include "pal_defs.h" #include "pal_error.h" -#include "api.h" +#include "pal_internal.h" /* must implement "pal_start", and call "pal_main" inside */ -void pal_start (void); +void pal_start(void); -unsigned long _DkGetAllocationAlignment (void) -{ +unsigned long _DkGetAllocationAlignment(void) { return 0; } @@ -27,18 +26,15 @@ void _DkGetAvailableUserAddressRange(PAL_PTR* start, PAL_PTR* end) { /* needs to be implemented */ } -PAL_NUM _DkGetProcessId (void) -{ +PAL_NUM _DkGetProcessId(void) { return 0; } -PAL_NUM _DkGetHostId (void) -{ +PAL_NUM _DkGetHostId(void) { return 0; } -int _DkGetCPUInfo (PAL_CPU_INFO * ci) -{ +int _DkGetCPUInfo(PAL_CPU_INFO* ci) { /* needs to be implemented */ return 0; } diff --git a/Pal/src/host/Skeleton/db_misc.c b/Pal/src/host/Skeleton/db_misc.c index f57fca14d2..4834ff8b5c 100644 --- a/Pal/src/host/Skeleton/db_misc.c +++ b/Pal/src/host/Skeleton/db_misc.c @@ -51,8 +51,8 @@ int _DkCpuIdRetrieve(unsigned int leaf, unsigned int subleaf, unsigned int value } int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size) { + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size) { __UNUSED(user_report_data); __UNUSED(user_report_data_size); __UNUSED(target_info); @@ -62,8 +62,8 @@ int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_siz return -PAL_ERROR_NOTIMPLEMENTED; } -int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, - PAL_PTR quote, PAL_NUM* quote_size) { +int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, PAL_PTR quote, + PAL_NUM* quote_size) { __UNUSED(user_report_data); __UNUSED(user_report_data_size); __UNUSED(quote); diff --git a/Pal/src/host/Skeleton/db_object.c b/Pal/src/host/Skeleton/db_object.c index 0383140f89..ab2278f87a 100644 --- a/Pal/src/host/Skeleton/db_object.c +++ b/Pal/src/host/Skeleton/db_object.c @@ -22,7 +22,7 @@ int _DkSynchronizationObjectWait(PAL_HANDLE handle, int64_t timeout_us) { /* Wait for specific events on all handles in the handle array and return multiple events * (including errors) reported by the host. Return 0 on success, PAL error on failure. */ -int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events, - int64_t timeout_us) { +int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, + PAL_FLG* ret_events, int64_t timeout_us) { return -PAL_ERROR_NOTIMPLEMENTED; } diff --git a/Pal/src/host/Skeleton/db_rtld.c b/Pal/src/host/Skeleton/db_rtld.c index b503377ab2..3bf505ce8f 100644 --- a/Pal/src/host/Skeleton/db_rtld.c +++ b/Pal/src/host/Skeleton/db_rtld.c @@ -11,16 +11,16 @@ */ #include -#include -#include #include "api.h" +#include "elf/elf.h" #include "pal.h" #include "pal_debug.h" #include "pal_defs.h" #include "pal_error.h" #include "pal_internal.h" #include "pal_rtld.h" +#include "sysdeps/generic/ldsodefs.h" void _DkDebugAddMap(struct link_map* map) {} diff --git a/Pal/src/pal_internal.h b/Pal/src/pal_internal.h index 7445f17142..bd58783d98 100644 --- a/Pal/src/pal_internal.h +++ b/Pal/src/pal_internal.h @@ -11,12 +11,14 @@ #ifndef PAL_INTERNAL_H #define PAL_INTERNAL_H +#include + +#include "pal.h" #include "pal_defs.h" #include "pal_error.h" -#include "pal.h" #ifndef IN_PAL -# error "pal_internal.h can only be included in PAL" +#error "pal_internal.h can only be included in PAL" #endif /* handle_ops is the operators provided for each handler type. They are @@ -24,11 +26,11 @@ some others in special ways. */ struct handle_ops { /* 'getrealpath' return the real path that represent the handle */ - const char * (*getrealpath) (PAL_HANDLE handle); + const char* (*getrealpath)(PAL_HANDLE handle); /* 'getname' is used by DkStreamGetName. It's different from 'getrealpath' */ - int (*getname) (PAL_HANDLE handle, char * buffer, size_t count); + int (*getname)(PAL_HANDLE handle, char* buffer, size_t count); /* 'open' is used by DkStreamOpen. 'handle' is a preallocated handle, 'type' will be a normalized prefix, 'uri' is the remaining string @@ -36,28 +38,26 @@ struct handle_ops { access, share, create, and options follow the same flags defined for DkStreamOpen in pal.h. */ - int (*open) (PAL_HANDLE * handle, const char * type, const char * uri, - int access, int share, int create, int options); + int (*open)(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share, + int create, int options); /* 'read' and 'write' is used by DkStreamRead and DkStreamWrite, so they have exactly same prototype as them. */ - int64_t (*read) (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buffer); - int64_t (*write) (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buffer); + int64_t (*read)(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer); + int64_t (*write)(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer); /* 'readbyaddr' and 'writebyaddr' are the same as read and write, but with extra field to specify address */ - int64_t (*readbyaddr) (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buffer, char * addr, size_t addrlen); - int64_t (*writebyaddr) (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buffer, const char * addr, size_t addrlen); + int64_t (*readbyaddr)(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer, + char* addr, size_t addrlen); + int64_t (*writebyaddr)(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer, + const char* addr, size_t addrlen); /* 'close' and 'delete' is used by DkObjectClose and DkStreamDelete, 'close' will close the stream, while 'delete' actually destroy the stream, such as deleting a file or shutting down a socket */ - int (*close) (PAL_HANDLE handle); - int (*delete) (PAL_HANDLE handle, int access); + int (*close)(PAL_HANDLE handle); + int (*delete)(PAL_HANDLE handle, int access); /* 'map' and 'unmap' will map or unmap the handle into memory space, * it's not necessary mapped by mmap, so unmap also needs 'handle' @@ -66,32 +66,30 @@ struct handle_ops { * Common PAL code will ensure that *address, offset, and size are * page-aligned. 'address' should not be NULL. */ - int (*map) (PAL_HANDLE handle, void ** address, int prot, uint64_t offset, - uint64_t size); + int (*map)(PAL_HANDLE handle, void** address, int prot, uint64_t offset, uint64_t size); /* 'setlength' is used by DkStreamFlush. It truncate the stream to certain size. */ - int64_t (*setlength) (PAL_HANDLE handle, uint64_t length); + int64_t (*setlength)(PAL_HANDLE handle, uint64_t length); /* 'flush' is used by DkStreamFlush. It syncs the stream to the device */ - int (*flush) (PAL_HANDLE handle); + int (*flush)(PAL_HANDLE handle); /* 'waitforclient' is used by DkStreamWaitforClient. It accepts an connection */ - int (*waitforclient) (PAL_HANDLE server, PAL_HANDLE *client); + int (*waitforclient)(PAL_HANDLE server, PAL_HANDLE* client); /* 'attrquery' is used by DkStreamAttributesQuery. It queries the attributes of a stream */ - int (*attrquery) (const char * type, const char * uri, - PAL_STREAM_ATTR * attr); + int (*attrquery)(const char* type, const char* uri, PAL_STREAM_ATTR* attr); /* 'attrquerybyhdl' is used by DkStreamAttributesQueryByHandle. It queries the attributes of a stream handle */ - int (*attrquerybyhdl) (PAL_HANDLE handle, PAL_STREAM_ATTR * attr); + int (*attrquerybyhdl)(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); /* 'attrsetbyhdl' is used by DkStreamAttributesSetByHandle. It queries the attributes of a stream handle */ - int (*attrsetbyhdl) (PAL_HANDLE handle, PAL_STREAM_ATTR * attr); + int (*attrsetbyhdl)(PAL_HANDLE handle, PAL_STREAM_ATTR* attr); /* 'wait' is used for synchronous wait. * The 'timeout_us' is in microseconds, NO_TIMEOUT means no timeout. @@ -99,17 +97,16 @@ struct handle_ops { * Timeout: -PAL_ERROR_TRYAGAIN * Positive return values are undefined. */ - int (*wait) (PAL_HANDLE handle, int64_t timeout_us); + int (*wait)(PAL_HANDLE handle, int64_t timeout_us); /* 'rename' is used to change name of a stream, or reset its share option */ - int (*rename) (PAL_HANDLE handle, const char * type, const char * uri); + int (*rename)(PAL_HANDLE handle, const char* type, const char* uri); }; extern const struct handle_ops* g_pal_handle_ops[]; -static inline const struct handle_ops* HANDLE_OPS(PAL_HANDLE handle) -{ +static inline const struct handle_ops* HANDLE_OPS(PAL_HANDLE handle) { int _type = PAL_GET_TYPE(handle); if (_type < 0 || _type >= PAL_HANDLE_TYPE_BOUND) return NULL; @@ -119,23 +116,25 @@ static inline const struct handle_ops* HANDLE_OPS(PAL_HANDLE handle) /* We allow dynamic size handle allocation. Here is some macro to help deciding the actual size of the handle */ extern PAL_HANDLE _h; -#define HANDLE_SIZE(type) (sizeof(*_h)) +#define HANDLE_SIZE(type) (sizeof(*_h)) -static inline int handle_size (PAL_HANDLE handle) -{ +static inline int handle_size(PAL_HANDLE handle) { return sizeof(*handle); } #ifndef ENTER_PAL_CALL -# define ENTER_PAL_CALL(name) +#define ENTER_PAL_CALL(name) #endif #ifndef LEAVE_PAL_CALL -# define LEAVE_PAL_CALL() +#define LEAVE_PAL_CALL() #endif #ifndef LEAVE_PAL_CALL_RETURN -# define LEAVE_PAL_CALL_RETURN(retval) do { return (retval); } while (0) +#define LEAVE_PAL_CALL_RETURN(retval) \ + do { \ + return (retval); \ + } while (0) #endif /* failure notify. The rountine is called whenever a PAL call return @@ -144,7 +143,7 @@ static inline int handle_size (PAL_HANDLE handle) PAL call error. If the user does not set up a upcall, the error code will be ignored. Ignoring PAL error code can be a possible optimization for SHIM. */ -void notify_failure (unsigned long error); +void notify_failure(unsigned long error); /* all pal config value */ extern struct pal_internal_state { @@ -152,13 +151,13 @@ extern struct pal_internal_state { PAL_HANDLE parent_process; - const char * manifest; + const char* manifest; PAL_HANDLE manifest_handle; - const char * exec; + const char* exec; PAL_HANDLE exec_handle; - struct config_store * root_config; + struct config_store* root_config; /* May not be the same as page size, see e.g. SYSTEM_INFO::dwAllocationGranularity on Windows. */ @@ -192,85 +191,80 @@ extern PAL_CONTROL g_pal_control; * \param arguments application arguments * \param environments environment variables */ -noreturn void pal_main( - PAL_NUM instance_id, PAL_HANDLE manifest_handle, PAL_HANDLE exec_handle, - PAL_PTR exec_loaded_addr, PAL_HANDLE parent_process, PAL_HANDLE first_thread, - PAL_STR* arguments, PAL_STR* environments); +noreturn void pal_main(PAL_NUM instance_id, PAL_HANDLE manifest_handle, PAL_HANDLE exec_handle, + PAL_PTR exec_loaded_addr, PAL_HANDLE parent_process, PAL_HANDLE first_thread, + PAL_STR* arguments, PAL_STR* environments); /* For initialization */ -unsigned long _DkGetAllocationAlignment (void); +unsigned long _DkGetAllocationAlignment(void); void _DkGetAvailableUserAddressRange(PAL_PTR* start, PAL_PTR* end); -bool _DkCheckMemoryMappable (const void * addr, size_t size); -PAL_NUM _DkGetProcessId (void); -PAL_NUM _DkGetHostId (void); -unsigned long _DkMemoryQuota (void); -unsigned long _DkMemoryAvailableQuota (void); +bool _DkCheckMemoryMappable(const void* addr, size_t size); +PAL_NUM _DkGetProcessId(void); +PAL_NUM _DkGetHostId(void); +unsigned long _DkMemoryQuota(void); +unsigned long _DkMemoryAvailableQuota(void); // Returns 0 on success, negative PAL code on failure -int _DkGetCPUInfo (PAL_CPU_INFO * info); +int _DkGetCPUInfo(PAL_CPU_INFO* info); /* Internal DK calls, in case any of the internal routines needs to use them */ /* DkStream calls */ int _DkStreamOpen(PAL_HANDLE* handle, const char* uri, int access, int share, int create, int options); -int _DkStreamDelete (PAL_HANDLE handle, int access); -int64_t _DkStreamRead (PAL_HANDLE handle, uint64_t offset, uint64_t count, - void * buf, char * addr, int addrlen); -int64_t _DkStreamWrite (PAL_HANDLE handle, uint64_t offset, uint64_t count, - const void * buf, const char * addr, int addrlen); -int _DkStreamAttributesQuery (const char * uri, PAL_STREAM_ATTR * attr); -int _DkStreamAttributesQueryByHandle (PAL_HANDLE hdl, PAL_STREAM_ATTR * attr); -int _DkStreamMap (PAL_HANDLE handle, void ** addr, int prot, uint64_t offset, - uint64_t size); -int _DkStreamUnmap (void * addr, uint64_t size); -int64_t _DkStreamSetLength (PAL_HANDLE handle, uint64_t length); -int _DkStreamFlush (PAL_HANDLE handle); -int _DkStreamGetName (PAL_HANDLE handle, char * buf, int size); -const char * _DkStreamRealpath (PAL_HANDLE hdl); +int _DkStreamDelete(PAL_HANDLE handle, int access); +int64_t _DkStreamRead(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buf, char* addr, + int addrlen); +int64_t _DkStreamWrite(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buf, + const char* addr, int addrlen); +int _DkStreamAttributesQuery(const char* uri, PAL_STREAM_ATTR* attr); +int _DkStreamAttributesQueryByHandle(PAL_HANDLE hdl, PAL_STREAM_ATTR* attr); +int _DkStreamMap(PAL_HANDLE handle, void** addr, int prot, uint64_t offset, uint64_t size); +int _DkStreamUnmap(void* addr, uint64_t size); +int64_t _DkStreamSetLength(PAL_HANDLE handle, uint64_t length); +int _DkStreamFlush(PAL_HANDLE handle); +int _DkStreamGetName(PAL_HANDLE handle, char* buf, int size); +const char* _DkStreamRealpath(PAL_HANDLE hdl); int _DkSendHandle(PAL_HANDLE hdl, PAL_HANDLE cargo); -int _DkReceiveHandle(PAL_HANDLE hdl, PAL_HANDLE * cargo); +int _DkReceiveHandle(PAL_HANDLE hdl, PAL_HANDLE* cargo); /* DkProcess and DkThread calls */ -int _DkThreadCreate (PAL_HANDLE * handle, int (*callback) (void *), - const void * param); +int _DkThreadCreate(PAL_HANDLE* handle, int (*callback)(void*), const void* param); noreturn void _DkThreadExit(int* clear_child_tid); int _DkThreadDelayExecution(uint64_t* duration_us); -void _DkThreadYieldExecution (void); -int _DkThreadResume (PAL_HANDLE threadHandle); -int _DkProcessCreate (PAL_HANDLE * handle, const char * uri, - const char ** args); -noreturn void _DkProcessExit (int exitCode); +void _DkThreadYieldExecution(void); +int _DkThreadResume(PAL_HANDLE threadHandle); +int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args); +noreturn void _DkProcessExit(int exitCode); /* DkMutex calls */ -int _DkMutexCreate (PAL_HANDLE * handle, int initialCount); +int _DkMutexCreate(PAL_HANDLE* handle, int initialCount); int _DkMutexAcquire(PAL_HANDLE sem); int _DkMutexAcquireTimeout(PAL_HANDLE sem, int64_t timeout_us); -void _DkMutexRelease (PAL_HANDLE sem); -int _DkMutexGetCurrentCount (PAL_HANDLE sem); +void _DkMutexRelease(PAL_HANDLE sem); +int _DkMutexGetCurrentCount(PAL_HANDLE sem); /* DkEvent calls */ -int _DkEventCreate (PAL_HANDLE * event, bool initialState, - bool isnotification); -int _DkEventSet (PAL_HANDLE event, int wakeup); +int _DkEventCreate(PAL_HANDLE* event, bool initialState, bool isnotification); +int _DkEventSet(PAL_HANDLE event, int wakeup); int _DkEventWaitTimeout(PAL_HANDLE event, int64_t timeout_us); int _DkEventWait(PAL_HANDLE event); -int _DkEventClear (PAL_HANDLE event); +int _DkEventClear(PAL_HANDLE event); /* DkVirtualMemory calls */ -int _DkVirtualMemoryAlloc (void ** paddr, uint64_t size, int alloc_type, int prot); -int _DkVirtualMemoryFree (void * addr, uint64_t size); -int _DkVirtualMemoryProtect (void * addr, uint64_t size, int prot); +int _DkVirtualMemoryAlloc(void** paddr, uint64_t size, int alloc_type, int prot); +int _DkVirtualMemoryFree(void* addr, uint64_t size); +int _DkVirtualMemoryProtect(void* addr, uint64_t size, int prot); /* DkObject calls */ -int _DkObjectReference (PAL_HANDLE objectHandle); -int _DkObjectClose (PAL_HANDLE objectHandle); +int _DkObjectReference(PAL_HANDLE objectHandle); +int _DkObjectClose(PAL_HANDLE objectHandle); int _DkSynchronizationObjectWait(PAL_HANDLE handle, int64_t timeout_us); -int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events, - int64_t timeout_us); +int _DkStreamsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, + PAL_FLG* ret_events, int64_t timeout_us); /* DkException calls & structures */ -PAL_EVENT_HANDLER _DkGetExceptionHandler (PAL_NUM event_num); -void _DkRaiseFailure (int error); -void _DkExceptionReturn (void * event); +PAL_EVENT_HANDLER _DkGetExceptionHandler(PAL_NUM event_num); +void _DkRaiseFailure(int error); +void _DkExceptionReturn(void* event); /* other DK calls */ void _DkInternalLock(PAL_LOCK* mut); @@ -282,23 +276,23 @@ int _DkSystemTimeQuery(uint64_t* out_usec); * Cryptographically secure random. * 0 on success, negative on failure. */ -size_t _DkRandomBitsRead (void * buffer, size_t size); -int _DkSegmentRegisterSet (int reg, const void * addr); -int _DkSegmentRegisterGet (int reg, void ** addr); -int _DkInstructionCacheFlush (const void * addr, int size); -int _DkCpuIdRetrieve (unsigned int leaf, unsigned int subleaf, unsigned int values[4]); +size_t _DkRandomBitsRead(void* buffer, size_t size); +int _DkSegmentRegisterSet(int reg, const void* addr); +int _DkSegmentRegisterGet(int reg, void** addr); +int _DkInstructionCacheFlush(const void* addr, int size); +int _DkCpuIdRetrieve(unsigned int leaf, unsigned int subleaf, unsigned int values[4]); int _DkAttestationReport(PAL_PTR user_report_data, PAL_NUM* user_report_data_size, - PAL_PTR target_info, PAL_NUM* target_info_size, - PAL_PTR report, PAL_NUM* report_size); -int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, - PAL_PTR quote, PAL_NUM* quote_size); + PAL_PTR target_info, PAL_NUM* target_info_size, PAL_PTR report, + PAL_NUM* report_size); +int _DkAttestationQuote(PAL_PTR user_report_data, PAL_NUM user_report_data_size, PAL_PTR quote, + PAL_NUM* quote_size); int _DkSetProtectedFilesKey(PAL_PTR pf_key_hex); -#define INIT_FAIL(exitcode, reason) \ - do { \ - printf("PAL failed at " __FILE__ ":%s:%u (exitcode = %u, reason=%s)\n", \ - __FUNCTION__, (unsigned int)__LINE__, (unsigned int)(exitcode), reason); \ - _DkProcessExit(exitcode); \ +#define INIT_FAIL(exitcode, reason) \ + do { \ + printf("PAL failed at " __FILE__ ":%s:%u (exitcode = %u, reason=%s)\n", __FUNCTION__, \ + (unsigned int)__LINE__, (unsigned int)(exitcode), reason); \ + _DkProcessExit(exitcode); \ } while (0) /* Loading ELF binaries */ @@ -306,24 +300,24 @@ enum object_type { OBJECT_RTLD, OBJECT_EXEC, OBJECT_PRELOAD, OBJECT_EXTERNAL }; bool has_elf_magic(const void* header, size_t len); bool is_elf_object(PAL_HANDLE handle); -int load_elf_object (const char * uri, enum object_type type); -int load_elf_object_by_handle (PAL_HANDLE handle, enum object_type type); -int add_elf_object(void * addr, PAL_HANDLE handle, int type); +int load_elf_object(const char* uri, enum object_type type); +int load_elf_object_by_handle(PAL_HANDLE handle, enum object_type type); +int add_elf_object(void* addr, PAL_HANDLE handle, int type); -void init_slab_mgr (int alignment); -void * malloc (size_t size); -void * malloc_copy(const void * mem, size_t size); -void * calloc (size_t nmem, size_t size); -char * strdup(const char *source); -void free (void * mem); +void init_slab_mgr(int alignment); +void* malloc(size_t size); +void* malloc_copy(const void* mem, size_t size); +void* calloc(size_t nmem, size_t size); +char* strdup(const char* source); +void free(void* mem); #ifdef __GNUC__ -# define __attribute_hidden __attribute__ ((visibility ("hidden"))) -# define __attribute_always_inline __attribute__((always_inline)) -# define __attribute_unused __attribute__((unused)) -# define __attribute_noinline __attribute__((noinline)) +#define __attribute_hidden __attribute__((visibility("hidden"))) +#define __attribute_always_inline __attribute__((always_inline)) +#define __attribute_unused __attribute__((unused)) +#define __attribute_noinline __attribute__((noinline)) #else -# error Unsupported compiler +#error Unsupported compiler #endif #define ALIAS_STR(name) #name @@ -331,13 +325,12 @@ void free (void * mem); # define EXTERN_ALIAS(name) \ extern __typeof(name) pal_##name __attribute ((alias (ALIAS_STR(name)))) #else -# define EXTERN_ALIAS(name) +#define EXTERN_ALIAS(name) #endif -void _DkPrintConsole (const void * buf, int size); -int printf (const char *fmt, ...) __attribute__((format (printf, 1, 2))); -#include -int vprintf(const char * fmt, va_list ap) __attribute__((format (printf, 1, 0))); +void _DkPrintConsole(const void* buf, int size); +int printf(const char* fmt, ...) __attribute__((format(printf, 1, 2))); +int vprintf(const char* fmt, va_list ap) __attribute__((format(printf, 1, 0))); /* errval is negative value, see pal_strerror */ static inline void print_error(const char* errstring, int errval) { diff --git a/Pal/src/pal_rtld.h b/Pal/src/pal_rtld.h index a5e1146d9c..8421c7cee0 100644 --- a/Pal/src/pal_rtld.h +++ b/Pal/src/pal_rtld.h @@ -8,15 +8,15 @@ #ifndef PAL_RTLD_H #define PAL_RTLD_H -#include "pal_internal.h" -#include "pal_error.h" #include "api.h" - -#include -#include +#include "elf/elf.h" +#include "host_endian.h" +#include "pal_error.h" +#include "pal_internal.h" +#include "sysdeps/generic/ldsodefs.h" #ifndef DT_THISPROCNUM -# define DT_THISPROCNUM 0 +#define DT_THISPROCNUM 0 #endif typedef ElfW(Word) Elf_Symndx; @@ -36,22 +36,23 @@ struct link_map { /* These first few members are part of the protocol with the debugger. This is the same format used in SVR4. */ - ElfW(Addr) l_addr; /* Base address shared object is loaded at. */ - const char * l_name; /* Absolute file name object was found in. */ - ElfW(Dyn) * l_real_ld; /* Dynamic section of the shared object. */ - struct link_map * l_next, * l_prev; /* Chain of loaded objects. */ + ElfW(Addr) l_addr; /* Base address shared object is loaded at. */ + const char* l_name; /* Absolute file name object was found in. */ + ElfW(Dyn)* l_real_ld; /* Dynamic section of the shared object. */ + struct link_map* l_next; /* Chain of loaded objects. */ + struct link_map* l_prev; /* All following members are internal to the dynamic linker. They may change without notice. */ enum object_type l_type; - ElfW(Dyn) * l_ld; - ElfW(Dyn) * l_info[DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM - + DT_EXTRANUM + DT_VALNUM + DT_ADDRNUM]; - const ElfW(Phdr) * l_phdr; /* Pointer to program header table in core. */ - ElfW(Addr) l_entry; /* Entry point location. */ - ElfW(Half) l_phnum; /* Number of program header entries. */ - ElfW(Half) l_ldnum; /* Number of dynamic segment entries. */ + ElfW(Dyn)* l_ld; + ElfW(Dyn)* l_info[DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM + DT_EXTRANUM + DT_VALNUM + + DT_ADDRNUM]; + const ElfW(Phdr)* l_phdr; /* Pointer to program header table in core. */ + ElfW(Addr) l_entry; /* Entry point location. */ + ElfW(Half) l_phnum; /* Number of program header entries. */ + ElfW(Half) l_ldnum; /* Number of dynamic segment entries. */ /* Start and finish of memory map for this object. l_map_start need not be the same as l_addr. */ @@ -65,25 +66,26 @@ struct link_map { Elf_Symndx l_nbuckets; /* For DT_HASH */ - const Elf_Symndx *l_buckets; - const Elf_Symndx *l_chain; + const Elf_Symndx* l_buckets; + const Elf_Symndx* l_chain; /* For DT_GNU_HASH */ Elf32_Word l_gnu_bitmask_idxbits; Elf32_Word l_gnu_shift; - const ElfW(Addr) * l_gnu_bitmask; - const Elf32_Word * l_gnu_buckets; - const Elf32_Word * l_gnu_chain_zero; + const ElfW(Addr)* l_gnu_bitmask; + const Elf32_Word* l_gnu_buckets; + const Elf32_Word* l_gnu_chain_zero; }; struct link_gdb_map { /* These first few members are part of the protocol with the debugger. This is the same format used in SVR4. */ - ElfW(Addr) l_addr; /* Base address shared object is loaded at. */ - const char * l_name; /* Absolute file name object was found in. */ - ElfW(Dyn) * l_ld; /* Dynamic section of the shared object. */ - struct link_map * l_next, * l_prev; /* Chain of loaded objects. */ + ElfW(Addr) l_addr; /* Base address shared object is loaded at. */ + const char* l_name; /* Absolute file name object was found in. */ + ElfW(Dyn)* l_ld; /* Dynamic section of the shared object. */ + struct link_map* l_next; /* Chain of loaded objects. */ + struct link_map* l_prev; }; extern struct link_map* g_loaded_maps; @@ -96,7 +98,7 @@ extern struct link_map* g_exec_map; This results in a more efficient address space usage. Defaults to zero for almost all systems. */ #ifndef MAP_BASE_ADDR -# define MAP_BASE_ADDR(l) 0 +#define MAP_BASE_ADDR(l) 0 #endif /* Handle situations where we have a preferred location in memory for @@ -106,61 +108,55 @@ ELF_PREFERRED_ADDRESS_DATA; #endif #ifndef ELF_PREFERRED_ADDRESS -# define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref) +#define ELF_PREFERRED_ADDRESS(loader, maplength, mapstartpref) (mapstartpref) #endif #ifndef ELF_FIXED_ADDRESS -# define ELF_FIXED_ADDRESS(loader, mapstart) ((void)0) +#define ELF_FIXED_ADDRESS(loader, mapstart) ((void)0) #endif #ifndef VERSYMIDX -# define VERSYMIDX(sym) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX(sym)) +#define VERSYMIDX(sym) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGIDX(sym)) #endif #ifndef VALIDX -# define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM \ - + DT_EXTRANUM + DT_VALTAGIDX(tag)) +#define VALIDX(tag) (DT_NUM + DT_THISPROCNUM + DT_VERSIONTAGNUM + DT_EXTRANUM + DT_VALTAGIDX(tag)) #endif -#include #if __BYTE_ORDER == __BIG_ENDIAN -# define byteorder ELFDATA2MSB +#define byteorder ELFDATA2MSB #elif __BYTE_ORDER == __LITTLE_ENDIAN -# define byteorder ELFDATA2LSB +#define byteorder ELFDATA2LSB #else -# error "Unknown __BYTE_ORDER " __BYTE_ORDER -# define byteorder ELFDATANONE +#error "Unknown __BYTE_ORDER " __BYTE_ORDER +#define byteorder ELFDATANONE #endif #if __WORDSIZE == 32 -# define FILEBUF_SIZE 512 +#define FILEBUF_SIZE 512 #else -# define FILEBUF_SIZE 832 +#define FILEBUF_SIZE 832 #endif -struct link_map * -new_elf_object (const char * realname, enum object_type type); +struct link_map* new_elf_object(const char* realname, enum object_type type); void free_elf_object(struct link_map* map); void setup_elf_hash(struct link_map* map); -static inline uint_fast32_t elf_fast_hash (const char *s) -{ - uint_fast32_t h = 5381; - for (unsigned char c = *s; c != '\0'; c = *++s) - h = h * 33 + c; - return h & 0xffffffff; +static inline uint_fast32_t elf_fast_hash(const char* s) { + uint_fast32_t h = 5381; + for (unsigned char c = *s; c != '\0'; c = *++s) + h = h * 33 + c; + return h & 0xffffffff; } -unsigned long int elf_hash (const char *name_arg); +unsigned long int elf_hash(const char* name_arg); -ElfW(Sym) * -do_lookup_map (ElfW(Sym) * ref, const char * undef_name, - const uint_fast32_t hash, unsigned long int elf_hash, - const struct link_map * map); +ElfW(Sym)* do_lookup_map(ElfW(Sym)* ref, const char* undef_name, const uint_fast32_t hash, + unsigned long int elf_hash, const struct link_map* map); /* for GDB debugging */ -void _DkDebugAddMap (struct link_map * map); -void _DkDebugDelMap (struct link_map * map); +void _DkDebugAddMap(struct link_map* map); +void _DkDebugDelMap(struct link_map* map); noreturn void start_execution(const char** arguments, const char** environs); diff --git a/Pal/src/printf.c b/Pal/src/printf.c index 7fe086c02b..d26ef71675 100644 --- a/Pal/src/printf.c +++ b/Pal/src/printf.c @@ -1,8 +1,8 @@ /* SPDX-License-Identifier: LGPL-3.0-or-later */ /* Copyright (C) 2014 Stony Brook University */ -#include "pal_internal.h" #include "api.h" +#include "pal_internal.h" #ifndef NO_INTERNAL_PRINTF @@ -12,17 +12,15 @@ // and prevent interrupts from causing context switches // in the middle of a console output line and such. -#define PRINTBUF_SIZE 256 +#define PRINTBUF_SIZE 256 struct printbuf { - int idx; // current buffer index - int cnt; // total bytes printed so far + int idx; // current buffer index + int cnt; // total bytes printed so far char buf[PRINTBUF_SIZE]; }; -static int -fputch(void * f, int ch, struct printbuf * b) -{ +static int fputch(void* f, int ch, struct printbuf* b) { __UNUSED(f); b->buf[b->idx++] = ch; @@ -34,22 +32,18 @@ fputch(void * f, int ch, struct printbuf * b) return 0; } -int -vprintf(const char * fmt, va_list ap) -{ +int vprintf(const char* fmt, va_list ap) { struct printbuf b; b.idx = 0; b.cnt = 0; - vfprintfmt((void *) &fputch, NULL, &b, fmt, ap); + vfprintfmt((void*)&fputch, NULL, &b, fmt, ap); _DkPrintConsole(b.buf, b.idx); return b.cnt; } -int -printf(const char * fmt, ...) -{ +int printf(const char* fmt, ...) { va_list ap; int cnt; diff --git a/Pal/src/slab.c b/Pal/src/slab.c index b1bf4b5eff..a88885279b 100644 --- a/Pal/src/slab.c +++ b/Pal/src/slab.c @@ -8,11 +8,10 @@ */ #include "api.h" -#include "pal_internal.h" - #include "pal_debug.h" #include "pal_defs.h" #include "pal_error.h" +#include "pal_internal.h" static int g_slab_alignment; static PAL_LOCK g_slab_mgr_lock = LOCK_INIT;