Skip to content

Instantly share code, notes, and snippets.

@charmoniumQ
Created April 12, 2023 22:57
Show Gist options
  • Save charmoniumQ/596f22a3cb1df01bd4f52fb8985c1910 to your computer and use it in GitHub Desktop.
Save charmoniumQ/596f22a3cb1df01bd4f52fb8985c1910 to your computer and use it in GitHub Desktop.
import re, pathlib, collections, shlex
shared_paths = {}
for proc_dir in pathlib.Path("/proc").iterdir():
if re.match("[0-9]+", proc_dir.name) and (proc_dir / "maps").exists():
try:
map_text = (proc_dir / "maps").read_text()
except PermissionError:
pass
else:
# yay, the read_text succeeded
proc_name = shlex.join((proc_dir / "cmdline").read_text().split("\x00"))
this_shared_paths = set()
for line in map_text.strip().split("\n"):
m = re.match("([a-z0-9]+)-([a-z0-9]+) +([a-z-]{4}) +([0-9a-z]+) +([0-9a-z]+):([0-9a-z]+) +([0-9]+) +([^ ].+|)", line)
if m is not None:
addr_begin, addr_end, mode, offset, major, minor, inode, path = m.groups()
path = path.partition(" ")[0]
if mode[3] == "s":
shared_paths.setdefault(path, set()).add(proc_name)
elif line.strip():
print("Failed to parse:", line)
k = 10
print("printing top", k, "shared libraries")
for path in sorted(shared_paths, key=lambda path: len(shared_paths[path]), reverse=True)[:k]:
processes = shared_paths[path]
print(path, "is used by", len(processes), "processes")
for process in processes:
print(" ", process)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment