Emulator.cpp 23 KB

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