repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/c-platform/SKILL.md

Raw

name: c-platform description: Platform abstraction — context cracking, OS abstraction layer, compiler intrinsics, opaque handles. Use when: writing cross-platform C, abstracting OS differences, compiler-specific code. license: MIT

Platform Abstraction

Writing portable C requires abstracting OS, compiler, and architecture differences. The key is detecting the platform at compile time and providing a unified interface.


Context Cracking

Compile-time detection of compiler, OS, and architecture.

Detection Macros

// Compiler detection
#if defined(__clang__)
  #define COMPILER_CLANG  1
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    0
#elif defined(_MSC_VER)
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   1
  #define COMPILER_GCC    0
#elif defined(__GNUC__)
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    1
#else
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    0
#endif

// OS detection
#if defined(_WIN32)
  #define OS_WINDOWS 1
  #define OS_LINUX   0
  #define OS_MAC     0
#elif defined(__gnu_linux__) || defined(__linux__)
  #define OS_WINDOWS 0
  #define OS_LINUX   1
  #define OS_MAC     0
#elif defined(__APPLE__) && defined(__MACH__)
  #define OS_WINDOWS 0
  #define OS_LINUX   0
  #define OS_MAC     1
#else
  #define OS_WINDOWS 0
  #define OS_LINUX   0
  #define OS_MAC     0
#endif

// Architecture detection
#if defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)
  #define ARCH_X64  1
  #define ARCH_X86  0
  #define ARCH_ARM64 0
#elif defined(__i386__) || defined(_M_IX86)
  #define ARCH_X64  0
  #define ARCH_X86  1
  #define ARCH_ARM64 0
#elif defined(__aarch64__) || defined(_M_ARM64)
  #define ARCH_X64  0
  #define ARCH_X86  0
  #define ARCH_ARM64 1
#else
  #define ARCH_X64  0
  #define ARCH_X86  0
  #define ARCH_ARM64 0
#endif

Usage

#if OS_WINDOWS
  #include <windows.h>
#elif OS_LINUX
  #include <unistd.h>
  #include <sys/mman.h>
#endif

void *allocate_memory(U64 size)
{
    void *result = 0;
#if OS_WINDOWS
    result = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
#elif OS_LINUX
    result = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif
    return result;
}

Compiler Intrinsics

Trap / Debug Break

#if COMPILER_MSVC
  #define Trap() __debugbreak()
#elif COMPILER_CLANG || COMPILER_GCC
  #if ARCH_X86 || ARCH_X64
    #define Trap() __asm__ __volatile__("int3;")
  #else
    #define Trap() __builtin_trap()
  #endif
#endif

Inline Control

#if COMPILER_MSVC
  #define force_inline __forceinline
  #define no_inline    __declspec(noinline)
#elif COMPILER_CLANG || COMPILER_GCC
  #define force_inline __attribute__((always_inline)) static inline
  #define no_inline    __attribute__((noinline))
#endif

Branch Prediction

#if COMPILER_CLANG || COMPILER_GCC
  #define Expect(expr, val) __builtin_expect((expr), (val))
#else
  #define Expect(expr, val) (expr)
#endif

#define Likely(expr)   Expect(expr, 1)
#define Unlikely(expr) Expect(expr, 0)

// Usage
if (Unlikely(ptr == NULL)) {
    handle_error();
}

Atomics

#if COMPILER_MSVC
  #define ins_atomic_u32_eval(x)              (*(volatile U32 *)(x))
  #define ins_atomic_u32_inc(x)               InterlockedIncrement((LONG *)(x))
  #define ins_atomic_u32_eval_assign(x, val)  InterlockedExchange((LONG *)(x), (val))
  // InterlockedCompareExchange64(Destination, Exchange, Comparand)
  #define ins_atomic_u64_cas(x, cmp, val)     InterlockedCompareExchange64((__int64 *)(x), (val), (cmp))
#elif COMPILER_CLANG || COMPILER_GCC
  #define ins_atomic_u32_eval(x)              __atomic_load_n((U32 *)(x), __ATOMIC_SEQ_CST)
  #define ins_atomic_u32_inc(x)               __atomic_fetch_add((U32 *)(x), 1, __ATOMIC_SEQ_CST)
  #define ins_atomic_u32_eval_assign(x, val)  __atomic_exchange_n((U32 *)(x), (val), __ATOMIC_SEQ_CST)
  #define ins_atomic_u64_cas(x, cmp, val)     __sync_val_compare_and_swap((U64 *)(x), (cmp), (val))
#endif

Thread-Local Storage

#if COMPILER_MSVC
  #define thread_static __declspec(thread)
#elif COMPILER_CLANG || COMPILER_GCC
  #define thread_static __thread
#endif

thread_static U64 thread_local_counter = 0;

Read-Only Data Section

#if COMPILER_MSVC
  #define read_only __declspec(allocate(".rdata$"))
#elif COMPILER_CLANG || COMPILER_GCC
  #define read_only __attribute__((section(".rodata")))
#endif

global read_only U8 hex_table[16] = "0123456789ABCDEF";

OS Abstraction Layer

Interface Header (os_core.h)

// Platform-independent interface

typedef struct OS_SystemInfo OS_SystemInfo;
struct OS_SystemInfo
{
    U64 page_size;
    U64 large_page_size;
    U64 core_count;
    U64 memory_size;
};

internal OS_SystemInfo *os_get_system_info(void);
internal void *os_reserve(U64 size);
internal B32   os_commit(void *ptr, U64 size);
internal void  os_decommit(void *ptr, U64 size);
internal void  os_release(void *ptr, U64 size);
internal void  os_sleep(U64 milliseconds);
internal void  os_abort(S32 code);

Platform Implementations

os/
├── os_core.h          // Interface
├── os_inc.h           // Master include
├── win32/
│   └── os_win32.c     // Windows implementation
└── linux/
    └── os_linux.c     // Linux implementation

Windows Implementation

// os/win32/os_win32.c

internal void *
os_reserve(U64 size)
{
    void *result = VirtualAlloc(0, size, MEM_RESERVE, PAGE_READWRITE);
    return result;
}

internal B32
os_commit(void *ptr, U64 size)
{
    void *result = VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE);
    return result != 0;
}

internal void
os_decommit(void *ptr, U64 size)
{
    VirtualFree(ptr, size, MEM_DECOMMIT);
}

internal void
os_release(void *ptr, U64 size)
{
    (void)size;
    VirtualFree(ptr, 0, MEM_RELEASE);
}

Linux Implementation

// os/linux/os_linux.c

internal void *
os_reserve(U64 size)
{
    void *result = mmap(0, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (result == MAP_FAILED) {
        result = 0;
    }
    return result;
}

internal B32
os_commit(void *ptr, U64 size)
{
    B32 result = mprotect(ptr, size, PROT_READ | PROT_WRITE) == 0;
    return result;
}

internal void
os_decommit(void *ptr, U64 size)
{
    mprotect(ptr, size, PROT_NONE);
    madvise(ptr, size, MADV_DONTNEED);
}

internal void
os_release(void *ptr, U64 size)
{
    munmap(ptr, size);
}

Opaque Handles

Wrap native handles in a portable type.

typedef struct OS_Handle OS_Handle;
struct OS_Handle
{
    U64 u64[1];  // Wraps native handle (HANDLE on Windows, int on Linux)
};

internal OS_Handle
os_handle_zero(void)
{
    OS_Handle h = { 0 };
    return h;
}

internal B32
os_handle_match(OS_Handle a, OS_Handle b)
{
    return a.u64[0] == b.u64[0];
}

// Usage
#if OS_WINDOWS
  #define os_handle_from_native(h) ((OS_Handle){ .u64 = { (U64)(h) } })
  #define os_handle_to_native(h)   ((HANDLE)(h).u64[0])
#elif OS_LINUX
  #define os_handle_from_native(h) ((OS_Handle){ .u64 = { (U64)(h) } })
  #define os_handle_to_native(h)   ((int)(h).u64[0])
#endif

File Iteration

Hide OS-specific directory iteration:

typedef struct OS_FileIter OS_FileIter;
struct OS_FileIter
{
    U8 opaque[1024];  // OS-specific data hidden
};

typedef struct OS_FileInfo OS_FileInfo;
struct OS_FileInfo
{
    String8 name;
    U64 size;
    U64 created_time;
    U64 modified_time;
    B32 is_folder;
};

internal OS_FileIter *os_file_iter_begin(Arena *arena, String8 path);
internal B32          os_file_iter_next(Arena *arena, OS_FileIter *iter, OS_FileInfo *info);
internal void         os_file_iter_end(OS_FileIter *iter);

Threading Primitives

typedef struct Mutex    Mutex;
typedef struct RWMutex  RWMutex;
typedef struct CondVar  CondVar;
typedef struct Semaphore Semaphore;

internal Mutex    os_mutex_alloc(void);
internal void     os_mutex_release(Mutex mutex);
internal void     os_mutex_take(Mutex mutex);
internal void     os_mutex_drop(Mutex mutex);

internal Semaphore os_semaphore_alloc(U32 initial_count);
internal void      os_semaphore_release(Semaphore semaphore);
internal B32       os_semaphore_take(Semaphore semaphore, U64 endt_us);

// Scoped locking
#define MutexScope(mutex) DeferLoop(os_mutex_take(mutex), os_mutex_drop(mutex))

Endianness

#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  #define ARCH_LITTLE_ENDIAN 1
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  #define ARCH_LITTLE_ENDIAN 0
#else
  // Runtime detection or assume
  #define ARCH_LITTLE_ENDIAN 1
#endif

// Byte swapping
internal U16 bswap_u16(U16 x) { return (U16)((x >> 8) | (U16)(x << 8)); }
internal U32 bswap_u32(U32 x) { return __builtin_bswap32(x); }
internal U64 bswap_u64(U64 x) { return __builtin_bswap64(x); }

// Convert from/to big-endian
#if ARCH_LITTLE_ENDIAN
  #define from_be_u16(x) bswap_u16(x)
  #define from_be_u32(x) bswap_u32(x)
  #define from_be_u64(x) bswap_u64(x)
  #define to_be_u16(x)   bswap_u16(x)
#else
  #define from_be_u16(x) (x)
  #define to_be_u16(x)   (x)
#endif

Quick Reference

// Platform detection
#if OS_WINDOWS
  // Windows code
#elif OS_LINUX
  // Linux code
#endif

// Compiler intrinsics
force_inline int add(int a, int b) { return a + b; }
if (Unlikely(error)) { ... }

// OS abstraction
void *mem = os_reserve(MB(64));
os_commit(mem, KB(4));

// Opaque handle
OS_Handle file = os_file_open(path, OS_FileOpenMode_Read);
if (!os_handle_match(file, os_handle_zero())) { ... }
Markdown source
File outline
---
name: c-platform
description: Platform abstraction — context cracking, OS abstraction layer, compiler intrinsics, opaque handles. Use when: writing cross-platform C, abstracting OS differences, compiler-specific code.
  license: MIT
---

# Platform Abstraction

Writing portable C requires abstracting OS, compiler, and architecture
differences. The key is detecting the platform at compile time and providing a
unified interface.

---

## Context Cracking

Compile-time detection of compiler, OS, and architecture.

### Detection Macros

```c
// Compiler detection
#if defined(__clang__)
  #define COMPILER_CLANG  1
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    0
#elif defined(_MSC_VER)
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   1
  #define COMPILER_GCC    0
#elif defined(__GNUC__)
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    1
#else
  #define COMPILER_CLANG  0
  #define COMPILER_MSVC   0
  #define COMPILER_GCC    0
#endif

// OS detection
#if defined(_WIN32)
  #define OS_WINDOWS 1
  #define OS_LINUX   0
  #define OS_MAC     0
#elif defined(__gnu_linux__) || defined(__linux__)
  #define OS_WINDOWS 0
  #define OS_LINUX   1
  #define OS_MAC     0
#elif defined(__APPLE__) && defined(__MACH__)
  #define OS_WINDOWS 0
  #define OS_LINUX   0
  #define OS_MAC     1
#else
  #define OS_WINDOWS 0
  #define OS_LINUX   0
  #define OS_MAC     0
#endif

// Architecture detection
#if defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64)
  #define ARCH_X64  1
  #define ARCH_X86  0
  #define ARCH_ARM64 0
#elif defined(__i386__) || defined(_M_IX86)
  #define ARCH_X64  0
  #define ARCH_X86  1
  #define ARCH_ARM64 0
#elif defined(__aarch64__) || defined(_M_ARM64)
  #define ARCH_X64  0
  #define ARCH_X86  0
  #define ARCH_ARM64 1
#else
  #define ARCH_X64  0
  #define ARCH_X86  0
  #define ARCH_ARM64 0
#endif
```

### Usage

```c
#if OS_WINDOWS
  #include <windows.h>
#elif OS_LINUX
  #include <unistd.h>
  #include <sys/mman.h>
#endif

void *allocate_memory(U64 size)
{
    void *result = 0;
#if OS_WINDOWS
    result = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
#elif OS_LINUX
    result = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
#endif
    return result;
}
```

---

## Compiler Intrinsics

### Trap / Debug Break

```c
#if COMPILER_MSVC
  #define Trap() __debugbreak()
#elif COMPILER_CLANG || COMPILER_GCC
  #if ARCH_X86 || ARCH_X64
    #define Trap() __asm__ __volatile__("int3;")
  #else
    #define Trap() __builtin_trap()
  #endif
#endif
```

### Inline Control

```c
#if COMPILER_MSVC
  #define force_inline __forceinline
  #define no_inline    __declspec(noinline)
#elif COMPILER_CLANG || COMPILER_GCC
  #define force_inline __attribute__((always_inline)) static inline
  #define no_inline    __attribute__((noinline))
#endif
```

### Branch Prediction

```c
#if COMPILER_CLANG || COMPILER_GCC
  #define Expect(expr, val) __builtin_expect((expr), (val))
#else
  #define Expect(expr, val) (expr)
#endif

#define Likely(expr)   Expect(expr, 1)
#define Unlikely(expr) Expect(expr, 0)

// Usage
if (Unlikely(ptr == NULL)) {
    handle_error();
}
```

### Atomics

```c
#if COMPILER_MSVC
  #define ins_atomic_u32_eval(x)              (*(volatile U32 *)(x))
  #define ins_atomic_u32_inc(x)               InterlockedIncrement((LONG *)(x))
  #define ins_atomic_u32_eval_assign(x, val)  InterlockedExchange((LONG *)(x), (val))
  // InterlockedCompareExchange64(Destination, Exchange, Comparand)
  #define ins_atomic_u64_cas(x, cmp, val)     InterlockedCompareExchange64((__int64 *)(x), (val), (cmp))
#elif COMPILER_CLANG || COMPILER_GCC
  #define ins_atomic_u32_eval(x)              __atomic_load_n((U32 *)(x), __ATOMIC_SEQ_CST)
  #define ins_atomic_u32_inc(x)               __atomic_fetch_add((U32 *)(x), 1, __ATOMIC_SEQ_CST)
  #define ins_atomic_u32_eval_assign(x, val)  __atomic_exchange_n((U32 *)(x), (val), __ATOMIC_SEQ_CST)
  #define ins_atomic_u64_cas(x, cmp, val)     __sync_val_compare_and_swap((U64 *)(x), (cmp), (val))
#endif
```

### Thread-Local Storage

```c
#if COMPILER_MSVC
  #define thread_static __declspec(thread)
#elif COMPILER_CLANG || COMPILER_GCC
  #define thread_static __thread
#endif

thread_static U64 thread_local_counter = 0;
```

### Read-Only Data Section

```c
#if COMPILER_MSVC
  #define read_only __declspec(allocate(".rdata$"))
#elif COMPILER_CLANG || COMPILER_GCC
  #define read_only __attribute__((section(".rodata")))
#endif

global read_only U8 hex_table[16] = "0123456789ABCDEF";
```

---

## OS Abstraction Layer

### Interface Header (os_core.h)

```c
// Platform-independent interface

typedef struct OS_SystemInfo OS_SystemInfo;
struct OS_SystemInfo
{
    U64 page_size;
    U64 large_page_size;
    U64 core_count;
    U64 memory_size;
};

internal OS_SystemInfo *os_get_system_info(void);
internal void *os_reserve(U64 size);
internal B32   os_commit(void *ptr, U64 size);
internal void  os_decommit(void *ptr, U64 size);
internal void  os_release(void *ptr, U64 size);
internal void  os_sleep(U64 milliseconds);
internal void  os_abort(S32 code);
```

### Platform Implementations

```
os/
├── os_core.h          // Interface
├── os_inc.h           // Master include
├── win32/
│   └── os_win32.c     // Windows implementation
└── linux/
    └── os_linux.c     // Linux implementation
```

### Windows Implementation

```c
// os/win32/os_win32.c

internal void *
os_reserve(U64 size)
{
    void *result = VirtualAlloc(0, size, MEM_RESERVE, PAGE_READWRITE);
    return result;
}

internal B32
os_commit(void *ptr, U64 size)
{
    void *result = VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE);
    return result != 0;
}

internal void
os_decommit(void *ptr, U64 size)
{
    VirtualFree(ptr, size, MEM_DECOMMIT);
}

internal void
os_release(void *ptr, U64 size)
{
    (void)size;
    VirtualFree(ptr, 0, MEM_RELEASE);
}
```

### Linux Implementation

```c
// os/linux/os_linux.c

internal void *
os_reserve(U64 size)
{
    void *result = mmap(0, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (result == MAP_FAILED) {
        result = 0;
    }
    return result;
}

internal B32
os_commit(void *ptr, U64 size)
{
    B32 result = mprotect(ptr, size, PROT_READ | PROT_WRITE) == 0;
    return result;
}

internal void
os_decommit(void *ptr, U64 size)
{
    mprotect(ptr, size, PROT_NONE);
    madvise(ptr, size, MADV_DONTNEED);
}

internal void
os_release(void *ptr, U64 size)
{
    munmap(ptr, size);
}
```

---

## Opaque Handles

Wrap native handles in a portable type.

```c
typedef struct OS_Handle OS_Handle;
struct OS_Handle
{
    U64 u64[1];  // Wraps native handle (HANDLE on Windows, int on Linux)
};

internal OS_Handle
os_handle_zero(void)
{
    OS_Handle h = { 0 };
    return h;
}

internal B32
os_handle_match(OS_Handle a, OS_Handle b)
{
    return a.u64[0] == b.u64[0];
}

// Usage
#if OS_WINDOWS
  #define os_handle_from_native(h) ((OS_Handle){ .u64 = { (U64)(h) } })
  #define os_handle_to_native(h)   ((HANDLE)(h).u64[0])
#elif OS_LINUX
  #define os_handle_from_native(h) ((OS_Handle){ .u64 = { (U64)(h) } })
  #define os_handle_to_native(h)   ((int)(h).u64[0])
#endif
```

---

## File Iteration

Hide OS-specific directory iteration:

```c
typedef struct OS_FileIter OS_FileIter;
struct OS_FileIter
{
    U8 opaque[1024];  // OS-specific data hidden
};

typedef struct OS_FileInfo OS_FileInfo;
struct OS_FileInfo
{
    String8 name;
    U64 size;
    U64 created_time;
    U64 modified_time;
    B32 is_folder;
};

internal OS_FileIter *os_file_iter_begin(Arena *arena, String8 path);
internal B32          os_file_iter_next(Arena *arena, OS_FileIter *iter, OS_FileInfo *info);
internal void         os_file_iter_end(OS_FileIter *iter);
```

---

## Threading Primitives

```c
typedef struct Mutex    Mutex;
typedef struct RWMutex  RWMutex;
typedef struct CondVar  CondVar;
typedef struct Semaphore Semaphore;

internal Mutex    os_mutex_alloc(void);
internal void     os_mutex_release(Mutex mutex);
internal void     os_mutex_take(Mutex mutex);
internal void     os_mutex_drop(Mutex mutex);

internal Semaphore os_semaphore_alloc(U32 initial_count);
internal void      os_semaphore_release(Semaphore semaphore);
internal B32       os_semaphore_take(Semaphore semaphore, U64 endt_us);

// Scoped locking
#define MutexScope(mutex) DeferLoop(os_mutex_take(mutex), os_mutex_drop(mutex))
```

---

## Endianness

```c
#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  #define ARCH_LITTLE_ENDIAN 1
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  #define ARCH_LITTLE_ENDIAN 0
#else
  // Runtime detection or assume
  #define ARCH_LITTLE_ENDIAN 1
#endif

// Byte swapping
internal U16 bswap_u16(U16 x) { return (U16)((x >> 8) | (U16)(x << 8)); }
internal U32 bswap_u32(U32 x) { return __builtin_bswap32(x); }
internal U64 bswap_u64(U64 x) { return __builtin_bswap64(x); }

// Convert from/to big-endian
#if ARCH_LITTLE_ENDIAN
  #define from_be_u16(x) bswap_u16(x)
  #define from_be_u32(x) bswap_u32(x)
  #define from_be_u64(x) bswap_u64(x)
  #define to_be_u16(x)   bswap_u16(x)
#else
  #define from_be_u16(x) (x)
  #define to_be_u16(x)   (x)
#endif
```

---

## Quick Reference

```c
// Platform detection
#if OS_WINDOWS
  // Windows code
#elif OS_LINUX
  // Linux code
#endif

// Compiler intrinsics
force_inline int add(int a, int b) { return a + b; }
if (Unlikely(error)) { ... }

// OS abstraction
void *mem = os_reserve(MB(64));
os_commit(mem, KB(4));

// Opaque handle
OS_Handle file = os_file_open(path, OS_FileOpenMode_Read);
if (!os_handle_match(file, os_handle_zero())) { ... }
```