Emulator.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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 inlineing
  226. // another way of getting the current function is at need
  227. if (auto const* region = load_library_from_adress(m_cpu.base_eip())) {
  228. auto separator_index = region->name().find(":").value();
  229. String lib_name = region->name().substring(0, separator_index);
  230. String lib_path = lib_name;
  231. if (region->name().contains(".so"))
  232. lib_path = String::formatted("/usr/lib/{}", lib_path);
  233. auto it = m_dynamic_library_cache.find(lib_path);
  234. auto& elf = it->value.debug_info->elf();
  235. String symbol = elf.symbolicate(m_cpu.base_eip() - region->base());
  236. outln("[{}]: {}", lib_name, symbol);
  237. }
  238. outln("==> {}", create_instruction_line(m_cpu.base_eip(), insn));
  239. for (int i = 0; i < 7; ++i) {
  240. m_cpu.save_base_eip();
  241. insn = X86::Instruction::from_stream(m_cpu, true, true);
  242. outln(" {}", create_instruction_line(m_cpu.base_eip(), insn));
  243. }
  244. // We don't want to increase EIP here, we just want the instructions
  245. m_cpu.set_eip(saved_eip);
  246. outln();
  247. m_cpu.dump();
  248. outln();
  249. auto line_or_error = m_editor->get_line(">> ");
  250. if (line_or_error.is_error())
  251. return;
  252. // FIXME: find a way to find a global symbol-address for run-until-call
  253. auto help = [] {
  254. outln("Available commands:");
  255. outln("continue, c: Continue the execution");
  256. outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
  257. outln("ret, r: Run until function returns");
  258. outln("step, s [count]: Execute [count] instructions and then halt");
  259. outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
  260. };
  261. auto line = line_or_error.release_value();
  262. if (line.is_empty()) {
  263. if (m_editor->history().is_empty()) {
  264. help();
  265. return;
  266. }
  267. line = m_editor->history().last().entry;
  268. }
  269. auto parts = line.split_view(' ', false);
  270. m_editor->add_to_history(line);
  271. if (parts[0].is_one_of("s"sv, "step"sv)) {
  272. if (parts.size() == 1) {
  273. m_steps_til_pause = 1;
  274. return;
  275. }
  276. auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
  277. if (!number.has_value()) {
  278. outln("usage \"step [count]\"\n\tcount can't be less than 1");
  279. return;
  280. }
  281. m_steps_til_pause = number.value();
  282. } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
  283. m_steps_til_pause = -1;
  284. } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
  285. m_run_til_return = true;
  286. // FIXME: This may be uninitialized
  287. m_watched_addr = m_mmu.read32({ 0x23, m_cpu.ebp().value() + 4 }).value();
  288. m_steps_til_pause = -1;
  289. } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
  290. m_shutdown = true;
  291. } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
  292. if (parts.size() == 1) {
  293. did_receive_signal(SIGINT);
  294. return;
  295. } else if (parts.size() == 2) {
  296. auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
  297. if (number.has_value()) {
  298. did_receive_signal(number.value());
  299. return;
  300. }
  301. }
  302. outln("Usage: sig [signal:int], default: SINGINT:2");
  303. } else {
  304. help();
  305. }
  306. }
  307. Vector<FlatPtr> Emulator::raw_backtrace()
  308. {
  309. Vector<FlatPtr, 128> backtrace;
  310. backtrace.append(m_cpu.base_eip());
  311. // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
  312. u32 frame_ptr = m_cpu.ebp().value();
  313. while (frame_ptr) {
  314. u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
  315. if (!ret_ptr)
  316. break;
  317. backtrace.append(ret_ptr);
  318. frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
  319. }
  320. return backtrace;
  321. }
  322. MmapRegion const* Emulator::find_text_region(FlatPtr address)
  323. {
  324. MmapRegion const* matching_region = nullptr;
  325. mmu().for_each_region([&](auto& region) {
  326. if (!is<MmapRegion>(region))
  327. return IterationDecision::Continue;
  328. auto const& mmap_region = static_cast<MmapRegion const&>(region);
  329. if (!(mmap_region.is_executable() && address >= mmap_region.base() && address < mmap_region.base() + mmap_region.size()))
  330. return IterationDecision::Continue;
  331. matching_region = &mmap_region;
  332. return IterationDecision::Break;
  333. });
  334. return matching_region;
  335. }
  336. // FIXME: This interface isn't the nicest
  337. MmapRegion const* Emulator::load_library_from_adress(FlatPtr address)
  338. {
  339. auto const* region = find_text_region(address);
  340. if (!region)
  341. return {};
  342. auto separator_index = region->name().find(':');
  343. if (!separator_index.has_value())
  344. return {};
  345. String lib_name = region->name().substring(0, separator_index.value());
  346. String lib_path = lib_name;
  347. if (region->name().contains(".so"))
  348. lib_path = String::formatted("/usr/lib/{}", lib_path);
  349. if (!m_dynamic_library_cache.contains(lib_path)) {
  350. auto file_or_error = MappedFile::map(lib_path);
  351. if (file_or_error.is_error())
  352. return {};
  353. auto image = make<ELF::Image>(file_or_error.value()->bytes());
  354. auto debug_info = make<Debug::DebugInfo>(*image);
  355. m_dynamic_library_cache.set(lib_path, CachedELF { file_or_error.release_value(), move(debug_info), move(image) });
  356. }
  357. return region;
  358. }
  359. String Emulator::create_backtrace_line(FlatPtr address)
  360. {
  361. auto minimal = String::formatted("=={{{}}}== {:p}", getpid(), (void*)address);
  362. auto const* region = load_library_from_adress(address);
  363. if (!region)
  364. return minimal;
  365. // FIXME: This is redundant
  366. auto separator_index = region->name().find(":").value();
  367. String lib_name = region->name().substring(0, separator_index);
  368. String lib_path = lib_name;
  369. if (region->name().contains(".so"))
  370. lib_path = String::formatted("/usr/lib/{}", lib_path);
  371. auto it = m_dynamic_library_cache.find(lib_path);
  372. auto& elf = it->value.debug_info->elf();
  373. String symbol = elf.symbolicate(address - region->base());
  374. auto line_without_source_info = String::formatted("=={{{}}}== {:p} [{}]: {}", getpid(), (void*)address, lib_name, symbol);
  375. auto source_position = it->value.debug_info->get_source_position(address - region->base());
  376. if (source_position.has_value())
  377. 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);
  378. return line_without_source_info;
  379. }
  380. void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
  381. {
  382. for (auto& address : backtrace) {
  383. reportln("{}", create_backtrace_line(address));
  384. }
  385. }
  386. void Emulator::dump_backtrace()
  387. {
  388. dump_backtrace(raw_backtrace());
  389. }
  390. void Emulator::emit_profile_sample(AK::OutputStream& output)
  391. {
  392. StringBuilder builder;
  393. timeval tv {};
  394. gettimeofday(&tv, nullptr);
  395. builder.appendff(R"~(, {{"type": "sample", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [)~", getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000);
  396. builder.join(',', raw_backtrace());
  397. builder.append("]}");
  398. output.write_or_error(builder.string_view().bytes());
  399. }
  400. void Emulator::emit_profile_event(AK::OutputStream& output, StringView event_name, String contents)
  401. {
  402. StringBuilder builder;
  403. timeval tv {};
  404. gettimeofday(&tv, nullptr);
  405. builder.appendff(R"~(, {{"type": "{}", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [], {}}})~", event_name, getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000, contents);
  406. output.write_or_error(builder.string_view().bytes());
  407. }
  408. String Emulator::create_instruction_line(FlatPtr address, X86::Instruction insn)
  409. {
  410. auto minimal = String::formatted("{:p}: {}", (void*)address, insn.to_string(address));
  411. auto const* region = load_library_from_adress(address);
  412. if (!region)
  413. return minimal;
  414. // FIXME: This is redundant
  415. auto separator_index = region->name().find(":").value();
  416. String lib_name = region->name().substring(0, separator_index);
  417. String lib_path = lib_name;
  418. if (region->name().contains(".so"))
  419. lib_path = String::formatted("/usr/lib/{}", lib_path);
  420. auto it = m_dynamic_library_cache.find(lib_path);
  421. auto& elf = it->value.debug_info->elf();
  422. String symbol = elf.symbolicate(address - region->base());
  423. auto source_position = it->value.debug_info->get_source_position(address - region->base());
  424. if (!source_position.has_value())
  425. return minimal;
  426. 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);
  427. }
  428. static void emulator_signal_handler(int signum)
  429. {
  430. Emulator::the().did_receive_signal(signum);
  431. }
  432. static void emulator_sigint_handler(int signum)
  433. {
  434. Emulator::the().did_receive_sigint(signum);
  435. }
  436. void Emulator::register_signal_handlers()
  437. {
  438. for (int signum = 0; signum < NSIG; ++signum)
  439. signal(signum, emulator_signal_handler);
  440. signal(SIGINT, emulator_sigint_handler);
  441. }
  442. enum class DefaultSignalAction {
  443. Terminate,
  444. Ignore,
  445. DumpCore,
  446. Stop,
  447. Continue,
  448. };
  449. static DefaultSignalAction default_signal_action(int signal)
  450. {
  451. VERIFY(signal && signal < NSIG);
  452. switch (signal) {
  453. case SIGHUP:
  454. case SIGINT:
  455. case SIGKILL:
  456. case SIGPIPE:
  457. case SIGALRM:
  458. case SIGUSR1:
  459. case SIGUSR2:
  460. case SIGVTALRM:
  461. case SIGSTKFLT:
  462. case SIGIO:
  463. case SIGPROF:
  464. case SIGTERM:
  465. return DefaultSignalAction::Terminate;
  466. case SIGCHLD:
  467. case SIGURG:
  468. case SIGWINCH:
  469. case SIGINFO:
  470. return DefaultSignalAction::Ignore;
  471. case SIGQUIT:
  472. case SIGILL:
  473. case SIGTRAP:
  474. case SIGABRT:
  475. case SIGBUS:
  476. case SIGFPE:
  477. case SIGSEGV:
  478. case SIGXCPU:
  479. case SIGXFSZ:
  480. case SIGSYS:
  481. return DefaultSignalAction::DumpCore;
  482. case SIGCONT:
  483. return DefaultSignalAction::Continue;
  484. case SIGSTOP:
  485. case SIGTSTP:
  486. case SIGTTIN:
  487. case SIGTTOU:
  488. return DefaultSignalAction::Stop;
  489. }
  490. VERIFY_NOT_REACHED();
  491. }
  492. void Emulator::dispatch_one_pending_signal()
  493. {
  494. int signum = -1;
  495. for (signum = 1; signum < NSIG; ++signum) {
  496. int mask = 1 << signum;
  497. if (m_pending_signals & mask)
  498. break;
  499. }
  500. VERIFY(signum != -1);
  501. m_pending_signals &= ~(1 << signum);
  502. auto& handler = m_signal_handler[signum];
  503. if (handler.handler == 0) {
  504. // SIG_DFL
  505. auto action = default_signal_action(signum);
  506. if (action == DefaultSignalAction::Ignore)
  507. return;
  508. reportln("\n=={}== Got signal {} ({}), no handler registered", getpid(), signum, strsignal(signum));
  509. dump_backtrace();
  510. m_shutdown = true;
  511. return;
  512. }
  513. if (handler.handler == 1) {
  514. // SIG_IGN
  515. return;
  516. }
  517. reportln("\n=={}== Got signal {} ({}), handler at {:p}", getpid(), signum, strsignal(signum), handler.handler);
  518. auto old_esp = m_cpu.esp();
  519. u32 stack_alignment = (m_cpu.esp().value() - 56) % 16;
  520. m_cpu.set_esp(shadow_wrap_as_initialized(m_cpu.esp().value() - stack_alignment));
  521. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eflags()));
  522. m_cpu.push32(shadow_wrap_as_initialized(m_cpu.eip()));
  523. m_cpu.push32(m_cpu.eax());
  524. m_cpu.push32(m_cpu.ecx());
  525. m_cpu.push32(m_cpu.edx());
  526. m_cpu.push32(m_cpu.ebx());
  527. m_cpu.push32(old_esp);
  528. m_cpu.push32(m_cpu.ebp());
  529. m_cpu.push32(m_cpu.esi());
  530. m_cpu.push32(m_cpu.edi());
  531. // FIXME: Push old signal mask here.
  532. m_cpu.push32(shadow_wrap_as_initialized(0u));
  533. m_cpu.push32(shadow_wrap_as_initialized((u32)signum));
  534. m_cpu.push32(shadow_wrap_as_initialized(handler.handler));
  535. m_cpu.push32(shadow_wrap_as_initialized(0u));
  536. VERIFY((m_cpu.esp().value() % 16) == 0);
  537. m_cpu.set_eip(m_signal_trampoline);
  538. }
  539. // Make sure the compiler doesn't "optimize away" this function:
  540. static void signal_trampoline_dummy() __attribute__((used));
  541. NEVER_INLINE void signal_trampoline_dummy()
  542. {
  543. // The trampoline preserves the current eax, pushes the signal code and
  544. // then calls the signal handler. We do this because, when interrupting a
  545. // blocking syscall, that syscall may return some special error code in eax;
  546. // This error code would likely be overwritten by the signal handler, so it's
  547. // necessary to preserve it here.
  548. asm(
  549. ".intel_syntax noprefix\n"
  550. "asm_signal_trampoline:\n"
  551. "push ebp\n"
  552. "mov ebp, esp\n"
  553. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  554. "sub esp, 4\n" // align the stack to 16 bytes
  555. "mov eax, [ebp+12]\n" // push the signal code
  556. "push eax\n"
  557. "call [ebp+8]\n" // call the signal handler
  558. "add esp, 8\n"
  559. "mov eax, %P0\n"
  560. "int 0x82\n" // sigreturn syscall
  561. "asm_signal_trampoline_end:\n"
  562. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  563. }
  564. extern "C" void asm_signal_trampoline(void);
  565. extern "C" void asm_signal_trampoline_end(void);
  566. void Emulator::setup_signal_trampoline()
  567. {
  568. auto trampoline_region = make<SimpleRegion>(0xb0000000, 4096);
  569. u8* trampoline = (u8*)asm_signal_trampoline;
  570. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  571. size_t trampoline_size = trampoline_end - trampoline;
  572. u8* code_ptr = trampoline_region->data();
  573. memcpy(code_ptr, trampoline, trampoline_size);
  574. m_signal_trampoline = trampoline_region->base();
  575. mmu().add_region(move(trampoline_region));
  576. }
  577. bool Emulator::find_malloc_symbols(MmapRegion const& libc_text)
  578. {
  579. auto file_or_error = MappedFile::map("/usr/lib/libc.so");
  580. if (file_or_error.is_error())
  581. return false;
  582. ELF::Image image(file_or_error.value()->bytes());
  583. auto malloc_symbol = image.find_demangled_function("malloc");
  584. auto free_symbol = image.find_demangled_function("free");
  585. auto realloc_symbol = image.find_demangled_function("realloc");
  586. auto calloc_symbol = image.find_demangled_function("calloc");
  587. auto malloc_size_symbol = image.find_demangled_function("malloc_size");
  588. if (!malloc_symbol.has_value() || !free_symbol.has_value() || !realloc_symbol.has_value() || !malloc_size_symbol.has_value())
  589. return false;
  590. m_malloc_symbol_start = malloc_symbol.value().value() + libc_text.base();
  591. m_malloc_symbol_end = m_malloc_symbol_start + malloc_symbol.value().size();
  592. m_free_symbol_start = free_symbol.value().value() + libc_text.base();
  593. m_free_symbol_end = m_free_symbol_start + free_symbol.value().size();
  594. m_realloc_symbol_start = realloc_symbol.value().value() + libc_text.base();
  595. m_realloc_symbol_end = m_realloc_symbol_start + realloc_symbol.value().size();
  596. m_calloc_symbol_start = calloc_symbol.value().value() + libc_text.base();
  597. m_calloc_symbol_end = m_calloc_symbol_start + calloc_symbol.value().size();
  598. m_malloc_size_symbol_start = malloc_size_symbol.value().value() + libc_text.base();
  599. m_malloc_size_symbol_end = m_malloc_size_symbol_start + malloc_size_symbol.value().size();
  600. return true;
  601. }
  602. void Emulator::dump_regions() const
  603. {
  604. const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
  605. reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} ",
  606. region.base(),
  607. region.end() - 1,
  608. region.is_readable() ? 'R' : '-',
  609. region.is_writable() ? 'W' : '-',
  610. region.is_executable() ? 'X' : '-',
  611. is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
  612. is<MmapRegion>(region) ? "(mmap) " : "",
  613. region.is_stack() ? "(stack) " : "",
  614. region.is_text() ? "(text) " : "");
  615. return IterationDecision::Continue;
  616. });
  617. }
  618. }