liyujie
2025-08-29 87c7c0d90966d729ca3d39cbfca77a39a43960eb
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
#!/usr/bin/env python
 
"""
Check boot jars.
 
Usage: check_boot_jars.py <package_whitelist_file> <jar1> <jar2> ...
"""
import logging
import os.path
import re
import subprocess
import sys
 
 
# The compiled whitelist RE.
whitelist_re = None
 
 
def LoadWhitelist(filename):
  """ Load and compile whitelist regular expressions from filename.
  """
  lines = []
  with open(filename, 'r') as f:
    for line in f:
      line = line.strip()
      if not line or line.startswith('#'):
        continue
      lines.append(line)
  combined_re = r'^(%s)$' % '|'.join(lines)
  global whitelist_re
  try:
    whitelist_re = re.compile(combined_re)
  except re.error:
    logging.exception(
        'Cannot compile package whitelist regular expression: %r',
        combined_re)
    whitelist_re = None
    return False
  return True
 
 
def CheckJar(whitelist_path, jar):
  """Check a jar file.
  """
  # Get the list of files inside the jar file.
  p = subprocess.Popen(args='jar tf %s' % jar,
      stdout=subprocess.PIPE, shell=True)
  stdout, _ = p.communicate()
  if p.returncode != 0:
    return False
  items = stdout.split()
  for f in items:
    if f.endswith('.class'):
      package_name = os.path.dirname(f)
      package_name = package_name.replace('/', '.')
      # Skip class without a package name
      if package_name and not whitelist_re.match(package_name):
        print >> sys.stderr, ('Error: %s contains class file %s, whose package name %s is not '
                              'in the whitelist %s of packages allowed on the bootclasspath.'
                              % (jar, f, package_name, whitelist_path))
        return False
  return True
 
 
def main(argv):
  if len(argv) < 2:
    print __doc__
    return 1
  whitelist_path = argv[0]
 
  if not LoadWhitelist(whitelist_path):
    return 1
 
  passed = True
  for jar in argv[1:]:
    if not CheckJar(whitelist_path, jar):
      passed = False
  if not passed:
    return 1
 
  return 0
 
 
if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))