Emulator.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Leon Albrecht <leon2002.l@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Emulator.h"
  8. #include "MmapRegion.h"
  9. #include "SimpleRegion.h"
  10. #include "SoftCPU.h"
  11. #include <AK/Format.h>
  12. #include <AK/LexicalPath.h>
  13. #include <AK/StringUtils.h>
  14. #include <Kernel/API/MemoryLayout.h>
  15. #include <LibCore/MappedFile.h>
  16. #include <LibELF/AuxiliaryVector.h>
  17. #include <LibELF/Image.h>
  18. #include <LibELF/Validation.h>
  19. #include <LibX86/ELFSymbolProvider.h>
  20. #include <fcntl.h>
  21. #include <syscall.h>
  22. #include <unistd.h>
  23. #if defined(AK_COMPILER_GCC)
  24. # pragma GCC optimize("O3")
  25. #endif
  26. namespace UserspaceEmulator {
  27. static constexpr u32 stack_location = 0x10000000;
  28. static constexpr size_t stack_size = 1 * MiB;
  29. static constexpr u32 signal_trampoline_location = 0xb0000000;
  30. static Emulator* s_the;
  31. Emulator& Emulator::the()
  32. {
  33. VERIFY(s_the);
  34. return *s_the;
  35. }
  36. Emulator::Emulator(DeprecatedString const& executable_path, Vector<StringView> const& arguments, Vector<DeprecatedString> const& environment)
  37. : m_executable_path(executable_path)
  38. , m_arguments(arguments)
  39. , m_environment(environment)
  40. , m_mmu(*this)
  41. , m_cpu(make<SoftCPU>(*this))
  42. , m_editor(Line::Editor::construct())
  43. {
  44. m_malloc_tracer = make<MallocTracer>(*this);
  45. static constexpr FlatPtr userspace_range_ceiling = 0xbe000000;
  46. #ifdef UE_ASLR
  47. static constexpr FlatPtr page_mask = 0xfffff000u;
  48. size_t random_offset = (get_random<u8>() % 32 * MiB) & page_mask;
  49. FlatPtr base = userspace_range_base + random_offset;
  50. #else
  51. FlatPtr base = userspace_range_base;
  52. #endif
  53. m_range_allocator.initialize_with_range(VirtualAddress(base), userspace_range_ceiling - base);
  54. VERIFY(!s_the);
  55. s_the = this;
  56. // setup_stack(arguments, environment);
  57. register_signal_handlers();
  58. setup_signal_trampoline();
  59. }
  60. Vector<ELF::AuxiliaryValue> Emulator::generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, DeprecatedString const& executable_path, int executable_fd) const
  61. {
  62. // FIXME: This is not fully compatible with the auxiliary vector the kernel generates, this is just the bare
  63. // minimum to get the loader going.
  64. Vector<ELF::AuxiliaryValue> auxv;
  65. // PHDR/EXECFD
  66. // PH*
  67. auxv.append({ ELF::AuxiliaryValue::PageSize, PAGE_SIZE });
  68. auxv.append({ ELF::AuxiliaryValue::BaseAddress, (void*)load_base });
  69. auxv.append({ ELF::AuxiliaryValue::Entry, (void*)entry_eip });
  70. // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
  71. auxv.append({ ELF::AuxiliaryValue::Platform, "i386"sv });
  72. auxv.append({ ELF::AuxiliaryValue::ExecFilename, executable_path });
  73. auxv.append({ ELF::AuxiliaryValue::ExecFileDescriptor, executable_fd });
  74. auxv.append({ ELF::AuxiliaryValue::Null, 0L });
  75. return auxv;
  76. }
  77. void Emulator::setup_stack(Vector<ELF::AuxiliaryValue> aux_vector)
  78. {
  79. m_range_allocator.reserve_user_range(VirtualAddress(stack_location), stack_size);
  80. auto stack_region = make<SimpleRegion>(stack_location, stack_size);
  81. stack_region->set_stack(true);
  82. m_mmu.add_region(move(stack_region));
  83. m_cpu->set_esp(shadow_wrap_as_initialized<u32>(stack_location + stack_size));
  84. Vector<u32> argv_entries;
  85. for (auto const& argument : m_arguments) {
  86. m_cpu->push_string(argument);
  87. argv_entries.append(m_cpu->esp().value());
  88. }
  89. Vector<u32> env_entries;
  90. for (auto const& variable : m_environment) {
  91. m_cpu->push_string(variable.view());
  92. env_entries.append(m_cpu->esp().value());
  93. }
  94. for (auto& auxv : aux_vector) {
  95. if (!auxv.optional_string.is_empty()) {
  96. m_cpu->push_string(auxv.optional_string);
  97. auxv.auxv.a_un.a_ptr = (void*)m_cpu->esp().value();
  98. }
  99. }
  100. for (ssize_t i = aux_vector.size() - 1; i >= 0; --i) {
  101. auto& value = aux_vector[i].auxv;
  102. m_cpu->push_buffer((u8 const*)&value, sizeof(value));
  103. }
  104. m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // char** envp = { envv_entries..., nullptr }
  105. for (ssize_t i = env_entries.size() - 1; i >= 0; --i)
  106. m_cpu->push32(shadow_wrap_as_initialized(env_entries[i]));
  107. u32 envp = m_cpu->esp().value();
  108. m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // char** argv = { argv_entries..., nullptr }
  109. for (ssize_t i = argv_entries.size() - 1; i >= 0; --i)
  110. m_cpu->push32(shadow_wrap_as_initialized(argv_entries[i]));
  111. u32 argv = m_cpu->esp().value();
  112. while ((m_cpu->esp().value() + 4) % 16 != 0)
  113. m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // (alignment)
  114. u32 argc = argv_entries.size();
  115. m_cpu->push32(shadow_wrap_as_initialized(envp));
  116. m_cpu->push32(shadow_wrap_as_initialized(argv));
  117. m_cpu->push32(shadow_wrap_as_initialized(argc));
  118. VERIFY(m_cpu->esp().value() % 16 == 0);
  119. }
  120. bool Emulator::load_elf()
  121. {
  122. auto file_or_error = Core::MappedFile::map(m_executable_path);
  123. if (file_or_error.is_error()) {
  124. reportln("Unable to map {}: {}"sv, m_executable_path, file_or_error.error());
  125. return false;
  126. }
  127. auto elf_image_data = file_or_error.value()->bytes();
  128. ELF::Image executable_elf(elf_image_data);
  129. if (!executable_elf.is_dynamic()) {
  130. // FIXME: Support static objects
  131. VERIFY_NOT_REACHED();
  132. }
  133. StringBuilder interpreter_path_builder;
  134. auto result_or_error = ELF::validate_program_headers(*(Elf32_Ehdr const*)elf_image_data.data(), elf_image_data.size(), elf_image_data, &interpreter_path_builder);
  135. if (result_or_error.is_error() || !result_or_error.value()) {
  136. reportln("failed to validate ELF file"sv);
  137. return false;
  138. }
  139. auto interpreter_path = interpreter_path_builder.string_view();
  140. VERIFY(!interpreter_path.is_null());
  141. dbgln("interpreter: {}", interpreter_path);
  142. auto interpreter_file_or_error = Core::MappedFile::map(interpreter_path);
  143. VERIFY(!interpreter_file_or_error.is_error());
  144. auto interpreter_image_data = interpreter_file_or_error.value()->bytes();
  145. ELF::Image interpreter_image(interpreter_image_data);
  146. constexpr FlatPtr interpreter_load_offset = 0x08000000;
  147. interpreter_image.for_each_program_header([&](ELF::Image::ProgramHeader const& program_header) {
  148. // Loader is not allowed to have its own TLS regions
  149. VERIFY(program_header.type() != PT_TLS);
  150. if (program_header.type() == PT_LOAD) {
  151. auto start_address = program_header.vaddr().offset(interpreter_load_offset);
  152. m_range_allocator.reserve_user_range(start_address, program_header.size_in_memory());
  153. auto region = make<SimpleRegion>(start_address.get(), program_header.size_in_memory());
  154. if (program_header.is_executable() && !program_header.is_writable())
  155. region->set_text(true);
  156. memcpy(region->data(), program_header.raw_data(), program_header.size_in_image());
  157. memset(region->shadow_data(), 0x01, program_header.size_in_memory());
  158. if (program_header.is_executable()) {
  159. m_loader_text_base = region->base();
  160. m_loader_text_size = region->size();
  161. }
  162. mmu().add_region(move(region));
  163. return IterationDecision::Continue;
  164. }
  165. return IterationDecision::Continue;
  166. });
  167. auto entry_point = interpreter_image.entry().offset(interpreter_load_offset).get();
  168. m_cpu->set_eip(entry_point);
  169. // executable_fd will be used by the loader
  170. int executable_fd = open(m_executable_path.characters(), O_RDONLY);
  171. if (executable_fd < 0)
  172. return false;
  173. auto aux_vector = generate_auxiliary_vector(interpreter_load_offset, entry_point, m_executable_path, executable_fd);
  174. setup_stack(move(aux_vector));
  175. return true;
  176. }
  177. int Emulator::exec()
  178. {
  179. // X86::ELFSymbolProvider symbol_provider(*m_elf);
  180. X86::ELFSymbolProvider* symbol_provider = nullptr;
  181. constexpr bool trace = false;
  182. size_t instructions_until_next_profile_dump = profile_instruction_interval();
  183. if (is_profiling() && m_loader_text_size.has_value())
  184. emit_profile_event(profile_stream(), "mmap"sv, DeprecatedString::formatted(R"("ptr": {}, "size": {}, "name": "/usr/lib/Loader.so")", *m_loader_text_base, *m_loader_text_size));
  185. while (!m_shutdown) {
  186. if (m_steps_til_pause) [[likely]] {
  187. m_cpu->save_base_eip();
  188. auto insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
  189. // Exec cycle
  190. if constexpr (trace) {
  191. outln("{:p} \033[33;1m{}\033[0m", m_cpu->base_eip(), insn.to_deprecated_string(m_cpu->base_eip(), symbol_provider));
  192. }
  193. (m_cpu->*insn.handler())(insn);
  194. if (is_profiling()) {
  195. if (instructions_until_next_profile_dump == 0) {
  196. instructions_until_next_profile_dump = profile_instruction_interval();
  197. emit_profile_sample(profile_stream());
  198. } else {
  199. --instructions_until_next_profile_dump;
  200. }
  201. }
  202. if constexpr (trace) {
  203. m_cpu->dump();
  204. }
  205. if (m_pending_signals) [[unlikely]] {
  206. dispatch_one_pending_signal();
  207. }
  208. if (m_steps_til_pause > 0)
  209. m_steps_til_pause--;
  210. } else {
  211. handle_repl();
  212. }
  213. }
  214. if (auto* tracer = malloc_tracer())
  215. tracer->dump_leak_report();
  216. return m_exit_status;
  217. }
  218. void Emulator::send_signal(int signal)
  219. {
  220. SignalInfo info {
  221. // FIXME: Fill this in somehow
  222. .signal_info = {
  223. .si_signo = signal,
  224. .si_code = SI_USER,
  225. .si_errno = 0,
  226. .si_pid = getpid(),
  227. .si_uid = geteuid(),
  228. .si_addr = 0,
  229. .si_status = 0,
  230. .si_band = 0,
  231. .si_value = {
  232. .sival_int = 0,
  233. },
  234. },
  235. .context = {},
  236. };
  237. did_receive_signal(signal, info, true);
  238. }
  239. void Emulator::handle_repl()
  240. {
  241. // Console interface
  242. // FIXME: Previous Instruction**s**
  243. // FIXME: Function names (base, call, jump)
  244. auto saved_eip = m_cpu->eip();
  245. m_cpu->save_base_eip();
  246. auto insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
  247. // FIXME: This does not respect inlining
  248. // another way of getting the current function is at need
  249. if (auto symbol = symbol_at(m_cpu->base_eip()); symbol.has_value()) {
  250. outln("[{}]: {}", symbol->lib_name, symbol->symbol);
  251. }
  252. outln("==> {}", create_instruction_line(m_cpu->base_eip(), insn));
  253. for (int i = 0; i < 7; ++i) {
  254. m_cpu->save_base_eip();
  255. insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
  256. outln(" {}", create_instruction_line(m_cpu->base_eip(), insn));
  257. }
  258. // We don't want to increase EIP here, we just want the instructions
  259. m_cpu->set_eip(saved_eip);
  260. outln();
  261. m_cpu->dump();
  262. outln();
  263. auto line_or_error = m_editor->get_line(">> ");
  264. if (line_or_error.is_error())
  265. return;
  266. // FIXME: find a way to find a global symbol-address for run-until-call
  267. auto help = [] {
  268. outln("Available commands:");
  269. outln("continue, c: Continue the execution");
  270. outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
  271. outln("ret, r: Run until function returns");
  272. outln("step, s [count]: Execute [count] instructions and then halt");
  273. outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
  274. };
  275. auto line = line_or_error.release_value();
  276. if (line.is_empty()) {
  277. if (m_editor->history().is_empty()) {
  278. help();
  279. return;
  280. }
  281. line = m_editor->history().last().entry;
  282. }
  283. auto parts = line.split_view(' ');
  284. m_editor->add_to_history(line);
  285. if (parts[0].is_one_of("s"sv, "step"sv)) {
  286. if (parts.size() == 1) {
  287. m_steps_til_pause = 1;
  288. return;
  289. }
  290. auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
  291. if (!number.has_value()) {
  292. outln("usage \"step [count]\"\n\tcount can't be less than 1");
  293. return;
  294. }
  295. m_steps_til_pause = number.value();
  296. } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
  297. m_steps_til_pause = -1;
  298. } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
  299. m_run_til_return = true;
  300. // FIXME: This may be uninitialized
  301. m_watched_addr = m_mmu.read32({ 0x23, m_cpu->ebp().value() + 4 }).value();
  302. m_steps_til_pause = -1;
  303. } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
  304. m_shutdown = true;
  305. } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
  306. if (parts.size() == 1) {
  307. send_signal(SIGINT);
  308. return;
  309. }
  310. if (parts.size() == 2) {
  311. auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
  312. if (number.has_value()) {
  313. send_signal(*number);
  314. return;
  315. }
  316. }
  317. outln("Usage: sig [signal:int], default: SINGINT:2");
  318. } else {
  319. help();
  320. }
  321. }
  322. Vector<FlatPtr> Emulator::raw_backtrace()
  323. {
  324. Vector<FlatPtr, 128> backtrace;
  325. backtrace.append(m_cpu->base_eip());
  326. // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
  327. u32 frame_ptr = m_cpu->ebp().value();
  328. while (frame_ptr) {
  329. u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
  330. if (!ret_ptr)
  331. break;
  332. backtrace.append(ret_ptr);
  333. frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
  334. }
  335. return backtrace;
  336. }
  337. MmapRegion const* Emulator::find_text_region(FlatPtr address)
  338. {
  339. MmapRegion const* matching_region = nullptr;
  340. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  341. if (!(region.is_executable() && address >= region.base() && address < region.base() + region.size()))
  342. return IterationDecision::Continue;
  343. matching_region = &region;
  344. return IterationDecision::Break;
  345. });
  346. return matching_region;
  347. }
  348. // FIXME: This interface isn't the nicest
  349. MmapRegion const* Emulator::load_library_from_address(FlatPtr address)
  350. {
  351. auto const* region = find_text_region(address);
  352. if (!region)
  353. return {};
  354. DeprecatedString lib_name = region->lib_name();
  355. if (lib_name.is_null())
  356. return {};
  357. DeprecatedString lib_path = lib_name;
  358. if (Core::DeprecatedFile::looks_like_shared_library(lib_name))
  359. lib_path = DeprecatedString::formatted("/usr/lib/{}", lib_path);
  360. if (!m_dynamic_library_cache.contains(lib_path)) {
  361. auto file_or_error = Core::MappedFile::map(lib_path);
  362. if (file_or_error.is_error())
  363. return {};
  364. auto image = make<ELF::Image>(file_or_error.value()->bytes());
  365. auto debug_info = make<Debug::DebugInfo>(*image);
  366. m_dynamic_library_cache.set(lib_path, CachedELF { file_or_error.release_value(), move(debug_info), move(image) });
  367. }
  368. return region;
  369. }
  370. MmapRegion const* Emulator::first_region_for_object(StringView name)
  371. {
  372. MmapRegion* ret = nullptr;
  373. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  374. if (region.lib_name() == name) {
  375. ret = &region;
  376. return IterationDecision::Break;
  377. }
  378. return IterationDecision::Continue;
  379. });
  380. return ret;
  381. }
  382. // FIXME: This disregards function inlining.
  383. Optional<Emulator::SymbolInfo> Emulator::symbol_at(FlatPtr address)
  384. {
  385. auto const* address_region = load_library_from_address(address);
  386. if (!address_region)
  387. return {};
  388. auto lib_name = address_region->lib_name();
  389. auto const* first_region = (lib_name.is_null() || lib_name.is_empty()) ? address_region : first_region_for_object(lib_name);
  390. VERIFY(first_region);
  391. auto lib_path = lib_name;
  392. if (Core::DeprecatedFile::looks_like_shared_library(lib_name)) {
  393. lib_path = DeprecatedString::formatted("/usr/lib/{}", lib_name);
  394. }
  395. auto it = m_dynamic_library_cache.find(lib_path);
  396. auto const& elf = it->value.debug_info->elf();
  397. auto symbol = elf.symbolicate(address - first_region->base());
  398. auto source_position = it->value.debug_info->get_source_position(address - first_region->base());
  399. return { { lib_name, symbol, source_position } };
  400. }
  401. DeprecatedString Emulator::create_backtrace_line(FlatPtr address)
  402. {
  403. auto maybe_symbol = symbol_at(address);
  404. if (!maybe_symbol.has_value()) {
  405. return DeprecatedString::formatted("=={}== {:p}", getpid(), address);
  406. }
  407. if (!maybe_symbol->source_position.has_value()) {
  408. return DeprecatedString::formatted("=={}== {:p} [{}]: {}", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol);
  409. }
  410. auto const& source_position = maybe_symbol->source_position.value();
  411. return DeprecatedString::formatted("=={}== {:p} [{}]: {} (\e[34;1m{}\e[0m:{})", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol, LexicalPath::basename(source_position.file_path), source_position.line_number);
  412. }
  413. void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
  414. {
  415. for (auto const& address : backtrace) {
  416. reportln("{}"sv, create_backtrace_line(address));
  417. }
  418. }
  419. void Emulator::dump_backtrace()
  420. {
  421. dump_backtrace(raw_backtrace());
  422. }
  423. void Emulator::emit_profile_sample(Stream& output)
  424. {
  425. if (!is_in_region_of_interest())
  426. return;
  427. StringBuilder builder;
  428. timeval tv {};
  429. gettimeofday(&tv, nullptr);
  430. builder.appendff(R"~(, {{"type": "sample", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [)~", getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000);
  431. builder.join(',', raw_backtrace());
  432. builder.append("]}\n"sv);
  433. output.write_until_depleted(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
  434. }
  435. void Emulator::emit_profile_event(Stream& output, StringView event_name, DeprecatedString const& contents)
  436. {
  437. StringBuilder builder;
  438. timeval tv {};
  439. gettimeofday(&tv, nullptr);
  440. builder.appendff(R"~(, {{"type": "{}", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [], {}}})~", event_name, getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000, contents);
  441. builder.append('\n');
  442. output.write_until_depleted(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
  443. }
  444. DeprecatedString Emulator::create_instruction_line(FlatPtr address, X86::Instruction const& insn)
  445. {
  446. auto symbol = symbol_at(address);
  447. if (!symbol.has_value() || !symbol->source_position.has_value())
  448. return DeprecatedString::formatted("{:p}: {}", address, insn.to_deprecated_string(address));
  449. return DeprecatedString::formatted("{:p}: {} \e[34;1m{}\e[0m:{}", address, insn.to_deprecated_string(address), LexicalPath::basename(symbol->source_position->file_path), symbol->source_position.value().line_number);
  450. }
  451. static void emulator_signal_handler(int signum, siginfo_t* signal_info, void* context)
  452. {
  453. Emulator::the().did_receive_signal(signum, { *signal_info, *reinterpret_cast<ucontext_t*>(context) });
  454. }
  455. void Emulator::register_signal_handlers()
  456. {
  457. struct sigaction action {
  458. .sa_sigaction = emulator_signal_handler,
  459. .sa_mask = 0,
  460. .sa_flags = SA_SIGINFO,
  461. };
  462. sigemptyset(&action.sa_mask);
  463. for (int signum = 0; signum < NSIG; ++signum)
  464. sigaction(signum, &action, nullptr);
  465. }
  466. enum class DefaultSignalAction {
  467. Terminate,
  468. Ignore,
  469. DumpCore,
  470. Stop,
  471. Continue,
  472. };
  473. static DefaultSignalAction default_signal_action(int signal)
  474. {
  475. VERIFY(signal && signal < NSIG);
  476. switch (signal) {
  477. case SIGHUP:
  478. case SIGINT:
  479. case SIGKILL:
  480. case SIGPIPE:
  481. case SIGALRM:
  482. case SIGUSR1:
  483. case SIGUSR2:
  484. case SIGVTALRM:
  485. case SIGSTKFLT:
  486. case SIGIO:
  487. case SIGPROF:
  488. case SIGTERM:
  489. return DefaultSignalAction::Terminate;
  490. case SIGCHLD:
  491. case SIGURG:
  492. case SIGWINCH:
  493. case SIGINFO:
  494. return DefaultSignalAction::Ignore;
  495. case SIGQUIT:
  496. case SIGILL:
  497. case SIGTRAP:
  498. case SIGABRT:
  499. case SIGBUS:
  500. case SIGFPE:
  501. case SIGSEGV:
  502. case SIGXCPU:
  503. case SIGXFSZ:
  504. case SIGSYS:
  505. return DefaultSignalAction::DumpCore;
  506. case SIGCONT:
  507. return DefaultSignalAction::Continue;
  508. case SIGSTOP:
  509. case SIGTSTP:
  510. case SIGTTIN:
  511. case SIGTTOU:
  512. return DefaultSignalAction::Stop;
  513. }
  514. VERIFY_NOT_REACHED();
  515. }
  516. void Emulator::dispatch_one_pending_signal()
  517. {
  518. int signum = -1;
  519. for (signum = 1; signum < NSIG; ++signum) {
  520. int mask = 1 << signum;
  521. if (m_pending_signals & mask)
  522. break;
  523. }
  524. VERIFY(signum != -1);
  525. m_pending_signals &= ~(1 << signum);
  526. if (((1 << (signum - 1)) & m_signal_mask) != 0)
  527. return;
  528. auto& handler = m_signal_handler[signum];
  529. if (handler.handler == 0) {
  530. // SIG_DFL
  531. auto action = default_signal_action(signum);
  532. if (action == DefaultSignalAction::Ignore)
  533. return;
  534. reportln("\n=={}== Got signal {} ({}), no handler registered"sv, getpid(), signum, strsignal(signum));
  535. dump_backtrace();
  536. m_shutdown = true;
  537. return;
  538. }
  539. if (handler.handler == 1) {
  540. // SIG_IGN
  541. return;
  542. }
  543. reportln("\n=={}== Got signal {} ({}), handler at {:p}"sv, getpid(), signum, strsignal(signum), handler.handler);
  544. auto old_esp = m_cpu->esp().value();
  545. auto signal_info = m_signal_data[signum];
  546. signal_info.context.uc_sigmask = m_signal_mask;
  547. signal_info.context.uc_stack = {
  548. .ss_sp = bit_cast<void*>(old_esp),
  549. .ss_flags = 0,
  550. .ss_size = 0,
  551. };
  552. signal_info.context.uc_mcontext = __mcontext {
  553. .eax = m_cpu->eax().value(),
  554. .ecx = m_cpu->ecx().value(),
  555. .edx = m_cpu->edx().value(),
  556. .ebx = m_cpu->ebx().value(),
  557. .esp = m_cpu->esp().value(),
  558. .ebp = m_cpu->ebp().value(),
  559. .esi = m_cpu->esi().value(),
  560. .edi = m_cpu->edi().value(),
  561. .eip = m_cpu->eip(),
  562. .eflags = m_cpu->eflags(),
  563. .cs = m_cpu->cs(),
  564. .ss = m_cpu->ss(),
  565. .ds = m_cpu->ds(),
  566. .es = m_cpu->es(),
  567. // ???
  568. .fs = 0,
  569. .gs = 0,
  570. };
  571. // Align the stack to 16 bytes.
  572. // Note that we push some elements on to the stack before the return address,
  573. // so we need to account for this here.
  574. constexpr static FlatPtr elements_pushed_on_stack_before_handler_address = 1; // one slot for a saved register
  575. FlatPtr const extra_bytes_pushed_on_stack_before_handler_address = sizeof(ucontext_t) + sizeof(siginfo_t);
  576. FlatPtr stack_alignment = (old_esp - elements_pushed_on_stack_before_handler_address * sizeof(FlatPtr) + extra_bytes_pushed_on_stack_before_handler_address) % 16;
  577. // Also note that we have to skip the thread red-zone (if needed), so do that here.
  578. old_esp -= stack_alignment;
  579. m_cpu->set_esp(shadow_wrap_with_taint_from(old_esp, m_cpu->esp()));
  580. m_cpu->push32(shadow_wrap_as_initialized(0u)); // syscall return value slot
  581. m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.context), sizeof(ucontext_t));
  582. auto pointer_to_ucontext = m_cpu->esp().value();
  583. m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.signal_info), sizeof(siginfo_t));
  584. auto pointer_to_signal_info = m_cpu->esp().value();
  585. // FPU state, leave a 512-byte gap. FIXME: Fill this in.
  586. m_cpu->set_esp({ m_cpu->esp().value() - 512, m_cpu->esp().shadow() });
  587. // Leave one empty slot to align the stack for a handler call.
  588. m_cpu->push32(shadow_wrap_as_initialized(0u));
  589. m_cpu->push32(shadow_wrap_as_initialized(pointer_to_ucontext));
  590. m_cpu->push32(shadow_wrap_as_initialized(pointer_to_signal_info));
  591. m_cpu->push32(shadow_wrap_as_initialized(static_cast<u32>(signum)));
  592. m_cpu->push32(shadow_wrap_as_initialized<u32>(handler.handler));
  593. m_cpu->set_eip(m_signal_trampoline);
  594. }
  595. // Make sure the compiler doesn't "optimize away" this function:
  596. static void signal_trampoline_dummy() __attribute__((used));
  597. NEVER_INLINE void signal_trampoline_dummy()
  598. {
  599. // The trampoline preserves the current eax, pushes the signal code and
  600. // then calls the signal handler. We do this because, when interrupting a
  601. // blocking syscall, that syscall may return some special error code in eax;
  602. // This error code would likely be overwritten by the signal handler, so it's
  603. // necessary to preserve it here.
  604. constexpr static auto offset_to_first_register_slot = sizeof(__ucontext) + sizeof(siginfo) + 512 + 4 * sizeof(FlatPtr);
  605. asm(
  606. ".intel_syntax noprefix\n"
  607. ".globl asm_signal_trampoline\n"
  608. "asm_signal_trampoline:\n"
  609. // stack state: 0, ucontext, signal_info, (alignment = 16), fpu_state (alignment = 16), 0, ucontext*, siginfo*, signal, (alignment = 16), handler
  610. // Pop the handler into ecx
  611. "pop ecx\n" // save handler
  612. // we have to save eax 'cause it might be the return value from a syscall
  613. "mov [esp+%P2], eax\n"
  614. // Note that the stack is currently aligned to 16 bytes as we popped the extra entries above.
  615. // and it's already setup to call the handler with the expected values on the stack.
  616. // call the signal handler
  617. "call ecx\n"
  618. // drop the 4 arguments
  619. "add esp, 16\n"
  620. // Current stack state is just saved_eax, ucontext, signal_info, fpu_state?.
  621. // syscall SC_sigreturn
  622. "mov eax, %P0\n"
  623. "int 0x82\n"
  624. ".globl asm_signal_trampoline_end\n"
  625. "asm_signal_trampoline_end:\n"
  626. ".att_syntax"
  627. :
  628. : "i"(Syscall::SC_sigreturn),
  629. "i"(offset_to_first_register_slot),
  630. "i"(offset_to_first_register_slot - sizeof(FlatPtr)));
  631. }
  632. extern "C" void asm_signal_trampoline(void);
  633. extern "C" void asm_signal_trampoline_end(void);
  634. void Emulator::setup_signal_trampoline()
  635. {
  636. m_range_allocator.reserve_user_range(VirtualAddress(signal_trampoline_location), 4096);
  637. auto trampoline_region = make<SimpleRegion>(signal_trampoline_location, 4096);
  638. u8* trampoline = (u8*)asm_signal_trampoline;
  639. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  640. size_t trampoline_size = trampoline_end - trampoline;
  641. u8* code_ptr = trampoline_region->data();
  642. memcpy(code_ptr, trampoline, trampoline_size);
  643. m_signal_trampoline = trampoline_region->base();
  644. mmu().add_region(move(trampoline_region));
  645. }
  646. void Emulator::dump_regions() const
  647. {
  648. const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
  649. reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} "sv,
  650. region.base(),
  651. region.end() - 1,
  652. region.is_readable() ? 'R' : '-',
  653. region.is_writable() ? 'W' : '-',
  654. region.is_executable() ? 'X' : '-',
  655. is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
  656. is<MmapRegion>(region) ? "(mmap) " : "",
  657. region.is_stack() ? "(stack) " : "",
  658. region.is_text() ? "(text) " : "");
  659. return IterationDecision::Continue;
  660. });
  661. }
  662. bool Emulator::is_in_libsystem() const
  663. {
  664. return m_cpu->base_eip() >= m_libsystem_start && m_cpu->base_eip() < m_libsystem_end;
  665. }
  666. bool Emulator::is_in_loader_code() const
  667. {
  668. if (!m_loader_text_base.has_value() || !m_loader_text_size.has_value())
  669. return false;
  670. return (m_cpu->base_eip() >= m_loader_text_base.value() && m_cpu->base_eip() < m_loader_text_base.value() + m_loader_text_size.value());
  671. }
  672. }