Emulator.cpp 23 KB

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