Skip to content
grgalexPublic

About

Build cross-language call graphs for Python packages. Perform vulnerability reachability analysis, detect unused code (bloat)

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Repository files navigation

DOI Zenodo License: AGPL v3 Docker Image

PyXray: Practical Python Cross-Language Call Graphs

Important

New

  1. Static ELF bridge scan (on by default): PyXray reads the binding tables out of each extension module's ELF image, finding bridges that the object-layout analysis never reaches, for example functions that are registered only when another function is invoked.
  2. Programmatically loaded libraries: calls through ctypes, cffi and numpy.ctypeslib handles (CDLL('libfoo.so').bar()) become bridges to the library's functions.
  3. Type-hierarchy scan: the object-layout analysis enumerates every C type the interpreter holds, through object.__subclasses__(), and reads each type's own methods and getters. A type a module creates but never exports, such as Pillow's ImagingCore, gives up its methods, which no attribute lookup from the module reaches. On Pillow 10.0.1 that is 109 of the 240 bridges the object layout yields.

PyXray is under active development.

PyXray is a hybrid (static/dynamic) analysis tool that constructs cross-language call graphs (XLCGs) of Python packages with native extensions.

It is based on the ICSE'26 paper PyXray: Practical Cross-Language Call Graph Construction through Object Layout Analysis (PDF) and has grown beyond it.

PyXray cross-language call graph architecture diagram

Use Cases

  • Analyze supply-chain CVE reachability across Python and native code
  • Audit Python packages with native extensions
  • Quantify dependency bloat for a given client package

How It Works

PyXray:

  1. Resolves the dependencies of a target package
  2. Detects Python-to-native call bridges by analyzing the live object layout of callable Python objects
  3. Generates static Python call graphs (via PyCG) and native binary call graphs (via Ghidra)
  4. Stitches the Python and binary graphs together using the identified bridges
  5. Produces a unified cross-language call graph (XLCG) for the target package and all of its dependencies

Bridges and call graphs are cached per package version and reused across analyses, so the cost of computing XLCGs drops as the cache grows.

Note that the XLCG inherits potential imprecision and incompleteness from the underlying call graph generators (PyCG for Python code, Ghidra for binaries), so it may contain false positives and false negatives.

Quickstart

1. Clone with submodules

git clone --recurse-submodules https://github.com/grgalex/pyxray.git
cd pyxray

2. Pull the prebuilt image (or build it locally, see docs/installation.md)

docker pull docker.io/grgalex/pyxray:latest

To maximize bridge-detection accuracy, PyXray builds the package under analysis (and its dependencies) from source with debug symbols. The default image bundles the compilers, system headers, and Python build backends this needs. If you prefer a smaller image, grgalex/pyxray:slim is enough for wheel-only (-W) analysis.

3. Start a container

docker run --rm -it --name pyxray \
    -e GHIDRA_INSTALL_DIR=/ghidra --cap-add=SYS_PTRACE \
    --security-opt seccomp=unconfined \
    -v ${PWD}:/pyxray -w /pyxray \
    grgalex/pyxray:latest

All commands below run inside the container. Results land under data/, which is bind-mounted from your host. The container runs as a non-root user named pyxray (UID 1000, with passwordless sudo), so the results are owned by your host user.

Usage

1. Find Python-to-native bridges

A bridge is a Python-visible callable that is actually implemented by a C function inside a native library. PyXray discovers bridges through object layout analysis, without any prior knowledge of the package:

pyxray bridges markupsafe:3.0.2

The result is written to data/bridges/m/markupsafe/3.0.2/bridges.json. Each bridge records the Python name, the C function, and the native library that contains it:

{
  "pyname": "markupsafe._speedups._escape_inner",
  "cfunc": "escape_unicode",
  "library": "markupsafe/3.0.2/markupsafe/_speedups.cpython-312-x86_64-linux-gnu.so"
}

2. Build the cross-language call graph

pyxray xlcg markupsafe:3.0.2

This runs the full pipeline: dependency resolution, Python call graph construction, bridge detection, binary call graph extraction with Ghidra, and stitching. Outputs:

  • data/runs/m/markupsafe/3.0.2/<run-label>/xlcg/xlcg.json, the full XLCG
  • data/runs/m/markupsafe/3.0.2/<run-label>/reached_cg/reached.json, the subgraph reachable from the package entry points

An XLCG is a single graph that contains both Python functions and native functions. Every node carries its owning package, native nodes also carry their library, and edges are plain caller-to-callee pairs that cross the language boundary at bridges:

{
  "nodes": {
    "31": {"name": "markupsafe._speedups._escape_inner", "package": "markupsafe:3.0.2"},
    "43": {"name": "escape_unicode",
           "library": "markupsafe/_speedups.cpython-312-x86_64-linux-gnu.so",
           "package": "markupsafe:3.0.2"}
  },
  "edges": [[31, 43]]
}

In this fragment the Python callable markupsafe._speedups._escape_inner calls the C function escape_unicode inside the package's native extension.

3. Quantify dependency bloat

After an xlcg run, bloat reports how much of each dependency is actually reachable from the client package:

pyxray xlcg thumbor:7.7.4
pyxray bloat thumbor:7.7.4 -T

The -T flag prints a summary table. For thumbor, three direct dependencies turn out to be entirely unused:

Unreachable (3 packages):
  pytz:2023.4  (6 py files, 107 py funcs, 0 bin files, 0 bin funcs, 69.9K)
  webcolors:1.13  (6 py files, 31 py funcs, 0 bin files, 0 bin funcs, 39.4K)
  thumbor-plugins-gifv:0.1.5  (2 py files, 7 py funcs, 0 bin files, 0 bin funcs, 3.5K)

The full per-package metrics are written to data/runs/t/thumbor/7.7.4/<run-label>/bloat/bloat.json.

We reported the unused webcolors dependency to the thumbor maintainers and it was fixed (thumbor#1808).

4. Check CVE reachability

CVE-2024-28219 affects the native function buildTransform in Pillow versions before 10.3.0.

Before running any reachability analysis, first determine whether PyXray can see the vulnerable symbol at all. bridge-reach computes every native function reachable from any Python-to-native bridge of the package, so search its output for the symbol:

pyxray bridge-reach pillow:10.0.1
grep buildTransform data/bridge_reach/p/pillow/10.0.1/bridge_reach.json

If there is no match, PyXray cannot observe the vulnerable symbol (for example, the symbol may be inlined or stripped) and reachability results for it would be meaningless. If there is a match, checking client reachability makes sense: to determine whether a specific application is transitively affected, search its reached XLCG (thumbor 7.7.4 depends on the vulnerable Pillow, and we built its XLCG in the previous step):

grep buildTransform data/runs/t/thumbor/7.7.4/wheels/reached_cg/reached.json

PyXray can then extract the concrete cross-language call chains from the client to the vulnerable function:

python3 -m pyxray.tools.call_chain -i data/runs/t/thumbor/7.7.4/wheels/reached_cg/reached.json -s buildTransform
[
  "thumbor.engines.pil.Engine.read",
  "thumbor.utils.ensure_srgb",
  "PIL.ImageCms.ImageCmsTransform.__init__",
  "PIL._imagingcms.buildTransform",
  "buildTransform"
]

The chain starts at a Python function of thumbor, crosses into Pillow's Python layer, and ends inside the vulnerable native code.

Analysing a deployed environment

To analyse an application exactly as it is deployed, run PyXray inside the deployment's own image. The interpreter, the installed wheels and the system libraries that ldd resolves are then the deployed ones by construction, and nothing is downloaded or rebuilt.

1. Build a PyXray image on top of your image. The script layers the analysis toolchain over the image you name and verifies that none of the image's own packages changed version. gdb, sudo and a font come from the image's own package manager. A JDK and Ghidra are downloaded, pinned by sha256, into /opt/pyxray. PyXray and its Python dependencies are installed into /opt/pyxray/lib on PYTHONPATH, so python3 stays the image's own interpreter. There is no separate toolchain image. The script's package gate and the scan manifest's ownership check use dpkg, so the base image must be Debian or Ubuntu. musl-based images (Alpine) are not supported.

scripts/build-target-image.sh --base myapp:1.2.3 --tag pyxray-target:myapp

2. Run PyXray in it, pointing at the deployed site-packages. For a pip-installed package:

docker run --rm -it --cap-add=SYS_PTRACE -v ${PWD}:/pyxray -w /pyxray pyxray-target:myapp
pyxray xlcg --install-dir /opt/venv/lib/python3.11/site-packages mypackage:1.2.3

For an application that runs from a source tree (a Django project at /srv/app, say) and is not itself a distribution, name that directory as the target:

pyxray xlcg --install-dir /srv/venv/lib/python3.11/site-packages \
            --app-dir /srv/app --requirements /srv/app/requirements.txt \
            myapp:3f9c2d1

name:version is only a label here (a git SHA is fine). With --install-dir every dependency's files come from that directory through its dist-info RECORD, ldd runs on the deployed extension modules, Ghidra disassembles them in place, and the environment is never written to. python3 -m pyxray.tools.scan_manifest myapp:3f9c2d1 then records the sha256 and owning pip or Debian package of every analysed binary. See docs/deployment-scan.md.

3. Better symbol names with --syms-from-source. Deployed wheels are stripped, so gdb can name a bridge's C function only when it is exported and Ghidra names everything else FUN_.... With --syms-from-source PyXray builds each dependency from source at its installed version and takes symbol names and binary call graphs from those debug builds, while the graph keeps the deployed file paths, library set and linkage. The result is a superset of the wheel-only graph. It needs compilers in the image and, for wheels compiled with non-default options, a per-package configuration:

scripts/build-target-image.sh --base myapp:1.2.3 --tag pyxray-target:myapp-build \
    --with-build-tools --build-deps build-deps.txt --build-pip build-pip.txt
# inside the image: check every build reproduces its wheel before the long scan
python3 -m pyxray.tools.source_build_check --install-dir ... --app-dir ... myapp:1.2.3
pyxray xlcg --install-dir ... --app-dir ... --syms-from-source \
            --build-options build-options.json myapp:1.2.3

--build-options is a JSON map of package name to {"pip_args": [...], "env": {...}}; --build-deps, --build-pip and --build-script add the system packages, tool-directory pip packages and build-time libraries a particular application's wheels need. A build is only substituted for a wheel when its exports and linkage match. The rest fall back to the wheel, and the scan manifest records which (scan_manifest --run-label source-syms, since --syms-from-source labels its run source-syms).

Where results go. Everything is under data/ in the PyXray checkout:

data/runs/<n>/<name>/<version>/<run-label>/   xlcg/ reached_cg/ bloat/
                                              scan_manifest/ leaf_bridges/ ...
data/bridges/<n>/<name>/<version>/bridges.json  a package's bridges
data/cache/binary_cg/from-wheel/              Ghidra output, keyed by sha256
                    /from-source/
                    /from-system/

--run-label keeps several analyses of one target apart while they share the binary call-graph cache. The default is wheels, or source-syms with --syms-from-source.

CLI Overview

pyxray [-v] [--log LEVEL] [--version] <command> [PACKAGE...] [options]

Commands:
  bridges         Find Python-to-native bridges of the package itself (deps excluded)
  bridge-reach    Compute native reachability from ANY bridge (baseline for CVE reachability)
  xlcg            Compute cross-language call graph (XLCG)
  bloat           Calculate dependency bloat (requires prior xlcg)
  static-bridges  Read the binding tables out of extension module files

Global options (before the command):
  --version            Show version and exit
  -v, --verbose        Stream subprocess output in real time
  --log LEVEL          Logging level (debug, info, warning, error)

Package sources:
  PACKAGE              One or more packages as name:version (e.g. numpy:1.26.4)
                       or just name (e.g. pillow) to use the latest PyPI version
  -i, --input-file     CSV file with name:version entries (one per line)
  --source-dir DIR     Source project directory (auto-detect & install)
  --install-dir DIR    Deployed site-packages directory, analysed as it is
                       (nothing fetched from PyPI; binaries analysed as deployed
                       unless --syms-from-source)
  --app-dir DIR        With --install-dir: deployed application directory that
                       is the target (apps that run from a source tree)
  --app-exclude NAMES  Comma-separated --app-dir entries to skip
  --requirements FILE  Requirements file: deps for --source-dir, or the direct
                       deps of an --app-dir target

Options:
  -j, --jobs N         Number of parallel workers (default: 1)
  -A, --always         Force regeneration of all artifacts
  -B, --binary-always  Force binary CG regeneration via Ghidra (xlcg/bridge-reach)
  -W, --wheel-only     Use pre-built wheels instead of source builds
  --static-scan        Join the static ELF bridge scan to the object-layout
  --no-static-scan     analysis (default: on; bridges/bridge-reach/xlcg)
  --no-gc-heap         Skip the GC heap scan of the object-layout analysis
                       (default: on; bridges/bridge-reach/xlcg)
  --bridges-from SRC   bridges (default) or leaf-bridges: how xlcg resolves the
                       call graph's names to bridges
  --analysis-of N:V    bridges/bridge-reach: analyse the binaries of a completed
                       xlcg run of N:V instead of the install directory
  --app-max-iter N     Bound PyCG iterations on large targets (default: 1)
  --pycg-time-budget S Seconds PyCG may spend on one package (default: 0, none)
  --syms-from-source   With --install-dir: source-build deps for symbol names only;
                       paths, library set and linkage stay deployed (excludes -W)
  --build-options FILE JSON per-package pip_args/env for --syms-from-source builds
  --run-label LABEL    Keep this run's outputs apart from other runs of the same
                       target (default: wheels, or source-syms with --syms-from-source)
  -T, --table          Print ASCII summary table (bloat only)

Documentation

  • docs/installation.md: installing via Docker (pull or build locally) or manual setup without Docker.
  • docs/deployment-scan.md: analysing a deployed environment inside its own image (--install-dir, --app-dir, Dockerfile.target, scan manifest).
  • docs/advanced-usage.md: full CLI reference, all subcommands, batch processing, parallelism, wheel-only mode, source-dir and install-dir analysis, architecture, data layout, development and tests.

Changelog

Latest changes (1.2.0):

  • Static ELF bridge scan, on by default: the binding tables are read out of each extension module's ELF image and joined to the bridges the object-layout analysis finds. --no-static-scan turns it off.
  • GC heap scan, on by default: after each extension module's object layout is read, every object the garbage collector tracks is examined too, so a callable stored nowhere dir() reaches is still a bridge. --no-gc-heap turns it off.
  • Bridges through programmatically loaded libraries: calls through ctypes, cffi and numpy.ctypeslib handles become bridges to the library's functions.
  • Analyse a deployed environment as it is deployed: --install-dir, --app-dir, scripts/build-target-image.sh, --syms-from-source.
  • Fix: a submodule is loaded under its real parent package. Every pyyaml bridge was named _yaml.X and seven numpy.random modules gave no bridges at all.
  • Fix: libraries behind symlinked install entries are found. The stitcher analysed no package binary at all for such installs.

See CHANGELOG.md for the full list.

License

Copyright (C) 2026 Georgios Alexopoulos

This project is licensed under the GNU Affero General Public License v3.0 (AGPLv3). See the LICENSE file for details.

Related Publications

About

Build cross-language call graphs for Python packages. Perform vulnerability reachability analysis, detect unused code (bloat)

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages