Descriptors, open Flags & Permissions

Omitting O_CLOEXEC leaks sensitive descriptors across execve(), testing (flags & O_RDONLY) evaluates false on every file, and forgetting the variadic mode argument on O_CREAT stamps random stack bits onto disk. You will master lowest-slot descriptor allocation, open() flag bitmasks, 16-bit mode_t permissions, and UB-free unsigned bit shifts.

20 minfree previewLinux 6.12C11glibc 2.39→ module 2 lab
What you'll learn
  • Verify lowest-unused descriptor allocation across 0..2, slot reuse after close(), and dentry removal via unlink().
  • Select open() O_ACCMODE modes and O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_CLOEXEC, and O_TMPFILE flags.
  • Derive creation permissions via mode & ~umask and UB-free unsigned shifts (1U << bit) without variadic stack bugs.

Why Naive open() Calls Leak Handles, Corrupt Modes & Trigger UB

Picture a background daemon that closes STDIN_FILENO (0), STDOUT_FILENO (1), and STDERR_FILENO (2) during startup without reopening /dev/null, then calls int db_fd = open("/var/lib/app/keys.db", O_RDWR | O_CREAT) with two arguments, and later calls perror("warn") when a network timeout occurs. Three silent disasters strike in sequence: open() allocates slot 2 (STDERR_FILENO) as db_fd so perror() overwrites keys.db with ASCII error text; omitting the third mode_t argument with O_CREAT pulls random caller register garbage into the new inode's permission bits; and omitting O_CLOEXEC leaks db_fd into every child helper spawned via execve()!

Naive code stumbles on open() because C lacks function overloading (forcing <fcntl.h> to declare open() as a variadic function), Linux encodes O_RDONLY as 0 rather than a bitmask flag, and the kernel silently clears requested permission bits through the process umask. Mastering unbuffered POSIX I/O begins with exact command of descriptor table indexing, open() flag composition, and unsigned bit-mask algebra.

note: Think of a numbered coat-check rack with brass tags 0 through 1023. Slots 0, 1, and 2 are pre-hung at shift start, every new coat claims the lowest empty hook, and returning a tag immediately frees that hook for the next guest.

Where it stops working: Unlike brass coat tags, an open file descriptor also carries kernel access-mode and close-on-exec flags enforced on every subsequent read, write, or execve call.

definition (File Descriptors, O_ACCMODE & Process umask): File Descriptor (fd) & Lowest-Unused Allocation: Coined in Seventh Edition Unix for a non-negative int array index into a process's private files_struct descriptor table (0..RLIMIT_NOFILE - 1), POSIX mandates that open() and openat() allocate the lowest-numbered unused slot (returning -1 with EMFILE when full). Access Mode (O_ACCMODE) is a 2-bit field (03 octal: O_RDONLY = 0, O_WRONLY = 1, O_RDWR = 2), while User File-Creation Mask (umask) clears disallowed permission bits on O_CREAT / O_TMPFILE via effective_mode = mode & ~umask.

One Layer Down: fdtable Bitmap Scan, st_mode Bit Algebra & Unsigned Shifts

Inside the Linux kernel (fs/file.c), __alloc_fd() locates the lowest free descriptor in O(1) amortized time using a two-level unsigned long bitmap inside files->fdt: a top-level bitword identifies the first 64-slot chunk with a 0 bit, and a hardware find-first-zero instruction (tzcnt / clz) selects the exact lowest free integer (3 in a fresh process where 0, 1, and 2 are open). Closing a descriptor clears its bitmap bit immediately, so the very next open() reclaims that exact slot.

When O_CREAT or O_TMPFILE creates a new inode, VFS combines the 4-bit file type (S_IFREG = 0100000) with masked 12-bit permissions via effective_mode = mode & ~current->fs->umask. For requested mode = 0666 (110 110 110 binary: rw-rw-rw-) under standard umask = 0022 (000 010 010, so ~0022 masks out group-write and other-write), bitwise AND yields 0666 & 0755 = 0644 (rw-r--r--). Whenever composing custom bitmasks or rotating 32-bit protocol flags in ISO C11, always shift unsigned types (1U << 31, UINT32_C(1) << bit): 1 << 31 overflows a 32-bit signed int (UB), and (x << n) | (x >> (32 - n)) evaluates x >> 32 (UB) when n == 0! Writing (x << (n & 31U)) | (x >> ((-n) & 31U)) eliminates both UB edges and compiles to a single rol/ror instruction at -O2.

open() Flag / MacroOctal / Mask CategoryExact Linux 6.12 VFS Contract
O_RDONLY / O_WRONLY / O_RDWR0 / 1 / 2 (O_ACCMODE = 03)Mutually exclusive access modes; test via (fl & O_ACCMODE) == O_RDONLY
O_CREAT & O_TMPFILECreation flagsRequire 3rd mode_t argument (0644 or S_I*); O_TMPFILE creates unnamed inode
O_EXCLAtomic existence guardWith O_CREAT, fails atomically with EEXIST if path exists (never follows final symlink)
O_TRUNC & O_APPENDOpen / write modifiersO_TRUNC resets length to 0; O_APPEND moves cursor to i_size before every write()
O_CLOEXECDescriptor-slot flagSets FD_CLOEXEC atomically at open so execve() never leaks fd to child binaries
O_NOFOLLOW & O_DIRECTORYPath traversal guardsFails with ELOOP if target is a symlink or ENOTDIR if target is not a directory
`S_IRUSR\S_IWUSR / S_IRGRP / S_IROTH`0600 / 0040 / 0004Owner rw-, group r--, other r-- (0644), masked by ~umask
fig_m02_l01_flags.svg — Per-process descriptor table lowest-slot allocation and…

Figure 2.1a. Per-process descriptor table lowest-slot allocation and open() flag composition.

fig_m02_l01_arch.svg — Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t…

Figure 2.1b. Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t / ~umask bitfield algebra.

step_m02_l01.svg — Every open() claims the lowest unused fdtable slot,…step 1/4
  1. Step 1. Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.
  2. Step 2. Kernel __alloc_fd() scans files_struct->fdt open_fds in O(1) to claim the lowest unused integer slot.
  3. Step 3. VFS computes effective_mode = mode & ~umask on newly created inodes; inspect modes via (fl & O_ACCMODE).
  4. Step 4. Closing a descriptor clears its bitmap bit immediately so the next open() reclaims that lowest slot.

Figure 2.1c. Every open() claims the lowest unused fdtable slot, seals FD_CLOEXEC atomically when O_CLOEXEC is passed, and masks new inode permissions by ~umask.

Auditing Lowest-Slot Reuse, O_ACCMODE, umask & UB-Free Rotates

Save open_perm_audit.c below. It verifies STDIN_FILENO..STDERR_FILENO (0,1,2), sets umask(0022), creates p1 (0666 & ~0022 == 0644) and p2 (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), proves close(fd1) causes the next open() (fd3) to reclaim that exact lowest integer, checks (fl & O_ACCMODE) == O_RDONLY, confirms O_CREAT | O_EXCL fails with EEXIST, verifies unlink() (ENOENT), and tests UB-free UINT32_C(1) << 31 + rotl32_safe(..., 0U) under -fsanitize=undefined.

learner@ksa: ~/gl-c01/m02-l01
learner@ksa:~/gl-c01/m02-l01$ bat -H 12 -H 26 -H 41 open_perm_audit.c File: open_perm_audit.c    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <sys/stat.h>    #include <sys/types.h>    #include <unistd.h>        static inline uint32_t rotl32_safe(uint32_t x, unsigned int n) {      return (x << (n & 31U)) | (x >> ((-n) & 31U));    }        int main(void) {        const char *p1 = "/tmp/ksa_m02_a.tmp";        const char *p2 = "/tmp/ksa_m02_b.tmp";        const char *p3 = "/tmp/ksa_m02_del.tmp";        (void)unlink(p1);        (void)unlink(p2);        (void)unlink(p3);            mode_t old_mask = umask(0022);            int fd1 = open(p1, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0666);      int fd2 = open(p2, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,                       S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);        int fd_del = open(p3, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);        if (fd1 == -1 || fd2 == -1 || fd_del == -1) {            perror("open");            umask(old_mask);            return EXIT_FAILURE;        }        (void)close(fd_del);            int consecutive = (fd2 == fd1 + 1);        if (close(fd1) == -1) {            umask(old_mask);            return EXIT_FAILURE;        }      int fd3 = open(p1, O_RDONLY | O_CLOEXEC);        int fl3 = (fd3 != -1) ? fcntl(fd3, F_GETFL) : -1;        int acc_rdonly = (fl3 != -1 && (fl3 & O_ACCMODE) == O_RDONLY);        int reused_lowest = (fd3 == fd1 && acc_rdonly);            errno = 0;        int dup_excl = open(p1, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);        int excl_eexist = (dup_excl == -1 && errno == EEXIST);            int unlinked = (unlink(p3) == 0);        errno = 0;        int gone_fd = open(p3, O_RDONLY | O_CLOEXEC);        int unlink_ok = (unlinked && gone_fd == -1 && errno == ENOENT);            uint32_t hi_mask = UINT32_C(1) << 31;        int rot_ok = (rotl32_safe(hi_mask, 0U) == 0x80000000U &&                      rotl32_safe(hi_mask, 1U) == 0x00000001U);            if (fd3 != -1) (void)close(fd3);        (void)close(fd2);        umask(old_mask);            printf("std_fds=%d,%d,%d consecutive=%d reused_lowest=%d\n",               STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO,               consecutive, reused_lowest);        printf("excl_eexist=%d unlink_ok=%d rot_ub_safe=%d\n",               excl_eexist, unlink_ok, rot_ok);        return EXIT_SUCCESS;    }
  1. Masking shift counts with & 31U avoids x >> 32 Undefined Behavior when n == 0 while compiling to a single rotate instruction.
  2. Pass 0666 with O_CREAT | O_EXCL | O_CLOEXEC; kernel stores 0666 & ~0022 = 0644 atomically.
  3. Mask with O_ACCMODE (never flags & O_RDONLY) to verify fd3 opened read-only.

Verifying Descriptor Slots and Masked Inode Permissions

Compile open_perm_audit under -fsanitize=undefined, verify the runtime invariants, inspect the effective octal permissions (644 644) stored on disk via stat -c '%a', and remove the scratch files.

learner@ksa: ~/gl-c01/m02-l01
learner@ksa:~/gl-c01/m02-l01gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror -fsanitize=undefined open_perm_audit.c -o open_perm_auditlearner@ksa:~/gl-c01/m02-l01./open_perm_auditstd_fds=0,1,2 consecutive=1 reused_lowest=1excl_eexist=1 unlink_ok=1 rot_ub_safe=1learner@ksa:~/gl-c01/m02-l01echo "$(stat -c '%a' /tmp/ksa_m02_a.tmp) $(stat -c '%a' /tmp/ksa_m02_b.tmp)" && rm -f /tmp/ksa_m02_a.tmp /tmp/ksa_m02_b.tmp open_perm_audit644 644learner@ksa:~/gl-c01/m02-l01

Tracing Bitmap Reuse, O_ACCMODE & umask Enforcement

Every check in open_perm_audit confirmed the VFS descriptor contract: fd1 and fd2 claimed consecutive slots (3 and 4), closing fd1 cleared bit 3 in files_struct so fd3 immediately reclaimed slot 3 (reused_lowest=1), (fl3 & O_ACCMODE) == O_RDONLY verified read-only access cleanly, and 0666 & ~0022 stamped 0644 onto disk while O_CREAT | O_EXCL blocked duplicate creation with EEXIST.

Guided Practice: Exact Private Keyfile Creation Under Loose umask

Suppose an administrator runs your key-provisioning tool in a shell whose umask is 0000 (clearing zero bits!), and you need /tmp/ksa_secret.key created atomically with exact owner-only 0600 (rw-------) permissions even if umask is 0000 or 0077:

  1. Step 1 (Compute effective_mode across both umask extremes): Evaluate 0600 & ~0000 and 0600 & ~0077 (0600 in both cases!), then evaluate what would happen if umask were 0200 (0600 & ~0200 == 0400, stripping owner write!).
  2. Step 2 (Complete the open() call): Write the exact open() call combining O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW, and O_CLOEXEC with S_IRUSR | S_IWUSR, saving and restoring umask(0077) around creation so group/other bits can never be set.

Independent Practice: Descriptor-Leak Exhaustion (EMFILE) Probe

Write a C11 diagnostic emfile_probe.c that lowers the process's soft RLIMIT_NOFILE ceiling to 16 inside main() using getrlimit(RLIMIT_NOFILE, &rl) and setrlimit(RLIMIT_NOFILE, &rl) (<sys/resource.h>), opens /dev/null with O_RDONLY | O_CLOEXEC in a bounded array until open() returns -1, asserts errno == EMFILE, closes every acquired descriptor in strict reverse (LIFO) order, and proves a fresh open("/dev/null", O_RDONLY | O_CLOEXEC) succeeds again at the lowest slot (3).

Common Production Pitfalls

warning: Symptom: Newly created log files appear on disk with random permissions like --w-r-xr-T (01252) that change from run to run! Root Cause: Calling variadic open(path, O_WRONLY | O_CREAT) with two arguments causes the kernel wrapper to read uninitialized ABI register %rdx / r2 garbage as mode_t mode. Fix: Always pass an explicit octal mode (0644 or 0600) whenever flags includes O_CREAT or O_TMPFILE.

warning: Symptom: Writing if (flags & O_RDONLY) to verify read-only access evaluates to 0 (false) on every descriptor in the system! Root Cause: On Linux and POSIX, O_RDONLY has integer value 0 (O_WRONLY == 1, O_RDWR == 2), so bitwise AND with 0 always yields 0. Fix: Mask the 2-bit access field with (flags & O_ACCMODE) == O_RDONLY.

Knowledge Check

quiz · 1 of 4

A process starts with standard descriptors 0, 1, and 2 open, calls close(0) to close standard input, and immediately calls open("/etc/hostname", O_RDONLY | O_CLOEXEC). Which integer descriptor does open() return?

quiz · 2 of 4

(Review from previous module) If a process running with umask 0027 calls open("key.bin", O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH), what effective octal mode is stored on the new inode?

quiz · 3 of 4

Why do production Linux C services include O_CLOEXEC directly inside open() rather than calling fcntl(fd, F_SETFD, FD_CLOEXEC) on the next line?

quiz · 4 of 4

A framing header defines #define HDR_URGENT (1 << 31) and uint32_t rot(uint32_t x, unsigned int n) { return (x << n) | (x >> (32 - n)); }. Why does -fsanitize=undefined abort on HDR_URGENT and rot(v, 0U)?

Key takeaways

  • Every process indexes open VFS objects through non-negative int file descriptors (0..RLIMIT_NOFILE - 1), pre-opening 0, 1, and 2 and always allocating the lowest unused integer.
  • open() requires one access mode (O_RDONLY, O_WRONLY, or O_RDWR, tested via O_ACCMODE) combined with creation and status flags (O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_CLOEXEC).
  • Whenever O_CREAT or O_TMPFILE is present, pass the third mode_t argument (0644 or S_I* macros); the kernel applies effective_mode = mode & ~umask, and custom bitmasks must use unsigned shifts (1U << bit).
  • Close descriptors in reverse acquisition order on error paths so long-running daemons never exhaust RLIMIT_NOFILE (EMFILE).
  • Next, with open descriptors in hand, we will implement binary-safe write_all() and read_full() loops across all four ssize_t return regimes, MAX_RW_COUNT, and Linux close() error semantics.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure