Emulator.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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(AK_COMPILER_GCC)
  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(make<SoftCPU>(*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"sv });
  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.view());
  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 {}: {}"sv, 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. StringBuilder interpreter_path_builder;
  137. auto result_or_error = ELF::validate_program_headers(*(Elf32_Ehdr const*)elf_image_data.data(), elf_image_data.size(), elf_image_data, &interpreter_path_builder);
  138. if (result_or_error.is_error() || !result_or_error.value()) {
  139. reportln("failed to validate ELF file"sv);
  140. return false;
  141. }
  142. auto interpreter_path = interpreter_path_builder.string_view();
  143. VERIFY(!interpreter_path.is_null());
  144. dbgln("interpreter: {}", interpreter_path);
  145. auto interpreter_file_or_error = Core::MappedFile::map(interpreter_path);
  146. VERIFY(!interpreter_file_or_error.is_error());
  147. auto interpreter_image_data = interpreter_file_or_error.value()->bytes();
  148. ELF::Image interpreter_image(interpreter_image_data);
  149. constexpr FlatPtr interpreter_load_offset = 0x08000000;
  150. interpreter_image.for_each_program_header([&](ELF::Image::ProgramHeader const& program_header) {
  151. // Loader is not allowed to have its own TLS regions
  152. VERIFY(program_header.type() != PT_TLS);
  153. if (program_header.type() == PT_LOAD) {
  154. auto start_address = program_header.vaddr().offset(interpreter_load_offset);
  155. m_range_allocator.reserve_user_range(start_address, program_header.size_in_memory());
  156. auto region = make<SimpleRegion>(start_address.get(), program_header.size_in_memory());
  157. if (program_header.is_executable() && !program_header.is_writable())
  158. region->set_text(true);
  159. memcpy(region->data(), program_header.raw_data(), program_header.size_in_image());
  160. memset(region->shadow_data(), 0x01, program_header.size_in_memory());
  161. if (program_header.is_executable()) {
  162. m_loader_text_base = region->base();
  163. m_loader_text_size = region->size();
  164. }
  165. mmu().add_region(move(region));
  166. return IterationDecision::Continue;
  167. }
  168. return IterationDecision::Continue;
  169. });
  170. auto entry_point = interpreter_image.entry().offset(interpreter_load_offset).get();
  171. m_cpu->set_eip(entry_point);
  172. // executable_fd will be used by the loader
  173. int executable_fd = open(m_executable_path.characters(), O_RDONLY);
  174. if (executable_fd < 0)
  175. return false;
  176. auto aux_vector = generate_auxiliary_vector(interpreter_load_offset, entry_point, m_executable_path, executable_fd);
  177. setup_stack(move(aux_vector));
  178. return true;
  179. }
  180. int Emulator::exec()
  181. {
  182. // X86::ELFSymbolProvider symbol_provider(*m_elf);
  183. X86::ELFSymbolProvider* symbol_provider = nullptr;
  184. constexpr bool trace = false;
  185. size_t instructions_until_next_profile_dump = profile_instruction_interval();
  186. if (is_profiling() && m_loader_text_size.has_value())
  187. emit_profile_event(profile_stream(), "mmap"sv, String::formatted(R"("ptr": {}, "size": {}, "name": "/usr/lib/Loader.so")", *m_loader_text_base, *m_loader_text_size));
  188. while (!m_shutdown) {
  189. if (m_steps_til_pause) [[likely]] {
  190. m_cpu->save_base_eip();
  191. auto insn = X86::Instruction::from_stream(*m_cpu, true, true);
  192. // Exec cycle
  193. if constexpr (trace) {
  194. outln("{:p} \033[33;1m{}\033[0m", m_cpu->base_eip(), insn.to_string(m_cpu->base_eip(), symbol_provider));
  195. }
  196. (m_cpu->*insn.handler())(insn);
  197. if (is_profiling()) {
  198. if (instructions_until_next_profile_dump == 0) {
  199. instructions_until_next_profile_dump = profile_instruction_interval();
  200. emit_profile_sample(profile_stream());
  201. } else {
  202. --instructions_until_next_profile_dump;
  203. }
  204. }
  205. if constexpr (trace) {
  206. m_cpu->dump();
  207. }
  208. if (m_pending_signals) [[unlikely]] {
  209. dispatch_one_pending_signal();
  210. }
  211. if (m_steps_til_pause > 0)
  212. m_steps_til_pause--;
  213. } else {
  214. handle_repl();
  215. }
  216. }
  217. if (auto* tracer = malloc_tracer())
  218. tracer->dump_leak_report();
  219. return m_exit_status;
  220. }
  221. void Emulator::send_signal(int signal)
  222. {
  223. SignalInfo info {
  224. // FIXME: Fill this in somehow
  225. .signal_info = {
  226. .si_signo = signal,
  227. .si_code = SI_USER,
  228. .si_errno = 0,
  229. .si_pid = getpid(),
  230. .si_uid = geteuid(),
  231. .si_addr = 0,
  232. .si_status = 0,
  233. .si_band = 0,
  234. .si_value = {
  235. .sival_int = 0,
  236. },
  237. },
  238. .context = {},
  239. };
  240. did_receive_signal(signal, info, true);
  241. }
  242. void Emulator::handle_repl()
  243. {
  244. // Console interface
  245. // FIXME: Previous Instruction**s**
  246. // FIXME: Function names (base, call, jump)
  247. auto saved_eip = m_cpu->eip();
  248. m_cpu->save_base_eip();
  249. auto insn = X86::Instruction::from_stream(*m_cpu, true, true);
  250. // FIXME: This does not respect inlining
  251. // another way of getting the current function is at need
  252. if (auto symbol = symbol_at(m_cpu->base_eip()); symbol.has_value()) {
  253. outln("[{}]: {}", symbol->lib_name, symbol->symbol);
  254. }
  255. outln("==> {}", create_instruction_line(m_cpu->base_eip(), insn));
  256. for (int i = 0; i < 7; ++i) {
  257. m_cpu->save_base_eip();
  258. insn = X86::Instruction::from_stream(*m_cpu, true, true);
  259. outln(" {}", create_instruction_line(m_cpu->base_eip(), insn));
  260. }
  261. // We don't want to increase EIP here, we just want the instructions
  262. m_cpu->set_eip(saved_eip);
  263. outln();
  264. m_cpu->dump();
  265. outln();
  266. auto line_or_error = m_editor->get_line(">> ");
  267. if (line_or_error.is_error())
  268. return;
  269. // FIXME: find a way to find a global symbol-address for run-until-call
  270. auto help = [] {
  271. outln("Available commands:");
  272. outln("continue, c: Continue the execution");
  273. outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
  274. outln("ret, r: Run until function returns");
  275. outln("step, s [count]: Execute [count] instructions and then halt");
  276. outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
  277. };
  278. auto line = line_or_error.release_value();
  279. if (line.is_empty()) {
  280. if (m_editor->history().is_empty()) {
  281. help();
  282. return;
  283. }
  284. line = m_editor->history().last().entry;
  285. }
  286. auto parts = line.split_view(' ');
  287. m_editor->add_to_history(line);
  288. if (parts[0].is_one_of("s"sv, "step"sv)) {
  289. if (parts.size() == 1) {
  290. m_steps_til_pause = 1;
  291. return;
  292. }
  293. auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
  294. if (!number.has_value()) {
  295. outln("usage \"step [count]\"\n\tcount can't be less than 1");
  296. return;
  297. }
  298. m_steps_til_pause = number.value();
  299. } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
  300. m_steps_til_pause = -1;
  301. } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
  302. m_run_til_return = true;
  303. // FIXME: This may be uninitialized
  304. m_watched_addr = m_mmu.read32({ 0x23, m_cpu->ebp().value() + 4 }).value();
  305. m_steps_til_pause = -1;
  306. } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
  307. m_shutdown = true;
  308. } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
  309. if (parts.size() == 1) {
  310. send_signal(SIGINT);
  311. return;
  312. }
  313. if (parts.size() == 2) {
  314. auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
  315. if (number.has_value()) {
  316. send_signal(*number);
  317. return;
  318. }
  319. }
  320. outln("Usage: sig [signal:int], default: SINGINT:2");
  321. } else {
  322. help();
  323. }
  324. }
  325. Vector<FlatPtr> Emulator::raw_backtrace()
  326. {
  327. Vector<FlatPtr, 128> backtrace;
  328. backtrace.append(m_cpu->base_eip());
  329. // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
  330. u32 frame_ptr = m_cpu->ebp().value();
  331. while (frame_ptr) {
  332. u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
  333. if (!ret_ptr)
  334. break;
  335. backtrace.append(ret_ptr);
  336. frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
  337. }
  338. return backtrace;
  339. }
  340. MmapRegion const* Emulator::find_text_region(FlatPtr address)
  341. {
  342. MmapRegion const* matching_region = nullptr;
  343. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  344. if (!(region.is_executable() && address >= region.base() && address < region.base() + region.size()))
  345. return IterationDecision::Continue;
  346. matching_region = &region;
  347. return IterationDecision::Break;
  348. });
  349. return matching_region;
  350. }
  351. // FIXME: This interface isn't the nicest
  352. MmapRegion const* Emulator::load_library_from_address(FlatPtr address)
  353. {
  354. auto const* region = find_text_region(address);
  355. if (!region)
  356. return {};
  357. String lib_name = region->lib_name();
  358. if (lib_name.is_null())
  359. return {};
  360. String lib_path = lib_name;
  361. if (Core::File::looks_like_shared_library(lib_name))
  362. lib_path = String::formatted("/usr/lib/{}", lib_path);
  363. if (!m_dynamic_library_cache.contains(lib_path)) {
  364. auto file_or_error = Core::MappedFile::map(lib_path);
  365. if (file_or_error.is_error())
  366. return {};
  367. auto image = make<ELF::Image>(file_or_error.value()->bytes());
  368. auto debug_info = make<Debug::DebugInfo>(*image);
  369. m_dynamic_library_cache.set(lib_path, CachedELF { file_or_error.release_value(), move(debug_info), move(image) });
  370. }
  371. return region;
  372. }
  373. MmapRegion const* Emulator::first_region_for_object(StringView name)
  374. {
  375. MmapRegion* ret = nullptr;
  376. mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
  377. if (region.lib_name() == name) {
  378. ret = &region;
  379. return IterationDecision::Break;
  380. }
  381. return IterationDecision::Continue;
  382. });
  383. return ret;
  384. }
  385. // FIXME: This disregards function inlining.
  386. Optional<Emulator::SymbolInfo> Emulator::symbol_at(FlatPtr address)
  387. {
  388. auto const* address_region = load_library_from_address(address);
  389. if (!address_region)
  390. return {};
  391. auto lib_name = address_region->lib_name();
  392. auto const* first_region = (lib_name.is_null() || lib_name.is_empty()) ? address_region : first_region_for_object(lib_name);
  393. VERIFY(first_region);
  394. auto lib_path = lib_name;
  395. if (Core::File::looks_like_shared_library(lib_name)) {
  396. lib_path = String::formatted("/usr/lib/{}", lib_name);
  397. }
  398. auto it = m_dynamic_library_cache.find(lib_path);
  399. auto const& elf = it->value.debug_info->elf();
  400. auto symbol = elf.symbolicate(address - first_region->base());
  401. auto source_position = it->value.debug_info->get_source_position(address - first_region->base());
  402. return { { lib_name, symbol, source_position } };
  403. }
  404. String Emulator::create_backtrace_line(FlatPtr address)
  405. {
  406. auto maybe_symbol = symbol_at(address);
  407. if (!maybe_symbol.has_value()) {
  408. return String::formatted("=={}== {:p}", getpid(), address);
  409. }
  410. if (!maybe_symbol->source_position.has_value()) {
  411. return String::formatted("=={}== {:p} [{}]: {}", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol);
  412. }
  413. auto const& source_position = maybe_symbol->source_position.value();
  414. 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);
  415. }
  416. void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
  417. {
  418. for (auto const& address : backtrace) {
  419. reportln("{}"sv, create_backtrace_line(address));
  420. }
  421. }
  422. void Emulator::dump_backtrace()
  423. {
  424. dump_backtrace(raw_backtrace());
  425. }
  426. void Emulator::emit_profile_sample(AK::OutputStream& output)
  427. {
  428. if (!is_in_region_of_interest())
  429. return;
  430. StringBuilder builder;
  431. timeval tv {};
  432. gettimeofday(&tv, nullptr);
  433. builder.appendff(R"~(, {{"type": "sample", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [)~", getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000);
  434. builder.join(',', raw_backtrace());
  435. builder.append("]}\n"sv);
  436. output.write_or_error(builder.string_view().bytes());
  437. }
  438. void Emulator::emit_profile_event(AK::OutputStream& output, StringView event_name, String const& contents)
  439. {
  440. StringBuilder builder;
  441. timeval tv {};
  442. gettimeofday(&tv, nullptr);
  443. builder.appendff(R"~(, {{"type": "{}", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [], {}}})~", event_name, getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000, contents);
  444. builder.append('\n');
  445. output.write_or_error(builder.string_view().bytes());
  446. }
  447. String Emulator::create_instruction_line(FlatPtr address, X86::Instruction const& insn)
  448. {
  449. auto symbol = symbol_at(address);
  450. if (!symbol.has_value() || !symbol->source_position.has_value())
  451. return String::formatted("{:p}: {}", address, insn.to_string(address));
  452. 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);
  453. }
  454. static void emulator_signal_handler(int signum, siginfo_t* signal_info, void* context)
  455. {
  456. Emulator::the().did_receive_signal(signum, { *signal_info, *reinterpret_cast<ucontext_t*>(context) });
  457. }
  458. void Emulator::register_signal_handlers()
  459. {
  460. struct sigaction action {
  461. .sa_sigaction = emulator_signal_handler,
  462. .sa_mask = 0,
  463. .sa_flags = SA_SIGINFO,
  464. };
  465. sigemptyset(&action.sa_mask);
  466. for (int signum = 0; signum < NSIG; ++signum)
  467. sigaction(signum, &action, nullptr);
  468. }
  469. enum class DefaultSignalAction {
  470. Terminate,
  471. Ignore,
  472. DumpCore,
  473. Stop,
  474. Continue,
  475. };
  476. static DefaultSignalAction default_signal_action(int signal)
  477. {
  478. VERIFY(signal && signal < NSIG);
  479. switch (signal) {
  480. case SIGHUP:
  481. case SIGINT:
  482. case SIGKILL:
  483. case SIGPIPE:
  484. case SIGALRM:
  485. case SIGUSR1:
  486. case SIGUSR2:
  487. case SIGVTALRM:
  488. case SIGSTKFLT:
  489. case SIGIO:
  490. case SIGPROF:
  491. case SIGTERM:
  492. return DefaultSignalAction::Terminate;
  493. case SIGCHLD:
  494. case SIGURG:
  495. case SIGWINCH:
  496. case SIGINFO:
  497. return DefaultSignalAction::Ignore;
  498. case SIGQUIT:
  499. case SIGILL:
  500. case SIGTRAP:
  501. case SIGABRT:
  502. case SIGBUS:
  503. case SIGFPE:
  504. case SIGSEGV:
  505. case SIGXCPU:
  506. case SIGXFSZ:
  507. case SIGSYS:
  508. return DefaultSignalAction::DumpCore;
  509. case SIGCONT:
  510. return DefaultSignalAction::Continue;
  511. case SIGSTOP:
  512. case SIGTSTP:
  513. case SIGTTIN:
  514. case SIGTTOU:
  515. return DefaultSignalAction::Stop;
  516. }
  517. VERIFY_NOT_REACHED();
  518. }
  519. void Emulator::dispatch_one_pending_signal()
  520. {
  521. int signum = -1;
  522. for (signum = 1; signum < NSIG; ++signum) {
  523. int mask = 1 << signum;
  524. if (m_pending_signals & mask)
  525. break;
  526. }
  527. VERIFY(signum != -1);
  528. m_pending_signals &= ~(1 << signum);
  529. if (((1 << (signum - 1)) & m_signal_mask) != 0)
  530. return;
  531. auto& handler = m_signal_handler[signum];
  532. if (handler.handler == 0) {
  533. // SIG_DFL
  534. auto action = default_signal_action(signum);
  535. if (action == DefaultSignalAction::Ignore)
  536. return;
  537. reportln("\n=={}== Got signal {} ({}), no handler registered"sv, getpid(), signum, strsignal(signum));
  538. dump_backtrace();
  539. m_shutdown = true;
  540. return;
  541. }
  542. if (handler.handler == 1) {
  543. // SIG_IGN
  544. return;
  545. }
  546. reportln("\n=={}== Got signal {} ({}), handler at {:p}"sv, getpid(), signum, strsignal(signum), handler.handler);
  547. auto old_esp = m_cpu->esp().value();
  548. auto signal_info = m_signal_data[signum];
  549. signal_info.context.uc_sigmask = m_signal_mask;
  550. signal_info.context.uc_stack = {
  551. .ss_sp = bit_cast<void*>(old_esp),
  552. .ss_flags = 0,
  553. .ss_size = 0,
  554. };
  555. signal_info.context.uc_mcontext = __mcontext {
  556. .eax = m_cpu->eax().value(),
  557. .ecx = m_cpu->ecx().value(),
  558. .edx = m_cpu->edx().value(),
  559. .ebx = m_cpu->ebx().value(),
  560. .esp = m_cpu->esp().value(),
  561. .ebp = m_cpu->ebp().value(),
  562. .esi = m_cpu->esi().value(),
  563. .edi = m_cpu->edi().value(),
  564. .eip = m_cpu->eip(),
  565. .eflags = m_cpu->eflags(),
  566. .cs = m_cpu->cs(),
  567. .ss = m_cpu->ss(),
  568. .ds = m_cpu->ds(),
  569. .es = m_cpu->es(),
  570. // ???
  571. .fs = 0,
  572. .gs = 0,
  573. };
  574. // Align the stack to 16 bytes.
  575. // Note that we push some elements on to the stack before the return address,
  576. // so we need to account for this here.
  577. constexpr static FlatPtr elements_pushed_on_stack_before_handler_address = 1; // one slot for a saved register
  578. FlatPtr const extra_bytes_pushed_on_stack_before_handler_address = sizeof(ucontext_t) + sizeof(siginfo_t);
  579. FlatPtr stack_alignment = (old_esp - elements_pushed_on_stack_before_handler_address * sizeof(FlatPtr) + extra_bytes_pushed_on_stack_before_handler_address) % 16;
  580. // Also note that we have to skip the thread red-zone (if needed), so do that here.
  581. old_esp -= stack_alignment;
  582. m_cpu->set_esp(shadow_wrap_with_taint_from(old_esp, m_cpu->esp()));
  583. m_cpu->push32(shadow_wrap_as_initialized(0u)); // syscall return value slot
  584. m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.context), sizeof(ucontext_t));
  585. auto pointer_to_ucontext = m_cpu->esp().value();
  586. m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.signal_info), sizeof(siginfo_t));
  587. auto pointer_to_signal_info = m_cpu->esp().value();
  588. // FPU state, leave a 512-byte gap. FIXME: Fill this in.
  589. m_cpu->set_esp({ m_cpu->esp().value() - 512, m_cpu->esp().shadow() });
  590. // Leave one empty slot to align the stack for a handler call.
  591. m_cpu->push32(shadow_wrap_as_initialized(0u));
  592. m_cpu->push32(shadow_wrap_as_initialized(pointer_to_ucontext));
  593. m_cpu->push32(shadow_wrap_as_initialized(pointer_to_signal_info));
  594. m_cpu->push32(shadow_wrap_as_initialized(static_cast<u32>(signum)));
  595. m_cpu->push32(shadow_wrap_as_initialized<u32>(handler.handler));
  596. m_cpu->set_eip(m_signal_trampoline);
  597. }
  598. // Make sure the compiler doesn't "optimize away" this function:
  599. static void signal_trampoline_dummy() __attribute__((used));
  600. NEVER_INLINE void signal_trampoline_dummy()
  601. {
  602. // The trampoline preserves the current eax, pushes the signal code and
  603. // then calls the signal handler. We do this because, when interrupting a
  604. // blocking syscall, that syscall may return some special error code in eax;
  605. // This error code would likely be overwritten by the signal handler, so it's
  606. // necessary to preserve it here.
  607. constexpr static auto offset_to_first_register_slot = sizeof(__ucontext) + sizeof(siginfo) + 512 + 4 * sizeof(FlatPtr);
  608. asm(
  609. ".intel_syntax noprefix\n"
  610. ".globl asm_signal_trampoline\n"
  611. "asm_signal_trampoline:\n"
  612. // stack state: 0, ucontext, signal_info, (alignment = 16), fpu_state (alignment = 16), 0, ucontext*, siginfo*, signal, (alignment = 16), handler
  613. // Pop the handler into ecx
  614. "pop ecx\n" // save handler
  615. // we have to save eax 'cause it might be the return value from a syscall
  616. "mov [esp+%P2], eax\n"
  617. // Note that the stack is currently aligned to 16 bytes as we popped the extra entries above.
  618. // and it's already setup to call the handler with the expected values on the stack.
  619. // call the signal handler
  620. "call ecx\n"
  621. // drop the 4 arguments
  622. "add esp, 16\n"
  623. // Current stack state is just saved_eax, ucontext, signal_info, fpu_state?.
  624. // syscall SC_sigreturn
  625. "mov eax, %P0\n"
  626. "int 0x82\n"
  627. ".globl asm_signal_trampoline_end\n"
  628. "asm_signal_trampoline_end:\n"
  629. ".att_syntax"
  630. :
  631. : "i"(Syscall::SC_sigreturn),
  632. "i"(offset_to_first_register_slot),
  633. "i"(offset_to_first_register_slot - sizeof(FlatPtr)));
  634. }
  635. extern "C" void asm_signal_trampoline(void);
  636. extern "C" void asm_signal_trampoline_end(void);
  637. void Emulator::setup_signal_trampoline()
  638. {
  639. m_range_allocator.reserve_user_range(VirtualAddress(signal_trampoline_location), 4096);
  640. auto trampoline_region = make<SimpleRegion>(signal_trampoline_location, 4096);
  641. u8* trampoline = (u8*)asm_signal_trampoline;
  642. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  643. size_t trampoline_size = trampoline_end - trampoline;
  644. u8* code_ptr = trampoline_region->data();
  645. memcpy(code_ptr, trampoline, trampoline_size);
  646. m_signal_trampoline = trampoline_region->base();
  647. mmu().add_region(move(trampoline_region));
  648. }
  649. void Emulator::dump_regions() const
  650. {
  651. const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
  652. reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} "sv,
  653. region.base(),
  654. region.end() - 1,
  655. region.is_readable() ? 'R' : '-',
  656. region.is_writable() ? 'W' : '-',
  657. region.is_executable() ? 'X' : '-',
  658. is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
  659. is<MmapRegion>(region) ? "(mmap) " : "",
  660. region.is_stack() ? "(stack) " : "",
  661. region.is_text() ? "(text) " : "");
  662. return IterationDecision::Continue;
  663. });
  664. }
  665. bool Emulator::is_in_libsystem() const
  666. {
  667. return m_cpu->base_eip() >= m_libsystem_start && m_cpu->base_eip() < m_libsystem_end;
  668. }
  669. bool Emulator::is_in_loader_code() const
  670. {
  671. if (!m_loader_text_base.has_value() || !m_loader_text_size.has_value())
  672. return false;
  673. return (m_cpu->base_eip() >= m_loader_text_base.value() && m_cpu->base_eip() < m_loader_text_base.value() + m_loader_text_size.value());
  674. }
  675. }