pledge.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/String.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/MappedFile.h>
  9. #include <LibCore/System.h>
  10. #include <LibELF/Image.h>
  11. #include <LibMain/Main.h>
  12. static ErrorOr<bool> is_dynamically_linked_executable(StringView filename)
  13. {
  14. auto executable = TRY(Core::System::resolve_executable_from_environment(filename));
  15. auto file = TRY(Core::MappedFile::map(executable));
  16. ELF::Image elf_image(file->bytes());
  17. return elf_image.is_dynamic();
  18. }
  19. ErrorOr<int> serenity_main(Main::Arguments arguments)
  20. {
  21. DeprecatedString promises;
  22. Vector<StringView> command;
  23. bool add_promises_for_dynamic_linker;
  24. Core::ArgsParser args_parser;
  25. args_parser.add_option(promises, "Space-separated list of pledge promises", "promises", 'p', "promises");
  26. args_parser.add_option(add_promises_for_dynamic_linker, "Add temporary promises for dynamic linker", "dynamic-linker-promises", 'd');
  27. args_parser.add_positional_argument(command, "Command to execute", "command");
  28. args_parser.parse(arguments);
  29. if (add_promises_for_dynamic_linker && TRY(is_dynamically_linked_executable(command[0]))) {
  30. auto constexpr loader_promises = "stdio rpath prot_exec"sv;
  31. MUST(Core::System::setenv("_LOADER_PLEDGE_PROMISES"sv, loader_promises, true));
  32. MUST(Core::System::setenv("_LOADER_MAIN_PROGRAM_PLEDGE_PROMISES"sv, promises, true));
  33. promises = DeprecatedString::formatted("{} {}", promises, loader_promises);
  34. }
  35. TRY(Core::System::pledge(StringView(), promises));
  36. TRY(Core::System::exec(command[0], command.span(), Core::System::SearchInPath::Yes));
  37. return 0;
  38. }