Debian Codegraph @

testing/mozbase/mozinfo/mozinfo/mozinfo.py

raw
1 #!/usr/bin/env python
2
3 # This Source Code Form is subject to the terms of the Mozilla Public
4 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 # You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 # TODO: it might be a good idea of adding a system name (e.g. 'Ubuntu' for
8 # linux) to the information; I certainly wouldn't want anyone parsing this
9 # information and having behaviour depend on it
10
11 import os
12 import platform
13 import re
14 import sys
15 from ctypes.util import find_library
16
17 from .string_version import StringVersion
18
19 # keep a copy of the os module since updating globals overrides this
20 _os = os
21
22
23 class unknown:
24 """marker class for unknown information"""
25
26 # pylint: disable=W1629
27 def __nonzero__(self):
28 return False
29
30 def __bool__(self):
31 return False
32
33 def __str__(self):
34 return "UNKNOWN"
35
36
37 unknown = unknown() # singleton
38
39
40 # get system information
41 info = {
42 "os": unknown,
43 "processor": unknown,
44 "version": unknown,
45 "os_version": unknown,
46 "bits": unknown,
47 "has_sandbox": unknown,
48 "display": None,
49 "android_version": "",
50 "automation": bool(os.environ.get("MOZ_AUTOMATION", False)),
51 }
52 (system, node, release, version, machine, processor) = platform.uname()
53 (bits, linkage) = platform.architecture()
54
55 # get os information and related data
56 if system in ["Microsoft", "Windows"]:
57 info["os"] = "win"
58 # uname().processor on Windows gives the full CPU name but
59 # mozinfo.processor is only about CPU architecture
60 processor = machine
61 system = os.environ.get("OS", system).replace("_", " ")
62 (major, minor, build_number, _, _) = os.sys.getwindowsversion()
63 version = "%d.%d.%d" % (major, minor, build_number)
64 if major == 10 and minor == 0 and build_number >= 22000:
65 major = 11
66
67 # 2009 == 22H2 software update. These are the build numbers
68 # we use 2009 as the "build" which maps to what taskcluster tasks see
69 if build_number == 22621 or build_number == 19045:
70 build_number = 2009
71
72 os_version = "%d.%d" % (major, build_number)
73 elif system.startswith(("MINGW", "MSYS_NT")):
74 # windows/mingw python build (msys)
75 info["os"] = "win"
76 os_version = version = unknown
77 elif system == "Linux":
78 # Attempt to use distro package to determine Linux distribution first.
79 # Failing that, fall back to use the platform method.
80 # Note that platform.linux_distribution() will be deprecated as of 3.8
81 # and this block will be removed once support for 2.7/3.5 is dropped.
82 try:
83 from distro import linux_distribution
84 except ImportError:
85 from platform import linux_distribution
86
87 output = linux_distribution()
88 (distribution, os_version, codename) = tuple(str(item.title()) for item in output)
89
90 if not processor:
91 processor = machine
92 if not distribution:
93 distribution = "lfs"
94 if not os_version:
95 os_version = release
96 if not codename:
97 codename = "unknown"
98 version = "%s %s" % (distribution, os_version)
99
100 if os.environ.get("WAYLAND_DISPLAY"):
101 info["display"] = "wayland"
102 elif os.environ.get("DISPLAY"):
103 info["display"] = "x11"
104
105 info["os"] = "linux"
106 info["linux_distro"] = distribution
107 elif system in ["DragonFly", "FreeBSD", "NetBSD", "OpenBSD"]:
108 info["os"] = "bsd" # community builds
109 version = os_version = sys.platform
110 elif system == "Darwin":
111 (release, versioninfo, machine) = platform.mac_ver()
112 version = "OS X %s" % release
113 versionNums = release.split(".")[:2]
114 os_version = "%s.%s" % (versionNums[0], versionNums[1].ljust(2, "0"))
115 info["os"] = "mac"
116 elif sys.platform in ("solaris", "sunos5"):
117 info["os"] = "unix" # community builds
118 os_version = version = sys.platform
119 else:
120 os_version = version = unknown
121
122 info["apple_silicon"] = False
123 if (
124 info["os"] == "mac"
125 and float(os_version) > 10.15
126 and processor == "arm"
127 and bits == "64bit"
128 ):
129 info["apple_silicon"] = True
130
131 info["apple_catalina"] = False
132 if info["os"] == "mac" and float(os_version) == 10.15:
133 info["apple_catalina"] = True
134
135 info["win10_2009"] = False
136 if info["os"] == "win" and version == "10.0.19045":
137 info["win10_2009"] = True
138
139 info["win11_2009"] = False
140 if info["os"] == "win" and version == "10.0.22621":
141 info["win11_2009"] = True
142
143 info["version"] = version
144 info["os_version"] = StringVersion(os_version)
145 info["is_ubuntu"] = "Ubuntu" in version
146
147 # processor type and bits
148 if processor in ["i386", "i686"]:
149 if bits == "32bit":
150 processor = "x86"
151 elif bits == "64bit":
152 processor = "x86_64"
153 elif processor.upper() == "AMD64":
154 bits = "64bit"
155 processor = "x86_64"
156 elif processor.upper() == "ARM64":
157 bits = "64bit"
158 processor = "aarch64"
159 elif processor == "arm" and bits == "64bit":
160 processor = "aarch64"
161
162 bits = re.search(r"(\d+)bit", bits).group(1)
163 info.update(
164 {
165 "processor": processor,
166 "bits": int(bits),
167 }
168 )
169
170 # we want to transition to this instead of using `!debug`, etc.
171 info["arch"] = info["processor"]
172
173
174 if info["os"] == "linux":
175 import ctypes
176 import errno
177
178 PR_SET_SECCOMP = 22
179 SECCOMP_MODE_FILTER = 2
180 ctypes.CDLL(find_library("c"), use_errno=True).prctl(
181 PR_SET_SECCOMP, SECCOMP_MODE_FILTER, 0
182 )
183 info["has_sandbox"] = ctypes.get_errno() == errno.EFAULT
184 else:
185 info["has_sandbox"] = True
186
187 # standard value of choices, for easy inspection
188 choices = {
189 "os": ["linux", "win", "mac"],
190 "bits": [32, 64],
191 "processor": ["x86", "x86_64", "aarch64"],
192 }
193
194
195 def sanitize(info):
196 """Do some sanitization of input values, primarily
197 to handle universal Mac builds."""
198 if "processor" in info and info["processor"] == "universal-x86-x86_64":
199 # If we're running on OS X 10.6 or newer, assume 64-bit
200 if release[:4] >= "10.6": # Note this is a string comparison
201 info["processor"] = "x86_64"
202 info["bits"] = 64
203 else:
204 info["processor"] = "x86"
205 info["bits"] = 32
206
207
208 # method for updating information
209
210
211 def update(new_info):
212 """
213 Update the info.
214
215 :param new_info: Either a dict containing the new info or a path/url
216 to a json file containing the new info.
217 """
218 from six import string_types
219
220 if isinstance(new_info, string_types):
221 # lazy import
222 import json
223
224 import mozfile
225
226 f = mozfile.load(new_info)
227 new_info = json.loads(f.read())
228 f.close()
229
230 info.update(new_info)
231 sanitize(info)
232 globals().update(info)
233
234 # convenience data for os access
235 for os_name in choices["os"]:
236 globals()["is" + os_name.title()] = info["os"] == os_name
237
238
239 def find_and_update_from_json(*dirs, **kwargs):
240 """Find a mozinfo.json file, load it, and update global symbol table.
241
242 This method will first check the relevant objdir directory for the
243 necessary mozinfo.json file, if the current script is being run from a
244 Mozilla objdir.
245
246 If the objdir directory did not supply the necessary data, this method
247 will then look for the required mozinfo.json file from the provided
248 tuple of directories.
249
250 If file is found, the global symbols table is updated via a helper method.
251
252 If no valid files are found, this method no-ops unless the raise_exception
253 kwargs is provided with explicit boolean value of True.
254
255 :param tuple dirs: Directories in which to look for the file.
256 :param dict kwargs: optional values:
257 raise_exception: if True, exceptions are raised.
258 False by default.
259 :returns: None: default behavior if mozinfo.json cannot be found.
260 json_path: string representation of mozinfo.json path.
261 :raises: IOError: if raise_exception is True and file is not found.
262 """
263 # First, see if we're in an objdir
264 try:
265 from mozboot.mozconfig import MozconfigFindException
266 from mozbuild.base import BuildEnvironmentNotFoundException, MozbuildObject
267
268 build = MozbuildObject.from_environment()
269 json_path = _os.path.join(build.topobjdir, "mozinfo.json")
270 if _os.path.isfile(json_path):
271 update(json_path)
272 return json_path
273 except ImportError:
274 pass
275 except (BuildEnvironmentNotFoundException, MozconfigFindException):
276 pass
277
278 for dir in dirs:
279 d = _os.path.abspath(dir)
280 json_path = _os.path.join(d, "mozinfo.json")
281 if _os.path.isfile(json_path):
282 update(json_path)
283 return json_path
284
285 # by default, exceptions are suppressed. Set this to True if otherwise
286 # desired.
287 if kwargs.get("raise_exception", False):
288 raise OSError("mozinfo.json could not be found.")
289 return None
290
291
292 def output_to_file(path):
293 import json
294
295 with open(path, "w") as f:
296 f.write(json.dumps(info))
297
298
299 update({})
300
301 # exports
302 __all__ = list(info.keys())
303 __all__ += ["is" + os_name.title() for os_name in choices["os"]]
304 __all__ += [
305 "info",
306 "unknown",
307 "main",
308 "choices",
309 "update",
310 "find_and_update_from_json",
311 "output_to_file",
312 "StringVersion",
313 ]
314
315
316 def main(args=None):
317 # parse the command line
318 from optparse import OptionParser
319
320 parser = OptionParser(description=__doc__)
321 for key in choices:
322 parser.add_option(
323 "--%s" % key,
324 dest=key,
325 action="store_true",
326 default=False,
327 help="display choices for %s" % key,
328 )
329 options, args = parser.parse_args()
330
331 # args are JSON blobs to override info
332 if args:
333 # lazy import
334 import json
335
336 for arg in args:
337 if _os.path.exists(arg):
338 string = open(arg).read()
339 else:
340 string = arg
341 update(json.loads(string))
342
343 # print out choices if requested
344 flag = False
345 for key, value in options.__dict__.items():
346 if value is True:
347 print(
348 "%s choices: %s"
349 % (key, " ".join([str(choice) for choice in choices[key]]))
350 )
351 flag = True
352 if flag:
353 return
354
355 # otherwise, print out all info
356 for key, value in info.items():
357 print("%s: %s" % (key, value))
358
359
360 if __name__ == "__main__":
361 main()