Debian Codegraph @

mesonbuild/minstall.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2014 The Meson development team
3
4 from __future__ import annotations
5
6 from glob import glob
7 import argparse
8 import errno
9 import os
10 import selectors
11 import shlex
12 import shutil
13 import subprocess
14 import sys
15 import typing as T
16 import re
17
18 from . import build, tooldetect
19 from .backend.backends import InstallData
20 from .mesonlib import (InstallScriptFailure, MesonException, Popen_safe, RealPathAction,
21 is_windows, is_aix, setup_vsenv, path_has_root, pickle_load, is_osx,
22 unwrap)
23 from .options import OptionKey
24 from .scripts import depfixer, destdir_join
25 from .scripts.meson_exe import run_exe
26 main_file: str | None
27 try:
28 from __main__ import __file__ as main_file
29 except ImportError:
30 # Happens when running as meson.exe which is native Windows.
31 # This is only used for pkexec which is not, so this is fine.
32 main_file = None
33
34 if T.TYPE_CHECKING:
35 from .backend.backends import (
36 InstallDataBase, InstallEmptyDir,
37 InstallSymlinkData, TargetInstallData
38 )
39 from .mesonlib import FileMode, EnvironOrDict, ExecutableSerialisation, InstallScript
40
41 try:
42 from typing import Protocol
43 except AttributeError:
44 from typing_extensions import Protocol
45
46 class ArgumentType(Protocol):
47 """Typing information for the object returned by argparse."""
48 no_rebuild: bool
49 only_changed: bool
50 profile: bool
51 quiet: bool
52 wd: str
53 destdir: str
54 dry_run: bool
55 skip_subprojects: str
56 tags: str
57 strip: bool
58
59
60 symlink_warning = '''\
61 Warning: trying to copy a symlink that points to a file. This currently copies
62 the file by default, but will be changed in a future version of Meson to copy
63 the link instead. Set follow_symlinks to true to preserve current behavior, or
64 false to copy the link.'''
65
66 selinux_updates: T.List[str] = []
67
68 # Note: when adding arguments, please also add them to the completion
69 # scripts in $MESONSRC/data/shell-completions/
70 def add_arguments(parser: argparse.ArgumentParser) -> None:
71 parser.add_argument('-C', dest='wd', action=RealPathAction,
72 help='directory to cd into before running')
73 parser.add_argument('--profile-self', action='store_true', dest='profile',
74 help=argparse.SUPPRESS)
75 parser.add_argument('--no-rebuild', default=False, action='store_true',
76 help='Do not rebuild before installing.')
77 parser.add_argument('--only-changed', default=False, action='store_true',
78 help='Only overwrite files that are older than the copied file.')
79 parser.add_argument('-q', '--quiet', default=False, action='store_true',
80 help='Do not print every file that was installed.')
81 parser.add_argument('--destdir', default=None,
82 help='Sets or overrides DESTDIR environment. (Since 0.57.0)')
83 parser.add_argument('-n', '--dry-run', action='store_true',
84 help='Doesn\'t actually install, but print logs. (Since 0.57.0)')
85 parser.add_argument('--skip-subprojects', nargs='?', const='*', default='',
86 help='Do not install files from given subprojects. (Since 0.58.0)')
87 parser.add_argument('--tags', default=None,
88 help='Install only targets having one of the given tags. (Since 0.60.0)')
89 parser.add_argument('--strip', action='store_true',
90 help='Strip targets even if strip option was not set during configure. (Since 0.62.0)')
91
92 class DirMaker:
93 def __init__(self, lf: T.TextIO, makedirs: T.Callable[..., None]):
94 self.lf = lf
95 self.dirs: T.List[str] = []
96 self.all_dirs: T.Set[str] = set()
97 self.makedirs_impl = makedirs
98
99 def makedirs(self, path: str, exist_ok: bool = False) -> None:
100 dirname = os.path.normpath(path)
101 self.all_dirs.add(dirname)
102 dirs = []
103 while dirname != os.path.dirname(dirname):
104 if dirname in self.dirs:
105 # In dry-run mode the directory does not exist but we would have
106 # created it with all its parents otherwise.
107 break
108 if not os.path.exists(dirname):
109 dirs.append(dirname)
110 dirname = os.path.dirname(dirname)
111 self.makedirs_impl(path, exist_ok=exist_ok)
112
113 # store the directories in creation order, with the parent directory
114 # before the child directories. Future calls of makedir() will not
115 # create the parent directories, so the last element in the list is
116 # the last one to be created. That is the first one to be removed on
117 # __exit__
118 dirs.reverse()
119 self.dirs += dirs
120
121 def __enter__(self) -> 'DirMaker':
122 return self
123
124 def __exit__(self, exception_type: T.Type[Exception], value: T.Any, traceback: T.Any) -> None:
125 self.dirs.reverse()
126 for d in self.dirs:
127 append_to_log(self.lf, d)
128
129
130 def load_install_data(fname: str) -> InstallData:
131 return pickle_load(fname, 'InstallData', InstallData)
132
133 def is_executable(path: str, follow_symlinks: bool = False) -> bool:
134 '''Checks whether any of the "x" bits are set in the source file mode.'''
135 return bool(os.stat(path, follow_symlinks=follow_symlinks).st_mode & 0o111)
136
137
138 def append_to_log(lf: T.TextIO, line: str) -> None:
139 lf.write(line)
140 if not line.endswith('\n'):
141 lf.write('\n')
142 lf.flush()
143
144 def set_chown(path: str, user: T.Union[str, int, None] = None,
145 group: T.Union[str, int, None] = None,
146 dir_fd: T.Optional[int] = None, follow_symlinks: bool = True) -> None:
147 # shutil.chown will call os.chown without passing all the parameters
148 # and particularly follow_symlinks, thus we replace it temporary
149 # with a lambda with all the parameters so that follow_symlinks will
150 # be actually passed properly.
151 # Not nice, but better than actually rewriting shutil.chown until
152 # this python bug is fixed: https://bugs.python.org/issue18108
153
154 # This is running into a problem where this may not match any of signatures
155 # of `shtil.chown`, which (simplified) are:
156 # chown(path: int | AnyPath, user: int | str, group: None = None)
157 # chown(path: int | AnyPath, user: None, group: int | str)
158 # We cannot through easy coercion of the type system force it to say:
159 # - user is non null and group is null
160 # - user is null and group is non null
161 # - user is non null and group is non null
162 #
163 # This is checked by the only (current) caller, but let's be sure that the
164 # call we're making to `shutil.chown` is actually valid.
165 assert user is not None or group is not None, 'ensure that calls to chown are valid'
166
167 if sys.version_info >= (3, 13):
168 # pylint: disable=unexpected-keyword-arg
169 # cannot handle sys.version_info, https://github.com/pylint-dev/pylint/issues/9622
170 #
171 # Mypy does not understand that the assert above ensures that user,
172 # group is either `None, int | str` or `int | str, None`, so we need to
173 # ignore the warning
174 shutil.chown(path, user, group, dir_fd=dir_fd, follow_symlinks=follow_symlinks) # type: ignore[arg-type]
175 else:
176 real_os_chown = os.chown
177
178 def chown(path: T.Union[int, str, 'os.PathLike[str]', bytes, 'os.PathLike[bytes]'],
179 uid: int, gid: int, *, dir_fd: T.Optional[int] = dir_fd,
180 follow_symlinks: bool = follow_symlinks) -> None:
181 """Override the default behavior of os.chown
182
183 Use a real function rather than a lambda to help mypy out. Also real
184 functions are faster.
185 """
186 real_os_chown(path, uid, gid, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
187
188 try:
189 os.chown = chown
190 # Mypy does not understand that the assert above ensures that user,
191 # group is either `None, int | str` or `int | str, None`, so we need to
192 # ignore the warning
193 shutil.chown(path, user, group) # type: ignore[arg-type]
194 finally:
195 os.chown = real_os_chown
196
197
198 def set_chmod(path: str, mode: int, dir_fd: T.Optional[int] = None,
199 follow_symlinks: bool = True) -> None:
200 try:
201 os.chmod(path, mode, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
202 except (NotImplementedError, OSError, SystemError):
203 if not os.path.islink(path):
204 os.chmod(path, mode, dir_fd=dir_fd)
205
206
207 def sanitize_permissions(path: str, umask: T.Union[str, int]) -> None:
208 # TODO: with python 3.8 or typing_extensions we could replace this with
209 # `umask: T.Union[T.Literal['preserve'], int]`, which would be more correct
210 if umask == 'preserve':
211 return
212 assert isinstance(umask, int), 'umask should only be "preserver" or an integer'
213 new_perms = 0o777 if is_executable(path, follow_symlinks=False) else 0o666
214 new_perms &= ~umask
215 try:
216 set_chmod(path, new_perms, follow_symlinks=False)
217 except PermissionError as e:
218 print(f'{path!r}: Unable to set permissions {new_perms!r}: {e.strerror}, ignoring...')
219
220
221 def set_mode(path: str, mode: T.Optional['FileMode'], default_umask: T.Union[str, int]) -> None:
222 if mode is None or all(m is None for m in [mode.perms_s, mode.owner, mode.group]):
223 # Just sanitize permissions with the default umask
224 sanitize_permissions(path, default_umask)
225 return
226 # No chown() on Windows, and must set one of owner/group
227 if not is_windows() and (mode.owner is not None or mode.group is not None):
228 try:
229 set_chown(path, mode.owner, mode.group, follow_symlinks=False)
230 except PermissionError as e:
231 print(f'{path!r}: Unable to set owner {mode.owner!r} and group {mode.group!r}: {e.strerror}, ignoring...')
232 except LookupError:
233 print(f'{path!r}: Nonexistent owner {mode.owner!r} or group {mode.group!r}: ignoring...')
234 except OSError as e:
235 if e.errno == errno.EINVAL:
236 print(f'{path!r}: Nonexistent numeric owner {mode.owner!r} or group {mode.group!r}: ignoring...')
237 else:
238 raise
239 # Must set permissions *after* setting owner/group otherwise the
240 # setuid/setgid bits will get wiped by chmod
241 # NOTE: On Windows you can set read/write perms; the rest are ignored
242 if mode.perms_s is not None:
243 try:
244 set_chmod(path, mode.perms, follow_symlinks=False)
245 except PermissionError as e:
246 print(f'{path!r}: Unable to set permissions {mode.perms_s!r}: {e.strerror}, ignoring...')
247 else:
248 sanitize_permissions(path, default_umask)
249
250
251 def restore_selinux_contexts() -> None:
252 '''
253 Restores the SELinux context for files in @selinux_updates
254
255 If $DESTDIR is set, do not warn if the call fails.
256 '''
257 try:
258 subprocess.check_call(['selinuxenabled'])
259 except (FileNotFoundError, NotADirectoryError, OSError, PermissionError, subprocess.CalledProcessError):
260 # If we don't have selinux or selinuxenabled returned 1, failure
261 # is ignored quietly.
262 return
263
264 if not shutil.which('restorecon'):
265 # If we don't have restorecon, failure is ignored quietly.
266 return
267
268 if not selinux_updates:
269 # If the list of files is empty, do not try to call restorecon.
270 return
271
272 proc, out, err = Popen_safe(['restorecon', '-F', '-f-', '-0'], ('\0'.join(f for f in selinux_updates) + '\0'))
273 if proc.returncode != 0:
274 print('Failed to restore SELinux context of installed files...',
275 'Standard output:', out,
276 'Standard error:', err, sep='\n')
277
278 def get_destdir_path(destdir: str, fullprefix: str, path: str) -> str:
279 if path_has_root(path):
280 output = destdir_join(destdir, path)
281 else:
282 output = os.path.join(fullprefix, path)
283 return output
284
285
286 def check_for_stampfile(fname: str) -> str:
287 '''Some languages e.g. Rust have output files
288 whose names are not known at configure time.
289 Check if this is the case and return the real
290 file instead.'''
291 if fname.endswith('.so') or fname.endswith('.dll'):
292 if os.stat(fname).st_size == 0:
293 (base, suffix) = os.path.splitext(fname)
294 files = glob(base + '-*' + suffix)
295 if len(files) > 1:
296 print("Stale dynamic library files in build dir. Can't install.")
297 sys.exit(1)
298 if len(files) == 1:
299 return files[0]
300 elif fname.endswith('.a') or fname.endswith('.lib'):
301 if os.stat(fname).st_size == 0:
302 (base, suffix) = os.path.splitext(fname)
303 files = glob(base + '-*' + '.rlib')
304 if len(files) > 1:
305 print("Stale static library files in build dir. Can't install.")
306 sys.exit(1)
307 if len(files) == 1:
308 return files[0]
309 return fname
310
311
312 class Installer:
313
314 def __init__(self, options: 'ArgumentType', lf: T.TextIO):
315 self.did_install_something = False
316 self.printed_symlink_error = False
317 self.options = options
318 self.lf = lf
319 self.preserved_file_count = 0
320 self.dry_run = options.dry_run
321 # [''] means skip none,
322 # ['*'] means skip all,
323 # ['sub1', ...] means skip only those.
324 self.skip_subprojects = [i.strip() for i in options.skip_subprojects.split(',')]
325 self.tags = [i.strip() for i in options.tags.split(',')] if options.tags else None
326
327 def remove(self, *args: T.Any, **kwargs: T.Any) -> None:
328 if not self.dry_run:
329 os.remove(*args, **kwargs)
330
331 def symlink(self, *args: T.Any, **kwargs: T.Any) -> None:
332 if not self.dry_run:
333 os.symlink(*args, **kwargs)
334
335 def makedirs(self, *args: T.Any, **kwargs: T.Any) -> None:
336 if not self.dry_run:
337 os.makedirs(*args, **kwargs)
338
339 def copy(self, *args: T.Any, **kwargs: T.Any) -> None:
340 if not self.dry_run:
341 shutil.copy(*args, **kwargs)
342
343 def copy2(self, *args: T.Any, **kwargs: T.Any) -> None:
344 if not self.dry_run:
345 shutil.copy2(*args, **kwargs)
346
347 def copyfile(self, *args: T.Any, **kwargs: T.Any) -> None:
348 if not self.dry_run:
349 shutil.copyfile(*args, **kwargs)
350
351 def copystat(self, *args: T.Any, **kwargs: T.Any) -> None:
352 if not self.dry_run:
353 shutil.copystat(*args, **kwargs)
354
355 def fix_rpath(self, *args: T.Any, **kwargs: T.Any) -> None:
356 if not self.dry_run:
357 depfixer.fix_rpath(*args, **kwargs)
358
359 def set_chown(self, *args: T.Any, **kwargs: T.Any) -> None:
360 if not self.dry_run:
361 set_chown(*args, **kwargs)
362
363 def set_chmod(self, *args: T.Any, **kwargs: T.Any) -> None:
364 if not self.dry_run:
365 set_chmod(*args, **kwargs)
366
367 def sanitize_permissions(self, *args: T.Any, **kwargs: T.Any) -> None:
368 if not self.dry_run:
369 sanitize_permissions(*args, **kwargs)
370
371 def set_mode(self, *args: T.Any, **kwargs: T.Any) -> None:
372 if not self.dry_run:
373 set_mode(*args, **kwargs)
374
375 def restore_selinux_contexts(self, destdir: str) -> None:
376 if not self.dry_run and not destdir:
377 restore_selinux_contexts()
378
379 def Popen_safe(self, *args: T.Any, **kwargs: T.Any) -> T.Tuple[int, str, str]:
380 if not self.dry_run:
381 p, o, e = Popen_safe(*args, **kwargs)
382 return p.returncode, o, e
383 return 0, '', ''
384
385 def run_exe(self, exe: ExecutableSerialisation, extra_env: T.Optional[T.Dict[str, str]] = None) -> int:
386 if (not self.dry_run) or exe.dry_run:
387 return run_exe(exe, extra_env)
388 return 0
389
390 def should_install(self, d: T.Union[TargetInstallData, InstallEmptyDir,
391 InstallDataBase, InstallSymlinkData,
392 InstallScript]) -> bool:
393 if d.subproject and (d.subproject in self.skip_subprojects or '*' in self.skip_subprojects):
394 return False
395 if self.tags and d.tag not in self.tags:
396 return False
397 return True
398
399 def log(self, msg: str) -> None:
400 if not self.options.quiet:
401 print(msg)
402
403 def should_preserve_existing_file(self, from_file: str, to_file: str) -> bool:
404 if not self.options.only_changed:
405 return False
406 # Always replace danging symlinks
407 if os.path.islink(from_file) and not os.path.isfile(from_file):
408 return False
409 from_time = os.stat(from_file).st_mtime
410 to_time = os.stat(to_file).st_mtime
411 return from_time <= to_time
412
413 def do_copyfile(self, from_file: str, to_file: str,
414 makedirs: T.Optional[T.Tuple[T.Any, str]] = None,
415 follow_symlinks: T.Optional[bool] = None) -> bool:
416 outdir = os.path.split(to_file)[0]
417 if not os.path.isfile(from_file) and not os.path.islink(from_file):
418 raise MesonException(f'Tried to install something that isn\'t a file: {from_file!r}')
419 # copyfile fails if the target file already exists, so remove it to
420 # allow overwriting a previous install. If the target is not a file, we
421 # want to give a readable error.
422 if os.path.exists(to_file):
423 if not os.path.isfile(to_file):
424 raise MesonException(f'Destination {to_file!r} already exists and is not a file')
425 if self.should_preserve_existing_file(from_file, to_file):
426 append_to_log(self.lf, f'# Preserving old file {to_file}\n')
427 self.preserved_file_count += 1
428 return False
429 self.log(f'Installing {from_file} to {outdir}')
430 self.remove(to_file)
431 else:
432 self.log(f'Installing {from_file} to {outdir}')
433 if makedirs:
434 # Unpack tuple
435 dirmaker, outdir = makedirs
436 # Create dirs if needed
437 dirmaker.makedirs(outdir, exist_ok=True)
438 if os.path.islink(from_file):
439 if not os.path.exists(from_file):
440 # Dangling symlink. Replicate as is.
441 self.copy(from_file, outdir, follow_symlinks=False)
442 else:
443 if follow_symlinks is None:
444 follow_symlinks = True # TODO: change to False when removing the warning
445 print(symlink_warning)
446 self.copy2(from_file, to_file, follow_symlinks=follow_symlinks)
447 else:
448 self.copy2(from_file, to_file)
449 selinux_updates.append(to_file)
450 append_to_log(self.lf, to_file)
451 return True
452
453 def do_symlink(self, target: str, link: str, destdir: str, full_dst_dir: str) -> bool:
454 abs_target = target
455 if not path_has_root(target):
456 abs_target = os.path.join(full_dst_dir, target)
457 elif not os.path.exists(abs_target):
458 abs_target = destdir_join(destdir, abs_target)
459 if os.path.lexists(link):
460 if not os.path.islink(link):
461 raise MesonException(f'Destination {link!r} already exists and is not a symlink')
462 self.remove(link)
463 if not self.printed_symlink_error:
464 self.log(f'Installing symlink pointing to {target} to {link}')
465 try:
466 self.symlink(target, link, target_is_directory=os.path.isdir(abs_target))
467 except (NotImplementedError, OSError):
468 if not self.printed_symlink_error:
469 print("Symlink creation does not work on this platform. "
470 "Skipping all symlinking.")
471 self.printed_symlink_error = True
472 return False
473 append_to_log(self.lf, link)
474 return True
475
476 def do_copydir(self, data: InstallData, src_dir: str, dst_dir: str,
477 exclude: T.Optional[T.Tuple[T.Set[str], T.Set[str]]],
478 install_mode: 'FileMode', dm: DirMaker, follow_symlinks: T.Optional[bool] = None) -> None:
479 '''
480 Copies the contents of directory @src_dir into @dst_dir.
481
482 For directory
483 /foo/
484 bar/
485 excluded
486 foobar
487 file
488 do_copydir(..., '/foo', '/dst/dir', {'bar/excluded'}) creates
489 /dst/
490 dir/
491 bar/
492 foobar
493 file
494
495 Args:
496 src_dir: str, absolute path to the source directory
497 dst_dir: str, absolute path to the destination directory
498 exclude: (set(str), set(str)), tuple of (exclude_files, exclude_dirs),
499 each element of the set is a path relative to src_dir.
500 '''
501 if not os.path.isabs(src_dir):
502 raise ValueError(f'src_dir must be absolute, got {src_dir}')
503 if not os.path.isabs(dst_dir):
504 raise ValueError(f'dst_dir must be absolute, got {dst_dir}')
505 if exclude is not None:
506 exclude_files, exclude_dirs = exclude
507 exclude_files = {os.path.normpath(x) for x in exclude_files}
508 exclude_dirs = {os.path.normpath(x) for x in exclude_dirs}
509 else:
510 exclude_files = exclude_dirs = set()
511 for root, dirs, files in os.walk(src_dir):
512 assert os.path.isabs(root)
513 for d in dirs[:]:
514 abs_src = os.path.join(root, d)
515 filepart = os.path.relpath(abs_src, start=src_dir)
516 abs_dst = os.path.join(dst_dir, filepart)
517 if os.path.islink(abs_src):
518 files.append(d)
519 continue
520 # Remove these so they aren't visited by os.walk at all.
521 if filepart in exclude_dirs:
522 dirs.remove(d)
523 continue
524 if os.path.isdir(abs_dst):
525 continue
526 if os.path.exists(abs_dst):
527 print(f'Tried to copy directory {abs_dst} but a file of that name already exists.')
528 sys.exit(1)
529 dm.makedirs(abs_dst)
530 self.copystat(abs_src, abs_dst)
531 self.sanitize_permissions(abs_dst, data.install_umask)
532 for f in files:
533 abs_src = os.path.join(root, f)
534 filepart = os.path.relpath(abs_src, start=src_dir)
535 if filepart in exclude_files:
536 continue
537 abs_dst = os.path.join(dst_dir, filepart)
538 if os.path.isdir(abs_dst):
539 print(f'Tried to copy file {abs_dst} but a directory of that name already exists.')
540 sys.exit(1)
541 parent_dir = os.path.dirname(abs_dst)
542 if not os.path.isdir(parent_dir):
543 dm.makedirs(parent_dir)
544 self.copystat(os.path.dirname(abs_src), parent_dir)
545 # FIXME: what about symlinks?
546 self.do_copyfile(abs_src, abs_dst, follow_symlinks=follow_symlinks)
547 self.set_mode(abs_dst, install_mode, data.install_umask)
548
549 def do_install(self, datafilename: str) -> None:
550 d = load_install_data(datafilename)
551
552 destdir = self.options.destdir
553 if destdir is None:
554 destdir = os.environ.get('DESTDIR')
555 if destdir and not path_has_root(destdir):
556 destdir = os.path.join(d.build_dir, destdir)
557 # Override in the env because some scripts could use it and require an
558 # absolute path.
559 if destdir is not None:
560 os.environ['DESTDIR'] = destdir
561 destdir = destdir or ''
562 fullprefix = destdir_join(destdir, d.prefix)
563
564 if d.install_umask != 'preserve':
565 assert isinstance(d.install_umask, int)
566 os.umask(d.install_umask)
567
568 self.did_install_something = False
569 try:
570 with DirMaker(self.lf, self.makedirs) as dm:
571 self.install_subdirs(d, dm, destdir, fullprefix) # Must be first, because it needs to delete the old subtree.
572 self.install_targets(d, dm, destdir, fullprefix)
573 self.install_headers(d, dm, destdir, fullprefix)
574 self.install_man(d, dm, destdir, fullprefix)
575 self.install_emptydir(d, dm, destdir, fullprefix)
576 self.install_data(d, dm, destdir, fullprefix)
577 self.install_symlinks(d, dm, destdir, fullprefix)
578 self.restore_selinux_contexts(destdir)
579 self.run_install_script(d, destdir, fullprefix)
580 if not self.did_install_something:
581 self.log('Nothing to install.')
582 if not self.options.quiet and self.preserved_file_count > 0:
583 self.log('Preserved {} unchanged files, see {} for the full list'
584 .format(self.preserved_file_count, os.path.normpath(self.lf.name)))
585 except PermissionError:
586 if is_windows() or destdir != '' or not os.isatty(sys.stdout.fileno()) or not os.isatty(sys.stderr.fileno()):
587 # can't elevate to root except in an interactive unix environment *and* when not doing a destdir install
588 raise
589
590 rootcmd = (
591 os.environ.get('MESON_ROOT_CMD')
592 or shutil.which('sudo')
593 or shutil.which('doas')
594 or shutil.which('run0')
595 )
596 pkexec = shutil.which('pkexec')
597 if rootcmd is None and pkexec is not None and 'PKEXEC_UID' not in os.environ:
598 rootcmd = pkexec
599
600 if rootcmd is not None:
601 print('Installation failed due to insufficient permissions.')
602 s = selectors.DefaultSelector()
603 s.register(sys.stdin, selectors.EVENT_READ)
604 ans = None
605 for attempt in range(5):
606 print(f'Attempt to use {rootcmd} to gain elevated privileges? [y/n] ', end='', flush=True)
607 if s.select(30):
608 # we waited on sys.stdin *only*
609 ans = sys.stdin.readline().rstrip('\n')
610 else:
611 print()
612 break
613 if ans in {'y', 'n'}:
614 break
615 else:
616 if ans is not None:
617 raise MesonException('Answer not one of [y/n]')
618 if ans == 'y':
619 mf = unwrap(main_file, 'main_file should only be None on Windows')
620 os.execlp(rootcmd, rootcmd, sys.executable, mf, *sys.argv[1:],
621 '-C', os.getcwd(), '--no-rebuild')
622 raise
623
624 def do_strip(self, strip_bin: T.List[str], fname: str, outname: str) -> None:
625 self.log(f'Stripping target {fname!r}.')
626 if is_osx():
627 # macOS expects dynamic objects to be stripped with -x maximum.
628 # To also strip the debug info, -S must be added.
629 # See: https://www.unix.com/man-page/osx/1/strip/
630 returncode, stdo, stde = self.Popen_safe(strip_bin + ['-S', '-x', outname])
631 else:
632 returncode, stdo, stde = self.Popen_safe(strip_bin + [outname])
633 if returncode != 0:
634 print('Could not strip file.\n')
635 print(f'Stdout:\n{stdo}\n')
636 print(f'Stderr:\n{stde}\n')
637 sys.exit(1)
638
639 def install_subdirs(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
640 for i in d.install_subdirs:
641 if not self.should_install(i):
642 continue
643 self.did_install_something = True
644 full_dst_dir = get_destdir_path(destdir, fullprefix, i.install_path)
645 self.log(f'Installing subdir {i.path} to {full_dst_dir}')
646 dm.makedirs(full_dst_dir, exist_ok=True)
647 self.do_copydir(d, i.path, full_dst_dir, i.exclude, i.install_mode, dm,
648 follow_symlinks=i.follow_symlinks)
649
650 def install_data(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
651 for i in d.data:
652 if not self.should_install(i):
653 continue
654 fullfilename = i.path
655 outfilename = get_destdir_path(destdir, fullprefix, i.install_path)
656 outdir = os.path.dirname(outfilename)
657 if self.do_copyfile(fullfilename, outfilename, makedirs=(dm, outdir), follow_symlinks=i.follow_symlinks):
658 self.did_install_something = True
659 self.set_mode(outfilename, i.install_mode, d.install_umask)
660
661 def install_symlinks(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
662 for s in d.symlinks:
663 if not self.should_install(s):
664 continue
665 full_dst_dir = get_destdir_path(destdir, fullprefix, s.install_path)
666 full_link_name = get_destdir_path(destdir, fullprefix, s.name)
667 dm.makedirs(full_dst_dir, exist_ok=True)
668 if self.do_symlink(s.target, full_link_name, destdir, full_dst_dir):
669 self.did_install_something = True
670
671 def install_man(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
672 for m in d.man:
673 if not self.should_install(m):
674 continue
675 full_source_filename = m.path
676 outfilename = get_destdir_path(destdir, fullprefix, m.install_path)
677 outdir = os.path.dirname(outfilename)
678 if self.do_copyfile(full_source_filename, outfilename, makedirs=(dm, outdir)):
679 self.did_install_something = True
680 self.set_mode(outfilename, m.install_mode, d.install_umask)
681
682 def install_emptydir(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
683 for e in d.emptydir:
684 if not self.should_install(e):
685 continue
686 self.did_install_something = True
687 full_dst_dir = get_destdir_path(destdir, fullprefix, e.path)
688 self.log(f'Installing new directory {full_dst_dir}')
689 if os.path.isfile(full_dst_dir):
690 print(f'Tried to create directory {full_dst_dir} but a file of that name already exists.')
691 sys.exit(1)
692 dm.makedirs(full_dst_dir, exist_ok=True)
693 self.set_mode(full_dst_dir, e.install_mode, d.install_umask)
694
695 def install_headers(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
696 for t in d.headers:
697 if not self.should_install(t):
698 continue
699 fullfilename = t.path
700 fname = os.path.basename(fullfilename)
701 outdir = get_destdir_path(destdir, fullprefix, t.install_path)
702 outfilename = os.path.join(outdir, fname)
703 if self.do_copyfile(fullfilename, outfilename, makedirs=(dm, outdir),
704 follow_symlinks=t.follow_symlinks):
705 self.did_install_something = True
706 self.set_mode(outfilename, t.install_mode, d.install_umask)
707
708 def run_install_script(self, d: InstallData, destdir: str, fullprefix: str) -> None:
709 failing_scripts = [script for script in d.install_scripts if isinstance(script, InstallScriptFailure)]
710 if not destdir and len(failing_scripts) > 0:
711 for script in failing_scripts:
712 self.log(f'ERROR: Failed to run install script {script.name}: {script.reason}')
713 raise MesonException('Install scripts failed to run')
714
715 env = {'MESON_SOURCE_ROOT': d.source_dir,
716 'MESON_BUILD_ROOT': d.build_dir,
717 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in d.mesonintrospect]),
718 }
719 if self.options.quiet:
720 env['MESON_INSTALL_QUIET'] = '1'
721 if self.dry_run:
722 env['MESON_INSTALL_DRY_RUN'] = '1'
723
724 for i in d.install_scripts:
725 if not self.should_install(i):
726 continue
727
728 name = i.name if isinstance(i, InstallScriptFailure) else ' '.join(i.cmd_args)
729 if destdir and (isinstance(i, InstallScriptFailure) or i.skip_if_destdir):
730 self.log(f'Skipping custom install script because DESTDIR is set {name!r}')
731 continue
732
733 assert not isinstance(i, InstallScriptFailure) # Should part of failing_scripts and thus this is not reached
734
735 if i.installdir_map is not None:
736 mapp = i.installdir_map
737 else:
738 mapp = {'prefix': d.prefix}
739 localenv = env.copy()
740 localenv.update({'MESON_INSTALL_'+k.upper(): os.path.join(d.prefix, v) for k, v in mapp.items()})
741 localenv.update({'MESON_INSTALL_DESTDIR_'+k.upper(): get_destdir_path(destdir, fullprefix, v) for k, v in mapp.items()})
742
743 self.did_install_something = True # Custom script must report itself if it does nothing.
744 self.log(f'Running custom install script {name!r}')
745 try:
746 rc = self.run_exe(i, localenv)
747 except OSError:
748 print(f'FAILED: install script \'{name}\' could not be run.')
749 # POSIX shells return 127 when a command could not be found
750 sys.exit(127)
751 if rc != 0:
752 print(f'FAILED: install script \'{name}\' failed with exit code {rc}.')
753 sys.exit(rc)
754
755 def install_targets(self, d: InstallData, dm: DirMaker, destdir: str, fullprefix: str) -> None:
756 for t in d.targets:
757 # In AIX, we archive our shared libraries. When we install any package in AIX we need to
758 # install the archive in which the shared library exists. The below code does the same.
759 # We change the .so files having lt_version or so_version to archive file install.
760 # If .so does not exist then it means it is in the archive. Otherwise it is a .so that exists.
761 if is_aix():
762 if not os.path.exists(t.fname) and '.so' in t.fname:
763 t.fname = re.sub('[.][a]([.]?([0-9]+))*([.]?([a-z]+))*', '.a', t.fname.replace('.so', '.a'))
764 if not self.should_install(t):
765 continue
766 if not os.path.exists(t.fname):
767 # For example, import libraries of shared modules are optional
768 if t.optional:
769 self.log(f'File {t.fname!r} not found, skipping')
770 continue
771 else:
772 raise MesonException(f'File {t.fname!r} could not be found')
773 file_copied = False # not set when a directory is copied
774 fname = check_for_stampfile(t.fname)
775 outdir = get_destdir_path(destdir, fullprefix, t.outdir)
776 outname = os.path.join(outdir, os.path.basename(fname))
777 final_path = os.path.join(d.prefix, t.outdir, os.path.basename(fname))
778 should_strip = t.strip or (t.can_strip and self.options.strip)
779 install_rpath = t.install_rpath
780 install_name_mappings = t.install_name_mappings
781 install_mode = t.install_mode
782 if not os.path.exists(fname):
783 raise MesonException(f'File {fname!r} could not be found')
784 elif os.path.isfile(fname):
785 file_copied = self.do_copyfile(fname, outname, makedirs=(dm, outdir))
786 if should_strip and d.strip_bin is not None:
787 if fname.endswith('.jar'):
788 self.log('Not stripping jar target: {}'.format(os.path.basename(fname)))
789 continue
790 self.do_strip(d.strip_bin, fname, outname)
791 if fname.endswith('.js'):
792 # Emscripten outputs js files and optionally a wasm file.
793 # If one was generated, install it as well.
794 wasm_source = os.path.splitext(fname)[0] + '.wasm'
795 if os.path.exists(wasm_source):
796 wasm_output = os.path.splitext(outname)[0] + '.wasm'
797 file_copied = self.do_copyfile(wasm_source, wasm_output)
798 elif os.path.isdir(fname):
799 fname = os.path.join(d.build_dir, fname.rstrip('/'))
800 outname = os.path.join(outdir, os.path.basename(fname))
801 dm.makedirs(outdir, exist_ok=True)
802 self.do_copydir(d, fname, outname, None, install_mode, dm)
803 else:
804 raise RuntimeError(f'Unknown file type for {fname!r}')
805 if file_copied:
806 self.did_install_something = True
807 try:
808 self.fix_rpath(outname, t.rpath_dirs_to_remove, install_rpath, final_path,
809 install_name_mappings, t.system, verbose=False)
810 except SystemExit as e:
811 if isinstance(e.code, int) and e.code == 0:
812 pass
813 else:
814 raise
815 # file mode needs to be set last, after strip/depfixer editing
816 self.set_mode(outname, install_mode, d.install_umask)
817
818 def rebuild_all(wd: str, backend: str) -> bool:
819 if backend == 'none':
820 # nothing to build...
821 return True
822 if backend != 'ninja':
823 print('Only ninja backend is supported to rebuild the project before installation.')
824 return True
825
826 ninja = tooldetect.detect_ninja()
827 if not ninja:
828 print("Can't find ninja, can't rebuild test.")
829 return False
830
831 def drop_privileges() -> T.Tuple[T.Optional[EnvironOrDict], T.Optional[T.Callable[[], None]]]:
832 if not is_windows() and os.geteuid() == 0:
833 import pwd
834 env = os.environ.copy()
835
836 if os.environ.get('SUDO_USER') is not None:
837 orig_user = env.pop('SUDO_USER')
838 orig_uid = env.pop('SUDO_UID', 0)
839 orig_gid = env.pop('SUDO_GID', 0)
840 try:
841 homedir = pwd.getpwuid(int(orig_uid)).pw_dir
842 except KeyError:
843 # `sudo chroot` leaves behind stale variable and builds as root without a user
844 return None, None
845 elif os.environ.get('DOAS_USER') is not None:
846 orig_user = env.pop('DOAS_USER')
847 try:
848 pwdata = pwd.getpwnam(orig_user)
849 except KeyError:
850 # `doas chroot` leaves behind stale variable and builds as root without a user
851 return None, None
852 orig_uid = pwdata.pw_uid
853 orig_gid = pwdata.pw_gid
854 homedir = pwdata.pw_dir
855 else:
856 return None, None
857
858 if os.stat(os.path.join(wd, 'build.ninja')).st_uid != int(orig_uid):
859 # the entire build process is running with sudo, we can't drop privileges
860 return None, None
861
862 env['USER'] = orig_user
863 env['HOME'] = homedir
864
865 def wrapped() -> None:
866 print(f'Dropping privileges to {orig_user!r} before running ninja...')
867 if orig_gid is not None:
868 os.setgid(int(orig_gid))
869 if orig_uid is not None:
870 os.setuid(int(orig_uid))
871
872 return env, wrapped
873 else:
874 return None, None
875
876 env, preexec_fn = drop_privileges()
877 ret = subprocess.run(ninja + ['-C', wd], env=env, preexec_fn=preexec_fn).returncode
878 if ret != 0:
879 print(f'Could not rebuild {wd}')
880 return False
881
882 return True
883
884
885 def run(opts: 'ArgumentType') -> int:
886 datafilename = 'meson-private/install.dat'
887 private_dir = os.path.dirname(datafilename)
888 log_dir = os.path.join(private_dir, '../meson-logs')
889 if not os.path.exists(os.path.join(opts.wd, datafilename)):
890 sys.exit('Install data not found. Run this command in build directory root.')
891 if not opts.no_rebuild:
892 b = build.load(opts.wd)
893 need_vsenv = T.cast('bool', b.environment.coredata.optstore.get_value_for(OptionKey('vsenv')))
894 setup_vsenv(need_vsenv)
895 backend = T.cast('str', b.environment.coredata.optstore.get_value_for(OptionKey('backend')))
896 if not rebuild_all(opts.wd, backend):
897 sys.exit(-1)
898 os.chdir(opts.wd)
899 with open(os.path.join(log_dir, 'install-log.txt'), 'w', encoding='utf-8') as lf:
900 installer = Installer(opts, lf)
901 append_to_log(lf, '# List of files installed by Meson')
902 append_to_log(lf, '# Does not contain files installed by custom scripts.')
903 if opts.profile:
904 import cProfile as profile
905 fname = os.path.join(private_dir, 'profile-installer.log')
906 profile.runctx('installer.do_install(datafilename)', globals(), locals(), filename=fname)
907 else:
908 installer.do_install(datafilename)
909 return 0