11 # Encode to UTF-8 to get binary data.
12 return str.encode('utf-8')
15 if isinstance(bytes, str):
17 return to_bytes(bytes)
19 def convert_string(bytes):
21 return to_string(bytes.decode('utf-8'))
27 Detects the number of CPUs on a system. Cribbed from pp.
29 # Linux, Unix and MacOS:
30 if hasattr(os, "sysconf"):
31 if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
33 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
34 if isinstance(ncpus, int) and ncpus > 0:
37 return int(capture(['sysctl', '-n', 'hw.ncpu']))
39 if "NUMBER_OF_PROCESSORS" in os.environ:
40 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
46 """mkdir_p(path) - Make the "path" directory, if it does not exist; this
47 will also make directories for any missing parent directories."""
48 if not path or os.path.exists(path):
51 parent = os.path.dirname(path)
59 # Ignore EEXIST, which may occur during a race condition.
60 if e.errno != errno.EEXIST:
63 def capture(args, env=None):
64 """capture(command) - Run the given command (or argv list) in a shell and
65 return the standard output."""
66 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
68 out,_ = p.communicate()
69 return convert_string(out)
71 def which(command, paths = None):
72 """which(command, [paths]) - Look up the given command in the paths string
73 (or the PATH environment variable, if unspecified)."""
76 paths = os.environ.get('PATH','')
78 # Check for absolute match first.
79 if os.path.isfile(command):
82 # Would be nice if Python had a lib function for this.
86 # Get suffixes to search.
87 # On Cygwin, 'PATHEXT' may exist but it should not be used.
89 pathext = os.environ.get('PATHEXT', '').split(';')
94 for path in paths.split(os.pathsep):
96 p = os.path.join(path, command + ext)
102 def checkToolsPath(dir, tools):
104 if not os.path.exists(os.path.join(dir, tool)):
108 def whichTools(tools, paths):
109 for path in paths.split(os.pathsep):
110 if checkToolsPath(path, tools):
114 def printHistogram(items, title = 'Items'):
115 items.sort(key = lambda item: item[1])
117 maxValue = max([v for _,v in items])
119 # Select first "nice" bar height that produces more than 10 bars.
120 power = int(math.ceil(math.log(maxValue, 10)))
121 for inc in itertools.cycle((5, 2, 2.5, 1)):
122 barH = inc * 10**power
123 N = int(math.ceil(maxValue / barH))
129 histo = [set() for i in range(N)]
131 bin = min(int(N * v/maxValue), N-1)
135 hr = '-' * (barW + 34)
136 print('\nSlowest %s:' % title)
138 for name,value in items[-20:]:
139 print('%.2fs: %s' % (value, name))
140 print('\n%s Times:' % title)
142 pDigits = int(math.ceil(math.log(maxValue, 10)))
143 pfDigits = max(0, 3-pDigits)
145 pDigits += pfDigits + 1
146 cDigits = int(math.ceil(math.log(len(items), 10)))
147 print("[%s] :: [%s] :: [%s]" % ('Range'.center((pDigits+1)*2 + 3),
148 'Percentage'.center(barW),
149 'Count'.center(cDigits*2 + 1)))
151 for i,row in enumerate(histo):
152 pct = float(len(row)) / len(items)
154 print("[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]" % (
155 pDigits, pfDigits, i*barH, pDigits, pfDigits, (i+1)*barH,
156 '*'*w, ' '*(barW-w), cDigits, len(row), cDigits, len(items)))
158 # Close extra file handles on UNIX (on Windows this cannot be done while
159 # also redirecting input).
160 kUseCloseFDs = not (platform.system() == 'Windows')
161 def executeCommand(command, cwd=None, env=None):
162 p = subprocess.Popen(command, cwd=cwd,
163 stdin=subprocess.PIPE,
164 stdout=subprocess.PIPE,
165 stderr=subprocess.PIPE,
166 env=env, close_fds=kUseCloseFDs)
167 out,err = p.communicate()
170 # Detect Ctrl-C in subprocess.
171 if exitCode == -signal.SIGINT:
172 raise KeyboardInterrupt
174 # Ensure the resulting output is always of string type.
175 out = convert_string(out)
176 err = convert_string(err)
178 return out, err, exitCode
180 def usePlatformSdkOnDarwin(config, lit_config):
181 # On Darwin, support relocatable SDKs by providing Clang with a
182 # default system root path.
183 if 'darwin' in config.target_triple:
185 cmd = subprocess.Popen(['xcrun', '--show-sdk-path'],
186 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
187 out, err = cmd.communicate()
194 lit_config.note('using SDKROOT: %r' % sdk_path)
195 config.environment['SDKROOT'] = sdk_path