소스 검색

Reformat repository to our clang-format rules (2nd iteration)

Michał Kowalczyk 4 년 전
부모
커밋
f1c334357c
59개의 변경된 파일2160개의 추가작업 그리고 2550개의 파일을 삭제
  1. 247 265
      LibOS/shim/include/shim_checkpoint.h
  2. 213 250
      LibOS/shim/include/shim_fs.h
  3. 2 1
      LibOS/shim/src/bookkeep/shim_handle.c
  4. 4 2
      LibOS/shim/src/fs/chroot/fs.c
  5. 10 9
      LibOS/shim/src/fs/eventfd/fs.c
  6. 45 60
      LibOS/shim/src/fs/shim_dcache.c
  7. 130 140
      LibOS/shim/src/fs/shim_fs.c
  8. 2 1
      LibOS/shim/src/fs/shim_namei.c
  9. 155 168
      LibOS/shim/src/ipc/shim_ipc_helper.c
  10. 152 201
      LibOS/shim/src/ipc/shim_ipc_pid.c
  11. 36 39
      LibOS/shim/src/shim_async.c
  12. 6 3
      LibOS/shim/src/shim_parser.c
  13. 14 16
      LibOS/shim/src/sys/shim_access.c
  14. 54 71
      LibOS/shim/src/sys/shim_brk.c
  15. 15 18
      LibOS/shim/src/sys/shim_eventfd.c
  16. 100 118
      LibOS/shim/src/sys/shim_exec.c
  17. 20 26
      LibOS/shim/src/sys/shim_fork.c
  18. 107 137
      LibOS/shim/src/sys/shim_fs.c
  19. 35 36
      LibOS/shim/src/sys/shim_poll.c
  20. 75 103
      LibOS/shim/src/sys/shim_sigaction.c
  21. 12 17
      LibOS/shim/src/sys/shim_sleep.c
  22. 36 48
      LibOS/shim/src/sys/shim_stat.c
  23. 3 3
      LibOS/shim/test/regression/abort_multithread.c
  24. 0 2
      LibOS/shim/test/regression/eventfd.c
  25. 2 2
      LibOS/shim/test/regression/exit_group.c
  26. 8 6
      LibOS/shim/test/regression/fdleak.c
  27. 9 7
      LibOS/shim/test/regression/poll.c
  28. 10 8
      LibOS/shim/test/regression/ppoll.c
  29. 3 3
      LibOS/shim/test/regression/pselect.c
  30. 4 4
      LibOS/shim/test/regression/sched.c
  31. 3 3
      LibOS/shim/test/regression/select.c
  32. 3 5
      LibOS/shim/test/regression/sigprocmask.c
  33. 4 4
      LibOS/shim/test/regression/spinlock.c
  34. 4 2
      Pal/lib/graphene/config.c
  35. 23 19
      Pal/lib/network/inet_pton.c
  36. 0 1
      Pal/lib/string/strendswith.c
  37. 2 2
      Pal/regression/Attestation.c
  38. 6 3
      Pal/regression/Pipe.c
  39. 15 21
      Pal/src/db_object.c
  40. 28 30
      Pal/src/host/Linux-SGX/db_eventfd.c
  41. 17 16
      Pal/src/host/Linux-SGX/db_object.c
  42. 70 59
      Pal/src/host/Linux-SGX/enclave_platform.c
  43. 53 52
      Pal/src/host/Linux-SGX/sgx_arch.h
  44. 9 10
      Pal/src/host/Linux-SGX/sgx_attest.h
  45. 3 3
      Pal/src/host/Linux-SGX/sgx_enclave.h
  46. 30 32
      Pal/src/host/Linux/db_eventfd.c
  47. 25 35
      Pal/src/host/Linux/db_misc.c
  48. 19 20
      Pal/src/host/Linux/db_object.c
  49. 68 93
      Pal/src/host/Skeleton/db_devices.c
  50. 13 14
      Pal/src/host/Skeleton/db_eventfd.c
  51. 14 22
      Pal/src/host/Skeleton/db_events.c
  52. 59 90
      Pal/src/host/Skeleton/db_files.c
  53. 11 20
      Pal/src/host/Skeleton/db_misc.c
  54. 9 17
      Pal/src/host/Skeleton/db_mutex.c
  55. 33 49
      Pal/src/host/Skeleton/db_pipes.c
  56. 17 25
      Pal/src/host/Skeleton/db_process.c
  57. 62 85
      Pal/src/host/Skeleton/db_sockets.c
  58. 8 11
      Pal/src/host/Skeleton/pal_host.h
  59. 43 43
      Pal/src/pal_error.c

+ 247 - 265
LibOS/shim/include/shim_checkpoint.h

@@ -23,20 +23,19 @@
 #ifndef _SHIM_CHECKPOINT_H_
 #define _SHIM_CHECKPOINT_H_
 
+#include <stdarg.h>
+
+#include <pal.h>
 #include <shim_defs.h>
 #include <shim_ipc.h>
 #include <shim_profile.h>
 
-#include <pal.h>
-
-#include <stdarg.h>
-
 #ifdef __i386__
-# error "x86-32 support is heavily broken."
+#error "x86-32 support is heavily broken."
 #endif
 
 typedef uint64_t ptr_t;
-# define hashfunc hash64
+#define hashfunc hash64
 
 #define __attribute_migratable __attribute__((section(".migratable")))
 
@@ -75,66 +74,62 @@ extern char __migratable_end;
 
 */
 
-struct shim_cp_entry
-{
+struct shim_cp_entry {
     ptr_t cp_type;  /* entry type */
-    union
-    {
-        ptr_t cp_val;   /* integer value */
+    union {
+        ptr_t cp_val;  /* integer value */
         /* originally there is a pointer, now we don't need them */
     } cp_un;
 };
 
 struct shim_mem_entry {
-    struct shim_mem_entry * prev;
-    void * addr;
+    struct shim_mem_entry* prev;
+    void* addr;
     size_t size;
-    void ** paddr;
+    void** paddr;
     int prot;
-    void * data;
+    void* data;
 };
 
 struct shim_palhdl_entry {
-    struct shim_palhdl_entry * prev;
+    struct shim_palhdl_entry* prev;
     PAL_HANDLE handle;
-    struct shim_qstr * uri;
-    PAL_HANDLE * phandle;
+    struct shim_qstr* uri;
+    PAL_HANDLE* phandle;
 };
 
 struct shim_cp_store {
     /* checkpoint data mapping */
-    void * cp_map;
-    struct shim_handle * cp_file;
+    void* cp_map;
+    struct shim_handle* cp_file;
 
     /* allocation method for check point area */
-    void * (*alloc) (struct shim_cp_store *, void *, size_t);
+    void* (*alloc)(struct shim_cp_store*, void*, size_t);
 
     /* check point area */
     ptr_t base, offset, bound;
 
     /* entries of out-of-band data */
-    struct shim_mem_entry * last_mem_entry;
+    struct shim_mem_entry* last_mem_entry;
     int mem_nentries;
     int mem_size;
 
     /* entries of pal handles to send */
-    struct shim_palhdl_entry * last_palhdl_entry;
+    struct shim_palhdl_entry* last_palhdl_entry;
     int palhdl_nentries;
 };
 
-#define CP_FUNC_ARGS                                    \
-    struct shim_cp_store * store, void * obj, size_t size, void ** objp
+#define CP_FUNC_ARGS struct shim_cp_store* store, void* obj, size_t size, void** objp
 
-#define RS_FUNC_ARGS                                    \
-    struct shim_cp_entry * entry, ptr_t base, ptr_t * offset, long rebase
+#define RS_FUNC_ARGS struct shim_cp_entry* entry, ptr_t base, ptr_t* offset, long rebase
 
-#define DEFINE_CP_FUNC(name) int cp_##name (CP_FUNC_ARGS)
-#define DEFINE_RS_FUNC(name) int rs_##name (RS_FUNC_ARGS)
+#define DEFINE_CP_FUNC(name) int cp_##name(CP_FUNC_ARGS)
+#define DEFINE_RS_FUNC(name) int rs_##name(RS_FUNC_ARGS)
 
-typedef int (*cp_func) (CP_FUNC_ARGS);
-typedef int (*rs_func) (RS_FUNC_ARGS);
+typedef int (*cp_func)(CP_FUNC_ARGS);
+typedef int (*rs_func)(RS_FUNC_ARGS);
 
-extern const char *  __cp_name;
+extern const char* __cp_name;
 extern const cp_func __cp_func;
 extern const rs_func __rs_func;
 
@@ -147,252 +142,251 @@ enum {
     CP_FUNC_BASE,
 };
 
-#define CP_FUNC_INDEX(name)                                         \
-    ({ extern const cp_func cp_func_##name; &cp_func_##name - &__cp_func; })
-
-#define CP_FUNC(name)   CP_FUNC_BASE + CP_FUNC_INDEX(name)
-#define CP_FUNC_NAME(type)      (&__cp_name)[(type) - CP_FUNC_BASE]
-
-#define __ADD_CP_OFFSET(size)                                       \
-    ({                                                              \
-        ptr_t _off = store->offset;                                 \
-        if (store->offset + (size) > store->bound) {                \
-            ptr_t new_bound = store->bound * 2;                     \
-                                                                    \
-            while (store->offset + (size) > new_bound)              \
-                new_bound *= 2;                                     \
-                                                                    \
-            void * buf = store->alloc(store,                        \
-                            (void *) store->base + store->bound,    \
-                            new_bound - store->bound);              \
-            if (!buf)                                               \
-                return -ENOMEM;                                     \
-                                                                    \
-            store->bound = new_bound;                               \
-        }                                                           \
-        store->offset += (size);                                    \
-    _off;  })
-
-#define ADD_CP_ENTRY(type, value)                                   \
-    ({                                                              \
-        struct shim_cp_entry * tmp =                                \
-                (void *) base +                                     \
-                __ADD_CP_OFFSET(sizeof(struct shim_cp_entry));      \
-        tmp->cp_type = CP_##type;                                   \
-        tmp->cp_un.cp_val = (ptr_t) (value);                        \
-        if (DEBUG_CHECKPOINT)                                       \
-            debug("ADD CP_" #type "(0x%08lx) >%ld\n", tmp->cp_un.cp_val, \
-                  store->offset);                                   \
-    tmp; })
-
-#define ADD_CP_OFFSET(size)                                         \
-    ({                                                              \
-        size_t _size = ALIGN_UP(size, sizeof(void*));               \
-        struct shim_cp_entry * oob =                                \
-                (void *) base +                                     \
-                __ADD_CP_OFFSET(sizeof(struct shim_cp_entry));      \
-        oob->cp_type = CP_OOB;                                      \
-        oob->cp_un.cp_val = (ptr_t) _size;                          \
-        ptr_t _off = (ptr_t) __ADD_CP_OFFSET(_size);                \
-        if (DEBUG_CHECKPOINT)                                       \
-            debug("ADD OFFSET(%lu) >%ld\n", (size), store->offset); \
-    _off; })
-
-#define ADD_CP_FUNC_ENTRY(value)                                    \
-    ({                                                              \
-        struct shim_cp_entry * tmp =                                \
-                (void *) base +                                     \
-                __ADD_CP_OFFSET(sizeof(struct shim_cp_entry));      \
-        tmp->cp_type = CP_FUNC_TYPE;                                \
-        tmp->cp_un.cp_val = (ptr_t) (value);                        \
-        if (DEBUG_CHECKPOINT)                                       \
-            debug("ADD %s(0x%08lx) >%ld\n", CP_FUNC_NAME, (value),  \
-                  store->offset);                                   \
-    tmp; })
-
-#define NEXT_CP_ENTRY()                                             \
-    ({  struct shim_cp_entry * tmp;                                 \
-        while (1) {                                                 \
-            tmp = (void *) base + *offset;                          \
-            if (tmp->cp_type == CP_NULL) {                          \
-                tmp = NULL;                                         \
-                break;                                              \
-            }                                                       \
-            *offset += sizeof(struct shim_cp_entry);                \
-            if (tmp->cp_type == CP_OOB)                             \
-                *offset += tmp->cp_un.cp_val;                       \
-            else                                                    \
-                break;                                              \
-        }                                                           \
-    tmp; })
-
-#define GET_CP_ENTRY(type)                                          \
-    ({  struct shim_cp_entry * tmp = NEXT_CP_ENTRY();               \
-                                                                    \
-        while (tmp->cp_type != CP_##type)                           \
-            tmp = NEXT_CP_ENTRY();                                  \
-                                                                    \
-        /* debug("GET CP_" #type "(%p)\n",tmp->cp_un.cp_val); */    \
-    tmp->cp_un.cp_val; })
-
-#define GET_CP_FUNC_ENTRY()                                         \
-    ({  /* debug("GET CP_FUNC_%s(%p) :%d\n", CP_FUNC_NAME,          \
-                 entry->cp_un.cp_val); */                           \
-    entry->cp_un.cp_val; })
-
-#define BEGIN_CP_FUNC(name)                                         \
-    const char * cp_name_##name                                     \
-            __attribute__((section(".cp_name." #name))) = #name;    \
-    extern DEFINE_CP_FUNC(name);                                    \
-    extern DEFINE_RS_FUNC(name);                                    \
-    const cp_func cp_func_##name                                    \
-            __attribute__((section(".cp_func." #name))) = &cp_##name; \
-    const rs_func rs_func_##name                                    \
-            __attribute__((section(".rs_func." #name))) = &rs_##name; \
-                                                                    \
-    DEFINE_PROFILE_INTERVAL(cp_##name, checkpoint_func);            \
-    DEFINE_PROFILE_INTERVAL(rs_##name, resume_func);                \
-                                                                    \
-    DEFINE_CP_FUNC(name)                                            \
-    {                                                               \
-        int CP_FUNC_TYPE __attribute__((unused)) = CP_FUNC(name);   \
-        const char * CP_FUNC_NAME __attribute__((unused)) = #name;  \
-        ptr_t base __attribute__((unused)) = store->base;           \
-        BEGIN_PROFILE_INTERVAL();                                   \
+#define CP_FUNC_INDEX(name)                  \
+    ({                                       \
+        extern const cp_func cp_func_##name; \
+        &cp_func_##name - &__cp_func;        \
+    })
+
+#define CP_FUNC(name)      (CP_FUNC_BASE + CP_FUNC_INDEX(name))
+#define CP_FUNC_NAME(type) ((&__cp_name)[(type) - CP_FUNC_BASE])
+
+#define __ADD_CP_OFFSET(size)                                                                     \
+    ({                                                                                            \
+        ptr_t _off = store->offset;                                                               \
+        if (store->offset + (size) > store->bound) {                                              \
+            ptr_t new_bound = store->bound * 2;                                                   \
+                                                                                                  \
+            while (store->offset + (size) > new_bound)                                            \
+                new_bound *= 2;                                                                   \
+                                                                                                  \
+            void* buf =                                                                           \
+                store->alloc(store, (void*)store->base + store->bound, new_bound - store->bound); \
+            if (!buf)                                                                             \
+                return -ENOMEM;                                                                   \
+                                                                                                  \
+            store->bound = new_bound;                                                             \
+        }                                                                                         \
+        store->offset += (size);                                                                  \
+        _off;                                                                                     \
+    })
+
+#define ADD_CP_ENTRY(type, value)                                                                \
+    ({                                                                                           \
+        struct shim_cp_entry* tmp = (void*)base + __ADD_CP_OFFSET(sizeof(struct shim_cp_entry)); \
+        tmp->cp_type              = CP_##type;                                                   \
+        tmp->cp_un.cp_val         = (ptr_t)(value);                                              \
+        if (DEBUG_CHECKPOINT)                                                                    \
+            debug("ADD CP_" #type "(0x%08lx) >%ld\n", tmp->cp_un.cp_val, store->offset);         \
+        tmp;                                                                                     \
+    })
+
+#define ADD_CP_OFFSET(size)                                                                      \
+    ({                                                                                           \
+        size_t _size              = ALIGN_UP(size, sizeof(void*));                               \
+        struct shim_cp_entry* oob = (void*)base + __ADD_CP_OFFSET(sizeof(struct shim_cp_entry)); \
+        oob->cp_type              = CP_OOB;                                                      \
+        oob->cp_un.cp_val         = (ptr_t)_size;                                                \
+        ptr_t _off                = (ptr_t)__ADD_CP_OFFSET(_size);                               \
+        if (DEBUG_CHECKPOINT)                                                                    \
+            debug("ADD OFFSET(%lu) >%ld\n", size, store->offset);                                \
+        _off;                                                                                    \
+    })
+
+#define ADD_CP_FUNC_ENTRY(value)                                                                 \
+    ({                                                                                           \
+        struct shim_cp_entry* tmp = (void*)base + __ADD_CP_OFFSET(sizeof(struct shim_cp_entry)); \
+        tmp->cp_type              = CP_FUNC_TYPE;                                                \
+        tmp->cp_un.cp_val         = (ptr_t)(value);                                              \
+        if (DEBUG_CHECKPOINT)                                                                    \
+            debug("ADD %s(0x%08lx) >%ld\n", CP_FUNC_NAME, value, store->offset);                 \
+        tmp;                                                                                     \
+    })
+
+#define NEXT_CP_ENTRY()                              \
+    ({                                               \
+        struct shim_cp_entry* tmp;                   \
+        while (1) {                                  \
+            tmp = (void*)base + *offset;             \
+            if (tmp->cp_type == CP_NULL) {           \
+                tmp = NULL;                          \
+                break;                               \
+            }                                        \
+            *offset += sizeof(struct shim_cp_entry); \
+            if (tmp->cp_type == CP_OOB)              \
+                *offset += tmp->cp_un.cp_val;        \
+            else                                     \
+                break;                               \
+        }                                            \
+        tmp;                                         \
+    })
+
+#define GET_CP_ENTRY(type)                                       \
+    ({                                                           \
+        struct shim_cp_entry* tmp = NEXT_CP_ENTRY();             \
+                                                                 \
+        while (tmp->cp_type != CP_##type)                        \
+            tmp = NEXT_CP_ENTRY();                               \
+                                                                 \
+        /* debug("GET CP_" #type "(%p)\n",tmp->cp_un.cp_val); */ \
+        tmp->cp_un.cp_val;                                       \
+    })
+
+#define GET_CP_FUNC_ENTRY()                                                         \
+    ({                                                                              \
+        /* debug("GET CP_FUNC_%s(%p) :%d\n", CP_FUNC_NAME, entry->cp_un.cp_val); */ \
+        entry->cp_un.cp_val;                                                        \
+    })
+
+#define BEGIN_CP_FUNC(name)                                                                \
+    const char* cp_name_##name __attribute__((section(".cp_name." #name))) = #name;        \
+    extern DEFINE_CP_FUNC(name);                                                           \
+    extern DEFINE_RS_FUNC(name);                                                           \
+    const cp_func cp_func_##name __attribute__((section(".cp_func." #name))) = &cp_##name; \
+    const rs_func rs_func_##name __attribute__((section(".rs_func." #name))) = &rs_##name; \
+                                                                                           \
+    DEFINE_PROFILE_INTERVAL(cp_##name, checkpoint_func);                                   \
+    DEFINE_PROFILE_INTERVAL(rs_##name, resume_func);                                       \
+                                                                                           \
+    DEFINE_CP_FUNC(name) {                                                                 \
+        int CP_FUNC_TYPE __attribute__((unused))         = CP_FUNC(name);                  \
+        const char* CP_FUNC_NAME __attribute__((unused)) = #name;                          \
+        ptr_t base __attribute__((unused))               = store->base;                    \
+        BEGIN_PROFILE_INTERVAL();                                                          \
         ASSIGN_PROFILE_INTERVAL(cp_##name);
 
-#define END_CP_FUNC(name)                                           \
-        SAVE_PROFILE_INTERVAL_ASSIGNED();                           \
-        return 0;                                                   \
+#define END_CP_FUNC(name)                 \
+        SAVE_PROFILE_INTERVAL_ASSIGNED(); \
+        return 0;                         \
     }
 
-#define END_CP_FUNC_NO_RS(name)                                     \
-    END_CP_FUNC(name)                                               \
-    BEGIN_RS_FUNC(name) {__UNUSED(entry); __UNUSED(base);           \
-        __UNUSED(offset); __UNUSED(rebase); } END_RS_FUNC(name)
-
-#define BEGIN_RS_FUNC(name)                                         \
-    DEFINE_RS_FUNC(name)                                            \
-    {                                                               \
-        int CP_FUNC_TYPE __attribute__((unused)) = CP_FUNC(name);   \
-        const char * CP_FUNC_NAME __attribute__((unused)) = #name;  \
-        BEGIN_PROFILE_INTERVAL();                                   \
+#define END_CP_FUNC_NO_RS(name) \
+    END_CP_FUNC(name)           \
+    BEGIN_RS_FUNC(name) {       \
+        __UNUSED(entry);        \
+        __UNUSED(base);         \
+        __UNUSED(offset);       \
+        __UNUSED(rebase);       \
+    }                           \
+    END_RS_FUNC(name)
+
+#define BEGIN_RS_FUNC(name)                                               \
+    DEFINE_RS_FUNC(name) {                                                \
+        int CP_FUNC_TYPE __attribute__((unused))         = CP_FUNC(name); \
+        const char* CP_FUNC_NAME __attribute__((unused)) = #name;         \
+        BEGIN_PROFILE_INTERVAL();                                         \
         ASSIGN_PROFILE_INTERVAL(rs_##name);
 
-#define END_RS_FUNC(name)                                           \
-        SAVE_PROFILE_INTERVAL_ASSIGNED();                           \
-        return 0;                                                   \
+#define END_RS_FUNC(name)                 \
+        SAVE_PROFILE_INTERVAL_ASSIGNED(); \
+        return 0;                         \
     }
 
-#define CP_REBASE(obj)                                          \
-    do {                                                        \
-        void * _ptr = &(obj);                                   \
-        size_t _size = sizeof(obj);                             \
-        void ** _p;                                             \
-        for (_p = _ptr ; _p < (void **)(_ptr + _size) ; _p++)   \
-            if (*_p)                                            \
-                *_p += rebase;                                  \
+#define CP_REBASE(obj)                                     \
+    do {                                                   \
+        void* _ptr   = &(obj);                             \
+        size_t _size = sizeof(obj);                        \
+        void** _p;                                         \
+        for (_p = _ptr; _p < (void**)(_ptr + _size); _p++) \
+            if (*_p)                                       \
+                *_p += rebase;                             \
     } while (0)
 
-#define DO_CP_SIZE(name, obj, size, objp)                       \
-    do {                                                        \
-        extern DEFINE_CP_FUNC(name);                            \
-        int ret = cp_##name(store, obj, size, (void**)(objp));  \
-        if (ret < 0) return ret;                                \
+#define DO_CP_SIZE(name, obj, size, objp)                      \
+    do {                                                       \
+        extern DEFINE_CP_FUNC(name);                           \
+        int ret = cp_##name(store, obj, size, (void**)(objp)); \
+        if (ret < 0)                                           \
+            return ret;                                        \
     } while (0)
 
+#define DO_CP(name, obj, objp)                  DO_CP_SIZE(name, obj, sizeof(*(obj)), objp)
+#define DO_CP_MEMBER(name, obj, newobj, member) DO_CP(name, (obj)->member, &((newobj)->member));
+#define DO_CP_IN_MEMBER(name, obj, member)      DO_CP(name, &((obj)->member), NULL)
 
-#define DO_CP(name, obj, objp)                                  \
-        DO_CP_SIZE(name, obj, sizeof(*(obj)), objp)
-
-#define DO_CP_MEMBER(name, obj, newobj, member)                 \
-        DO_CP(name, (obj)->member, &((newobj)->member));
-
-#define DO_CP_IN_MEMBER(name, obj, member)                      \
-        DO_CP(name, &((obj)->member), NULL)
-
-struct shim_cp_map_entry { void * addr; ptr_t off; };
+struct shim_cp_map_entry {
+    void* addr;
+    ptr_t off;
+};
 
-void * create_cp_map (void);
-void destroy_cp_map (void * map);
+void* create_cp_map(void);
+void destroy_cp_map(void* map);
 
-struct shim_cp_map_entry *
-get_cp_map_entry (void * map, void * addr, bool create);
+struct shim_cp_map_entry* get_cp_map_entry(void* map, void* addr, bool create);
 
-#define GET_FROM_CP_MAP(obj)                                    \
-    ({                                                          \
-        struct shim_cp_map_entry * e =                          \
-                get_cp_map_entry(store->cp_map, obj, false);    \
-    e ? e->off : 0; })
+#define GET_FROM_CP_MAP(obj)                                                       \
+    ({                                                                             \
+        struct shim_cp_map_entry* e = get_cp_map_entry(store->cp_map, obj, false); \
+        e ? e->off : 0;                                                            \
+    })
 
-#define ADD_TO_CP_MAP(obj, off)                                 \
-    do {                                                        \
-        struct shim_cp_map_entry * e =                          \
-                get_cp_map_entry(store->cp_map, obj, true);     \
-        e->off = (off);                                         \
+#define ADD_TO_CP_MAP(obj, off)                                                   \
+    do {                                                                          \
+        struct shim_cp_map_entry* e = get_cp_map_entry(store->cp_map, obj, true); \
+        e->off                      = (off);                                      \
     } while (0)
 
-#define BEGIN_MIGRATION_DEF(name, ...)                                  \
-    int migrate_##name (struct shim_cp_store * store, ##__VA_ARGS__)    \
-    {                                                                   \
-        int ret = 0;                                                    \
+#define BEGIN_MIGRATION_DEF(name, ...)                               \
+    int migrate_##name(struct shim_cp_store* store, ##__VA_ARGS__) { \
+        int ret    = 0;                                              \
         ptr_t base = store->base;
 
-#define END_MIGRATION_DEF(name)                                         \
-        ADD_CP_ENTRY(NULL, 0);                                          \
-        return 0;                                                       \
+#define END_MIGRATION_DEF(name)     \
+        ADD_CP_ENTRY(NULL, 0);      \
+        return 0;                   \
     }
 
-#define DEFINE_MIGRATE(name, obj, size)                                 \
-    do {                                                                \
-        extern DEFINE_CP_FUNC(name);                                    \
-        if ((ret = cp_##name(store, obj, size, NULL)) < 0)              \
-            return ret;                                                 \
+#define DEFINE_MIGRATE(name, obj, size)                    \
+    do {                                                   \
+        extern DEFINE_CP_FUNC(name);                       \
+        if ((ret = cp_##name(store, obj, size, NULL)) < 0) \
+            return ret;                                    \
     } while (0)
 
-#define DEBUG_RESUME      0
-#define DEBUG_CHECKPOINT  0
+#define DEBUG_RESUME     0
+#define DEBUG_CHECKPOINT 0
 
 #if DEBUG_RESUME == 1
-# define DEBUG_RS(fmt, ...)                                              \
-    debug("GET %s(0x%08lx): " fmt "\n", CP_FUNC_NAME, entry->cp_un.cp_val, \
-          ##__VA_ARGS__)
+#define DEBUG_RS(fmt, ...) \
+    debug("GET %s(0x%08lx): " fmt "\n", CP_FUNC_NAME, entry->cp_un.cp_val, ##__VA_ARGS__)
 #else
-# define DEBUG_RS(...) do {} while (0)
+#define DEBUG_RS(...) do {} while (0)
 #endif
 
 #include <shim_profile.h>
 
-#define START_MIGRATE(store, name, ...)                                     \
-    ({  int ret = 0;                                                        \
-        do {                                                                \
-            BEGIN_PROFILE_INTERVAL();                                       \
-                                                                            \
-            if (!((store)->cp_map = create_cp_map())) {                     \
-                ret = -ENOMEM;                                              \
-                goto out;                                                   \
-            }                                                               \
-            SAVE_PROFILE_INTERVAL(checkpoint_create_map);                   \
-                                                                            \
-            ret = migrate_##name(store, ##__VA_ARGS__);                     \
-            if (ret < 0)                                                    \
-                goto out;                                                   \
-                                                                            \
-            SAVE_PROFILE_INTERVAL(checkpoint_copy);                         \
-            ADD_PROFILE_OCCURENCE(checkpoint_total_size, (store)->offset);  \
-            INC_PROFILE_OCCURENCE(checkpoint_count);                        \
-                                                                            \
-            debug("complete checkpointing data\n");                         \
-        out:                                                                \
-            destroy_cp_map((store)->cp_map);                                \
-            SAVE_PROFILE_INTERVAL(checkpoint_destroy_map);                  \
-        } while (0);                                                        \
-        ret; })
+#define START_MIGRATE(store, name, ...)                                    \
+    ({                                                                     \
+        int ret = 0;                                                       \
+        do {                                                               \
+            BEGIN_PROFILE_INTERVAL();                                      \
+                                                                           \
+            if (!((store)->cp_map = create_cp_map())) {                    \
+                ret = -ENOMEM;                                             \
+                goto out;                                                  \
+            }                                                              \
+            SAVE_PROFILE_INTERVAL(checkpoint_create_map);                  \
+                                                                           \
+            ret = migrate_##name(store, ##__VA_ARGS__);                    \
+            if (ret < 0)                                                   \
+                goto out;                                                  \
+                                                                           \
+            SAVE_PROFILE_INTERVAL(checkpoint_copy);                        \
+            ADD_PROFILE_OCCURENCE(checkpoint_total_size, (store)->offset); \
+            INC_PROFILE_OCCURENCE(checkpoint_count);                       \
+                                                                           \
+            debug("complete checkpointing data\n");                        \
+        out:                                                               \
+            destroy_cp_map((store)->cp_map);                               \
+            SAVE_PROFILE_INTERVAL(checkpoint_destroy_map);                 \
+        } while (0);                                                       \
+        ret;                                                               \
+    })
 
 struct newproc_cp_header {
     struct cp_header {
         unsigned long size;
-        void * addr;
+        void* addr;
         unsigned long offset;
     } hdr;
     struct mem_header {
@@ -420,28 +414,16 @@ struct newproc_response {
     int failure;
 };
 
-int do_migration (struct newproc_cp_header * hdr, void ** cpptr);
-
-int restore_checkpoint (struct cp_header * cphdr, struct mem_header * memhdr,
-                        ptr_t base, ptr_t type);
-
-int do_migrate_process (int (*migrate) (struct shim_cp_store *,
-                                        struct shim_thread *,
-                                        struct shim_process *, va_list),
-                        struct shim_handle * exec,
-                        const char ** argv,
-                        struct shim_thread * thread, ...);
-
-int init_from_checkpoint_file (const char * filename,
-                               struct newproc_cp_header * hdr,
-                               void ** cpptr);
-
-int restore_from_file (const char * filename, struct newproc_cp_header * hdr,
-                       void ** cpptr);
-
-void restore_context (struct shim_context * context);
-
-int create_checkpoint (const char * cpdir, IDTYPE * session);
-int join_checkpoint (struct shim_thread * cur, IDTYPE sid);
+int do_migration(struct newproc_cp_header* hdr, void** cpptr);
+int restore_checkpoint(struct cp_header* cphdr, struct mem_header* memhdr, ptr_t base, ptr_t type);
+int do_migrate_process(int (*migrate)(struct shim_cp_store*, struct shim_thread*,
+                                      struct shim_process*, va_list),
+                       struct shim_handle* exec, const char** argv, struct shim_thread* thread,
+                       ...);
+int init_from_checkpoint_file(const char* filename, struct newproc_cp_header* hdr, void** cpptr);
+int restore_from_file(const char* filename, struct newproc_cp_header* hdr, void** cpptr);
+void restore_context(struct shim_context* context);
+int create_checkpoint(const char* cpdir, IDTYPE* session);
+int join_checkpoint(struct shim_thread* cur, IDTYPE sid);
 
 #endif /* _SHIM_CHECKPOINT_H_ */

+ 213 - 250
LibOS/shim/include/shim_fs.h

@@ -25,142 +25,133 @@
 
 #include <stdbool.h>
 
-#include <shim_types.h>
+#include <list.h>
+#include <pal.h>
 #include <shim_defs.h>
 #include <shim_handle.h>
+#include <shim_types.h>
 #include <shim_utils.h>
 
-#include <pal.h>
-#include <list.h>
-
 struct shim_handle;
 
-#define FS_POLL_RD         0x01
-#define FS_POLL_WR         0x02
-#define FS_POLL_ER         0x04
-#define FS_POLL_SZ         0x08
+#define FS_POLL_RD 0x01
+#define FS_POLL_WR 0x02
+#define FS_POLL_ER 0x04
+#define FS_POLL_SZ 0x08
 
 struct shim_fs_ops {
     /* mount: mount an uri to the certain location */
-    int (*mount) (const char * uri, void ** mount_data);
-    int (*unmount) (void * mount_data);
+    int (*mount)(const char* uri, void** mount_data);
+    int (*unmount)(void* mount_data);
 
     /* close: clean up the file state inside the handle */
-    int (*close) (struct shim_handle * hdl);
+    int (*close)(struct shim_handle* hdl);
 
     /* read: the content from the file opened as handle */
-    ssize_t (*read) (struct shim_handle * hdl, void * buf, size_t count);
+    ssize_t (*read)(struct shim_handle* hdl, void* buf, size_t count);
 
     /* write: the content from the file opened as handle */
-    ssize_t (*write) (struct shim_handle * hdl, const void * buf, size_t count);
+    ssize_t (*write)(struct shim_handle* hdl, const void* buf, size_t count);
 
     /* mmap: mmap handle to address */
-    int (*mmap) (struct shim_handle * hdl, void ** addr, size_t size,
-                 int prot, int flags, off_t offset);
+    int (*mmap)(struct shim_handle* hdl, void** addr, size_t size, int prot, int flags,
+                off_t offset);
 
     /* flush: flush out user buffer */
-    int (*flush) (struct shim_handle * hdl);
+    int (*flush)(struct shim_handle* hdl);
 
     /* seek: the content from the file opened as handle */
-    off_t (*seek) (struct shim_handle * hdl, off_t offset, int wence);
+    off_t (*seek)(struct shim_handle* hdl, off_t offset, int wence);
 
     /* move, copy: rename or duplicate the file */
-    int (*move) (const char * trim_old_name, const char * trim_new_name);
-    int (*copy) (const char * trim_old_name, const char * trim_new_name);
+    int (*move)(const char* trim_old_name, const char* trim_new_name);
+    int (*copy)(const char* trim_old_name, const char* trim_new_name);
 
     /* Returns 0 on success, -errno on error */
-    int (*truncate) (struct shim_handle * hdl, off_t len);
+    int (*truncate)(struct shim_handle* hdl, off_t len);
 
     /* hstat: get status of the file */
-    int (*hstat) (struct shim_handle * hdl, struct stat * buf);
+    int (*hstat)(struct shim_handle* hdl, struct stat* buf);
 
     /* setflags: set flags of the file */
-    int (*setflags) (struct shim_handle * hdl, int flags);
+    int (*setflags)(struct shim_handle* hdl, int flags);
 
     /* hput: delete the handle and close the PAL handle. */
-    void (*hput) (struct shim_handle * hdl);
+    void (*hput)(struct shim_handle* hdl);
 
     /* lock and unlock the file */
-    int (*lock) (const char * trim_name);
-    int (*unlock) (const char * trim_name);
+    int (*lock)(const char* trim_name);
+    int (*unlock)(const char* trim_name);
 
     /* lock and unlock the file system */
-    int (*lockfs) (void);
-    int (*unlockfs) (void);
+    int (*lockfs)(void);
+    int (*unlockfs)(void);
 
     /* checkout/reowned/checkin a single handle for migration */
-    int (*checkout) (struct shim_handle * hdl);
-    int (*checkin) (struct shim_handle * hdl);
+    int (*checkout)(struct shim_handle* hdl);
+    int (*checkin)(struct shim_handle* hdl);
 
     /* poll a single handle */
     /* POLL_RD|POLL_WR: return POLL_RD|POLL_WR for readable|writable,
        POLL_ER for failure, -EAGAIN for unknown. */
     /* POLL_SZ: return total size */
-    off_t (*poll) (struct shim_handle * hdl, int poll_type);
+    off_t (*poll)(struct shim_handle* hdl, int poll_type);
 
-    /* checkpoint/migrate the filesystem */
-    ssize_t (*checkpoint) (void ** checkpoint, void * mount_data);
-    int (*migrate) (void * checkpoint, void ** mount_data);
+    /* checkpoint/migrate the file system */
+    ssize_t (*checkpoint)(void** checkpoint, void* mount_data);
+    int (*migrate)(void* checkpoint, void** mount_data);
 };
 
-#define DENTRY_VALID        0x0001  /* this dentry is verified to be valid */
-#define DENTRY_NEGATIVE     0x0002  /* recently deleted or inaccessible */
-#define DENTRY_RECENTLY     0x0004  /* recently used */
-#define DENTRY_PERSIST      0x0008  /* added as a persistent dentry */
-#define DENTRY_HASHED       0x0010  /* added in the dcache */
-#define DENTRY_MOUNTPOINT   0x0040  /* this dentry is a mount point */
-#define DENTRY_ISLINK       0x0080  /* this dentry is a link */
-#define DENTRY_ISDIRECTORY  0x0100  /* this dentry is a directory */
-#define DENTRY_LOCKED       0x0200  /* locked by mountpoints at children */
+#define DENTRY_VALID       0x0001 /* this dentry is verified to be valid */
+#define DENTRY_NEGATIVE    0x0002 /* recently deleted or inaccessible */
+#define DENTRY_RECENTLY    0x0004 /* recently used */
+#define DENTRY_PERSIST     0x0008 /* added as a persistent dentry */
+#define DENTRY_HASHED      0x0010 /* added in the dcache */
+#define DENTRY_MOUNTPOINT  0x0040 /* this dentry is a mount point */
+#define DENTRY_ISLINK      0x0080 /* this dentry is a link */
+#define DENTRY_ISDIRECTORY 0x0100 /* this dentry is a directory */
+#define DENTRY_LOCKED      0x0200 /* locked by mountpoints at children */
 /* These flags are not used */
 //#define DENTRY_REACHABLE    0x0400  /* permission checked to be reachable */
 //#define DENTRY_UNREACHABLE  0x0800  /* permission checked to be unreachable */
-#define DENTRY_LISTED       0x1000  /* children in directory listed */
-#define DENTRY_INO_UPDATED  0x2000  /* ino updated */
-#define DENTRY_ANCESTOR     0x4000 /* Auto-generated dentry to connect a mount
-                                    * point in the manifest to the root, when
-                                    * one or more intermediate directories do
-                                    * not exist on the underlying FS. The
-                                    * semantics of subsequent changes to such
-                                    * directories (or attempts to really
-                                    * create them) are not currently
-                                    * well-defined. */
+#define DENTRY_LISTED      0x1000 /* children in directory listed */
+#define DENTRY_INO_UPDATED 0x2000 /* ino updated */
+#define DENTRY_ANCESTOR    0x4000 /* Auto-generated dentry to connect a mount point in the        \
+                                   * manifest to the root, when one or more intermediate          \
+                                   * directories do not exist on the underlying FS. The semantics \
+                                   * of subsequent changes to such directories (or attempts to    \
+                                   * really create them) are not currently well-defined. */
 
 // Catch memory corruption issues by checking for invalid state values
 #define DENTRY_INVALID_FLAGS (~0x7FFF)
 
-#define DCACHE_HASH_SIZE    1024
+#define DCACHE_HASH_SIZE  1024
 #define DCACHE_HASH(hash) ((hash) & (DCACHE_HASH_SIZE - 1))
 
 DEFINE_LIST(shim_dentry);
 DEFINE_LISTP(shim_dentry);
 struct shim_dentry {
-    int state;  /* flags for managing state */
-
-    struct shim_mount * fs;         /* this dentry's mounted fs */
-    struct shim_qstr rel_path;      /* the path is relative to
-                                       its mount point */
-    struct shim_qstr name;          /* caching the file's name. */
+    int state; /* flags for managing state */
 
+    struct shim_mount* fs;     /* this dentry's mounted fs */
+    struct shim_qstr rel_path; /* the path is relative to its mount point */
+    struct shim_qstr name;     /* caching the file's name. */
 
-    /* DEP 6/16/17: For now, let's try not hashing; I suspect it is
-     * overkill for most purposes.  I'll leave the field here for now,
-     * but propose we move to a per-directory table to accelerate lookups,
-     * rather than a global table, since this just supports one process.
+    /* DEP 6/16/17: For now, let's try not hashing; I suspect it is overkill for most purposes.
+     * I'll leave the field here for now, but propose we move to a per-directory table to accelerate
+     * lookups, rather than a global table, since this just supports one process.
      */
-    LIST_TYPE(shim_dentry) hlist;    /* to resolve collisions in
-                                       the hash table */
-    LIST_TYPE(shim_dentry) list;     /* put dentry to different list
-                                       according to its availability,
-                                       persistent or freeable */
+    LIST_TYPE(shim_dentry) hlist; /* to resolve collisions in the hash table */
+    LIST_TYPE(shim_dentry) list; /* put dentry to different list according to its availability, \
+                                  * persistent or freeable */
 
-    struct shim_dentry * parent;
+    struct shim_dentry* parent;
     int nchildren;
     LISTP_TYPE(shim_dentry) children; /* These children and siblings link */
     LIST_TYPE(shim_dentry) siblings;
 
-    struct shim_mount * mounted;
-    void * data;
+    struct shim_mount* mounted;
+    void* data;
     unsigned long ino;
     mode_t type;
     mode_t mode;
@@ -172,8 +163,7 @@ struct shim_dentry {
 struct shim_d_ops {
     /* open: provide a filename relative to the mount point and flags,
        modify the shim handle, file_data is "inode" equivalent */
-    int (*open) (struct shim_handle * hdl, struct shim_dentry * dent,
-                 int flags);
+    int (*open)(struct shim_handle* hdl, struct shim_dentry* dent, int flags);
 
     /* look up dentry and allocate internal data.
      *
@@ -181,68 +171,67 @@ struct shim_d_ops {
      * this function should call get_new_dentry(), populating additional fields,
      * and storing the new dentry in dent.
      */
-    int (*lookup) (struct shim_dentry * dent);
+    int (*lookup)(struct shim_dentry* dent);
 
     /* this is to check file type and access, returning the stat.st_mode */
-    int (*mode) (struct shim_dentry * dent, mode_t * mode);
+    int (*mode)(struct shim_dentry* dent, mode_t* mode);
 
     /* detach internal data from dentry */
-    int (*dput) (struct shim_dentry * dent);
+    int (*dput)(struct shim_dentry* dent);
 
     /* create a dentry inside a directory */
-    int (*creat) (struct shim_handle * hdl, struct shim_dentry * dir,
-                  struct shim_dentry * dent, int flags, mode_t mode);
+    int (*creat)(struct shim_handle* hdl, struct shim_dentry* dir, struct shim_dentry* dent,
+                 int flags, mode_t mode);
 
     /* unlink a dentry inside a directory */
-    int (*unlink) (struct shim_dentry * dir, struct shim_dentry * dent);
+    int (*unlink)(struct shim_dentry* dir, struct shim_dentry* dent);
 
     /* create a directory inside a directory */
-    int (*mkdir) (struct shim_dentry * dir, struct shim_dentry * dent,
-                  mode_t mode);
+    int (*mkdir)(struct shim_dentry* dir, struct shim_dentry* dent, mode_t mode);
 
     /* stat: get status of the file */
-    int (*stat) (struct shim_dentry * dent, struct stat * buf);
+    int (*stat)(struct shim_dentry* dent, struct stat* buf);
 
     /* extracts the symlink name and saves in link */
-    int (*follow_link) (struct shim_dentry * dent, struct shim_qstr * link);
+    int (*follow_link)(struct shim_dentry* dent, struct shim_qstr* link);
     /* set up symlink name to a dentry */
-    int (*set_link) (struct shim_dentry * dent, const char * link);
+    int (*set_link)(struct shim_dentry* dent, const char* link);
 
     /* change the mode or owner of a dentry */
-    int (*chmod) (struct shim_dentry * dent, mode_t mode);
-    int (*chown) (struct shim_dentry * dent, int uid, int gid);
+    int (*chmod)(struct shim_dentry* dent, mode_t mode);
+    int (*chown)(struct shim_dentry* dent, int uid, int gid);
 
     /* change the name of a dentry */
-    int (*rename) (struct shim_dentry * old, struct shim_dentry * new);
+    int (*rename)(struct shim_dentry* old, struct shim_dentry* new);
 
     /* readdir: given the path relative to the mount point, read the childs
        into the the buffer.  This call always returns everything under
        the directory in one big buffer; you do not need to try again
        or keep a cursor in the directory.  You do need to free the
        returned buffer. */
-    int (*readdir) (struct shim_dentry * dent, struct shim_dirent ** dirent);
+    int (*readdir)(struct shim_dentry* dent, struct shim_dirent** dirent);
 };
 
-#define MAX_PATH        4096
-#define MAX_FILENAME    255
+#define MAX_PATH     4096
+#define MAX_FILENAME 255
 
 DEFINE_LIST(shim_mount);
 struct shim_mount {
     char type[8];  // Null-terminated.
 
-    struct shim_dentry * mount_point;
+    struct shim_dentry* mount_point;
 
     struct shim_qstr path;
     struct shim_qstr uri;
 
-    struct shim_fs_ops * fs_ops;
-    struct shim_d_ops * d_ops;
+    struct shim_fs_ops* fs_ops;
+    struct shim_d_ops* d_ops;
 
-    struct shim_dentry * root;
+    struct shim_dentry* root;
 
-    void * data;
+    void* data;
 
-    void * cpdata;
+    void* cpdata;
     size_t cpsize;
 
     REFTYPE ref_count;
@@ -250,35 +239,36 @@ struct shim_mount {
     LIST_TYPE(shim_mount) list;
 };
 
-extern struct shim_dentry * dentry_root;
+extern struct shim_dentry* dentry_root;
 
-#define LOOKUP_FOLLOW            001
-#define LOOKUP_DIRECTORY         002
-#define LOOKUP_CONTINUE          004 // No longer needed
-#define LOOKUP_PARENT            010 // Not sure we need this
+#define LOOKUP_FOLLOW    001
+#define LOOKUP_DIRECTORY 002
+#define LOOKUP_CONTINUE  004  // No longer needed
+#define LOOKUP_PARENT    010  // Not sure we need this
 
-#define F_OK          0
+#define F_OK 0
 // XXX: Duplicate definition; should probably weed out includes of host system
-//include of unistd.h in future work
+// include of unistd.h in future work
 //#define R_OK        001
 //#define W_OK        002
 //#define X_OK        004
-#define MAY_EXEC    001
-#define MAY_WRITE   002
-#define MAY_READ    004
+#define MAY_EXEC  001
+#define MAY_WRITE 002
+#define MAY_READ  004
 #if 0
-#define MAY_APPEND  010
+#define MAY_APPEND 010
 #endif
 
-#define NO_MODE     ((mode_t) -1)
+#define NO_MODE ((mode_t)-1)
 
-#define ACC_MODE(x) ((((x) == O_RDONLY || (x) == O_RDWR) ? MAY_READ : 0) | \
-                     (((x) == O_WRONLY || (x) == O_RDWR) ? MAY_WRITE : 0))
+#define ACC_MODE(x)                                        \
+    ((((x) == O_RDONLY || (x) == O_RDWR) ? MAY_READ : 0) | \
+     (((x) == O_WRONLY || (x) == O_RDWR) ? MAY_WRITE : 0))
 
-#define LOOKUP_OPEN             0100 // Appears to be ignored
-#define LOOKUP_CREATE           0200
-#define LOOKUP_ACCESS           0400 // Appears to be ignored
-#define LOOKUP_SYNC     (LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_ACCESS)
+#define LOOKUP_OPEN   0100  // Appears to be ignored
+#define LOOKUP_CREATE 0200
+#define LOOKUP_ACCESS 0400  // Appears to be ignored
+#define LOOKUP_SYNC   (LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_ACCESS)
 
 enum lookup_type {
     LAST_NORM,
@@ -289,91 +279,83 @@ enum lookup_type {
 };
 
 struct lookup {
-    struct shim_dentry * dentry;
-    struct shim_mount * mount;
-    const char * last;
+    struct shim_dentry* dentry;
+    struct shim_mount* mount;
+    const char* last;
     int depth;
     int flags;
     enum lookup_type last_type;
 };
 
-
 /* initialization for fs and mounts */
-int init_fs (void);
-int init_mount_root (void);
-int init_mount (void);
+int init_fs(void);
+int init_mount_root(void);
+int init_mount(void);
 
 /* path utilities */
-const char * get_file_name (const char * path, size_t len);
+const char* get_file_name(const char* path, size_t len);
 
 /* file system operations */
-int mount_fs (const char * mount_type, const char * mount_uri,
-              const char * mount_point, struct shim_dentry *parent,
-              struct shim_dentry **dentp, bool make_ancestor);
-int unmount_fs (const char * mount_point);
-int search_builtin_fs (const char * type, struct shim_mount ** fs);
+int mount_fs(const char* mount_type, const char* mount_uri, const char* mount_point,
+             struct shim_dentry* parent, struct shim_dentry** dentp, bool make_ancestor);
+int unmount_fs(const char* mount_point);
+int search_builtin_fs(const char* type, struct shim_mount** fs);
 
-void get_mount (struct shim_mount * mount);
-void put_mount (struct shim_mount * mount);
+void get_mount(struct shim_mount* mount);
+void put_mount(struct shim_mount* mount);
 
-struct shim_mount * find_mount_from_uri (const char * uri);
+struct shim_mount* find_mount_from_uri(const char* uri);
 
 #include <shim_utils.h>
 
-static inline void set_handle_fs (struct shim_handle * hdl,
-                                  struct shim_mount * fs)
-{
+static inline void set_handle_fs(struct shim_handle* hdl, struct shim_mount* fs) {
     get_mount(fs);
     hdl->fs = fs;
     memcpy(hdl->fs_type, fs->type, sizeof(hdl->fs_type));
 }
 
-int walk_mounts (int (*walk) (struct shim_mount * mount, void * arg),
-                 void * arg);
+int walk_mounts(int (*walk)(struct shim_mount* mount, void* arg), void* arg);
 
 /* functions for dcache supports */
-int init_dcache (void);
+int init_dcache(void);
 
 extern struct shim_lock dcache_lock;
 
-/* check permission (specified by mask) of a dentry. If force is not set,
- * permission is considered granted on invalid dentries */
-/* Assume caller has acquired dcache_lock */
-int permission (struct shim_dentry * dent, mode_t mask);
+/* Checks permission (specified by mask) of a dentry. If force is not set, permission is considered
+ * granted on invalid dentries.
+ * Assumes that caller has acquired dcache_lock. */
+int permission(struct shim_dentry* dent, mode_t mask);
 
-/* This function looks up a single dentry based on its parent dentry pointer
- * and the name.  Namelen is the length of char * name.
- * The dentry is returned in pointer *new.
+/* This function looks up a single dentry based on its parent dentry pointer and the name. `namelen`
+ * is the length of char* name. The dentry is returned in pointer *new.
  *
  * 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);
 
-/* Looks up path under start dentry.  Saves in dent.
+/* Looks up path under start dentry. Saves in dent.
  *
- * Assumes dcache_lock is held; main difference from path_lookupat is that
- * dcache_lock is not released on return.
+ * Assumes dcache_lock is held; main difference from path_lookupat is that dcache_lock is not
+ * released on return.
  *
  * The refcount is dropped by one on the returned dentry.
  *
- * The make_ancestor flag creates pseudo-dentries for any parent paths that
- * are not in cache and do not exist on the underlying file system.  This is
- * intended for use only in setting up the file system view specified in the manifest.
+ * The make_ancestor flag creates pseudo-dentries for any parent paths that are not in cache and do
+ * not exist on the underlying file system. This is intended for use only in setting up the
+ * file system view specified in the manifest.
  *
  * If the file isnt' found, returns -ENOENT.
  *
- * If the LOOKUP_DIRECTORY flag is set, and the found file isn't a directory,
- *  returns -ENOTDIR.
+ * 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);
 
-/* 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);
+/* 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);
 
 /*
  * This function returns a dentry (in *dir) from a handle corresponding to dirfd.
@@ -388,67 +370,59 @@ int get_dirfd_dentry(int dirfd, struct shim_dentry** dir);
 /* Open path with given flags, in mode, similar to Unix open.
  *
  * The start dentry specifies where to begin the search.
- * hdl is an optional argument; if passed in, it is initialized to
- *   refer to the opened path.
+ * `hdl` is an optional argument; if passed in, it is initialized to refer to the opened path.
  *
- * The result is stored in dent.
+ * 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);
 
-/* This function calls the low-level file system to do the work
- * of opening file indicated by dent, and initializing it in hdl.
- * Flags are standard open flags.
+/* This function calls the low-level file system to do the work of opening file indicated by dent,
+ * and initializing it in hdl. Flags are standard open flags.
  *
- * If O_TRUNC is specified, this function is responsible for calling
- * the underlying truncate function.
+ * If O_TRUNC is specified, this function is responsible for calling 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);
 
 /* This function enumerates a directory and caches the results in the dentry.
  *
- * Input: A dentry for a directory in the DENTRY_ISDIRECTORY and not in the
- * DENTRY_LISTED state.  The dentry DENTRY_LISTED flag is set upon success.
+ * Input: A dentry for a directory in the DENTRY_ISDIRECTORY and not in the DENTRY_LISTED state.
+ * The dentry DENTRY_LISTED flag is set upon success.
  *
  * Return value: 0 on success, <0 on error
  */
-int list_directory_dentry (struct shim_dentry *dir);
+int list_directory_dentry(struct shim_dentry* dir);
 
-/* This function caches the contents of a directory (dent), already
- * in the listed state, in a buffer associated with a handle (hdl).
+/* This function caches the contents of a directory (dent), already in the listed state, in a buffer
+ * associated with a handle (hdl).
  *
  * This function should only be called once on a handle.
  *
  * Returns 0 on success, <0 on failure.
  */
-int list_directory_handle (struct shim_dentry *dent, struct shim_handle *hdl );
-
+int list_directory_handle(struct shim_dentry* dent, struct shim_handle* hdl);
 
 /* Increment the reference count on dent */
-void get_dentry (struct shim_dentry * dent);
+void get_dentry(struct shim_dentry* dent);
 /* Decrement the reference count on dent */
-void put_dentry (struct shim_dentry * dent);
-
-static_always_inline
-void fast_pathcpy (char * dst, const char * src, size_t size, char ** ptr)
-{
-    char * d = dst;
-    const char * s = src;
-    for (size_t i = 0 ; i < size ; i++, s++, d++)
+void put_dentry(struct shim_dentry* dent);
+
+static_always_inline void fast_pathcpy(char* dst, const char* src, size_t size, char** ptr) {
+    char* d       = dst;
+    const char* s = src;
+    for (size_t i = 0; i < size; i++, s++, d++)
         *d = *s;
     *ptr = d;
 }
 
-static_always_inline
-char * dentry_get_path (struct shim_dentry * dent, bool on_stack,
-                        size_t * sizeptr)
-{
-    struct shim_mount * fs = dent->fs;
-    char * buffer, * c;
+static_always_inline char* dentry_get_path(struct shim_dentry* dent, bool on_stack,
+                                           size_t* sizeptr) {
+    struct shim_mount* fs = dent->fs;
+    char* buffer;
+    char* c;
     size_t bufsize = dent->rel_path.len + 1;
 
     if (fs)
@@ -465,8 +439,8 @@ char * dentry_get_path (struct shim_dentry * dent, bool on_stack,
         fast_pathcpy(c, qstrgetstr(&fs->path), fs->path.len, &c);
 
     if (dent->rel_path.len) {
-        const char * path = qstrgetstr(&dent->rel_path);
-        int len = dent->rel_path.len;
+        const char* path = qstrgetstr(&dent->rel_path);
+        int len          = dent->rel_path.len;
 
         if (c > buffer && *(c - 1) == '/') {
             if (*path == '/')
@@ -486,63 +460,54 @@ char * dentry_get_path (struct shim_dentry * dent, bool on_stack,
     return buffer;
 }
 
-static_always_inline
-const char * dentry_get_name (struct shim_dentry * dent)
-{
+static_always_inline const char* dentry_get_name(struct shim_dentry* dent) {
     return qstrgetstr(&dent->name);
 }
 
-/* Allocate and initialize a new dentry for path name, under
- * parent.  Return the dentry.
+/* Allocate and initialize a new dentry for path name, under parent.  Return the dentry.
  *
- * mount is the mountpoint the dentry is under; this is typically
- * the parent->fs, but is passed explicitly for initializing
- * the dentry of a mountpoint.
+ * `mount` is the mountpoint the dentry is under; this is typically the parent->fs, but is passed
+ * explicitly for initializing the dentry of a mountpoint.
  *
- * If hashptr is passed (as an optimization), this is a hash
- * of the name.
+ * If hashptr is passed (as an optimization), this is a hash of the name.
  *
  * If parent is non-null, the ref count is 2; else it is 1.
  *
  * This function also sets up both a name and a relative path
  */
-struct shim_dentry * get_new_dentry (struct shim_mount *mount,
-                                     struct shim_dentry * parent,
-                                     const char * name, int namelen,
-                                     HASHTYPE * hashptr);
+struct shim_dentry* get_new_dentry(struct shim_mount* mount, struct shim_dentry* parent,
+                                   const char* name, int namelen, HASHTYPE* hashptr);
 
 /* This function searches for name/namelen (as the relative path).
  *
- * If requested, the expected hash of the dentry is returned in hashptr,
- * primarily so that the hashing can be reused to add the dentry later.
+ * If requested, the expected hash of the dentry is returned in hashptr, primarily so that the
+ * hashing can be reused to add the dentry later.
  *
  * The reference count on the found dentry is incremented by one.
  *
  * Used only by shim_namei.c
  */
-struct shim_dentry *
-__lookup_dcache (struct shim_dentry * start, const char * name, int namelen,
-                 HASHTYPE * hashptr);
+struct shim_dentry* __lookup_dcache(struct shim_dentry* start, const char* name, int namelen,
+                                    HASHTYPE* hashptr);
 
 /* This function recursively deletes and frees all dentries under root
  *
  * XXX: Current code doesn't do a free..
  */
-int __del_dentry_tree(struct shim_dentry * root);
+int __del_dentry_tree(struct shim_dentry* root);
 
 /*
  * Returns true if `anc` is an ancestor of `dent`.
  */
 bool dentry_is_ancestor(struct shim_dentry* anc, struct shim_dentry* dent);
 
-/* XXX: Future work: current dcache never shrinks.  Would be nice
- * to be able to do something like LRU under space pressure, although
- * for a single app, this may be over-kill. */
+/* XXX: Future work: current dcache never shrinks. Would be nice to be able to do something like LRU
+ * under space pressure, although for a single app, this may be over-kill. */
 
 /* hashing utilities */
-#define MOUNT_HASH_BYTE     1
-#define MOUNT_HASH_WIDTH    8
-#define MOUNT_HASH_SIZE     256
+#define MOUNT_HASH_BYTE  1
+#define MOUNT_HASH_WIDTH 8
+#define MOUNT_HASH_SIZE  256
 
 #define MOUNT_HASH(hash) ((hash) & (MOUNT_HASH_SIZE - 1))
 
@@ -551,19 +516,19 @@ HASHTYPE rehash_name(HASHTYPE parent_hbuf, const char* name, size_t size);
 HASHTYPE rehash_path(HASHTYPE ancester_hbuf, const char* path, size_t size);
 
 extern struct shim_fs_ops chroot_fs_ops;
-extern struct shim_d_ops  chroot_d_ops;
+extern struct shim_d_ops chroot_d_ops;
 
 extern struct shim_fs_ops str_fs_ops;
-extern struct shim_d_ops  str_d_ops;
+extern struct shim_d_ops str_d_ops;
 
 extern struct shim_fs_ops dev_fs_ops;
-extern struct shim_d_ops  dev_d_ops;
+extern struct shim_d_ops dev_d_ops;
 
 extern struct shim_fs_ops config_fs_ops;
-extern struct shim_d_ops  config_d_ops;
+extern struct shim_d_ops config_d_ops;
 
 extern struct shim_fs_ops proc_fs_ops;
-extern struct shim_d_ops  proc_d_ops;
+extern struct shim_d_ops proc_d_ops;
 
 extern struct shim_mount chroot_builtin_fs;
 extern struct shim_mount pipe_builtin_fs;
@@ -573,27 +538,25 @@ extern struct shim_mount eventfd_builtin_fs;
 
 /* proc file system */
 struct proc_nm_ops {
-    int (*match_name) (const char * name);
-    int (*list_name) (const char * name, struct shim_dirent ** buf,
-                      int count);
+    int (*match_name)(const char* name);
+    int (*list_name)(const char* name, struct shim_dirent** buf, int count);
 };
 
 struct proc_fs_ops {
-    int (*open) (struct shim_handle * hdl, const char * name, int flags);
-    int (*mode) (const char * name, mode_t * mode);
-    int (*stat) (const char * name, struct stat * buf);
-    int (*follow_link) (const char * name, struct shim_qstr * link);
+    int (*open)(struct shim_handle* hdl, const char* name, int flags);
+    int (*mode)(const char* name, mode_t* mode);
+    int (*stat)(const char* name, struct stat* buf);
+    int (*follow_link)(const char* name, struct shim_qstr* link);
 };
 
 struct proc_dir;
 
 struct proc_ent {
-    const char * name;                      /* a proc_callback should at least
-                                               have a name or nm_ops.
-                                               Otherwise, it is a NULL-end. */
-    const struct proc_nm_ops * nm_ops;
-    const struct proc_fs_ops * fs_ops;
-    const struct proc_dir * dir;
+    const char* name; /* A proc_callback should at least have a name or nm_ops. Otherwise, it is a
+                       * NULL-end. */
+    const struct proc_nm_ops* nm_ops;
+    const struct proc_fs_ops* fs_ops;
+    const struct proc_dir* dir;
 };
 
 struct proc_dir {
@@ -602,14 +565,14 @@ struct proc_dir {
 };
 
 /* string-type file system */
-int str_add_dir (const char * path, mode_t mode, struct shim_dentry ** dent);
-int str_add_file (const char * path, mode_t mode, struct shim_dentry ** dent);
-int str_open (struct shim_handle * hdl, struct shim_dentry * dent, int flags);
-int str_dput (struct shim_dentry * dent);
-int str_close (struct shim_handle * hdl);
-ssize_t str_read (struct shim_handle * hdl, void * buf, size_t count);
-ssize_t str_write (struct shim_handle * hdl, const void * buf, size_t count);
-off_t str_seek (struct shim_handle * hdl, off_t offset, int whence);
-int str_flush (struct shim_handle * hdl);
+int str_add_dir(const char* path, mode_t mode, struct shim_dentry** dent);
+int str_add_file(const char* path, mode_t mode, struct shim_dentry** dent);
+int str_open(struct shim_handle* hdl, struct shim_dentry* dent, int flags);
+int str_dput(struct shim_dentry* dent);
+int str_close(struct shim_handle* hdl);
+ssize_t str_read(struct shim_handle* hdl, void* buf, size_t count);
+ssize_t str_write(struct shim_handle* hdl, const void* buf, size_t count);
+off_t str_seek(struct shim_handle* hdl, off_t offset, int whence);
+int str_flush(struct shim_handle* hdl);
 
 #endif /* _SHIM_FS_H_ */

+ 2 - 1
LibOS/shim/src/bookkeep/shim_handle.c

@@ -393,8 +393,9 @@ int set_new_fd_handle_by_fd(FDTYPE fd, struct shim_handle* hdl, int flags,
     if (ret < 0) {
         if (fd == handle_map->fd_top)
             handle_map->fd_top = fd ? fd - 1 : FD_NULL;
-    } else
+    } else {
         ret = fd;
+    }
 out:
     unlock(&handle_map->lock);
     return ret;

+ 4 - 2
LibOS/shim/src/fs/chroot/fs.c

@@ -69,8 +69,9 @@ static int chroot_mount (const char * uri, void ** mount_data)
     } else if (strstartswith_static(uri, URI_PREFIX_DEV)) {
         type = strstartswith_static(uri + static_strlen(URI_PREFIX_DEV), "tty") ? FILE_TTY : FILE_DEV;
         uri += 4;
-    } else
+    } else {
         return -EINVAL;
+    }
 
     if (!(*uri))
         uri = ".";
@@ -258,8 +259,9 @@ static int __query_attr (struct shim_dentry * dent,
             for (d = dbuf; d; d = d->next)
                 nlink++;
             free(dbuf);
-        } else
+        } else {
             nlink = 2; // Educated guess...
+        }
         data->nlink = nlink;
     } else {
         /* DEP 3/18/17: Right now, we don't support hard links,

+ 10 - 9
LibOS/shim/src/fs/eventfd/fs.c

@@ -23,12 +23,13 @@
 #include <asm/fcntl.h>
 #include <asm/unistd.h>
 #include <errno.h>
-#include <linux/stat.h>
 #include <linux/fcntl.h>
+#include <linux/stat.h>
+
 #include <pal.h>
-#include <shim_internal.h>
-#include <shim_handle.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))
@@ -39,19 +40,19 @@ static ssize_t eventfd_read(struct shim_handle* hdl, void* buf, size_t count) {
     if (bytes == PAL_STREAM_ERROR)
         return -PAL_ERRNO;
 
-    return (ssize_t) bytes;
+    return (ssize_t)bytes;
 }
 
 static ssize_t eventfd_write(struct shim_handle* hdl, const void* buf, size_t count) {
     if (count < sizeof(uint64_t))
         return -EINVAL;
 
-    PAL_NUM bytes = DkStreamWrite(hdl->pal_handle, 0, count, (void *) buf, NULL);
+    PAL_NUM bytes = DkStreamWrite(hdl->pal_handle, 0, count, (void*)buf, NULL);
 
     if (bytes == PAL_STREAM_ERROR)
         return -PAL_ERRNO;
 
-    return (ssize_t) bytes;
+    return (ssize_t)bytes;
 }
 
 static off_t eventfd_poll(struct shim_handle* hdl, int poll_type) {
@@ -89,12 +90,12 @@ out:
 }
 
 struct shim_fs_ops eventfd_fs_ops = {
-    .read = &eventfd_read,
+    .read  = &eventfd_read,
     .write = &eventfd_write,
-    .poll = &eventfd_poll,
+    .poll  = &eventfd_poll,
 };
 
 struct shim_mount eventfd_builtin_fs = {
-    .type = URI_TYPE_EVENTFD,
+    .type   = URI_TYPE_EVENTFD,
     .fs_ops = &eventfd_fs_ops,
 };

+ 45 - 60
LibOS/shim/src/fs/shim_dcache.c

@@ -21,13 +21,12 @@
  * This file contains codes for maintaining directory cache in library OS.
  */
 
-#include <shim_types.h>
-#include <shim_internal.h>
-#include <shim_handle.h>
-#include <shim_fs.h>
-#include <shim_checkpoint.h>
-
 #include <list.h>
+#include <shim_checkpoint.h>
+#include <shim_fs.h>
+#include <shim_handle.h>
+#include <shim_internal.h>
+#include <shim_types.h>
 
 struct shim_lock dcache_lock;
 
@@ -38,19 +37,15 @@ struct shim_lock dcache_lock;
 
 static MEM_MGR dentry_mgr = NULL;
 
-struct shim_dentry * dentry_root = NULL;
+struct shim_dentry* dentry_root = NULL;
 
-static inline
-HASHTYPE hash_dentry (struct shim_dentry * start, const char * path, int len)
-{
+static inline HASHTYPE hash_dentry(struct shim_dentry* start, const char* path, int len) {
     return rehash_path(start ? start->rel_path.hash : 0, path, len);
 }
 
-static struct shim_dentry * alloc_dentry (void)
-{
-    struct shim_dentry * dent =
-                get_mem_obj_from_mgr_enlarge(dentry_mgr,
-                                             size_align_up(DCACHE_MGR_ALLOC));
+static struct shim_dentry* alloc_dentry(void) {
+    struct shim_dentry* dent =
+        get_mem_obj_from_mgr_enlarge(dentry_mgr, size_align_up(DCACHE_MGR_ALLOC));
     if (!dent)
         return NULL;
 
@@ -67,9 +62,7 @@ static struct shim_dentry * alloc_dentry (void)
     return dent;
 }
 
-
-int init_dcache (void)
-{
+int init_dcache(void) {
     dentry_mgr = create_mem_mgr(init_align_up(DCACHE_MGR_ALLOC));
 
     create_lock(&dcache_lock);
@@ -87,7 +80,7 @@ int init_dcache (void)
     /* The root should be a directory too*/
     dentry_root->state |= DENTRY_ISDIRECTORY;
 
-    qstrsetstr(&dentry_root->name,     "", 0);
+    qstrsetstr(&dentry_root->name, "", 0);
     qstrsetstr(&dentry_root->rel_path, "", 0);
 
     get_dentry(dentry_root);
@@ -95,21 +88,18 @@ int init_dcache (void)
 }
 
 /* Increment the reference count for a dentry */
-void get_dentry (struct shim_dentry * dent)
-{
+void get_dentry(struct shim_dentry* dent) {
 #ifdef DEBUG_REF
     int count = REF_INC(dent->ref_count);
 
     debug("get dentry %p(%s/%s) (ref_count = %d)\n", dent,
-          dent->fs ?
-          qstrgetstr(&dent->fs->path) : "",
-          qstrgetstr(&dent->rel_path), count);
+          dent->fs ? qstrgetstr(&dent->fs->path) : "", qstrgetstr(&dent->rel_path), count);
 #else
     REF_INC(dent->ref_count);
 #endif
 }
 
-static void free_dentry (struct shim_dentry *dent) {
+static void free_dentry(struct shim_dentry* dent) {
     free_mem_obj_to_mgr(dentry_mgr, dent);
 }
 
@@ -124,7 +114,7 @@ static void free_dentry (struct shim_dentry *dent) {
  * If the ref count ever hits zero, we free the dentry.
  *
  */
-void put_dentry (struct shim_dentry * dent) {
+void put_dentry(struct shim_dentry* dent) {
     int count = REF_DEC(dent->ref_count);
     assert(count >= 0);
     // We don't expect this to commonly free a dentry, and may represent a
@@ -154,12 +144,9 @@ void put_dentry (struct shim_dentry * dent) {
  *
  * This function also sets up both a name and a relative path
  */
-struct shim_dentry * get_new_dentry (struct shim_mount *mount,
-                                     struct shim_dentry * parent,
-                                     const char * name, int namelen,
-                                     HASHTYPE * hashptr)
-{
-    struct shim_dentry * dent = alloc_dentry();
+struct shim_dentry* get_new_dentry(struct shim_mount* mount, struct shim_dentry* parent,
+                                   const char* name, int namelen, HASHTYPE* hashptr) {
+    struct shim_dentry* dent = alloc_dentry();
     HASHTYPE hash;
 
     if (!dent)
@@ -173,8 +160,9 @@ struct shim_dentry * get_new_dentry (struct shim_mount *mount,
         assert(*hashptr == hash_dentry(parent, name, namelen));
 #endif
         hash = *hashptr;
-    } else
+    } else {
         hash = hash_dentry(parent, name, namelen);
+    }
 
     qstrsetstr(&dent->name, name, namelen);
     dent->rel_path.hash = hash;
@@ -197,12 +185,13 @@ struct shim_dentry * get_new_dentry (struct shim_mount *mount,
         parent->nchildren++;
 
         if (!qstrempty(&parent->rel_path)) {
-            const char * strs[] = { qstrgetstr(&parent->rel_path), "/", name };
-            size_t lens[] = { parent->rel_path.len, 1, namelen };
+            const char* strs[] = {qstrgetstr(&parent->rel_path), "/", name};
+            size_t lens[]      = {parent->rel_path.len, 1, namelen};
             assert(lens[0] + lens[1] + lens[2] < STR_SIZE);
             qstrsetstrs(&dent->rel_path, 3, strs, lens);
-        } else
+        } else {
             qstrsetstr(&dent->rel_path, name, namelen);
+        }
     } else {
         qstrsetstr(&dent->rel_path, name, namelen);
     }
@@ -220,10 +209,8 @@ struct shim_dentry * get_new_dentry (struct shim_mount *mount,
  *
  * Used only by shim_namei.c
  */
-struct shim_dentry *
-__lookup_dcache (struct shim_dentry * start, const char * name, int namelen,
-                 HASHTYPE * hashptr) {
-
+struct shim_dentry* __lookup_dcache(struct shim_dentry* start, const char* name, int namelen,
+                                    HASHTYPE* hashptr) {
     /* In this implementation, we just look at the children
      * under the parent and see if there are matches.  It so,
      * return it; if not, don't.
@@ -239,7 +226,8 @@ __lookup_dcache (struct shim_dentry * start, const char * name, int namelen,
      * This mainly happens when boostrapping; in general, we assume the
      * caller will use the current root or cwd.
      */
-    if (!start) return NULL;
+    if (!start)
+        return NULL;
 
     /* If we are looking up an empty string, return start */
     if (namelen == 0) {
@@ -253,8 +241,8 @@ __lookup_dcache (struct shim_dentry * start, const char * name, int namelen,
          * reason for mount point lookup to fail, at least in this code.
          * Keeping a note just in case.  That is why you always leave a note.
          */
-        //if (dent->state & DENTRY_MOUNTPOINT)
-        //continue;
+        // if (dent->state & DENTRY_MOUNTPOINT)
+        //     continue;
 
         // Check for memory corruption
         assert((dent->state & DENTRY_INVALID_FLAGS) == 0);
@@ -266,10 +254,10 @@ __lookup_dcache (struct shim_dentry * start, const char * name, int namelen,
         /* I think comparing the relative path is adequate; with a global
          * hash table, a full path comparison may be needed, but I think
          * we can assume a parent has children with unique names */
-        const char * filename = get_file_name(name, namelen);
-        const char * dname = dentry_get_name(dent);
-        int dname_len = strlen(dname);
-        int fname_len = name + namelen - filename;
+        const char* filename = get_file_name(name, namelen);
+        const char* dname    = dentry_get_name(dent);
+        int dname_len        = strlen(dname);
+        int fname_len        = name + namelen - filename;
         if (dname_len != fname_len || memcmp(dname, filename, fname_len))
             continue;
 
@@ -295,7 +283,7 @@ out:
  * may be preferable to rewrite this using tail recursion or allocating a
  * structure on the heap to track progress.
  */
-int __del_dentry_tree(struct shim_dentry * root) {
+int __del_dentry_tree(struct shim_dentry* root) {
     struct shim_dentry *cursor, *n;
 
     LISTP_FOR_EACH_ENTRY_SAFE(cursor, n, &root->children, siblings) {
@@ -325,20 +313,19 @@ bool dentry_is_ancestor(struct shim_dentry* anc, struct shim_dentry* dent) {
     return false;
 }
 
-BEGIN_CP_FUNC(dentry)
-{
+BEGIN_CP_FUNC(dentry) {
     __UNUSED(size);
     assert(size == sizeof(struct shim_dentry));
 
-    struct shim_dentry * dent = (struct shim_dentry *) obj;
-    struct shim_dentry * new_dent = NULL;
+    struct shim_dentry* dent     = (struct shim_dentry*)obj;
+    struct shim_dentry* new_dent = NULL;
 
     ptr_t off = GET_FROM_CP_MAP(obj);
 
     if (!off) {
         off = ADD_CP_OFFSET(sizeof(struct shim_dentry));
         ADD_TO_CP_MAP(obj, off);
-        new_dent = (struct shim_dentry *) (base + off);
+        new_dent = (struct shim_dentry*)(base + off);
 
         lock(&dent->lock);
         *new_dent = *dent;
@@ -365,18 +352,17 @@ BEGIN_CP_FUNC(dentry)
         unlock(&dent->lock);
         ADD_CP_FUNC_ENTRY(off);
     } else {
-        new_dent = (struct shim_dentry *) (base + off);
+        new_dent = (struct shim_dentry*)(base + off);
     }
 
     if (objp)
-        *objp = (void *) new_dent;
+        *objp = (void*)new_dent;
 }
 END_CP_FUNC(dentry)
 
-BEGIN_RS_FUNC(dentry)
-{
+BEGIN_RS_FUNC(dentry) {
     __UNUSED(offset);
-    struct shim_dentry * dent = (void *) (base + GET_CP_FUNC_ENTRY());
+    struct shim_dentry* dent = (void*)(base + GET_CP_FUNC_ENTRY());
 
     CP_REBASE(dent->hlist);
     CP_REBASE(dent->list);
@@ -397,8 +383,7 @@ BEGIN_RS_FUNC(dentry)
         LISTP_ADD_TAIL(dent, &dent->parent->children, siblings);
     }
 
-    DEBUG_RS("hash=%08lx,path=%s,fs=%s", dent->rel_path.hash,
-             dentry_get_path(dent, true, NULL),
+    DEBUG_RS("hash=%08lx,path=%s,fs=%s", dent->rel_path.hash, dentry_get_path(dent, true, NULL),
              dent->fs ? qstrgetstr(&dent->fs->path) : NULL);
 }
 END_RS_FUNC(dentry)

+ 130 - 140
LibOS/shim/src/fs/shim_fs.c

@@ -20,46 +20,57 @@
  * This file contains codes for creating filesystems in library OS.
  */
 
-#include <shim_internal.h>
-#include <shim_utils.h>
-#include <shim_fs.h>
-#include <shim_checkpoint.h>
+#include <linux/fcntl.h>
 
+#include <list.h>
 #include <pal.h>
-#include <pal_error.h>
 #include <pal_debug.h>
-#include <list.h>
-
-#include <linux/fcntl.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];
-    struct shim_fs_ops * fs_ops;
-    struct shim_d_ops * d_ops;
+    struct shim_fs_ops* fs_ops;
+    struct shim_d_ops* d_ops;
 };
 
-#define NUM_MOUNTABLE_FS    3
-
-struct shim_fs mountable_fs [NUM_MOUNTABLE_FS] = {
-        { .name = "chroot", .fs_ops = &chroot_fs_ops, .d_ops = &chroot_d_ops, },
-        { .name = "proc",   .fs_ops = &proc_fs_ops,   .d_ops = &proc_d_ops,   },
-        { .name = "dev",    .fs_ops = &dev_fs_ops,    .d_ops = &dev_d_ops,    },
-    };
+#define NUM_MOUNTABLE_FS 3
+
+struct shim_fs mountable_fs[NUM_MOUNTABLE_FS] = {
+    {
+        .name   = "chroot",
+        .fs_ops = &chroot_fs_ops,
+        .d_ops  = &chroot_d_ops,
+    },
+    {
+        .name   = "proc",
+        .fs_ops = &proc_fs_ops,
+        .d_ops  = &proc_d_ops,
+    },
+    {
+        .name   = "dev",
+        .fs_ops = &dev_fs_ops,
+        .d_ops  = &dev_d_ops,
+    },
+};
 
-#define NUM_BUILTIN_FS      5
+#define NUM_BUILTIN_FS 5
 
-struct shim_mount * builtin_fs [NUM_BUILTIN_FS] = {
-                &chroot_builtin_fs,
-                &pipe_builtin_fs,
-                &socket_builtin_fs,
-                &epoll_builtin_fs,
-                &eventfd_builtin_fs,
-        };
+struct shim_mount* builtin_fs[NUM_BUILTIN_FS] = {
+    &chroot_builtin_fs,
+    &pipe_builtin_fs,
+    &socket_builtin_fs,
+    &epoll_builtin_fs,
+    &eventfd_builtin_fs,
+};
 
 static struct shim_lock mount_mgr_lock;
 
-#define SYSTEM_LOCK()       lock(&mount_mgr_lock)
-#define SYSTEM_UNLOCK()     unlock(&mount_mgr_lock)
+#define SYSTEM_LOCK()   lock(&mount_mgr_lock)
+#define SYSTEM_UNLOCK() unlock(&mount_mgr_lock)
 
 #define MOUNT_MGR_ALLOC 64
 
@@ -72,8 +83,7 @@ DEFINE_LISTP(shim_mount);
 static LISTP_TYPE(shim_mount) mount_list;
 static struct shim_lock mount_list_lock;
 
-int init_fs (void)
-{
+int init_fs(void) {
     mount_mgr = create_mem_mgr(init_align_up(MOUNT_MGR_ALLOC));
     if (!mount_mgr)
         return -ENOMEM;
@@ -83,22 +93,19 @@ int init_fs (void)
     return 0;
 }
 
-static struct shim_mount * alloc_mount (void)
-{
-    return get_mem_obj_from_mgr_enlarge(mount_mgr,
-                                        size_align_up(MOUNT_MGR_ALLOC));
+static struct shim_mount* alloc_mount(void) {
+    return get_mem_obj_from_mgr_enlarge(mount_mgr, size_align_up(MOUNT_MGR_ALLOC));
 }
 
 static bool mount_migrated = false;
 
-static int __mount_root (struct shim_dentry ** root)
-{
-    char type[CONFIG_MAX], uri[CONFIG_MAX];
+static int __mount_root(struct shim_dentry** root) {
+    char type[CONFIG_MAX];
+    char uri[CONFIG_MAX];
     int ret = 0;
 
-    if (root_config &&
-            get_config(root_config, "fs.root.type", type, sizeof(type)) > 0 &&
-            get_config(root_config, "fs.root.uri", uri, sizeof(uri)) > 0) {
+    if (root_config && get_config(root_config, "fs.root.type", type, sizeof(type)) > 0 &&
+                       get_config(root_config, "fs.root.uri", uri, sizeof(uri)) > 0) {
         debug("mounting root filesystem: %s from %s\n", type, uri);
         if ((ret = mount_fs(type, uri, "/", NULL, root, 0)) < 0) {
             debug("mounting root filesystem failed (%d)\n", ret);
@@ -114,8 +121,7 @@ static int __mount_root (struct shim_dentry ** root)
     return ret;
 }
 
-static int __mount_sys (struct shim_dentry *root)
-{
+static int __mount_sys(struct shim_dentry* root) {
     int ret;
 
     debug("mounting as proc filesystem: /proc\n");
@@ -127,7 +133,7 @@ static int __mount_sys (struct shim_dentry *root)
 
     debug("mounting as dev filesystem: /dev\n");
 
-    struct shim_dentry *dev_dent = NULL;
+    struct shim_dentry* dev_dent = NULL;
     if ((ret = mount_fs("dev", NULL, "/dev", root, &dev_dent, 0)) < 0) {
         debug("mounting dev filesystem failed (%d)\n", ret);
         return ret;
@@ -143,19 +149,20 @@ static int __mount_sys (struct shim_dentry *root)
     return 0;
 }
 
-static int __mount_one_other (const char * key, int keylen)
-{
+static int __mount_one_other(const char* key, int keylen) {
     if (!root_config)
         return 0;
 
-    char k[CONFIG_MAX], p[CONFIG_MAX], u[CONFIG_MAX],
-         t[CONFIG_MAX];
-    char * uri = NULL;
+    char k[CONFIG_MAX];
+    char p[CONFIG_MAX];
+    char u[CONFIG_MAX];
+    char t[CONFIG_MAX];
+    char* uri = NULL;
     int ret;
 
     memcpy(k, "fs.mount.", 9);
     memcpy(k + 9, key, keylen);
-    char * kp = k + 9 + keylen;
+    char* kp = k + 9 + keylen;
 
     memcpy(kp, ".path", 6);
     if (get_config(root_config, k, p, sizeof(p)) <= 0)
@@ -172,17 +179,15 @@ static int __mount_one_other (const char * key, int keylen)
     debug("mounting as %s filesystem: from %s to %s\n", t, uri, p);
 
     if ((ret = mount_fs(t, uri, p, NULL, NULL, 1)) < 0) {
-        debug("mounting %s on %s (type=%s) failed (%d)\n", uri, p, t,
-              -ret);
+        debug("mounting %s on %s (type=%s) failed (%d)\n", uri, p, t, -ret);
         return ret;
     }
 
     return 0;
 }
 
-static int __mount_others (void)
-{
-    char * keybuf;
+static int __mount_others(void) {
+    char* keybuf;
     int ret = 0;
 
     if (!root_config)
@@ -203,9 +208,11 @@ static int __mount_others (void)
     if (nkeys <= 0)
         goto out;
 
-    const char * key = keybuf, * next = NULL;
-    for (int n = 0 ; n < nkeys ; key = next, n++) {
-        for (next = key ; *next ; next++);
+    const char *key = keybuf;
+    const char *next = NULL;
+    for (int n = 0; n < nkeys; key = next, n++) {
+        for (next = key; *next; next++)
+            ;
         next++;
         ret = __mount_one_other(key, next - key - 1);
         if (ret < 0)
@@ -217,13 +224,12 @@ out:
     return ret;
 }
 
-int init_mount_root (void)
-{
+int init_mount_root(void) {
     if (mount_migrated)
         return 0;
 
     int ret;
-    struct shim_dentry *root = NULL;
+    struct shim_dentry* root = NULL;
 
     if ((ret = __mount_root(&root)) < 0)
         return ret;
@@ -234,8 +240,7 @@ int init_mount_root (void)
     return 0;
 }
 
-int init_mount (void)
-{
+int init_mount(void) {
     if (mount_migrated)
         return 0;
 
@@ -247,12 +252,11 @@ int init_mount (void)
     return 0;
 }
 
-static inline struct shim_fs * find_fs (const char * type)
-{
-    struct shim_fs * fs = NULL;
+static inline struct shim_fs* find_fs(const char* type) {
+    struct shim_fs* fs = NULL;
     size_t len = strlen(type);
 
-    for (int i = 0 ; i < NUM_MOUNTABLE_FS ; i++)
+    for (int i = 0; i < NUM_MOUNTABLE_FS; i++)
         if (!memcmp(type, mountable_fs[i].name, len + 1)) {
             fs = &mountable_fs[i];
             break;
@@ -261,11 +265,10 @@ static inline struct shim_fs * find_fs (const char * type)
     return fs;
 }
 
-int search_builtin_fs (const char * type, struct shim_mount ** fs)
-{
+int search_builtin_fs(const char* type, struct shim_mount** fs) {
     size_t len = strlen(type);
 
-    for (int i = 0 ; i < NUM_BUILTIN_FS ; i++)
+    for (int i = 0; i < NUM_BUILTIN_FS; i++)
         if (!memcmp(type, builtin_fs[i]->type, len + 1)) {
             *fs = builtin_fs[i];
             return 0;
@@ -274,16 +277,15 @@ int search_builtin_fs (const char * type, struct shim_mount ** fs)
     return -ENOENT;
 }
 
-int __mount_fs (struct shim_mount * mount, struct shim_dentry * dent)
-{
+int __mount_fs(struct shim_mount* mount, struct shim_dentry* dent) {
     int ret = 0;
 
     dent->state |= DENTRY_MOUNTPOINT;
     get_dentry(dent);
     mount->mount_point = dent;
-    dent->mounted = mount;
+    dent->mounted      = mount;
 
-    struct shim_dentry * mount_root = mount->root;
+    struct shim_dentry* mount_root = mount->root;
 
     if (!mount_root) {
         /* mount_root->state |= DENTRY_VALID; */
@@ -307,7 +309,7 @@ int __mount_fs (struct shim_mount * mount, struct shim_dentry * dent)
     /* DEP 6/16/17: In the dcache redesign, we don't use the *REACHABLE flags, but
      * leaving this commented for documentation, in case there is a problem
      * I over-simplified */
-    //mount_root->state |= dent->state & (DENTRY_REACHABLE|DENTRY_UNREACHABLE);
+    // mount_root->state |= dent->state & (DENTRY_REACHABLE|DENTRY_UNREACHABLE);
 
     /* DEP 6/16/17: In the dcache redesign, I don't believe we need to manually
      * rehash the path; this should be handled by get_new_dentry, or already be
@@ -325,7 +327,7 @@ int __mount_fs (struct shim_mount * mount, struct shim_dentry * dent)
     unlock(&mount_list_lock);
 
     do {
-        struct shim_dentry * parent = dent->parent;
+        struct shim_dentry* parent = dent->parent;
 
         if (dent->state & DENTRY_ANCESTOR) {
             put_dentry(dent);
@@ -339,14 +341,12 @@ int __mount_fs (struct shim_mount * mount, struct shim_dentry * dent)
         dent = parent;
     } while (dent);
 
-
     return 0;
 }
 
-// Extracts the last component of the `path`. If there's none, `*last_elem_len`
-// is set to 0 and `*last_elem` is set to NULL.
-static void find_last_component(const char* path, const char** last_comp,
-                                size_t* last_comp_len) {
+/* Extracts the last component of the `path`. If there's none, `*last_elem_len` is set to 0 and
+ * `*last_elem` is set to NULL. */
+static void find_last_component(const char* path, const char** last_comp, size_t* last_comp_len) {
     *last_comp = NULL;
     size_t last_len = 0;
     size_t path_len = strlen(path);
@@ -362,7 +362,7 @@ static void find_last_component(const char* path, const char** last_comp,
 
     // Skip the last component.
     last_len = 1;
-    while (last > path && *(last-1) != '/') {
+    while (last > path && *(last - 1) != '/') {
         last--;
         last_len++;
     }
@@ -374,16 +374,14 @@ out:
 /* Parent is optional, but helpful.
  * dentp (optional) memoizes the dentry of the newly-mounted FS, on success.
  *
- * The make_ancestor flag creates pseudo-dentries for any missing paths (passed to
- * __path_lookupat).  This is only intended for use to connect mounts specified in the manifest
- * when an intervening path is missing.
+ * The make_ancestor flag creates pseudo-dentries for any missing paths (passed to __path_lookupat).
+ * This is only intended for use to connect mounts specified in the manifest when an intervening
+ * path is missing.
  */
-int mount_fs (const char * type, const char * uri, const char * mount_point,
-              struct shim_dentry *parent, struct shim_dentry **dentp,
-              bool make_ancestor)
-{
+int mount_fs(const char* type, const char* uri, const char* mount_point, struct shim_dentry* parent,
+             struct shim_dentry** dentp, bool make_ancestor) {
     int ret = 0;
-    struct shim_fs * fs = find_fs(type);
+    struct shim_fs* fs = find_fs(type);
 
     if (!fs || !fs->fs_ops || !fs->fs_ops->mount) {
         ret = -ENODEV;
@@ -405,11 +403,11 @@ int mount_fs (const char * type, const char * uri, const char * mount_point,
         if (last_len > 0) {
             // Look up the parent
             size_t parent_len = last - mount_point;
-            char * parent_path = __alloca(parent_len + 1);
+            char* parent_path = __alloca(parent_len + 1);
             memcpy(parent_path, mount_point, parent_len);
             parent_path[parent_len] = 0;
-            if ((ret = __path_lookupat(dentry_root, parent_path, 0, &parent, 0,
-                                       dentry_root->fs, make_ancestor)) < 0) {
+            if ((ret = __path_lookupat(dentry_root, parent_path, 0, &parent, 0, dentry_root->fs,
+                                       make_ancestor)) < 0) {
                 debug("Path lookup failed %d\n", ret);
                 goto out;
             }
@@ -428,24 +426,24 @@ int mount_fs (const char * type, const char * uri, const char * mount_point,
 
     lock(&dcache_lock);
 
-    struct shim_mount * mount = alloc_mount();
-    void * mount_data = NULL;
+    struct shim_mount* mount = alloc_mount();
+    void* mount_data         = NULL;
 
     /* call fs-specific mount to allocate mount_data */
     if ((ret = fs->fs_ops->mount(uri, &mount_data)) < 0)
         goto out_with_unlock;
 
-
     size_t uri_len = uri ? strlen(uri) : 0;
     qstrsetstr(&mount->path, mount_point, mount_point_len);
     qstrsetstr(&mount->uri, uri, uri_len);
     memcpy(mount->type, fs->name, sizeof(fs->name));
-    mount->fs_ops    = fs->fs_ops;
-    mount->d_ops     = fs->d_ops;
-    mount->data      = mount_data;
+    mount->fs_ops = fs->fs_ops;
+    mount->d_ops  = fs->d_ops;
+    mount->data   = mount_data;
 
     /* Get the negative dentry from the cache, if one exists */
-    struct shim_dentry * dent, *dent2;
+    struct shim_dentry* dent;
+    struct shim_dentry* dent2;
     /* Special case the root */
     if (last_len == 0)
         dent = dentry_root;
@@ -465,8 +463,8 @@ int mount_fs (const char * type, const char * uri, const char * mount_point,
     mount->path.hash = dent->rel_path.hash;
 
     /*Now go ahead and do a lookup so the dentry is valid */
-    if ((ret = __path_lookupat(dentry_root, mount_point, 0, &dent2, 0,
-                               parent ? parent->fs : mount, make_ancestor)) < 0)
+    if ((ret = __path_lookupat(dentry_root, mount_point, 0, &dent2, 0, parent ? parent->fs : mount,
+                               make_ancestor)) < 0)
         goto out_with_unlock;
 
     assert(dent == dent2);
@@ -495,27 +493,24 @@ out:
     return ret;
 }
 
-void get_mount (struct shim_mount * mount)
-{
+void get_mount(struct shim_mount* mount) {
     REF_INC(mount->ref_count);
 }
 
-void put_mount (struct shim_mount * mount)
-{
+void put_mount(struct shim_mount* mount) {
     REF_DEC(mount->ref_count);
 }
 
-int walk_mounts (int (*walk) (struct shim_mount * mount, void * arg),
-                 void * arg)
-{
-    struct shim_mount * mount, * n;
+int walk_mounts(int (*walk)(struct shim_mount* mount, void* arg), void* arg) {
+    struct shim_mount* mount;
+    struct shim_mount* n;
     int ret = 0;
     int nsrched = 0;
 
     lock(&mount_list_lock);
 
     LISTP_FOR_EACH_ENTRY_SAFE(mount, n, &mount_list, list) {
-        if ((ret = (*walk) (mount, arg)) < 0)
+        if ((ret = (*walk)(mount, arg)) < 0)
             break;
 
         if (ret > 0)
@@ -526,9 +521,9 @@ int walk_mounts (int (*walk) (struct shim_mount * mount, void * arg),
     return ret < 0 ? ret : (nsrched ? 0 : -ESRCH);
 }
 
-struct shim_mount * find_mount_from_uri (const char * uri)
-{
-    struct shim_mount * mount, * found = NULL;
+struct shim_mount* find_mount_from_uri(const char* uri) {
+    struct shim_mount* mount;
+    struct shim_mount* found = NULL;
     size_t longest_path = 0;
 
     lock(&mount_list_lock);
@@ -536,8 +531,7 @@ struct shim_mount * find_mount_from_uri (const char * uri)
         if (qstrempty(&mount->uri))
             continue;
 
-        if (!memcmp(qstrgetstr(&mount->uri), uri, mount->uri.len) &&
-            uri[mount->uri.len] == '/') {
+        if (!memcmp(qstrgetstr(&mount->uri), uri, mount->uri.len) && uri[mount->uri.len] == '/') {
             if (mount->path.len > longest_path) {
                 longest_path = mount->path.len;
                 found = mount;
@@ -552,13 +546,12 @@ struct shim_mount * find_mount_from_uri (const char * uri)
     return found;
 }
 
-BEGIN_CP_FUNC(mount)
-{
+BEGIN_CP_FUNC(mount) {
     __UNUSED(size);
     assert(size == sizeof(struct shim_mount));
 
-    struct shim_mount * mount = (struct shim_mount *) obj;
-    struct shim_mount * new_mount = NULL;
+    struct shim_mount* mount     = (struct shim_mount*)obj;
+    struct shim_mount* new_mount = NULL;
 
     ptr_t off = GET_FROM_CP_MAP(obj);
 
@@ -568,7 +561,7 @@ BEGIN_CP_FUNC(mount)
 
         mount->cpdata = NULL;
         if (mount->fs_ops && mount->fs_ops->checkpoint) {
-            void * cpdata = NULL;
+            void* cpdata = NULL;
             int bytes = mount->fs_ops->checkpoint(&cpdata, mount->data);
             if (bytes > 0) {
                 mount->cpdata = cpdata;
@@ -576,19 +569,19 @@ BEGIN_CP_FUNC(mount)
             }
         }
 
-        new_mount = (struct shim_mount *) (base + off);
+        new_mount  = (struct shim_mount*)(base + off);
         *new_mount = *mount;
 
         if (mount->cpdata) {
-            struct shim_mem_entry * entry;
+            struct shim_mem_entry* entry;
             DO_CP_SIZE(memory, mount->cpdata, mount->cpsize, &entry);
             new_mount->cpdata = NULL;
             entry->paddr = &new_mount->cpdata;
         }
 
-        new_mount->data = NULL;
+        new_mount->data        = NULL;
         new_mount->mount_point = NULL;
-        new_mount->root = NULL;
+        new_mount->root        = NULL;
         INIT_LIST_HEAD(new_mount, list);
 
         DO_CP_IN_MEMBER(qstr, new_mount, path);
@@ -602,35 +595,34 @@ BEGIN_CP_FUNC(mount)
 
         ADD_CP_FUNC_ENTRY(off);
     } else {
-        new_mount = (struct shim_mount *) (base + off);
+        new_mount = (struct shim_mount*)(base + off);
     }
 
     if (objp)
-        *objp = (void *) new_mount;
+        *objp = (void*)new_mount;
 }
 END_CP_FUNC(mount)
 
-BEGIN_RS_FUNC(mount)
-{
+BEGIN_RS_FUNC(mount) {
     __UNUSED(offset);
-    struct shim_mount * mount = (void *) (base + GET_CP_FUNC_ENTRY());
+    struct shim_mount* mount = (void*)(base + GET_CP_FUNC_ENTRY());
 
     CP_REBASE(mount->cpdata);
     CP_REBASE(mount->list);
     CP_REBASE(mount->mount_point);
     CP_REBASE(mount->root);
 
-    struct shim_fs * fs = find_fs(mount->type);
+    struct shim_fs* fs = find_fs(mount->type);
 
     if (fs && fs->fs_ops && fs->fs_ops->migrate && mount->cpdata) {
-        void * mount_data = NULL;
+        void* mount_data = NULL;
         if (fs->fs_ops->migrate(mount->cpdata, &mount_data) == 0)
             mount->data = mount_data;
         mount->cpdata = NULL;
     }
 
     mount->fs_ops = fs->fs_ops;
-    mount->d_ops = fs->d_ops;
+    mount->d_ops  = fs->d_ops;
 
     LISTP_ADD_TAIL(mount, &mount_list, list);
 
@@ -643,15 +635,15 @@ BEGIN_RS_FUNC(mount)
 }
 END_RS_FUNC(mount)
 
-BEGIN_CP_FUNC(all_mounts)
-{
+BEGIN_CP_FUNC(all_mounts) {
     __UNUSED(obj);
     __UNUSED(size);
     __UNUSED(objp);
-    struct shim_mount * mount;
+    struct shim_mount* mount;
     lock(&mount_list_lock);
-    LISTP_FOR_EACH_ENTRY(mount, &mount_list, list)
+    LISTP_FOR_EACH_ENTRY(mount, &mount_list, list) {
         DO_CP(mount, mount, NULL);
+    }
     unlock(&mount_list_lock);
 
     /* add an empty entry to mark as migrated */
@@ -659,8 +651,7 @@ BEGIN_CP_FUNC(all_mounts)
 }
 END_CP_FUNC(all_mounts)
 
-BEGIN_RS_FUNC(all_mounts)
-{
+BEGIN_RS_FUNC(all_mounts) {
     __UNUSED(entry);
     __UNUSED(base);
     __UNUSED(offset);
@@ -670,9 +661,8 @@ BEGIN_RS_FUNC(all_mounts)
 }
 END_RS_FUNC(all_mounts)
 
-const char * get_file_name (const char * path, size_t len)
-{
-    const char * c = path + len - 1;
+const char* get_file_name(const char* path, size_t len) {
+    const char* c = path + len - 1;
     while (c > path && *c != '/')
         c--;
     return *c == '/' ? c + 1 : c;

+ 2 - 1
LibOS/shim/src/fs/shim_namei.c

@@ -649,8 +649,9 @@ int dentry_open (struct shim_handle * hdl, struct shim_dentry * dent,
         if (dent->parent) {
             get_dentry(dent->parent);
             hdl->dir_info.dotdot = dent->parent;
-        } else
+        } else {
             hdl->dir_info.dotdot = NULL;
+        }
 
         // Let's defer setting the DENTRY_LISTED flag until we need it
         // Use -1 to indicate that the buf/ptr isn't initialized

+ 155 - 168
LibOS/shim/src/ipc/shim_ipc_helper.c

@@ -17,26 +17,25 @@
 /*
  * shim_ipc_helper.c
  *
- * This file contains code to create an IPC helper thread inside library OS
- * and maintain bookkeeping of IPC ports.
+ * This file contains code to create an IPC helper thread inside library OS and maintain bookkeeping
+ * of IPC ports.
  */
 
-#include <shim_internal.h>
-#include <shim_utils.h>
-#include <shim_thread.h>
+#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_checkpoint.h>
 #include <shim_profile.h>
-
-#include <pal.h>
-#include <pal_error.h>
-#include <list.h>
+#include <shim_thread.h>
+#include <shim_utils.h>
 
 #define IPC_HELPER_STACK_SIZE (g_pal_alloc_align * 4)
 
-#define PORT_MGR_ALLOC  32
-#define OBJ_TYPE struct shim_ipc_port
+#define PORT_MGR_ALLOC 32
+#define OBJ_TYPE       struct shim_ipc_port
 #include "memmgr.h"
 static MEM_MGR port_mgr;
 
@@ -46,7 +45,7 @@ static LISTP_TYPE(shim_ipc_port) port_list;
 static enum { HELPER_NOTALIVE, HELPER_ALIVE } ipc_helper_state;
 
 static struct shim_thread* ipc_helper_thread;
-static struct shim_lock    ipc_helper_lock;
+static struct shim_lock ipc_helper_lock;
 
 static AEVENTTYPE install_new_event;
 
@@ -54,38 +53,38 @@ static int create_ipc_helper(void);
 static int ipc_resp_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port);
 
 static ipc_callback ipc_callbacks[IPC_CODE_NUM] = {
-    /* RESP             */  &ipc_resp_callback,
-    /* CHECKPOINT       */  &ipc_checkpoint_callback,
+    /* RESP             */ &ipc_resp_callback,
+    /* CHECKPOINT       */ &ipc_checkpoint_callback,
 
     /* parents and children */
-    /* CLD_EXIT         */  &ipc_cld_exit_callback,
+    /* CLD_EXIT         */ &ipc_cld_exit_callback,
 
 #ifdef PROFILE
-    /* CLD_PROFILE      */  &ipc_cld_profile_callback,
+    /* CLD_PROFILE      */ &ipc_cld_profile_callback,
 #endif
 
     /* pid namespace */
     IPC_NS_CALLBACKS(pid)
-    /* PID_KILL         */  &ipc_pid_kill_callback,
-    /* PID_GETSTATUS    */  &ipc_pid_getstatus_callback,
-    /* PID_RETSTATUS    */  &ipc_pid_retstatus_callback,
-    /* PID_GETMETA      */  &ipc_pid_getmeta_callback,
-    /* PID_RETMETA      */  &ipc_pid_retmeta_callback,
-    /* PID_NOP          */  &ipc_pid_nop_callback,
-    /* PID_SENDRPC      */  &ipc_pid_sendrpc_callback,
+    /* PID_KILL         */ &ipc_pid_kill_callback,
+    /* PID_GETSTATUS    */ &ipc_pid_getstatus_callback,
+    /* PID_RETSTATUS    */ &ipc_pid_retstatus_callback,
+    /* PID_GETMETA      */ &ipc_pid_getmeta_callback,
+    /* PID_RETMETA      */ &ipc_pid_retmeta_callback,
+    /* PID_NOP          */ &ipc_pid_nop_callback,
+    /* PID_SENDRPC      */ &ipc_pid_sendrpc_callback,
 
     /* sysv namespace */
     IPC_NS_CALLBACKS(sysv)
     IPC_NS_KEY_CALLBACKS(sysv)
-    /* SYSV_DELRES      */  &ipc_sysv_delres_callback,
-    /* SYSV_MOVRES      */  &ipc_sysv_movres_callback,
-    /* SYSV_MSGSND      */  &ipc_sysv_msgsnd_callback,
-    /* SYSV_MSGRCV      */  &ipc_sysv_msgrcv_callback,
-    /* SYSV_MSGMOV      */  &ipc_sysv_msgmov_callback,
-    /* SYSV_SEMOP       */  &ipc_sysv_semop_callback,
-    /* SYSV_SEMCTL      */  &ipc_sysv_semctl_callback,
-    /* SYSV_SEMRET      */  &ipc_sysv_semret_callback,
-    /* SYSV_SEMMOV      */  &ipc_sysv_semmov_callback,
+    /* SYSV_DELRES      */ &ipc_sysv_delres_callback,
+    /* SYSV_MOVRES      */ &ipc_sysv_movres_callback,
+    /* SYSV_MSGSND      */ &ipc_sysv_msgsnd_callback,
+    /* SYSV_MSGRCV      */ &ipc_sysv_msgrcv_callback,
+    /* SYSV_MSGMOV      */ &ipc_sysv_msgmov_callback,
+    /* SYSV_SEMOP       */ &ipc_sysv_semop_callback,
+    /* SYSV_SEMCTL      */ &ipc_sysv_semctl_callback,
+    /* SYSV_SEMRET      */ &ipc_sysv_semret_callback,
+    /* SYSV_SEMMOV      */ &ipc_sysv_semmov_callback,
 };
 
 static int init_self_ipc_port(void) {
@@ -102,11 +101,8 @@ static int init_self_ipc_port(void) {
         /* execve case: inherited IPC port from parent process */
         assert(cur_process.self->pal_handle && !qstrempty(&cur_process.self->uri));
 
-        add_ipc_port_by_id(cur_process.self->vmid,
-                           cur_process.self->pal_handle,
-                           IPC_PORT_SERVER,
-                           /*fini=*/NULL,
-                           &cur_process.self->port);
+        add_ipc_port_by_id(cur_process.self->vmid, cur_process.self->pal_handle, IPC_PORT_SERVER,
+                           /*fini=*/NULL, &cur_process.self->port);
     }
 
     unlock(&cur_process.lock);
@@ -122,19 +118,17 @@ static int init_parent_ipc_port(void) {
     lock(&cur_process.lock);
     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 cur_process.parent) */
+    /* 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 
+     * cur_process.parent) */
     if (!cur_process.parent->pal_handle) {
         /* for clone/fork case, parent is connected on parent_process */
         cur_process.parent->pal_handle = PAL_CB(parent_process);
     }
 
-    add_ipc_port_by_id(cur_process.parent->vmid,
-                       cur_process.parent->pal_handle,
+    add_ipc_port_by_id(cur_process.parent->vmid, cur_process.parent->pal_handle,
                        IPC_PORT_DIRPRT | IPC_PORT_LISTEN,
-                       /*fini=*/NULL,
-                       &cur_process.parent->port);
+                       /*fini=*/NULL, &cur_process.parent->port);
 
     unlock(&cur_process.lock);
     return 0;
@@ -147,9 +141,8 @@ static int init_ns_ipc_port(int ns_idx) {
     }
 
     if (!cur_process.ns[ns_idx]->pal_handle && qstrempty(&cur_process.ns[ns_idx]->uri)) {
-        /* there is no connection to NS leader via PAL handle and there is no
-         * URI to find NS leader: do not create NS IPC port now, it will be
-         * created on-demand during NS leader lookup */
+        /* there is no connection to NS leader via PAL handle and there is no URI to find NS leader:
+         * do not create NS IPC port now, it will be created on-demand during NS leader lookup */
         return 0;
     }
 
@@ -157,7 +150,8 @@ static int init_ns_ipc_port(int ns_idx) {
 
     if (!cur_process.ns[ns_idx]->pal_handle) {
         debug("Reconnecting IPC port %s\n", qstrgetstr(&cur_process.ns[ns_idx]->uri));
-        cur_process.ns[ns_idx]->pal_handle = DkStreamOpen(qstrgetstr(&cur_process.ns[ns_idx]->uri), 0, 0, 0, 0);
+        cur_process.ns[ns_idx]->pal_handle =
+            DkStreamOpen(qstrgetstr(&cur_process.ns[ns_idx]->uri), 0, 0, 0, 0);
         if (!cur_process.ns[ns_idx]->pal_handle) {
             unlock(&cur_process.lock);
             return -PAL_ERRNO;
@@ -165,11 +159,9 @@ static int init_ns_ipc_port(int ns_idx) {
     }
 
     IDTYPE type = (ns_idx == PID_NS) ? IPC_PORT_PIDLDR : IPC_PORT_SYSVLDR;
-    add_ipc_port_by_id(cur_process.ns[ns_idx]->vmid,
-                       cur_process.ns[ns_idx]->pal_handle,
+    add_ipc_port_by_id(cur_process.ns[ns_idx]->vmid, cur_process.ns[ns_idx]->pal_handle,
                        type | IPC_PORT_LISTEN,
-                       /*fini=*/NULL,
-                       &cur_process.ns[ns_idx]->port);
+                       /*fini=*/NULL, &cur_process.ns[ns_idx]->port);
 
     unlock(&cur_process.lock);
     return 0;
@@ -192,16 +184,14 @@ int init_ipc_ports(void) {
     return 0;
 }
 
-
 int init_ipc_helper(void) {
     /* early enough in init, can write global vars without the lock */
     ipc_helper_state = HELPER_NOTALIVE;
     create_lock(&ipc_helper_lock);
     create_event(&install_new_event);
 
-    /* some IPC ports were already added before this point, so spawn IPC
-     * helper thread (and enable locking mechanisms if not done already
-     * since we are going in multi-threaded mode) */
+    /* some IPC ports were already added before this point, so spawn IPC helper thread (and enable
+     * locking mechanisms if not done already since we are going in multi-threaded mode) */
     enable_locking();
     lock(&ipc_helper_lock);
     create_ipc_helper();
@@ -261,8 +251,7 @@ void put_ipc_port(struct shim_ipc_port* port) {
     }
 }
 
-static void __add_ipc_port(struct shim_ipc_port* port, IDTYPE vmid,
-                           IDTYPE type, port_fini fini) {
+static void __add_ipc_port(struct shim_ipc_port* port, IDTYPE vmid, IDTYPE type, port_fini fini) {
     port->type |= type;
     if (vmid && !port->vmid)
         port->vmid = vmid;
@@ -273,7 +262,7 @@ static void __add_ipc_port(struct shim_ipc_port* port, IDTYPE vmid,
         __UNUSED(found_empty_slot);
         for (int i = 0; i < MAX_IPC_PORT_FINI_CB; i++)
             if (!port->fini[i] || port->fini[i] == fini) {
-                port->fini[i] = fini;
+                port->fini[i]    = fini;
                 found_empty_slot = true;
                 break;
             }
@@ -292,8 +281,8 @@ static void __add_ipc_port(struct shim_ipc_port* port, IDTYPE vmid,
 }
 
 static void __del_ipc_port(struct shim_ipc_port* port) {
-    debug("Deleting port %p (handle %p) of process %u\n",
-          port, port->pal_handle, port->vmid & 0xFFFF);
+    debug("Deleting port %p (handle %p) of process %u\n", port, port->pal_handle,
+          port->vmid & 0xFFFF);
 
     DkStreamDelete(port->pal_handle, 0);
     LISTP_DEL_INIT(port, &port_list, list);
@@ -306,8 +295,8 @@ static void __del_ipc_port(struct shim_ipc_port* port) {
         LISTP_DEL_INIT(msg, &port->msgs, list);
         msg->retval = -ECONNRESET;
         if (msg->thread) {
-            debug("Deleted pending message on port %p, wake up blocking thread %d\n",
-                  port, msg->thread->tid);
+            debug("Deleted pending message on port %p, wake up blocking thread %d\n", port,
+                  msg->thread->tid);
             thread_wakeup(msg->thread);
         }
     }
@@ -321,18 +310,17 @@ static void __del_ipc_port(struct shim_ipc_port* port) {
 }
 
 void add_ipc_port(struct shim_ipc_port* port, IDTYPE vmid, IDTYPE type, port_fini fini) {
-    debug("Adding port %p (handle %p) for process %u (type=%04x)\n",
-          port, port->pal_handle, port->vmid & 0xFFFF, type);
+    debug("Adding port %p (handle %p) for process %u (type=%04x)\n", port, port->pal_handle,
+          port->vmid & 0xFFFF, type);
 
     lock(&ipc_helper_lock);
     __add_ipc_port(port, vmid, type, fini);
     unlock(&ipc_helper_lock);
 }
 
-void add_ipc_port_by_id(IDTYPE vmid, PAL_HANDLE hdl, IDTYPE type,
-                        port_fini fini, struct shim_ipc_port** portptr) {
-    debug("Adding port (handle %p) for process %u (type %04x)\n",
-            hdl, vmid & 0xFFFF, type);
+void add_ipc_port_by_id(IDTYPE vmid, PAL_HANDLE hdl, IDTYPE type, port_fini fini,
+                        struct shim_ipc_port** portptr) {
+    debug("Adding port (handle %p) for process %u (type %04x)\n", hdl, vmid & 0xFFFF, type);
 
     struct shim_ipc_port* port = NULL;
     if (portptr)
@@ -341,14 +329,15 @@ void add_ipc_port_by_id(IDTYPE vmid, PAL_HANDLE hdl, IDTYPE type,
     assert(hdl);
     lock(&ipc_helper_lock);
 
-    /* check if port with this PAL handle already exists, then we only
-     * need to update its vmid, type, and fini callback */
+    /* check if port with this PAL handle already exists, then we only need to update its vmid,
+     * type, and fini callback */
     struct shim_ipc_port* tmp;
-    LISTP_FOR_EACH_ENTRY(tmp, &port_list, list)
+    LISTP_FOR_EACH_ENTRY(tmp, &port_list, list) {
         if (tmp->pal_handle == hdl) {
             port = tmp;
             break;
         }
+    }
 
     if (!port) {
         /* port does not yet exist, create it */
@@ -399,8 +388,9 @@ void del_all_ipc_ports(void) {
 
     struct shim_ipc_port* port;
     struct shim_ipc_port* tmp;
-    LISTP_FOR_EACH_ENTRY_SAFE(port, tmp, &port_list, list)
+    LISTP_FOR_EACH_ENTRY_SAFE(port, tmp, &port_list, list) {
         __del_ipc_port(port);
+    }
 
     unlock(&ipc_helper_lock);
 }
@@ -414,8 +404,8 @@ struct shim_ipc_port* lookup_ipc_port(IDTYPE vmid, IDTYPE type) {
     struct shim_ipc_port* tmp;
     LISTP_FOR_EACH_ENTRY(tmp, &port_list, list) {
         if (tmp->vmid == vmid && (tmp->type & type)) {
-            debug("Found port %p (handle %p) for process %u (type %04x)\n",
-                  tmp, tmp->pal_handle, tmp->vmid & 0xFFFF, tmp->type);
+            debug("Found port %p (handle %p) for process %u (type %04x)\n", tmp, tmp->pal_handle,
+                  tmp->vmid & 0xFFFF, tmp->type);
             port = tmp;
             __get_ipc_port(port);
             break;
@@ -437,9 +427,9 @@ int broadcast_ipc(struct shim_ipc_msg* msg, int target_type, struct shim_ipc_por
     assert(target_type);
     lock(&ipc_helper_lock);
 
-    /* Collect all ports with appropriate types. In common case, stack-allocated
-     * array of PORTS_ON_STACK_CNT ports is enough. If there are more ports, we
-     * will allocate a bigger array on the heap and collect all ports again. */
+    /* Collect all ports with appropriate types. In common case, stack-allocated array of
+     * PORTS_ON_STACK_CNT ports is enough. If there are more ports, we will allocate a bigger array
+     * on the heap and collect all ports again. */
     struct shim_ipc_port* target_ports_stack[PORTS_ON_STACK_CNT];
     LISTP_FOR_EACH_ENTRY(port, &port_list, list) {
         if (port == exclude_port)
@@ -453,11 +443,11 @@ int broadcast_ipc(struct shim_ipc_msg* msg, int target_type, struct shim_ipc_por
     target_ports = target_ports_stack;
 
     if (target_ports_cnt > PORTS_ON_STACK_CNT) {
-        /* Rare case when there are more than PORTS_ON_STACK_CNT ports. Allocate
-         * big-enough array on the heap and collect all ports again. */
+        /* Rare case when there are more than PORTS_ON_STACK_CNT ports. Allocate big-enough array on
+         * the heap and collect all ports again. */
         size_t cnt = 0;
         struct shim_ipc_port** target_ports_heap =
-            malloc(sizeof(struct shim_ipc_port *) * target_ports_cnt);
+            malloc(sizeof(struct shim_ipc_port*) * target_ports_cnt);
 
         LISTP_FOR_EACH_ENTRY(port, &port_list, list) {
             if (port == exclude_port)
@@ -500,7 +490,7 @@ out:
 }
 
 static int ipc_resp_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) {
-    struct shim_ipc_resp* resp = (struct shim_ipc_resp*) &msg->msg;
+    struct shim_ipc_resp* resp = (struct shim_ipc_resp*)&msg->msg;
     debug("IPC callback from %u: IPC_RESP(%d)\n", msg->src & 0xFFFF, resp->retval);
 
     if (!msg->seq)
@@ -524,12 +514,12 @@ int send_response_ipc_message(struct shim_ipc_port* port, IDTYPE dest, int ret,
     ret = (ret == RESPONSE_CALLBACK) ? 0 : ret;
 
     /* create IPC_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_RESP, total_msg_size, dest);
     resp_msg->seq = seq;
 
-    struct shim_ipc_resp* resp = (struct shim_ipc_resp *)resp_msg->msg;
+    struct shim_ipc_resp* resp = (struct shim_ipc_resp*)resp_msg->msg;
     resp->retval = ret;
 
     debug("IPC send to %u: IPC_RESP(%d)\n", resp_msg->dst & 0xFFFF, ret);
@@ -539,11 +529,11 @@ 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);
-    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) {
@@ -557,14 +547,16 @@ static int receive_ipc_message(struct shim_ipc_port* port) {
                 msg = tmp_buf;
             }
 
-            PAL_NUM read = DkStreamRead(port->pal_handle, /*offset=*/0, expected_size - bytes + readahead,
-                                       (void *) msg + bytes, NULL, 0);
+            PAL_NUM read =
+                DkStreamRead(port->pal_handle, /*offset=*/0, expected_size - bytes + readahead,
+                             (void*)msg + bytes, NULL, 0);
 
             if (read == PAL_STREAM_ERROR) {
                 if (PAL_ERRNO == EINTR || PAL_ERRNO == EAGAIN || PAL_ERRNO == EWOULDBLOCK)
                     continue;
 
-                debug("Port %p (handle %p) closed while receiving IPC message\n", port, port->pal_handle);
+                debug("Port %p (handle %p) closed while receiving IPC message\n", port,
+                      port->pal_handle);
                 del_ipc_port_fini(port, -ECHILD);
                 ret = -PAL_ERRNO;
                 goto out;
@@ -577,8 +569,11 @@ static int receive_ipc_message(struct shim_ipc_port* port) {
                 expected_size = msg->size;
         }
 
-        debug("Received IPC message from port %p (handle %p): code=%d size=%lu src=%u dst=%u seq=%lx\n",
-              port, port->pal_handle, msg->code, msg->size, msg->src & 0xFFFF, msg->dst & 0xFFFF, msg->seq);
+        debug(
+            "Received IPC message from port %p (handle %p): code=%d size=%lu "
+            "src=%u dst=%u seq=%lx\n",
+            port, port->pal_handle, msg->code, msg->size, msg->src & 0xFFFF, msg->dst & 0xFFFF,
+            msg->seq);
 
         /* skip messages coming from myself (in case of broadcast) */
         if (msg->src != cur_process.vmid) {
@@ -589,8 +584,8 @@ static int receive_ipc_message(struct shim_ipc_port* port) {
                     /* send IPC_RESP message to sender of this msg */
                     ret = send_response_ipc_message(port, msg->src, ret, msg->seq);
                     if (ret < 0) {
-                        debug("Sending IPC_RESP msg on port %p (handle %p) to %u failed\n",
-                              port, port->pal_handle, msg->src & 0xFFFF);
+                        debug("Sending IPC_RESP msg on port %p (handle %p) to %u failed\n", port,
+                              port->pal_handle, msg->src & 0xFFFF);
                         ret = -PAL_ERRNO;
                         goto out;
                     }
@@ -598,12 +593,12 @@ 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 buffer and reset expected size */
-            memmove(msg, (void *)msg + expected_size, bytes);
+            /* we may have started reading the next message, move this message to beginning of msg
+             * buffer and reset expected size */
+            memmove(msg, (void*)msg + expected_size, bytes);
             expected_size = IPC_MSG_MINIMAL_SIZE;
             if (bytes >= IPC_MSG_MINIMAL_SIZE)
                 expected_size = msg->size;
@@ -616,28 +611,24 @@ out:
     return ret;
 }
 
-/* Main routine of the IPC helper thread. IPC helper thread is spawned when
- * the first IPC port is added and is terminated only when the whole Graphene
- * application terminates. IPC helper thread runs in an endless loop and waits
- * on port events (either the addition/removal of ports or actual port events:
- * acceptance of new client or receiving/sending messages). In particular,
- * IPC helper thread calls receive_ipc_message() if a message arrives on port.
+/* Main routine of the IPC helper thread. IPC helper thread is spawned when the first IPC port is
+ * added and is terminated only when the whole Graphene application terminates. IPC helper thread
+ * runs in an endless loop and waits on port events (either the addition/removal of ports or actual
+ * port events: acceptance of new client or receiving/sending messages). In particular, IPC helper
+ * thread calls receive_ipc_message() if a message arrives on port.
  *
- * Other threads add and remove IPC ports via add_ipc_xxx() and del_ipc_xxx()
- * functions. These ports are added to port_list which the IPC helper thread
- * consults before each new DkObjectsWaitAny().
+ * Other threads add and remove IPC ports via add_ipc_xxx() and del_ipc_xxx() functions. These ports
+ * are added to port_list which the IPC helper thread consults before each new DkObjectsWaitAny().
  *
- * Note that ports are copied from global port_list to local object_list. This
- * is because ports may be removed from port_list by other threads while IPC
- * helper thread is waiting on DkObjectsWaitAny(). For this reason IPC thread
- * also get references to all current ports and puts them after handling all
- * ports in object_list.
+ * Note that ports are copied from global port_list to local object_list. This is because ports may
+ * be removed from port_list by other threads while IPC helper thread is waiting on
+ * DkObjectsWaitAny(). For this reason IPC thread also get references to all current ports and puts
+ * them after handling all ports in object_list.
  *
- * Previous implementation went to great lengths to keep changes to the list of
- * current ports to a minimum (instead of repopulating the list before each wait
- * like in current code). Unfortunately, this resulted in undue complexity.
- * Current implementation should perform fine for usual case of <100 IPC ports
- * and with IPC helper thread always running in background on its own core.
+ * Previous implementation went to great lengths to keep changes to the list of current ports to a
+ * minimum (instead of repopulating the list before each wait like in current code). Unfortunately,
+ * this resulted in undue complexity. Current implementation should perform fine for usual case of
+ * <100 IPC ports and with IPC helper thread always running in background on its own core.
  */
 noreturn static void shim_ipc_helper(void* dummy) {
     __UNUSED(dummy);
@@ -647,22 +638,21 @@ noreturn static void shim_ipc_helper(void* dummy) {
 
     /* Initialize two lists:
      * - object_list collects IPC port objects and is the main handled list
-     * - palhandle_list collects corresponding PAL handles of IPC port objects
-     *   and is needed for DkObjectsWaitAny(.., <array-of-PAL-handles>, ..)
-     *   interface; palhandle_list always contains at least install_new_event
+     * - palhandle_list collects corresponding PAL handles of IPC port objects and is needed for
+     *   DkObjectsWaitAny(.., <array-of-PAL-handles>, ..) interface; palhandle_list always contains
+     *   at least install_new_event
      *
-     * We allocate these two lists on the heap so they do not overflow the
-     * limited PAL stack. We grow them at runtime if needed.
+     * We allocate these two lists on the heap so they do not overflow the limited PAL stack. We
+     * grow them at runtime if needed.
      */
-    size_t object_list_size = 0;
+    size_t object_list_size    = 0;
     size_t object_list_maxsize = 32;
     struct shim_ipc_port** object_list =
-            malloc(sizeof(struct shim_ipc_port *) * object_list_maxsize);
-    PAL_HANDLE* palhandle_list =
-            malloc(sizeof(PAL_HANDLE) * (1 + object_list_maxsize));
+        malloc(sizeof(struct shim_ipc_port*) * object_list_maxsize);
+    PAL_HANDLE* palhandle_list = malloc(sizeof(PAL_HANDLE) * (1 + object_list_maxsize));
 
     PAL_HANDLE install_new_event_hdl = event_handle(&install_new_event);
-    palhandle_list[0] = install_new_event_hdl;
+    palhandle_list[0]                = install_new_event_hdl;
 
     while (true) {
         lock(&ipc_helper_lock);
@@ -676,8 +666,8 @@ noreturn static void shim_ipc_helper(void* dummy) {
         struct shim_ipc_port* polled_port = NULL;
 
         if (polled == install_new_event_hdl) {
-            /* some thread wants to install new event; this event is found
-             * in object_list below, so just re-init install_new_event */
+            /* some thread wants to install new event; this event is found in object_list below, so
+             * just re-init install_new_event */
             debug("New IPC event was requested (port was added/removed)\n");
             clear_event(&install_new_event);
         } else {
@@ -691,18 +681,17 @@ noreturn static void shim_ipc_helper(void* dummy) {
 
         if (polled_port) {
             if (polled_port->type & IPC_PORT_SERVER) {
-                /* if polled port is server port, accept a client,
-                 * create client port, and add it to port list */
+                /* if polled port is server port, accept a client, create client port, and add it to
+                 * port list */
                 PAL_HANDLE client = DkStreamWaitForClient(polled_port->pal_handle);
                 if (client) {
-                    /* type of client port is the same as original server port
-                     * but with LISTEN (for remote client) and without SERVER
-                     * (this port doesn't wait for new clients) */
+                    /* type of client port is the same as original server port but with LISTEN (for
+                     * remote client) and without SERVER (this port doesn't wait for new clients) */
                     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",
-                            polled_port, polled_port->pal_handle);
+                    debug("Port %p (handle %p) was removed during accepting client\n", polled_port,
+                          polled_port->pal_handle);
                     del_ipc_port_fini(polled_port, -ECHILD);
                 }
             } else {
@@ -715,13 +704,13 @@ noreturn static void shim_ipc_helper(void* dummy) {
                     }
 
                     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);
                 }
             }
@@ -743,14 +732,12 @@ noreturn static void shim_ipc_helper(void* dummy) {
 
             if (object_list_size == object_list_maxsize) {
                 /* grow object_list and palhandle_list to accomodate more objects */
-                struct shim_ipc_port** tmp_array = malloc(
-                        sizeof(struct shim_ipc_port *) * (object_list_maxsize * 2));
-                PAL_HANDLE* tmp_pal_array = malloc(
-                        sizeof(PAL_HANDLE) * (1 + object_list_maxsize * 2));
-                memcpy(tmp_array, object_list,
-                        sizeof(struct shim_ipc_port *) * (object_list_size));
-                memcpy(tmp_pal_array, palhandle_list,
-                        sizeof(PAL_HANDLE) * (1 + object_list_size));
+                struct shim_ipc_port** tmp_array =
+                    malloc(sizeof(struct shim_ipc_port*) * (object_list_maxsize * 2));
+                PAL_HANDLE* tmp_pal_array =
+                    malloc(sizeof(PAL_HANDLE) * (1 + object_list_maxsize * 2));
+                memcpy(tmp_array, object_list, sizeof(struct shim_ipc_port*) * (object_list_size));
+                memcpy(tmp_pal_array, palhandle_list, sizeof(PAL_HANDLE) * (1 + object_list_size));
                 object_list_maxsize *= 2;
                 free(object_list);
                 free(palhandle_list);
@@ -788,7 +775,7 @@ noreturn static void shim_ipc_helper(void* dummy) {
 }
 
 static void shim_ipc_helper_prepare(void* arg) {
-    struct shim_thread * self = (struct shim_thread *) arg;
+    struct shim_thread* self = (struct shim_thread*)arg;
     if (!arg)
         return;
 
@@ -814,7 +801,7 @@ static void shim_ipc_helper_prepare(void* arg) {
 
     /* swap stack to be sure we don't drain the small stack PAL provides */
     self->stack_top = stack + IPC_HELPER_STACK_SIZE;
-    self->stack = stack;
+    self->stack     = stack;
     __SWITCH_STACK(self->stack_top, shim_ipc_helper, NULL);
 }
 
@@ -823,19 +810,19 @@ static int create_ipc_helper(void) {
     if (ipc_helper_state == HELPER_ALIVE)
         return 0;
 
-    struct shim_thread * new = get_new_internal_thread();
+    struct shim_thread* new = get_new_internal_thread();
     if (!new)
         return -ENOMEM;
 
     ipc_helper_thread = new;
-    ipc_helper_state = HELPER_ALIVE;
+    ipc_helper_state  = HELPER_ALIVE;
 
     PAL_HANDLE handle = thread_create(shim_ipc_helper_prepare, new);
 
     if (!handle) {
         int ret = -PAL_ERRNO;  /* put_thread() may overwrite errno */
         ipc_helper_thread = NULL;
-        ipc_helper_state = HELPER_NOTALIVE;
+        ipc_helper_state  = HELPER_NOTALIVE;
         put_thread(new);
         return ret;
     }
@@ -844,10 +831,10 @@ static int create_ipc_helper(void) {
     return 0;
 }
 
-/* On success, the reference to ipc helper thread is returned with refcount
- * incremented. It is the responsibility of caller to wait for ipc helper's
- * exit and then release the final reference to free related resources (it is
- * problematic for the thread itself to release its own resources e.g. stack).
+/* On success, the reference to ipc helper thread is returned with refcount incremented. It is the
+ * responsibility of caller to wait for ipc helper's exit and then release the final reference to
+ * free related resources (it is problematic for the thread itself to release its own resources e.g.
+ * stack).
  */
 struct shim_thread* terminate_ipc_helper(void) {
     /* First check if thread is alive. */
@@ -858,18 +845,18 @@ struct shim_thread* terminate_ipc_helper(void) {
     }
     unlock(&ipc_helper_lock);
 
-    /* NOTE: Graphene doesn't have an abstraction of a queue of pending signals
-     * between communicating processes (instead all communication is done over
-     * streams). Thus, app code like this (found in e.g. Lmbench's bw_unix):
+    /* NOTE: Graphene doesn't have an abstraction of a queue of pending signals between
+     * communicating processes (instead all communication is done over streams). Thus, app code like
+     * this (found in e.g. Lmbench's bw_unix):
      *     kill(child, SIGKILL);
      *     exit(0);
-     * results in a data race between the SIGKILL message sent over IPC stream
-     * and the parent process exiting. In the worst case, the parent will exit
-     * before the SIGKILL message goes 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");
+     * results in a data race between the SIGKILL message sent over IPC stream and the parent
+     * process exiting. In the worst case, the parent will exit before the SIGKILL message goes
+     * 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 */
 
     lock(&ipc_helper_lock);

+ 152 - 201
LibOS/shim/src/ipc/shim_ipc_pid.c

@@ -20,43 +20,38 @@
  * This file contains functions and callbacks to handle IPC of PID namespace.
  */
 
-#include <shim_internal.h>
-#include <shim_thread.h>
-#include <shim_fs.h>
-#include <shim_ipc.h>
-#include <shim_checkpoint.h>
+#include <errno.h>
 
 #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_thread.h>
 
-#include <errno.h>
-
-#define PID_RANGE_SIZE      32
-#define PID_LEASE_TIME      1000
+#define PID_RANGE_SIZE 32
+#define PID_LEASE_TIME 1000
 
-#define NS      pid
-#define NS_CAP  PID
+#define NS     pid
+#define NS_CAP PID
 
 #define INCLUDE_IPC_NSIMPL
 #include "shim_ipc_nsimpl.h"
 
-static int thread_add_subrange (struct shim_thread * thread, void * arg,
-                                bool * unlocked)
-{
-    __UNUSED(unlocked); // Kept for API compatibility - used by some callbacks
+static int thread_add_subrange(struct shim_thread* thread, void* arg, bool* unlocked) {
+    __UNUSED(unlocked);  // Kept for API compatibility - used by some callbacks
     if (!thread->in_vm)
         return 0;
 
-    struct shim_ipc_info * info = (struct shim_ipc_info *) arg;
+    struct shim_ipc_info* info = (struct shim_ipc_info*)arg;
 
-    add_pid_subrange(thread->tid, info->vmid,
-                     qstrgetstr(&info->uri), &thread->tid_lease);
+    add_pid_subrange(thread->tid, info->vmid, qstrgetstr(&info->uri), &thread->tid_lease);
     return 0;
 }
 
-int init_ns_pid (void)
-{
-    struct shim_ipc_info * info;
+int init_ns_pid(void) {
+    struct shim_ipc_info* info;
     int ret = 0;
 
     init_namespace();
@@ -90,23 +85,22 @@ int ipc_pid_kill_send(IDTYPE sender, IDTYPE target, enum kill_type type, int sig
             goto out;
     }
 
-    size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_pid_kill));
+    size_t total_msg_size    = get_ipc_msg_size(sizeof(struct shim_ipc_pid_kill));
     struct shim_ipc_msg* msg = __alloca(total_msg_size);
     init_ipc_msg(msg, IPC_PID_KILL, total_msg_size, dest);
 
-    struct shim_ipc_pid_kill* msgin = (struct shim_ipc_pid_kill *)&msg->msg;
-    msgin->sender = sender;
-    msgin->type   = type;
-    msgin->id     = target;
-    msgin->signum = signum;
+    struct shim_ipc_pid_kill* msgin = (struct shim_ipc_pid_kill*)&msg->msg;
+    msgin->sender                   = sender;
+    msgin->type                     = type;
+    msgin->id                       = target;
+    msgin->signum                   = signum;
 
     if (type == KILL_ALL) {
-        debug("IPC broadcast: IPC_PID_KILL(%u, %d, %u, %d)\n",
-              sender, type, target, signum);
-        ret = broadcast_ipc(msg, IPC_PORT_DIRCLD|IPC_PORT_DIRPRT, /*exclude_port=*/NULL);
+        debug("IPC broadcast: IPC_PID_KILL(%u, %d, %u, %d)\n", sender, type, target, signum);
+        ret = broadcast_ipc(msg, IPC_PORT_DIRCLD | IPC_PORT_DIRPRT, /*exclude_port=*/NULL);
     } else {
-        debug("IPC send to %u: IPC_PID_KILL(%u, %d, %u, %d)\n",
-              dest & 0xFFFF, sender, type, target, signum);
+        debug("IPC send to %u: IPC_PID_KILL(%u, %d, %u, %d)\n", dest & 0xFFFF, sender, type, target,
+              signum);
         ret = send_ipc_message(msg, port);
         put_ipc_port(port);
     }
@@ -121,10 +115,10 @@ DEFINE_PROFILE_INTERVAL(ipc_pid_kill_callback, ipc);
 
 int ipc_pid_kill_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_kill* msgin = (struct shim_ipc_pid_kill *) msg->msg;
+    struct shim_ipc_pid_kill* msgin = (struct shim_ipc_pid_kill*)msg->msg;
 
-    debug("IPC callback from %u: IPC_PID_KILL(%u, %d, %u, %d)\n",
-          msg->src & 0xFFFF, msgin->sender, msgin->type, msgin->id, msgin->signum);
+    debug("IPC callback from %u: IPC_PID_KILL(%u, %d, %u, %d)\n", msg->src & 0xFFFF, msgin->sender,
+          msgin->type, msgin->id, msgin->signum);
 
     int ret = 0;
 
@@ -139,7 +133,7 @@ int ipc_pid_kill_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port)
             ret = do_kill_pgroup(msgin->sender, msgin->id, msgin->signum, true);
             break;
         case KILL_ALL:
-            broadcast_ipc(msg, IPC_PORT_DIRCLD|IPC_PORT_DIRPRT, port);
+            broadcast_ipc(msg, IPC_PORT_DIRCLD | IPC_PORT_DIRPRT, port);
             kill_all_threads(NULL, msgin->sender, msgin->signum);
             break;
     }
@@ -151,25 +145,21 @@ int ipc_pid_kill_callback(struct shim_ipc_msg* msg, struct shim_ipc_port* port)
 DEFINE_PROFILE_INTERVAL(ipc_pid_getstatus_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_getstatus_callback, ipc);
 
-int ipc_pid_getstatus_send (struct shim_ipc_port * port, IDTYPE dest,
-                            int npids, IDTYPE * pids,
-                            struct pid_status ** status)
-{
+int ipc_pid_getstatus_send(struct shim_ipc_port* port, IDTYPE dest, int npids, IDTYPE* pids,
+                           struct pid_status** status) {
     BEGIN_PROFILE_INTERVAL();
     int ret;
 
-    size_t total_msg_size = get_ipc_msg_duplex_size(sizeof(struct shim_ipc_pid_getstatus) +
-                                                 sizeof(IDTYPE) * npids);
+    size_t total_msg_size =
+        get_ipc_msg_duplex_size(sizeof(struct shim_ipc_pid_getstatus) + sizeof(IDTYPE) * npids);
     struct shim_ipc_msg_duplex* msg = __alloca(total_msg_size);
     init_ipc_msg_duplex(msg, IPC_PID_GETSTATUS, total_msg_size, dest);
 
-    struct shim_ipc_pid_getstatus * msgin =
-                    (struct shim_ipc_pid_getstatus *) &msg->msg.msg;
-    msgin->npids = npids;
+    struct shim_ipc_pid_getstatus* msgin = (struct shim_ipc_pid_getstatus*)&msg->msg.msg;
+    msgin->npids                         = npids;
     memcpy(msgin->pids, pids, sizeof(IDTYPE) * npids);
 
-    debug("ipc send to %u: IPC_PID_GETSTATUS(%d, [%u, ...])\n", dest,
-          npids, pids[0]);
+    debug("ipc send to %u: IPC_PID_GETSTATUS(%d, [%u, ...])\n", dest, npids, pids[0]);
 
     ret = send_ipc_message_duplex(msg, port, NULL, status);
 
@@ -179,20 +169,17 @@ int ipc_pid_getstatus_send (struct shim_ipc_port * port, IDTYPE dest,
 
 struct thread_status {
     int npids;
-    IDTYPE * pids;
+    IDTYPE* pids;
     int nstatus;
-    struct pid_status * status;
+    struct pid_status* status;
 };
 
-int check_thread (struct shim_thread * thread, void * arg,
-                  bool * unlocked)
-{
-    __UNUSED(unlocked); // Kept for API compatibility
-    struct thread_status * status = (struct thread_status *) arg;
+int check_thread(struct shim_thread* thread, void* arg, bool* unlocked) {
+    __UNUSED(unlocked);  // Kept for API compatibility
+    struct thread_status* status = (struct thread_status*)arg;
 
-    for (int i = 0 ; i < status->npids ; i++)
-        if (status->pids[i] == thread->tid &&
-            thread->in_vm && thread->is_alive) {
+    for (int i = 0; i < status->npids; i++)
+        if (status->pids[i] == thread->tid && thread->in_vm && thread->is_alive) {
             status->status[status->nstatus].pid  = thread->tid;
             status->status[status->nstatus].tgid = thread->tgid;
             status->status[status->nstatus].pgid = thread->pgid;
@@ -203,28 +190,25 @@ int check_thread (struct shim_thread * thread, void * arg,
     return 0;
 }
 
-int ipc_pid_getstatus_callback (IPC_CALLBACK_ARGS)
-{
+int ipc_pid_getstatus_callback(IPC_CALLBACK_ARGS) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_getstatus * msgin =
-                            (struct shim_ipc_pid_getstatus *) msg->msg;
+    struct shim_ipc_pid_getstatus* msgin = (struct shim_ipc_pid_getstatus*)msg->msg;
     int ret = 0;
 
-    debug("ipc callback from %u: IPC_PID_GETSTATUS(%d, [%u, ...])\n",
-          msg->src, msgin->npids, msgin->pids[0]);
+    debug("ipc callback from %u: IPC_PID_GETSTATUS(%d, [%u, ...])\n", msg->src, msgin->npids,
+          msgin->pids[0]);
 
     struct thread_status status;
-    status.npids = msgin->npids;
-    status.pids = msgin->pids;
+    status.npids   = msgin->npids;
+    status.pids    = msgin->pids;
     status.nstatus = 0;
-    status.status = __alloca(sizeof(struct pid_status) * msgin->npids);
+    status.status  = __alloca(sizeof(struct pid_status) * msgin->npids);
 
     ret = walk_thread_list(&check_thread, &status);
     if (ret < 0 && ret != -ESRCH)
         goto out;
 
-    ret = ipc_pid_retstatus_send(port, msg->src, status.nstatus, status.status,
-                                 msg->seq);
+    ret = ipc_pid_retstatus_send(port, msg->src, status.nstatus, status.status, msg->seq);
 out:
     SAVE_PROFILE_INTERVAL(ipc_pid_getstatus_callback);
     return ret;
@@ -233,10 +217,8 @@ out:
 DEFINE_PROFILE_INTERVAL(ipc_pid_retstatus_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_retstatus_callback, ipc);
 
-int ipc_pid_retstatus_send (struct shim_ipc_port * port, IDTYPE dest,
-                            int nstatus, struct pid_status * status,
-                            unsigned long seq)
-{
+int ipc_pid_retstatus_send(struct shim_ipc_port* port, IDTYPE dest, int nstatus,
+                           struct pid_status* status, unsigned long seq) {
     BEGIN_PROFILE_INTERVAL();
     int ret;
 
@@ -245,16 +227,14 @@ int ipc_pid_retstatus_send (struct shim_ipc_port * port, IDTYPE dest,
     struct shim_ipc_msg* msg = __alloca(total_msg_size);
     init_ipc_msg(msg, IPC_PID_RETSTATUS, total_msg_size, dest);
 
-    struct shim_ipc_pid_retstatus * msgin =
-                    (struct shim_ipc_pid_retstatus *) &msg->msg;
+    struct shim_ipc_pid_retstatus* msgin = (struct shim_ipc_pid_retstatus*)&msg->msg;
 
-    msgin->nstatus  = nstatus;
+    msgin->nstatus = nstatus;
     memcpy(msgin->status, status, sizeof(struct pid_status) * nstatus);
     msg->seq = seq;
 
     if (nstatus)
-        debug("ipc send to %u: IPC_PID_RETSTATUS(%d, [%u, ...])\n", dest,
-              nstatus, status[0].pid);
+        debug("ipc send to %u: IPC_PID_RETSTATUS(%d, [%u, ...])\n", dest, nstatus, status[0].pid);
     else
         debug("ipc send to %u: IPC_PID_RETSTATUS(0, [])\n", dest);
 
@@ -264,26 +244,22 @@ int ipc_pid_retstatus_send (struct shim_ipc_port * port, IDTYPE dest,
     return ret;
 }
 
-int ipc_pid_retstatus_callback (IPC_CALLBACK_ARGS)
-{
+int ipc_pid_retstatus_callback(IPC_CALLBACK_ARGS) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_retstatus * msgin =
-                            (struct shim_ipc_pid_retstatus *) msg->msg;
+    struct shim_ipc_pid_retstatus* msgin = (struct shim_ipc_pid_retstatus*)msg->msg;
 
     if (msgin->nstatus)
-        debug("ipc callback from %u: IPC_PID_RETSTATUS(%d, [%u, ...])\n",
-              msg->src, msgin->nstatus, msgin->status[0].pid);
+        debug("ipc callback from %u: IPC_PID_RETSTATUS(%d, [%u, ...])\n", msg->src, msgin->nstatus,
+              msgin->status[0].pid);
     else
         debug("ipc callback from %u: IPC_PID_RETSTATUS(0, [])\n", msg->src);
 
-
-    struct shim_ipc_msg_duplex * obj = pop_ipc_msg_duplex(port, msg->seq);
+    struct shim_ipc_msg_duplex* obj = pop_ipc_msg_duplex(port, msg->seq);
     if (obj) {
-        struct pid_status ** status = (struct pid_status **) obj->private;
+        struct pid_status** status = (struct pid_status**)obj->private;
 
         if (status) {
-            *status = malloc_copy(msgin->status, sizeof(struct pid_status) *
-                                  msgin->nstatus);
+            *status = malloc_copy(msgin->status, sizeof(struct pid_status) * msgin->nstatus);
 
             obj->retval = msgin->nstatus;
         }
@@ -296,41 +272,40 @@ int ipc_pid_retstatus_callback (IPC_CALLBACK_ARGS)
     return 0;
 }
 
-int get_all_pid_status (struct pid_status ** status)
-{
+int get_all_pid_status(struct pid_status** status) {
     /* run queryall unconditionally */
     ipc_pid_queryall_send();
 
-    int bufsize = RANGE_SIZE;
-    struct pid_status * status_buf = malloc(bufsize);
-    int nstatus = 0;
+    int bufsize                   = RANGE_SIZE;
+    struct pid_status* status_buf = malloc(bufsize);
+    int nstatus                   = 0;
 
     if (!bufsize)
         return -ENOMEM;
 
-    LISTP_TYPE(range) * list = &offered_ranges;
-    struct range * r;
+    LISTP_TYPE(range)* list = &offered_ranges;
+    struct range* r;
     int ret;
 
     lock(&range_map_lock);
 
 retry:
     LISTP_FOR_EACH_ENTRY(r, list, list) {
-        struct subrange * s = NULL;
-        struct shim_ipc_info * p;
+        struct subrange* s = NULL;
+        struct shim_ipc_info* p;
         IDTYPE off, idx;
         IDTYPE base;
         IDTYPE pids[RANGE_SIZE];
-        struct pid_status * range_status;
+        struct pid_status* range_status;
 
-#define UNDEF_IDX   ((IDTYPE) -1)
+#define UNDEF_IDX ((IDTYPE)-1)
 
-next_range:
-        idx = UNDEF_IDX;
-        off = r->offset;
+    next_range:
+        idx  = UNDEF_IDX;
+        off  = r->offset;
         base = off * RANGE_SIZE + 1;
 
-next_sub:
+    next_sub:
         if (idx == UNDEF_IDX) {
             p = r->owner;
         } else {
@@ -352,10 +327,10 @@ next_sub:
         }
 
         if (!p->port) {
-            IDTYPE type = IPC_PORT_PIDOWN|IPC_PORT_LISTEN;
-            IDTYPE owner = p->vmid;
-            char * uri = qstrtostr(&p->uri, true);
-            struct shim_ipc_port * port = NULL;
+            IDTYPE type                = IPC_PORT_PIDOWN | IPC_PORT_LISTEN;
+            IDTYPE owner               = p->vmid;
+            char* uri                  = qstrtostr(&p->uri, true);
+            struct shim_ipc_port* port = NULL;
             unlock(&range_map_lock);
 
             PAL_HANDLE pal_handle = DkStreamOpen(uri, 0, 0, 0, 0);
@@ -364,11 +339,12 @@ next_sub:
                 add_ipc_port_by_id(owner, pal_handle, type, NULL, &port);
 
             lock(&range_map_lock);
-            LISTP_FOR_EACH_ENTRY(r, list, list)
+            LISTP_FOR_EACH_ENTRY(r, list, list) {
                 if (r->offset >= off)
                     break;
+            }
             /* DEP 5/15/17: I believe this is checking if the list is empty */
-            //if (&r->list == list)
+            // if (&r->list == list)
             if (LISTP_EMPTY(list))
                 break;
             if (r->offset > off)
@@ -395,14 +371,13 @@ next_sub:
         }
 
         if (idx == UNDEF_IDX) {
-            for (int i = 0 ; i < RANGE_SIZE ; i++)
+            for (int i = 0; i < RANGE_SIZE; i++)
                 pids[i] = base + i;
         } else {
             pids[0] = base + idx;
         }
 
-        ret = ipc_pid_getstatus_send(p->port, p->vmid,
-                                     idx == UNDEF_IDX ? RANGE_SIZE : 1, pids,
+        ret = ipc_pid_getstatus_send(p->port, p->vmid, idx == UNDEF_IDX ? RANGE_SIZE : 1, pids,
                                      &range_status);
 
         if (ret > 0) {
@@ -412,7 +387,7 @@ next_sub:
                 while (nstatus + ret > newsize)
                     newsize *= 2;
 
-                struct pid_status * new_buf = malloc(newsize);
+                struct pid_status* new_buf = malloc(newsize);
 
                 if (!new_buf) {
                     unlock(&range_map_lock);
@@ -421,16 +396,14 @@ next_sub:
                     return -ENOMEM;
                 }
 
-                memcpy(new_buf, status_buf,
-                       sizeof(struct pid_status) * nstatus);
+                memcpy(new_buf, status_buf, sizeof(struct pid_status) * nstatus);
 
                 free(status_buf);
                 status_buf = new_buf;
-                bufsize = newsize;
+                bufsize    = newsize;
             }
 
-            memcpy(status_buf + nstatus, range_status,
-                   sizeof(struct pid_status) * ret);
+            memcpy(status_buf + nstatus, range_status, sizeof(struct pid_status) * ret);
             free(range_status);
             nstatus += ret;
         }
@@ -458,30 +431,31 @@ next_sub:
 DEFINE_PROFILE_INTERVAL(ipc_pid_getmeta_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_getmeta_callback, ipc);
 
-static const char * pid_meta_code_str[4] = { "CRED", "EXEC", "CWD", "ROOT", };
+static const char* pid_meta_code_str[4] = {
+    "CRED",
+    "EXEC",
+    "CWD",
+    "ROOT",
+};
 
-int ipc_pid_getmeta_send (IDTYPE pid, enum pid_meta_code code,
-                          void ** data)
-{
+int ipc_pid_getmeta_send(IDTYPE pid, enum pid_meta_code code, void** data) {
     BEGIN_PROFILE_INTERVAL();
     IDTYPE dest;
-    struct shim_ipc_port * port = NULL;
+    struct shim_ipc_port* port = NULL;
     int ret;
 
     if ((ret = connect_owner(pid, &port, &dest)) < 0)
         goto out;
 
-    size_t total_msg_size = get_ipc_msg_duplex_size(sizeof(struct shim_ipc_pid_getmeta));
+    size_t total_msg_size           = get_ipc_msg_duplex_size(sizeof(struct shim_ipc_pid_getmeta));
     struct shim_ipc_msg_duplex* msg = __alloca(total_msg_size);
     init_ipc_msg_duplex(msg, IPC_PID_GETMETA, total_msg_size, dest);
 
-    struct shim_ipc_pid_getmeta * msgin =
-                    (struct shim_ipc_pid_getmeta *) &msg->msg.msg;
+    struct shim_ipc_pid_getmeta* msgin = (struct shim_ipc_pid_getmeta*)&msg->msg.msg;
     msgin->pid  = pid;
     msgin->code = code;
 
-    debug("ipc send to %u: IPC_PID_GETMETA(%u, %s)\n", dest,
-          pid, pid_meta_code_str[code]);
+    debug("ipc send to %u: IPC_PID_GETMETA(%u, %s)\n", dest, pid, pid_meta_code_str[code]);
 
     ret = send_ipc_message_duplex(msg, port, NULL, data);
     put_ipc_port(port);
@@ -490,19 +464,17 @@ out:
     return ret;
 }
 
-int ipc_pid_getmeta_callback (IPC_CALLBACK_ARGS)
-{
+int ipc_pid_getmeta_callback(IPC_CALLBACK_ARGS) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_getmeta * msgin =
-                            (struct shim_ipc_pid_getmeta *) msg->msg;
+    struct shim_ipc_pid_getmeta* msgin = (struct shim_ipc_pid_getmeta*)msg->msg;
     int ret = 0;
 
-    debug("ipc callback from %u: IPC_PID_GETMETA(%u, %s)\n", msg->src,
-          msgin->pid, pid_meta_code_str[msgin->code]);
+    debug("ipc callback from %u: IPC_PID_GETMETA(%u, %s)\n", msg->src, msgin->pid,
+          pid_meta_code_str[msgin->code]);
 
-    struct shim_thread * thread = lookup_thread(msgin->pid);
-    void * data = NULL;
-    size_t datasize = 0;
+    struct shim_thread* thread = lookup_thread(msgin->pid);
+    void* data                 = NULL;
+    size_t datasize            = 0;
 
     if (!thread) {
         ret = -ESRCH;
@@ -513,10 +485,10 @@ int ipc_pid_getmeta_callback (IPC_CALLBACK_ARGS)
 
     switch (msgin->code) {
         case PID_META_CRED:
-            datasize = sizeof(IDTYPE) * 2;
-            data = __alloca(datasize);
-            ((IDTYPE *) data)[0] = thread->uid;
-            ((IDTYPE *) data)[1] = thread->gid;
+            datasize           = sizeof(IDTYPE) * 2;
+            data               = __alloca(datasize);
+            ((IDTYPE*)data)[0] = thread->uid;
+            ((IDTYPE*)data)[1] = thread->gid;
             break;
         case PID_META_EXEC:
             if (!thread->exec || !thread->exec->dentry) {
@@ -550,8 +522,7 @@ int ipc_pid_getmeta_callback (IPC_CALLBACK_ARGS)
     if (ret < 0)
         goto out;
 
-    ret = ipc_pid_retmeta_send(port, msg->src, msgin->pid, msgin->code,
-                               data, datasize, msg->seq);
+    ret = ipc_pid_retmeta_send(port, msg->src, msgin->pid, msgin->code, data, datasize, msg->seq);
 out:
     SAVE_PROFILE_INTERVAL(ipc_pid_getmeta_callback);
     return ret;
@@ -560,28 +531,25 @@ out:
 DEFINE_PROFILE_INTERVAL(ipc_pid_retmeta_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_retmeta_callback, ipc);
 
-int ipc_pid_retmeta_send (struct shim_ipc_port * port, IDTYPE dest,
-                          IDTYPE pid, enum pid_meta_code code,
-                          const void * data, int datasize,
-                          unsigned long seq)
-{
+int ipc_pid_retmeta_send(struct shim_ipc_port* port, IDTYPE dest, IDTYPE pid,
+                         enum pid_meta_code code, const void* data, int datasize,
+                         unsigned long seq) {
     BEGIN_PROFILE_INTERVAL();
     int ret;
 
-    size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_pid_retmeta) + datasize);
+    size_t total_msg_size    = get_ipc_msg_size(sizeof(struct shim_ipc_pid_retmeta) + datasize);
     struct shim_ipc_msg* msg = __alloca(total_msg_size);
     init_ipc_msg(msg, IPC_PID_RETMETA, total_msg_size, dest);
-    struct shim_ipc_pid_retmeta * msgin =
-                    (struct shim_ipc_pid_retmeta *) &msg->msg;
+    struct shim_ipc_pid_retmeta* msgin = (struct shim_ipc_pid_retmeta*)&msg->msg;
 
     msgin->pid      = pid;
     msgin->code     = code;
     msgin->datasize = datasize;
     memcpy(msgin->data, data, datasize);
-    msg->seq        = seq;
+    msg->seq = seq;
 
-    debug("ipc send to %u: IPC_PID_RETMETA(%d, %s, %d)\n", dest,
-          pid, pid_meta_code_str[code], datasize);
+    debug("ipc send to %u: IPC_PID_RETMETA(%d, %s, %d)\n", dest, pid, pid_meta_code_str[code],
+          datasize);
 
     ret = send_ipc_message(msg, port);
 
@@ -589,22 +557,19 @@ int ipc_pid_retmeta_send (struct shim_ipc_port * port, IDTYPE dest,
     return ret;
 }
 
-int ipc_pid_retmeta_callback (IPC_CALLBACK_ARGS)
-{
+int ipc_pid_retmeta_callback(IPC_CALLBACK_ARGS) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_retmeta * msgin =
-                            (struct shim_ipc_pid_retmeta *) msg->msg;
+    struct shim_ipc_pid_retmeta* msgin = (struct shim_ipc_pid_retmeta*)msg->msg;
 
-    debug("ipc callback from %u: IPC_PID_RETMETA(%u, %s, %d)\n", msg->src,
-          msgin->pid, pid_meta_code_str[msgin->code], msgin->datasize);
+    debug("ipc callback from %u: IPC_PID_RETMETA(%u, %s, %d)\n", msg->src, msgin->pid,
+          pid_meta_code_str[msgin->code], msgin->datasize);
 
-    struct shim_ipc_msg_duplex * obj = pop_ipc_msg_duplex(port, msg->seq);
+    struct shim_ipc_msg_duplex* obj = pop_ipc_msg_duplex(port, msg->seq);
     if (obj) {
-        void ** data = (void **) obj->private;
+        void** data = (void**)obj->private;
 
         if (data)
-            *data = msgin->datasize ?
-                    malloc_copy(msgin->data, msgin->datasize) : NULL;
+            *data = msgin->datasize ? malloc_copy(msgin->data, msgin->datasize) : NULL;
 
         obj->retval = msgin->datasize;
 
@@ -616,8 +581,7 @@ int ipc_pid_retmeta_callback (IPC_CALLBACK_ARGS)
     return 0;
 }
 
-int get_pid_port (IDTYPE pid, IDTYPE * dest, struct shim_ipc_port ** port)
-{
+int get_pid_port(IDTYPE pid, IDTYPE* dest, struct shim_ipc_port** port) {
     IDTYPE owner;
     int ret;
 
@@ -633,16 +597,13 @@ int get_pid_port (IDTYPE pid, IDTYPE * dest, struct shim_ipc_port ** port)
 DEFINE_PROFILE_INTERVAL(ipc_pid_nop_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_nop_callback, ipc);
 
-int ipc_pid_nop_send (struct shim_ipc_port * port, IDTYPE dest, int count,
-                      const void * buf, int len)
-{
+int ipc_pid_nop_send(struct shim_ipc_port* port, IDTYPE dest, int count, const void* buf, int len) {
     BEGIN_PROFILE_INTERVAL();
     size_t total_msg_size = get_ipc_msg_duplex_size(sizeof(struct shim_ipc_pid_nop) + len);
     struct shim_ipc_msg_duplex* msg = __alloca(total_msg_size);
     init_ipc_msg_duplex(msg, IPC_PID_NOP, total_msg_size, dest);
 
-    struct shim_ipc_pid_nop * msgin =
-                (struct shim_ipc_pid_nop *) &msg->msg.msg;
+    struct shim_ipc_pid_nop* msgin = (struct shim_ipc_pid_nop*)&msg->msg.msg;
     msgin->count = count * 2;
     memcpy(msgin->payload, buf, len);
 
@@ -653,17 +614,14 @@ int ipc_pid_nop_send (struct shim_ipc_port * port, IDTYPE dest, int count,
     return send_ipc_message_duplex(msg, port, NULL, NULL);
 }
 
-int ipc_pid_nop_callback (IPC_CALLBACK_ARGS)
-{
+int ipc_pid_nop_callback(IPC_CALLBACK_ARGS) {
     BEGIN_PROFILE_INTERVAL();
-    struct shim_ipc_pid_nop * msgin =
-                        (struct shim_ipc_pid_nop *) &msg->msg;
+    struct shim_ipc_pid_nop* msgin = (struct shim_ipc_pid_nop*)&msg->msg;
 
-    debug("ipc callback from %u: IPC_PID_NOP(%d)\n", msg->src,
-          msgin->count);
+    debug("ipc callback from %u: IPC_PID_NOP(%d)\n", msg->src, msgin->count);
 
     if (!(--msgin->count)) {
-        struct shim_ipc_msg_duplex * obj = pop_ipc_msg_duplex(port, msg->seq);
+        struct shim_ipc_msg_duplex* obj = pop_ipc_msg_duplex(port, msg->seq);
         if (obj && obj->thread)
             thread_wakeup(obj->thread);
 
@@ -673,8 +631,7 @@ int ipc_pid_nop_callback (IPC_CALLBACK_ARGS)
 
     SAVE_PROFILE_INTERVAL(ipc_pid_nop_callback);
 
-    debug("ipc send to %u: IPC_PID_NOP(%d)\n", msg->src,
-          msgin->count);
+    debug("ipc send to %u: IPC_PID_NOP(%d)\n", msg->src, msgin->count);
 
     int ret = send_ipc_message(msg, port);
     SAVE_PROFILE_INTERVAL(ipc_pid_nop_send);
@@ -684,26 +641,23 @@ int ipc_pid_nop_callback (IPC_CALLBACK_ARGS)
 DEFINE_PROFILE_INTERVAL(ipc_pid_sendrpc_send, ipc);
 DEFINE_PROFILE_INTERVAL(ipc_pid_sendrpc_callback, ipc);
 
-int ipc_pid_sendrpc_send (IDTYPE pid, IDTYPE sender, const void * buf,
-                          int len)
-{
+int ipc_pid_sendrpc_send(IDTYPE pid, IDTYPE sender, const void* buf, int len) {
     BEGIN_PROFILE_INTERVAL();
     int ret = 0;
     IDTYPE dest;
-    struct shim_ipc_port * port = NULL;
+    struct shim_ipc_port* port = NULL;
 
     if ((ret = get_pid_port(pid, &dest, &port)) < 0)
         return ret;
 
-    size_t total_msg_size = get_ipc_msg_size(sizeof(struct shim_ipc_pid_sendrpc) + len);
+    size_t total_msg_size    = get_ipc_msg_size(sizeof(struct shim_ipc_pid_sendrpc) + len);
     struct shim_ipc_msg* msg = __alloca(total_msg_size);
     init_ipc_msg(msg, IPC_PID_SENDRPC, total_msg_size, dest);
-    struct shim_ipc_pid_sendrpc * msgin =
-                    (struct shim_ipc_pid_sendrpc *) &msg->msg;
+    struct shim_ipc_pid_sendrpc* msgin = (struct shim_ipc_pid_sendrpc*)&msg->msg;
 
     debug("ipc send to %u: IPC_PID_SENDPRC(%d)\n", dest, len);
     msgin->sender = sender;
-    msgin->len = len;
+    msgin->len    = len;
     memcpy(msgin->payload, buf, len);
 
     ret = send_ipc_message(msg, port);
@@ -723,10 +677,10 @@ struct rpcmsg {
 DEFINE_LIST(rpcreq);
 struct rpcreq {
     LIST_TYPE(rpcreq) list;
-    struct shim_thread * thread;
+    struct shim_thread* thread;
     IDTYPE sender;
     int len;
-    void * buffer;
+    void* buffer;
 };
 
 DEFINE_LISTP(rpcmsg);
@@ -759,7 +713,7 @@ int get_rpc_msg(IDTYPE* sender, void* buf, int len) {
 
     INIT_LIST_HEAD(r, list);
     r->sender = 0;
-    r->len = len;
+    r->len    = len;
     r->buffer = buf;
     thread_setwait(&r->thread, NULL);
     LISTP_ADD_TAIL(r, &rpc_reqs, list);
@@ -776,22 +730,19 @@ int get_rpc_msg(IDTYPE* sender, void* buf, int len) {
     return ret;
 }
 
-int ipc_pid_sendrpc_callback (IPC_CALLBACK_ARGS)
-{
-    __UNUSED(port); // API compatibility
+int ipc_pid_sendrpc_callback(IPC_CALLBACK_ARGS) {
+    __UNUSED(port);  // API compatibility
     BEGIN_PROFILE_INTERVAL();
     int ret = 0;
-    struct shim_ipc_pid_sendrpc * msgin =
-                        (struct shim_ipc_pid_sendrpc *) msg->msg;
+    struct shim_ipc_pid_sendrpc* msgin = (struct shim_ipc_pid_sendrpc*)msg->msg;
 
-    debug("ipc callback from %u: IPC_PID_SENDPRC(%u, %d)\n", msg->src,
-          msgin->sender, msgin->len);
+    debug("ipc callback from %u: IPC_PID_SENDPRC(%u, %d)\n", msg->src, msgin->sender, msgin->len);
 
     create_lock_runtime(&rpc_queue_lock);
     lock(&rpc_queue_lock);
 
     if (!LISTP_EMPTY(&rpc_reqs)) {
-        struct rpcreq * r = LISTP_FIRST_ENTRY(&rpc_reqs, struct rpcreq, list);
+        struct rpcreq* r = LISTP_FIRST_ENTRY(&rpc_reqs, struct rpcreq, list);
         LISTP_DEL(r, &rpc_reqs, list);
         if (msgin->len < r->len)
             r->len = msgin->len;
@@ -801,7 +752,7 @@ int ipc_pid_sendrpc_callback (IPC_CALLBACK_ARGS)
         goto out;
     }
 
-    struct rpcmsg * m = malloc(sizeof(struct rpcmsg) + msgin->len);
+    struct rpcmsg* m = malloc(sizeof(struct rpcmsg) + msgin->len);
     if (!m) {
         ret = -ENOMEM;
         goto out;
@@ -809,7 +760,7 @@ int ipc_pid_sendrpc_callback (IPC_CALLBACK_ARGS)
 
     INIT_LIST_HEAD(m, list);
     m->sender = msgin->sender;
-    m->len = msgin->len;
+    m->len    = msgin->len;
     memcpy(m->payload, msgin->payload, msgin->len);
     LISTP_ADD_TAIL(m, &rpc_msgs, list);
 out:

+ 36 - 39
LibOS/shim/src/shim_async.c

@@ -20,30 +20,29 @@
  * This file contains functions to add asyncronous events triggered by timer.
  */
 
+#include <list.h>
+#include <pal.h>
 #include <shim_internal.h>
-#include <shim_utils.h>
 #include <shim_thread.h>
+#include <shim_utils.h>
 
-#include <pal.h>
-#include <list.h>
-
-#define IDLE_SLEEP_TIME     1000
-#define MAX_IDLE_CYCLES     100
+#define IDLE_SLEEP_TIME 1000
+#define MAX_IDLE_CYCLES 100
 
 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 */
+    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 */
 };
 DEFINE_LISTP(async_event);
 static LISTP_TYPE(async_event) async_list;
 
 /* can be read without async_helper_lock but always written with lock held */
-static enum {  HELPER_NOTALIVE, HELPER_ALIVE } async_helper_state;
+static enum { HELPER_NOTALIVE, HELPER_ALIVE } async_helper_state;
 
 static struct shim_thread* async_helper_thread;
 static struct shim_lock async_helper_lock;
@@ -68,27 +67,27 @@ static int create_async_helper(void);
  * or 0 for async IO events. On error, it returns -1.
  */
 int64_t install_async_event(PAL_HANDLE object, uint64_t time,
-                            void (*callback) (IDTYPE caller, void * arg),
-                            void * arg) {
+                            void (*callback)(IDTYPE caller, void* arg), void* arg) {
     /* if event happens on object, time must be zero */
     assert(!object || (object && !time));
 
-    uint64_t now = DkSystemTimeQuery();
+    uint64_t now                  = DkSystemTimeQuery();
     uint64_t max_prev_expire_time = now;
 
     struct async_event* event = malloc(sizeof(struct async_event));
-    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);
 
     if (callback != &cleanup_thread && !object) {
         /* This is alarm() or setitimer() emulation, treat both according to
          * alarm() syscall semantics: cancel any pending alarm/timer. */
-        struct async_event * tmp, * n;
+        struct async_event* tmp;
+        struct async_event* n;
         LISTP_FOR_EACH_ENTRY_SAFE(tmp, n, &async_list, list) {
             if (tmp->expire_time) {
                 /* this is a pending alarm/timer, cancel it and save its expiration time */
@@ -139,8 +138,8 @@ int init_async(void) {
     return 0;
 }
 
-static void shim_async_helper(void * arg) {
-    struct shim_thread * self = (struct shim_thread *) arg;
+static void shim_async_helper(void* arg) {
+    struct shim_thread* self = (struct shim_thread*)arg;
     if (!arg)
         return;
 
@@ -173,11 +172,10 @@ static void shim_async_helper(void * arg) {
 
     /* init object_list so that it always contains at least install_new_event */
     size_t object_list_size = 32;
-    PAL_HANDLE * object_list =
-            malloc(sizeof(PAL_HANDLE) * (1 + object_list_size));
+    PAL_HANDLE* object_list = malloc(sizeof(PAL_HANDLE) * (1 + object_list_size));
 
     PAL_HANDLE install_new_event_hdl = event_handle(&install_new_event);
-    object_list[0] = install_new_event_hdl;
+    object_list[0]                   = install_new_event_hdl;
 
     while (true) {
         uint64_t now = DkSystemTimeQuery();
@@ -204,9 +202,10 @@ static void shim_async_helper(void * arg) {
          *   - repopulate object_list with async IO events (if any), and
          *   - find the next expiring alarm/timer (if any) */
         uint64_t next_expire_time = 0;
-        size_t object_num = 0;
+        size_t object_num         = 0;
 
-        struct async_event * tmp, * n;
+        struct async_event* tmp;
+        struct async_event* n;
         LISTP_FOR_EACH_ENTRY_SAFE(tmp, n, &async_list, list) {
             /* First check if this event was triggered; there are three types:
              *   1. Exited child:  trigger callback and remove from the list;
@@ -231,8 +230,8 @@ static void shim_async_helper(void * arg) {
                 lock(&async_helper_lock);
                 goto again;
             } else if (tmp->expire_time && tmp->expire_time <= now) {
-                debug("Async alarm/timer triggered at %lu (expired at %lu)\n",
-                        now, tmp->expire_time);
+                debug("Async alarm/timer triggered at %lu (expired at %lu)\n", now,
+                      tmp->expire_time);
                 LISTP_DEL(tmp, &async_list, list);
                 LISTP_ADD_TAIL(tmp, &triggered, list);
                 continue;
@@ -242,10 +241,8 @@ static void shim_async_helper(void * arg) {
             if (tmp->object) {
                 if (object_num == object_list_size) {
                     /* grow object_list to accomodate more objects */
-                    PAL_HANDLE * tmp_array = malloc(
-                            sizeof(PAL_HANDLE) * (1 + object_list_size * 2));
-                    memcpy(tmp_array, object_list,
-                            sizeof(PAL_HANDLE) * (1 + object_list_size));
+                    PAL_HANDLE* tmp_array = malloc(sizeof(PAL_HANDLE) * (1 + object_list_size * 2));
+                    memcpy(tmp_array, object_list, sizeof(PAL_HANDLE) * (1 + object_list_size));
                     object_list_size *= 2;
                     free(object_list);
                     object_list = tmp_array;
@@ -272,10 +269,10 @@ static void shim_async_helper(void * arg) {
 
         uint64_t sleep_time;
         if (next_expire_time) {
-            sleep_time = next_expire_time - now;
+            sleep_time  = next_expire_time - now;
             idle_cycles = 0;
         } else if (object_num) {
-            sleep_time = NO_TIMEOUT;
+            sleep_time  = NO_TIMEOUT;
             idle_cycles = 0;
         } else {
             /* no async IO events and no timers/alarms: thread is idling */
@@ -284,7 +281,7 @@ static void shim_async_helper(void * arg) {
         }
 
         if (idle_cycles == MAX_IDLE_CYCLES) {
-            async_helper_state = HELPER_NOTALIVE;
+            async_helper_state  = HELPER_NOTALIVE;
             async_helper_thread = NULL;
             unlock(&async_helper_lock);
             debug("Async helper thread has been idle for some time; stopping it\n");
@@ -314,13 +311,13 @@ static int create_async_helper(void) {
         return -ENOMEM;
 
     async_helper_thread = new;
-    async_helper_state = HELPER_ALIVE;
+    async_helper_state  = HELPER_ALIVE;
 
     PAL_HANDLE handle = thread_create(shim_async_helper, new);
 
     if (!handle) {
         async_helper_thread = NULL;
-        async_helper_state = HELPER_NOTALIVE;
+        async_helper_state  = HELPER_NOTALIVE;
         put_thread(new);
         return -PAL_ERRNO;
     }

+ 6 - 3
LibOS/shim/src/shim_parser.c

@@ -492,8 +492,9 @@ void parse_syscall_before(int sysno, const char* name, int nr, ...) {
             const char* type = va_arg(ap, const char*);
             __UNUSED(type);  // type not needed on this path
             (*parser->parser[i])(ap);
-        } else
+        } else {
             parse_syscall_args(ap);
+        }
     }
 
     PUTCH(')');
@@ -540,8 +541,9 @@ void parse_syscall_after(int sysno, const char* name, int nr, ...) {
                 const char* type = va_arg(ap, const char*);
                 __UNUSED(type);  // type not needed on this path
                 (*parser->parser[i])(ap);
-            } else
+            } else {
                 parse_syscall_args(ap);
+            }
         }
 
     if (is_pointer(ret_type)) {
@@ -565,8 +567,9 @@ static void parse_open_flags(va_list ap) {
     } else if (flags & O_RDWR) {
         PUTS("O_RDWR");
         flags &= ~O_RDWR;
-    } else
+    } else {
         PUTS("O_RDONLY");
+    }
 
     if (flags & O_APPEND) {
         PUTS("|O_APPEND");

+ 14 - 16
LibOS/shim/src/sys/shim_access.c

@@ -20,51 +20,49 @@
  * Implementation of system call "access" and "faccessat".
  */
 
-#include <shim_internal.h>
-#include <shim_table.h>
-#include <shim_thread.h>
-#include <shim_handle.h>
-#include <shim_fs.h>
+#include <errno.h>
+#include <linux/fcntl.h>
 
 #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 <linux/fcntl.h>
-#include <errno.h>
-
-int shim_do_access (const char * file, mode_t mode)
-{
+int shim_do_access(const char* file, mode_t mode) {
     if (!file)
         return -EINVAL;
 
     if (test_user_string(file))
         return -EFAULT;
 
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
-    ret = path_lookupat(NULL, file, LOOKUP_ACCESS|LOOKUP_FOLLOW, &dent, NULL);
+    ret = path_lookupat(NULL, file, LOOKUP_ACCESS | LOOKUP_FOLLOW, &dent, NULL);
     if (!ret)
         ret = permission(dent, mode);
 
     return ret;
 }
 
-int shim_do_faccessat (int dfd, const char * filename, mode_t mode)
-{
+int shim_do_faccessat(int dfd, const char* filename, mode_t mode) {
     if (!filename)
         return -EINVAL;
 
     if (test_user_string(filename))
         return -EFAULT;
 
-    struct shim_dentry * dir = NULL, * dent = NULL;
+    struct shim_dentry* dir = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if ((ret = get_dirfd_dentry(dfd, &dir)) < 0)
         return ret;
 
-    ret = path_lookupat(dir, filename, LOOKUP_ACCESS|LOOKUP_FOLLOW, &dent, NULL);
+    ret = path_lookupat(dir, filename, LOOKUP_ACCESS | LOOKUP_FOLLOW, &dent, NULL);
     if (ret < 0)
         goto out;
 

+ 54 - 71
LibOS/shim/src/sys/shim_brk.c

@@ -20,18 +20,17 @@
  * Implementation of system call "brk".
  */
 
+#include <sys/mman.h>
+
+#include <pal.h>
+#include <shim_checkpoint.h>
 #include <shim_internal.h>
-#include <shim_utils.h>
+#include <shim_profile.h>
 #include <shim_table.h>
+#include <shim_utils.h>
 #include <shim_vma.h>
-#include <shim_checkpoint.h>
-#include <shim_profile.h>
-
-#include <pal.h>
-
-#include <sys/mman.h>
 
-#define BRK_SIZE           4096
+#define BRK_SIZE 4096
 
 struct shim_brk_info {
     size_t data_segment_size;
@@ -46,8 +45,7 @@ DEFINE_PROFILE_OCCURENCE(brk, memory);
 DEFINE_PROFILE_OCCURENCE(brk_count, memory);
 DEFINE_PROFILE_OCCURENCE(brk_migrate_count, memory);
 
-void get_brk_region (void ** start, void ** end, void ** current)
-{
+void get_brk_region(void** start, void** end, void** current) {
     MASTER_LOCK();
     *start   = region.brk_start;
     *end     = region.brk_end;
@@ -59,7 +57,7 @@ int init_brk_region(void* brk_region, size_t data_segment_size) {
     if (region.brk_start)
         return 0;
 
-    data_segment_size = ALLOC_ALIGN_UP(data_segment_size);
+    data_segment_size     = ALLOC_ALIGN_UP(data_segment_size);
     uint64_t brk_max_size = DEFAULT_BRK_MAX_SIZE;
 
     if (root_config) {
@@ -70,16 +68,15 @@ int init_brk_region(void* brk_region, size_t data_segment_size) {
 
     set_rlimit_cur(RLIMIT_DATA, brk_max_size + data_segment_size);
 
-    int flags = MAP_PRIVATE|MAP_ANONYMOUS;
+    int flags        = MAP_PRIVATE | MAP_ANONYMOUS;
     bool brk_on_heap = true;
-    const int TRIES = 10;
+    const int TRIES  = 10;
 
     /*
      * Chia-Che 8/24/2017
-     * Adding an argument to specify the initial starting
-     * address of brk region.
-     * The general assumption of Linux is that the brk region
-     * should be within [exec-data-end, exec-data-end + 0x2000000)
+     * Adding an argument to specify the initial starting address of brk region. The general
+     * assumption of Linux is that the brk region should be within
+     * [exec-data-end, exec-data-end + 0x2000000).
      */
     if (brk_region) {
         size_t max_brk = 0;
@@ -89,7 +86,8 @@ int init_brk_region(void* brk_region, size_t data_segment_size) {
         if (PAL_CB(user_address_hole.end) - PAL_CB(user_address_hole.start) > 0) {
             /* XXX: This assumes that we always want brk to be after the hole. */
             brk_region = MAX(brk_region, PAL_CB(user_address_hole.end));
-            max_brk = MIN(max_brk, (size_t) (PAL_CB(user_address.end) - PAL_CB(user_address_hole.end)));
+            max_brk =
+                MIN(max_brk, (size_t)(PAL_CB(user_address.end) - PAL_CB(user_address_hole.end)));
         }
 
         /* Check whether the brk region can potentially be located after exec at all. */
@@ -129,27 +127,26 @@ int init_brk_region(void* brk_region, size_t data_segment_size) {
     }
 
     if (brk_on_heap) {
-        brk_region = bkeep_unmapped_heap(brk_max_size, PROT_READ|PROT_WRITE,
-                                         flags|VMA_UNMAPPED, NULL, 0, "brk");
+        brk_region = bkeep_unmapped_heap(brk_max_size, PROT_READ | PROT_WRITE, flags | VMA_UNMAPPED,
+                                         NULL, 0, "brk");
         if (!brk_region) {
             return -ENOMEM;
         }
     } else {
         /*
-         * Create the bookkeeping before allocating the brk region.
-         * The bookkeeping should never fail because we've already confirmed
-         * the availability.
+         * Create the bookkeeping before allocating the brk region. The bookkeeping should never
+         * fail because we've already confirmed the availability.
          */
-        if (bkeep_mmap(brk_region, brk_max_size, PROT_READ|PROT_WRITE,
-                       flags|VMA_UNMAPPED, NULL, 0, "brk") < 0)
+        if (bkeep_mmap(brk_region, brk_max_size, PROT_READ | PROT_WRITE, flags | VMA_UNMAPPED, NULL,
+                       0, "brk") < 0)
             BUG();
     }
 
-    void * end_brk_region = NULL;
+    void* end_brk_region = NULL;
 
     /* Allocate the whole brk region */
-    void * ret = (void *) DkVirtualMemoryAlloc(brk_region, brk_max_size, 0,
-                                               PAL_PROT_READ|PAL_PROT_WRITE);
+    void* ret =
+        (void*)DkVirtualMemoryAlloc(brk_region, brk_max_size, 0, PAL_PROT_READ | PAL_PROT_WRITE);
 
     /* Checking if the PAL call succeeds. */
     if (!ret) {
@@ -163,28 +160,24 @@ int init_brk_region(void* brk_region, size_t data_segment_size) {
     end_brk_region = brk_region + BRK_SIZE;
 
     region.data_segment_size = data_segment_size;
-    region.brk_start = brk_region;
-    region.brk_end = end_brk_region;
-    region.brk_current = brk_region;
+    region.brk_start         = brk_region;
+    region.brk_end           = end_brk_region;
+    region.brk_current       = brk_region;
 
     debug("brk area: %p - %p\n", brk_region, end_brk_region);
-    debug("brk reserved area: %p - %p\n", end_brk_region,
-          brk_region + brk_max_size);
+    debug("brk reserved area: %p - %p\n", end_brk_region, brk_region + brk_max_size);
 
     /*
-     * Create another bookkeeping for the current brk region. The remaining
-     * space will be marked as unmapped so that the library OS can reuse the
-     * space for other purpose.
+     * Create another bookkeeping for the current brk region. The remaining space will be marked as
+     * unmapped so that the library OS can reuse the space for other purpose.
      */
-    if (bkeep_mmap(brk_region, BRK_SIZE, PROT_READ|PROT_WRITE, flags,
-                   NULL, 0, "brk") < 0)
+    if (bkeep_mmap(brk_region, BRK_SIZE, PROT_READ | PROT_WRITE, flags, NULL, 0, "brk") < 0)
         BUG();
 
     return 0;
 }
 
-int reset_brk (void)
-{
+int reset_brk(void) {
     MASTER_LOCK();
 
     if (!region.brk_start) {
@@ -192,8 +185,7 @@ int reset_brk (void)
         return 0;
     }
 
-    int ret = shim_do_munmap(region.brk_start,
-                             region.brk_end - region.brk_start);
+    int ret = shim_do_munmap(region.brk_start, region.brk_end - region.brk_start);
 
     if (ret < 0) {
         MASTER_UNLOCK();
@@ -206,17 +198,17 @@ int reset_brk (void)
     return 0;
 }
 
-void* shim_do_brk (void* brk) {
+void* shim_do_brk(void* brk) {
     MASTER_LOCK();
 
-    if (init_brk_region(NULL, 0) < 0) { // If brk is never initialized, assume no executable
+    if (init_brk_region(NULL, 0) < 0) {  // If brk is never initialized, assume no executable
         debug("Failed to initialize brk!\n");
         brk = NULL;
         goto out;
     }
 
     if (!brk) {
-unchanged:
+    unchanged:
         brk = region.brk_current;
         goto out;
     }
@@ -238,20 +230,18 @@ unchanged:
         if (brk > region.brk_start + brk_max_size)
             goto unchanged;
 
-        void * brk_end = region.brk_end;
+        void* brk_end = region.brk_end;
         while (brk_end < brk)
             brk_end += BRK_SIZE;
 
         debug("brk area: %p - %p\n", region.brk_start, brk_end);
-        debug("brk reserved area: %p - %p\n", brk_end,
-              region.brk_start + brk_max_size);
+        debug("brk reserved area: %p - %p\n", brk_end, region.brk_start + brk_max_size);
 
-        bkeep_mmap(region.brk_start, brk_end - region.brk_start,
-                   PROT_READ|PROT_WRITE,
-                   MAP_ANONYMOUS|MAP_PRIVATE, NULL, 0, "brk");
+        bkeep_mmap(region.brk_start, brk_end - region.brk_start, PROT_READ | PROT_WRITE,
+                   MAP_ANONYMOUS | MAP_PRIVATE, NULL, 0, "brk");
 
         region.brk_current = brk;
-        region.brk_end = brk_end;
+        region.brk_end     = brk_end;
         goto out;
     }
     region.brk_current = brk;
@@ -261,8 +251,7 @@ out:
     return brk;
 }
 
-BEGIN_CP_FUNC(brk)
-{
+BEGIN_CP_FUNC(brk) {
     __UNUSED(obj);
     __UNUSED(size);
     __UNUSED(objp);
@@ -275,23 +264,22 @@ BEGIN_CP_FUNC(brk)
 }
 END_CP_FUNC(bek)
 
-BEGIN_RS_FUNC(brk)
-{
+BEGIN_RS_FUNC(brk) {
     __UNUSED(rebase);
-    region.brk_start   = (void *) GET_CP_FUNC_ENTRY();
-    region.brk_current = (void *) GET_CP_ENTRY(ADDR);
-    region.brk_end     = region.brk_start + GET_CP_ENTRY(SIZE);
+    region.brk_start         = (void*)GET_CP_FUNC_ENTRY();
+    region.brk_current       = (void*)GET_CP_ENTRY(ADDR);
+    region.brk_end           = region.brk_start + GET_CP_ENTRY(SIZE);
     region.data_segment_size = GET_CP_ENTRY(SIZE);
 
     debug("brk area: %p - %p\n", region.brk_start, region.brk_end);
 
-    size_t brk_size = region.brk_end - region.brk_start;
+    size_t brk_size    = region.brk_end - region.brk_start;
     uint64_t rlim_data = get_rlimit_cur(RLIMIT_DATA);
     assert(rlim_data > region.data_segment_size);
     uint64_t brk_max_size = rlim_data - region.data_segment_size;
 
     if (brk_size < brk_max_size) {
-        void * alloc_addr = region.brk_end;
+        void* alloc_addr  = region.brk_end;
         size_t alloc_size = brk_max_size - brk_size;
         struct shim_vma_val vma;
 
@@ -301,25 +289,20 @@ BEGIN_RS_FUNC(brk)
             set_rlimit_cur(RLIMIT_DATA, (uint64_t)brk_size + alloc_size + region.data_segment_size);
         }
 
-        int ret = bkeep_mmap(alloc_addr, alloc_size,
-                             PROT_READ|PROT_WRITE,
-                             MAP_ANONYMOUS|MAP_PRIVATE|VMA_UNMAPPED,
-                             NULL, 0, "brk");
+        int ret = bkeep_mmap(alloc_addr, alloc_size, PROT_READ | PROT_WRITE,
+                             MAP_ANONYMOUS | MAP_PRIVATE | VMA_UNMAPPED, NULL, 0, "brk");
         if (ret < 0)
             return ret;
 
-        void * ptr = DkVirtualMemoryAlloc(alloc_addr, alloc_size, 0,
-                                          PAL_PROT_READ|PAL_PROT_WRITE);
+        void* ptr = DkVirtualMemoryAlloc(alloc_addr, alloc_size, 0, PAL_PROT_READ | PAL_PROT_WRITE);
         __UNUSED(ptr);
         assert(ptr == alloc_addr);
         ADD_PROFILE_OCCURENCE(brk, alloc_size);
         INC_PROFILE_OCCURENCE(brk_migrate_count);
 
-        debug("brk reserved area: %p - %p\n", alloc_addr,
-              alloc_addr + alloc_size);
+        debug("brk reserved area: %p - %p\n", alloc_addr, alloc_addr + alloc_size);
     }
 
-    DEBUG_RS("current=%p,region=%p-%p", region.brk_current, region.brk_start,
-             region.brk_end);
+    DEBUG_RS("current=%p,region=%p-%p", region.brk_current, region.brk_start, region.brk_end);
 }
 END_RS_FUNC(brk)

+ 15 - 18
LibOS/shim/src/sys/shim_eventfd.c

@@ -17,21 +17,21 @@
 /*
  * shim_eventfd.c
  *
- * Implementation of system calls "eventfd" and "eventfd2". Since eventfd emulation currently
- * relies on the host, these system calls are disallowed by default due to security concerns.
- * To use them, they must be explicitly allowed through the "sys.allow_insecure_eventfd" manifest
- * key.
+ * Implementation of system calls "eventfd" and "eventfd2". Since eventfd emulation currently relies
+ * on the host, these system calls are disallowed by default due to security concerns. To use them,
+ * they must be explicitly allowed through the "sys.allow_insecure_eventfd" manifest key.
  */
 
 #include <asm/fcntl.h>
 #include <sys/eventfd.h>
+
 #include <pal.h>
 #include <pal_error.h>
+#include <shim_fs.h>
+#include <shim_handle.h>
 #include <shim_internal.h>
-#include <shim_utils.h>
 #include <shim_table.h>
-#include <shim_handle.h>
-#include <shim_fs.h>
+#include <shim_utils.h>
 
 static int create_eventfd(PAL_HANDLE* efd, unsigned count, int flags) {
     if (!root_config) {
@@ -40,22 +40,22 @@ static int create_eventfd(PAL_HANDLE* efd, unsigned count, int flags) {
     }
 
     char eventfd_cfg[2];
-    ssize_t len = get_config(root_config, "sys.allow_insecure_eventfd", eventfd_cfg,
-                             sizeof(eventfd_cfg));
+    ssize_t len =
+        get_config(root_config, "sys.allow_insecure_eventfd", eventfd_cfg, sizeof(eventfd_cfg));
     if (len != 1 || eventfd_cfg[0] != '1') {
         /* eventfd is not explicitly allowed in manifest */
         return -ENOSYS;
     }
 
     PAL_HANDLE hdl = NULL;
-    int pal_flags = 0;
+    int pal_flags  = 0;
 
     pal_flags |= flags & EFD_NONBLOCK ? PAL_OPTION_NONBLOCK : 0;
     pal_flags |= flags & EFD_CLOEXEC ? PAL_OPTION_CLOEXEC : 0;
     pal_flags |= flags & EFD_SEMAPHORE ? PAL_OPTION_EFD_SEMAPHORE : 0;
 
-    /* eventfd() requires count (aka initval) but PAL's DkStreamOpen() doesn't have such an argument.
-     * Using create arg as a work-around (note: initval is uint32 but create is int32).*/
+    /* eventfd() requires count (aka initval) but PAL's DkStreamOpen() doesn't have such an
+     * argument. Using create arg as a work-around (note: initval is uint32 but create is int32). */
     if (!(hdl = DkStreamOpen(URI_PREFIX_EVENTFD, 0, 0, count, pal_flags))) {
         debug("eventfd open failure\n");
         return -PAL_ERRNO;
@@ -63,7 +63,6 @@ static int create_eventfd(PAL_HANDLE* efd, unsigned count, int flags) {
 
     *efd = hdl;
     return 0;
-
 }
 
 int shim_do_eventfd2(unsigned int count, int flags) {
@@ -77,7 +76,7 @@ int shim_do_eventfd2(unsigned int count, int flags) {
 
     hdl->type = TYPE_EVENTFD;
     set_handle_fs(hdl, &eventfd_builtin_fs);
-    hdl->flags = O_RDWR;
+    hdl->flags    = O_RDWR;
     hdl->acc_mode = MAY_READ | MAY_WRITE;
 
     if ((ret = create_eventfd(&hdl->pal_handle, count, flags)) < 0)
@@ -85,9 +84,8 @@ int shim_do_eventfd2(unsigned int count, int flags) {
 
     flags = flags & EFD_CLOEXEC ? FD_CLOEXEC : 0;
 
-    /* get_new_handle() above increments hdl's refcount.
-     * Followed by another increment inside set_new_fd_handle.
-     * So we need to put_handle() afterwards. */
+    /* get_new_handle() above increments hdl's refcount. Followed by another increment inside
+     * set_new_fd_handle. So we need to put_handle() afterwards. */
     int vfd = set_new_fd_handle(hdl, flags, NULL);
 
     ret = vfd;
@@ -97,7 +95,6 @@ out:
         put_handle(hdl);
 
     return ret;
-
 }
 
 int shim_do_eventfd(unsigned int count) {

+ 100 - 118
LibOS/shim/src/sys/shim_exec.c

@@ -20,23 +20,20 @@
  * Implementation of system call "execve".
  */
 
-#include <shim_internal.h>
-#include <shim_table.h>
-#include <shim_thread.h>
-#include <shim_fs.h>
-#include <shim_ipc.h>
-#include <shim_profile.h>
-
-#include <pal.h>
-#include <pal_error.h>
-
+#include <asm/prctl.h>
 #include <errno.h>
-
 #include <linux/futex.h>
-
-#include <sys/syscall.h>
 #include <sys/mman.h>
-#include <asm/prctl.h>
+#include <sys/syscall.h>
+
+#include <pal.h>
+#include <pal_error.h>
+#include <shim_fs.h>
+#include <shim_internal.h>
+#include <shim_ipc.h>
+#include <shim_profile.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) {
@@ -45,8 +42,8 @@ static int normalize_and_cmp_uris(const char* uri1, const char* uri2) {
     size_t len;
     int ret;
 
-    if (!strstartswith_static(uri1, URI_PREFIX_FILE)
-            || !strstartswith_static(uri2, URI_PREFIX_FILE))
+    if (!strstartswith_static(uri1, URI_PREFIX_FILE) ||
+        !strstartswith_static(uri2, URI_PREFIX_FILE))
         return -1;
 
     uri1 += URI_PREFIX_FILE_LEN;
@@ -64,18 +61,15 @@ static int normalize_and_cmp_uris(const char* uri1, const char* uri2) {
     return memcmp(norm1, norm2, len + 1);
 }
 
-static int close_on_exec (struct shim_fd_handle * fd_hdl,
-                          struct shim_handle_map * map)
-{
+static int close_on_exec(struct shim_fd_handle* fd_hdl, struct shim_handle_map* map) {
     if (fd_hdl->flags & FD_CLOEXEC) {
-        struct shim_handle * hdl = __detach_fd_handle(fd_hdl, NULL, map);
+        struct shim_handle* hdl = __detach_fd_handle(fd_hdl, NULL, map);
         put_handle(hdl);
     }
     return 0;
 }
 
-static int close_cloexec_handle (struct shim_handle_map * map)
-{
+static int close_cloexec_handle(struct shim_handle_map* map) {
     return walk_handle_map(&close_on_exec, map);
 }
 
@@ -87,30 +81,28 @@ DEFINE_PROFILE_INTERVAL(unmap_loaded_binaries_for_exec, exec_rtld);
 DEFINE_PROFILE_INTERVAL(unmap_all_vmas_for_exec, exec_rtld);
 DEFINE_PROFILE_INTERVAL(load_new_executable_for_exec, exec_rtld);
 
-int init_brk_from_executable (struct shim_handle * exec);
+int init_brk_from_executable(struct shim_handle* exec);
 
-struct execve_rtld_arg
-{
-    void *        old_stack_top;
-    void *        old_stack;
-    void *        old_stack_red;
-    const char ** new_argp;
-    int *         new_argcp;
-    elf_auxv_t *  new_auxp;
+struct execve_rtld_arg {
+    void* old_stack_top;
+    void* old_stack;
+    void* old_stack_red;
+    const char** new_argp;
+    int* new_argcp;
+    elf_auxv_t* new_auxp;
 };
 
-noreturn static void __shim_do_execve_rtld (struct execve_rtld_arg * __arg)
-{
+noreturn static void __shim_do_execve_rtld(struct execve_rtld_arg* __arg) {
     struct execve_rtld_arg arg;
     memcpy(&arg, __arg, sizeof(arg));
-    void * old_stack_top = arg.old_stack_top;
-    void * old_stack = arg.old_stack;
-    void * old_stack_red = arg.old_stack_red;
-    const char ** new_argp = arg.new_argp;
-    int * new_argcp = arg.new_argcp;
-    elf_auxv_t * new_auxp = arg.new_auxp;
-
-    struct shim_thread * cur_thread = get_cur_thread();
+    void* old_stack_top   = arg.old_stack_top;
+    void* old_stack       = arg.old_stack;
+    void* old_stack_red   = arg.old_stack_red;
+    const char** new_argp = arg.new_argp;
+    int* new_argcp        = arg.new_argcp;
+    elf_auxv_t* new_auxp  = arg.new_auxp;
+
+    struct shim_thread* cur_thread = get_cur_thread();
     int ret = 0;
 
     unsigned long fs_base = 0;
@@ -133,7 +125,7 @@ noreturn static void __shim_do_execve_rtld (struct execve_rtld_arg * __arg)
     reset_brk();
 
     size_t count = DEFAULT_VMA_COUNT;
-    struct shim_vma_val * vmas = malloc(sizeof(struct shim_vma_val) * count);
+    struct shim_vma_val* vmas = malloc(sizeof(struct shim_vma_val) * count);
 
     if (!vmas) {
         ret = -ENOMEM;
@@ -144,8 +136,7 @@ retry_dump_vmas:
     ret = dump_all_vmas(vmas, count);
 
     if (ret == -EOVERFLOW) {
-        struct shim_vma_val * new_vmas
-                = malloc(sizeof(struct shim_vma_val) * count * 2);
+        struct shim_vma_val* new_vmas = malloc(sizeof(struct shim_vma_val) * count * 2);
         if (!new_vmas) {
             free(vmas);
             ret = -ENOMEM;
@@ -163,7 +154,7 @@ retry_dump_vmas:
     }
 
     count = ret;
-    for (struct shim_vma_val * vma = vmas ; vma < vmas + count ; vma++) {
+    for (struct shim_vma_val* vma = vmas; vma < vmas + count; vma++) {
         /* Don't free the current stack */
         if (vma->addr == cur_thread->stack)
             continue;
@@ -206,12 +197,10 @@ error:
     shim_clean_and_exit(ret);
 }
 
-static int shim_do_execve_rtld (struct shim_handle * hdl, const char ** argv,
-                         const char ** envp)
-{
+static int shim_do_execve_rtld(struct shim_handle* hdl, const char** argv, const char** envp) {
     BEGIN_PROFILE_INTERVAL();
 
-    struct shim_thread * cur_thread = get_cur_thread();
+    struct shim_thread* cur_thread = get_cur_thread();
     int ret;
 
     if ((ret = close_cloexec_handle(cur_thread->handle_map)) < 0)
@@ -223,34 +212,34 @@ static int shim_do_execve_rtld (struct shim_handle * hdl, const char ** argv,
     get_handle(hdl);
     cur_thread->exec = hdl;
 
-    void * old_stack_top = cur_thread->stack_top;
-    void * old_stack     = cur_thread->stack;
-    void * old_stack_red = cur_thread->stack_red;
+    void* old_stack_top   = cur_thread->stack_top;
+    void* old_stack       = cur_thread->stack;
+    void* old_stack_red   = cur_thread->stack_red;
     cur_thread->stack_top = NULL;
     cur_thread->stack     = NULL;
     cur_thread->stack_red = NULL;
 
     initial_envp = NULL;
     int new_argc = 0;
-    for (const char ** a = argv ; *a ; a++, new_argc++);
+    for (const char** a = argv; *a; a++, new_argc++)
+        ;
 
-    int * new_argcp = &new_argc;
-    const char ** new_argp;
-    elf_auxv_t * new_auxp;
+    int* new_argcp = &new_argc;
+    const char** new_argp;
+    elf_auxv_t* new_auxp;
     if ((ret = init_stack(argv, envp, &new_argcp, &new_argp, &new_auxp)) < 0)
         return ret;
 
-    __disable_preempt(shim_get_tcb()); // Temporarily disable preemption
-                                       // during execve().
+    __disable_preempt(shim_get_tcb());  // Temporarily disable preemption during execve().
     SAVE_PROFILE_INTERVAL(alloc_new_stack_for_exec);
 
     struct execve_rtld_arg arg = {
         .old_stack_top = old_stack_top,
-        .old_stack = old_stack,
+        .old_stack     = old_stack,
         .old_stack_red = old_stack_red,
-        .new_argp = new_argp,
-        .new_argcp = new_argcp,
-        .new_auxp = new_auxp
+        .new_argp      = new_argp,
+        .new_argcp     = new_argcp,
+        .new_auxp      = new_auxp
     };
     __SWITCH_STACK(new_argcp, &__shim_do_execve_rtld, &arg);
     return 0;
@@ -265,12 +254,10 @@ DEFINE_PROFILE_INTERVAL(close_CLOEXEC_files_for_exec, exec);
 
 /* thread is cur_thread stripped off stack & tcb (see below func);
  * process is new process which is forked and waits for checkpoint. */
-static int migrate_execve (struct shim_cp_store * cpstore,
-                           struct shim_thread * thread,
-                           struct shim_process * process, va_list ap)
-{
-    struct shim_handle_map * handle_map;
-    const char ** envp = va_arg(ap, const char **);
+static int migrate_execve(struct shim_cp_store* cpstore, struct shim_thread* thread,
+                          struct shim_process* process, va_list ap) {
+    struct shim_handle_map* handle_map;
+    const char** envp = va_arg(ap, const char**);
     int ret;
 
     BEGIN_PROFILE_INTERVAL();
@@ -291,16 +278,12 @@ static int migrate_execve (struct shim_cp_store * cpstore,
             2. cur_threadrent filesystem
             3. handle mapping
             4. each handle              */
-    BEGIN_MIGRATION_DEF(execve,
-                        struct shim_thread * thread,
-                        struct shim_process * proc,
-                        const char ** envp)
-    {
+    BEGIN_MIGRATION_DEF(execve, struct shim_thread* thread, struct shim_process* proc,
+                        const char** envp) {
         DEFINE_MIGRATE(process, proc, sizeof(struct shim_process));
         DEFINE_MIGRATE(all_mounts, NULL, 0);
         DEFINE_MIGRATE(running_thread, thread, sizeof(struct shim_thread));
-        DEFINE_MIGRATE(handle_map, thread->handle_map,
-                       sizeof (struct shim_handle_map));
+        DEFINE_MIGRATE(handle_map, thread->handle_map, sizeof(struct shim_handle_map));
         DEFINE_MIGRATE(migratable, NULL, 0);
         DEFINE_MIGRATE(environ, envp, 0);
     }
@@ -309,12 +292,9 @@ static int migrate_execve (struct shim_cp_store * cpstore,
     return START_MIGRATE(cpstore, execve, thread, process, envp);
 }
 
-
-int shim_do_execve (const char * file, const char ** argv,
-                    const char ** envp)
-{
-    struct shim_thread * cur_thread = get_cur_thread();
-    struct shim_dentry * dent = NULL;
+int shim_do_execve(const char* file, const char** argv, const char** envp) {
+    struct shim_thread* cur_thread = get_cur_thread();
+    struct shim_dentry* dent       = NULL;
     int ret = 0, argc = 0;
 
     if (test_user_string(file))
@@ -343,10 +323,9 @@ int shim_do_execve (const char * file, const char ** argv,
 
     BEGIN_PROFILE_INTERVAL();
 
-
     DEFINE_LIST(sharg);
     struct sharg {
-        LIST_TYPE(sharg)  list;
+        LIST_TYPE(sharg) list;
         int len;
         char arg[0];
     };
@@ -361,12 +340,12 @@ reopen:
     if ((ret = path_lookupat(NULL, file, LOOKUP_OPEN, &dent, NULL)) < 0)
         return ret;
 
-    struct shim_mount * fs = dent->fs;
+    struct shim_mount* fs = dent->fs;
     get_dentry(dent);
 
     if (!fs->d_ops->open) {
         ret = -EACCES;
-err:
+    err:
         put_dentry(dent);
         return ret;
     }
@@ -379,7 +358,7 @@ err:
 
     SAVE_PROFILE_INTERVAL(search_and_check_file_for_exec);
 
-    struct shim_handle * exec = NULL;
+    struct shim_handle* exec = NULL;
 
     if (!(exec = get_new_handle())) {
         ret = -ENOMEM;
@@ -387,7 +366,7 @@ err:
     }
 
     set_handle_fs(exec, fs);
-    exec->flags = O_RDONLY;
+    exec->flags    = O_RDONLY;
     exec->acc_mode = MAY_READ;
     ret = fs->d_ops->open(exec, dent, O_RDONLY);
 
@@ -397,7 +376,7 @@ err:
     }
 
     size_t pathlen;
-    char *path = dentry_get_path(dent, true, &pathlen);
+    char* path = dentry_get_path(dent, true, &pathlen);
     qstrsetstr(&exec->path, path, pathlen);
 
     if ((ret = check_elf_object(exec)) < 0 && ret != -EINVAL) {
@@ -407,7 +386,7 @@ err:
 
     if (ret == -EINVAL) { /* it's a shebang */
         LISTP_TYPE(sharg) new_shargs = LISTP_INIT;
-        struct sharg * next = NULL;
+        struct sharg* next = NULL;
         bool ended = false, started = false;
         char buf[80];
 
@@ -416,7 +395,9 @@ err:
             if (ret <= 0)
                 break;
 
-            char * s = buf, * c = buf, * e = buf + ret;
+            char* s = buf;
+            char* c = buf;
+            char* e = buf + ret;
 
             if (!started) {
                 if (ret < 2 || buf[0] != '#' || buf[1] != '!')
@@ -427,12 +408,11 @@ err:
                 started = true;
             }
 
-            for (; c < e ; c++) {
+            for (; c < e; c++) {
                 if (*c == ' ' || *c == '\n' || c == e - 1) {
-                    int l = (*c == ' ' || * c == '\n') ? c - s : e - s;
+                    int l = (*c == ' ' || *c == '\n') ? c - s : e - s;
                     if (next) {
-                        struct sharg * sh =
-                            __alloca(sizeof(struct sharg) + next->len + l + 1);
+                        struct sharg* sh = __alloca(sizeof(struct sharg) + next->len + l + 1);
                         sh->len = next->len + l;
                         memcpy(sh->arg, next->arg, next->len);
                         memcpy(sh->arg + next->len, s, l);
@@ -464,8 +444,7 @@ err:
                 LISTP_ADD_TAIL(next, &new_shargs, list);
             }
 
-            struct sharg * first =
-                LISTP_FIRST_ENTRY(&new_shargs, struct sharg, list);
+            struct sharg* first = LISTP_FIRST_ENTRY(&new_shargs, struct sharg, list);
             assert(first);
             debug("detected as script: run by %s\n", first->arg);
             file = first->arg;
@@ -479,9 +458,9 @@ err:
 
     bool use_same_process = check_last_thread(cur_thread) == 0;
     if (use_same_process && !strcmp_static(PAL_CB(host_type), "Linux-SGX")) {
-        /* for SGX PALs, can use same process only if it is the same executable (because a
-         * different executable has a different measurement and thus requires a new enclave);
-         * this special case is to correctly handle e.g. Bash process replacing itself */
+        /* for SGX PALs, can use same process only if it is the same executable (because a different
+         * executable has a different measurement and thus requires a new enclave); this special
+         * case is to correctly handle e.g. Bash process replacing itself */
         assert(cur_thread->exec);
         if (normalize_and_cmp_uris(qstrgetstr(&cur_thread->exec->uri), qstrgetstr(&exec->uri))) {
             /* it is not the same executable, definitely cannot use same process */
@@ -498,32 +477,33 @@ err:
     INC_PROFILE_OCCURENCE(syscall_use_ipc);
 
     if (!LISTP_EMPTY(&shargs)) {
-        struct sharg * sh;
+        struct sharg* sh;
         int shargc = 0, cnt = 0;
-        LISTP_FOR_EACH_ENTRY(sh, &shargs, list)
+        LISTP_FOR_EACH_ENTRY(sh, &shargs, list) {
             shargc++;
+        }
 
-        const char ** new_argv =
-                __alloca(sizeof(const char *) * (argc + shargc + 1));
+        const char** new_argv = __alloca(sizeof(const char*) * (argc + shargc + 1));
 
-        LISTP_FOR_EACH_ENTRY(sh, &shargs, list)
+        LISTP_FOR_EACH_ENTRY(sh, &shargs, list) {
             new_argv[cnt++] = sh->arg;
+        }
 
-        for (cnt = 0 ; cnt < argc ; cnt++)
+        for (cnt = 0; cnt < argc; cnt++)
             new_argv[shargc + cnt] = argv[cnt];
 
         new_argv[shargc + argc] = NULL;
-        argv = new_argv;
+        argv                    = new_argv;
     }
 
     lock(&cur_thread->lock);
     put_handle(cur_thread->exec);
     cur_thread->exec = exec;
 
-    void * stack     = cur_thread->stack;
-    void * stack_top = cur_thread->stack_top;
-    shim_tcb_t * shim_tcb = cur_thread->shim_tcb;
-    void * frameptr  = cur_thread->frameptr;
+    void* stack          = cur_thread->stack;
+    void* stack_top      = cur_thread->stack_top;
+    shim_tcb_t* shim_tcb = cur_thread->shim_tcb;
+    void* frameptr       = cur_thread->frameptr;
 
     cur_thread->stack     = NULL;
     cur_thread->stack_top = NULL;
@@ -535,10 +515,10 @@ err:
     ret = do_migrate_process(&migrate_execve, exec, argv, cur_thread, envp);
 
     lock(&cur_thread->lock);
-    cur_thread->stack       = stack;
-    cur_thread->stack_top   = stack_top;
-    cur_thread->frameptr    = frameptr;
-    cur_thread->shim_tcb    = shim_tcb;
+    cur_thread->stack     = stack;
+    cur_thread->stack_top = stack_top;
+    cur_thread->frameptr  = frameptr;
+    cur_thread->shim_tcb  = shim_tcb;
 
     if (ret < 0) {
         /* execve failed, so reanimate this thread as if nothing happened */
@@ -547,10 +527,12 @@ err:
         return ret;
     }
 
-    /* This "temporary" process must die quietly, not sending any messages
-     * to not confuse the parent and the execve'ed child */
-    debug("Temporary process %u exited after emulating execve (by forking new process to replace this one)\n",
-          cur_process.vmid & 0xFFFF);
+    /* This "temporary" process must die quietly, not sending any messages to not confuse the parent
+     * and the execve'ed child */
+    debug(
+        "Temporary process %u exited after emulating execve (by forking new process to replace this"
+        " one)\n",
+        cur_process.vmid & 0xFFFF);
     MASTER_LOCK();
     DkProcessExit(0);
 

+ 20 - 26
LibOS/shim/src/sys/shim_fork.c

@@ -20,30 +20,25 @@
  * Implementation of system call "fork".
  */
 
-#include <shim_internal.h>
-#include <shim_table.h>
-#include <shim_thread.h>
-#include <shim_ipc.h>
-#include <shim_profile.h>
-#include <shim_checkpoint.h>
+#include <asm/prctl.h>
+#include <errno.h>
+#include <linux/futex.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
 
 #include <pal.h>
 #include <pal_error.h>
+#include <shim_checkpoint.h>
+#include <shim_internal.h>
+#include <shim_ipc.h>
+#include <shim_profile.h>
+#include <shim_table.h>
+#include <shim_thread.h>
 
-#include <errno.h>
-#include <sys/syscall.h>
-#include <sys/mman.h>
-#include <asm/prctl.h>
-#include <linux/futex.h>
-
-int migrate_fork (struct shim_cp_store * store,
-                  struct shim_thread * thread,
-                  struct shim_process * process, va_list ap)
-{
+int migrate_fork(struct shim_cp_store* store, struct shim_thread* thread,
+                 struct shim_process* process, va_list ap) {
     __UNUSED(ap);
-    BEGIN_MIGRATION_DEF(fork, struct shim_thread * thread,
-                        struct shim_process * process)
-    {
+    BEGIN_MIGRATION_DEF(fork, struct shim_thread* thread, struct shim_process* process) {
         DEFINE_MIGRATE(process, process, sizeof(struct shim_process));
         DEFINE_MIGRATE(all_mounts, NULL, 0);
         DEFINE_MIGRATE(all_vmas, NULL, 0);
@@ -70,16 +65,15 @@ int migrate_fork (struct shim_cp_store * store,
     return ret;
 }
 
-int shim_do_fork (void)
-{
+int shim_do_fork(void) {
     int ret = 0;
     INC_PROFILE_OCCURENCE(syscall_use_ipc);
 
     if ((ret = prepare_ns_leaders()) < 0)
         return ret;
 
-    struct shim_thread * cur_thread = get_cur_thread();
-    struct shim_thread * new_thread = get_new_thread(0);
+    struct shim_thread* cur_thread = get_cur_thread();
+    struct shim_thread* new_thread = get_new_thread(0);
 
     if (!new_thread)
         return -ENOMEM;
@@ -97,9 +91,9 @@ int shim_do_fork (void)
     }
 
     lock(&new_thread->lock);
-    struct shim_handle_map * handle_map = new_thread->handle_map;
-    new_thread->handle_map = NULL;
-    new_thread->shim_tcb = NULL;
+    struct shim_handle_map* handle_map = new_thread->handle_map;
+    new_thread->handle_map             = NULL;
+    new_thread->shim_tcb               = NULL;
     unlock(&new_thread->lock);
     if (handle_map)
         put_handle_map(handle_map);

+ 107 - 137
LibOS/shim/src/sys/shim_fs.c

@@ -22,35 +22,33 @@
  * "sendfile".
  */
 
-#include <shim_internal.h>
-#include <shim_table.h>
-#include <shim_utils.h>
-#include <shim_thread.h>
-#include <shim_handle.h>
-#include <shim_fs.h>
+#include <asm/mman.h>
+#include <errno.h>
+#include <linux/fcntl.h>
 
 #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>
 
-#include <errno.h>
-
-#include <linux/fcntl.h>
+/* FIXME(mkow): for some reason it must be included last, otherwise S_IFREG is not being
+ * defined inside (sic!). */
 #include <linux/stat.h>
 
-#include <asm/mman.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. */
-int shim_do_unlink (const char * file)
-{
+/* 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. */
+int shim_do_unlink(const char* file) {
     if (!file)
         return -EINVAL;
 
     if (test_user_string(file))
         return -EFAULT;
 
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if ((ret = path_lookupat(NULL, file, LOOKUP_OPEN, &dent, NULL)) < 0)
@@ -62,20 +60,19 @@ int shim_do_unlink (const char * file)
     if (dent->state & DENTRY_ISDIRECTORY)
         return -EISDIR;
 
-    if (dent->fs && dent->fs->d_ops &&
-        dent->fs->d_ops->unlink) {
+    if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->unlink) {
         if ((ret = dent->fs->d_ops->unlink(dent->parent, dent)) < 0)
             return ret;
-    } else
+    } else {
         dent->state |= DENTRY_PERSIST;
+    }
 
     dent->state |= DENTRY_NEGATIVE;
     put_dentry(dent);
     return 0;
 }
 
-int shim_do_unlinkat (int dfd, const char * pathname, int flag)
-{
+int shim_do_unlinkat(int dfd, const char* pathname, int flag) {
     if (!pathname)
         return -EINVAL;
 
@@ -85,7 +82,8 @@ int shim_do_unlinkat (int dfd, const char * pathname, int flag)
     if (flag & ~AT_REMOVEDIR)
         return -EINVAL;
 
-    struct shim_dentry * dir = NULL, * dent = NULL;
+    struct shim_dentry* dir = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if ((ret = get_dirfd_dentry(dfd, &dir)) < 0)
@@ -107,12 +105,12 @@ int shim_do_unlinkat (int dfd, const char * pathname, int flag)
             return -EISDIR;
     }
 
-    if (dent->fs && dent->fs->d_ops &&
-        dent->fs->d_ops->unlink) {
+    if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->unlink) {
         if ((ret = dent->fs->d_ops->unlink(dent->parent, dent)) < 0)
             return ret;
-    } else
+    } else {
         dent->state |= DENTRY_PERSIST;
+    }
 
     if (flag & AT_REMOVEDIR)
         dent->state &= ~DENTRY_ISDIRECTORY;
@@ -125,37 +123,32 @@ out:
     return ret;
 }
 
-int shim_do_mkdir (const char * pathname, int mode)
-{
-    return open_namei(NULL, NULL, pathname, O_CREAT|O_EXCL|O_DIRECTORY,
-                      mode, NULL);
+int shim_do_mkdir(const char* pathname, int mode) {
+    return open_namei(NULL, NULL, pathname, O_CREAT | O_EXCL | O_DIRECTORY, mode, NULL);
 }
 
-int shim_do_mkdirat (int dfd, const char * pathname, int mode)
-{
+int shim_do_mkdirat(int dfd, const char* pathname, int mode) {
     if (!pathname)
         return -EINVAL;
 
     if (test_user_string(pathname))
         return -EFAULT;
 
-    struct shim_dentry * dir = NULL;
+    struct shim_dentry* dir = NULL;
     int ret = 0;
 
     if ((ret = get_dirfd_dentry(dfd, &dir)) < 0)
         return ret;
 
-    ret = open_namei(NULL, dir, pathname, O_CREAT|O_EXCL|O_DIRECTORY,
-                     mode, NULL);
+    ret = open_namei(NULL, dir, pathname, O_CREAT | O_EXCL | O_DIRECTORY, mode, NULL);
 
     put_dentry(dir);
     return ret;
 }
 
-int shim_do_rmdir (const char * pathname)
-{
+int shim_do_rmdir(const char* pathname) {
     int ret = 0;
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
 
     if (!pathname)
         return -EINVAL;
@@ -163,8 +156,7 @@ int shim_do_rmdir (const char * pathname)
     if (test_user_string(pathname))
         return -EFAULT;
 
-    if ((ret = path_lookupat(NULL, pathname, LOOKUP_OPEN|LOOKUP_DIRECTORY,
-                             &dent, NULL)) < 0)
+    if ((ret = path_lookupat(NULL, pathname, LOOKUP_OPEN | LOOKUP_DIRECTORY, &dent, NULL)) < 0)
         return ret;
 
     if (!dent->parent) {
@@ -177,12 +169,12 @@ int shim_do_rmdir (const char * pathname)
         goto out;
     }
 
-    if (dent->fs && dent->fs->d_ops &&
-        dent->fs->d_ops->unlink) {
+    if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->unlink) {
         if ((ret = dent->fs->d_ops->unlink(dent->parent, dent)) < 0)
             goto out;
-    } else
+    } else {
         dent->state |= DENTRY_PERSIST;
+    }
 
     dent->state &= ~DENTRY_ISDIRECTORY;
     dent->state |= DENTRY_NEGATIVE;
@@ -191,9 +183,8 @@ out:
     return 0;
 }
 
-mode_t shim_do_umask (mode_t mask)
-{
-    struct shim_thread * cur = get_cur_thread();
+mode_t shim_do_umask(mode_t mask) {
+    struct shim_thread* cur = get_cur_thread();
     lock(&cur->lock);
     mode_t old = cur->umask;
     cur->umask = mask & 0777;
@@ -201,9 +192,8 @@ mode_t shim_do_umask (mode_t mask)
     return old;
 }
 
-int shim_do_chmod (const char * path, mode_t mode)
-{
-    struct shim_dentry * dent = NULL;
+int shim_do_chmod(const char* path, mode_t mode) {
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if (test_user_string(path))
@@ -212,12 +202,12 @@ int shim_do_chmod (const char * path, mode_t mode)
     if ((ret = path_lookupat(NULL, path, LOOKUP_OPEN, &dent, NULL)) < 0)
         return ret;
 
-    if (dent->fs && dent->fs->d_ops &&
-        dent->fs->d_ops->chmod) {
+    if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->chmod) {
         if ((ret = dent->fs->d_ops->chmod(dent, mode)) < 0)
             goto out;
-    } else
+    } else {
         dent->state |= DENTRY_PERSIST;
+    }
 
     dent->mode = mode;
 out:
@@ -225,15 +215,15 @@ out:
     return ret;
 }
 
-int shim_do_fchmodat (int dfd, const char * filename, mode_t mode)
-{
+int shim_do_fchmodat(int dfd, const char* filename, mode_t mode) {
     if (!filename)
         return -EINVAL;
 
     if (test_user_string(filename))
         return -EFAULT;
 
-    struct shim_dentry * dir = NULL, * dent = NULL;
+    struct shim_dentry* dir = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if ((ret = get_dirfd_dentry(dfd, &dir)) < 0)
@@ -242,12 +232,12 @@ int shim_do_fchmodat (int dfd, const char * filename, mode_t mode)
     if ((ret = path_lookupat(dir, filename, LOOKUP_OPEN, &dent, NULL)) < 0)
         goto out;
 
-    if (dent->fs && dent->fs->d_ops &&
-        dent->fs->d_ops->chmod) {
+    if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->chmod) {
         if ((ret = dent->fs->d_ops->chmod(dent, mode)) < 0)
             goto out_dent;
-    } else
+    } else {
         dent->state |= DENTRY_PERSIST;
+    }
 
     dent->mode = mode;
 out_dent:
@@ -257,13 +247,12 @@ out:
     return ret;
 }
 
-int shim_do_fchmod (int fd, mode_t mode)
-{
-    struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL);
+int shim_do_fchmod(int fd, mode_t mode) {
+    struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL);
     if (!hdl)
         return -EBADF;
 
-    struct shim_dentry * dent = hdl->dentry;
+    struct shim_dentry* dent = hdl->dentry;
     int ret = 0;
 
     if (dent->fs && dent->fs->d_ops && dent->fs->d_ops->chmod) {
@@ -279,9 +268,8 @@ out:
     return ret;
 }
 
-int shim_do_chown (const char * path, uid_t uid, gid_t gid)
-{
-    struct shim_dentry * dent = NULL;
+int shim_do_chown(const char* path, uid_t uid, gid_t gid) {
+    struct shim_dentry* dent = NULL;
     int ret = 0;
     __UNUSED(uid);
     __UNUSED(gid);
@@ -300,9 +288,7 @@ int shim_do_chown (const char * path, uid_t uid, gid_t gid)
     return ret;
 }
 
-int shim_do_fchownat (int dfd, const char * filename, uid_t uid, gid_t gid,
-                      int flags)
-{
+int shim_do_fchownat(int dfd, const char* filename, uid_t uid, gid_t gid, int flags) {
     __UNUSED(flags);
     __UNUSED(uid);
     __UNUSED(gid);
@@ -313,7 +299,8 @@ int shim_do_fchownat (int dfd, const char * filename, uid_t uid, gid_t gid,
     if (test_user_string(filename))
         return -EFAULT;
 
-    struct shim_dentry * dir = NULL, * dent = NULL;
+    struct shim_dentry* dir = NULL;
+    struct shim_dentry* dent = NULL;
     int ret = 0;
 
     if ((ret = get_dirfd_dentry(dfd, &dir)) < 0)
@@ -329,12 +316,11 @@ out:
     return ret;
 }
 
-int shim_do_fchown (int fd, uid_t uid, gid_t gid)
-{
+int shim_do_fchown(int fd, uid_t uid, gid_t gid) {
     __UNUSED(uid);
     __UNUSED(gid);
 
-    struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL);
+    struct shim_handle* hdl = get_fd_handle(fd, NULL, NULL);
     if (!hdl)
         return -EBADF;
 
@@ -345,12 +331,10 @@ int shim_do_fchown (int fd, uid_t uid, gid_t gid)
 #define MAP_SIZE (g_pal_alloc_align * 4)
 #define BUF_SIZE 2048
 
-static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
-                            struct shim_handle * hdlo, off_t * offseto,
-                            ssize_t count)
-{
-    struct shim_mount * fsi = hdli->fs;
-    struct shim_mount * fso = hdlo->fs;
+static ssize_t handle_copy(struct shim_handle* hdli, off_t* offseti, struct shim_handle* hdlo,
+                           off_t* offseto, ssize_t count) {
+    struct shim_mount* fsi = hdli->fs;
+    struct shim_mount* fso = hdlo->fs;
 
     if (!count)
         return 0;
@@ -358,9 +342,10 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
     if (!fsi || !fsi->fs_ops || !fso || !fso->fs_ops)
         return -EACCES;
 
-    bool do_mapi = (fsi->fs_ops->mmap != NULL);
-    bool do_mapo = (fso->fs_ops->mmap != NULL);
-    bool do_marki = false, do_marko = false;
+    bool do_mapi  = fsi->fs_ops->mmap != NULL;
+    bool do_mapo  = fso->fs_ops->mmap != NULL;
+    bool do_marki = false;
+    bool do_marko = false;
     int offi = 0, offo = 0;
 
     if (offseti) {
@@ -369,8 +354,7 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         offi = *offseti;
         fsi->fs_ops->seek(hdli, offi, SEEK_SET);
     } else {
-        if (!fsi->fs_ops->seek ||
-             (offi = fsi->fs_ops->seek(hdli, 0, SEEK_CUR)) < 0)
+        if (!fsi->fs_ops->seek || (offi = fsi->fs_ops->seek(hdli, 0, SEEK_CUR)) < 0)
             do_mapi = false;
     }
 
@@ -380,30 +364,27 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         offo = *offseto;
         fso->fs_ops->seek(hdlo, offo, SEEK_SET);
     } else {
-        if (!fso->fs_ops->seek ||
-             (offo = fso->fs_ops->seek(hdlo, 0, SEEK_CUR)) < 0)
+        if (!fso->fs_ops->seek || (offo = fso->fs_ops->seek(hdlo, 0, SEEK_CUR)) < 0)
             do_mapo = false;
     }
 
     if (do_mapi) {
         int size;
-        if (fsi->fs_ops->poll &&
-            (size = fsi->fs_ops->poll(hdli, FS_POLL_SZ)) >= 0) {
-            if (count == -1 ||
-                count > size - offi)
+        if (fsi->fs_ops->poll && (size = fsi->fs_ops->poll(hdli, FS_POLL_SZ)) >= 0) {
+            if (count == -1 || count > size - offi)
                 count = size - offi;
 
             if (!count)
                 return 0;
-        } else
+        } else {
             do_mapi = false;
+        }
     }
 
     if (do_mapo && count > 0)
         do {
             int size;
-            if (!fso->fs_ops->poll ||
-                (size = fso->fs_ops->poll(hdlo, FS_POLL_SZ)) < 0) {
+            if (!fso->fs_ops->poll || (size = fso->fs_ops->poll(hdlo, FS_POLL_SZ)) < 0) {
                 do_mapo = false;
                 break;
             }
@@ -411,20 +392,19 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
             if (offo + count < size)
                 break;
 
-            if (!fso->fs_ops->truncate ||
-                fso->fs_ops->truncate(hdlo, offo + count) < 0) {
+            if (!fso->fs_ops->truncate || fso->fs_ops->truncate(hdlo, offo + count) < 0) {
                 do_mapo = false;
                 break;
             }
-        } while(0);
+        } while (0);
 
-    void * bufi = NULL, * bufo = NULL;
-    int bytes = 0;
-    int bufsize = MAP_SIZE;
+    void* bufi = NULL;
+    void* bufo = NULL;
+    int bytes    = 0;
+    int bufsize  = MAP_SIZE;
     int copysize = 0;
 
-    if (!do_mapi && (hdli->flags & O_NONBLOCK) &&
-        fsi->fs_ops->setflags) {
+    if (!do_mapi && (hdli->flags & O_NONBLOCK) && fsi->fs_ops->setflags) {
         int ret = fsi->fs_ops->setflags(hdli, 0);
         if (!ret) {
             debug("mark handle %s as blocking\n", qstrgetstr(&hdli->uri));
@@ -432,8 +412,7 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         }
     }
 
-    if (!do_mapo && (hdlo->flags & O_NONBLOCK) &&
-        fso->fs_ops->setflags) {
+    if (!do_mapo && (hdlo->flags & O_NONBLOCK) && fso->fs_ops->setflags) {
         int ret = fso->fs_ops->setflags(hdlo, 0);
         if (!ret) {
             debug("mark handle %s as blocking\n", qstrgetstr(&hdlo->uri));
@@ -452,15 +431,14 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         if (do_mapi && !bufi) {
             boffi = offi - ALLOC_ALIGN_DOWN(offi);
 
-            if (fsi->fs_ops->mmap(hdli, &bufi, ALLOC_ALIGN_UP(bufsize + boffi),
-                                  PROT_READ, MAP_FILE, offi - boffi) < 0) {
+            if (fsi->fs_ops->mmap(hdli, &bufi, ALLOC_ALIGN_UP(bufsize + boffi), PROT_READ, MAP_FILE,
+                                  offi - boffi) < 0) {
                 do_mapi = false;
                 boffi = 0;
                 if ((hdli->flags & O_NONBLOCK) && fsi->fs_ops->setflags) {
                     int ret = fsi->fs_ops->setflags(hdli, 0);
                     if (!ret) {
-                        debug("mark handle %s as blocking\n",
-                              qstrgetstr(&hdli->uri));
+                        debug("mark handle %s as blocking\n", qstrgetstr(&hdli->uri));
                         do_marki = true;
                     }
                 }
@@ -472,15 +450,14 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         if (do_mapo && !bufo) {
             boffo = offo - ALLOC_ALIGN_DOWN(offo);
 
-            if (fso->fs_ops->mmap(hdlo, &bufo, ALLOC_ALIGN_UP(bufsize + boffo),
-                                  PROT_WRITE, MAP_FILE, offo - boffo) < 0) {
+            if (fso->fs_ops->mmap(hdlo, &bufo, ALLOC_ALIGN_UP(bufsize + boffo), PROT_WRITE,
+                                  MAP_FILE, offo - boffo) < 0) {
                 do_mapo = false;
                 boffo = 0;
                 if ((hdlo->flags & O_NONBLOCK) && fso->fs_ops->setflags) {
                     int ret = fso->fs_ops->setflags(hdlo, 0);
                     if (!ret) {
-                        debug("mark handle %s as blocking\n",
-                              qstrgetstr(&hdlo->uri));
+                        debug("mark handle %s as blocking\n", qstrgetstr(&hdlo->uri));
                         do_marko = true;
                     }
                 }
@@ -490,8 +467,7 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
         }
 
         if (do_mapi && do_mapo) {
-            copysize = count - bytes > bufsize ? bufsize :
-                       count - bytes;
+            copysize = count - bytes > bufsize ? bufsize : count - bytes;
             memcpy(bufo + boffo, bufi + boffi, copysize);
             DkVirtualMemoryFree(bufi, ALLOC_ALIGN_UP(bufsize + boffi));
             bufi = NULL;
@@ -511,8 +487,7 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
                 break;
         } else {
             if (!bufi)
-                bufi = __alloca((bufsize = (bufsize > BUF_SIZE) ? BUF_SIZE :
-                                 bufsize));
+                bufi = __alloca((bufsize = (bufsize > BUF_SIZE) ? BUF_SIZE : bufsize));
 
             copysize = fsi->fs_ops->read(hdli, bufi, bufsize);
 
@@ -576,8 +551,8 @@ static ssize_t handle_copy (struct shim_handle * hdli, off_t * offseti,
 }
 
 static int do_rename(struct shim_dentry* old_dent, struct shim_dentry* new_dent) {
-    if ((old_dent->type != S_IFREG)
-        || (!(new_dent->state & DENTRY_NEGATIVE) && (new_dent->type != S_IFREG))) {
+    if ((old_dent->type != S_IFREG) ||
+            (!(new_dent->state & DENTRY_NEGATIVE) && (new_dent->type != S_IFREG))) {
         /* Current implementation of fs does not allow for renaming anything but regular files */
         return -ENOSYS;
     }
@@ -600,8 +575,8 @@ static int do_rename(struct shim_dentry* old_dent, struct shim_dentry* new_dent)
                 return -ENOTEMPTY;
             }
         } else {
-            /* destination is a negative dentry and needs to be marked as a directory,
-             * since source is a directory */
+            /* destination is a negative dentry and needs to be marked as a directory, since source
+             * is a directory */
             new_dent->state |= DENTRY_ISDIRECTORY;
         }
     } else if (new_dent->state & DENTRY_ISDIRECTORY) {
@@ -629,9 +604,9 @@ int shim_do_rename(const char* oldpath, const char* newpath) {
 
 int shim_do_renameat(int olddirfd, const char* oldpath, int newdirfd, const char* newpath) {
     struct shim_dentry* old_dir_dent = NULL;
-    struct shim_dentry* old_dent = NULL;
+    struct shim_dentry* old_dent     = NULL;
     struct shim_dentry* new_dir_dent = NULL;
-    struct shim_dentry* new_dent = NULL;
+    struct shim_dentry* new_dent     = NULL;
     int ret = 0;
 
     if (!oldpath || test_user_string(oldpath) || !newpath || test_user_string(newpath)) {
@@ -655,12 +630,11 @@ int shim_do_renameat(int olddirfd, const char* oldpath, int newdirfd, const char
         goto out;
     }
 
-    ret = path_lookupat(new_dir_dent, newpath, LOOKUP_OPEN|LOOKUP_CREATE, &new_dent, NULL);
+    ret = path_lookupat(new_dir_dent, newpath, LOOKUP_OPEN | LOOKUP_CREATE, &new_dent, NULL);
     if (ret < 0) {
-        if (ret != -ENOENT
-                || !new_dent
-                || (new_dent->state & (DENTRY_NEGATIVE|DENTRY_VALID))
-                        != (DENTRY_NEGATIVE|DENTRY_VALID)) {
+        if (ret != -ENOENT || !new_dent ||
+            (new_dent->state & (DENTRY_NEGATIVE | DENTRY_VALID)) !=
+                (DENTRY_NEGATIVE | DENTRY_VALID)) {
             goto out;
         }
     }
@@ -683,11 +657,9 @@ out:
     return ret;
 }
 
-ssize_t shim_do_sendfile (int ofd, int ifd, off_t * offset,
-                          size_t count)
-{
-    struct shim_handle * hdli = get_fd_handle(ifd, NULL, NULL);
-    struct shim_handle * hdlo = get_fd_handle(ofd, NULL, NULL);
+ssize_t shim_do_sendfile(int ofd, int ifd, off_t* offset, size_t count) {
+    struct shim_handle* hdli = get_fd_handle(ifd, NULL, NULL);
+    struct shim_handle* hdlo = get_fd_handle(ofd, NULL, NULL);
 
     if (!hdli || !hdlo)
         return -EBADF;
@@ -696,8 +668,7 @@ ssize_t shim_do_sendfile (int ofd, int ifd, off_t * offset,
     int ret = -EACCES;
 
     if (offset) {
-        if (!hdli->fs || !hdli->fs->fs_ops ||
-            !hdli->fs->fs_ops->seek)
+        if (!hdli->fs || !hdli->fs->fs_ops || !hdli->fs->fs_ops->seek)
             goto out;
 
         old_offset = hdli->fs->fs_ops->seek(hdli, 0, SEEK_CUR);
@@ -718,11 +689,10 @@ out:
     return ret;
 }
 
-int shim_do_chroot (const char * filename)
-{
+int shim_do_chroot(const char* filename) {
     int ret = 0;
-    struct shim_dentry * dent = NULL;
-    if ((ret = path_lookupat(NULL, filename, 0 , &dent, NULL)) < 0)
+    struct shim_dentry* dent = NULL;
+    if ((ret = path_lookupat(NULL, filename, 0, &dent, NULL)) < 0)
         goto out;
 
     if (!dent) {
@@ -730,7 +700,7 @@ int shim_do_chroot (const char * filename)
         goto out;
     }
 
-    struct shim_thread * thread = get_cur_thread();
+    struct shim_thread* thread = get_cur_thread();
     lock(&thread->lock);
     put_dentry(thread->root);
     thread->root = dent;

+ 35 - 36
LibOS/shim/src/sys/shim_poll.c

@@ -41,21 +41,21 @@ typedef long int __fd_mask;
 #define __FDS_BITS(set) ((set)->fds_bits)
 #endif
 
-#define __FD_ZERO(set)                                         \
-    do {                                                       \
-        unsigned int i;                                        \
-        fd_set* arr = (set);                                   \
-        for (i = 0; i < sizeof(fd_set)/sizeof(__fd_mask); i++) \
-            __FDS_BITS(arr)[i] = 0;                            \
+#define __FD_ZERO(set)                                           \
+    do {                                                         \
+        unsigned int i;                                          \
+        fd_set* arr = (set);                                     \
+        for (i = 0; i < sizeof(fd_set) / sizeof(__fd_mask); i++) \
+            __FDS_BITS(arr)[i] = 0;                              \
     } while (0)
 
-#define __FD_ELT(d) ((d) / __NFDBITS)
-#define __FD_MASK(d) ((__fd_mask)1 << ((d) % __NFDBITS))
-#define __FD_SET(d, set) ((void)(__FDS_BITS(set)[__FD_ELT(d)] |= __FD_MASK(d)))
-#define __FD_CLR(d, set) ((void)(__FDS_BITS(set)[__FD_ELT(d)] &= ~__FD_MASK(d)))
+#define __FD_ELT(d)        ((d) / __NFDBITS)
+#define __FD_MASK(d)       ((__fd_mask)1 << ((d) % __NFDBITS))
+#define __FD_SET(d, set)   ((void)(__FDS_BITS(set)[__FD_ELT(d)] |= __FD_MASK(d)))
+#define __FD_CLR(d, set)   ((void)(__FDS_BITS(set)[__FD_ELT(d)] &= ~__FD_MASK(d)))
 #define __FD_ISSET(d, set) ((__FDS_BITS(set)[__FD_ELT(d)] & __FD_MASK(d)) != 0)
 
-#define POLL_NOTIMEOUT  ((uint64_t)-1)
+#define POLL_NOTIMEOUT ((uint64_t)-1)
 
 int shim_do_poll(struct pollfd* fds, nfds_t nfds, int timeout_ms) {
     if (!fds || test_user_memory(fds, sizeof(*fds) * nfds, true))
@@ -75,8 +75,8 @@ int shim_do_poll(struct pollfd* fds, nfds_t nfds, int timeout_ms) {
 
     /* for bookkeeping, need to have a mapping FD -> {shim handle, index-in-pals} */
     struct fds_mapping_t {
-        struct shim_handle* hdl;  /* NULL if no mapping (handle is not used in polling) */
-        nfds_t idx;               /* index from fds array to pals array */
+        struct shim_handle* hdl; /* NULL if no mapping (handle is not used in polling) */
+        nfds_t idx;              /* index from fds array to pals array */
     };
     struct fds_mapping_t* fds_mapping = malloc(nfds * sizeof(struct fds_mapping_t));
     if (!fds_mapping) {
@@ -110,32 +110,32 @@ int shim_do_poll(struct pollfd* fds, nfds_t nfds, int timeout_ms) {
 
         struct shim_handle* hdl = __get_fd_handle(fds[i].fd, NULL, map);
         if (!hdl || !hdl->fs || !hdl->fs->fs_ops) {
-            /* the corresponding handle doesn't exist or doesn't provide FS-like semantics;
-             * do not include it in handles-to-poll array but notify user about invalid request */
+            /* The corresponding handle doesn't exist or doesn't provide FS-like semantics; do not
+             * include it in handles-to-poll array but notify user about invalid request. */
             fds[i].revents = POLLNVAL;
             nrevents++;
             continue;
         }
 
         PAL_FLG allowed_events = 0;
-        if ((fds[i].events & (POLLIN|POLLRDNORM)) && (hdl->acc_mode & MAY_READ))
+        if ((fds[i].events & (POLLIN | POLLRDNORM)) && (hdl->acc_mode & MAY_READ))
             allowed_events |= PAL_WAIT_READ;
-        if ((fds[i].events & (POLLOUT|POLLWRNORM)) && (hdl->acc_mode & MAY_WRITE))
+        if ((fds[i].events & (POLLOUT | POLLWRNORM)) && (hdl->acc_mode & MAY_WRITE))
             allowed_events |= PAL_WAIT_WRITE;
 
-        if ((fds[i].events & (POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM)) && !allowed_events) {
-            /* if user requested read/write events but they are not allowed on this handle,
-             * ignore this handle (but note that user may only be interested in errors, and
-             * this is a valid request) */
+        if ((fds[i].events & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM)) && !allowed_events) {
+            /* If user requested read/write events but they are not allowed on this handle, ignore
+             * this handle (but note that user may only be interested in errors, and this is a valid
+             * request). */
             continue;
         }
 
         get_handle(hdl);
         fds_mapping[i].hdl = hdl;
         fds_mapping[i].idx = pal_cnt;
-        pals[pal_cnt]        = hdl->pal_handle;
-        pal_events[pal_cnt]  = allowed_events;
-        ret_events[pal_cnt]  = 0;
+        pals[pal_cnt] = hdl->pal_handle;
+        pal_events[pal_cnt] = allowed_events;
+        ret_events[pal_cnt] = 0;
         pal_cnt++;
     }
 
@@ -153,9 +153,9 @@ int shim_do_poll(struct pollfd* fds, nfds_t nfds, int timeout_ms) {
             if (ret_events[fds_mapping[i].idx] & PAL_WAIT_ERROR)
                 fds[i].revents |= POLLERR | POLLHUP;
             if (ret_events[fds_mapping[i].idx] & PAL_WAIT_READ)
-                fds[i].revents |= fds[i].events & (POLLIN|POLLRDNORM);
+                fds[i].revents |= fds[i].events & (POLLIN | POLLRDNORM);
             if (ret_events[fds_mapping[i].idx] & PAL_WAIT_WRITE)
-                fds[i].revents |= fds[i].events & (POLLOUT|POLLWRNORM);
+                fds[i].revents |= fds[i].events & (POLLOUT | POLLWRNORM);
 
             if (fds[i].revents)
                 nrevents++;
@@ -171,8 +171,8 @@ int shim_do_poll(struct pollfd* fds, nfds_t nfds, int timeout_ms) {
     return nrevents;
 }
 
-int shim_do_ppoll(struct pollfd* fds, int nfds, struct timespec* tsp,
-                  const __sigset_t* sigmask, size_t sigsetsize) {
+int shim_do_ppoll(struct pollfd* fds, int nfds, struct timespec* tsp, const __sigset_t* sigmask,
+                  size_t sigsetsize) {
     __UNUSED(sigmask);
     __UNUSED(sigsetsize);
 
@@ -180,10 +180,10 @@ int shim_do_ppoll(struct pollfd* fds, int nfds, struct timespec* tsp,
     return shim_do_poll(fds, nfds, timeout_ms);
 }
 
-int shim_do_select(int nfds, fd_set* readfds, fd_set* writefds,
-                   fd_set* errorfds, struct __kernel_timeval* tsv) {
+int shim_do_select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* errorfds,
+                   struct __kernel_timeval* tsv) {
     if (tsv && (tsv->tv_sec < 0 || tsv->tv_usec < 0))
-            return -EINVAL;
+        return -EINVAL;
 
     if (nfds < 0 || (uint64_t)nfds > get_rlimit_cur(RLIMIT_NOFILE))
         return -EINVAL;
@@ -194,7 +194,7 @@ int shim_do_select(int nfds, fd_set* readfds, fd_set* writefds,
 
         /* special case of select(0, ..., tsv) used for sleep */
         struct __kernel_timespec tsp;
-        tsp.tv_sec = tsv->tv_sec;
+        tsp.tv_sec  = tsv->tv_sec;
         tsp.tv_nsec = tsv->tv_usec * 1000;
         return shim_do_nanosleep(&tsp, NULL);
     }
@@ -278,14 +278,13 @@ int shim_do_select(int nfds, fd_set* readfds, fd_set* writefds,
     return ret;
 }
 
-int shim_do_pselect6(int nfds, fd_set* readfds, fd_set* writefds,
-                     fd_set* errorfds, const struct __kernel_timespec* tsp,
-                     const __sigset_t* sigmask) {
+int shim_do_pselect6(int nfds, fd_set* readfds, fd_set* writefds, fd_set* errorfds,
+                     const struct __kernel_timespec* tsp, const __sigset_t* sigmask) {
     __UNUSED(sigmask);
 
     if (tsp) {
         struct __kernel_timeval tsv;
-        tsv.tv_sec = tsp->tv_sec;
+        tsv.tv_sec  = tsp->tv_sec;
         tsv.tv_usec = tsp->tv_nsec / 1000;
         return shim_do_select(nfds, readfds, writefds, errorfds, &tsv);
     }

+ 75 - 103
LibOS/shim/src/sys/shim_sigaction.c

@@ -21,41 +21,40 @@
  * "kill", "tkill" and "tgkill".
  */
 
-#include <shim_internal.h>
-#include <shim_utils.h>
-#include <shim_table.h>
-#include <shim_thread.h>
-#include <shim_ipc.h>
-#include <shim_profile.h>
+#include <errno.h>
+#include <stddef.h>  // FIXME(mkow): Without this we get:
+                     //     asm/signal.h:126:2: error: unknown type name ‘size_t’
+                     // It definitely shouldn't behave like this...
+#include <linux/signal.h>
 
 #include <pal.h>
 #include <pal_error.h>
+#include <shim_internal.h>
+#include <shim_ipc.h>
+#include <shim_profile.h>
+#include <shim_table.h>
+#include <shim_thread.h>
+#include <shim_utils.h>
 
-#include <errno.h>
-
-#include <linux/signal.h>
-
-int shim_do_sigaction (int signum, const struct __kernel_sigaction * act,
-                       struct __kernel_sigaction * oldact, size_t sigsetsize)
-{
+int shim_do_sigaction(int signum, const struct __kernel_sigaction* act,
+                      struct __kernel_sigaction* oldact, size_t sigsetsize) {
     /* SIGKILL and SIGSTOP cannot be caught or ignored */
-    if (signum == SIGKILL || signum == SIGSTOP ||
-        signum <= 0 || signum > NUM_SIGS ||
-        sigsetsize != sizeof(__sigset_t))
+    if (signum == SIGKILL || signum == SIGSTOP || signum <= 0 || signum > NUM_SIGS ||
+            sigsetsize != sizeof(__sigset_t))
         return -EINVAL;
 
-    if (act && test_user_memory((void *) act, sizeof(*act), false))
+    if (act && test_user_memory((void*)act, sizeof(*act), false))
         return -EFAULT;
 
     if (oldact && test_user_memory(oldact, sizeof(*oldact), false))
         return -EFAULT;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
     int err = 0;
 
-    assert(!act || (void *) act->k_sa_handler != (void *) 0x11);
+    assert(!act || (void*)act->k_sa_handler != (void*)0x11);
 
-    struct shim_signal_handle * sighdl = &cur->signal_handles[signum - 1];
+    struct shim_signal_handle* sighdl = &cur->signal_handles[signum - 1];
 
     lock(&cur->lock);
 
@@ -86,28 +85,27 @@ out:
     return err;
 }
 
-int shim_do_sigreturn (int __unused)
-{
+int shim_do_sigreturn(int __unused) {
     __UNUSED(__unused);
     /* do nothing */
     return 0;
 }
 
-int shim_do_sigprocmask (int how, const __sigset_t * set, __sigset_t * oldset)
-{
-    __sigset_t * old, tmp, set_tmp;
+int shim_do_sigprocmask(int how, const __sigset_t* set, __sigset_t* oldset) {
+    __sigset_t* old;
+    __sigset_t tmp;
+    __sigset_t set_tmp;
 
-    if (how != SIG_BLOCK && how != SIG_UNBLOCK &&
-        how != SIG_SETMASK)
+    if (how != SIG_BLOCK && how != SIG_UNBLOCK && how != SIG_SETMASK)
         return -EINVAL;
 
-    if (set && test_user_memory((void *) set, sizeof(*set), false))
+    if (set && test_user_memory((void*)set, sizeof(*set), false))
         return -EFAULT;
 
     if (oldset && test_user_memory(oldset, sizeof(*oldset), false))
         return -EFAULT;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
     int err = 0;
 
     lock(&cur->lock);
@@ -150,25 +148,22 @@ out:
     return err;
 }
 
-int shim_do_sigaltstack (const stack_t * ss, stack_t * oss)
-{
+int shim_do_sigaltstack(const stack_t* ss, stack_t* oss) {
     if (ss && (ss->ss_flags & ~SS_DISABLE))
         return -EINVAL;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
     lock(&cur->lock);
 
-    stack_t * cur_ss = &cur->signal_altstack;
+    stack_t* cur_ss = &cur->signal_altstack;
 
     if (oss)
         *oss = *cur_ss;
 
-    void * sp = (void *)shim_get_tcb()->context.regs->rsp;
+    void* sp = (void*)shim_get_tcb()->context.regs->rsp;
     /* check if thread is currently executing on an active altstack */
-    if (!(cur_ss->ss_flags & SS_DISABLE) &&
-        sp &&
-        cur_ss->ss_sp <= sp &&
-        sp < cur_ss->ss_sp + cur_ss->ss_size) {
+    if (!(cur_ss->ss_flags & SS_DISABLE) && sp && cur_ss->ss_sp <= sp &&
+            sp < cur_ss->ss_sp + cur_ss->ss_size) {
         if (oss)
             oss->ss_flags |= SS_ONSTACK;
         if (ss) {
@@ -195,18 +190,18 @@ int shim_do_sigaltstack (const stack_t * ss, stack_t * oss)
     return 0;
 }
 
-int shim_do_sigsuspend (const __sigset_t * mask)
-{
-    if (!mask || test_user_memory((void *) mask, sizeof(*mask), false))
+int shim_do_sigsuspend(const __sigset_t* mask) {
+    if (!mask || test_user_memory((void*)mask, sizeof(*mask), false))
         return -EFAULT;
 
-    __sigset_t * old, tmp;
-    struct shim_thread * cur = get_cur_thread();
+    __sigset_t* old;
+    __sigset_t tmp;
+    struct shim_thread* cur = get_cur_thread();
 
     lock(&cur->lock);
 
     /* return immediately on some pending unblocked signal */
-    for (int sig = 1 ; sig <= NUM_SIGS ; sig++) {
+    for (int sig = 1; sig <= NUM_SIGS; sig++) {
         if (atomic_read(&cur->signal_logs[sig - 1].head) !=
             atomic_read(&cur->signal_logs[sig - 1].tail)) {
             /* at least one signal of type sig... */
@@ -235,22 +230,21 @@ int shim_do_sigsuspend (const __sigset_t * mask)
     return -EINTR;
 }
 
-int shim_do_sigpending (__sigset_t * set, size_t sigsetsize)
-{
+int shim_do_sigpending(__sigset_t* set, size_t sigsetsize) {
     if (sigsetsize != sizeof(*set))
         return -EINVAL;
 
     if (!set || test_user_memory(set, sigsetsize, false))
         return -EFAULT;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
 
     __sigemptyset(set);
 
     if (!cur->signal_logs)
         return 0;
 
-    for (int sig = 1 ; sig <= NUM_SIGS ; sig++) {
+    for (int sig = 1; sig <= NUM_SIGS; sig++) {
         if (atomic_read(&cur->signal_logs[sig - 1].head) !=
             atomic_read(&cur->signal_logs[sig - 1].tail))
             __sigaddset(set, sig);
@@ -260,7 +254,7 @@ int shim_do_sigpending (__sigset_t * set, size_t sigsetsize)
 }
 
 struct walk_arg {
-    struct shim_thread * current;
+    struct shim_thread* current;
     IDTYPE sender;
     IDTYPE id;
     int sig;
@@ -268,8 +262,7 @@ struct walk_arg {
 };
 
 // Need to hold thread->lock
-static inline void __append_signal(struct shim_thread* thread, int sig, IDTYPE sender)
-{
+static inline void __append_signal(struct shim_thread* thread, int sig, IDTYPE sender) {
     debug("Thread %d killed by signal %d\n", thread->tid, sig);
     siginfo_t info;
     memset(&info, 0, sizeof(siginfo_t));
@@ -278,10 +271,8 @@ static inline void __append_signal(struct shim_thread* thread, int sig, IDTYPE s
     append_signal(thread, sig, &info, true);
 }
 
-static int __kill_proc (struct shim_thread * thread, void * arg,
-                        bool * unlocked)
-{
-    struct walk_arg * warg = (struct walk_arg *) arg;
+static int __kill_proc(struct shim_thread* thread, void* arg, bool* unlocked) {
+    struct walk_arg* warg = (struct walk_arg*)arg;
     int srched = 0;
 
     if (!warg->use_ipc && !thread->in_vm)
@@ -303,8 +294,7 @@ static int __kill_proc (struct shim_thread * thread, void * arg,
     if (!thread->in_vm) {
         unlock(&thread_list_lock);
         *unlocked = true;
-        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS,
-                                   warg->sig)) ? 1 : 0;
+        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS, warg->sig)) ? 1 : 0;
     } else {
         lock(&thread->lock);
 
@@ -320,8 +310,7 @@ static int __kill_proc (struct shim_thread * thread, void * arg,
             unlock(&thread->lock);
             unlock(&thread_list_lock);
             *unlocked = true;
-            return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS,
-                                   warg->sig)) ? 1 : 0;
+            return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS, warg->sig)) ? 1 : 0;
         }
     }
 out_locked:
@@ -330,10 +319,8 @@ out:
     return srched;
 }
 
-static int __kill_proc_simple (struct shim_simple_thread * sthread,
-                               void * arg, bool * unlocked)
-{
-    struct walk_arg * warg = (struct walk_arg *) arg;
+static int __kill_proc_simple(struct shim_simple_thread* sthread, void* arg, bool* unlocked) {
+    struct walk_arg* warg = (struct walk_arg*)arg;
     int srched = 0;
 
     if (sthread->tgid != warg->id)
@@ -345,17 +332,15 @@ static int __kill_proc_simple (struct shim_simple_thread * sthread,
         unlock(&sthread->lock);
         unlock(&thread_list_lock);
         *unlocked = true;
-        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS,
-                                   warg->sig)) ? 1 : 0;
+        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PROCESS, warg->sig)) ? 1 : 0;
     }
 
     unlock(&sthread->lock);
     return srched;
 }
 
-int do_kill_proc (IDTYPE sender, IDTYPE tgid, int sig, bool use_ipc)
-{
-   struct shim_thread * cur = get_cur_thread();
+int do_kill_proc(IDTYPE sender, IDTYPE tgid, int sig, bool use_ipc) {
+    struct shim_thread* cur = get_cur_thread();
 
     if (!tgid) {
         /* DEP: cur->tgid never changes.  No lock needed */
@@ -387,10 +372,8 @@ out:
     return srched ? 0 : -ESRCH;
 }
 
-static int __kill_pgroup (struct shim_thread * thread, void * arg,
-                          bool * unlocked)
-{
-    struct walk_arg * warg = (struct walk_arg *) arg;
+static int __kill_pgroup(struct shim_thread* thread, void* arg, bool* unlocked) {
+    struct walk_arg* warg = (struct walk_arg*)arg;
     int srched = 0;
 
     if (!warg->use_ipc && !thread->in_vm)
@@ -416,8 +399,7 @@ static int __kill_pgroup (struct shim_thread * thread, void * arg,
         unlock(&thread->lock);
         unlock(&thread_list_lock);
         *unlocked = true;
-        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PGROUP,
-                                   warg->sig)) ? 1 : 0;
+        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PGROUP, warg->sig)) ? 1 : 0;
     }
 
 out:
@@ -425,10 +407,8 @@ out:
     return srched;
 }
 
-static int __kill_pgroup_simple (struct shim_simple_thread * sthread,
-                                 void * arg, bool * unlocked)
-{
-    struct walk_arg * warg = (struct walk_arg *) arg;
+static int __kill_pgroup_simple(struct shim_simple_thread* sthread, void* arg, bool* unlocked) {
+    struct walk_arg* warg = (struct walk_arg*)arg;
     int srched = 0;
 
     if (sthread->pgid != warg->id)
@@ -440,17 +420,15 @@ static int __kill_pgroup_simple (struct shim_simple_thread * sthread,
         unlock(&sthread->lock);
         unlock(&thread_list_lock);
         *unlocked = true;
-        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PGROUP,
-                                   warg->sig)) ? 1 : 0;
+        return (!ipc_pid_kill_send(warg->sender, warg->id, KILL_PGROUP, warg->sig)) ? 1 : 0;
     }
 
     unlock(&sthread->lock);
     return srched;
 }
 
-int do_kill_pgroup (IDTYPE sender, IDTYPE pgid, int sig, bool use_ipc)
-{
-    struct shim_thread * cur = get_cur_thread();
+int do_kill_pgroup(IDTYPE sender, IDTYPE pgid, int sig, bool use_ipc) {
+    struct shim_thread* cur = get_cur_thread();
 
     if (!pgid) {
         pgid = cur->pgid;
@@ -481,12 +459,10 @@ out:
     return srched ? 0 : -ESRCH;
 }
 
-static int __kill_all_threads (struct shim_thread * thread, void * arg,
-                               bool * unlocked)
-{
-    __UNUSED(unlocked); // Retained for API compatibility
+static int __kill_all_threads(struct shim_thread* thread, void* arg, bool* unlocked) {
+    __UNUSED(unlocked);  // Retained for API compatibility
     int srched = 0;
-    struct walk_arg * warg = (struct walk_arg *) arg;
+    struct walk_arg* warg = (struct walk_arg*)arg;
 
     if (thread->tgid != thread->tid)
         return 0;
@@ -505,8 +481,7 @@ static int __kill_all_threads (struct shim_thread * thread, void * arg,
     return srched;
 }
 
-int kill_all_threads (struct shim_thread * cur, IDTYPE sender, int sig)
-{
+int kill_all_threads(struct shim_thread* cur, IDTYPE sender, int sig) {
     struct walk_arg arg;
     arg.current = cur;
     arg.sender  = sender;
@@ -517,14 +492,13 @@ int kill_all_threads (struct shim_thread * cur, IDTYPE sender, int sig)
     return 0;
 }
 
-int shim_do_kill (pid_t pid, int sig)
-{
+int shim_do_kill(pid_t pid, int sig) {
     INC_PROFILE_OCCURENCE(syscall_use_ipc);
 
     if (sig < 0 || sig > NUM_SIGS)
         return -EINVAL;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
     int ret = 0;
     bool send_to_self = false;
 
@@ -547,14 +521,14 @@ int shim_do_kill (pid_t pid, int sig)
        specified by pid. */
     else if (pid > 0) {
         ret = do_kill_proc(cur->tid, pid, sig, true);
-        send_to_self = ((IDTYPE) pid == cur->tgid);
+        send_to_self = (IDTYPE)pid == cur->tgid;
     }
 
     /* If pid is less than -1, then sig is sent to every process in the
        process group whose id is -pid */
     else {
         ret = do_kill_pgroup(cur->tid, -pid, sig, true);
-        send_to_self = ((IDTYPE) -pid == cur->pgid);
+        send_to_self = (IDTYPE)-pid == cur->pgid;
     }
 
     if (send_to_self) {
@@ -603,16 +577,15 @@ int do_kill_thread(IDTYPE sender, IDTYPE tgid, IDTYPE tid, int sig, bool use_ipc
     return ipc_pid_kill_send(sender, tid, KILL_THREAD, sig);
 }
 
-int shim_do_tkill (pid_t tid, int sig)
-{
+int shim_do_tkill(pid_t tid, int sig) {
     INC_PROFILE_OCCURENCE(syscall_use_ipc);
 
     if (tid <= 0)
         return -EINVAL;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
 
-    if ((IDTYPE) tid == cur->tid) {
+    if ((IDTYPE)tid == cur->tid) {
         if (sig) {
             siginfo_t info;
             memset(&info, 0, sizeof(siginfo_t));
@@ -626,8 +599,7 @@ int shim_do_tkill (pid_t tid, int sig)
     return do_kill_thread(cur->tgid, 0, tid, sig, true);
 }
 
-int shim_do_tgkill (pid_t tgid, pid_t tid, int sig)
-{
+int shim_do_tgkill(pid_t tgid, pid_t tid, int sig) {
     INC_PROFILE_OCCURENCE(syscall_use_ipc);
 
     if (tgid < -1 || tgid == 0 || tid <= 0)
@@ -636,9 +608,9 @@ int shim_do_tgkill (pid_t tgid, pid_t tid, int sig)
     if (tgid == -1)
         tgid = 0;
 
-    struct shim_thread * cur = get_cur_thread();
+    struct shim_thread* cur = get_cur_thread();
 
-    if ((IDTYPE) tid == cur->tid) {
+    if ((IDTYPE)tid == cur->tid) {
         if (sig) {
             siginfo_t info;
             memset(&info, 0, sizeof(siginfo_t));

+ 12 - 17
LibOS/shim/src/sys/shim_sleep.c

@@ -20,20 +20,18 @@
  * Implementation of system call "pause" and "nanosleep".
  */
 
-#include <shim_internal.h>
-#include <shim_utils.h>
-#include <shim_table.h>
-#include <shim_handle.h>
-#include <shim_vma.h>
-#include <shim_thread.h>
+#include <errno.h>
 
 #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>
 
-#include <errno.h>
-
-static bool signal_pending (void)
-{
+static bool signal_pending(void) {
     struct shim_thread* cur = get_cur_thread();
     if (!cur)
         return false;
@@ -61,8 +59,7 @@ static bool signal_pending (void)
     return false;
 }
 
-int shim_do_pause (void)
-{
+int shim_do_pause(void) {
     if (signal_pending())
         return -EINTR;
 
@@ -71,16 +68,14 @@ int shim_do_pause (void)
     return -EINTR;
 }
 
-int shim_do_nanosleep (const struct __kernel_timespec * rqtp,
-                       struct __kernel_timespec * rmtp)
-{
+int shim_do_nanosleep(const struct __kernel_timespec* rqtp, struct __kernel_timespec* rmtp) {
     if (!rqtp)
         return -EFAULT;
 
     if (signal_pending()) {
         if (rmtp) {
             /* no time elapsed, so copy time interval from rqtp to rmtp */
-            rmtp->tv_sec = rqtp->tv_sec;
+            rmtp->tv_sec  = rqtp->tv_sec;
             rmtp->tv_nsec = rqtp->tv_nsec;
         }
         return -EINTR;
@@ -92,7 +87,7 @@ int shim_do_nanosleep (const struct __kernel_timespec * rqtp,
     if (ret < time) {
         if (rmtp) {
             unsigned long remtime = time - ret;
-            rmtp->tv_sec = remtime / 1000000L;
+            rmtp->tv_sec  = remtime / 1000000L;
             rmtp->tv_nsec = (remtime - rmtp->tv_sec * 1000) * 1000;
         }
         return -EINTR;

+ 36 - 48
LibOS/shim/src/sys/shim_stat.c

@@ -20,22 +20,19 @@
  * Implementation of system call "stat", "lstat", "fstat" and "readlink".
  */
 
-#include <shim_internal.h>
-#include <shim_table.h>
-#include <shim_handle.h>
-#include <shim_fs.h>
-#include <shim_profile.h>
-#include <shim_thread.h>
+#include <errno.h>
+#include <linux/fcntl.h>
 
 #include <pal.h>
 #include <pal_error.h>
+#include <shim_fs.h>
+#include <shim_handle.h>
+#include <shim_internal.h>
+#include <shim_profile.h>
+#include <shim_table.h>
+#include <shim_thread.h>
 
-#include <errno.h>
-
-#include <linux/fcntl.h>
-
-int shim_do_stat (const char * file, struct stat * stat)
-{
+int shim_do_stat(const char* file, struct stat* stat) {
     if (!file || test_user_string(file))
         return -EFAULT;
 
@@ -43,12 +40,12 @@ int shim_do_stat (const char * file, struct stat * stat)
         return -EFAULT;
 
     int ret;
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
 
-    if ((ret = path_lookupat(NULL, file, LOOKUP_ACCESS|LOOKUP_FOLLOW, &dent, NULL)) < 0)
+    if ((ret = path_lookupat(NULL, file, LOOKUP_ACCESS | LOOKUP_FOLLOW, &dent, NULL)) < 0)
         goto out;
 
-    struct shim_mount * fs = dent->fs;
+    struct shim_mount* fs = dent->fs;
 
     if (!fs->d_ops || !fs->d_ops->stat) {
         ret = -EACCES;
@@ -62,8 +59,7 @@ out:
     return ret;
 }
 
-int shim_do_lstat (const char * file, struct stat * stat)
-{
+int shim_do_lstat(const char* file, struct stat* stat) {
     if (!file || test_user_string(file))
         return -EFAULT;
 
@@ -71,12 +67,12 @@ int shim_do_lstat (const char * file, struct stat * stat)
         return -EFAULT;
 
     int ret;
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
 
     if ((ret = path_lookupat(NULL, file, LOOKUP_ACCESS, &dent, NULL)) < 0)
         goto out;
 
-    struct shim_mount * fs = dent->fs;
+    struct shim_mount* fs = dent->fs;
 
     if (!fs->d_ops || !fs->d_ops->stat) {
         ret = -EACCES;
@@ -90,14 +86,13 @@ out:
     return ret;
 }
 
-int shim_do_fstat (int fd, struct stat * stat)
-{
-    struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL);
+int shim_do_fstat(int fd, struct stat* stat) {
+    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;
@@ -111,8 +106,7 @@ out:
     return ret;
 }
 
-int shim_do_readlink (const char * file, char * buf, size_t bufsize)
-{
+int shim_do_readlink(const char* file, char* buf, size_t bufsize) {
     if (!file || test_user_string(file))
         return -EFAULT;
 
@@ -123,7 +117,7 @@ int shim_do_readlink (const char * file, char * buf, size_t bufsize)
         return -EINVAL;
 
     int ret;
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
     struct shim_qstr qstr = QSTR_INIT;
 
     if ((ret = path_lookupat(NULL, file, LOOKUP_ACCESS, &dent, NULL)) < 0)
@@ -153,55 +147,49 @@ out:
     return ret;
 }
 
-static int __do_statfs (struct shim_mount * fs, struct statfs * buf)
-{
+static int __do_statfs(struct shim_mount* fs, struct statfs* buf) {
     __UNUSED(fs);
     if (!buf || test_user_memory(buf, sizeof(*buf), true))
         return -EFAULT;
 
     memset(buf, 0, sizeof(*buf));
 
-    buf->f_bsize = 4096;
+    buf->f_bsize  = 4096;
     buf->f_blocks = 20000000;
-    buf->f_bfree = 10000000;
+    buf->f_bfree  = 10000000;
     buf->f_bavail = 10000000;
 
-    debug("statfs: %ld %ld %ld\n", buf->f_blocks, buf->f_bfree,
-            buf->f_bavail);
+    debug("statfs: %ld %ld %ld\n", buf->f_blocks, buf->f_bfree, buf->f_bavail);
 
     return 0;
 }
 
-int shim_do_statfs (const char * path, struct statfs * buf)
-{
+int shim_do_statfs(const char* path, struct statfs* buf) {
     if (!path || test_user_string(path))
         return -EFAULT;
 
     int ret;
-    struct shim_dentry * dent = NULL;
+    struct shim_dentry* dent = NULL;
 
-    if ((ret = path_lookupat(NULL, path, LOOKUP_ACCESS|LOOKUP_FOLLOW, &dent, NULL)) < 0)
+    if ((ret = path_lookupat(NULL, path, LOOKUP_ACCESS | LOOKUP_FOLLOW, &dent, NULL)) < 0)
         return ret;
 
-    struct shim_mount * fs = dent->fs;
+    struct shim_mount* fs = dent->fs;
     put_dentry(dent);
-    return __do_statfs (fs, buf);
+    return __do_statfs(fs, buf);
 }
 
-int shim_do_fstatfs (int fd, struct statfs * buf)
-{
-    struct shim_handle * hdl = get_fd_handle(fd, NULL, NULL);
+int shim_do_fstatfs(int fd, struct statfs* buf) {
+    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;
     put_handle(hdl);
-    return __do_statfs (fs, buf);
+    return __do_statfs(fs, buf);
 }
 
-int shim_do_newfstatat(int dirfd, const char* pathname,
-                       struct stat* statbuf, int flags)
-{
+int shim_do_newfstatat(int dirfd, const char* pathname, struct stat* statbuf, int flags) {
     if (flags & ~(AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_SYMLINK_NOFOLLOW))
         return -EINVAL;
     if (test_user_string(pathname))
@@ -217,12 +205,12 @@ int shim_do_newfstatat(int dirfd, const char* pathname,
         debug("ignoring AT_NO_AUTOMOUNT.");
     }
 
-    if (!*pathname){
+    if (!*pathname) {
         if (!(flags & AT_EMPTY_PATH))
             return -ENOENT;
 
         if (dirfd == AT_FDCWD) {
-            struct shim_dentry * cwd = get_cur_thread()->cwd;
+            struct shim_dentry* cwd  = get_cur_thread()->cwd;
             struct shim_d_ops* d_ops = cwd->fs->d_ops;
             if (d_ops && d_ops->stat)
                 return d_ops->stat(cwd, statbuf);

+ 3 - 3
LibOS/shim/test/regression/abort_multithread.c

@@ -1,9 +1,9 @@
+#include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <pthread.h>
 
-/* Test if abort() in a child thread kills the whole process. This should report
- * 134 (128 + 6 where 6 is SIGABRT) as its return code. */
+/* Test if abort() in a child thread kills the whole process. This should report 134 (128 + 6 where
+ * 6 is SIGABRT) as its return code. */
 
 void* thread_abort(void* arg) {
     abort();

+ 0 - 2
LibOS/shim/test/regression/eventfd.c

@@ -1,8 +1,6 @@
 #include <errno.h>
-
 #include <poll.h>
 #include <pthread.h>
-
 #include <signal.h>
 #include <stdarg.h>
 #include <stdint.h>

+ 2 - 2
LibOS/shim/test/regression/exit_group.c

@@ -11,8 +11,8 @@ atomic_int counter = 1;
 
 pthread_barrier_t barrier;
 
-/* Test the process exit logic in Graphene. Multiple threads race to execute
- * exit()/exit_group(). Expected return code is 0 .. 4, depending on which thread wins. */
+/* Test the process exit logic in Graphene. Multiple threads race to execute exit()/exit_group().
+ * Expected return code is 0 .. 4, depending on which thread wins. */
 
 void* inc(void* arg) {
     int a = counter++;

+ 8 - 6
LibOS/shim/test/regression/fdleak.c

@@ -1,22 +1,24 @@
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/types.h>
 #include <unistd.h>
 
-/* This is supposed to expose resource leaks where close()d files are not
-   properly cleaned up. */
+/* This is supposed to expose resource leaks where close()d files are not properly cleaned up. */
 
 int main(int argc, char** argv) {
     for (int i = 0; i < 10000; i++) {
         int fd = open(argv[0], O_RDONLY);
-        if (fd == -1) abort();
+        if (fd == -1)
+            abort();
         char buf[1024];
         ssize_t read_ret = read(fd, buf, sizeof(buf));
-        if (read_ret == -1) abort();
+        if (read_ret == -1)
+            abort();
         int ret = close(fd);
-        if (ret == -1) abort();
+        if (ret == -1)
+            abort();
     }
 
     puts("Test succeeded.");

+ 9 - 7
LibOS/shim/test/regression/poll.c

@@ -5,8 +5,8 @@
 #include <unistd.h>
 
 int main(void) {
-    int  ret;
-    int  fd[2];
+    int ret;
+    int fd[2];
     char string[] = "Hello, world!\n";
 
     ret = pipe(fd);
@@ -15,7 +15,9 @@ int main(void) {
         return 1;
     }
 
-    struct pollfd outfds[] = { {.fd = fd[1], .events = POLLOUT}, };
+    struct pollfd outfds[] = {
+        {.fd = fd[1], .events = POLLOUT},
+    };
     ret = poll(outfds, 1, -1);
     if (ret <= 0) {
         perror("poll with POLLOUT failed");
@@ -23,8 +25,10 @@ int main(void) {
     }
     printf("poll(POLLOUT) returned %d file descriptors\n", ret);
 
-    struct pollfd infds[] = { {.fd = fd[0], .events = POLLIN}, };
-    write(fd[1], string, (strlen(string)+1));
+    struct pollfd infds[] = {
+        {.fd = fd[0], .events = POLLIN},
+    };
+    write(fd[1], string, (strlen(string) + 1));
     ret = poll(infds, 1, -1);
     if (ret <= 0) {
         perror("poll with POLLIN failed");
@@ -34,5 +38,3 @@ int main(void) {
 
     return 0;
 }
-
-

+ 10 - 8
LibOS/shim/test/regression/ppoll.c

@@ -7,10 +7,10 @@
 #include <unistd.h>
 
 int main(void) {
-    int  ret;
-    int  fd[2];
+    int ret;
+    int fd[2];
     char string[] = "Hello, world!\n";
-    struct timespec tv = { .tv_sec = 10, .tv_nsec = 0};
+    struct timespec tv = {.tv_sec = 10, .tv_nsec = 0};
 
     ret = pipe(fd);
     if (ret < 0) {
@@ -18,7 +18,9 @@ int main(void) {
         return 1;
     }
 
-    struct pollfd outfds[] = { {.fd = fd[1], .events = POLLOUT}, };
+    struct pollfd outfds[] = {
+        {.fd = fd[1], .events = POLLOUT},
+    };
     ret = ppoll(outfds, 1, &tv, NULL);
     if (ret <= 0) {
         perror("ppoll with POLLOUT failed");
@@ -26,8 +28,10 @@ int main(void) {
     }
     printf("ppoll(POLLOUT) returned %d file descriptors\n", ret);
 
-    struct pollfd infds[] = { {.fd = fd[0], .events = POLLIN}, };
-    write(fd[1], string, (strlen(string)+1));
+    struct pollfd infds[] = {
+        {.fd = fd[0], .events = POLLIN},
+    };
+    write(fd[1], string, (strlen(string) + 1));
     ret = ppoll(infds, 1, &tv, NULL);
     if (ret <= 0) {
         perror("ppoll with POLLIN failed");
@@ -37,5 +41,3 @@ int main(void) {
 
     return 0;
 }
-
-

+ 3 - 3
LibOS/shim/test/regression/pselect.c

@@ -9,8 +9,8 @@ int main(void) {
     fd_set rfds;
     fd_set wfds;
 
-    int  ret;
-    int  fd[2];
+    int ret;
+    int fd[2];
     char string[] = "Hello, world!\n";
     struct timespec tv = {.tv_sec = 10, .tv_nsec = 0};
 
@@ -32,7 +32,7 @@ int main(void) {
     }
     printf("pselect() on write event returned %d file descriptors\n", ret);
 
-    write(fd[1], string, (strlen(string)+1));
+    write(fd[1], string, (strlen(string) + 1));
     ret = pselect(fd[1] + 1, &rfds, NULL, NULL, &tv, NULL);
     if (ret <= 0) {
         perror("pselect() on read event failed");

+ 4 - 4
LibOS/shim/test/regression/sched.c

@@ -11,7 +11,7 @@
 
 int main(int argc, char** argv) {
     /* setters */
-    struct sched_param param = { .sched_priority = 50 };
+    struct sched_param param = {.sched_priority = 50};
     if (sched_setscheduler(0, SCHED_RR, &param) == -1) {
         perror("Error setting scheduler\n");
         return 1;
@@ -65,9 +65,9 @@ int main(int argc, char** argv) {
         return 2;
     }
 
-    struct timespec interval = { 0 };
-    if (sched_rr_get_interval(0, &interval) == -1 ||
-            interval.tv_sec != 0 || interval.tv_nsec != 100000000) {
+    struct timespec interval = {0};
+    if (sched_rr_get_interval(0, &interval) == -1 || interval.tv_sec != 0 ||
+            interval.tv_nsec != 100000000) {
         perror("Error getting interval of SCHED_RR\n");
         return 2;
     }

+ 3 - 3
LibOS/shim/test/regression/select.c

@@ -9,8 +9,8 @@ int main(void) {
     fd_set rfds;
     fd_set wfds;
 
-    int  ret;
-    int  fd[2];
+    int ret;
+    int fd[2];
     char string[] = "Hello, world!\n";
     struct timeval tv = {.tv_sec = 10, .tv_usec = 0};
 
@@ -32,7 +32,7 @@ int main(void) {
     }
     printf("select() on write event returned %d file descriptors\n", ret);
 
-    write(fd[1], string, (strlen(string)+1));
+    write(fd[1], string, (strlen(string) + 1));
     ret = select(fd[1] + 1, &rfds, NULL, NULL, &tv);
     if (ret <= 0) {
         perror("select() on read event failed");

+ 3 - 5
LibOS/shim/test/regression/sigprocmask.c

@@ -4,14 +4,12 @@
 #include <stdlib.h>
 #include <unistd.h>
 
-void* thread_func(void* arg)
-{
+void* thread_func(void* arg) {
     exit(113);
     return NULL;
 }
 
-int main(int argc, char* argv[])
-{
+int main(int argc, char* argv[]) {
     sigset_t newmask;
     sigset_t oldmask;
     sigemptyset(&newmask);
@@ -44,7 +42,7 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-    while(1)
+    while (1)
         sleep(1);
 
     return -1;

+ 4 - 4
LibOS/shim/test/regression/spinlock.c

@@ -1,14 +1,14 @@
 /* Poor man's spinlock test */
+#include "spinlock.h"
+
 #include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
 
-#include "spinlock.h"
-
 #define TEST_TIMES 1000
 
 static spinlock_t guard = INIT_SPINLOCK_UNLOCKED;
-static spinlock_t go = INIT_SPINLOCK_UNLOCKED;
+static spinlock_t go    = INIT_SPINLOCK_UNLOCKED;
 static volatile int x = 0;
 
 static int set_expect(int s, int e) {
@@ -47,7 +47,7 @@ static void do_test(void) {
         exit(1);
     }
 
-    pthread_join(th, (void **)&ret_val);
+    pthread_join(th, (void**)&ret_val);
     if (ret_val) {
         puts("Test failed!");
         exit(1);

+ 4 - 2
Pal/lib/graphene/config.c

@@ -414,8 +414,9 @@ static int __dup_config(const struct config_store* ss, const LISTP_TYPE(config)
                 *data += e->klen;
                 *size -= e->klen;
                 memcpy(key, e->key, e->klen);
-            } else
+            } else {
                 need += e->klen;
+            }
         }
         if (e->val) {
             if (*size > e->vlen) {
@@ -423,8 +424,9 @@ static int __dup_config(const struct config_store* ss, const LISTP_TYPE(config)
                 *data += e->vlen;
                 *size -= e->vlen;
                 memcpy(val, e->val, e->vlen);
-            } else
+            } else {
                 need += e->vlen;
+            }
         }
 
         if (need) {

+ 23 - 19
Pal/lib/network/inet_pton.c

@@ -54,27 +54,28 @@ int inet_pton4(const char* src, size_t len, void* dstp) {
             uint32_t new = *tp * 10 + (ch - '0');
 
             if (saw_digit && *tp == 0)
-                return (0);
+                return 0;
             if (new > 255)
-                return (0);
+                return 0;
             *tp = new;
             if (!saw_digit) {
                 if (++octets > 4)
-                    return (0);
+                    return 0;
                 saw_digit = 1;
             }
         } else if (ch == '.' && saw_digit) {
             if (octets == 4)
-                return (0);
+                return 0;
             *++tp     = 0;
             saw_digit = 0;
-        } else
-            return (0);
+        } else {
+            return 0;
+        }
     }
     if (octets < 4)
-        return (0);
+        return 0;
     memcpy(dst, tmp, NS_INADDRSZ);
-    return (1);
+    return 1;
 }
 
 static int tolower(char c) {
@@ -97,7 +98,10 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
     unsigned char* dst          = (unsigned char*)dstp;
     const char* end             = src + len;
     static const char xdigits[] = "0123456789abcdef";
-    unsigned char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
+    unsigned char tmp[NS_IN6ADDRSZ];
+    unsigned char* tp;
+    unsigned char* endp;
+    unsigned char* colonp;
     const char* curtok;
     int ch, saw_xdigit;
     unsigned int val;
@@ -108,7 +112,7 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
     /* Leading :: requires some special handling. */
     if (*src == ':')
         if (*++src != ':')
-            return (0);
+            return 0;
     curtok     = src;
     saw_xdigit = 0;
     val        = 0;
@@ -120,7 +124,7 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
             val <<= 4;
             val |= (pch - xdigits);
             if (val > 0xffff)
-                return (0);
+                return 0;
             saw_xdigit = 1;
             continue;
         }
@@ -128,14 +132,14 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
             curtok = src;
             if (!saw_xdigit) {
                 if (colonp)
-                    return (0);
+                    return 0;
                 colonp = tp;
                 continue;
             } else if (*src == '\0') {
-                return (0);
+                return 0;
             }
             if (tp + NS_INT16SZ > endp)
-                return (0);
+                return 0;
             *tp++      = (unsigned char)(val >> 8) & 0xff;
             *tp++      = (unsigned char)val & 0xff;
             saw_xdigit = 0;
@@ -147,11 +151,11 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
             saw_xdigit = 0;
             break; /* '\0' was seen by inet_pton4(). */
         }
-        return (0);
+        return 0;
     }
     if (saw_xdigit) {
         if (tp + NS_INT16SZ > endp)
-            return (0);
+            return 0;
         *tp++ = (unsigned char)(val >> 8) & 0xff;
         *tp++ = (unsigned char)val & 0xff;
     }
@@ -164,7 +168,7 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
         int i;
 
         if (tp == endp)
-            return (0);
+            return 0;
         for (i = 1; i <= n; i++) {
             endp[-i]      = colonp[n - i];
             colonp[n - i] = 0;
@@ -172,7 +176,7 @@ int inet_pton6(const char* src, size_t len, void* dstp) {
         tp = endp;
     }
     if (tp != endp)
-        return (0);
+        return 0;
     memcpy(dst, tmp, NS_IN6ADDRSZ);
-    return (1);
+    return 1;
 }

+ 0 - 1
Pal/lib/string/strendswith.c

@@ -1,6 +1,5 @@
 #include <api.h>
 
-
 bool strendswith(const char* haystack, const char* needle) {
     size_t haystack_len = strlen(haystack);
     size_t needle_len = strlen(needle);

+ 2 - 2
Pal/regression/Attestation.c

@@ -2,7 +2,7 @@
 #include "pal_debug.h"
 
 int main(int argc, char** argv, char** envp) {
-    pal_printf("Attestation status: %s\n",      pal_control.attestation_status);
-    pal_printf("Attestation timestamp: %s\n",   pal_control.attestation_timestamp);
+    pal_printf("Attestation status: %s\n", pal_control.attestation_status);
+    pal_printf("Attestation timestamp: %s\n", pal_control.attestation_timestamp);
     return 0;
 }

+ 6 - 3
Pal/regression/Pipe.c

@@ -3,8 +3,10 @@
 #include "pal_debug.h"
 
 int main(int argc, char** argv, char** envp) {
-    char buffer1[20] = "Hello World 1", buffer2[20] = "Hello World 2";
-    char buffer3[20], buffer4[20];
+    char buffer1[20] = "Hello World 1";
+    char buffer2[20] = "Hello World 2";
+    char buffer3[20];
+    char buffer4[20];
     int ret;
 
     PAL_HANDLE pipe1 = DkStreamOpen("pipe.srv:1", PAL_ACCESS_RDWR, 0, 0, 0);
@@ -17,8 +19,9 @@ int main(int argc, char** argv, char** envp) {
         if (!DkStreamAttributesQueryByHandle(pipe1, &attr)) {
             pal_printf("Failed to get any attributes from the pipesrv\n");
             return -1;
-        } else
+        } else {
             pal_printf("Pipe Attribute Query 1 on pipesrv returned OK\n");
+        }
         // DEP: would be nice to sanity check the attributes.
         // Job for another day...
 

+ 15 - 21
Pal/src/db_object.c

@@ -20,19 +20,18 @@
  * This file contains APIs for closing or polling PAL handles.
  */
 
-#include "pal_defs.h"
-#include "pal.h"
-#include "pal_internal.h"
-#include "pal_error.h"
-#include "pal_debug.h"
 #include "api.h"
 #include "atomic.h"
+#include "pal.h"
+#include "pal_debug.h"
+#include "pal_defs.h"
+#include "pal_error.h"
+#include "pal_internal.h"
 
 /* Deprecated DkObjectReference. */
 
-int _DkObjectClose (PAL_HANDLE objectHandle)
-{
-    const struct handle_ops * ops = HANDLE_OPS(objectHandle);
+int _DkObjectClose(PAL_HANDLE objectHandle) {
+    const struct handle_ops* ops = HANDLE_OPS(objectHandle);
     if (!ops)
         return -PAL_ERROR_BADHANDLE;
 
@@ -44,9 +43,8 @@ int _DkObjectClose (PAL_HANDLE objectHandle)
 
     /*
      * Chia-Che 12/7/2017:
-     *   _DkObjectClose will free the object, unless the handle has
-     *   a 'close' operation, and the operation returns a non-zero value
-     *   (e.g., 1 for skipping free() or -ERRNO).
+     *   _DkObjectClose will free the object, unless the handle has a 'close' operation, and the
+     *   operation returns a non-zero value (e.g., 1 for skipping free() or -ERRNO).
      */
     if (!ret)
         free(objectHandle);
@@ -55,8 +53,7 @@ int _DkObjectClose (PAL_HANDLE objectHandle)
 }
 
 /* PAL call DkObjectClose: Close the given object handle. */
-void DkObjectClose (PAL_HANDLE objectHandle)
-{
+void DkObjectClose(PAL_HANDLE objectHandle) {
     ENTER_PAL_CALL(DkObjectClose);
 
     if (!objectHandle) {
@@ -71,8 +68,8 @@ void DkObjectClose (PAL_HANDLE objectHandle)
     LEAVE_PAL_CALL();
 }
 
-// PAL call DkObjectsWaitAny: wait for any of the handles in the handle array.
-// The wait can be timed out, unless NO_TIMEOUT is given for the timeout_us argument.
+/* PAL call DkObjectsWaitAny: wait for any of the handles in the handle array. The wait can be timed
+ * out, unless NO_TIMEOUT is given for the timeout_us argument. */
 PAL_HANDLE
 DkObjectsWaitAny(PAL_NUM count, PAL_HANDLE* handle_array, PAL_NUM timeout_us) {
     ENTER_PAL_CALL(DkObjectsWaitAny);
@@ -82,13 +79,12 @@ DkObjectsWaitAny(PAL_NUM count, PAL_HANDLE* handle_array, PAL_NUM timeout_us) {
         LEAVE_PAL_CALL_RETURN(NULL);
     }
 
-    for (PAL_NUM i = 0 ; i < count ; i++)
+    for (PAL_NUM i = 0; i < count; i++)
         if (UNKNOWN_HANDLE(handle_array[i])) {
             _DkRaiseFailure(PAL_ERROR_INVAL);
             LEAVE_PAL_CALL_RETURN(NULL);
         }
 
-
     PAL_HANDLE polled = NULL;
 
     int ret = _DkObjectsWaitAny(count, handle_array, timeout_us, &polled);
@@ -100,10 +96,8 @@ DkObjectsWaitAny(PAL_NUM count, PAL_HANDLE* handle_array, PAL_NUM timeout_us) {
     LEAVE_PAL_CALL_RETURN(polled);
 }
 
-/* Wait for user-specified events of handles in the handle array. The wait can be timed out,
- * unless NO_TIMEOUT is given in the timeout_us argument. Returns PAL_TRUE if waiting was
- * successful.
- */
+/* Wait for user-specified events of handles in the handle array. The wait can be timed out, unless
+ * NO_TIMEOUT is given in the timeout_us argument. Returns PAL_TRUE if waiting was successful. */
 PAL_BOL DkObjectsWaitEvents(PAL_NUM count, PAL_HANDLE* handle_array, PAL_FLG* events,
                             PAL_FLG* ret_events, PAL_NUM timeout_us) {
     ENTER_PAL_CALL(DkObjectsWaitEvents);

+ 28 - 30
Pal/src/host/Linux-SGX/db_eventfd.c

@@ -17,26 +17,25 @@
 /*
  * db_eventfd.c
  *
- * This file contains operations to handle streams with URIs that have
- * "eventfd:".
+ * This file contains operations to handle streams with URIs that have "eventfd:".
  */
 
 #include <asm/fcntl.h>
 #include <asm/poll.h>
-#include <linux/un.h>
 #include <linux/types.h>
+#include <linux/un.h>
 #include <sys/eventfd.h>
 
 #include "api.h"
-#include "pal_defs.h"
-#include "pal_linux_defs.h"
 #include "pal.h"
+#include "pal_debug.h"
+#include "pal_defs.h"
+#include "pal_error.h"
 #include "pal_internal.h"
 #include "pal_linux.h"
+#include "pal_linux_defs.h"
 #include "pal_linux_error.h"
-#include "pal_error.h"
 #include "pal_security.h"
-#include "pal_debug.h"
 
 static inline int eventfd_type(int options) {
     int type = 0;
@@ -52,10 +51,10 @@ static inline int eventfd_type(int options) {
     return type;
 }
 
-/* `type` must be eventfd, `uri` & `access` & `share` are unused,
- * `create` holds eventfd's initval, `options` holds eventfd's flags */
+/* `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) {
+                            int share, int create, int options) {
     int ret;
     __UNUSED(access);
     __UNUSED(share);
@@ -76,12 +75,11 @@ static int eventfd_pal_open(PAL_HANDLE* handle, const char* type, const char* ur
     /* Note: using index 0, given that there is only 1 eventfd FD per pal-handle. */
     HANDLE_HDR(hdl)->flags = RFD(0) | WFD(0) | WRITABLE(0);
 
-    hdl->eventfd.fd = ret;
+    hdl->eventfd.fd          = ret;
     hdl->eventfd.nonblocking = (options & PAL_OPTION_NONBLOCK) ? PAL_TRUE : PAL_FALSE;
     *handle = hdl;
 
     return 0;
-
 }
 
 static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len, void* buffer) {
@@ -94,8 +92,8 @@ static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len
     if (len < sizeof(uint64_t))
         return -PAL_ERROR_INVAL;
 
-    /* TODO: verify that the value returned in buffer is somehow meaningful
-     * (to prevent Iago attacks) */
+    /* TODO: verify that the value returned in buffer is somehow meaningful (to prevent Iago
+     * attacks) */
     int bytes = ocall_read(handle->eventfd.fd, buffer, len);
 
     if (IS_ERR(bytes))
@@ -108,7 +106,7 @@ static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len
 }
 
 static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t len,
-        const void* buffer) {
+                                 const void* buffer) {
     if (offset)
         return -PAL_ERROR_INVAL;
 
@@ -127,9 +125,9 @@ static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t le
         return unix_to_pal_error(ERRNO(bytes));
     }
 
-    /* whether fd is writable or not, gets updated here,
-     * to optimize polling logic in _DkObjectsWaitAny */
-    if ((uint64_t) bytes == sizeof(uint64_t))
+    /* whether fd is writable or not, gets updated here, to optimize polling logic in
+     * _DkObjectsWaitAny */
+    if ((uint64_t)bytes == sizeof(uint64_t))
         HANDLE_HDR(handle)->flags |= writable;
     else
         HANDLE_HDR(handle)->flags &= ~writable;
@@ -147,21 +145,21 @@ static int eventfd_pal_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr)
     int efd = handle->eventfd.fd;
     int flags = HANDLE_HDR(handle)->flags;
 
-    struct pollfd pfd = { .fd = efd, .events = POLLIN, .revents = 0 };
+    struct pollfd pfd = {.fd = efd, .events = POLLIN, .revents = 0};
     int ret = ocall_poll(&pfd, 1, 0);
 
     if (IS_ERR(ret))
         return unix_to_pal_error(ERRNO(ret));
 
-    attr->readable = (ret == 1 && pfd.revents == POLLIN);
+    attr->readable     = (ret == 1 && pfd.revents == POLLIN);
     attr->disconnected = flags & ERROR(0);
-    attr->nonblocking = handle->eventfd.nonblocking;
+    attr->nonblocking  = handle->eventfd.nonblocking;
 
-    /* For future use, so that Linux host kernel can send notifications to user-space apps.
-     * App receives virtual FD from LibOS, but the Linux-host eventfd is memorized
-     * here, such that this Linux-host eventfd can be retrieved (by LibOS) during app's ioctl(). */
+    /* For future use, so that Linux host kernel can send notifications to user-space apps. App
+     * receives virtual FD from LibOS, but the Linux-host eventfd is memorized here, such that this
+     * Linux-host eventfd can be retrieved (by LibOS) during app's ioctl(). */
     attr->no_of_fds = 1;
-    attr->fds[0] = efd;
+    attr->fds[0]    = efd;
 
     return 0;
 }
@@ -179,9 +177,9 @@ static int eventfd_pal_close(PAL_HANDLE handle) {
 }
 
 struct handle_ops eventfd_ops = {
-    .open               = &eventfd_pal_open,
-    .read               = &eventfd_pal_read,
-    .write              = &eventfd_pal_write,
-    .close              = &eventfd_pal_close,
-    .attrquerybyhdl     = &eventfd_pal_attrquerybyhdl,
+    .open           = &eventfd_pal_open,
+    .read           = &eventfd_pal_read,
+    .write          = &eventfd_pal_write,
+    .close          = &eventfd_pal_close,
+    .attrquerybyhdl = &eventfd_pal_attrquerybyhdl,
 };

+ 17 - 16
Pal/src/host/Linux-SGX/db_object.c

@@ -20,6 +20,10 @@
  * This file contains APIs for waiting on PAL handles (polling).
  */
 
+#include <linux/poll.h>
+#include <linux/time.h>
+#include <linux/wait.h>
+
 #include "api.h"
 #include "pal.h"
 #include "pal_debug.h"
@@ -30,12 +34,8 @@
 #include "pal_linux_defs.h"
 #include "pal_linux_error.h"
 
-#include <linux/poll.h>
-#include <linux/time.h>
-#include <linux/wait.h>
-
-/* Wait for an event on any handle in the handle array and return this handle in `polled`.
- * If no ready-event handle was found, `polled` is set to NULL. */
+/* Wait for an event on any handle in the handle array and return this handle in `polled`. If no
+ * ready-event handle was found, `polled` is set to NULL. */
 int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us,
                       PAL_HANDLE* polled) {
     int ret;
@@ -43,7 +43,7 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
         return 0;
 
     if (count == 1 && handle_array[0] &&
-        (IS_HANDLE_TYPE(handle_array[0], mutex) || IS_HANDLE_TYPE(handle_array[0], event))) {
+            (IS_HANDLE_TYPE(handle_array[0], mutex) || IS_HANDLE_TYPE(handle_array[0], event))) {
         /* Special case of DkObjectsWaitAny(1, mutex/event, ...): perform a mutex-specific or
          * event-specific wait() callback instead of host-OS poll. */
         const struct handle_ops* ops = HANDLE_OPS(handle_array[0]);
@@ -93,7 +93,7 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
                 fds[nfds].fd      = hdl->generic.fds[j];
                 fds[nfds].events  = events;
                 fds[nfds].revents = 0;
-                hdls[nfds]        = hdl;
+                hdls[nfds] = hdl;
                 nfds++;
             }
         }
@@ -148,10 +148,11 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
             if (polled_hdl->generic.fds[j] != (PAL_IDX)fds[i].fd)
                 continue;
 
-            /* found internal FD of PAL handle that corresponds to the FD of event-ready fds[i] */
+            /* found internal FD of PAL handle that corresponds to the FD of
+             * event-ready fds[i] */
             if (fds[i].revents & POLLOUT)
                 HANDLE_HDR(polled_hdl)->flags |= WRITABLE(j);
-            if (fds[i].revents & (POLLHUP|POLLERR))
+            if (fds[i].revents & (POLLHUP | POLLERR))
                 HANDLE_HDR(polled_hdl)->flags |= ERROR(j);
         }
     }
@@ -162,12 +163,12 @@ out:
     return ret;
 }
 
-
 /* Improved version of _DkObjectsWaitAny(): wait for specific events on all handles in the handle
- * array and return multiple events (including errors) reported by the host. Returns 0 on success,
+ * array and return multiple events (including errors) reported by the host.
+ * Returns 0 on success,
  * PAL error on failure. */
-int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events,
-                         int64_t timeout_us) {
+int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events,
+                         PAL_FLG* ret_events, int64_t timeout_us) {
     int ret;
 
     if (count == 0)
@@ -211,7 +212,7 @@ int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events
                 fds[nfds].fd      = hdl->generic.fds[j];
                 fds[nfds].events  = fdevents;
                 fds[nfds].revents = 0;
-                offsets[nfds]     = i;
+                offsets[nfds] = i;
                 nfds++;
             }
         }
@@ -253,7 +254,7 @@ int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events
             ret_events[j] |= PAL_WAIT_READ;
         if (fds[i].revents & POLLOUT)
             ret_events[j] |= PAL_WAIT_WRITE;
-        if (fds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
+        if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL))
             ret_events[j] |= PAL_WAIT_ERROR;
     }
 

+ 70 - 59
Pal/src/host/Linux-SGX/enclave_platform.c

@@ -113,15 +113,16 @@
 
 
 /*
- * Perform the initial attestation procedure if "sgx.ra_client.spid" is specified in
- * the manifest file.
+ * Perform the initial attestation procedure if "sgx.ra_client.spid" is specified in the manifest
+ * file.
  */
 int init_trusted_platform(void) {
     char spid_hex[sizeof(sgx_spid_t) * 2 + 1];
-    ssize_t len = get_config(pal_state.root_config, "sgx.ra_client_spid", spid_hex,
-                             sizeof(spid_hex));
+    ssize_t len =
+        get_config(pal_state.root_config, "sgx.ra_client_spid", spid_hex, sizeof(spid_hex));
     if (len <= 0) {
-        SGX_DBG(DBG_E, "*** No client info specified in the manifest. "
+        SGX_DBG(DBG_E,
+                "*** No client info specified in the manifest. "
                 "Graphene will not perform remote attestation ***\n");
         return 0;
     }
@@ -138,7 +139,7 @@ int init_trusted_platform(void) {
             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 subkey[CONFIG_MAX];
@@ -172,7 +173,7 @@ int init_trusted_platform(void) {
         return ret;
 
     // If the attestation is successful, update the control block
-    __pal_control.attestation_status = status;
+    __pal_control.attestation_status    = status;
     __pal_control.attestation_timestamp = timestamp;
     return ret;
 }
@@ -313,11 +314,11 @@ static int parse_x509(uint8_t* cert, size_t cert_len, uint8_t** body, size_t* bo
     exp = ptr;
     ptr += exp_len;
 
-    *body = malloc(cert_signed_len);
+    *body     = malloc(cert_signed_len);
     *body_len = cert_signed_len;
     memcpy(*body, cert_signed, cert_signed_len);
 
-    *sig = malloc(cert_sig_len);
+    *sig     = malloc(cert_sig_len);
     *sig_len = cert_sig_len;
     memcpy(*sig, cert_sig, cert_sig_len);
 
@@ -345,7 +346,6 @@ static int parse_x509(uint8_t* cert, size_t cert_len, uint8_t** body, size_t* bo
  */
 static int parse_x509_pem(char* cert, char** cert_end, uint8_t** body, size_t* body_len,
                           uint8_t** sig, size_t* sig_len, LIB_RSA_KEY* pubkey) {
-
     int ret;
     char* start = strchr(cert, '-');
     if (!start) {
@@ -384,13 +384,13 @@ static int parse_x509_pem(char* cert, char** cert_end, uint8_t** body, size_t* b
 /*
  * Perform the remote attestation to verify the current SGX platform.
  *
- * The remote attestation procedure verifies two primary properties: (1) The current execution
- * runs in an SGX enclave; and (2) The enclave is created on a genuine, up-to-date Intel CPU.
- * This procedure requires interaction with the Intel PSW quoting enclave (AESMD) and the
- * Intel Attestation Service (IAS). The quoting enclave verifies a local attestation report
- * from the target enclave, and then generates a quoting enclave (QE) report and a platform
- * quote signed by the platform's attestation key. The IAS then verifies the platform quote and
- * issues a remote attestation report, signed by a certificate chain attached to the report.
+ * The remote attestation procedure verifies two primary properties: (1) The current execution runs
+ * in an SGX enclave; and (2) The enclave is created on a genuine, up-to-date Intel CPU. This
+ * procedure requires interaction with the Intel PSW quoting enclave (AESMD) and the Intel
+ * Attestation Service (IAS). The quoting enclave verifies a local attestation report from the
+ * target enclave, and then generates a quoting enclave (QE) report and a platform quote signed by
+ * the platform's attestation key. The IAS then verifies the platform quote and issues a remote
+ * attestation report, signed by a certificate chain attached to the report.
  *
  * TODO: currently no verification of the correctness of the IAS certificate
  *
@@ -411,7 +411,6 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
                         bool accept_group_out_of_date, bool accept_configuration_needed,
                         sgx_attestation_t* ret_attestation, char** ret_ias_status,
                         char** ret_ias_timestamp) {
-
     SGX_DBG(DBG_S, "Request quote:\n");
     SGX_DBG(DBG_S, "  spid:  %s\n", ALLOCA_BYTES2HEXSTR(*spid));
     SGX_DBG(DBG_S, "  type:  %s\n", linkable ? "linkable" : "unlinkable");
@@ -443,30 +442,28 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
     // Verify the IAS response against the certificate chain
     uint8_t* data_to_verify = (uint8_t*)attestation.ias_report;
     uint8_t* data_sig       = attestation.ias_sig;
-    size_t   data_len       = attestation.ias_report_len;
-    size_t   data_sig_len   = attestation.ias_sig_len;
+    size_t data_len         = attestation.ias_report_len;
+    size_t data_sig_len     = attestation.ias_sig_len;
 
     // Attach the IAS signing chain with the hard-coded CA certificate
     const char* ca_cert = IAS_CA_CERT;
-    size_t len1 = strlen(attestation.ias_certs);
-    size_t len2 = static_strlen(IAS_CA_CERT);
-    char* certs = malloc(len1 + len2 + 1);
+    size_t len1         = strlen(attestation.ias_certs);
+    size_t len2         = static_strlen(IAS_CA_CERT);
+    char* certs         = malloc(len1 + len2 + 1);
     memcpy(certs, attestation.ias_certs, len1);
     memcpy(certs + len1, ca_cert, len2);
     certs[len1 + len2] = 0;
     free(attestation.ias_certs);
-    attestation.ias_certs = certs;
+    attestation.ias_certs     = certs;
     attestation.ias_certs_len = len1 + len2 + 1;
 
-    // There can be multiple certificates in the chain. We need to use the public key from
-    // the *first* certificate to verify the IAS response. For each certificate except
-    // the last one, we need to use the public key from the *next* certificate to verify
-    // the certificate body. The last certificate will be verified by the CA certificate
-    // (hard-coded in the binary)
+    // There can be multiple certificates in the chain. We need to use the public key from the
+    // *first* certificate to verify the IAS response. For each certificate except the last one, we
+    // need to use the public key from the *next* certificate to verify the certificate body. The
+    // last certificate will be verified by the CA certificate (hard-coded in the binary)
 
     for (char* cert_start = attestation.ias_certs;
-         cert_start < attestation.ias_certs + attestation.ias_certs_len && *cert_start; ) {
-
+            cert_start < attestation.ias_certs + attestation.ias_certs_len && *cert_start;) {
         // Generate the message digest first (without RSA)
         LIB_SHA256_CONTEXT ctx;
         uint8_t hash[32];
@@ -481,10 +478,10 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
             goto failed;
 
         // Use the public key to verify the last signature
-        uint8_t*    cert_body;
-        uint8_t*    cert_sig;
-        size_t      cert_body_len;
-        size_t      cert_sig_len;
+        uint8_t* cert_body;
+        uint8_t* cert_sig;
+        size_t   cert_body_len;
+        size_t   cert_sig_len;
         LIB_RSA_KEY cert_key;
 
         ret = parse_x509_pem(cert_start, &cert_start, &cert_body, &cert_body_len, &cert_sig,
@@ -496,8 +493,9 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
 
         ret = lib_RSAVerifySHA256(&cert_key, hash, sizeof(hash), data_sig, data_sig_len);
         if (ret < 0) {
-            SGX_DBG(DBG_E, "Failed to verify the report against the IAS certificates,"
-                    " rv = %d\n", ret);
+            SGX_DBG(DBG_E,
+                    "Failed to verify the report against the IAS certificates, rv = %d\n",
+                    ret);
             lib_RSAFreeKey(&cert_key);
             goto failed;
         }
@@ -511,12 +509,13 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
     }
 
     // Parse the IAS report in JSON format
-    char* ias_status    = NULL;
-    char* ias_timestamp = NULL;
+    char* ias_status             = NULL;
+    char* ias_timestamp          = NULL;
     sgx_quote_nonce_t* ias_nonce = NULL;
-    sgx_quote_t*       ias_quote = NULL;
+    sgx_quote_t* ias_quote       = NULL;
     char* start = attestation.ias_report;
-    if (start[0] == '{') start++;
+    if (start[0] == '{')
+        start++;
     char* end = strchr(start, ',');
     while (end) {
         char* next_start = end + 1;
@@ -525,16 +524,24 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
         char* delim = strchr(start, ':');
         if (!delim)
             break;
-        char*  key  = start;
-        char*  val  = delim + 1;
+        char* key   = start;
+        char* val   = delim + 1;
         size_t klen = delim - start;
         size_t vlen = end - val;
 
         // Remove quotation marks (") around the key and value if there are any
-        if (key[0] == '"') { key++; klen--; }
-        if (key[klen - 1] == '"') klen--;
-        if (val[0] == '"') { val++; vlen--; }
-        if (val[vlen - 1] == '"') vlen--;
+        if (key[0] == '"') {
+            key++;
+            klen--;
+        }
+        if (key[klen - 1] == '"')
+            klen--;
+        if (val[0] == '"') {
+            val++;
+            vlen--;
+        }
+        if (val[vlen - 1] == '"')
+            vlen--;
 
         // Scan the fields in the IAS report.
         if (!memcmp(key, "isvEnclaveQuoteStatus", klen)) {
@@ -582,7 +589,7 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
         }
 
         start = next_start;
-        end = strchr(start, ',') ? : strchr(start, '}');
+        end   = strchr(start, ',') ?: strchr(start, '}');
     }
 
     if (!ias_status || !ias_nonce || !ias_timestamp || !ias_quote) {
@@ -591,18 +598,18 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
     }
 
     SGX_DBG(DBG_S, "Quote:\n");
-    SGX_DBG(DBG_S, "  version:    %04x\n",  ias_quote->body.version);
-    SGX_DBG(DBG_S, "  sigtype:    %04x\n",  ias_quote->body.sigtype);
-    SGX_DBG(DBG_S, "  gid:        %08x\n",  ias_quote->body.gid);
-    SGX_DBG(DBG_S, "  isvsvn qe:  %08x\n",  ias_quote->body.isvsvn_qe);
-    SGX_DBG(DBG_S, "  isvsvn pce: %08x\n",  ias_quote->body.isvsvn_pce);
+    SGX_DBG(DBG_S, "  version:    %04x\n", ias_quote->body.version);
+    SGX_DBG(DBG_S, "  sigtype:    %04x\n", ias_quote->body.sigtype);
+    SGX_DBG(DBG_S, "  gid:        %08x\n", ias_quote->body.gid);
+    SGX_DBG(DBG_S, "  isvsvn qe:  %08x\n", ias_quote->body.isvsvn_qe);
+    SGX_DBG(DBG_S, "  isvsvn pce: %08x\n", ias_quote->body.isvsvn_pce);
 
     SGX_DBG(DBG_S, "IAS report: %s\n", attestation.ias_report);
     SGX_DBG(DBG_S, "  status:    %s\n", ias_status);
     SGX_DBG(DBG_S, "  timestamp: %s\n", ias_timestamp);
 
-    // Only accept status to be "OK" or "GROUP_OUT_OF_DATE" / "CONFIGURATION_NEEDED"
-    // (if accept_out_of_date / accept_configuration_needed is true)
+    // Only accept status to be "OK" or "GROUP_OUT_OF_DATE" / "CONFIGURATION_NEEDED" (if
+    // accept_out_of_date / accept_configuration_needed is true)
     if (strcmp_static(ias_status, "OK") &&
         (!accept_group_out_of_date || strcmp_static(ias_status, "GROUP_OUT_OF_DATE")) &&
         (!accept_configuration_needed || strcmp_static(ias_status, "CONFIGURATION_NEEDED"))) {
@@ -648,10 +655,14 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
     }
     ret = 0;
 free_attestation:
-    if (attestation.quote)      free(attestation.quote);
-    if (attestation.ias_report) free(attestation.ias_report);
-    if (attestation.ias_sig)    free(attestation.ias_sig);
-    if (attestation.ias_certs)  free(attestation.ias_certs);
+    if (attestation.quote)
+        free(attestation.quote);
+    if (attestation.ias_report)
+        free(attestation.ias_report);
+    if (attestation.ias_sig)
+        free(attestation.ias_sig);
+    if (attestation.ias_certs)
+        free(attestation.ias_certs);
     return ret;
 
 failed:

+ 53 - 52
Pal/src/host/Linux-SGX/sgx_arch.h

@@ -21,9 +21,10 @@
 
 #ifndef __ASSEMBLER__
 
-#include "assert.h"
 #include <stdint.h>
 
+#include "assert.h"
+
 #pragma pack(push, 1)
 
 #define SE_KEY_SIZE      384
@@ -59,7 +60,7 @@ typedef uint32_t sgx_misc_select_t;
 typedef uint16_t sgx_prod_id_t;
 typedef uint16_t sgx_isv_svn_t;
 typedef uint16_t sgx_config_svn_t;
-typedef uint8_t  sgx_config_id_t[SGX_CONFIGID_SIZE];
+typedef uint8_t sgx_config_id_t[SGX_CONFIGID_SIZE];
 
 #define SGX_ISVEXT_PROD_ID_SIZE 16
 #define SGX_ISV_FAMILY_ID_SIZE  16
@@ -73,12 +74,12 @@ 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_MISCSELECT_EXINFO   0x01UL
+#define SGX_MISCSELECT_EXINFO 0x01UL
 
 typedef struct {
     uint64_t          size;
@@ -166,29 +167,30 @@ 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),
-               "rip must be directly after rflags in sgx_cpu_context_t");
-static_assert(offsetof(sgx_cpu_context_t, rflags) - offsetof(sgx_cpu_context_t, rdi) <= RED_ZONE_SIZE,
-               "rdi needs to be within red zone distance from 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, rflags) - offsetof(sgx_cpu_context_t, rdi) <=
+                  RED_ZONE_SIZE,
+              "rdi needs to be within red zone distance from rflags");
 
 typedef struct {
-    uint32_t vector:8;
-    uint32_t exit_type:3;
-    uint32_t reserved:20;
-    uint32_t valid:1;
+    uint32_t vector : 8;
+    uint32_t exit_type : 3;
+    uint32_t reserved : 20;
+    uint32_t valid : 1;
 } sgx_arch_exit_info_t;
 
-#define SGX_EXCEPTION_HARDWARE      3UL
-#define SGX_EXCEPTION_SOFTWARE      6UL
+#define SGX_EXCEPTION_HARDWARE 3UL
+#define SGX_EXCEPTION_SOFTWARE 6UL
 
-#define SGX_EXCEPTION_VECTOR_DE     0UL  /* DIV and IDIV instructions */
-#define SGX_EXCEPTION_VECTOR_DB     1UL  /* For Intel use only */
-#define SGX_EXCEPTION_VECTOR_BP     3UL  /* INT 3 instruction */
-#define SGX_EXCEPTION_VECTOR_BR     5UL  /* BOUND instruction */
-#define SGX_EXCEPTION_VECTOR_UD     6UL  /* UD2 instruction or reserved opcodes */
-#define SGX_EXCEPTION_VECTOR_MF    16UL  /* x87 FPU floating-point or WAIT/FWAIT instruction */
-#define SGX_EXCEPTION_VECTOR_AC    17UL  /* Any data reference in memory */
-#define SGX_EXCEPTION_VECTOR_XM    19UL  /* Any SIMD floating-point exceptions */
+#define SGX_EXCEPTION_VECTOR_DE 0UL  /* DIV and IDIV instructions */
+#define SGX_EXCEPTION_VECTOR_DB 1UL  /* For Intel use only */
+#define SGX_EXCEPTION_VECTOR_BP 3UL  /* INT 3 instruction */
+#define SGX_EXCEPTION_VECTOR_BR 5UL  /* BOUND instruction */
+#define SGX_EXCEPTION_VECTOR_UD 6UL  /* UD2 instruction or reserved opcodes */
+#define SGX_EXCEPTION_VECTOR_MF 16UL /* x87 FPU floating-point or WAIT/FWAIT instruction */
+#define SGX_EXCEPTION_VECTOR_AC 17UL /* Any data reference in memory */
+#define SGX_EXCEPTION_VECTOR_XM 19UL /* Any SIMD floating-point exceptions */
 
 typedef struct {
     uint64_t lin_addr;
@@ -202,12 +204,12 @@ typedef struct {
     uint64_t reserved[7];
 } sgx_arch_sec_info_t;
 
-#define SGX_SECINFO_FLAGS_R             0x001
-#define SGX_SECINFO_FLAGS_W             0x002
-#define SGX_SECINFO_FLAGS_X             0x004
-#define SGX_SECINFO_FLAGS_SECS          0x000
-#define SGX_SECINFO_FLAGS_TCS           0x100
-#define SGX_SECINFO_FLAGS_REG           0x200
+#define SGX_SECINFO_FLAGS_R    0x001
+#define SGX_SECINFO_FLAGS_W    0x002
+#define SGX_SECINFO_FLAGS_X    0x004
+#define SGX_SECINFO_FLAGS_SECS 0x000
+#define SGX_SECINFO_FLAGS_TCS  0x100
+#define SGX_SECINFO_FLAGS_REG  0x200
 
 typedef struct _css_header_t {
     uint8_t  header[12];
@@ -340,8 +342,7 @@ typedef struct _key_request_t {
 } sgx_key_request_t;
 static_assert(sizeof(sgx_key_request_t) == 512, "incorrect struct size");
 
-#define SGX_TARGETINFO_FILLED_SIZE (sizeof(sgx_measurement_t) + \
-                                    sizeof(sgx_attributes_t))
+#define SGX_TARGETINFO_FILLED_SIZE (sizeof(sgx_measurement_t) + sizeof(sgx_attributes_t))
 
 typedef uint8_t sgx_key_128bit_t[16];
 
@@ -356,34 +357,34 @@ typedef uint8_t sgx_key_128bit_t[16];
 
 #endif
 
-#define EENTER      2
-#define ERESUME     3
-#define EDBGRD      4
-#define EDBGWR      5
+#define EENTER  2
+#define ERESUME 3
+#define EDBGRD  4
+#define EDBGWR  5
 
-#define EREPORT     0
-#define EGETKEY     1
-#define EEXIT       4
+#define EREPORT 0
+#define EGETKEY 1
+#define EEXIT   4
 
-#define LAUNCH_KEY          0
-#define PROVISION_KEY       1
-#define PROVISION_SEAL_KEY  2
-#define REPORT_KEY          3
-#define SEAL_KEY            4
+#define LAUNCH_KEY         0
+#define PROVISION_KEY      1
+#define PROVISION_SEAL_KEY 2
+#define REPORT_KEY         3
+#define SEAL_KEY           4
 
-#define KEYPOLICY_MRENCLAVE     1
-#define KEYPOLICY_MRSIGNER      2
+#define KEYPOLICY_MRENCLAVE 1
+#define KEYPOLICY_MRSIGNER  2
 
-#define XSAVE_SIZE  512
+#define XSAVE_SIZE 512
 
-#define STACK_ALIGN 0xfffffffffffffff0
-#define XSAVE_ALIGN 0xffffffffffffffc0
+#define STACK_ALIGN       0xfffffffffffffff0
+#define XSAVE_ALIGN       0xffffffffffffffc0
 #define XSAVE_NON_FX_MASK 0xfffffffffffffffc
 
 #define RETURN_FROM_OCALL 0xffffffffffffffff
 
-#define RFLAGS_DF (1<<10)
-#define RFLAGS_AC (1<<18)
+#define RFLAGS_DF (1 << 10)
+#define RFLAGS_AC (1 << 18)
 
 #pragma pack(pop)
 #endif /* SGX_ARCH_H */

+ 9 - 10
Pal/src/host/Linux-SGX/sgx_attest.h

@@ -18,24 +18,24 @@
 #ifndef SGX_ATTEST_H
 #define SGX_ATTEST_H
 
-#include "sgx_arch.h"
-
 #include <stdint.h>
 
+#include "sgx_arch.h"
+
 typedef struct {
     uint16_t version;
     uint16_t sigtype;
     uint32_t gid;
     uint16_t isvsvn_qe;
     uint16_t isvsvn_pce;
-    uint8_t  reserved[4];
-    uint8_t  base[32];
+    uint8_t reserved[4];
+    uint8_t base[32];
 } __attribute__((packed)) sgx_quote_body_t;
 
 typedef struct {
-    sgx_quote_body_t  body;
+    sgx_quote_body_t body;
     sgx_report_body_t report_body;
-    uint32_t          sig_len;
+    uint32_t sig_len;
 } __attribute__((packed)) sgx_quote_t;
 
 typedef uint8_t sgx_spid_t[16];
@@ -46,10 +46,9 @@ enum {
     SGX_LINKABLE_SIGNATURE
 };
 
-#define SGX_QUOTE_MAX_SIZE   (2048)
+#define SGX_QUOTE_MAX_SIZE 2048
 
-#define IAS_REPORT_URL \
-    "https://api.trustedservices.intel.com/sgx/dev/attestation/v3/report"
+#define IAS_REPORT_URL "https://api.trustedservices.intel.com/sgx/dev/attestation/v3/report"
 
 int init_trusted_platform(void);
 
@@ -71,6 +70,6 @@ int sgx_verify_platform(sgx_spid_t* spid, const char* subkey, sgx_quote_nonce_t*
                         sgx_attestation_t* ret_attestation, char** ret_ias_status,
                         char** ret_ias_timestamp);
 
-#define HTTPS_REQUEST_MAX_LENGTH   (256)
+#define HTTPS_REQUEST_MAX_LENGTH 256
 
 #endif /* SGX_ATTEST_H */

+ 3 - 3
Pal/src/host/Linux-SGX/sgx_enclave.h

@@ -1,8 +1,8 @@
 #include "pal_linux.h"
 #include "pal_security.h"
 
-int ecall_enclave_start (char * args, size_t args_size, char * env, size_t env_size);
+int ecall_enclave_start(char* args, size_t args_size, char* env, size_t env_size);
 
-int ecall_thread_start (void);
+int ecall_thread_start(void);
 
-int ecall_thread_reset (void);
+int ecall_thread_reset(void);

+ 30 - 32
Pal/src/host/Linux/db_eventfd.c

@@ -17,27 +17,26 @@
 /*
  * db_eventfd.c
  *
- * This file contains operations to handle streams with URIs that have
- * "eventfd:".
+ * This file contains operations to handle streams with URIs that have "eventfd:".
  */
 
 #include <asm/fcntl.h>
 #include <asm/poll.h>
-#include <linux/un.h>
 #include <linux/time.h>
 #include <linux/types.h>
+#include <linux/un.h>
 #include <sys/eventfd.h>
 
 #include "api.h"
-#include "pal_defs.h"
-#include "pal_linux_defs.h"
 #include "pal.h"
+#include "pal_debug.h"
+#include "pal_defs.h"
+#include "pal_error.h"
 #include "pal_internal.h"
 #include "pal_linux.h"
+#include "pal_linux_defs.h"
 #include "pal_linux_error.h"
-#include "pal_error.h"
 #include "pal_security.h"
-#include "pal_debug.h"
 
 static inline int eventfd_type(int options) {
     int type = 0;
@@ -53,10 +52,10 @@ static inline int eventfd_type(int options) {
     return type;
 }
 
-/* `type` must be eventfd, `uri` & `access` & `share` are unused,
- * `create` holds eventfd's initval, `options` holds eventfd's flags */
+/* `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) {
+                            int share, int create, int options) {
     int ret;
 
     __UNUSED(access);
@@ -78,12 +77,11 @@ static int eventfd_pal_open(PAL_HANDLE* handle, const char* type, const char* ur
     /* Note: using index 0, given that there is only 1 eventfd FD per pal-handle. */
     HANDLE_HDR(hdl)->flags = RFD(0) | WFD(0) | WRITABLE(0);
 
-    hdl->eventfd.fd = ret;
+    hdl->eventfd.fd          = ret;
     hdl->eventfd.nonblocking = (options & PAL_OPTION_NONBLOCK) ? PAL_TRUE : PAL_FALSE;
-    *handle = hdl;
+    *handle                  = hdl;
 
     return 0;
-
 }
 
 static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len, void* buffer) {
@@ -108,7 +106,7 @@ static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len
 }
 
 static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t len,
-        const void* buffer) {
+                                 const void* buffer) {
     if (offset)
         return -PAL_ERROR_INVAL;
 
@@ -118,7 +116,7 @@ static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t le
     if (len < sizeof(uint64_t))
         return -PAL_ERROR_INVAL;
 
-    int bytes = INLINE_SYSCALL(write, 3, handle->eventfd.fd, buffer, len);
+    int bytes        = INLINE_SYSCALL(write, 3, handle->eventfd.fd, buffer, len);
     PAL_FLG writable = WRITABLE(0);
 
     if (IS_ERR(bytes)) {
@@ -127,9 +125,9 @@ static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t le
         return unix_to_pal_error(ERRNO(bytes));
     }
 
-    /* whether fd is writable or not, gets updated here,
-     * to optimize polling logic in _DkObjectsWaitAny */
-    if ((uint64_t) bytes == sizeof(uint64_t))
+    /* whether fd is writable or not, gets updated here, to optimize polling logic in
+     * _DkObjectsWaitAny */
+    if ((uint64_t)bytes == sizeof(uint64_t))
         HANDLE_HDR(handle)->flags |= writable;
     else
         HANDLE_HDR(handle)->flags &= ~writable;
@@ -143,25 +141,25 @@ static int eventfd_pal_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr)
         return -PAL_ERROR_BADHANDLE;
 
     attr->handle_type = PAL_GET_TYPE(handle);
-    int efd = handle->eventfd.fd;
-    int flags = HANDLE_HDR(handle)->flags;
+    int efd           = handle->eventfd.fd;
+    int flags         = HANDLE_HDR(handle)->flags;
 
-    struct pollfd pfd = { .fd = efd, .events = POLLIN, .revents = 0 };
+    struct pollfd pfd  = {.fd = efd, .events = POLLIN, .revents = 0};
     struct timespec tp = {0, 0};
     int ret = INLINE_SYSCALL(ppoll, 5, &pfd, 1, &tp, NULL, 0);
 
     if (IS_ERR(ret))
         return unix_to_pal_error(ERRNO(ret));
 
-    attr->readable = (ret == 1 && pfd.revents == POLLIN);
+    attr->readable     = (ret == 1 && pfd.revents == POLLIN);
     attr->disconnected = flags & ERROR(0);
-    attr->nonblocking = handle->eventfd.nonblocking;
+    attr->nonblocking  = handle->eventfd.nonblocking;
 
-    /* For future use, so that Linux host kernel can send notifications to user-space apps.
-     * App receives virtual FD from LibOS, but the Linux-host eventfd is memorized
-     * here, such that this Linux-host eventfd can be retrieved (by LibOS) during app's ioctl(). */
+    /* For future use, so that Linux host kernel can send notifications to user-space apps. App
+     * receives virtual FD from LibOS, but the Linux-host eventfd is memorized here, such that this
+     * Linux-host eventfd can be retrieved (by LibOS) during app's ioctl(). */
     attr->no_of_fds = 1;
-    attr->fds[0] = efd;
+    attr->fds[0]    = efd;
 
     return 0;
 }
@@ -178,9 +176,9 @@ static int eventfd_pal_close(PAL_HANDLE handle) {
 }
 
 struct handle_ops eventfd_ops = {
-    .open               = &eventfd_pal_open,
-    .read               = &eventfd_pal_read,
-    .write              = &eventfd_pal_write,
-    .close              = &eventfd_pal_close,
-    .attrquerybyhdl     = &eventfd_pal_attrquerybyhdl,
+    .open           = &eventfd_pal_open,
+    .read           = &eventfd_pal_read,
+    .write          = &eventfd_pal_write,
+    .close          = &eventfd_pal_close,
+    .attrquerybyhdl = &eventfd_pal_attrquerybyhdl,
 };

+ 25 - 35
Pal/src/host/Linux/db_misc.c

@@ -20,22 +20,21 @@
  * This file contains APIs for miscellaneous use.
  */
 
-#include "pal_defs.h"
-#include "pal_linux_defs.h"
+#include <asm/fcntl.h>
+#include <linux/time.h>
+
+#include "api.h"
 #include "pal.h"
+#include "pal_defs.h"
+#include "pal_error.h"
 #include "pal_internal.h"
 #include "pal_linux.h"
-#include "pal_error.h"
+#include "pal_linux_defs.h"
 #include "pal_security.h"
-#include "api.h"
-
-#include <linux/time.h>
-#include <asm/fcntl.h>
 
-int __gettimeofday(struct timeval *tv, struct timezone *tz);
+int __gettimeofday(struct timeval* tv, struct timezone* tz);
 
-unsigned long _DkSystemTimeQueryEarly (void)
-{
+unsigned long _DkSystemTimeQueryEarly(void) {
 #if USE_CLOCK_GETTIME == 1
     struct timespec time;
     int ret;
@@ -63,8 +62,7 @@ unsigned long _DkSystemTimeQueryEarly (void)
 #endif
 }
 
-unsigned long _DkSystemTimeQuery (void)
-{
+unsigned long _DkSystemTimeQuery(void) {
 #if USE_CLOCK_GETTIME == 1
     struct timespec time;
     int ret;
@@ -113,28 +111,25 @@ unsigned long _DkSystemTimeQuery (void)
 }
 
 #if USE_ARCH_RDRAND == 1
-int _DkRandomBitsRead (void * buffer, int size)
-{
+int _DkRandomBitsRead(void* buffer, int size) {
     int total_bytes = 0;
     do {
         unsigned long rand;
-        asm volatile (".Lretry: rdrand %%rax\r\n jnc .Lretry\r\n"
-                      : "=a"(rand) :: "memory", "cc");
+        asm volatile(".Lretry: rdrand %%rax\r\n jnc .Lretry\r\n" : "=a"(rand)::"memory", "cc");
 
         if (total_bytes + sizeof(rand) <= size) {
-            *(unsigned long *) (buffer + total_bytes) = rand;
+            *(unsigned long*)(buffer + total_bytes) = rand;
             total_bytes += sizeof(rand);
         } else {
-            for (int i = 0 ; i < size - total_bytes ; i++)
-                *(unsigned char *) (buffer + total_bytes + i) = ((unsigned char *) &rand)[i];
+            for (int i = 0; i < size - total_bytes; i++)
+                *(unsigned char*)(buffer + total_bytes + i) = ((unsigned char*)&rand)[i];
             total_bytes = size;
         }
     } while (total_bytes < size);
     return 0;
 }
 #else
-size_t _DkRandomBitsRead (void * buffer, size_t size)
-{
+size_t _DkRandomBitsRead(void* buffer, size_t size) {
     if (!pal_sec.random_device) {
         int fd = INLINE_SYSCALL(open, 3, RANDGEN_DEVICE, O_RDONLY, 0);
         if (IS_ERR(fd))
@@ -145,8 +140,8 @@ size_t _DkRandomBitsRead (void * buffer, size_t size)
 
     size_t total_bytes = 0;
     do {
-        int bytes = INLINE_SYSCALL(read, 3, pal_sec.random_device,
-                                   buffer + total_bytes, size - total_bytes);
+        int bytes = INLINE_SYSCALL(read, 3, pal_sec.random_device, buffer + total_bytes,
+                                   size - total_bytes);
         if (IS_ERR(bytes))
             return -PAL_ERROR_DENIED;
 
@@ -163,8 +158,7 @@ size_t _DkRandomBitsRead (void * buffer, size_t size)
 #include <asm/prctl.h>
 #endif
 
-int _DkSegmentRegisterSet (int reg, const void * addr)
-{
+int _DkSegmentRegisterSet(int reg, const void* addr) {
     int ret = 0;
 
 #if defined(__i386__)
@@ -176,7 +170,7 @@ int _DkSegmentRegisterSet (int reg, const void * addr)
         return NULL;
 
     u_info->entry_number = -1;
-    u_info->base_addr = (unsigned int) addr;
+    u_info->base_addr    = (unsigned int)addr;
 
     ret = INLINE_SYSCALL(set_thread_area, 1, &u_info);
 #else
@@ -194,8 +188,7 @@ int _DkSegmentRegisterSet (int reg, const void * addr)
     return 0;
 }
 
-int _DkSegmentRegisterGet (int reg, void ** addr)
-{
+int _DkSegmentRegisterGet(int reg, void** addr) {
     int ret;
 
 #if defined(__i386__)
@@ -206,7 +199,7 @@ int _DkSegmentRegisterGet (int reg, void ** addr)
     if (IS_ERR(ret))
         return -PAL_ERROR_DENIED;
 
-    *addr = (void *) u_info->base_addr;
+    *addr = (void*)u_info->base_addr;
 #else
     unsigned long ret_addr;
 
@@ -222,22 +215,19 @@ int _DkSegmentRegisterGet (int reg, void ** addr)
     if (IS_ERR(ret))
         return -PAL_ERROR_DENIED;
 
-    *addr = (void *) ret_addr;
+    *addr = (void*)ret_addr;
 #endif
     return 0;
 }
 
-int _DkInstructionCacheFlush (const void * addr, int size)
-{
+int _DkInstructionCacheFlush(const void* addr, int size) {
     __UNUSED(addr);
     __UNUSED(size);
 
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkCpuIdRetrieve (unsigned int leaf, unsigned int subleaf,
-                      unsigned int values[4])
-{
+int _DkCpuIdRetrieve(unsigned int leaf, unsigned int subleaf, unsigned int values[4]) {
     cpuid(leaf, subleaf, values);
     return 0;
 }

+ 19 - 20
Pal/src/host/Linux/db_object.c

@@ -20,6 +20,11 @@
  * This file contains APIs for waiting on PAL handles (polling).
  */
 
+#include <asm/errno.h>
+#include <linux/poll.h>
+#include <linux/time.h>
+#include <linux/wait.h>
+
 #include "api.h"
 #include "pal.h"
 #include "pal_debug.h"
@@ -29,13 +34,8 @@
 #include "pal_linux.h"
 #include "pal_linux_defs.h"
 
-#include <asm/errno.h>
-#include <linux/poll.h>
-#include <linux/time.h>
-#include <linux/wait.h>
-
-/* Wait for an event on any handle in the handle array and return this handle in `polled`.
- * If no ready-event handle was found, `polled` is set to NULL. */
+/* Wait for an event on any handle in the handle array and return this handle in `polled`. If no
+ * ready-event handle was found, `polled` is set to NULL. */
 int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us,
                       PAL_HANDLE* polled) {
     int ret;
@@ -94,7 +94,7 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
                 fds[nfds].fd      = hdl->generic.fds[j];
                 fds[nfds].events  = events;
                 fds[nfds].revents = 0;
-                hdls[nfds]        = hdl;
+                hdls[nfds] = hdl;
                 nfds++;
             }
         }
@@ -109,9 +109,9 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
     struct timespec timeout_ts;
 
     if (timeout_us >= 0) {
-        int64_t sec = timeout_us / 1000000;
-        int64_t microsec = timeout_us - sec * 1000000;
-        timeout_ts.tv_sec = sec;
+        int64_t sec        = timeout_us / 1000000;
+        int64_t microsec   = timeout_us - sec * 1000000;
+        timeout_ts.tv_sec  = sec;
         timeout_ts.tv_nsec = microsec * 1000;
     }
 
@@ -161,7 +161,7 @@ int _DkObjectsWaitAny(size_t count, PAL_HANDLE* handle_array, int64_t timeout_us
             /* found internal FD of PAL handle that corresponds to the FD of event-ready fds[i] */
             if (fds[i].revents & POLLOUT)
                 HANDLE_HDR(polled_hdl)->flags |= WRITABLE(j);
-            if (fds[i].revents & (POLLHUP|POLLERR))
+            if (fds[i].revents & (POLLHUP | POLLERR))
                 HANDLE_HDR(polled_hdl)->flags |= ERROR(j);
         }
     }
@@ -172,12 +172,11 @@ out:
     return ret;
 }
 
-
 /* Improved version of _DkObjectsWaitAny(): wait for specific events on all handles in the handle
  * array and return multiple events (including errors) reported by the host. Returns 0 on success,
  * PAL error on failure. */
-int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events, PAL_FLG* ret_events,
-                         int64_t timeout_us) {
+int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events,
+                         PAL_FLG* ret_events, int64_t timeout_us) {
     int ret;
 
     if (count == 0)
@@ -221,7 +220,7 @@ int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events
                 fds[nfds].fd      = hdl->generic.fds[j];
                 fds[nfds].events  = fdevents;
                 fds[nfds].revents = 0;
-                offsets[nfds]     = i;
+                offsets[nfds] = i;
                 nfds++;
             }
         }
@@ -236,9 +235,9 @@ int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events
     struct timespec timeout_ts;
 
     if (timeout_us >= 0) {
-        int64_t sec = timeout_us / 1000000;
-        int64_t microsec = timeout_us - sec * 1000000;
-        timeout_ts.tv_sec = sec;
+        int64_t sec        = timeout_us / 1000000;
+        int64_t microsec   = timeout_us - sec * 1000000;
+        timeout_ts.tv_sec  = sec;
         timeout_ts.tv_nsec = microsec * 1000;
     }
 
@@ -272,7 +271,7 @@ int _DkObjectsWaitEvents(size_t count, PAL_HANDLE* handle_array, PAL_FLG* events
             ret_events[j] |= PAL_WAIT_READ;
         if (fds[i].revents & POLLOUT)
             ret_events[j] |= PAL_WAIT_WRITE;
-        if (fds[i].revents & (POLLHUP|POLLERR|POLLNVAL))
+        if (fds[i].revents & (POLLHUP | POLLERR | POLLNVAL))
             ret_events[j] |= PAL_WAIT_ERROR;
     }
 

+ 68 - 93
Pal/src/host/Skeleton/db_devices.c

@@ -17,22 +17,21 @@
 /*
  * db_device.c
  *
- * This file contains operands to handle streams with URIs that start with
- * "dev:".
+ * This file contains operands to handle streams with URIs that start with "dev:".
  */
 
-#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"
 
-#define DEVICE_OPS(handle)                              \
-    ({ int _type = (handle)->dev.dev_type;              \
-       (_type <= 0 || _type >= PAL_DEVICE_TYPE_BOUND) ? \
-       NULL : pal_device_ops[_type];                    \
-     })
+#define DEVICE_OPS(handle)                                                             \
+    ({                                                                                 \
+        int _type = (handle)->dev.dev_type;                                            \
+        (_type <= 0 || _type >= PAL_DEVICE_TYPE_BOUND) ? NULL : pal_device_ops[_type]; \
+    })
 
 enum {
     device_type_none = 0,
@@ -42,19 +41,20 @@ enum {
 
 static struct handle_ops term_ops;
 
-static const struct handle_ops * pal_device_ops [PAL_DEVICE_TYPE_BOUND] = {
-            NULL,
-            &term_ops,
-        };
+static const struct handle_ops* pal_device_ops[PAL_DEVICE_TYPE_BOUND] = {
+    NULL,
+    &term_ops,
+};
 
-/* parse_device_uri scans the uri, parses the prefix of the uri and searches
-   for stream handler wich will open or access the device. */
-static int parse_device_uri(const char ** uri, char ** type, struct handle_ops ** ops)
-{
-    struct handle_ops * dops = NULL;
-    const char * p, * u = (*uri);
+/* parse_device_uri scans the uri, parses the prefix of the uri and searches for stream handler
+ * which will open or access the device. */
+static int parse_device_uri(const char** uri, char** type, struct handle_ops** ops) {
+    struct handle_ops* dops = NULL;
+    const char* p;
+    const char* u = *uri;
 
-    for (p = u ; (*p) && (*p) != ',' && (*p) != '/' ; p++);
+    for (p = u; *p && *p != ',' && *p != '/'; p++)
+        ;
 
     if (strstartswith_static(u, "tty"))
         dops = &term_ops;
@@ -62,7 +62,7 @@ static int parse_device_uri(const char ** uri, char ** type, struct handle_ops *
     if (!dops)
         return -PAL_ERROR_NOTSUPPORT;
 
-    *uri = (*p) ? p + 1 : p;
+    *uri = *p ? p + 1 : p;
     if (type) {
         *type = malloc_copy(u, p - u + 1);
         if (!*type)
@@ -74,74 +74,59 @@ static int parse_device_uri(const char ** uri, char ** type, struct handle_ops *
     return 0;
 }
 
-static int64_t char_read (PAL_HANDLE handle, uint64_t offset, uint64_t count,
-                          void * buffer);
-static int64_t char_write (PAL_HANDLE handle, uint64_t offset, uint64_t count,
-                           const void * buffer);
-static int term_attrquery (const char * type, const char * uri,
-                           PAL_STREAM_ATTR * attr);
-static int term_attrquerybyhdl (PAL_HANDLE hdl,
-                                PAL_STREAM_ATTR * attr);
+static int64_t char_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buffer);
+static int64_t char_write(PAL_HANDLE handle, uint64_t offset, uint64_t count, const void* buffer);
+static int term_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* attr);
+static int term_attrquerybyhdl(PAL_HANDLE hdl, PAL_STREAM_ATTR* attr);
 
 /* 'open' operation for terminal stream */
-static int term_open (PAL_HANDLE *handle, const char * type, const char * uri,
-                      int access, int share, int create, int options)
-{
+static int term_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                     int create, int options) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int term_close (PAL_HANDLE handle)
-{
+static int term_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'attrquery' operation for terminal stream */
-static int term_attrquery (const char * type, const char * uri,
-                           PAL_STREAM_ATTR * attr)
-{
+static int term_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* attr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'attrquery' operation for terminal stream */
-static int term_attrquerybyhdl (PAL_HANDLE hdl,
-                                PAL_STREAM_ATTR * attr)
-{
+static int term_attrquerybyhdl(PAL_HANDLE hdl, PAL_STREAM_ATTR* attr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 static struct handle_ops term_ops = {
-        .open           = &term_open,
-        .close          = &term_close,
-        .read           = &char_read,
-        .write          = &char_write,
-        .attrquery      = &term_attrquery,
-        .attrquerybyhdl = &term_attrquerybyhdl,
-    };
+    .open           = &term_open,
+    .close          = &term_close,
+    .read           = &char_read,
+    .write          = &char_write,
+    .attrquery      = &term_attrquery,
+    .attrquerybyhdl = &term_attrquerybyhdl,
+};
 
 /* 'read' operation for character streams. */
-static int64_t char_read (PAL_HANDLE handle, uint64_t offset, uint64_t size, void * buffer)
-{
+static int64_t char_read(PAL_HANDLE handle, uint64_t offset, uint64_t size, void* buffer) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'write' operation for character streams. */
-static int64_t char_write (PAL_HANDLE handle, uint64_t offset, uint64_t size,
-                           const void * buffer)
-{
+static int64_t char_write(PAL_HANDLE handle, uint64_t offset, uint64_t size, const void* buffer) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'open' operation for device streams */
-static int dev_open (PAL_HANDLE * handle, const char * type, const char * uri,
-                     int access, int share, int create, int options)
-{
+static int dev_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                    int create, int options) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'read' operation for device stream */
-static int64_t dev_read (PAL_HANDLE handle, uint64_t offset, uint64_t size, void * buffer)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int64_t dev_read(PAL_HANDLE handle, uint64_t offset, uint64_t size, void* buffer) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (!ops || !ops->read)
         return -PAL_ERROR_NOTSUPPORT;
@@ -150,10 +135,8 @@ static int64_t dev_read (PAL_HANDLE handle, uint64_t offset, uint64_t size, void
 }
 
 /* 'write' operation for device stream */
-static int64_t dev_write (PAL_HANDLE handle, uint64_t offset, uint64_t size,
-                          const void * buffer)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int64_t dev_write(PAL_HANDLE handle, uint64_t offset, uint64_t size, const void* buffer) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (!ops || !ops->write)
         return -PAL_ERROR_NOTSUPPORT;
@@ -162,9 +145,8 @@ static int64_t dev_write (PAL_HANDLE handle, uint64_t offset, uint64_t size,
 }
 
 /* 'close' operation for device streams */
-static int dev_close (PAL_HANDLE handle)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int dev_close(PAL_HANDLE handle) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (ops && ops->close)
         return ops->close(handle);
@@ -173,9 +155,8 @@ static int dev_close (PAL_HANDLE handle)
 }
 
 /* 'delete' operation for device streams */
-static int dev_delete (PAL_HANDLE handle, int access)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int dev_delete(PAL_HANDLE handle, int access) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (!ops || !ops->delete)
         return -PAL_ERROR_DENIED;
@@ -189,9 +170,8 @@ static int dev_delete (PAL_HANDLE handle, int access)
 }
 
 /* 'flush' operation for device streams */
-static int dev_flush (PAL_HANDLE handle)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int dev_flush(PAL_HANDLE handle) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (ops && ops->flush)
         return ops->flush(handle);
@@ -200,11 +180,9 @@ static int dev_flush (PAL_HANDLE handle)
 }
 
 /* 'attrquery' operation for device streams */
-static int dev_attrquery (const char * type, const char * uri,
-                          PAL_STREAM_ATTR * attr)
-{
-    struct handle_ops * ops = NULL;
-    char * dev_type = NULL;
+static int dev_attrquery(const char* type, const char* uri, PAL_STREAM_ATTR* attr) {
+    struct handle_ops* ops = NULL;
+    char* dev_type = NULL;
     int ret = 0;
 
     ret = parse_device_uri(&uri, &dev_type, &ops);
@@ -221,10 +199,8 @@ static int dev_attrquery (const char * type, const char * uri,
 }
 
 /* 'attrquerybyhdl' operation for device stream */
-static int dev_attrquerybyhdl (PAL_HANDLE handle,
-                               PAL_STREAM_ATTR * attr)
-{
-    const struct handle_ops * ops = DEVICE_OPS(handle);
+static int dev_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) {
+    const struct handle_ops* ops = DEVICE_OPS(handle);
 
     if (ops && ops->attrquerybyhdl)
         return ops->attrquerybyhdl(handle, attr);
@@ -232,19 +208,18 @@ static int dev_attrquerybyhdl (PAL_HANDLE handle,
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static const char * dev_getrealpath (PAL_HANDLE handle)
-{
+static const char* dev_getrealpath(PAL_HANDLE handle) {
     return NULL;
 }
 
 struct handle_ops dev_ops = {
-        .getrealpath        = &dev_getrealpath,
-        .open               = &dev_open,
-        .read               = &dev_read,
-        .write              = &dev_write,
-        .close              = &dev_close,
-        .delete             = &dev_delete,
-        .flush              = &dev_flush,
-        .attrquery          = &dev_attrquery,
-        .attrquerybyhdl     = &dev_attrquerybyhdl,
-    };
+    .getrealpath    = &dev_getrealpath,
+    .open           = &dev_open,
+    .read           = &dev_read,
+    .write          = &dev_write,
+    .close          = &dev_close,
+    .delete         = &dev_delete,
+    .flush          = &dev_flush,
+    .attrquery      = &dev_attrquery,
+    .attrquerybyhdl = &dev_attrquerybyhdl,
+};

+ 13 - 14
Pal/src/host/Skeleton/db_eventfd.c

@@ -17,20 +17,19 @@
 /*
  * db_eventfd.c
  *
- * This file contains operations to handle streams with URIs that have
- * "eventfd:".
+ * This file contains operations to handle streams with URIs that have "eventfd:".
  */
 
-#include "pal_defs.h"
+#include "api.h"
 #include "pal.h"
-#include "pal_internal.h"
+#include "pal_defs.h"
 #include "pal_error.h"
-#include "api.h"
+#include "pal_internal.h"
 
-/* `type` must be eventfd, `uri` & `access` & `share` are unused,
- * `create` holds eventfd's initval, `options` holds eventfd's flags */
+/* `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) {
+                            int share, int create, int options) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
@@ -41,7 +40,7 @@ static int64_t eventfd_pal_read(PAL_HANDLE handle, uint64_t offset, uint64_t len
 
 /* offset does not apply here. */
 static int64_t eventfd_pal_write(PAL_HANDLE handle, uint64_t offset, uint64_t len,
-        const void* buffer) {
+                                 const void* buffer) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
@@ -55,9 +54,9 @@ static int eventfd_pal_close(PAL_HANDLE handle) {
 }
 
 struct handle_ops eventfd_ops = {
-    .open               = &eventfd_pal_open,
-    .read               = &eventfd_pal_read,
-    .write              = &eventfd_pal_write,
-    .close              = &eventfd_pal_close,
-    .attrquerybyhdl     = &eventfd_pal_attrquerybyhdl,
+    .open           = &eventfd_pal_open,
+    .read           = &eventfd_pal_read,
+    .write          = &eventfd_pal_write,
+    .close          = &eventfd_pal_close,
+    .attrquerybyhdl = &eventfd_pal_attrquerybyhdl,
 };

+ 14 - 22
Pal/src/host/Skeleton/db_events.c

@@ -20,53 +20,45 @@
  * This file contains implementation of Drawbridge event synchronization APIs.
  */
 
-#include "pal_defs.h"
+#include "api.h"
 #include "pal.h"
-#include "pal_internal.h"
+#include "pal_defs.h"
 #include "pal_error.h"
-#include "api.h"
+#include "pal_internal.h"
 
-int _DkEventCreate (PAL_HANDLE * event, bool initialState, bool isnotification)
-{
+int _DkEventCreate(PAL_HANDLE* event, bool initialState, bool isnotification) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-void _DkEventDestroy (PAL_HANDLE handle)
-{
+void _DkEventDestroy(PAL_HANDLE handle) {
     /* needs to be implemented */
 }
 
-int _DkEventSet (PAL_HANDLE event, int wakeup)
-{
+int _DkEventSet(PAL_HANDLE event, int wakeup) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkEventWaitTimeout (PAL_HANDLE event, int64_t timeout_us)
-{
+int _DkEventWaitTimeout(PAL_HANDLE event, int64_t timeout_us) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkEventWait (PAL_HANDLE event)
-{
+int _DkEventWait(PAL_HANDLE event) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkEventClear (PAL_HANDLE event)
-{
+int _DkEventClear(PAL_HANDLE event) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int event_close (PAL_HANDLE handle)
-{
+static int event_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int event_wait (PAL_HANDLE handle, int64_t timeout_us)
-{
+static int event_wait(PAL_HANDLE handle, int64_t timeout_us) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops event_ops = {
-        .close              = &event_close,
-        .wait               = &event_wait,
-    };
+    .close = &event_close,
+    .wait  = &event_wait,
+};

+ 59 - 90
Pal/src/host/Skeleton/db_files.c

@@ -17,176 +17,145 @@
 /*
  * db_files.c
  *
- * This file contains operands to handle streams with URIs that start with
- * "file:" or "dir:".
+ * This file contains operands to handle streams with URIs that start with "file:" or "dir:".
  */
 
-#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"
 
 /* 'open' operation for file streams */
-static int file_open (PAL_HANDLE * handle, const char * type, const char * uri,
-                      int access, int share, int create, int options)
-{
+static int file_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                     int create, int options) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-/* 'close' operation for file streams. In this case, it will only
-   close the file withou deleting it. */
-static int file_close (PAL_HANDLE handle)
-{
+/* 'close' operation for file streams. In this case, it will only close the file withou deleting it.
+ */
+static int file_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-/* '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)
-{
+/* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'map' operation for file stream. */
-static int file_map (PAL_HANDLE handle, void ** addr, int prot,
-                     uint64_t offset, uint64_t size)
-{
+static int file_map(PAL_HANDLE handle, void** addr, int prot, uint64_t offset, uint64_t size) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'flush' operation for file stream. */
-static int file_flush (PAL_HANDLE handle)
-{
+static int file_flush(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* '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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int file_getname (PAL_HANDLE handle, char * buffer, size_t count)
-{
+static int file_getname(PAL_HANDLE handle, char* buffer, size_t count) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-const char * file_getrealpath (PAL_HANDLE handle)
-{
+const char* file_getrealpath(PAL_HANDLE handle) {
     return NULL;
 }
 
 struct handle_ops 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,
-        .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,
+    .rename         = &file_rename,
+};
 
-/* 'open' operation for directory stream. Directory stream does not have a
-   specific type prefix, its URI looks the same file streams, plus it
-   ended with slashes. dir_open will be called by file_open. */
-static int dir_open (PAL_HANDLE * handle, const char * type, const char * uri,
-                     int access, int share, int create, int options)
-{
+/* 'open' operation for directory stream. Directory stream does not have a specific type prefix, its
+ * URI looks the same file streams, plus it ended with slashes. dir_open will be called by
+ * file_open. */
+static int dir_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                    int create, int options) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-/* 'read' operation for directory stream. Directory stream will not
-   need a 'write' operation. */
-int64_t dir_read (PAL_HANDLE handle, uint64_t offset, uint64_t count, void * buf)
-{
+/* 'read' operation for directory stream. Directory stream will not need a 'write' operation. */
+int64_t dir_read(PAL_HANDLE handle, uint64_t offset, uint64_t count, void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'close' operation of directory streams */
-static int dir_close (PAL_HANDLE handle)
-{
+static int dir_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'delete' operation of directoy streams */
-static int dir_delete (PAL_HANDLE handle, int access)
-{
+static int dir_delete(PAL_HANDLE handle, int access) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'attrquerybyhdl' operation of directory streams */
-static int dir_attrquerybyhdl (PAL_HANDLE handle,
-                               PAL_STREAM_ATTR * attr)
-{
+static int dir_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int dir_getname (PAL_HANDLE handle, char * buffer, size_t count)
-{
+static int dir_getname(PAL_HANDLE handle, char* buffer, size_t count) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static const char * dir_getrealpath (PAL_HANDLE handle)
-{
+static const char* dir_getrealpath(PAL_HANDLE handle) {
     return NULL;
 }
 
 struct handle_ops dir_ops = {
-        .getname            = &dir_getname,
-        .getrealpath        = &dir_getrealpath,
-        .open               = &dir_open,
-        .read               = &dir_read,
-        .close              = &dir_close,
-        .delete             = &dir_delete,
-        .attrquery          = &file_attrquery,
-        .attrquerybyhdl     = &dir_attrquerybyhdl,
-        .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 = &dir_attrquerybyhdl,
+    .rename         = &dir_rename,
+};

+ 11 - 20
Pal/src/host/Skeleton/db_misc.c

@@ -20,49 +20,40 @@
  * This file contains APIs for miscellaneous use.
  */
 
-#include "pal_defs.h"
+#include "api.h"
 #include "pal.h"
-#include "pal_internal.h"
+#include "pal_defs.h"
 #include "pal_error.h"
-#include "api.h"
+#include "pal_internal.h"
 
-int _DkInternalLock (PAL_LOCK * lock)
-{
+int _DkInternalLock(PAL_LOCK* lock) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkInternalUnlock (PAL_LOCK * lock)
-{
+int _DkInternalUnlock(PAL_LOCK* lock) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-unsigned long _DkSystemTimeQuery (void)
-{
+unsigned long _DkSystemTimeQuery(void) {
     return 0;
 }
 
-size_t _DkRandomBitsRead (void * buffer, size_t size)
-{
+size_t _DkRandomBitsRead(void* buffer, size_t size) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkSegmentRegisterSet (int reg, const void * addr)
-{
+int _DkSegmentRegisterSet(int reg, const void* addr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkSegmentRegisterGet (int reg, void ** addr)
-{
+int _DkSegmentRegisterGet(int reg, void** addr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkInstructionCacheFlush (const void * addr, int size)
-{
+int _DkInstructionCacheFlush(const void* addr, int size) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkCpuIdRetrieve (unsigned int leaf, unsigned int subleaf,
-                      unsigned int values[4])
-{
+int _DkCpuIdRetrieve(unsigned int leaf, unsigned int subleaf, unsigned int values[4]) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }

+ 9 - 17
Pal/src/host/Skeleton/db_mutex.c

@@ -24,42 +24,34 @@
 #include "pal_error.h"
 #include "pal_internal.h"
 
-int
-_DkMutexCreate (PAL_HANDLE * handle, int initialCount)
-{
+int _DkMutexCreate(PAL_HANDLE* handle, int initialCount) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkMutexLockTimeout (struct mutex_handle * m, int64_t timeout_us)
-{
+int _DkMutexLockTimeout(struct mutex_handle* m, int64_t timeout_us) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkMutexLock (struct mutex_handle * m)
-{
+int _DkMutexLock(struct mutex_handle* m) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkMutexAcquireTimeout (PAL_HANDLE handle, int64_t timeout_us)
-{
+int _DkMutexAcquireTimeout(PAL_HANDLE handle, int64_t timeout_us) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-int _DkMutexUnlock (struct mutex_handle * m)
-{
+int _DkMutexUnlock(struct mutex_handle* m) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-void _DkMutexRelease (PAL_HANDLE handle)
-{
+void _DkMutexRelease(PAL_HANDLE handle) {
     /* Not implemented yet */
 }
 
-static int mutex_wait (PAL_HANDLE handle, int64_t timeout_us)
-{
+static int mutex_wait(PAL_HANDLE handle, int64_t timeout_us) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops mutex_ops = {
-        .wait               = &mutex_wait,
-    };
+    .wait = &mutex_wait,
+};

+ 33 - 49
Pal/src/host/Skeleton/db_pipes.c

@@ -17,50 +17,41 @@
 /*
  * db_pipes.c
  *
- * This file contains oeprands to handle streams with URIs that start with
- * "pipe:" or "pipe.srv:".
+ * This file contains oeprands to handle streams with URIs that start with "pipe:" or "pipe.srv:".
  */
 
-#include "pal_defs.h"
+#include "api.h"
 #include "pal.h"
-#include "pal_internal.h"
-#include "pal_error.h"
 #include "pal_debug.h"
-#include "api.h"
+#include "pal_defs.h"
+#include "pal_error.h"
+#include "pal_internal.h"
 
-static int pipe_listen (PAL_HANDLE * handle, PAL_NUM pipeid, int create)
-{
+static int pipe_listen(PAL_HANDLE* handle, PAL_NUM pipeid, int create) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int pipe_waitforclient (PAL_HANDLE handle, PAL_HANDLE *client)
-{
+static int pipe_waitforclient(PAL_HANDLE handle, PAL_HANDLE* client) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int pipe_connect (PAL_HANDLE * handle, PAL_NUM pipeid, PAL_IDX connid,
-                         int create)
-{
+static int pipe_connect(PAL_HANDLE* handle, PAL_NUM pipeid, PAL_IDX connid, int create) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int pipe_private (PAL_HANDLE * handle)
-{
+static int pipe_private(PAL_HANDLE* handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-/* 'open' operation of pipe stream. For each pipe stream, it is
-   identified by a decimal number in URI. There could be two
-   types: pipe and pipe.srv. They behave pretty much the same,
-   except they are two ends of the pipe. */
-static int pipe_open (PAL_HANDLE *handle, const char * type,
-                      const char * uri, int access, int share,
-                      int create, int options)
-{
+/* 'open' operation of pipe stream. For each pipe stream, it is identified by a decimal number in
+   URI. There could be two types: pipe and pipe.srv. They behave pretty much the same, except they
+   are two ends of the pipe. */
+static int pipe_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                     int create, int options) {
     if (!strcmp_static(type, URI_TYPE_PIPE) && !*uri)
         return pipe_private(handle);
 
-    char * endptr;
+    char* endptr;
     PAL_NUM pipeid = strtol(uri, &endptr, 10);
     PAL_IDX connid = 0;
 
@@ -84,49 +75,42 @@ static int pipe_open (PAL_HANDLE *handle, const char * type,
 }
 
 /* 'read' operation of pipe stream. offset does not apply here. */
-static int64_t pipe_read (PAL_HANDLE handle, uint64_t offset, uint64_t len,
-                          void * buffer)
-{
+static int64_t pipe_read(PAL_HANDLE handle, uint64_t offset, uint64_t len, void* buffer) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'write' operation of pipe stream. offset does not apply here. */
-static int64_t pipe_write (PAL_HANDLE handle, uint64_t offset, uint64_t len,
-                           const void * buffer)
-{
+static int64_t pipe_write(PAL_HANDLE handle, uint64_t offset, uint64_t len, const void* buffer) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'close' operation of pipe stream. */
-static int pipe_close (PAL_HANDLE handle)
-{
+static int pipe_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'delete' operation of pipe stream. */
-static int pipe_delete (PAL_HANDLE handle, int access)
-{
+static int pipe_delete(PAL_HANDLE handle, int access) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int pipe_getname (PAL_HANDLE handle, char * buffer, size_t count)
-{
+static int pipe_getname(PAL_HANDLE handle, char* buffer, size_t count) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops pipe_ops = {
-        .getname            = &pipe_getname,
-        .open               = &pipe_open,
-        .waitforclient      = &pipe_waitforclient,
-        .read               = &pipe_read,
-        .write              = &pipe_write,
-        .close              = &pipe_close,
-        .delete             = &pipe_delete,
-    };
+    .getname       = &pipe_getname,
+    .open          = &pipe_open,
+    .waitforclient = &pipe_waitforclient,
+    .read          = &pipe_read,
+    .write         = &pipe_write,
+    .close         = &pipe_close,
+    .delete        = &pipe_delete,
+};
 
 struct handle_ops pipeprv_ops = {
-        .open               = &pipe_open,
-        .read               = &pipe_read,
-        .write              = &pipe_write,
-        .close              = &pipe_close,
-    };
+    .open  = &pipe_open,
+    .read  = &pipe_read,
+    .write = &pipe_write,
+    .close = &pipe_close,
+};

+ 17 - 25
Pal/src/host/Skeleton/db_process.c

@@ -17,52 +17,44 @@
 /*
  * db_process.c
  *
- * This source file contains functions to create a child process and terminate
- * the running process. Child does not inherit any objects or memory from its
- * parent pricess. A Parent process may not modify the execution of its
- * children. It can wait for a child to exit using its handle. Also, parent and
- * child may communicate through I/O streams provided by the parent to the child
- * at creation.
+ * This source file contains functions to create a child process and terminate the running process.
+ * Child does not inherit any objects or memory from its parent process. A parent process may not
+ * modify the execution of its children. It can wait for a child to exit using its handle. Also,
+ * parent and child may communicate through I/O streams provided by the parent to the child at
+ * creation.
  */
 
-#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"
 
-int _DkProcessCreate (PAL_HANDLE * handle, const char * uri, const char ** args)
-{
+int _DkProcessCreate(PAL_HANDLE* handle, const char* uri, const char** args) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-noreturn void _DkProcessExit (int exitcode)
-{
+noreturn void _DkProcessExit(int exitcode) {
     while (true) {
         /* nothing */;
     }
 }
 
-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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-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) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int proc_close (PAL_HANDLE handle)
-{
+static int proc_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops proc_ops = {
-        .read           = &proc_read,
-        .write          = &proc_write,
-        .close          = &proc_close,
-    };
+    .read  = &proc_read,
+    .write = &proc_write,
+    .close = &proc_close,
+};

+ 62 - 85
Pal/src/host/Skeleton/db_sockets.c

@@ -17,43 +17,38 @@
 /*
  * db_socket.c
  *
- * This file contains operands for streams with URIs that start with
- * "tcp:", "tcp.srv:", "udp:", "udp.srv:".
+ * This file contains operands for streams with URIs that start with "tcp:", "tcp.srv:", "udp:",
+ * "udp.srv:".
  */
 
-#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"
 
-/* 96 bytes is the minimal size of buffer to store a IPv4/IPv6
-   address */
-#define PAL_SOCKADDR_SIZE   96
+/* 96 bytes is the minimal size of buffer to store a IPv4/IPv6 address */
+#define PAL_SOCKADDR_SIZE 96
 
 /* listen on a tcp socket */
-static int tcp_listen (PAL_HANDLE * handle, char * uri, int create)
-{
+static int tcp_listen(PAL_HANDLE* handle, char* uri, int create) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* accept a tcp connection */
-static int tcp_accept (PAL_HANDLE handle, PAL_HANDLE *client)
-{
+static int tcp_accept(PAL_HANDLE handle, PAL_HANDLE* client) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* connect on a tcp socket */
-static int tcp_connect (PAL_HANDLE * handle, char * uri, int create)
-{
+static int tcp_connect(PAL_HANDLE* handle, char* uri, int create) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* 'open' operation of tcp stream */
-static int tcp_open (PAL_HANDLE *handle, const char * type, const char * uri,
-                     int access, int share, int create, int options)
-{
+static int tcp_open(PAL_HANDLE* handle, const char* type, const char* uri, int access, int share,
+                    int create, int options) {
     size_t uri_len = strlen(uri) + 1;
 
     if (uri_len > PAL_SOCKADDR_SIZE)
@@ -72,32 +67,27 @@ static int tcp_open (PAL_HANDLE *handle, const char * type, const char * uri,
 }
 
 /* 'read' operation of tcp stream */
-static int64_t tcp_read (PAL_HANDLE handle, uint64_t offset, size_t len, void * buf)
-{
+static int64_t tcp_read(PAL_HANDLE handle, uint64_t offset, size_t len, void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* write' operation of tcp stream */
-static int64_t tcp_write (PAL_HANDLE handle, uint64_t offset, size_t len, const void * buf)
-{
+static int64_t tcp_write(PAL_HANDLE handle, uint64_t offset, size_t len, const void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* used by 'open' operation of tcp stream for bound socket */
-static int udp_bind (PAL_HANDLE *handle, char * uri, int create)
-{
+static int udp_bind(PAL_HANDLE* handle, char* uri, int create) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 /* used by 'open' operation of tcp stream for connected socket */
-static int udp_connect (PAL_HANDLE * handle, char * uri)
-{
+static int udp_connect(PAL_HANDLE* handle, char* uri) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int udp_open (PAL_HANDLE *hdl, const char * type, const char * uri,
-                     int access, int share, int create, int options)
-{
+static int udp_open(PAL_HANDLE* hdl, const char* type, const char* uri, int access, int share,
+                    int create, int options) {
     char buf[PAL_SOCKADDR_SIZE];
     size_t len = strlen(uri);
 
@@ -115,102 +105,89 @@ static int udp_open (PAL_HANDLE *hdl, const char * type, const char * uri,
     return -PAL_ERROR_NOTSUPPORT;
 }
 
-static int64_t udp_receive (PAL_HANDLE handle, uint64_t offset, size_t len, void * buf)
-{
+static int64_t udp_receive(PAL_HANDLE handle, uint64_t offset, size_t len, void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int64_t udp_receivebyaddr (PAL_HANDLE handle, uint64_t offset, size_t len,
-                              void * buf, char * addr, size_t addrlen)
-{
+static int64_t udp_receivebyaddr(PAL_HANDLE handle, uint64_t offset, size_t len, void* buf,
+                                 char* addr, size_t addrlen) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int64_t udp_send (PAL_HANDLE handle, uint64_t offset, size_t len, const void * buf)
-{
+static int64_t udp_send(PAL_HANDLE handle, uint64_t offset, size_t len, const void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int64_t udp_sendbyaddr (PAL_HANDLE handle, uint64_t offset, size_t len,
-                               const void * buf, const char * addr, size_t addrlen)
-{
+static int64_t udp_sendbyaddr(PAL_HANDLE handle, uint64_t offset, size_t len, const void* buf,
+                              const char* addr, size_t addrlen) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int socket_delete (PAL_HANDLE handle, int access)
-{
+static int socket_delete(PAL_HANDLE handle, int access) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int socket_close (PAL_HANDLE handle)
-{
+static int socket_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int socket_attrquerybyhdl (PAL_HANDLE handle, PAL_STREAM_ATTR  * attr)
-{
+static int socket_attrquerybyhdl(PAL_HANDLE handle, PAL_STREAM_ATTR* attr) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int socket_getname (PAL_HANDLE handle, char * buffer, size_t count)
-{
+static int socket_getname(PAL_HANDLE handle, char* buffer, size_t count) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops tcp_ops = {
-        .getname        = &socket_getname,
-        .open           = &tcp_open,
-        .waitforclient  = &tcp_accept,
-        .read           = &tcp_read,
-        .write          = &tcp_write,
-        .delete         = &socket_delete,
-        .close          = &socket_close,
-        .attrquerybyhdl = &socket_attrquerybyhdl,
-    };
+    .getname        = &socket_getname,
+    .open           = &tcp_open,
+    .waitforclient  = &tcp_accept,
+    .read           = &tcp_read,
+    .write          = &tcp_write,
+    .delete         = &socket_delete,
+    .close          = &socket_close,
+    .attrquerybyhdl = &socket_attrquerybyhdl,
+};
 
 struct handle_ops udp_ops = {
-        .getname        = &socket_getname,
-        .open           = &udp_open,
-        .read           = &udp_receive,
-        .write          = &udp_send,
-        .delete         = &socket_delete,
-        .close          = &socket_close,
-        .attrquerybyhdl = &socket_attrquerybyhdl,
-    };
+    .getname        = &socket_getname,
+    .open           = &udp_open,
+    .read           = &udp_receive,
+    .write          = &udp_send,
+    .delete         = &socket_delete,
+    .close          = &socket_close,
+    .attrquerybyhdl = &socket_attrquerybyhdl,
+};
 
 struct handle_ops udpsrv_ops = {
-        .getname        = &socket_getname,
-        .open           = &udp_open,
-        .readbyaddr     = &udp_receivebyaddr,
-        .writebyaddr    = &udp_sendbyaddr,
-        .delete         = &socket_delete,
-        .close          = &socket_close,
-        .attrquerybyhdl = &socket_attrquerybyhdl,
-    };
-
-PAL_HANDLE _DkBroadcastStreamOpen (void)
-{
+    .getname        = &socket_getname,
+    .open           = &udp_open,
+    .readbyaddr     = &udp_receivebyaddr,
+    .writebyaddr    = &udp_sendbyaddr,
+    .delete         = &socket_delete,
+    .close          = &socket_close,
+    .attrquerybyhdl = &socket_attrquerybyhdl,
+};
+
+PAL_HANDLE _DkBroadcastStreamOpen(void) {
     return NULL;
 }
 
-static int64_t mcast_send (PAL_HANDLE handle, uint64_t offset, uint64_t size,
-                           const void * buf)
-{
+static int64_t mcast_send(PAL_HANDLE handle, uint64_t offset, uint64_t size, const void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int64_t mcast_receive (PAL_HANDLE handle, uint64_t offset, uint64_t size, void * buf)
-{
+static int64_t mcast_receive(PAL_HANDLE handle, uint64_t offset, uint64_t size, void* buf) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
-static int mcast_close (PAL_HANDLE handle)
-{
+static int mcast_close(PAL_HANDLE handle) {
     return -PAL_ERROR_NOTIMPLEMENTED;
 }
 
 struct handle_ops mcast_ops = {
-        .write          = &mcast_send,
-        .read           = &mcast_receive,
-        .close          = &mcast_close,
-    };
+    .write = &mcast_send,
+    .read  = &mcast_receive,
+    .close = &mcast_close,
+};

+ 8 - 11
Pal/src/host/Skeleton/pal_host.h

@@ -24,22 +24,20 @@
 #define PAL_HOST_H
 
 #ifndef IN_PAL
-# error "cannot be included outside PAL"
+#error "cannot be included outside PAL"
 #endif
 
 typedef struct mutex_handle {
     int unused;
 } PAL_LOCK;
 
-#define LOCK_INIT   {}
+#define LOCK_INIT {}
 #define INIT_LOCK(lock) do {} while (0)
 
-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
-     * handles, so we hide the type name of these handles on purpose.
+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 handles, so we
+     * hide the type name of these handles on purpose.
      */
     PAL_HDR hdr;
 
@@ -48,9 +46,8 @@ typedef struct pal_handle
             PAL_IDX fds[MAX_FDS];
         } generic;
 
-        /* DP: Here we just define a placeholder fd; place your details here.
-         * Not every type requires an fd either - this is up to your
-         * host-specific code.
+        /* DP: Here we just define a placeholder fd; place your details here. Not every type
+         * requires an fd either - this is up to your host-specific code.
          */
         struct {
             PAL_IDX fd;

+ 43 - 43
Pal/src/pal_error.c

@@ -17,54 +17,54 @@
 #include "pal_error.h"
 
 struct pal_error_description {
-    int         error;
+    int error;
     const char* description;
 };
 
 static const struct pal_error_description pal_error_list[] = {
-    { PAL_ERROR_SUCCESS, "Success" },
-    { PAL_ERROR_NOTIMPLEMENTED, "Function not implemented" },
-    { PAL_ERROR_NOTDEFINED, "Symbol not defined" },
-    { PAL_ERROR_NOTSUPPORT, "Function not supported" },
-    { PAL_ERROR_INVAL, "Invalid argument" },
-    { PAL_ERROR_TOOLONG, "Name/path is too long" },
-    { PAL_ERROR_DENIED, "Operation denied" },
-    { PAL_ERROR_BADHANDLE, "Handle corrupted" },
-    { PAL_ERROR_STREAMEXIST, "Stream already exists" },
-    { PAL_ERROR_STREAMNOTEXIST, "Stream does not exist" },
-    { PAL_ERROR_STREAMISFILE, "Stream is a file" },
-    { PAL_ERROR_STREAMISDIR, "Stream is a directory" },
-    { PAL_ERROR_STREAMISDEVICE, "Stream is a device" },
-    { PAL_ERROR_INTERRUPTED, "Operation interrupted" },
-    { PAL_ERROR_OVERFLOW, "Buffer overflowed" },
-    { PAL_ERROR_BADADDR, "Invalid address" },
-    { PAL_ERROR_NOMEM, "Not enough memory" },
-    { PAL_ERROR_NOTKILLABLE, "Thread state unkillable" },
-    { PAL_ERROR_INCONSIST, "Inconsistent system state" },
-    { PAL_ERROR_TRYAGAIN, "Try again" },
-    { PAL_ERROR_ENDOFSTREAM, "End of stream" },
-    { PAL_ERROR_NOTSERVER, "Not a server" },
-    { PAL_ERROR_NOTCONNECTION, "Not a connection" },
-    { PAL_ERROR_CONNFAILED, "Connection failed" },
-    { PAL_ERROR_ADDRNOTEXIST, "Resource address does not exist" },
-    { PAL_ERROR_AFNOSUPPORT, "Address family not supported by protocol" },
+    {PAL_ERROR_SUCCESS, "Success"},
+    {PAL_ERROR_NOTIMPLEMENTED, "Function not implemented"},
+    {PAL_ERROR_NOTDEFINED, "Symbol not defined"},
+    {PAL_ERROR_NOTSUPPORT, "Function not supported"},
+    {PAL_ERROR_INVAL, "Invalid argument"},
+    {PAL_ERROR_TOOLONG, "Name/path is too long"},
+    {PAL_ERROR_DENIED, "Operation denied"},
+    {PAL_ERROR_BADHANDLE, "Handle corrupted"},
+    {PAL_ERROR_STREAMEXIST, "Stream already exists"},
+    {PAL_ERROR_STREAMNOTEXIST, "Stream does not exist"},
+    {PAL_ERROR_STREAMISFILE, "Stream is a file"},
+    {PAL_ERROR_STREAMISDIR, "Stream is a directory"},
+    {PAL_ERROR_STREAMISDEVICE, "Stream is a device"},
+    {PAL_ERROR_INTERRUPTED, "Operation interrupted"},
+    {PAL_ERROR_OVERFLOW, "Buffer overflowed"},
+    {PAL_ERROR_BADADDR, "Invalid address"},
+    {PAL_ERROR_NOMEM, "Not enough memory"},
+    {PAL_ERROR_NOTKILLABLE, "Thread state unkillable"},
+    {PAL_ERROR_INCONSIST, "Inconsistent system state"},
+    {PAL_ERROR_TRYAGAIN, "Try again"},
+    {PAL_ERROR_ENDOFSTREAM, "End of stream"},
+    {PAL_ERROR_NOTSERVER, "Not a server"},
+    {PAL_ERROR_NOTCONNECTION, "Not a connection"},
+    {PAL_ERROR_CONNFAILED, "Connection failed"},
+    {PAL_ERROR_ADDRNOTEXIST, "Resource address does not exist"},
+    {PAL_ERROR_AFNOSUPPORT, "Address family not supported by protocol"},
 
-    { PAL_ERROR_CRYPTO_FEATURE_UNAVAILABLE, "[Crypto] Feature not available" },
-    { PAL_ERROR_CRYPTO_INVALID_CONTEXT, "[Crypto] Invalid context" },
-    { PAL_ERROR_CRYPTO_INVALID_KEY_LENGTH, "[Crypto] Invalid key length" },
-    { PAL_ERROR_CRYPTO_INVALID_INPUT_LENGTH, "[Crypto] Invalid input length" },
-    { PAL_ERROR_CRYPTO_INVALID_OUTPUT_LENGTH, "[Crypto] Invalid output length" },
-    { PAL_ERROR_CRYPTO_BAD_INPUT_DATA, "[Crypto] Bad input parameters" },
-    { PAL_ERROR_CRYPTO_INVALID_PADDING, "[Crypto] Invalid padding" },
-    { PAL_ERROR_CRYPTO_DATA_MISALIGNED, "[Crypto] Data misaligned" },
-    { PAL_ERROR_CRYPTO_INVALID_FORMAT, "[Crypto] Invalid data format" },
-    { PAL_ERROR_CRYPTO_AUTH_FAILED, "[Crypto] Authentication failed" },
-    { PAL_ERROR_CRYPTO_IO_ERROR, "[Crypto] I/O error" },
-    { PAL_ERROR_CRYPTO_KEY_GEN_FAILED, "[Crypto] Key generation failed" },
-    { PAL_ERROR_CRYPTO_INVALID_KEY, "[Crypto] Invalid key" },
-    { PAL_ERROR_CRYPTO_VERIFY_FAILED, "[Crypto] Verification failed" },
-    { PAL_ERROR_CRYPTO_RNG_FAILED, "[Crypto] RNG failed to generate data" },
-    { PAL_ERROR_CRYPTO_INVALID_DH_STATE, "[Crypto] Invalid DH state" },
+    {PAL_ERROR_CRYPTO_FEATURE_UNAVAILABLE, "[Crypto] Feature not available"},
+    {PAL_ERROR_CRYPTO_INVALID_CONTEXT, "[Crypto] Invalid context"},
+    {PAL_ERROR_CRYPTO_INVALID_KEY_LENGTH, "[Crypto] Invalid key length"},
+    {PAL_ERROR_CRYPTO_INVALID_INPUT_LENGTH, "[Crypto] Invalid input length"},
+    {PAL_ERROR_CRYPTO_INVALID_OUTPUT_LENGTH, "[Crypto] Invalid output length"},
+    {PAL_ERROR_CRYPTO_BAD_INPUT_DATA, "[Crypto] Bad input parameters"},
+    {PAL_ERROR_CRYPTO_INVALID_PADDING, "[Crypto] Invalid padding"},
+    {PAL_ERROR_CRYPTO_DATA_MISALIGNED, "[Crypto] Data misaligned"},
+    {PAL_ERROR_CRYPTO_INVALID_FORMAT, "[Crypto] Invalid data format"},
+    {PAL_ERROR_CRYPTO_AUTH_FAILED, "[Crypto] Authentication failed"},
+    {PAL_ERROR_CRYPTO_IO_ERROR, "[Crypto] I/O error"},
+    {PAL_ERROR_CRYPTO_KEY_GEN_FAILED, "[Crypto] Key generation failed"},
+    {PAL_ERROR_CRYPTO_INVALID_KEY, "[Crypto] Invalid key"},
+    {PAL_ERROR_CRYPTO_VERIFY_FAILED, "[Crypto] Verification failed"},
+    {PAL_ERROR_CRYPTO_RNG_FAILED, "[Crypto] RNG failed to generate data"},
+    {PAL_ERROR_CRYPTO_INVALID_DH_STATE, "[Crypto] Invalid DH state"},
 };
 
 #define PAL_ERROR_COUNT (sizeof(pal_error_list) / sizeof(pal_error_list[0]))