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.
What you'll learn
- Verify lowest-unused descriptor allocation across
0..2, slot reuse afterclose(), and dentry removal viaunlink(). - Select
open()O_ACCMODEmodes andO_CREAT,O_EXCL,O_TRUNC,O_APPEND,O_CLOEXEC, andO_TMPFILEflags. - Derive creation permissions via
mode & ~umaskand 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 / Macro | Octal / Mask Category | Exact Linux 6.12 VFS Contract | |
|---|---|---|---|
O_RDONLY / O_WRONLY / O_RDWR | 0 / 1 / 2 (O_ACCMODE = 03) | Mutually exclusive access modes; test via (fl & O_ACCMODE) == O_RDONLY | |
O_CREAT & O_TMPFILE | Creation flags | Require 3rd mode_t argument (0644 or S_I*); O_TMPFILE creates unnamed inode | |
O_EXCL | Atomic existence guard | With O_CREAT, fails atomically with EEXIST if path exists (never follows final symlink) | |
O_TRUNC & O_APPEND | Open / write modifiers | O_TRUNC resets length to 0; O_APPEND moves cursor to i_size before every write() | |
O_CLOEXEC | Descriptor-slot flag | Sets FD_CLOEXEC atomically at open so execve() never leaks fd to child binaries | |
O_NOFOLLOW & O_DIRECTORY | Path traversal guards | Fails 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 / 0004 | Owner rw-, group r--, other r-- (0644), masked by ~umask |
Figure 2.1a. Per-process descriptor table lowest-slot allocation and open() flag composition.
Figure 2.1b. Kernel fdtable O(1) bitmap scan and 16-bit POSIX mode_t / ~umask bitfield algebra.
- Step 1. Compose one O_ACCMODE access value with O_CREAT | O_EXCL | O_CLOEXEC and an explicit octal mode_t.
- Step 2. Kernel __alloc_fd() scans files_struct->fdt open_fds in O(1) to claim the lowest unused integer slot.
- Step 3. VFS computes effective_mode = mode & ~umask on newly created inodes; inspect modes via (fl & O_ACCMODE).
- 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.
Variadic open() Prototypes, openat() & unlink()
Include <fcntl.h>, <sys/stat.h>, <sys/types.h>, and <unistd.h> under #define _POSIX_C_SOURCE 200809L. In glibc 2.39, user-space open(path, flags, ...) forwards internally to openat(AT_FDCWD, path, flags, mode). Release descriptors in reverse acquisition order (close(fd2) then close(fd1)) so error branches never leak slots toward RLIMIT_NOFILE (EMFILE), and remove directory entries cleanly via int unlink(const char *pathname).
open(2) GL-C01 Quick Reference open(2) NAME open, openat - open or create a file and allocate a descriptor SYNOPSIS #include <fcntl.h> int open(const char *pathname, int flags, ... /* mode_t mode */); int openat(int dirfd, const char *pathname, int flags, ...); STANDARDS POSIX.1-2008; openat() requires _POSIX_C_SOURCE >= 200809L. RETURN VALUE Returns lowest-numbered unused descriptor (>= 0), or -1 with errno set. ERRORS EACCES Requested access mode or directory search permission denied. EEXIST O_CREAT | O_EXCL specified and pathname already exists. EINTR Blocked open on a slow device or FIFO interrupted by signal. EISDIR pathname refers to a directory and write access was requested. EMFILE Per-process RLIMIT_NOFILE descriptor table is full. ENOENT O_CREAT was not set and pathname is missing. FLAGS O_CLOEXEC Atomically set FD_CLOEXEC so execve(2) closes fd. O_CREAT Create regular file if missing; requires octal mode. O_EXCL With O_CREAT, fail atomically with EEXIST if path exists. O_TRUNC Truncate existing regular file to 0 bytes on writable open. O_APPEND Move file offset to current i_size before every write(2). SEE ALSO close(2), fcntl(2), read(2), umask(2), unlink(2), write(2) Kernel Systems Academy Lesson 2.1 open(2) GL-C01 quick reference · full manual page: man 2 open 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$ 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; }- Masking shift counts with & 31U avoids x >> 32 Undefined Behavior when n == 0 while compiling to a single rotate instruction.
- Pass 0666 with O_CREAT | O_EXCL | O_CLOEXEC; kernel stores 0666 & ~0022 = 0644 atomically.
- 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-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-l01Tracing 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:
- Step 1 (Compute
effective_modeacross bothumaskextremes): Evaluate0600 & ~0000and0600 & ~0077(0600in both cases!), then evaluate what would happen ifumaskwere0200(0600 & ~0200 == 0400, stripping owner write!). - Step 2 (Complete the
open()call): Write the exactopen()call combiningO_WRONLY,O_CREAT,O_EXCL,O_NOFOLLOW, andO_CLOEXECwithS_IRUSR | S_IWUSR, saving and restoringumask(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
Key takeaways
- Every process indexes open VFS objects through non-negative
intfile descriptors (0..RLIMIT_NOFILE - 1), pre-opening0,1, and2and always allocating the lowest unused integer. open()requires one access mode (O_RDONLY,O_WRONLY, orO_RDWR, tested viaO_ACCMODE) combined with creation and status flags (O_CREAT,O_EXCL,O_TRUNC,O_APPEND,O_CLOEXEC).- Whenever
O_CREATorO_TMPFILEis present, pass the thirdmode_targument (0644orS_I*macros); the kernel applieseffective_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()andread_full()loops across all fourssize_treturn regimes,MAX_RW_COUNT, and Linuxclose()error semantics.