Emulator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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/Debug.h>
  12. #include <AK/FileStream.h>
  13. #include <AK/Format.h>
  14. #include <AK/LexicalPath.h>
  15. #include <AK/MappedFile.h>
  16. #include <AK/StringUtils.h>
  17. #include <LibELF/AuxiliaryVector.h>
  18. #include <LibELF/Image.h>
  19. #include <LibELF/Validation.h>
  20. #include <LibX86/ELFSymbolProvider.h>
  21. #include <fcntl.h>
  22. #include <syscall.h>
  23. #include <unistd.h>
  24. #if defined(__GNUC__) && !defined(__clang__)
  25. # pragma GCC optimize("O3")
  26. #endif
  27. namespace UserspaceEmulator {
  28. static constexpr u32 stack_location = 0x10000000;
  29. static constexpr size_t stack_size = 1 * MiB;
  30. static Emulator* s_the;
  31. Emulator& Emulator::the()
  32. {
  33. VERIFY(s_the);
  34. return *s_the;
  35. }
  36. Emulator::Emulator(String const& executable_path, Vector<String> const& arguments, Vector<String> const& environment)
  37. : m_executable_path(executable_path)
  38. , m_arguments(arguments)
  39. , m_environment(environment)
  40. , m_mmu(*this)
  41. , m_cpu(*this)
  42. , m_editor(Line::Editor::construct())
  43. {
  44. m_malloc_tracer = make<MallocTracer>(*this);
  45. static constexpr FlatPtr userspace_range_base = 0x00800000;
  46. static constexpr FlatPtr userspace_range_ceiling = 0xbe000000;
  47. #ifdef UE_ASLR
  48. static constexpr FlatPtr page_mask = 0xfffff000u;
  49. size_t random_offset = (get_random<u8>() % 32 * MiB) & page_mask;
  50. FlatPtr base = userspace_range_base + random_offset;
  51. #else
  52. FlatPtr base = userspace_range_base;
  53. #endif
  54. m_range_allocator.initialize_with_range(VirtualAddress(base), userspace_range_ceiling - base);
  55. VERIFY(!s_the);
  56. s_the = this;
  57. // setup_stack(arguments, environment);
  58. register_signal_handlers();
  59. setup_signal_trampoline();
  60. }
  61. Vector<ELF::AuxiliaryValue> Emulator::generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, String executable_path, int executable_fd) const
  62. {
  63. // FIXME: This is not fully compatible with the auxiliary vector the kernel generates, this is just the bare
  64. // minimum to get the loader going.
  65. Vector<ELF::AuxiliaryValue> auxv;
  66. // PHDR/EXECFD
  67. // PH*
  68. auxv.append({ ELF::AuxiliaryValue::PageSize, PAGE_SIZE });
  69. auxv.append({ ELF::AuxiliaryValue::BaseAddress, (void*)load_base });
  70. auxv.append({ ELF::AuxiliaryValue::Entry, (void*)entry_eip });
  71. // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
  72. auxv.append({ ELF::AuxiliaryValue::Platform, "i386" });
  73. auxv.append({ ELF::AuxiliaryValue::ExecFilename, executable_path });
  74. auxv.append({ ELF::AuxiliaryValue::ExecFileDescriptor, executable_fd });
  75. auxv.append({ ELF::AuxiliaryValue::Null, 0L });
  76. return auxv;
  77. }
  78. void Emulator::setup_stack(Vector<ELF::AuxiliaryValue> aux_vector)
  79. {
  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& argument : m_arguments) {
  86. m_cpu.push_string(argument.characters());
  87. argv_entries.append(m_cpu.esp().value());
  88. }
  89. Vector<u32> env_entries;
  90. for (auto& variable : m_environment) {
  91. m_cpu.push_string(variable.characters());
  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 = MappedFile::map(m_executable_path);
  123. if (file_or_error.is_error()) {
  124. reportln("Unable to map {}: {}", 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. String interpreter_path;
  134. if (!ELF::validate_program_headers(*(Elf32_Ehdr const*)elf_image_data.data(), elf_image_data.size(), (u8 const*)elf_image_data.data(), elf_image_data.size(), &interpreter_path)) {
  135. reportln("failed to validate ELF file");
  136. return false;
  137. }
  138. VERIFY(!interpreter_path.is_null());
  139. dbgln("interpreter: {}", interpreter_path);
  140. auto interpreter_file_or_error = MappedFile::map(interpreter_path);
  141. VERIFY(!interpreter_file_or_error.is_error());
  142. auto interpreter_image_data = interpreter_file_or_error.value()->bytes();
  143. ELF::Image interpreter_image(interpreter_image_data);
  144. constexpr FlatPtr interpreter_load_offset = 0x08000000;
  145. interpreter_image.for_each_program_header([&](ELF::Image::ProgramHeader const& program_header) {
  146. // Loader is not allowed to have its own TLS regions
  147. VERIFY(program_header.type() != PT_TLS);
  148. if (program_header.type() == PT_LOAD) {
  149. auto region = make<SimpleRegion>(program_header.vaddr().offset(interpreter_load_offset).get(), program_header.size_in_memory());
  150. if (program_header.is_executable() && !program_header.is_writable())
  151. region->set_text(true);
  152. memcpy(region->data(), program_header.raw_data(), program_header.size_in_image());
  153. memset(region->shadow_data(), 0x01, program_header.size_in_memory());
  154. if (program_header.is_executable()) {
  155. m_loader_text_base = region->base();
  156. m_loader_text_size = region->size();
  157. }
  158. mmu().add_region(move(region));
  159. return IterationDecision::Continue;
  160. }
  161. return IterationDecision::Continue;
  162. });
  163. auto entry_point = interpreter_image.entry().offset(interpreter_load_offset).get();
  164. m_cpu.set_eip(entry_point);
  165. // executable_fd will be used by the loader
  166. int executable_fd = open(m_executable_path.characters(), O_RDONLY);
  167. if (executable_fd < 0)
  168. return false;
  169. auto aux_vector = generate_auxiliary_vector(interpreter_load_offset, entry_point, m_executable_path, executable_fd);
  170. setup_stack(move(aux_vector));
  171. return true;
  172. }
  173. int Emulator::exec()
  174. {
  175. // X86::ELFSymbolProvider symbol_provider(*m_elf);
  176. X86::ELFSymbolProvider* symbol_provider = nullptr;
  177. constexpr bool trace = false;
  178. size_t instructions_until_next_profile_dump = profile_instruction_interval();
  179. if (is_profiling() && m_loader_text_size.has_value())
  180. emit_profile_event(profile_stream(), "mmap", String::formatted(R"("ptr": {}, "size": {}, "name": "/usr/lib/Loader.so")", *m_loader_text_base, *m_loader_text_size));
  181. while (!m_shutdown) {
  182. if (m_steps_til_pause) [[likely]] {
  183. m_cpu.save_base_eip();
  184. auto insn = X86::Instruction::from_stream(m_cpu, true, true);
  185. // Exec cycle
  186. if constexpr (trace) {
  187. outln("{:p} \033[33;1m{}\033[0m", m_cpu.base_eip(), insn.to_string(m_cpu.base_eip(), symbol_provider));
  188. }
  189. (m_cpu.*insn.handler())(insn);
  190. if (is_profiling()) {
  191. if (instructions_until_next_profile_dump == 0) {
  192. instructions_until_next_profile_dump = profile_instruction_interval();
  193. emit_profile_sample(profile_stream());
  194. } else {
  195. --instructions_until_next_profile_dump;
  196. }
  197. }
  198. if constexpr (trace) {
  199. m_cpu.dump();
  200. }
  201. if (m_pending_signals) [[unlikely]] {
  202. dispatch_one_pending_signal();
  203. }
  204. if (m_steps_til_pause > 0)
  205. m_steps_til_pause--;
  206. } else {
  207. handle_repl();
  208. }
  209. }
  210. if (auto* tracer = malloc_tracer())
  211. tracer->dump_leak_report();
  212. return m_exit_status;
  213. }
  214. void Emulator::handle_repl()
  215. {
  216. // Console interface
  217. // FIXME: Previous Instruction**s**
  218. // FIXME: Function names (base, call, jump)
  219. auto saved_eip = m_cpu.eip();
  220. m_cpu.save_base_eip();
  221. auto insn = X86::Instruction::from_stream(m_cpu, true, true);
  222. // FIXME: This does not respect inlining
  223. // another way of getting the current function is at need
  224. if (auto symbol = symbol_at(m_cpu.base_eip()); symbol.has_value()) {
  225. outln("[{}]: {}", symbol->lib_name, symbol->symbol);
  226. }
  227. outln("==> {}", create_instruction_line(m_cpu.base_eip(), insn));
  228. for (int i = 0; i < 7; ++i) {
  229. m_cpu.save_base_eip();
  230. insn = X86::Instruction::from_stream(m_cpu, true, true);
  231. outln(" {}", create_instruction_line(m_cpu.base_eip(), insn));
  232. }
  233. // We don't want to increase EIP here, we just want the instructions
  234. m_cpu.set_eip(saved_eip);
  235. outln();
  236. m_cpu.dump();
  237. outln();
  238. auto line_or_error = m_editor->get_line(">> ");
  239. if (line_or_error.is_error())
  240. return;
  241. // FIXME: find a way to find a global symbol-address for run-until-call
  242. auto help = [] {
  243. outln("Available commands:");
  244. outln("continue, c: Continue the execution");
  245. outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
  246. outln("ret, r: Run until function returns");
  247. outln("step, s [count]: Execute [count] instructions and then halt");
  248. outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
  249. };
  250. auto line = line_or_error.release_value();
  251. if (line.is_empty()) {
  252. if (m_editor->history().is_empty()) {
  253. help();
  254. return;
  255. }
  256. line = m_editor->history().last().entry;
  257. }
  258. auto parts = line.split_view(' ', false);
  259. m_editor->add_to_history(line);
  260. if (parts[0].is_one_of("s"sv, "step"sv)) {
  261. if (parts.size() == 1) {
  262. m_steps_til_pause = 1;
  263. return;
  264. }
  265. auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
  266. if (!number.has_value()) {
  267. outln("usage \"step [count]\"\n\tcount can't be less than 1");
  268. return;
  269. }
  270. m_steps_til_pause = number.value();
  271. } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
  272. m_steps_til_pause = -1;
  273. } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
  274. m_run_til_return = true;
  275. // FIXME: This may be uninitialized
  276. m_watched_addr = m_mmu.read32({ 0x23, m_cpu.ebp().value() + 4 }).value();
  277. m_steps_til_pause = -1;
  278. } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
  279. m_shutdown = true;
  280. } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
  281. if (parts.size() == 1) {
  282. did_receive_signal(SIGINT);
  283. return;
  284. } else if (parts.size() == 2) {
  285. auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
  286. if (number.has_value()) {
  287. did_receive_signal(number.value());
  288. return;
  289. }
  290. }
  291. outln("Usage: sig [signal:int], default: SINGINT:2");
  292. } else {
  293. help();
  294. }
  295. }
  296. Vector<FlatPtr> Emulator::raw_backtrace()
  297. {
  298. Vector<FlatPtr, 128> backtrace;
  299. backtrace.append(m_cpu.base_eip());
  300. // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
  301. u32 frame_ptr = m_cpu.ebp().value();
  302. while (frame_ptr) {
  303. u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
  304. if (!ret_ptr)
  305. break;
  306. backtrace.append(ret_ptr);
  307. frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
  308. }
  309. return backtrace;
  310. }
  311. MmapRegion const* Emulator::find_text_region(FlatPtr address)
  312. {
  313. MmapRegion const* matching_region = nullptr;
  314. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  315. if (!(region.is_executable() && address >= region.base() && address < region.base() + region.size()))
  316. return IterationDecision::Continue;
  317. matching_region = &region;
  318. return IterationDecision::Break;
  319. });
  320. return matching_region;
  321. }
  322. // FIXME: This interface isn't the nicest
  323. MmapRegion const* Emulator::load_library_from_address(FlatPtr address)
  324. {
  325. auto const* region = find_text_region(address);
  326. if (!region)
  327. return {};
  328. String lib_name = region->lib_name();
  329. if (lib_name.is_null())
  330. return {};
  331. String lib_path = lib_name;
  332. if (lib_name.ends_with(".so"))
  333. lib_path = String::formatted("/usr/lib/{}", lib_path);
  334. if (!m_dynamic_library_cache.contains(lib_path)) {
  335. auto file_or_error = MappedFile::map(lib_path);
  336. if (file_or_error.is_error())
  337. return {};
  338. auto image = make<ELF::Image>(file_or_error.value()->bytes());
  339. auto debug_info = make<Debug::DebugInfo>(*image);
  340. m_dynamic_library_cache.set(lib_path, CachedELF { file_or_error.release_value(), move(debug_info), move(image) });
  341. }
  342. return region;
  343. }
  344. MmapRegion const* Emulator::first_region_for_object(StringView name)
  345. {
  346. MmapRegion* ret = nullptr;
  347. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  348. if (region.lib_name() == name) {
  349. ret = &region;
  350. return IterationDecision::Break;
  351. }
  352. return IterationDecision::Continue;
  353. });
  354. return ret;
  355. }
  356. // FIXME: This disregards function inlining.
  357. Optional<Emulator::SymbolInfo> Emulator::symbol_at(FlatPtr address)
  358. {
  359. auto const* address_region = load_library_from_address(address);
  360. if (!address_region)
  361. return {};
  362. auto lib_name = address_region->lib_name();
  363. auto const* first_region = (lib_name.is_null() || lib_name.is_empty()) ? address_region : first_region_for_object(lib_name);
  364. VERIFY(first_region);
  365. auto lib_path = lib_name.ends_with(".so"sv) ? String::formatted("/usr/lib/{}", lib_name) : lib_name;
  366. auto it = m_dynamic_library_cache.find(lib_path);
  367. auto const& elf = it->value.debug_info->elf();
  368. auto symbol = elf.symbolicate(address - first_region->base());
  369. auto source_position = it->value.debug_info->get_source_position(address - first_region->base());
  370. return { { lib_name, symbol, source_position } };
  371. }
  372. String Emulator::create_backtrace_line(FlatPtr address)
  373. {
  374. auto maybe_symbol = symbol_at(address);
  375. if (!maybe_symbol.has_value()) {
  376. return String::formatted("=={}== {:p}", getpid(), address);
  377. } else if (!maybe_symbol->source_position.has_value()) {
  378. return String::formatted("=={}== {:p} [{}]: {}", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol);
  379. } else {
  380. auto const& source_position = maybe_symbol->source_position.value();
  381. return String::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);
  382. }
  383. }
  384. void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
  385. {
  386. for (auto& address : backtrace) {
  387. reportln("{}", create_backtrace_line(address));
  388. }
  389. }
  390. void Emulator::dump_backtrace()
  391. {
  392. dump_backtrace(raw_backtrace());
  393. }
  394. void Emulator::emit_profile_sample(AK::OutputStream& output)
  395. {
  396. if (!is_in_region_of_interest())
  397. return;
  398. StringBuilder builder;
  399. timeval tv {};
  400. gettimeofday(&tv, nullptr);
  401. builder.appendff(R"~(, {{"type": "sample", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [)~", getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000);
  402. builder.join(',', raw_backtrace());
  403. builder.append("]}\n");
  404. output.write_or_error(builder.string_view().bytes());
  405. }
  406. void Emulator::emit_profile_event(AK::OutputStream& output, StringView event_name, String contents)
  407. {
  408. StringBuilder builder;
  409. timeval tv {};
  410. gettimeofday(&tv, nullptr);
  411. builder.appendff(R"~(, {{"type": "{}", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [], {}}})~", event_name, getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000, contents);
  412. builder.append('\n');
  413. output.write_or_error(builder.string_view().bytes());
  414. }
  415. String Emulator::create_instruction_line(FlatPtr address, X86::Instruction insn)
  416. {
  417. auto symbol = symbol_at(address);
  418. if (!symbol.has_value() || !symbol->source_position.has_value())
  419. return String::formatted("{:p}: {}", address, insn.to_string(address));
  420. else
  421. return String::formatted("{:p}: {} \e[34;1m{}\e[0m:{}", address, insn.to_string(address), LexicalPath::basename(symbol->source_position->file_path), symbol->source_position.value().line_number);
  422. }
  423. static void emulator_signal_handler(int signum)
  424. {
  425. Emulator::the().did_receive_signal(signum);
  426. }
  427. static void emulator_sigint_handler(int signum)
  428. {
  429. Emulator::the().did_receive_sigint(signum);
  430. }
  431. void Emulator::register_signal_handlers()
  432. {
  433. for (int signum = 0; signum < NSIG; ++signum)
  434. signal(signum, emulator_signal_handler);
  435. signal(SIGINT, emulator_sigint_handler);
  436. }
  437. enum class DefaultSignalAction {
  438. Terminate,
  439. Ignore,
  440. DumpCore,
  441. Stop,
  442. Continue,
  443. };
  444. static DefaultSignalAction default_signal_action(int signal)
  445. {
  446. VERIFY(signal && signal < NSIG);
  447. switch (signal) {
  448. case SIGHUP:
  449. case SIGINT:
  450. case SIGKILL:
  451. case SIGPIPE:
  452. case SIGALRM:
  453. case SIGUSR1:
  454. case SIGUSR2:
  455. case SIGVTALRM:
  456. case SIGSTKFLT:
  457. case SIGIO:
  458. case SIGPROF:
  459. case SIGTERM:
  460. return DefaultSignalAction::Terminate;
  461. case SIGCHLD:
  462. case SIGURG:
  463. case SIGWINCH:
  464. case SIGINFO:
  465. return DefaultSignalAction::Ignore;
  466. case SIGQUIT:
  467. case SIGILL:
  468. case SIGTRAP:
  469. case SIGABRT:
  470. case SIGBUS:
  471. case SIGFPE:
  472. case SIGSEGV:
  473. case SIGXCPU:
  474. case SIGXFSZ:
  475. case SIGSYS:
  476. return DefaultSignalAction::DumpCore;
  477. case SIGCONT:
  478. return DefaultSignalAction::Continue;
  479. case SIGSTOP:
  480. case SIGTSTP:
  481. case SIGTTIN:
  482. case SIGTTOU:
  483. return DefaultSignalAction::Stop;
  484. }
  485. VERIFY_NOT_REACHED();
  486. }
  487. void Emulator::dispatch_one_pending_signal()
  488. {
  489. int signum = -1;
  490. for (signum = 1; signum < NSIG; ++signum) {
  491. int mask = 1 << signum;
  492. if (m_pending_signals & mask)
  493. break;
  494. }
  495. VERIFY(signum != -1);
  496. m_pending_signals &= ~(1 << signum);
  497. auto& handler = m_signal_handler[signum];
  498. if (handler.handler == 0) {
  499. // SIG_DFL
  500. auto action = default_signal_action(signum);
  501. if (action == DefaultSignalAction::Ignore)
  502. return;
  503. reportln("\n=={}== Got signal {} ({}), no handler registered", getpid(), signum, strsignal(signum));
  504. dump_backtrace();
  505. m_shutdown = true;
  506. return;
  507. }
  508. if (handler.handler == 1) {
  509. // SIG_IGN
  510. return;
  511. }
  512. reportln("\n=={}== Got signal {} ({}), handler at {:p}", getpid(), signum, strsignal(signum), handler.handler);
  513. auto old_esp = m_cpu.esp();
  514. u32 stack_alignment = (m_cpu.esp().value() - 52) % 16;
  515. m_cpu.set_esp(shadow_wrap_as_initialized(m_cpu.esp().value() - stack_alignment));
  516. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eflags()));
  517. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eip()));
  518. m_cpu.push32(m_cpu.eax());
  519. m_cpu.push32(m_cpu.ecx());
  520. m_cpu.push32(m_cpu.edx());
  521. m_cpu.push32(m_cpu.ebx());
  522. m_cpu.push32(old_esp);
  523. m_cpu.push32(m_cpu.ebp());
  524. m_cpu.push32(m_cpu.esi());
  525. m_cpu.push32(m_cpu.edi());
  526. // FIXME: Push old signal mask here.
  527. m_cpu.push32(shadow_wrap_as_initialized(0u));
  528. m_cpu.push32(shadow_wrap_as_initialized((u32)signum));
  529. m_cpu.push32(shadow_wrap_as_initialized(handler.handler));
  530. VERIFY((m_cpu.esp().value() % 16) == 0);
  531. m_cpu.push32(shadow_wrap_as_initialized(0u));
  532. m_cpu.set_eip(m_signal_trampoline);
  533. }
  534. // Make sure the compiler doesn't "optimize away" this function:
  535. static void signal_trampoline_dummy() __attribute__((used));
  536. NEVER_INLINE void signal_trampoline_dummy()
  537. {
  538. // The trampoline preserves the current eax, pushes the signal code and
  539. // then calls the signal handler. We do this because, when interrupting a
  540. // blocking syscall, that syscall may return some special error code in eax;
  541. // This error code would likely be overwritten by the signal handler, so it's
  542. // necessary to preserve it here.
  543. asm(
  544. ".intel_syntax noprefix\n"
  545. "asm_signal_trampoline:\n"
  546. "push ebp\n"
  547. "mov ebp, esp\n"
  548. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  549. "sub esp, 4\n" // align the stack to 16 bytes
  550. "mov eax, [ebp+12]\n" // push the signal code
  551. "push eax\n"
  552. "call [ebp+8]\n" // call the signal handler
  553. "add esp, 8\n"
  554. "mov eax, %P0\n"
  555. "int 0x82\n" // sigreturn syscall
  556. "asm_signal_trampoline_end:\n"
  557. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  558. }
  559. extern "C" void asm_signal_trampoline(void);
  560. extern "C" void asm_signal_trampoline_end(void);
  561. void Emulator::setup_signal_trampoline()
  562. {
  563. auto trampoline_region = make<SimpleRegion>(0xb0000000, 4096);
  564. u8* trampoline = (u8*)asm_signal_trampoline;
  565. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  566. size_t trampoline_size = trampoline_end - trampoline;
  567. u8* code_ptr = trampoline_region->data();
  568. memcpy(code_ptr, trampoline, trampoline_size);
  569. m_signal_trampoline = trampoline_region->base();
  570. mmu().add_region(move(trampoline_region));
  571. }
  572. void Emulator::dump_regions() const
  573. {
  574. const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
  575. reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} ",
  576. region.base(),
  577. region.end() - 1,
  578. region.is_readable() ? 'R' : '-',
  579. region.is_writable() ? 'W' : '-',
  580. region.is_executable() ? 'X' : '-',
  581. is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
  582. is<MmapRegion>(region) ? "(mmap) " : "",
  583. region.is_stack() ? "(stack) " : "",
  584. region.is_text() ? "(text) " : "");
  585. return IterationDecision::Continue;
  586. });
  587. }
  588. }