Debian Codegraph @

contrib/bindings/python/pathrs/pathrs_build.py

raw symbols SCIP
1 #!/usr/bin/python3
2 # SPDX-License-Identifier: MPL-2.0
3 #
4 # libpathrs: safe path resolution on Linux
5 # Copyright (C) 2019-2025 SUSE LLC
6 # Copyright (C) 2026 Aleksa Sarai <[email protected]>
7 #
8 # This Source Code Form is subject to the terms of the Mozilla Public
9 # License, v. 2.0. If a copy of the MPL was not distributed with this
10 # file, You can obtain one at https://mozilla.org/MPL/2.0/.
11
12 # This builds the _pathrs module (only needs to be done during the initial
13 # build of libpathrs, and can be redistributed alongside the pathrs.py wrapping
14 # library). It's much better than the ABI-mode of CFFI.
15
16 import re
17 import os
18 import sys
19
20 from typing import Any, Optional
21 from collections.abc import Iterable
22
23 import cffi
24
25
26 def load_hdr(ffi: cffi.FFI, hdr_path: str) -> None:
27 with open(hdr_path) as f:
28 hdr = f.read()
29
30 # We need to first filter out all the bits of <pathrs.h> that are not
31 # supported by cffi. Ideally this wouldn't be necessary, but the macro
32 # support in cffi is very limited, and we make use of basic features that
33 # are unsupported by cffi.
34
35 # Drop all non-#define lines (directives are not supported).
36 hdr = re.sub(r"^#\s*(?!define\b).*$", "", hdr, flags=re.MULTILINE)
37 # Drop all:
38 # * "#define FOO(n) ..." lines (function-style macros are not supported).
39 # * Empty-value "#define FOO" lines (empty macros are not supported)
40 # TODO: We probably should support multi-line macros.
41 hdr = re.sub(r"^#\s*define\b\s*\w*(\(.*|)$", "", hdr, flags=re.MULTILINE)
42
43 # Replace each struct-like body that has __CBINDGEN_ALIGNED before it,
44 # remove the __CBINDGEN_ALIGNED and add "...;" as the last field in the
45 # struct. This is how you tell cffi to get the proper alignment from the
46 # compiler (__attribute__((aligned(n))) is not supported by cdef).
47 hdr = re.sub(
48 r"__CBINDGEN_ALIGNED\(\d+\)([^{;]*){([^}]+)}",
49 r"\1 {\2 ...;}",
50 hdr,
51 flags=re.MULTILINE,
52 )
53
54 # Load the header.
55 ffi.cdef(hdr)
56
57
58 def create_ffibuilder(**kwargs: Any) -> cffi.FFI:
59 ffibuilder = cffi.FFI()
60 ffibuilder.cdef("typedef uint32_t dev_t;")
61
62 # We need to use cdef to tell cffi what functions we need to FFI to. But we
63 # don't need the structs (I hope).
64 for include_dir in kwargs.get("include_dirs", []):
65 pathrs_hdr = os.path.join(include_dir, "pathrs.h")
66 if os.path.exists(pathrs_hdr):
67 load_hdr(ffibuilder, pathrs_hdr)
68
69 # Add a source and link to libpathrs.
70 ffibuilder.set_source(
71 "_libpathrs_cffi", "#include <pathrs.h>", libraries=["pathrs"], **kwargs
72 )
73
74 return ffibuilder
75
76
77 def find_rootdir() -> str:
78 # Figure out where the libpathrs source dir is.
79 root_dir = None
80 candidate = os.path.dirname(sys.path[0] or os.getcwd())
81 while candidate != "/":
82 try:
83 # Look for a Cargo.toml which says it's pathrs.
84 candidate_toml = os.path.join(candidate, "Cargo.toml")
85 with open(candidate_toml, "r") as f:
86 content = f.read()
87 if re.findall(r'^name = "pathrs"$', content, re.MULTILINE):
88 root_dir = candidate
89 break
90 except FileNotFoundError:
91 pass
92 candidate = os.path.dirname(candidate)
93
94 if not root_dir:
95 raise FileNotFoundError("Could not find pathrs source-dir root.")
96
97 return root_dir
98
99
100 def srcdir_ffibuilder(root_dir: Optional[str] = None) -> cffi.FFI:
101 """
102 Build the CFFI bindings using the provided root_dir as the root of a
103 pathrs source tree which has compiled cdylibs ready in target/*.
104 """
105
106 if root_dir is None:
107 root_dir = find_rootdir()
108
109 # Figure out which libs are usable.
110 library_dirs: Iterable[str] = (
111 os.path.join(root_dir, "target/%s/libpathrs.so" % (mode,))
112 for mode in ("debug", "release")
113 )
114 library_dirs = (so_path for so_path in library_dirs if os.path.exists(so_path))
115 library_dirs = sorted(library_dirs, key=lambda path: -os.path.getmtime(path))
116 library_dirs = [os.path.dirname(path) for path in library_dirs]
117
118 # Compile the libpathrs module.
119 return create_ffibuilder(
120 include_dirs=[os.path.join(root_dir, "include")],
121 library_dirs=library_dirs,
122 )
123
124
125 def system_ffibuilder() -> cffi.FFI:
126 """
127 Build the CFFI bindings using the installed libpathrs system libraries.
128 """
129
130 return create_ffibuilder(
131 include_dirs=[
132 "/usr/include",
133 "/usr/local/include",
134 ]
135 )
136
137
138 if __name__ == "__main__":
139 try:
140 # Search for the compiled libraries to link to from our libpathrs
141 # source if running outside of setuptools as a regular program.
142 ffibuilder = srcdir_ffibuilder(root_dir=find_rootdir())
143 except FileNotFoundError:
144 # If we couldn't find a valid library in the source dir, just fallback
145 # to using the system libraries.
146 ffibuilder = system_ffibuilder()
147 ffibuilder.compile(verbose=True)
148 elif os.environ.get("PATHRS_SRC_ROOT", "") != "":
149 # If we're running in setup tools, we can't easily find the source dir.
150 # However, distributions can set PATHRS_SRC_ROOT to the path of the
151 # libpathrs source directory to make it easier to build the python modules
152 # in the same %build script as the main library.
153 ffibuilder = srcdir_ffibuilder(root_dir=os.environ.get("PATHRS_SRC_ROOT"))
154 else:
155 # Use the system libraries if running inside standard setuptools.
156 ffibuilder = system_ffibuilder()