tools/testing/selftests/exec/binfmt_script.py

Source file repositories/reference/linux-study-clean/tools/testing/selftests/exec/binfmt_script.py

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/exec/binfmt_script.py
Extension
.py
Size
7500 bytes
Lines
180
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: tools
Status
atlas-only

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
#
# Test that truncation of bprm->buf doesn't cause unexpected execs paths, along
# with various other pathological cases.
import os, subprocess

# Relevant commits
#
# b5372fe5dc84 ("exec: load_script: Do not exec truncated interpreter path")
# 6eb3c3d0a52d ("exec: increase BINPRM_BUF_SIZE to 256")

# BINPRM_BUF_SIZE
SIZE=256

NAME_MAX=int(subprocess.check_output(["getconf", "NAME_MAX", "."]))

test_num=0
pass_num=0
fail_num=0

code='''#!/usr/bin/perl
print "Executed interpreter! Args:\n";
print "0 : '$0'\n";
$counter = 1;
foreach my $a (@ARGV) {
    print "$counter : '$a'\n";
    $counter++;
}
'''

##
# test - produce a binfmt_script hashbang line for testing
#
# @size:     bytes for bprm->buf line, including hashbang but not newline
# @good:     whether this script is expected to execute correctly
# @hashbang: the special 2 bytes for running binfmt_script
# @leading:  any leading whitespace before the executable path
# @root:     start of executable pathname
# @target:   end of executable pathname
# @arg:      bytes following the executable pathname
# @fill:     character to fill between @root and @target to reach @size bytes
# @newline:  character to use as newline, not counted towards @size
# ...
def test(name, size, good=True, leading="", root="./", target="/perl",
                     fill="A", arg="", newline="\n", hashbang="#!"):
    global test_num, pass_num, fail_num, tests, NAME_MAX
    test_num += 1
    if test_num > tests:
        raise ValueError("more binfmt_script tests than expected! (want %d, expected %d)"
                         % (test_num, tests))

    middle = ""
    remaining = size - len(hashbang) - len(leading) - len(root) - len(target) - len(arg)
    # The middle of the pathname must not exceed NAME_MAX
    while remaining >= NAME_MAX:
        middle += fill * (NAME_MAX - 1)
        middle += '/'
        remaining -= NAME_MAX
    middle += fill * remaining

    dirpath = root + middle
    binary = dirpath + target
    if len(target):
        os.makedirs(dirpath, mode=0o755, exist_ok=True)
        open(binary, "w").write(code)
        os.chmod(binary, 0o755)

    buf=hashbang + leading + root + middle + target + arg + newline
    if len(newline) > 0:

Annotation

Implementation Notes