-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathutils.py
More file actions
155 lines (126 loc) · 4.51 KB
/
utils.py
File metadata and controls
155 lines (126 loc) · 4.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3
# Copyright 2025 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils for snapshotting shared libraries."""
from collections.abc import Mapping, Sequence
import dataclasses
import os
import pathlib
import re
import subprocess
from typing import Final, Protocol
from absl import logging
from google3.pyglib import gfile
import pathlib
LD_BINARY_NAME: Final[str] = "ld-linux-x86-64.so.2"
_LD_BINARY_PATH: Final[pathlib.Path] = pathlib.Path("/lib64") / LD_BINARY_NAME
@dataclasses.dataclass(frozen=True)
class SharedLibrary:
"""A shared library with its name and path."""
name: str
path: pathlib.Path
def _parse_ld_trace_output(output: str) -> Sequence[SharedLibrary]:
"""Parses the output of `LD_TRACE_LOADED_OBJECTS=1 ld.so`."""
if "statically linked" in output:
return []
# Example output:
# linux-vdso.so.1 => (0x00007f40afc0f000)
# linux-vdso.so.1 (0x00007f76b9377000)
# lib foo.so => /tmp/sharedlib/lib foo.so (0x00007f76b9367000)
# libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f76b9157000)
# /lib64/ld-linux-x86-64.so.2 (0x00007f76b9379000)
# The last line can also be:
# /grte/lib64/lib64/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2
# (0x00007f76b9379000)
#
# The lines that do not have a => should be skipped.
# The dynamic linker should always be copied AND have its executable bit set.
# The lines that have a => could contain a space, but we copy whatever is on
# the right side of the =>, removing the load address.
shared_libraries = [SharedLibrary(name=LD_BINARY_NAME, path=_LD_BINARY_PATH)]
for lib_name, lib_path in re.findall(r"(\S+) => .*?(\S+) \(", output):
lib_path = pathlib.Path(lib_path)
if lib_path == _LD_BINARY_PATH:
continue
shared_libraries.append(SharedLibrary(name=lib_name, path=lib_path))
return shared_libraries
class CommandRunner(Protocol):
"""Runs `command` with environment `env` and returns its stdout."""
def __call__(
self,
command: Sequence[str | os.PathLike[str]],
env: Mapping[str, str] | None = None,
) -> bytes:
pass
def run_subprocess(
command: Sequence[str | os.PathLike[str]],
env: Mapping[str, str] | None = None,
) -> bytes:
return subprocess.run(
command,
capture_output=True,
env=env,
check=True,
).stdout
def get_shared_libraries(
binary_path: os.PathLike[str],
command_runner: CommandRunner = run_subprocess,
) -> Sequence[SharedLibrary]:
"""Copies the shared libraries to the shared directory."""
env = os.environ | {
"LD_TRACE_LOADED_OBJECTS": "1",
"LD_BIND_NOW": "1",
}
stdout_bytes = command_runner([_LD_BINARY_PATH, binary_path], env=env)
return _parse_ld_trace_output(stdout_bytes.decode())
def copy_shared_libraries(
libraries: Sequence[SharedLibrary], dst_path: pathlib.Path
) -> None:
"""Copies the shared libraries to the shared directory."""
for lib in libraries:
try:
logging.info("Copying %s => %s", lib.name, lib.path)
gfile.Copy(lib.path, dst_path / lib.path.name, overwrite=True, mode=0o755)
except gfile.GOSError:
logging.exception("Could not copy %s to %s", lib.path, dst_path)
raise
def patch_binary_rpath_and_interpreter(
binary_path: os.PathLike[str],
lib_mount_path: pathlib.Path,
):
"""Patches the binary rpath and interpreter."""
subprocess.run(
[
"patchelf",
"--set-rpath",
lib_mount_path.as_posix(),
"--force-rpath",
binary_path,
],
check=True,
)
subprocess.run(
[
"patchelf",
"--set-interpreter",
(lib_mount_path / LD_BINARY_NAME).as_posix(),
binary_path,
],
check=True,
)
def get_library_mount_path(binary_id: str) -> pathlib.Path:
return pathlib.Path("/tmp") / (binary_id + "_lib")
def report_progress(stage: str, is_done: bool = False) -> None:
"""Reports progress of a stage of the snapshotting process."""
logging.info("%s%s", stage, "..." if not is_done else "")