Updated December 4, 2026 · every figure below was measured on the host described in Section 1 unless its table marks it as documented, and a timing row says how many calls it averaged.
A deployment writes a cache file whose key is a URL, and the write fails with OSError: [Errno 36] File name too long. The directory exists, the disk has room, and the name is a normal URL – but the filesystem counts bytes, and this one is a byte past what a single component may hold.
errno 36 is ENAMETOOLONG, rendered “File name too long” by os.strerror on this host. One number covers two limits: a component longer than 255 bytes, and a whole pathname longer than 4095. Different code refuses each, at a different moment, and the number alone does not say which one you hit.
Every figure below was measured on the guest in Table 2, as an unprivileged user, on the two filesystem types it mounts for writing: virtiofs and tmpfs. ext4, overlayfs, eCryptfs and network filesystems were not available here, so these numbers describe those two types, and a component limit can be shorter elsewhere. Numbers taken from a manual rather than a run say so where they appear: macOS’s number, Windows’s codes, the 256 bytes the kernel reserves for a shebang line, and the 108-byte socket address whose 107-byte boundary this host did confirm.
TL;DR — errno 36 means the name was refused for its length: 255 encoded bytes in one component, 4095 in one pathname argument, the terminator included. Both limits count bytes on the byte-oriented filesystems this host mounts, so a name of Hangul syllables is refused at a third of the characters. The whole-path check runs before the walk and the component check during it, so a 300-character name sometimes reports ENOENT instead. Shorten a component with a digest; reach a deep tree with a descriptor.
Fix It First: Ten Changes, Matched to What You Saw
The first column is what you see, the second the cheapest check that separates this cause from the others, and the third the change that ends it. Every row rests on a measurement below; the shebang row quotes the kernel’s documented buffer, and the boundary that buffer produces was measured here (Table 8).
| What you see | Cheapest check | Change that ends it |
|---|---|---|
Errno 36 on a path whose directory lists fine | count the bytes of the last component, not its characters | the component is over the filesystem’s limit: shorten it, or key on a digest |
| A name of 255 characters that is still refused | encode it: len(name.encode()) | on this host the limit counts bytes, so three-byte characters reach it at 85 |
os.path.exists() answered False, so the writer skipped the file | call os.stat and catch the error instead | the helper hides every errno but a missing file, including this one |
Path.exists() raised where the helper returned False | wrap the pathlib call in except OSError | pathlib re-raises this errno; only four numbers mean “no such thing” to it |
Errno 2 for a path you built from a 300-character name | check the parent directory before blaming the name | the walk reports its first failure, and the long component was never reached |
Errno 13 for the same long name | check search permission on the parent | the same reason: the walk stopped at the directory, not at the name |
| A build that fails only inside a deep dependency tree | count the bytes of the absolute path you pass | past the whole-path limit: shorten the root, or walk with a descriptor |
chdir into a deep directory that this process already holds open | pass the descriptor to os.fchdir | the limit is on the string, and a descriptor is not a string |
| A unix socket that will not bind under a long directory | count the socket path in bytes | the address holds 108 bytes; bind under a shorter path |
A script that answers Exec format error with a long interpreter path | count the whole shebang line | past 256 bytes the kernel does not parse it: use /usr/bin/env |
1. One Number, Two Limits, and the Host That Shows Both
errno 36 is ENAMETOOLONG. Linux documents it as a name that is too long for the operation (errno(3)) and leaves the length to each filesystem: pathconf asks a directory, and PC_NAME_MAX and PC_PATH_MAX are what it reports (pathconf(3)). On this host those numbers are 255 and 4096, the same on every filesystem mounted for writing.
The number does not say which limit was refused, and the two are refused at different points in a call. A pathname longer than the limit is rejected before the kernel looks at any component of it; that is a property of the syscall interface, not of a filesystem (fs/namei.c). A component that is too long is rejected during the walk, by the filesystem asked to create or look up that name. What the caller sees therefore depends on how far the walk got first. Sections 3 and 6 measure both orders.
One consequence follows immediately: a name of 300 characters is not automatically a name-length failure. If the directory that would hold it does not exist, the walk never asks about the name and the caller gets ENOENT. That is why a search for this errno in a log often comes up empty when the real problem is a generated name that grew.
| Condition | Value on this host |
|---|---|
| Kernel | 6.12.118-guest-1.2 |
| Python | 3.12.16, 64-bit |
| Machine and CPUs | x86_64, 2 vCPU |
| C library | glibc 2.41 |
| Shell | dash as /bin/sh |
| User id | 1000: unprivileged throughout, so nothing below needs root |
| Page size | 4096 bytes |
| Filesystems written to | virtiofs at /workspace, tmpfs at /tmp and at /dev/shm |
PC_NAME_MAX | 255 bytes, reported by pathconf on both types |
PC_PATH_MAX | 4096 bytes, reported on both |
PC_LINK_MAX | 127, which matters for hard links rather than for names |
| ENAMETOOLONG | 36, “File name too long” |
| ENOENT | 2, the number a walk returns when a parent is absent |
| ELOOP | 40, “Too many levels of symbolic links”: a different limit on a different thing |
Every arm below either succeeds or answers with an error number, and an error number does not move between runs, so those arms ran once. Durations do move, so Section 8 repeats each row five times and prints the range. A file size is the encoded length the filesystem counts, not the length of a string in a runtime.
Why the same number twice?
Linux returns ENAMETOOLONG for a component that is too long and for a pathname that is too long, because both are names in the same call. Windows keeps two documented codes apart: 206 ERROR_FILENAME_EXCED_RANGE for a file name or extension that is too long, and 3 ERROR_PATH_NOT_FOUND for a path it cannot find (Table 14). Its documentation gives the codes and the length limit, not which code a path past the limit produces, so this page reconstructs the distinction from the path itself.
2. The Component Limit: 255 Bytes in One Name
A single component – the last element of a path, the thing a directory entry holds – gets 255 bytes on both filesystems this host mounts for writing. That number is not baked into the kernel: it is what the filesystem reports when asked pathconf(directory, "PC_NAME_MAX"), and this host enforces exactly what it reports.
A create and a lookup meet the same wall. open with O_CREAT, mkdir, stat and unlink all answer 36 for a name of 256 bytes. A health check that only stats a file can therefore fail on a name that was never stored.
| Bytes in the name | virtiofs | tmpfs | What happened |
|---|---|---|---|
| 254 | ok | ok | stored, listed and removed |
| 255 | ok | ok | the largest storable name |
| 256 | 36 | 36 | refused by all four calls with errno 36 |
| 512 | 36 | 36 | refused in the same way, at any length past the limit |
The two types are different code: virtiofs forwards each operation to the host that owns the directory, and tmpfs keeps the entries in memory. Both stop at the same byte because the check sits where a name becomes a directory entry, not where the bytes are stored. The count itself is in bytes on byte-oriented Linux filesystems like these two. NTFS and exFAT measure a name in UTF-16 code units, and this host has neither, so how they would answer is not measured here.
So the check before a create is one expression: len(name.encode()), against 255. Not len(name); Section 4 shows how far apart those two answers land. And no call asks “would this fit” in advance – only pathconf for the limit and the create itself for the verdict.
Is 255 a Linux number?
It is the number Linux filesystems usually implement, and it is what NAME_MAX resolves to here. The portable question is pathconf: the value it returns for a directory applies to names inside that directory, so a program writing into a mounted volume should ask the volume rather than its own constant.
3. The Path Limit: 4,096 Bytes, One of Which Is the Terminator
The second limit belongs to the call, not to a directory: a pathname argument may hold 4096 bytes, and one of them is the terminator a C string spends, so the longest path a call accepts is 4095 bytes. The boundary is exact, and worth seeing rather than assuming: a program that reserves the terminator and one that forgets it differ by a byte at the worst possible moment.
| Bytes in the path | create and close | stat | What it says |
|---|---|---|---|
| 4,094 | ok | ok | inside the limit |
| 4,095 | ok | ok | the longest path a call accepts |
| 4,096 | 36 | 36 | one byte past it: refused before the walk |
| 4,097 | 36 | 36 | refused in the same way |
The kernel really walks the 4095-byte path. One of exactly that length, pointing at a file that does not exist, answers 2 – ENOENT, the walk’s own answer – while one byte more answers 36 before any component is examined. Two layers, two answers: that is how a long name ends up hidden behind the wrong error.
A path that long cannot be built with the usual calls, because every intermediate mkdir would need the finished path. Build it one component at a time instead: create a name relative to the open directory, open the result, close the parent, repeat. That is how the tree below was made – 5,038 bytes in 25 levels.
| What was tried | What it answered | Why |
|---|---|---|
| create a file by descriptor | ok | one short component per call |
| open that file by descriptor | ok | the same file, reached without its path |
| stat it by its absolute path, 5,048 bytes | 36 | the path is over the limit, so the call never starts |
| stat by a relative path of 4,220 bytes and a descriptor | 36 | relative is still a pathname, and it is measured |
read /proc/self/fd for the descriptor | 36 | the link answers with a copy of the path |
read /proc/self/cwd | 36 | the same copy, and the same ceiling |
os.chdir to the 5,038-byte path | 36 | the same string, refused by the same rule |
os.fchdir with the descriptor | ok | a descriptor is not a string, so nothing is measured |
| the getcwd system call, at a 4,096-byte buffer and a 16,384-byte one | 36 | the kernel fills a PATH_MAX buffer of its own and refuses a longer name |
| getcwd in the C library, a 4,096-byte buffer | 34 | the library’s own walk, with a buffer too small |
| getcwd in the C library, a 6,000-byte buffer | 5,038 bytes | the same walk, given room |
os.getcwd afterwards | 5,038 bytes | CPython passes its own buffer, 1 KiB at first, and grows it on ERANGE |
the shell’s pwd in the same directory | 5,038 bytes | a second caller, the same full name |
| is the reported directory the one that was walked | yes | the walk and the report describe the same tree |
Two rows are the ones to remember. /proc/self/fd looks like an escape hatch, because it names an open file without a path – but reading the link copies the path into a buffer of the same size, and /proc/self/cwd answers 36 as well. And chdir fails on the string while fchdir succeeds on the descriptor: a process can be inside a directory it cannot name.
Why getcwd still answers
The getcwd rows look impossible, so here is the whole mechanism. The kernel builds the name in a fixed PATH_MAX buffer (fs/d_path.c) and answers 36 when the name does not fit. A raw syscall with 4,096 bytes and another with 16,384 both returned 36: more memory cannot help, because the buffer that overflows is the kernel’s.
The C library does not stop there. glibc’s getcwd falls back to its generic implementation when the syscall fails with that error (sysdeps/unix/sysv/linux/getcwd.c), and the fallback builds the name by reading the tree upward, growing its buffer as it goes. Measured: a 4,096-byte buffer returned 34, ERANGE, a 6,000-byte buffer returned the full 5,038 bytes, and the shell’s pwd printed the same name.
The third caller is CPython, and it grows the buffer itself. os.getcwd passes the C library a buffer it starts at 1 KiB and reallocates it 1 KiB larger whenever the answer is ERANGE (Modules/posixmodule.c), so the call ends only when the buffer holds the whole name.
The result is a name you can read but not use. Hand the string from os.getcwd to stat, chdir or open and the answer is 36; only the descriptor still works. A process that logs its working directory from a tree this deep is logging a path its own syscalls will reject – readable to a human, useless to the code.
The relative-path row is the exception people hope for and do not get. The kernel measures the argument it was given, not the depth it will reach, so 4,220 bytes of component names fail whether or not a descriptor points at where they start. The way past the limit is not a cleverer string; it is more calls, each with a short one.
4. Bytes, Not Characters
The limit counts encoded bytes, and Python encodes a str to the filesystem’s encoding – UTF-8 here – before the call. A Latin-1 letter takes two bytes, a Hangul syllable three, an emoji four, so the same limit bites at a different character count for each.
| Character | Characters in the name | Bytes in the name | Result |
|---|---|---|---|
| ASCII | 255 | 255 | ok |
| ASCII | 256 | 256 | 36 |
| Latin-1 letter, two bytes | 127 | 254 | ok |
| Latin-1 letter, two bytes | 128 | 256 | 36 |
| Hangul syllable, three bytes | 85 | 255 | ok |
| Hangul syllable, three bytes | 86 | 258 | 36 |
| Emoji, four bytes | 63 | 252 | ok |
| Emoji, four bytes | 64 | 256 | 36 |
Each pair crosses the line at its own count: 127 two-byte letters, 85 Hangul syllables, 63 emoji. A test that asserts a name “fits in 255” with len() therefore passes names the filesystem refuses, and the failure lands in production in whatever language the key was written in.
The whole path has the same arithmetic, and it is easier to miss. The tree in this arm is 1,395 characters by the count len() gives, which reads as a third of the limit, and 4,115 bytes on disk. stat answers 36; creating a file inside the same directory by descriptor answers ok. A non-Latin tree meets the ceiling at about a third of the depth an ASCII tree reaches.
"""The two limits, asked of the filesystem, with the values Linux documents as a fallback."""
import os
NAME_MAX = 255
PATH_MAX = 4096
def encoded_length(text: str) -> int:
"""The number of bytes a filesystem counts for a name, not the number of characters.
``os.fsencode`` uses the filesystem encoding with ``surrogateescape``, so a name that came
from a directory listing and did not decode as UTF-8 still measures as the bytes it is.
"""
return len(os.fsencode(text))
def name_max(directory: str = ".") -> int:
"""The longest single component this directory accepts, in bytes."""
try:
return int(os.pathconf(directory, "PC_NAME_MAX"))
except (OSError, ValueError):
return NAME_MAX
def path_max(directory: str = ".") -> int:
"""The longest whole pathname this directory accepts, in bytes.
The number includes the byte a C string spends on its terminator, so a path of
``path_max()`` bytes is already one too long: 4095 bytes are accepted where this returns
4096.
"""
try:
return int(os.pathconf(directory, "PC_PATH_MAX"))
except (OSError, ValueError):
return PATH_MAX
Three details carry the weight. os.fsencode uses the filesystem encoding with surrogateescape, so a name that did not decode as UTF-8 still measures as the bytes it is. pathconf can fail – on a directory that does not exist, or a filesystem that does not report the value – so both functions fall back to the documented number instead of raising mid-check. And path_max returns the number including the terminator, so the verdict in Section 7 subtracts one before comparing.
5. Twenty Surfaces, and the Ones That Stay Quiet
A long name is not met in one place. The same 256-byte name was handed to twenty calls on this host. The answers split three ways: calls that raise errno 36, calls that answer as if the file were absent, and one call that succeeds because it never resolves the name at all.
| Surface | Answer on a 256-byte name | What it means for a caller |
|---|---|---|
os.stat | 36 | the walk itself, and the number to log |
os.lstat | 36 | the same, without following a link |
os.access | answers False | a boolean answer, so the error is lost |
os.path.exists | answers False | “absent” and “unnameable” are the same answer |
os.path.isfile | answers False | the same silence, for a predicate |
pathlib.Path.exists | 36 | pathlib re-raises: a different answer from the helper |
pathlib.Path.is_file | 36 | re-raised as well |
pathlib.Path.stat | 36 | the same call with a different wrapper |
os.path.getsize | 36 | fails rather than answering a size |
os.listdir | 36 | a directory that cannot be named cannot be read |
os.scandir | 36 | the iterator raises on first use |
glob.glob | returns [] | an empty list, as if nothing matched |
pathlib.Path.glob | returns [] | the same empty answer |
os.mkdir | 36 | the name is refused before an inode is spent |
os.unlink | 36 | a name that cannot exist cannot be removed |
os.rename, source | 36 | the old name is measured first |
os.rename, target | 36 | and the new one is measured before anything moves |
os.link | 36 | the link name is refused; the original is untouched |
os.symlink to a long target | creates it | the target is stored as data, not resolved |
shutil.copyfile | 36 | the write is refused at open time |
The three quiet answers
The quiet group is the dangerous one. os.path.exists answers False, os.access answers False, and glob.glob returns [] – three truthful statements about a file the caller cannot name, and three ways for a program to conclude a file is absent and create it again, or to skip a cleanup it should have run. None of that is a bug in the standard library: a predicate has no room to report an error, so it reports the closest true answer.
pathlib makes the opposite choice on this host, and the difference is its own trap. Path.exists raised 36 and Path.is_file raised 36, because pathlib treats only a small set of numbers as “no such file” and lets the rest out (pathlib). A program that migrated from os.path to pathlib can therefore start raising where it used to return False: better, because the error is visible, and still a production change nobody tested for.
The exception carries the path it was given, in full: for a path of 5,001 bytes the message is 5,034 characters. That is convenient when the destination is a terminal and expensive when it is a log – one refused write can add kilobytes to a line, and a retry loop multiplies it.
The one row that succeeds
One row succeeds, and deserves its own sentence. os.symlink with a target of 300 bytes created the link, and os.readlink returned all 300 bytes: a symbolic link stores its target as data, so the limit it meets is the target’s own when somebody resolves it. A link can be created by a deployment and fail only when the application follows it.
What about reading the directory instead of naming the file?
os.scandir on the parent returns entries with names as bytes, so a listing never meets the component limit for a name it is reading. It does raise when the directory it was given is itself too long to name, which is the row in Table 7.
6. Other Limits Behind the Same Symptom
Three further ceilings produce a failure that looks like this one and is not: a unix socket address, a shebang line, and the target of a symbolic link. Each has its own number, or none at all, and each is small enough to check before the call.
| Call | Answer | Which limit decided it |
|---|---|---|
| unix socket bind, 107-byte path | binds | the address has room for it, terminator included |
| unix socket bind, 108-byte path | OSError, no errno | “AF_UNIX path too long”: Python refuses before the kernel sees it |
| shebang line of 255 bytes | 2 | the line parses and the interpreter is looked up; it did not exist |
| shebang line of 256 bytes | 8 | past the kernel’s buffer the file is not a script at all |
| symlink with a 300-byte target | creates it | the target is stored as data, at any length up to the path limit |
| stat through that symlink | 36 | resolution walks the target, and its component is over the limit |
The socket row breaks an errno-based handler. Python checks the encoded path against the address structure before the call, so what it raises has no errno attribute at all – OSError with the message “AF_UNIX path too long” – and if exc.errno == errno.ENAMETOOLONG never fires. The structure holds 108 bytes on Linux (unix(7)), so the longest usable path is 107. Linux also accepts abstract names that begin with a null byte and never touch the filesystem; this page did not measure those.
The shebang line: a documented buffer, measured at its edge
The kernel reads the first line of a script from a fixed buffer before anything runs. BINPRM_BUF_SIZE, 256 bytes, is the constant that sizes that buffer; fs/binfmt_script.c parses the line out of it, and execve(2) documents the call that reaches it. This host measures the edge exactly: a line of 255 bytes produced 2, the interpreter lookup’s own answer, and a line of 256 bytes produced 8, which a shell reports as “Exec format error”. Neither is 36. The familiar “bad interpreter: No such file or directory” is the first case: a valid line, pointing at a path that is not there.
The order in which a walk reports things explains the wrong-error reports that make this errno hard to find in a log. Two rules are in play: the whole pathname is measured before the walk begins, and each component is measured when the walk reaches it. The table below breaks both rules on purpose and records which one answered.
| Path | Parent | Answer | Which rule decided it |
|---|---|---|---|
| long component, parent that resolves | exists | 36 | the walk reached the name and the filesystem refused it |
| long component, parent that is absent | missing | 2 | the walk stopped at the parent, so the name was never measured |
| long component, parent with no search permission | noexec | 13 | the same stop, one layer earlier |
| short component, parent that is absent | missing | 2 | the control: the same answer without a long name |
| path past the limit with an absent parent, 4,202 bytes | missing | 36 | the length is measured before the walk, so the absent parent is never consulted |
The lesson sits in the second and third rows. A 300-character name inside a directory that does not exist reports 2; inside one the process may not search, it reports 13. Code that creates a directory and then writes a generated name into it meets the first case on every fresh deployment: the directory is missing, so the long name is never the answer. errno 36 appears only once the directory exists, which is why this failure tends to arrive on the second run.
Those are the two rules to carry into code that predicts the answer instead of collecting it: measure the whole string first, then walk the components in order, and report the first thing that would fail. Section 7 writes exactly that down, because by the time an exception exists, “which limit” has to be answered from the path alone.
7. A Module That Measures Before It Calls
The rest of this page assumes a caller can answer three questions without a syscall: does this path fit, which limit would refuse it, and what should the name be instead. That is a small module and a lot of discipline – ask the filesystem for its limits, count bytes, check the total before the components, and shorten deterministically so the same key always lands in the same file. It is 180 lines in 5 files, with 40 tests in Appendix A.
The first decision is what the verdict returns. It answers a word instead of raising, because a caller deciding whether to shorten a name, walk by descriptor or call anyway wants to branch, not to handle an exception it just created.
"""Which limit a path would hit, answered without calling the kernel."""
import os
from .limits import encoded_length, name_max, path_max
COMPONENT = "component"
TOTAL = "total"
def verdict(path, directory: str = ".") -> dict:
"""Decide whether ``path`` fits, and name the limit that would refuse it.
The total is checked first because the kernel checks it first: a pathname longer than
``path_max() - 1`` bytes is refused before any of it is walked, so a component problem
inside such a path is never reported. Between the two, the answer this returns is the one
the caller would get, not the one it might prefer.
"""
text = os.fspath(path)
if isinstance(text, bytes):
text = text.decode("utf-8", "surrogateescape")
total = encoded_length(text)
ceiling = path_max(directory) - 1
if total > ceiling:
return {"ok": False, "reason": TOTAL, "component": None, "bytes": total,
"limit": ceiling}
limit = name_max(directory)
for part in text.split("/"):
size = encoded_length(part)
if size > limit:
return {"ok": False, "reason": COMPONENT, "component": part, "bytes": size,
"limit": limit}
return {"ok": True, "reason": "ok", "component": None, "bytes": total, "limit": ceiling}
The table runs that function against the kernel on the same paths: seven questions, five answers, and a last column that is what os.stat said about the identical string.
| Path | Verdict | What os.stat answered | Reading |
|---|---|---|---|
| a 26-byte path to a file that is absent | ok | 2 | both agree: the name fits, the file is simply not there |
| a component of 255 bytes | ok | 2 | the largest storable name is accepted |
| a component of 256 bytes | component | 36 | the verdict names the component limit, the kernel agrees |
| a path of 4,095 bytes | ok | 2 | the last accepted length, so the walk runs |
| a path one byte past that | total | 36 | the verdict names the path limit before any walk |
| 85 Hangul syllables | ok | 2 | three bytes each, and the total is exactly the limit |
| 86 Hangul syllables | component | 36 | the byte count, not the character count, decides |
Shortening is the second decision, and it has three requirements that pull against each other: truncation is stable but not distinct, a counter is distinct but not stable, and a digest is all three at the price of readability.
"""A deterministic replacement for a component that is too long to store."""
import hashlib
from .limits import encoded_length, name_max
def _cut(text: str, budget: int) -> str:
"""The longest prefix of ``text`` whose encoded form fits in ``budget`` bytes.
A character is never split: a three-byte syllable either fits whole or the cut stops before
it, which is what keeps the result a name the filesystem can store and a reader can read.
"""
kept: list[str] = []
used = 0
for character in text:
size = encoded_length(character)
if used + size > budget:
break
kept.append(character)
used += size
return "".join(kept)
def shorten(name: str, limit: int | None = None, digest_chars: int = 8,
keep_extension: bool = True) -> str:
"""Return a name of at most ``limit`` encoded bytes that still identifies the original.
The result is stable: the same name always shortens to the same string, because the digest
is taken over the whole name rather than over the part that survived. The tail of the
digest is what makes two long names that share a prefix land in different files.
"""
ceiling = name_max() if limit is None else limit
if encoded_length(name) <= ceiling:
return name
extension = ""
stem = name
if keep_extension:
head, dot, tail = name.rpartition(".")
if dot and 0 < len(tail) <= 12 and head:
extension, stem = dot + tail, head
if encoded_length(extension) + 10 > ceiling:
extension = ""
digest = hashlib.sha256(name.encode("utf-8", "surrogateescape")).hexdigest()[:digest_chars]
marker = "~" + digest
budget = ceiling - encoded_length(marker) - encoded_length(extension)
return _cut(stem, budget) + marker + extension
Two properties come out of that code. The digest covers the whole original name, so two names sharing a long prefix land in different files – the case a cache built from URLs meets at once. And the cut loops over characters and measures each one, so a three-byte syllable is kept whole or dropped. Cutting the encoded bytes instead would split a character and produce a name that is not valid UTF-8, which some tools accept and others refuse much later.
The third decision is the sentence. An operator reading a log needs to know which limit applied, and afterwards the only evidence left is the path inside the exception.
"""One sentence for the exception, naming the limit the caller actually hit."""
import errno
import os
import sys
from .limits import name_max, path_max
from .verdict import COMPONENT, TOTAL, verdict
UNIX_MESSAGE = "AF_UNIX path too long"
SUN_PATH = {"linux": 108, "darwin": 104}.get(sys.platform, 108)
def explain(exc: BaseException, directory: str = ".") -> str:
"""Say which limit refused ``exc``, or hand back what the system said.
errno 36 covers two different limits, so the sentence is built from the path in the
exception rather than from the number. A unix socket path is a third case: Python refuses
it before the kernel sees it, with no errno at all.
"""
number = getattr(exc, "errno", None)
text = getattr(exc, "filename", None) or ""
if number is None and UNIX_MESSAGE in str(exc):
return (f"a unix socket path is longer than the socket address holds: "
f"{SUN_PATH - 1} bytes are accepted and the {SUN_PATH}th is not part of the "
f"address")
if number == errno.ENAMETOOLONG:
answer = verdict(text, directory)
if answer["reason"] == COMPONENT:
return (f"a single component is {answer['bytes']:,} bytes, and this filesystem "
f"accepts {name_max(directory):,}")
if answer["reason"] == TOTAL:
return (f"the whole path is {answer['bytes']:,} bytes, and one pathname argument "
f"may hold {path_max(directory) - 1:,}")
return "the kernel refused a name this process could not measure again"
return os.strerror(number) if number else str(exc)
Run the three together and the output is the one this page has been promising. The last line is the one that matters for trust: the module predicted a component failure, and the kernel, asked the same question, gave the same answer.
short name: ok
256-byte component: component (256 bytes, limit 255)
4,220-byte path: total (4220 bytes, limit 4095)
85 hangul characters: ok (255 bytes)
shortened: 255 bytes, ends .csv, digest f87ad7ea
explain: a single component is 300 bytes, and this filesystem accepts 255
measured: errno 36 | predicted: component
| Call | What it answered | What it is for |
|---|---|---|
explain on a 300-byte component | a single component is 300 bytes, and this filesystem accepts 255 | the number and the limit, in one sentence |
explain on a path of 5,001 bytes | the whole path is 5,001 bytes, and one pathname argument may hold 4,095 | the total, named as the total |
explain on a long unix socket path | a unix socket path is longer than the socket address holds: 107 bytes are accepted and the 108th is not part of the address | the case with no errno at all |
shorten, twice on the same Hangul name | 253 bytes, ends .csv, digest 6b51141f | the same key always lands in the same file |
shorten, two names sharing a prefix | 6b99b18f and ceb0a63f | the digests differ, so the files do |
| the shortened name, created on disk | created | a name the module produced is a name the filesystem takes |
The module is deliberately not a path library. It opens, copies and walks nothing; it answers questions about strings and leaves the calls to the caller. That is the smallest useful shape for this problem, because a cache key builder, an uploader deciding whether to rename a file, and a worker that has just caught the exception all ask the same three questions.
8. What the Change Costs, and Where It Lands
Two questions remain before a fix ships: does a long path cost more to use, and what does a refusal cost? Both were measured with the same call – os.stat, 200 calls per run, five runs per row, the median in the table and the range in parentheses.
| Path | Median per call | What it shows |
|---|---|---|
| 1 component | 1.27 µs (1.16–1.34) | the baseline |
| 10 components | 1.52 µs (1.40–1.56) | the walk is per component |
| 30 components | 1.96 µs (1.94–2.28) | still inside the path limit |
| 60 components | 3.00 µs (2.96–3.18) | about twice the walk, at three times the depth |
| a name one byte too long | 3.82 µs (3.77–4.11) | refused with 36, and slower than a stat that succeeds |
| a path past the whole limit | 1.72 µs (1.72–1.76) | refused before the walk begins, at the price of a stat |
The depth rows are the clean ones: the median rises from 1.27 microseconds at one component to 3.00 at sixty – about 29 nanoseconds per component – and the two five-run ranges do not overlap.
The refusal rows are less tidy, and this page will not dress them up. A path refused past the whole limit, before any walk begins, cost 1.72 microseconds, the band of a stat that succeeds, while a name refused at the component cost 3.82 microseconds, about three times as much. The two arms differ in more than the point of refusal; this page did not run the experiment that would separate them, so it does not say why.
What the table is enough for is the retry argument. A refusal is not free, and a worker that retries a failed write without changing the name spends its deadline paying the same price for the same answer while its log records the same number each time. The check that would have stopped it – the verdict in Section 7 – costs no syscall at all, which is a better use of the first microsecond than the retry.
| Surface | Change to make | What the change buys |
|---|---|---|
| Cache keyed by URL or hash input | hash the key to a fixed length before it becomes a filename | no name can grow past the limit, whatever the input |
| Upload or export that names a file after a user string | shorten with the module, and keep the original in a column | the display name survives even when the name cannot |
| Build or backup walking a deep tree | walk from a descriptor, or chdir once and stay relative | depth stops being a limit and becomes a number of calls |
| Process manager or supervisor | start the child with its working directory, not its full path in an argument | the child never has to name where it is |
Health check that uses exists | catch the error and log the errno instead of a boolean | a name problem stops looking like a missing file |
| Deploy script with a long shebang | use /usr/bin/env and keep the line short | the file is a script on every host, not only this one |
The numbers on other platforms are close but not equal, and code that hard-codes 36 misreads them. The table marks what was measured here and what comes from each platform’s own documentation.
| Platform | What a long name is called | How this page knows |
|---|---|---|
| Linux, this host | 36 ENAMETOOLONG | measured throughout; errno(3) lists the same number |
| macOS | 63 ENAMETOOLONG | documented, not measured here: the same name, a different number (xnu bsd/sys/errno.h) |
| Windows, a long file name | 206 ERROR_FILENAME_EXCED_RANGE | documented, not measured here: a system error code, not an errno (System Error Codes) |
| Windows, a long path | 3 ERROR_PATH_NOT_FOUND | documented, not measured here: MAX_PATH is 260 characters (Naming Files, Paths, and Namespaces), and the number is on the same code list |
Both Windows rows are literature values, and worth reading that way. Microsoft’s list gives 206 for a file name or extension too long and 3 for a path that cannot be found; the naming page gives the 260-character limit and the \\?\ prefix that lifts it. This page ran no Windows, and the documentation states the number and the limit, not that a path past the limit surfaces as that number – so the row says documented rather than measured.
Five other runbooks in this series meet the same filesystem at a different point. ELOOP is the limit that looks similar and is not: a link chain that is too deep answers 40. E2BIG takes the same arithmetic to an argument list, where the ceiling is counted per argument and per total. EACCES explains the permission answer that Table 9 meets inside an unsearchable parent.
ENOSPC is the other way a name is refused at write time: the directory is fine and there is no room left to store one. The connection-refused runbook is the network’s version of an immediate answer: whether anything is listening, rather than whether the name fits.
Questions This Page Answers
What does errno 36 mean?
ENAMETOOLONG, “File name too long”: a name was refused because it is longer than the limit that applies to it. On this host that is either a single component over 255 bytes or a whole path over 4095 bytes, and the number alone does not say which.
Is the limit 255 characters or 255 bytes?
Bytes, on byte-oriented Linux filesystems like the two types measured here, counted after the name is encoded for the filesystem. NTFS and exFAT measure a name in UTF-16 code units; this host mounts neither, so how they would answer is not measured here. On this host a Hangul syllable takes three bytes, so a name of 85 syllables fills the component limit and a name of 86 is refused – even though it has 86 characters.
Why is the path limit 4,095 when everything says 4,096?
PATH_MAX counts the terminator a C string spends, so a pathname of 4096 bytes is already one too long for the call. The longest accepted path measured here was 4095 bytes, and one byte more was refused before the kernel walked any of it.
Why does a long name sometimes report “No such file or directory”?
Because the walk reports its first failure. A 300-byte name inside a directory that does not exist answers 2, and inside a directory without search permission it answers 13; the name is measured only when the walk reaches it.
Why did os.path.exists return False for a file that should be there?
Because a predicate has no room to report an error. os.path.exists answered False for a name one byte too long, and so did os.access and glob.glob. Call os.stat and catch the exception when the difference matters.
Why does pathlib raise where os.path returned False?
Path.exists treats only a few numbers as “no such file” and re-raises the rest, so on this host it raised 36 for the same name. That is safer, and it is a behaviour change for code that migrated.
Can I make a symlink to a name that is too long?
Yes. os.symlink stores its target as data, so a 300-byte target was created and read back; the failure arrives when something resolves the link and meets 36.
Why does a long unix socket path raise an error with no errno?
Python checks the path against the socket address structure before the call, so it raises OSError with the message “AF_UNIX path too long” and no errno attribute. The address holds 108 bytes, so the longest usable path is 107.
Why does a script with a long shebang fail with “Exec format error”?
The kernel reads the first line into a fixed buffer of 256 bytes and refuses a longer one with 8. A line that fits but points at a missing interpreter answers 2, the familiar “bad interpreter” message.
How do I reach a directory whose path is past the limit?
Open it once, then use the descriptor: create and open relative names with dir_fd, and use os.fchdir instead of os.chdir. A tree 5,038 bytes deep was usable that way, while its absolute path answered 36 and chdir answered 36.
Why does os.getcwd() return a path that stat refuses?
Because two different calls built it. The kernel’s getcwd fills a PATH_MAX buffer and answers 36 for anything longer, at any buffer size; glibc then falls back to walking the tree, so os.getcwd returns all 5,038 bytes. That string is a report, not a handle: stat and chdir answer 36, and only the open descriptor still works.
How should I shorten a name that is too long?
Deterministically, and in bytes. The module in Section 7 keeps a readable prefix, appends a digest of the whole original name, and keeps the last extension: a long Hangul name with an extension became 253 bytes ending .csv, and two names sharing a prefix got different digests.
Does a longer path cost more to use?
Per component, yes: a stat on a 60-component path took 3.00 microseconds against 1.27 for a single component here, about 29 nanoseconds per component. A refusal costs time as well – 1.72 microseconds before the walk and 3.82 at a component – so a retry that does not change the name pays again for the same answer.
Other errno runbooks: Zero-Crash Python.
Appendix A: The Module and Its Tests, Printed Whole
The folds below print the module and its tests character for character, so the tree can be rebuilt from this page without a repository: five module files, then the four test files that pytest pathguard/tests runs, 40 in all.
the exports pathguard/__init__.py
"""Path limits, measured before the call instead of guessed from the error.
Two numbers decide whether a path is accepted: the bytes in one component, and the bytes in
the whole pathname. The kernel reports both as errno 36, so a caller that only reads the number
cannot tell which one it hit; this package reads the path instead.
"""
from __future__ import annotations
from .explain import explain
from .limits import encoded_length, name_max, path_max
from .shorten import shorten
from .verdict import verdict
__all__ = ["explain", "encoded_length", "name_max", "path_max", "shorten", "verdict"]
the two limits, and how a name is measured pathguard/limits.py
"""The two limits, asked of the filesystem, with the values Linux documents as a fallback."""
from __future__ import annotations
import os
# Linux's fallback values. NAME_MAX is a property of the filesystem: ``pathconf`` reports 255
# on both types this page measured, virtiofs and tmpfs, and 255 is the number Linux's own
# headers document as the fallback. PATH_MAX is the ceiling on one pathname argument to a
# syscall, which the kernel applies before it walks anything.
NAME_MAX = 255
PATH_MAX = 4096
def encoded_length(text: str) -> int:
"""The number of bytes a filesystem counts for a name, not the number of characters.
``os.fsencode`` uses the filesystem encoding with ``surrogateescape``, so a name that came
from a directory listing and did not decode as UTF-8 still measures as the bytes it is.
"""
return len(os.fsencode(text))
def name_max(directory: str = ".") -> int:
"""The longest single component this directory accepts, in bytes."""
try:
return int(os.pathconf(directory, "PC_NAME_MAX"))
except (OSError, ValueError):
return NAME_MAX
def path_max(directory: str = ".") -> int:
"""The longest whole pathname this directory accepts, in bytes.
The number includes the byte a C string spends on its terminator, so a path of
``path_max()`` bytes is already one too long: 4095 bytes are accepted where this returns
4096.
"""
try:
return int(os.pathconf(directory, "PC_PATH_MAX"))
except (OSError, ValueError):
return PATH_MAX
which limit would refuse this path pathguard/verdict.py
"""Which limit a path would hit, answered without calling the kernel."""
from __future__ import annotations
import os
from .limits import encoded_length, name_max, path_max
COMPONENT = "component"
TOTAL = "total"
def verdict(path, directory: str = ".") -> dict:
"""Decide whether ``path`` fits, and name the limit that would refuse it.
The total is checked first because the kernel checks it first: a pathname longer than
``path_max() - 1`` bytes is refused before any of it is walked, so a component problem
inside such a path is never reported. Between the two, the answer this returns is the one
the caller would get, not the one it might prefer.
"""
text = os.fspath(path)
if isinstance(text, bytes):
text = text.decode("utf-8", "surrogateescape")
total = encoded_length(text)
ceiling = path_max(directory) - 1
if total > ceiling:
return {"ok": False, "reason": TOTAL, "component": None, "bytes": total,
"limit": ceiling}
limit = name_max(directory)
for part in text.split("/"):
size = encoded_length(part)
if size > limit:
return {"ok": False, "reason": COMPONENT, "component": part, "bytes": size,
"limit": limit}
return {"ok": True, "reason": "ok", "component": None, "bytes": total, "limit": ceiling}
a deterministic replacement name pathguard/shorten.py
"""A deterministic replacement for a component that is too long to store."""
from __future__ import annotations
import hashlib
from .limits import encoded_length, name_max
def _cut(text: str, budget: int) -> str:
"""The longest prefix of ``text`` whose encoded form fits in ``budget`` bytes.
A character is never split: a three-byte syllable either fits whole or the cut stops before
it, which is what keeps the result a name the filesystem can store and a reader can read.
"""
kept: list[str] = []
used = 0
for character in text:
size = encoded_length(character)
if used + size > budget:
break
kept.append(character)
used += size
return "".join(kept)
def shorten(name: str, limit: int | None = None, digest_chars: int = 8,
keep_extension: bool = True) -> str:
"""Return a name of at most ``limit`` encoded bytes that still identifies the original.
The result is stable: the same name always shortens to the same string, because the digest
is taken over the whole name rather than over the part that survived. The tail of the
digest is what makes two long names that share a prefix land in different files.
"""
ceiling = name_max() if limit is None else limit
if encoded_length(name) <= ceiling:
return name
extension = ""
stem = name
if keep_extension:
head, dot, tail = name.rpartition(".")
if dot and 0 < len(tail) <= 12 and head:
extension, stem = dot + tail, head
if encoded_length(extension) + 10 > ceiling:
extension = ""
digest = hashlib.sha256(name.encode("utf-8", "surrogateescape")).hexdigest()[:digest_chars]
marker = "~" + digest
budget = ceiling - encoded_length(marker) - encoded_length(extension)
return _cut(stem, budget) + marker + extension
one sentence for the exception pathguard/explain.py
"""One sentence for the exception, naming the limit the caller actually hit."""
from __future__ import annotations
import errno
import os
import sys
from .limits import name_max, path_max
from .verdict import COMPONENT, TOTAL, verdict
UNIX_MESSAGE = "AF_UNIX path too long"
# The socket address is not the same size everywhere, so the sentence about it is not either:
# Linux's sockaddr_un holds 108 bytes and macOS's holds 104. Anything else falls back to the
# number measured on this page, which is the Linux one.
SUN_PATH = {"linux": 108, "darwin": 104}.get(sys.platform, 108)
def explain(exc: BaseException, directory: str = ".") -> str:
"""Say which limit refused ``exc``, or hand back what the system said.
errno 36 covers two different limits, so the sentence is built from the path in the
exception rather than from the number. A unix socket path is a third case: Python refuses
it before the kernel sees it, with no errno at all.
"""
number = getattr(exc, "errno", None)
text = getattr(exc, "filename", None) or ""
if number is None and UNIX_MESSAGE in str(exc):
return (f"a unix socket path is longer than the socket address holds: "
f"{SUN_PATH - 1} bytes are accepted and the {SUN_PATH}th is not part of the "
f"address")
if number == errno.ENAMETOOLONG:
answer = verdict(text, directory)
if answer["reason"] == COMPONENT:
return (f"a single component is {answer['bytes']:,} bytes, and this filesystem "
f"accepts {name_max(directory):,}")
if answer["reason"] == TOTAL:
return (f"the whole path is {answer['bytes']:,} bytes, and one pathname argument "
f"may hold {path_max(directory) - 1:,}")
return "the kernel refused a name this process could not measure again"
return os.strerror(number) if number else str(exc)
bytes, fallbacks and the terminator pathguard/tests/test_limits.py
from __future__ import annotations
import pytest
from pathguard.limits import NAME_MAX, PATH_MAX, encoded_length, name_max, path_max
def test_ascii_name_measures_one_byte_per_character():
assert encoded_length("abc") == 3
def test_a_syllable_measures_three_bytes():
assert encoded_length("\uac00") == 3
def test_an_emoji_measures_four_bytes():
assert encoded_length("\U0001f642") == 4
def test_the_reported_component_limit_is_a_positive_number():
assert name_max("/tmp") > 0
def test_the_fallback_is_the_number_linux_documents():
assert (NAME_MAX, PATH_MAX) == (255, 4096)
def test_the_path_limit_is_the_one_the_kernel_applies():
# The number includes the terminator, so the longest accepted path is one byte shorter.
assert path_max("/tmp") == 4096
def test_a_missing_directory_falls_back_instead_of_raising():
assert name_max("/nonexistent-directory-for-this-test") == NAME_MAX
assert path_max("/nonexistent-directory-for-this-test") == PATH_MAX
def test_a_name_that_did_not_decode_still_measures():
assert encoded_length(b"\xff\xfe".decode("utf-8", "surrogateescape")) == 2
@pytest.mark.parametrize("character,count,width",
[("a", 255, 1), ("\u00e9", 127, 2), ("\uac00", 85, 3),
("\U0001f642", 63, 4)])
def test_each_width_reaches_the_limit_at_its_own_count(character, count, width):
assert encoded_length(character * count) == count * width
which limit, and which component pathguard/tests/test_verdict.py
from __future__ import annotations
from pathguard.verdict import COMPONENT, TOTAL, verdict
def test_a_short_path_passes(tmp_path):
assert verdict(str(tmp_path / "report.csv"), str(tmp_path))["ok"] is True
def test_a_component_of_255_bytes_passes(tmp_path):
assert verdict(str(tmp_path / ("n" * 255)), str(tmp_path))["reason"] == "ok"
def test_a_component_of_256_bytes_is_named(tmp_path):
answer = verdict(str(tmp_path / ("n" * 256)), str(tmp_path))
assert answer["reason"] == COMPONENT
assert answer["bytes"] == 256
assert answer["limit"] == 255
assert answer["component"] == "n" * 256
def test_a_whole_path_past_the_limit_is_the_walk_that_cannot_start(tmp_path):
answer = verdict("/" + "/".join(["d" * 200] * 21))
assert answer["reason"] == TOTAL
assert answer["limit"] == 4095
def test_the_total_is_checked_before_the_component():
# Both limits are broken; the kernel refuses the pathname before it walks it.
answer = verdict("/" + "/".join(["d" * 250] * 17))
assert answer["reason"] == TOTAL
def test_characters_are_not_bytes(tmp_path):
assert verdict(str(tmp_path / ("\uac00" * 85)), str(tmp_path))["reason"] == "ok"
assert verdict(str(tmp_path / ("\uac00" * 86)), str(tmp_path))["reason"] == COMPONENT
def test_the_component_is_the_one_that_does_not_fit(tmp_path):
answer = verdict(f"{tmp_path}/ok/{'x' * 300}/leaf")
assert answer["component"] == "x" * 300
def test_a_relative_path_is_measured_as_written():
assert verdict("a" * 255)["reason"] == "ok"
assert verdict("a" * 256)["reason"] == COMPONENT
def test_a_bytes_path_is_measured(tmp_path):
assert verdict(b"/tmp/" + b"n" * 256)["reason"] == COMPONENT
stability, distinctness, and no split character pathguard/tests/test_shorten.py
from __future__ import annotations
from pathguard.limits import encoded_length
from pathguard.shorten import shorten
def test_a_name_that_fits_is_returned_unchanged():
assert shorten("report.csv", limit=255) == "report.csv"
def test_a_long_ascii_name_reaches_the_limit_exactly():
name = shorten("a" * 400, limit=255)
assert encoded_length(name) <= 255
assert len(name) == 255
def test_the_last_extension_survives():
assert shorten("a" * 400 + ".csv", limit=255).endswith(".csv")
def test_only_the_last_suffix_is_kept():
name = shorten("a" * 400 + ".tar.gz", limit=255)
assert name.endswith(".gz")
assert not name.endswith(".tar.gz")
def test_the_marker_carries_a_digest():
name = shorten("a" * 400, limit=255)
assert "~" in name
assert len(name.split("~")[1].split(".")[0]) == 8
def test_the_same_name_shortens_the_same_way():
assert shorten("a" * 400, limit=255) == shorten("a" * 400, limit=255)
def test_two_names_sharing_a_prefix_stay_apart():
left = shorten("a" * 400 + "-one", limit=64)
right = shorten("a" * 400 + "-two", limit=64)
assert left != right
def test_a_character_is_never_split():
name = shorten("\uac00" * 200, limit=255)
assert encoded_length(name) <= 255
name.encode("utf-8") # a split character would not survive this
assert "\ufffd" not in name
def test_the_limit_counts_bytes_not_characters():
name = shorten("\U0001f642" * 200, limit=255)
assert encoded_length(name) <= 255
assert len(name) < 255
def test_shortening_never_grows_a_name():
for limit in (32, 64, 128, 255):
assert encoded_length(shorten("b" * 300, limit=limit)) <= limit
def test_a_hidden_file_keeps_no_extension():
name = shorten(".configuration-" + "c" * 300, limit=64)
assert encoded_length(name) <= 64
assert name.startswith(".")
the sentence for each case pathguard/tests/test_explain.py
from __future__ import annotations
import errno
import os
import shutil
import socket
import sys
import tempfile
import pytest
from pathguard.explain import SUN_PATH, explain
def _error(path: str) -> OSError:
try:
os.stat(path)
except OSError as exc:
return exc
raise AssertionError("the call unexpectedly succeeded")
def test_a_long_component_is_named_as_one(tmp_path):
sentence = explain(_error(str(tmp_path / ("n" * 300))))
assert "single component is 300 bytes" in sentence
assert "255" in sentence
def test_a_long_path_is_named_as_the_total(tmp_path):
sentence = explain(_error("/" + "z" * 5000))
assert "whole path is 5,001 bytes" in sentence
assert "4,095" in sentence
def test_a_unix_socket_path_is_its_own_case():
sentence = explain(OSError("AF_UNIX path too long"))
assert str(SUN_PATH - 1) in sentence
assert str(SUN_PATH) in sentence
def test_the_socket_boundary_is_the_one_the_sentence_names():
"""The sentence prints a boundary, so the test binds at both sides of it.
SUN_PATH - 1 bytes must bind and SUN_PATH must be refused with no errno, which is what the
page measured and what the explanation claims. The size itself is platform-specific, so the
test is skipped where the constant is another platform's.
"""
if sys.platform != "linux":
pytest.skip("Linux AF_UNIX path limit test")
base = tempfile.mkdtemp(dir="/tmp")
try:
for length, binds in ((SUN_PATH - 1, True), (SUN_PATH, False)):
path = os.path.join(base, "s" * (length - len(base) - 1))
assert len(path.encode()) == length
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
if binds:
sock.bind(path)
assert os.path.exists(path)
else:
try:
sock.bind(path)
except OSError as exc:
assert exc.errno is None
assert str(exc) == "AF_UNIX path too long"
else:
raise AssertionError(f"a path of {length} bytes was bound")
finally:
sock.close()
if os.path.exists(path):
os.unlink(path)
finally:
shutil.rmtree(base, ignore_errors=True)
def test_another_number_is_handed_back_as_the_system_says_it():
assert explain(FileNotFoundError(errno.ENOENT, "No such file or directory")) == \
"No such file or directory"
def test_an_error_without_a_filename_still_answers():
assert "could not measure" in explain(OSError(errno.ENAMETOOLONG, "File name too long"))
def test_the_sentence_names_the_limit_the_filesystem_reports(tmp_path):
sentence = explain(_error(str(tmp_path / ("n" * 300))))
assert str(os.pathconf(str(tmp_path), "PC_NAME_MAX")) in sentence
def test_a_plain_exception_without_an_errno_is_described():
assert explain(ValueError("boom")) == "boom"
Appendix B: The Probes, Printed Whole
These produced every figure in Tables 2 through 12 and the counts the body quotes about its own tree. Each writes one record under results/ with the arms its table shows – one run for an errno, five for a duration – and the helper they share comes first.
one record, one arm per condition sandbox/probelib.py
"""Shared helpers for the probes: one record per probe, one arm per condition.
An arm is a label and the runs of one callable. An arm that answers with an errno runs once,
because an errno does not move between runs; an arm that answers with a duration runs five
times so the page can print a median and the range it came from.
"""
from __future__ import annotations
import json
import os
import pathlib
import shutil
import statistics
import tempfile
import time
import traceback
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
def scratch(prefix: str) -> str:
"""A fresh directory under /tmp, removed by clean()."""
return tempfile.mkdtemp(prefix=prefix, dir="/tmp")
def clean(path: str) -> None:
shutil.rmtree(path, ignore_errors=True)
def describe(call) -> dict:
"""Run one call and describe what a caller would receive."""
try:
value = call()
return {"ok": True, "errno": None, "exception": None, "message": None, "value": value}
except OSError as exc:
return {"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
"message": str(exc), "strerror": exc.strerror}
except Exception as exc: # noqa: BLE001 - a probe reports what happened, whatever it is
return {"ok": False, "errno": None, "exception": type(exc).__name__,
"message": str(exc), "strerror": None}
def arm(label: str, call, repeats: int = 1) -> dict:
runs = [describe(call) for _ in range(repeats)]
return {"label": label, "runs": runs}
def timed(label: str, call, repeats: int = 5) -> dict:
"""Repeat a callable that returns (value, seconds) and record every run."""
runs = []
for _ in range(repeats):
try:
value, seconds = call()
runs.append({"ok": True, "value": value, "ns": round(seconds * 1e9)})
except OSError as exc:
runs.append({"ok": False, "errno": exc.errno, "exception": type(exc).__name__})
return {"label": label, "runs": runs}
def median_ns(record: dict) -> float:
return statistics.median([run["ns"] for run in record["runs"]])
def host() -> dict:
import platform
import sys
def read(path: str) -> str:
try:
return pathlib.Path(path).read_text().strip()
except OSError:
return ""
return {
"kernel": platform.release(),
"python": sys.version.split()[0],
"machine": platform.machine(),
"cpus": os.cpu_count(),
"sh": os.path.realpath("/bin/sh").rsplit("/", 1)[-1],
"uid": os.getuid(),
"page_size": os.sysconf("SC_PAGE_SIZE"),
"umask": oct(os.umask(os.umask(0o022))),
"libc": " ".join(platform.libc_ver()).strip(),
"boot_cmdline": read("/proc/cmdline")[:120],
}
def mount_of(path: str) -> dict:
"""The mount entry that owns a path: filesystem type and options, from /proc/mounts."""
target = os.path.realpath(path)
best = None
for line in pathlib.Path("/proc/mounts").read_text().splitlines():
fields = line.split()
if len(fields) < 4:
continue
point = fields[1].replace("\\040", " ")
if target == point or target.startswith(point.rstrip("/") + "/"):
if best is None or len(point) > len(best[1]):
best = (fields[2], point, fields[3])
if best is None:
return {"fstype": None, "mount": None, "options": None}
return {"device": None, "fstype": best[0], "mount": best[1], "options": best[2]}
def write(name: str, payload: dict) -> pathlib.Path:
RESULTS.mkdir(parents=True, exist_ok=True)
path = RESULTS / name
path.write_text(json.dumps(payload, indent=1, ensure_ascii=False, default=str) + "\n",
encoding="utf-8")
print("wrote", path, len(json.dumps(payload)))
return path
def guard(probe: str, body) -> None:
"""Run a probe body and write a record even if it fails, so a failure is visible."""
started = time.time()
try:
body()
except Exception: # noqa: BLE001 - the record must say what went wrong
traceback.print_exc()
record = {"probe": probe, "failed": True, "seconds": round(time.time() - started, 2)}
write(f"{probe}_failed.json", record)
raise
print(f"{probe} finished in {time.time() - started:.1f} s")
the host, the number and the filesystems sandbox/01_facts.py
"""The host, the number, the filesystems, and every limit the page's tables stand on."""
from __future__ import annotations
import errno
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
DIRS = ["/workspace", "/tmp", "/dev/shm"]
def facts() -> dict:
numbers = {name: int(getattr(errno, name)) for name in
("ENAMETOOLONG", "ENOENT", "ELOOP", "EACCES", "EINVAL", "ENOTDIR", "EBADF",
"ENOSPC", "E2BIG")}
return {
"host": probelib.host(),
"numbers": {
**numbers,
"message_for_36": os.strerror(numbers["ENAMETOOLONG"]),
"name_for_36": errno.errorcode[numbers["ENAMETOOLONG"]],
"message_for_40": os.strerror(numbers["ELOOP"]),
},
"filesystems": [{**probelib.mount_of(directory), "path": directory,
"name_max": os.pathconf(directory, "PC_NAME_MAX"),
"path_max": os.pathconf(directory, "PC_PATH_MAX"),
"link_max": os.pathconf(directory, "PC_LINK_MAX")}
for directory in DIRS],
"arms": [],
"notes": {},
}
def main() -> None:
record = facts()
# The kernel's own limits, as this process reads them.
record["arms"].append(probelib.arm("pathconf_name_max", lambda: os.pathconf("/tmp", "PC_NAME_MAX")))
record["arms"].append(probelib.arm("pathconf_path_max", lambda: os.pathconf("/tmp", "PC_PATH_MAX")))
record["arms"].append(probelib.arm("empty_component", lambda: os.stat("/tmp//")))
record["arms"].append(probelib.arm("trailing_slash_on_a_file", lambda: os.stat("/etc/hostname/")))
record["arms"].append(probelib.arm("dot_and_dotdot", lambda: os.stat("/tmp/./../tmp/.")))
# How a name is measured: characters or bytes. A four-character name in UTF-8 is compared
# with its encoded length, on the same call.
name = "\uac00\uac01\uac02\uac03"
record["notes"]["multibyte_name"] = {
"name": name,
"characters": len(name),
"bytes": len(name.encode("utf-8")),
"encode": "utf-8",
}
record["notes"]["ascii_name"] = {"characters": 4, "bytes": 4}
# Why the page talks about bytes: the filesystem stores what the encoder produced.
encoded = os.fsencode(name)
record["notes"]["fsencode_roundtrip"] = os.fsdecode(encoded) == name
probelib.write("01_facts.json", record)
if __name__ == "__main__":
main()
one name at six lengths on three mounts (two filesystem types) sandbox/02_component.py
"""The component limit: one name, three mounts, two filesystem types, every length around 255."""
from __future__ import annotations
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
DIRS = ["/workspace/probe_component", "/tmp/p48_component", "/dev/shm/p48_component"]
LENGTHS = [1, 254, 255, 256, 257, 512]
def create(directory: str):
def call():
os.makedirs(directory, exist_ok=True)
return call
def main() -> None:
record = {"probe": "02_component", "host": probelib.host(), "arms": [], "notes": {}}
for directory in DIRS:
try:
create(directory)()
record["notes"].setdefault("fstype", {})[directory] = probelib.mount_of(directory)
except OSError as exc:
record["notes"].setdefault("setup_error", {})[directory] = str(exc)
for directory in DIRS:
if not os.path.isdir(directory):
continue
label_root = probelib.mount_of(directory).get("fstype", "unknown")
for length in LENGTHS:
name = "n" * length
path = os.path.join(directory, name)
def open_create(path=path):
descriptor = os.open(path, os.O_CREAT | os.O_WRONLY, 0o644)
os.close(descriptor)
os.unlink(path)
def mkdir_once(path=path):
os.mkdir(path)
os.rmdir(path)
def stat_missing(path=path):
os.stat(path)
def unlink_missing(path=path):
os.unlink(path)
record["arms"].append({
"label": f"{label_root}:{length}:open",
"runs": [probelib.describe(open_create)],
"directory": directory, "length": length,
})
record["arms"].append({
"label": f"{label_root}:{length}:mkdir",
"runs": [probelib.describe(mkdir_once)],
"directory": directory, "length": length,
})
# The same length with no file in the way: the walk still has to check the name.
record["arms"].append({
"label": f"{label_root}:{length}:stat",
"runs": [probelib.describe(stat_missing)],
"directory": directory, "length": length,
})
record["arms"].append({
"label": f"{label_root}:{length}:unlink",
"runs": [probelib.describe(unlink_missing)],
"directory": directory, "length": length,
})
# The reported limit and the enforced one are the same number on all three.
record["notes"]["name_max"] = {directory: os.pathconf(directory, "PC_NAME_MAX")
for directory in DIRS if os.path.isdir(directory)}
record["notes"]["root_length"] = {directory: len(directory.encode())
for directory in DIRS if os.path.isdir(directory)}
for directory in DIRS:
probelib.clean(directory)
probelib.write("02_component.json", record)
if __name__ == "__main__":
main()
the byte that ends a path, and the walk that has none sandbox/03_path.py
"""The path limit: 4096 bytes, the one byte that is the terminator, and the walk that has none."""
from __future__ import annotations
import ctypes
import os
import pathlib
import subprocess
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
BASE = "/tmp/p48_path"
DEEP = "/tmp/p48_deep"
COMPONENT = "d" * 200
LIBC = ctypes.CDLL(None, use_errno=True)
LIBC.syscall.restype = ctypes.c_long
SYS_GETCWD = 79 # x86_64
def libc_getcwd(size: int) -> int:
"""The C library's getcwd with a buffer of exactly ``size`` bytes."""
buffer = ctypes.create_string_buffer(size)
ctypes.set_errno(0)
if not LIBC.getcwd(buffer, ctypes.c_size_t(size)):
code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
return len(buffer.value)
def raw_getcwd(size: int) -> int:
"""The getcwd system call itself, bypassing the C library, with ``size`` bytes."""
buffer = ctypes.create_string_buffer(size)
ctypes.set_errno(0)
if LIBC.syscall(ctypes.c_long(SYS_GETCWD), buffer, ctypes.c_size_t(size)) < 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
return len(buffer.value)
def build_chain(base: str, target: int) -> str:
"""A nested directory whose absolute path is exactly ``target`` bytes long.
Each step is created relative to the previous directory's descriptor, because the path this
builds is longer than a single call may name once it is done.
"""
os.makedirs(base, exist_ok=True)
descriptor = os.open(base, os.O_RDONLY)
current = base
try:
while len(current) + 1 + 200 <= target:
os.mkdir(COMPONENT, dir_fd=descriptor)
following = os.open(COMPONENT, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
current = f"{current}/{COMPONENT}"
room = target - len(current) - 1
if room:
name = "e" * room
os.mkdir(name, dir_fd=descriptor)
following = os.open(name, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
current = f"{current}/{name}"
finally:
os.close(descriptor)
if len(current) != target:
raise SystemExit(f"built a {len(current)}-byte path, wanted {target}")
return current
def deep_tree(base: str, levels: int) -> tuple[str, int]:
"""A tree whose absolute path is well past 4096 bytes, reached one directory at a time.
Returns the path it built and the descriptor of the deepest directory, still open: the
path itself can no longer be passed to a call, which is the point of the measurement.
"""
os.makedirs(base, exist_ok=True)
descriptor = os.open(base, os.O_RDONLY)
for _ in range(levels):
os.mkdir(COMPONENT, dir_fd=descriptor)
following = os.open(COMPONENT, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
return base + "/" + "/".join([COMPONENT] * levels), descriptor
def main() -> None:
probelib.clean(BASE)
probelib.clean(DEEP)
record = {"probe": "03_path", "host": probelib.host(), "arms": [], "notes": {}}
parent = build_chain(BASE, 4080)
# The threshold: a file whose whole path is exactly 4095 bytes, then 4096, then 4097.
for total in (4094, 4095, 4096, 4097):
name = "f" * (total - len(parent) - 1)
path = f"{parent}/{name}"
assert len(path) == total
created = probelib.describe(lambda path=path: open(path, "w").close())
record["arms"].append({"label": f"create:{total}", "runs": [created], "total": total})
record["arms"].append({"label": f"stat:{total}", "runs": [probelib.describe(
lambda path=path: os.stat(path))], "total": total})
# 4095 is a path the kernel walks: the file beside it answers ENOENT, not 36.
missing = f"{parent}/{'g' * (4095 - len(parent) - 1)}"
record["arms"].append({"label": "stat:4095:missing", "runs": [probelib.describe(
lambda: os.stat(missing))], "total": len(missing)})
# The same tree, past 4096, reached by descriptor and by relative name.
deep, descriptor = deep_tree(DEEP, 25)
record["notes"]["deep_path"] = deep
record["notes"]["deep_length"] = len(deep)
record["notes"]["deep_levels"] = 25
original = os.getcwd()
try:
record["arms"].append({"label": "relative:create_by_descriptor", "runs": [
probelib.describe(lambda: open("short.txt", "w", opener=lambda path, flags:
os.open(path, flags, dir_fd=descriptor)).close())]})
record["arms"].append({"label": "relative:open_by_descriptor", "runs": [probelib.describe(
lambda: os.open("short.txt", os.O_RDONLY, dir_fd=descriptor))]})
record["arms"].append({"label": "absolute:stat_past_path_max", "runs": [probelib.describe(
lambda: os.stat(f"{deep}/short.txt"))], "total": len(deep) + 10})
long_relative = "/".join(["d" * 200] * 21)
record["arms"].append({"label": "relative:past_path_max", "runs": [probelib.describe(
lambda: os.stat(long_relative, dir_fd=descriptor))], "total": len(long_relative)})
# /proc answers a link with a copy of the path, and that copy has the same ceiling.
record["arms"].append({"label": "readlink:/proc/self/fd", "runs": [probelib.describe(
lambda: os.readlink(f"/proc/self/fd/{descriptor}"))], "total": len(deep)})
# What a program is told its working directory is, after it walked in there: the string
# cannot be passed to chdir either, but a descriptor can be handed to fchdir.
record["arms"].append({"label": "chdir:past_path_max", "runs": [probelib.describe(
lambda: os.chdir(deep))], "total": len(deep)})
record["arms"].append({"label": "fchdir:past_path_max", "runs": [probelib.describe(
lambda: os.fchdir(descriptor))]})
# getcwd is the one call that reports this directory instead of naming it. The raw
# syscall is asked twice (4,096 bytes, then 16,384), the C library twice (4,096, then
# 6,000), and Python's os.getcwd() once - it passes a 1 KiB buffer of its own and grows
# it on ERANGE. Both raw calls fail: the buffer that overflows is the kernel's PATH_MAX
# one, so a larger buffer of the caller's own changes nothing.
record["arms"].append({"label": "getcwd:raw:4096", "runs": [probelib.describe(
lambda: raw_getcwd(4096))], "buffer": 4096})
record["arms"].append({"label": "getcwd:raw:16384", "runs": [probelib.describe(
lambda: raw_getcwd(16384))], "buffer": 16384})
record["arms"].append({"label": "getcwd:libc:4096", "runs": [probelib.describe(
lambda: libc_getcwd(4096))], "buffer": 4096})
record["arms"].append({"label": "getcwd:libc:6000", "runs": [probelib.describe(
lambda: libc_getcwd(6000))], "buffer": 6000})
record["arms"].append({"label": "getcwd:past_path_max", "runs": [probelib.describe(
lambda: len(os.getcwd()))]})
record["arms"].append({"label": "getcwd:same_as_walk", "runs": [probelib.describe(
lambda: os.getcwd() == deep)]})
record["arms"].append({"label": "getcwd:pwd_command", "runs": [probelib.describe(
lambda: len(subprocess.run(["/bin/sh", "-c", "pwd"], capture_output=True,
text=True).stdout.strip()))]})
record["notes"]["getcwd_error_name"] = os.strerror(34)
record["arms"].append({"label": "readlink:/proc/self/cwd", "runs": [probelib.describe(
lambda: os.readlink("/proc/self/cwd"))], "total": len(deep)})
finally:
os.chdir(original)
os.close(descriptor)
# The number pathconf reports, next to the number the walk enforces.
record["notes"]["pathconf"] = {directory: os.pathconf(directory, "PC_PATH_MAX")
for directory in ("/tmp", "/workspace", "/dev/shm")}
record["notes"]["base_length"] = len(BASE)
probelib.write("03_path.json", record)
if __name__ == "__main__":
main()
four alphabets and one multibyte tree sandbox/04_bytes.py
"""The limit counts bytes: the same name in ASCII, in two, three and four-byte characters."""
from __future__ import annotations
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
ROOT = "/tmp/p48_bytes"
BASE = "/tmp/p48_bytes_deep"
# One character of each width, and the name length at which the encoded form crosses 255.
ALPHABETS = [("ascii", "a", 1), ("latin-1", "\u00e9", 2), ("hangul", "\uac00", 3),
("emoji", "\U0001f642", 4)]
def main() -> None:
probelib.clean(ROOT)
probelib.clean(BASE)
os.makedirs(ROOT, exist_ok=True)
record = {"probe": "04_bytes", "host": probelib.host(), "arms": [], "notes": {}}
for label, character, width in ALPHABETS:
assert len(character.encode("utf-8")) == width
limit = 255 // width
for count in (limit - 1, limit, limit + 1):
name = character * count
path = os.path.join(ROOT, name)
def create(path=path):
descriptor = os.open(path, os.O_CREAT | os.O_WRONLY, 0o644)
os.close(descriptor)
os.unlink(path)
record["arms"].append({
"label": f"{label}:{count}",
"runs": [probelib.describe(create)],
"characters": count, "bytes": len(name.encode("utf-8")), "width": width,
})
# The count the caller sees and the count the filesystem sees, on one name.
sample = "\uac00" * 85
record["notes"]["hangul_85"] = {"characters": len(sample), "bytes": len(sample.encode()),
"fsencode": len(os.fsencode(sample))}
sample = "\uac00" * 86
record["notes"]["hangul_86"] = {"characters": len(sample), "bytes": len(sample.encode())}
# A whole path whose characters fit in 4096 and whose bytes do not.
os.makedirs(BASE, exist_ok=True)
descriptor = os.open(BASE, os.O_RDONLY)
component = "\uac00" * 85
levels = 0
try:
while levels < 16:
os.mkdir(component, dir_fd=descriptor)
following = os.open(component, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
levels += 1
current = BASE + "/" + "/".join([component] * levels)
record["notes"]["multibyte_path"] = {
"characters": len(current), "bytes": len(current.encode()),
"levels": levels, "component_characters": len(component),
"component_bytes": len(component.encode()),
}
record["arms"].append({"label": "multibyte_path:stat", "runs": [probelib.describe(
lambda: os.stat(current))], "bytes": len(current.encode()),
"characters": len(current)})
record["arms"].append({"label": "multibyte_path:create_by_descriptor", "runs": [
probelib.describe(lambda: open("leaf.txt", "w", opener=lambda path, flags:
os.open(path, flags, dir_fd=descriptor)).close())]})
finally:
os.close(descriptor)
probelib.write("04_bytes.json", record)
if __name__ == "__main__":
main()
twenty surfaces on one long name sandbox/05_surface.py
"""Every surface a program uses on a path, given one name that is one byte too long."""
from __future__ import annotations
import glob
import os
import pathlib
import shutil
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
ROOT = "/tmp/p48_surface"
LONG = "n" * 256
SHORT = "s" * 255
def main() -> None:
probelib.clean(ROOT)
os.makedirs(ROOT, exist_ok=True)
long_path = os.path.join(ROOT, LONG)
short_path = os.path.join(ROOT, SHORT)
with open(short_path, "w") as handle:
handle.write("x")
link = os.path.join(ROOT, "link")
os.symlink(short_path, link)
record = {"probe": "05_surface", "host": probelib.host(), "arms": [],
"notes": {"long_name_bytes": len(LONG), "short_name_bytes": len(SHORT),
"root": ROOT}}
calls = [
("os.stat", lambda: os.stat(long_path)),
("os.lstat", lambda: os.lstat(long_path)),
("os.stat_short", lambda: os.stat(short_path)),
("os.access", lambda: os.access(long_path, os.W_OK)),
("os.path.exists", lambda: os.path.exists(long_path)),
("os.path.isfile", lambda: os.path.isfile(long_path)),
("os.path.isdir", lambda: os.path.isdir(long_path)),
("pathlib.exists", lambda: pathlib.Path(long_path).exists()),
("pathlib.is_file", lambda: pathlib.Path(long_path).is_file()),
("pathlib.stat", lambda: pathlib.Path(long_path).stat()),
("os.path.getsize", lambda: os.path.getsize(long_path)),
("os.pathconf", lambda: os.pathconf(long_path, "PC_NAME_MAX")),
("os.listdir", lambda: os.listdir(long_path)),
("os.scandir", lambda: list(os.scandir(long_path))),
("glob.glob", lambda: glob.glob(long_path)),
("pathlib.glob", lambda: list(pathlib.Path(ROOT).glob(LONG))),
("os.mkdir", lambda: os.mkdir(long_path)),
("os.rmdir", lambda: os.rmdir(long_path)),
("os.unlink", lambda: os.unlink(long_path)),
("os.rename_source", lambda: os.rename(long_path, os.path.join(ROOT, "moved"))),
("os.rename_target", lambda: os.rename(short_path, long_path)),
("os.link", lambda: os.link(short_path, long_path)),
("os.symlink_to_long", lambda: os.symlink(long_path, os.path.join(ROOT, "x"))),
("os.readlink", lambda: os.readlink(link)),
("os.chmod", lambda: os.chmod(long_path, 0o600)),
("os.utime", lambda: os.utime(long_path, None)),
("builtin_open_read", lambda: open(long_path).read()),
("builtin_open_write", lambda: open(long_path, "w").close()),
("shutil.copyfile_target", lambda: shutil.copyfile(short_path, long_path)),
("os.makedirs", lambda: os.makedirs(os.path.join(long_path, "inner"))),
("pathlib.write_text", lambda: pathlib.Path(long_path).write_text("x")),
]
for label, call in calls:
record["arms"].append({"label": label, "runs": [probelib.describe(call)]})
# What the exception carries: the path it was given, and what its message prints.
deep = "/" + "z" * 5000
for label, path in (("name_256", long_path), ("path_5000", deep)):
try:
os.stat(path)
except OSError as exc:
record["arms"].append({"label": f"exception:{label}", "runs": [{
"ok": False, "errno": exc.errno, "exception": type(exc).__name__,
"filename_chars": len(exc.filename or ""),
"filename_bytes": len((exc.filename or "").encode()),
"message_chars": len(str(exc)),
"message_holds_whole_path": (exc.filename or "") in str(exc),
"input_chars": len(path),
}]})
# A walk over the directory never reports the name: it cannot be created to begin with.
record["notes"]["listing"] = len(os.listdir(ROOT))
record["notes"]["short_survives"] = os.path.exists(short_path)
probelib.write("05_surface.json", record)
if __name__ == "__main__":
main()
socket, shebang, symlink, and the order of a walk sandbox/06_limits.py
"""Three other ceilings a long path meets, and the order in which a walk reports them."""
from __future__ import annotations
import os
import pathlib
import socket
import subprocess
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
ROOT = "/tmp/p48_limits"
def unix_bind(length: int) -> dict:
path = "/tmp/p48_limits/" + "u" * (length - len("/tmp/p48_limits/"))
assert len(path.encode()) == length
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.bind(path)
return {"ok": True, "length": length, "errno": None, "exception": None}
except OSError as exc:
return {"ok": False, "length": length, "errno": exc.errno,
"exception": type(exc).__name__, "message": str(exc)}
finally:
sock.close()
try:
os.unlink(path)
except OSError:
pass
def shebang(interpreter_length: int) -> dict:
"""Run a script whose interpreter path is a given length; report the execve outcome."""
interpreter = "/tmp/p48_limits/" + "i" * (interpreter_length - len("/tmp/p48_limits/"))
script = os.path.join(ROOT, f"script_{interpreter_length}")
line = "#!" + interpreter
with open(script, "w") as handle:
handle.write(line + "\nprint('hi')\n")
os.chmod(script, 0o755)
pid = os.fork()
if pid == 0: # child
try:
os.execve(script, [script], {"PATH": "/usr/bin:/bin"})
except OSError as exc:
os._exit(100 + min(exc.errno or 0, 99))
os._exit(0)
_, status = os.waitpid(pid, 0)
code = os.waitstatus_to_exitcode(status)
return {"ok": code == 0, "line_bytes": len(line), "interpreter_bytes": interpreter_length,
"exit": code, "errno": code - 100 if 100 <= code < 200 else None}
def main() -> None:
probelib.clean(ROOT)
os.makedirs(ROOT, exist_ok=True)
record = {"probe": "06_limits", "host": probelib.host(), "arms": [], "notes": {}}
# 1. A unix socket path lives in sun_path, 108 bytes including its terminator.
for length in (100, 106, 107, 108, 109, 200):
record["arms"].append({"label": f"unix_bind:{length}", "runs": [unix_bind(length)],
"length": length})
record["notes"]["sun_path"] = 108
# 2. A shebang line is read into a fixed buffer; past it the kernel does not run the file.
for length in (120, 253, 254, 255, 256, 300):
record["arms"].append({"label": f"shebang:{length}", "runs": [shebang(length)],
"length": length})
# 3. A symlink stores its target, and only resolving it meets the component limit.
target = "t" * 300
link = os.path.join(ROOT, "long_target")
record["arms"].append({"label": "symlink_create", "runs": [probelib.describe(
lambda: os.symlink(target, link))]})
record["arms"].append({"label": "symlink_stat", "runs": [probelib.describe(
lambda: os.stat(link))]})
record["arms"].append({"label": "symlink_readlink", "runs": [probelib.describe(
lambda: len(os.readlink(link)))]})
# 4. The order the walk reports things in.
os.makedirs(os.path.join(ROOT, "exists"), exist_ok=True)
os.makedirs(os.path.join(ROOT, "noexec"), exist_ok=True)
os.chmod(os.path.join(ROOT, "noexec"), 0o000)
long_name = "n" * 300
cases = {
"long_component_resolvable_parent": os.path.join(ROOT, "exists", long_name),
"long_component_missing_parent": os.path.join(ROOT, "missing", long_name),
"long_component_unsearchable_parent": os.path.join(ROOT, "noexec", long_name),
"short_component_missing_parent": os.path.join(ROOT, "missing", "leaf"),
"total_past_limit_missing_parent": "/" + "z" * 3000 + "/" + "y" * 1200,
}
for label, path in cases.items():
record["arms"].append({"label": f"precedence:{label}", "runs": [probelib.describe(
lambda path=path: os.stat(path))], "bytes": len(path.encode())})
os.chmod(os.path.join(ROOT, "noexec"), 0o755)
# 5. A printf-style tool message, for the same failure, as an operator meets it.
result = subprocess.run([sys.executable, "-c",
"import os;os.stat('/tmp/p48_limits/exists/' + 'n'*300)"],
capture_output=True, text=True,
env={**os.environ, "PYTHONPATH": ""})
record["notes"]["traceback"] = {"rc": result.returncode,
"last_line": result.stderr.strip().splitlines()[-1]}
probelib.write("06_limits.json", record)
if __name__ == "__main__":
main()
the module on the paths it was written for sandbox/07_module.py
"""The module on the paths it was written for: a verdict, a shortening, and a sentence."""
from __future__ import annotations
import os
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
import probelib # noqa: E402
from pathguard import explain, shorten, verdict # noqa: E402
ROOT = "/tmp/p48_module"
def chain(base: str, target: int) -> str:
"""A directory whose absolute path is exactly ``target`` bytes, built one descriptor at a time."""
os.makedirs(base, exist_ok=True)
descriptor = os.open(base, os.O_RDONLY)
current = base
try:
while len(current) + 1 + 200 <= target:
os.mkdir("d" * 200, dir_fd=descriptor)
following = os.open("d" * 200, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
current = f"{current}/{'d' * 200}"
room = target - len(current) - 1
if room:
os.mkdir("e" * room, dir_fd=descriptor)
following = os.open("e" * room, os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
current = f"{current}/{'e' * room}"
finally:
os.close(descriptor)
return current + "/leaf"
def main() -> None:
probelib.clean(ROOT)
os.makedirs(ROOT, exist_ok=True)
record = {"probe": "07_module", "host": probelib.host(), "arms": [], "notes": {}}
def predict(label: str, path: str) -> None:
answer = verdict(path)
record["arms"].append({"label": f"verdict:{label}", "runs": [{
"ok": answer["ok"], "reason": answer["reason"], "bytes": answer["bytes"],
"limit": answer["limit"], "kernel": probelib.describe(lambda: os.stat(path)),
}]})
predict("ok", os.path.join(ROOT, "report.csv"))
predict("component_255", ROOT + "/" + "n" * 255)
predict("component_256", ROOT + "/" + "n" * 256)
exact = chain("/tmp/p48_module_chain", 4090)
assert len(exact) == 4095, len(exact)
predict("total_4095", exact)
predict("total_4096", exact + "x")
predict("hangul_85", ROOT + "/" + "\uac00" * 85)
predict("hangul_86", ROOT + "/" + "\uac00" * 86)
# The same verdict, asked after the fact about the path inside an exception.
for label, path in (("long_component", ROOT + "/" + "n" * 300),
("long_total", "/" + "z" * 5000)):
try:
os.stat(path)
exception = None
except OSError as exc:
exception = exc
record["arms"].append({"label": f"explain:{label}", "runs": [{
"ok": True, "errno": getattr(exception, "errno", None),
"sentence": explain(exception) if exception else "",
}]})
# A unix socket path, which never reaches the kernel: Python refuses it with no errno.
record["arms"].append({"label": "explain:unix", "runs": [{
"ok": True, "sentence": explain(OSError("AF_UNIX path too long"))}]})
# Shortening: the same name twice, then two names that share a prefix.
name = "\uac00" * 120 + ".csv"
first, second = shorten(name), shorten(name)
left, right = shorten(name + "-alpha"), shorten(name + "-beta")
record["arms"].append({"label": "shorten:stable", "runs": [{
"ok": first == second, "bytes": len(first.encode()), "limit": 255,
"ends": first[-4:], "digest": first.split("~")[1].split(".")[0],
}]})
record["arms"].append({"label": "shorten:distinct", "runs": [{
"ok": left != right, "left": len(left.encode()), "right": len(right.encode()),
"left_digest": left.split("~")[1].split(".")[0],
"right_digest": right.split("~")[1].split(".")[0],
}]})
record["arms"].append({"label": "shorten:fits", "runs": [{
"ok": shorten("report.csv") == "report.csv"}]})
# The shortened name is a name the filesystem takes.
target = os.path.join(ROOT, first)
record["arms"].append({"label": "shorten:stored", "runs": [probelib.describe(
lambda: open(target, "w").close())], "path": target})
record["notes"]["limits"] = {"name_max": os.pathconf(ROOT, "PC_NAME_MAX"),
"path_max": os.pathconf(ROOT, "PC_PATH_MAX")}
probelib.write("07_module.json", record)
if __name__ == "__main__":
main()
the walk per component, and what a refusal costs sandbox/08_cost.py
"""What a path costs: the walk per component, and what a refused pathname costs instead."""
from __future__ import annotations
import os
import pathlib
import sys
import time
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
ROOT = "/tmp/p48_cost"
CALLS = 200
def tree(levels: int) -> None:
os.makedirs(ROOT, exist_ok=True)
descriptor = os.open(ROOT, os.O_RDONLY)
try:
for _ in range(levels):
try:
os.mkdir("d", dir_fd=descriptor)
except FileExistsError:
pass
following = os.open("d", os.O_RDONLY, dir_fd=descriptor)
os.close(descriptor)
descriptor = following
finally:
os.close(descriptor)
def at_depth(depth: int) -> str:
return ROOT + "/d" * depth + "/leaf" if depth else ROOT + "/leaf"
def timed(label: str, path: str, repeats: int = 5) -> dict:
"""One run is CALLS calls; the recorded number is one call's share, in nanoseconds."""
def call():
started = time.perf_counter()
for _ in range(CALLS):
try:
os.stat(path)
except OSError:
pass
return None, time.perf_counter() - started
record = probelib.timed(label, call, repeats=repeats)
for run in record["runs"]:
run["ns"] = round(run["ns"] / CALLS)
run["path_bytes"] = len(path.encode())
return record
def main() -> None:
probelib.clean(ROOT)
tree(60)
for depth in (1, 10, 30, 60):
with open(at_depth(depth), "w") as handle:
handle.write("x")
record = {"probe": "08_cost", "host": probelib.host(), "calls_per_run": CALLS, "arms": [],
"notes": {"root": ROOT}}
for depth in (1, 10, 30, 60):
arm = timed(f"depth_{depth}", at_depth(depth))
arm["depth"] = depth
record["arms"].append(arm)
record["arms"].append(timed("missing_short", ROOT + "/absent"))
record["arms"].append(timed("rejected_component", ROOT + "/" + "n" * 256))
record["arms"].append(timed("rejected_total", ROOT + "/" + "/".join(["d" * 200] * 21)))
# What each arm actually answered, so the timing is never read as a different call.
for label, path in (("depth_60", at_depth(60)), ("missing_short", ROOT + "/absent"),
("rejected_component", ROOT + "/" + "n" * 256),
("rejected_total", ROOT + "/" + "/".join(["d" * 200] * 21))):
record.setdefault("notes", {}).setdefault("outcome", {})[label] = probelib.describe(
lambda path=path: os.stat(path))
probelib.write("08_cost.json", record)
if __name__ == "__main__":
main()
the tree’s own counts sandbox/09_counts.py
"""The tree's own counts: what the body quotes about the package, its tests and the probes."""
from __future__ import annotations
import os
import pathlib
import re
import subprocess
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import probelib # noqa: E402
HERE = pathlib.Path(__file__).resolve().parent.parent
PACKAGE = HERE / "pathguard"
TESTS = PACKAGE / "tests"
SANDBOX = HERE / "sandbox"
EXAMPLES = HERE / "examples"
def lines_of(paths: list[pathlib.Path]) -> int:
return sum(len(path.read_text(encoding="utf-8").splitlines()) for path in paths)
def main() -> None:
result = subprocess.run([sys.executable, "-m", "pytest", "pathguard/tests", "-q",
"-p", "no:cacheprovider", "-p", "no:warnings"],
cwd=str(HERE), capture_output=True, text=True)
output = (result.stdout + result.stderr).strip()
passed = int(match.group(1)) if (match := re.search(r"(\d+) passed", output)) else 0
package_files = sorted(PACKAGE.glob("*.py"))
test_files = sorted(TESTS.glob("*.py"))
probe_files = sorted(SANDBOX.glob("*.py"))
example_files = sorted(EXAMPLES.glob("*.py"))
demo = subprocess.run([sys.executable, "examples/pathcheck.py"], cwd=str(HERE),
capture_output=True, text=True,
env={**os.environ, "PYTHONPATH": str(HERE)})
notes = {
"pytest_passed": passed,
"example_output_lines": len(demo.stdout.strip().splitlines()),
"example_rc": demo.returncode,
"pytest_rc": result.returncode,
"package_files": len(package_files),
"package_lines": lines_of(package_files),
"test_files": len(test_files),
"test_lines": lines_of(test_files),
"probe_files": len(probe_files),
"probe_lines": lines_of(probe_files),
"example_files": len(example_files),
"example_file_lines": lines_of(example_files),
"package_names": [path.name for path in package_files],
"test_names": [path.name for path in test_files],
"probe_names": [path.name for path in probe_files],
"last_line": output.splitlines()[-1] if output else "",
}
record = {"probe": "09_counts", "notes": notes, "arms": [{"label": "counts", "runs": [notes]}]}
probelib.write("09_counts.json", record)
print(notes)
if __name__ == "__main__":
main()
the module’s answers in one run examples/pathcheck.py
#!/usr/bin/env python3
"""Seven answers from the module, printed in one run and quoted in Section 7."""
from __future__ import annotations
import os
from pathguard import explain, shorten, verdict
LONG_PATH = "/".join(["d" * 200] * 21)
def measured(path: str) -> str:
"""What the kernel said about the same path the verdict was asked about."""
try:
os.stat(path)
return "accepted"
except OSError as exc:
return f"errno {exc.errno}"
component = verdict("n" * 256)
total = verdict(LONG_PATH)
hangul = "\uac00" * 85
shortened = shorten("a" * 300 + ".csv")
print("short name:", verdict("report.csv")["reason"])
print("256-byte component:", component["reason"], f"({component['bytes']} bytes, "
f"limit {component['limit']})")
print("4,220-byte path:", total["reason"], f"({total['bytes']} bytes, limit {total['limit']})")
print("85 hangul characters:", verdict(hangul)["reason"],
f"({len(hangul.encode())} bytes)")
print("shortened:", f"{len(shortened.encode())} bytes, ends {shortened[-4:]}, "
f"digest {shortened.split('~')[1].split('.')[0]}")
print("explain:", explain(OSError(36, "File name too long", "/tmp/" + "n" * 300)))
print("measured:", measured("n" * 256), "| predicted:", component["reason"])
