Emulator.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. extern bool g_dump_profile;
  28. extern unsigned g_profile_instruction_interval;
  29. extern Optional<OutputFileStream> g_profile_stream;
  30. namespace UserspaceEmulator {
  31. static constexpr u32 stack_location = 0x10000000;
  32. static constexpr size_t stack_size = 1 * MiB;
  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<String> 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_base = 0x00800000;
  49. static constexpr FlatPtr userspace_range_ceiling = 0xbe000000;
  50. #ifdef UE_ASLR
  51. static constexpr FlatPtr page_mask = 0xfffff000u;
  52. size_t random_offset = (get_random<u8>() % 32 * MiB) & page_mask;
  53. FlatPtr base = userspace_range_base + random_offset;
  54. #else
  55. FlatPtr base = userspace_range_base;
  56. #endif
  57. m_range_allocator.initialize_with_range(VirtualAddress(base), userspace_range_ceiling - base);
  58. VERIFY(!s_the);
  59. s_the = this;
  60. // setup_stack(arguments, environment);
  61. register_signal_handlers();
  62. setup_signal_trampoline();
  63. }
  64. Vector<ELF::AuxiliaryValue> Emulator::generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, String executable_path, int executable_fd) const
  65. {
  66. // FIXME: This is not fully compatible with the auxiliary vector the kernel generates, this is just the bare
  67. // minimum to get the loader going.
  68. Vector<ELF::AuxiliaryValue> auxv;
  69. // PHDR/EXECFD
  70. // PH*
  71. auxv.append({ ELF::AuxiliaryValue::PageSize, PAGE_SIZE });
  72. auxv.append({ ELF::AuxiliaryValue::BaseAddress, (void*)load_base });
  73. auxv.append({ ELF::AuxiliaryValue::Entry, (void*)entry_eip });
  74. // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
  75. auxv.append({ ELF::AuxiliaryValue::Platform, "i386" });
  76. auxv.append({ ELF::AuxiliaryValue::ExecFilename, executable_path });
  77. auxv.append({ ELF::AuxiliaryValue::ExecFileDescriptor, executable_fd });
  78. auxv.append({ ELF::AuxiliaryValue::Null, 0L });
  79. return auxv;
  80. }
  81. void Emulator::setup_stack(Vector<ELF::AuxiliaryValue> aux_vector)
  82. {
  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& argument : m_arguments) {
  89. m_cpu.push_string(argument.characters());
  90. argv_entries.append(m_cpu.esp().value());
  91. }
  92. Vector<u32> env_entries;
  93. for (auto& 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.characters());
  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 = 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 = 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 region = make<SimpleRegion>(program_header.vaddr().offset(interpreter_load_offset).get(), program_header.size_in_memory());
  153. if (program_header.is_executable() && !program_header.is_writable())
  154. region->set_text(true);
  155. memcpy(region->data(), program_header.raw_data(), program_header.size_in_image());
  156. memset(region->shadow_data(), 0x01, program_header.size_in_memory());
  157. if (program_header.is_executable()) {
  158. m_loader_text_base = region->base();
  159. m_loader_text_size = region->size();
  160. }
  161. mmu().add_region(move(region));
  162. return IterationDecision::Continue;
  163. }
  164. return IterationDecision::Continue;
  165. });
  166. auto entry_point = interpreter_image.entry().offset(interpreter_load_offset).get();
  167. m_cpu.set_eip(entry_point);
  168. // executable_fd will be used by the loader
  169. int executable_fd = open(m_executable_path.characters(), O_RDONLY);
  170. if (executable_fd < 0)
  171. return false;
  172. auto aux_vector = generate_auxiliary_vector(interpreter_load_offset, entry_point, m_executable_path, executable_fd);
  173. setup_stack(move(aux_vector));
  174. return true;
  175. }
  176. int Emulator::exec()
  177. {
  178. // X86::ELFSymbolProvider symbol_provider(*m_elf);
  179. X86::ELFSymbolProvider* symbol_provider = nullptr;
  180. constexpr bool trace = false;
  181. size_t instructions_until_next_profile_dump = g_profile_instruction_interval;
  182. if (g_dump_profile && m_loader_text_size.has_value())
  183. emit_profile_event(*g_profile_stream, "mmap", String::formatted(R"("ptr": {}, "size": {}, "name": "/usr/lib/Loader.so")", *m_loader_text_base, *m_loader_text_size));
  184. while (!m_shutdown) {
  185. if (m_steps_til_pause) [[likely]] {
  186. m_cpu.save_base_eip();
  187. auto insn = X86::Instruction::from_stream(m_cpu, true, true);
  188. // Exec cycle
  189. if constexpr (trace) {
  190. outln("{:p} \033[33;1m{}\033[0m", m_cpu.base_eip(), insn.to_string(m_cpu.base_eip(), symbol_provider));
  191. }
  192. (m_cpu.*insn.handler())(insn);
  193. if (g_dump_profile) {
  194. if (instructions_until_next_profile_dump == 0) {
  195. instructions_until_next_profile_dump = g_profile_instruction_interval;
  196. emit_profile_sample(*g_profile_stream);
  197. } else {
  198. --instructions_until_next_profile_dump;
  199. }
  200. }
  201. if constexpr (trace) {
  202. m_cpu.dump();
  203. }
  204. if (m_pending_signals) [[unlikely]] {
  205. dispatch_one_pending_signal();
  206. }
  207. if (m_steps_til_pause > 0)
  208. m_steps_til_pause--;
  209. } else {
  210. handle_repl();
  211. }
  212. }
  213. if (auto* tracer = malloc_tracer())
  214. tracer->dump_leak_report();
  215. return m_exit_status;
  216. }
  217. void Emulator::handle_repl()
  218. {
  219. // Console interface
  220. // FIXME: Previous Instruction**s**
  221. // FIXME: Function names (base, call, jump)
  222. auto saved_eip = m_cpu.eip();
  223. m_cpu.save_base_eip();
  224. auto insn = X86::Instruction::from_stream(m_cpu, true, true);
  225. // FIXME: This does not respect inlining
  226. // another way of getting the current function is at need
  227. if (auto symbol = symbol_at(m_cpu.base_eip()); symbol.has_value()) {
  228. outln("[{}]: {}", symbol->lib_name, symbol->symbol);
  229. }
  230. outln("==> {}", create_instruction_line(m_cpu.base_eip(), insn));
  231. for (int i = 0; i < 7; ++i) {
  232. m_cpu.save_base_eip();
  233. insn = X86::Instruction::from_stream(m_cpu, true, true);
  234. outln(" {}", create_instruction_line(m_cpu.base_eip(), insn));
  235. }
  236. // We don't want to increase EIP here, we just want the instructions
  237. m_cpu.set_eip(saved_eip);
  238. outln();
  239. m_cpu.dump();
  240. outln();
  241. auto line_or_error = m_editor->get_line(">> ");
  242. if (line_or_error.is_error())
  243. return;
  244. // FIXME: find a way to find a global symbol-address for run-until-call
  245. auto help = [] {
  246. outln("Available commands:");
  247. outln("continue, c: Continue the execution");
  248. outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
  249. outln("ret, r: Run until function returns");
  250. outln("step, s [count]: Execute [count] instructions and then halt");
  251. outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
  252. };
  253. auto line = line_or_error.release_value();
  254. if (line.is_empty()) {
  255. if (m_editor->history().is_empty()) {
  256. help();
  257. return;
  258. }
  259. line = m_editor->history().last().entry;
  260. }
  261. auto parts = line.split_view(' ', false);
  262. m_editor->add_to_history(line);
  263. if (parts[0].is_one_of("s"sv, "step"sv)) {
  264. if (parts.size() == 1) {
  265. m_steps_til_pause = 1;
  266. return;
  267. }
  268. auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
  269. if (!number.has_value()) {
  270. outln("usage \"step [count]\"\n\tcount can't be less than 1");
  271. return;
  272. }
  273. m_steps_til_pause = number.value();
  274. } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
  275. m_steps_til_pause = -1;
  276. } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
  277. m_run_til_return = true;
  278. // FIXME: This may be uninitialized
  279. m_watched_addr = m_mmu.read32({ 0x23, m_cpu.ebp().value() + 4 }).value();
  280. m_steps_til_pause = -1;
  281. } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
  282. m_shutdown = true;
  283. } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
  284. if (parts.size() == 1) {
  285. did_receive_signal(SIGINT);
  286. return;
  287. } else if (parts.size() == 2) {
  288. auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
  289. if (number.has_value()) {
  290. did_receive_signal(number.value());
  291. return;
  292. }
  293. }
  294. outln("Usage: sig [signal:int], default: SINGINT:2");
  295. } else {
  296. help();
  297. }
  298. }
  299. Vector<FlatPtr> Emulator::raw_backtrace()
  300. {
  301. Vector<FlatPtr, 128> backtrace;
  302. backtrace.append(m_cpu.base_eip());
  303. // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
  304. u32 frame_ptr = m_cpu.ebp().value();
  305. while (frame_ptr) {
  306. u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
  307. if (!ret_ptr)
  308. break;
  309. backtrace.append(ret_ptr);
  310. frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
  311. }
  312. return backtrace;
  313. }
  314. MmapRegion const* Emulator::find_text_region(FlatPtr address)
  315. {
  316. MmapRegion const* matching_region = nullptr;
  317. mmu().for_each_region([&](auto& region) {
  318. if (!is<MmapRegion>(region))
  319. return IterationDecision::Continue;
  320. auto const& mmap_region = static_cast<MmapRegion const&>(region);
  321. if (!(mmap_region.is_executable() && address >= mmap_region.base() && address < mmap_region.base() + mmap_region.size()))
  322. return IterationDecision::Continue;
  323. matching_region = &mmap_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 (region->name().contains(".so"))
  339. lib_path = String::formatted("/usr/lib/{}", lib_path);
  340. if (!m_dynamic_library_cache.contains(lib_path)) {
  341. auto file_or_error = 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.contains(".so"sv) ? String::formatted("/usr/lib/{}", lib_name) : lib_name;
  372. auto it = m_dynamic_library_cache.find(lib_path);
  373. auto const& elf = it->value.debug_info->elf();
  374. auto symbol = elf.symbolicate(address - first_region->base());
  375. auto source_position = it->value.debug_info->get_source_position(address - first_region->base());
  376. return { { lib_name, symbol, source_position } };
  377. }
  378. String Emulator::create_backtrace_line(FlatPtr address)
  379. {
  380. auto maybe_symbol = symbol_at(address);
  381. if (!maybe_symbol.has_value()) {
  382. return String::formatted("=={{{}}}== {:p}", getpid(), address);
  383. } else if (!maybe_symbol->source_position.has_value()) {
  384. return String::formatted("=={{{}}}== {:p} [{}]: {}", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol);
  385. } else {
  386. auto const& source_position = maybe_symbol->source_position.value();
  387. 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);
  388. }
  389. }
  390. void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
  391. {
  392. for (auto& address : backtrace) {
  393. reportln("{}", create_backtrace_line(address));
  394. }
  395. }
  396. void Emulator::dump_backtrace()
  397. {
  398. dump_backtrace(raw_backtrace());
  399. }
  400. void Emulator::emit_profile_sample(AK::OutputStream& output)
  401. {
  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("]}");
  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. output.write_or_error(builder.string_view().bytes());
  417. }
  418. String Emulator::create_instruction_line(FlatPtr address, X86::Instruction insn)
  419. {
  420. auto symbol = symbol_at(address);
  421. if (!symbol.has_value() || !symbol->source_position.has_value())
  422. return String::formatted("{:p}: {}", address, insn.to_string(address));
  423. else
  424. 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);
  425. }
  426. static void emulator_signal_handler(int signum)
  427. {
  428. Emulator::the().did_receive_signal(signum);
  429. }
  430. static void emulator_sigint_handler(int signum)
  431. {
  432. Emulator::the().did_receive_sigint(signum);
  433. }
  434. void Emulator::register_signal_handlers()
  435. {
  436. for (int signum = 0; signum < NSIG; ++signum)
  437. signal(signum, emulator_signal_handler);
  438. signal(SIGINT, emulator_sigint_handler);
  439. }
  440. enum class DefaultSignalAction {
  441. Terminate,
  442. Ignore,
  443. DumpCore,
  444. Stop,
  445. Continue,
  446. };
  447. static DefaultSignalAction default_signal_action(int signal)
  448. {
  449. VERIFY(signal && signal < NSIG);
  450. switch (signal) {
  451. case SIGHUP:
  452. case SIGINT:
  453. case SIGKILL:
  454. case SIGPIPE:
  455. case SIGALRM:
  456. case SIGUSR1:
  457. case SIGUSR2:
  458. case SIGVTALRM:
  459. case SIGSTKFLT:
  460. case SIGIO:
  461. case SIGPROF:
  462. case SIGTERM:
  463. return DefaultSignalAction::Terminate;
  464. case SIGCHLD:
  465. case SIGURG:
  466. case SIGWINCH:
  467. case SIGINFO:
  468. return DefaultSignalAction::Ignore;
  469. case SIGQUIT:
  470. case SIGILL:
  471. case SIGTRAP:
  472. case SIGABRT:
  473. case SIGBUS:
  474. case SIGFPE:
  475. case SIGSEGV:
  476. case SIGXCPU:
  477. case SIGXFSZ:
  478. case SIGSYS:
  479. return DefaultSignalAction::DumpCore;
  480. case SIGCONT:
  481. return DefaultSignalAction::Continue;
  482. case SIGSTOP:
  483. case SIGTSTP:
  484. case SIGTTIN:
  485. case SIGTTOU:
  486. return DefaultSignalAction::Stop;
  487. }
  488. VERIFY_NOT_REACHED();
  489. }
  490. void Emulator::dispatch_one_pending_signal()
  491. {
  492. int signum = -1;
  493. for (signum = 1; signum < NSIG; ++signum) {
  494. int mask = 1 << signum;
  495. if (m_pending_signals & mask)
  496. break;
  497. }
  498. VERIFY(signum != -1);
  499. m_pending_signals &= ~(1 << signum);
  500. auto& handler = m_signal_handler[signum];
  501. if (handler.handler == 0) {
  502. // SIG_DFL
  503. auto action = default_signal_action(signum);
  504. if (action == DefaultSignalAction::Ignore)
  505. return;
  506. reportln("\n=={}== Got signal {} ({}), no handler registered", getpid(), signum, strsignal(signum));
  507. dump_backtrace();
  508. m_shutdown = true;
  509. return;
  510. }
  511. if (handler.handler == 1) {
  512. // SIG_IGN
  513. return;
  514. }
  515. reportln("\n=={}== Got signal {} ({}), handler at {:p}", getpid(), signum, strsignal(signum), handler.handler);
  516. auto old_esp = m_cpu.esp();
  517. u32 stack_alignment = (m_cpu.esp().value() - 56) % 16;
  518. m_cpu.set_esp(shadow_wrap_as_initialized(m_cpu.esp().value() - stack_alignment));
  519. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eflags()));
  520. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eip()));
  521. m_cpu.push32(m_cpu.eax());
  522. m_cpu.push32(m_cpu.ecx());
  523. m_cpu.push32(m_cpu.edx());
  524. m_cpu.push32(m_cpu.ebx());
  525. m_cpu.push32(old_esp);
  526. m_cpu.push32(m_cpu.ebp());
  527. m_cpu.push32(m_cpu.esi());
  528. m_cpu.push32(m_cpu.edi());
  529. // FIXME: Push old signal mask here.
  530. m_cpu.push32(shadow_wrap_as_initialized(0u));
  531. m_cpu.push32(shadow_wrap_as_initialized((u32)signum));
  532. m_cpu.push32(shadow_wrap_as_initialized(handler.handler));
  533. m_cpu.push32(shadow_wrap_as_initialized(0u));
  534. VERIFY((m_cpu.esp().value() % 16) == 0);
  535. m_cpu.set_eip(m_signal_trampoline);
  536. }
  537. // Make sure the compiler doesn't "optimize away" this function:
  538. static void signal_trampoline_dummy() __attribute__((used));
  539. NEVER_INLINE void signal_trampoline_dummy()
  540. {
  541. // The trampoline preserves the current eax, pushes the signal code and
  542. // then calls the signal handler. We do this because, when interrupting a
  543. // blocking syscall, that syscall may return some special error code in eax;
  544. // This error code would likely be overwritten by the signal handler, so it's
  545. // necessary to preserve it here.
  546. asm(
  547. ".intel_syntax noprefix\n"
  548. "asm_signal_trampoline:\n"
  549. "push ebp\n"
  550. "mov ebp, esp\n"
  551. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  552. "sub esp, 4\n" // align the stack to 16 bytes
  553. "mov eax, [ebp+12]\n" // push the signal code
  554. "push eax\n"
  555. "call [ebp+8]\n" // call the signal handler
  556. "add esp, 8\n"
  557. "mov eax, %P0\n"
  558. "int 0x82\n" // sigreturn syscall
  559. "asm_signal_trampoline_end:\n"
  560. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  561. }
  562. extern "C" void asm_signal_trampoline(void);
  563. extern "C" void asm_signal_trampoline_end(void);
  564. void Emulator::setup_signal_trampoline()
  565. {
  566. auto trampoline_region = make<SimpleRegion>(0xb0000000, 4096);
  567. u8* trampoline = (u8*)asm_signal_trampoline;
  568. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  569. size_t trampoline_size = trampoline_end - trampoline;
  570. u8* code_ptr = trampoline_region->data();
  571. memcpy(code_ptr, trampoline, trampoline_size);
  572. m_signal_trampoline = trampoline_region->base();
  573. mmu().add_region(move(trampoline_region));
  574. }
  575. bool Emulator::find_malloc_symbols(MmapRegion const& libc_text)
  576. {
  577. auto file_or_error = MappedFile::map("/usr/lib/libc.so");
  578. if (file_or_error.is_error())
  579. return false;
  580. ELF::Image image(file_or_error.value()->bytes());
  581. auto malloc_symbol = image.find_demangled_function("malloc");
  582. auto free_symbol = image.find_demangled_function("free");
  583. auto realloc_symbol = image.find_demangled_function("realloc");
  584. auto calloc_symbol = image.find_demangled_function("calloc");
  585. auto malloc_size_symbol = image.find_demangled_function("malloc_size");
  586. if (!malloc_symbol.has_value() || !free_symbol.has_value() || !realloc_symbol.has_value() || !malloc_size_symbol.has_value())
  587. return false;
  588. m_malloc_symbol_start = malloc_symbol.value().value() + libc_text.base();
  589. m_malloc_symbol_end = m_malloc_symbol_start + malloc_symbol.value().size();
  590. m_free_symbol_start = free_symbol.value().value() + libc_text.base();
  591. m_free_symbol_end = m_free_symbol_start + free_symbol.value().size();
  592. m_realloc_symbol_start = realloc_symbol.value().value() + libc_text.base();
  593. m_realloc_symbol_end = m_realloc_symbol_start + realloc_symbol.value().size();
  594. m_calloc_symbol_start = calloc_symbol.value().value() + libc_text.base();
  595. m_calloc_symbol_end = m_calloc_symbol_start + calloc_symbol.value().size();
  596. m_malloc_size_symbol_start = malloc_size_symbol.value().value() + libc_text.base();
  597. m_malloc_size_symbol_end = m_malloc_size_symbol_start + malloc_size_symbol.value().size();
  598. return true;
  599. }
  600. void Emulator::dump_regions() const
  601. {
  602. const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
  603. reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} ",
  604. region.base(),
  605. region.end() - 1,
  606. region.is_readable() ? 'R' : '-',
  607. region.is_writable() ? 'W' : '-',
  608. region.is_executable() ? 'X' : '-',
  609. is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
  610. is<MmapRegion>(region) ? "(mmap) " : "",
  611. region.is_stack() ? "(stack) " : "",
  612. region.is_text() ? "(text) " : "");
  613. return IterationDecision::Continue;
  614. });
  615. }
  616. }