Emulator.cpp 23 KB

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