Serenity Operating System
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
8#include "Emulator.h"
9#include "MmapRegion.h"
10#include "SimpleRegion.h"
11#include "SoftCPU.h"
12#include <AK/Format.h>
13#include <AK/LexicalPath.h>
14#include <AK/StringUtils.h>
15#include <Kernel/API/MemoryLayout.h>
16#include <LibCore/MappedFile.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
25#if defined(AK_COMPILER_GCC)
26# pragma GCC optimize("O3")
27#endif
28
29namespace UserspaceEmulator {
30
31static constexpr u32 stack_location = 0x10000000;
32static constexpr size_t stack_size = 1 * MiB;
33
34static constexpr u32 signal_trampoline_location = 0xb0000000;
35
36static Emulator* s_the;
37
38Emulator& Emulator::the()
39{
40 VERIFY(s_the);
41 return *s_the;
42}
43
44Emulator::Emulator(DeprecatedString const& executable_path, Vector<StringView> const& arguments, Vector<DeprecatedString> const& environment)
45 : m_executable_path(executable_path)
46 , m_arguments(arguments)
47 , m_environment(environment)
48 , m_mmu(*this)
49 , m_cpu(make<SoftCPU>(*this))
50 , m_editor(Line::Editor::construct())
51{
52 m_malloc_tracer = make<MallocTracer>(*this);
53
54 static constexpr FlatPtr userspace_range_ceiling = 0xbe000000;
55#ifdef UE_ASLR
56 static constexpr FlatPtr page_mask = 0xfffff000u;
57 size_t random_offset = (get_random<u8>() % 32 * MiB) & page_mask;
58 FlatPtr base = userspace_range_base + random_offset;
59#else
60 FlatPtr base = userspace_range_base;
61#endif
62
63 m_range_allocator.initialize_with_range(VirtualAddress(base), userspace_range_ceiling - base);
64
65 VERIFY(!s_the);
66 s_the = this;
67 // setup_stack(arguments, environment);
68 register_signal_handlers();
69 setup_signal_trampoline();
70}
71
72Vector<ELF::AuxiliaryValue> Emulator::generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, DeprecatedString const& executable_path, int executable_fd) const
73{
74 // FIXME: This is not fully compatible with the auxiliary vector the kernel generates, this is just the bare
75 // minimum to get the loader going.
76 Vector<ELF::AuxiliaryValue> auxv;
77 // PHDR/EXECFD
78 // PH*
79 auxv.append({ ELF::AuxiliaryValue::PageSize, PAGE_SIZE });
80 auxv.append({ ELF::AuxiliaryValue::BaseAddress, (void*)load_base });
81
82 auxv.append({ ELF::AuxiliaryValue::Entry, (void*)entry_eip });
83
84 // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
85 auxv.append({ ELF::AuxiliaryValue::Platform, "i386"sv });
86
87 auxv.append({ ELF::AuxiliaryValue::ExecFilename, executable_path });
88
89 auxv.append({ ELF::AuxiliaryValue::ExecFileDescriptor, executable_fd });
90
91 auxv.append({ ELF::AuxiliaryValue::Null, 0L });
92 return auxv;
93}
94
95void Emulator::setup_stack(Vector<ELF::AuxiliaryValue> aux_vector)
96{
97 m_range_allocator.reserve_user_range(VirtualAddress(stack_location), stack_size);
98 auto stack_region = make<SimpleRegion>(stack_location, stack_size);
99 stack_region->set_stack(true);
100 m_mmu.add_region(move(stack_region));
101 m_cpu->set_esp(shadow_wrap_as_initialized<u32>(stack_location + stack_size));
102
103 Vector<u32> argv_entries;
104
105 for (auto const& argument : m_arguments) {
106 m_cpu->push_string(argument);
107 argv_entries.append(m_cpu->esp().value());
108 }
109
110 Vector<u32> env_entries;
111
112 for (auto const& variable : m_environment) {
113 m_cpu->push_string(variable.view());
114 env_entries.append(m_cpu->esp().value());
115 }
116
117 for (auto& auxv : aux_vector) {
118 if (!auxv.optional_string.is_empty()) {
119 m_cpu->push_string(auxv.optional_string);
120 auxv.auxv.a_un.a_ptr = (void*)m_cpu->esp().value();
121 }
122 }
123
124 for (ssize_t i = aux_vector.size() - 1; i >= 0; --i) {
125 auto& value = aux_vector[i].auxv;
126 m_cpu->push_buffer((u8 const*)&value, sizeof(value));
127 }
128
129 m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // char** envp = { envv_entries..., nullptr }
130 for (ssize_t i = env_entries.size() - 1; i >= 0; --i)
131 m_cpu->push32(shadow_wrap_as_initialized(env_entries[i]));
132 u32 envp = m_cpu->esp().value();
133
134 m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // char** argv = { argv_entries..., nullptr }
135 for (ssize_t i = argv_entries.size() - 1; i >= 0; --i)
136 m_cpu->push32(shadow_wrap_as_initialized(argv_entries[i]));
137 u32 argv = m_cpu->esp().value();
138
139 while ((m_cpu->esp().value() + 4) % 16 != 0)
140 m_cpu->push32(shadow_wrap_as_initialized<u32>(0)); // (alignment)
141
142 u32 argc = argv_entries.size();
143 m_cpu->push32(shadow_wrap_as_initialized(envp));
144 m_cpu->push32(shadow_wrap_as_initialized(argv));
145 m_cpu->push32(shadow_wrap_as_initialized(argc));
146
147 VERIFY(m_cpu->esp().value() % 16 == 0);
148}
149
150bool Emulator::load_elf()
151{
152 auto file_or_error = Core::MappedFile::map(m_executable_path);
153 if (file_or_error.is_error()) {
154 reportln("Unable to map {}: {}"sv, m_executable_path, file_or_error.error());
155 return false;
156 }
157
158 auto elf_image_data = file_or_error.value()->bytes();
159 ELF::Image executable_elf(elf_image_data);
160
161 if (!executable_elf.is_dynamic()) {
162 // FIXME: Support static objects
163 VERIFY_NOT_REACHED();
164 }
165
166 StringBuilder interpreter_path_builder;
167 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);
168 if (result_or_error.is_error() || !result_or_error.value()) {
169 reportln("failed to validate ELF file"sv);
170 return false;
171 }
172 auto interpreter_path = interpreter_path_builder.string_view();
173
174 VERIFY(!interpreter_path.is_null());
175 dbgln("interpreter: {}", interpreter_path);
176
177 auto interpreter_file_or_error = Core::MappedFile::map(interpreter_path);
178 VERIFY(!interpreter_file_or_error.is_error());
179 auto interpreter_image_data = interpreter_file_or_error.value()->bytes();
180 ELF::Image interpreter_image(interpreter_image_data);
181
182 constexpr FlatPtr interpreter_load_offset = 0x08000000;
183 interpreter_image.for_each_program_header([&](ELF::Image::ProgramHeader const& program_header) {
184 // Loader is not allowed to have its own TLS regions
185 VERIFY(program_header.type() != PT_TLS);
186
187 if (program_header.type() == PT_LOAD) {
188 auto start_address = program_header.vaddr().offset(interpreter_load_offset);
189 m_range_allocator.reserve_user_range(start_address, program_header.size_in_memory());
190 auto region = make<SimpleRegion>(start_address.get(), program_header.size_in_memory());
191 if (program_header.is_executable() && !program_header.is_writable())
192 region->set_text(true);
193 memcpy(region->data(), program_header.raw_data(), program_header.size_in_image());
194 memset(region->shadow_data(), 0x01, program_header.size_in_memory());
195 if (program_header.is_executable()) {
196 m_loader_text_base = region->base();
197 m_loader_text_size = region->size();
198 }
199 mmu().add_region(move(region));
200 return IterationDecision::Continue;
201 }
202
203 return IterationDecision::Continue;
204 });
205
206 auto entry_point = interpreter_image.entry().offset(interpreter_load_offset).get();
207 m_cpu->set_eip(entry_point);
208
209 // executable_fd will be used by the loader
210 int executable_fd = open(m_executable_path.characters(), O_RDONLY);
211 if (executable_fd < 0)
212 return false;
213
214 auto aux_vector = generate_auxiliary_vector(interpreter_load_offset, entry_point, m_executable_path, executable_fd);
215 setup_stack(move(aux_vector));
216
217 return true;
218}
219
220int Emulator::exec()
221{
222 // X86::ELFSymbolProvider symbol_provider(*m_elf);
223 X86::ELFSymbolProvider* symbol_provider = nullptr;
224
225 constexpr bool trace = false;
226
227 size_t instructions_until_next_profile_dump = profile_instruction_interval();
228 if (is_profiling() && m_loader_text_size.has_value())
229 emit_profile_event(profile_stream(), "mmap"sv, DeprecatedString::formatted(R"("ptr": {}, "size": {}, "name": "/usr/lib/Loader.so")", *m_loader_text_base, *m_loader_text_size));
230
231 while (!m_shutdown) {
232 if (m_steps_til_pause) [[likely]] {
233 m_cpu->save_base_eip();
234 auto insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
235 // Exec cycle
236 if constexpr (trace) {
237 outln("{:p} \033[33;1m{}\033[0m", m_cpu->base_eip(), insn.to_deprecated_string(m_cpu->base_eip(), symbol_provider));
238 }
239
240 (m_cpu->*insn.handler())(insn);
241
242 if (is_profiling()) {
243 if (instructions_until_next_profile_dump == 0) {
244 instructions_until_next_profile_dump = profile_instruction_interval();
245 emit_profile_sample(profile_stream());
246 } else {
247 --instructions_until_next_profile_dump;
248 }
249 }
250
251 if constexpr (trace) {
252 m_cpu->dump();
253 }
254
255 if (m_pending_signals) [[unlikely]] {
256 dispatch_one_pending_signal();
257 }
258 if (m_steps_til_pause > 0)
259 m_steps_til_pause--;
260
261 } else {
262 handle_repl();
263 }
264 }
265
266 if (auto* tracer = malloc_tracer())
267 tracer->dump_leak_report();
268
269 return m_exit_status;
270}
271
272void Emulator::send_signal(int signal)
273{
274 SignalInfo info {
275 // FIXME: Fill this in somehow
276 .signal_info = {
277 .si_signo = signal,
278 .si_code = SI_USER,
279 .si_errno = 0,
280 .si_pid = getpid(),
281 .si_uid = geteuid(),
282 .si_addr = 0,
283 .si_status = 0,
284 .si_band = 0,
285 .si_value = {
286 .sival_int = 0,
287 },
288 },
289 .context = {},
290 };
291 did_receive_signal(signal, info, true);
292}
293
294void Emulator::handle_repl()
295{
296 // Console interface
297 // FIXME: Previous Instruction**s**
298 // FIXME: Function names (base, call, jump)
299 auto saved_eip = m_cpu->eip();
300 m_cpu->save_base_eip();
301 auto insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
302 // FIXME: This does not respect inlining
303 // another way of getting the current function is at need
304 if (auto symbol = symbol_at(m_cpu->base_eip()); symbol.has_value()) {
305 outln("[{}]: {}", symbol->lib_name, symbol->symbol);
306 }
307
308 outln("==> {}", create_instruction_line(m_cpu->base_eip(), insn));
309 for (int i = 0; i < 7; ++i) {
310 m_cpu->save_base_eip();
311 insn = X86::Instruction::from_stream(*m_cpu, X86::ProcessorMode::Protected);
312 outln(" {}", create_instruction_line(m_cpu->base_eip(), insn));
313 }
314 // We don't want to increase EIP here, we just want the instructions
315 m_cpu->set_eip(saved_eip);
316
317 outln();
318 m_cpu->dump();
319 outln();
320
321 auto line_or_error = m_editor->get_line(">> ");
322 if (line_or_error.is_error())
323 return;
324
325 // FIXME: find a way to find a global symbol-address for run-until-call
326 auto help = [] {
327 outln("Available commands:");
328 outln("continue, c: Continue the execution");
329 outln("quit, q: Quit the execution (this will \"kill\" the program and run checks)");
330 outln("ret, r: Run until function returns");
331 outln("step, s [count]: Execute [count] instructions and then halt");
332 outln("signal, sig [number:int], send signal to emulated program (default: sigint:2)");
333 };
334 auto line = line_or_error.release_value();
335 if (line.is_empty()) {
336 if (m_editor->history().is_empty()) {
337 help();
338 return;
339 }
340 line = m_editor->history().last().entry;
341 }
342
343 auto parts = line.split_view(' ');
344 m_editor->add_to_history(line);
345
346 if (parts[0].is_one_of("s"sv, "step"sv)) {
347 if (parts.size() == 1) {
348 m_steps_til_pause = 1;
349 return;
350 }
351 auto number = AK::StringUtils::convert_to_int<i64>(parts[1]);
352 if (!number.has_value()) {
353 outln("usage \"step [count]\"\n\tcount can't be less than 1");
354 return;
355 }
356 m_steps_til_pause = number.value();
357 } else if (parts[0].is_one_of("c"sv, "continue"sv)) {
358 m_steps_til_pause = -1;
359 } else if (parts[0].is_one_of("r"sv, "ret"sv)) {
360 m_run_til_return = true;
361 // FIXME: This may be uninitialized
362 m_watched_addr = m_mmu.read32({ 0x23, m_cpu->ebp().value() + 4 }).value();
363 m_steps_til_pause = -1;
364 } else if (parts[0].is_one_of("q"sv, "quit"sv)) {
365 m_shutdown = true;
366 } else if (parts[0].is_one_of("sig"sv, "signal"sv)) {
367 if (parts.size() == 1) {
368 send_signal(SIGINT);
369 return;
370 }
371 if (parts.size() == 2) {
372 auto number = AK::StringUtils::convert_to_int<i32>(parts[1]);
373 if (number.has_value()) {
374 send_signal(*number);
375 return;
376 }
377 }
378 outln("Usage: sig [signal:int], default: SINGINT:2");
379 } else {
380 help();
381 }
382}
383
384Vector<FlatPtr> Emulator::raw_backtrace()
385{
386 Vector<FlatPtr, 128> backtrace;
387 backtrace.append(m_cpu->base_eip());
388
389 // FIXME: Maybe do something if the backtrace has uninitialized data in the frame chain.
390
391 u32 frame_ptr = m_cpu->ebp().value();
392 while (frame_ptr) {
393 u32 ret_ptr = m_mmu.read32({ 0x23, frame_ptr + 4 }).value();
394 if (!ret_ptr)
395 break;
396 backtrace.append(ret_ptr);
397 frame_ptr = m_mmu.read32({ 0x23, frame_ptr }).value();
398 }
399 return backtrace;
400}
401
402MmapRegion const* Emulator::find_text_region(FlatPtr address)
403{
404 MmapRegion const* matching_region = nullptr;
405 mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
406 if (!(region.is_executable() && address >= region.base() && address < region.base() + region.size()))
407 return IterationDecision::Continue;
408 matching_region = ®ion;
409 return IterationDecision::Break;
410 });
411 return matching_region;
412}
413
414// FIXME: This interface isn't the nicest
415MmapRegion const* Emulator::load_library_from_address(FlatPtr address)
416{
417 auto const* region = find_text_region(address);
418 if (!region)
419 return {};
420
421 DeprecatedString lib_name = region->lib_name();
422 if (lib_name.is_null())
423 return {};
424
425 DeprecatedString lib_path = lib_name;
426 if (Core::DeprecatedFile::looks_like_shared_library(lib_name))
427 lib_path = DeprecatedString::formatted("/usr/lib/{}", lib_path);
428
429 if (!m_dynamic_library_cache.contains(lib_path)) {
430 auto file_or_error = Core::MappedFile::map(lib_path);
431 if (file_or_error.is_error())
432 return {};
433
434 auto image = make<ELF::Image>(file_or_error.value()->bytes());
435 auto debug_info = make<Debug::DebugInfo>(*image);
436 m_dynamic_library_cache.set(lib_path, CachedELF { file_or_error.release_value(), move(debug_info), move(image) });
437 }
438 return region;
439}
440
441MmapRegion const* Emulator::first_region_for_object(StringView name)
442{
443 MmapRegion* ret = nullptr;
444 mmu().for_each_region_of_type<MmapRegion>([&](auto& region) {
445 if (region.lib_name() == name) {
446 ret = ®ion;
447 return IterationDecision::Break;
448 }
449 return IterationDecision::Continue;
450 });
451 return ret;
452}
453
454// FIXME: This disregards function inlining.
455Optional<Emulator::SymbolInfo> Emulator::symbol_at(FlatPtr address)
456{
457 auto const* address_region = load_library_from_address(address);
458 if (!address_region)
459 return {};
460 auto lib_name = address_region->lib_name();
461 auto const* first_region = (lib_name.is_null() || lib_name.is_empty()) ? address_region : first_region_for_object(lib_name);
462 VERIFY(first_region);
463 auto lib_path = lib_name;
464 if (Core::DeprecatedFile::looks_like_shared_library(lib_name)) {
465 lib_path = DeprecatedString::formatted("/usr/lib/{}", lib_name);
466 }
467
468 auto it = m_dynamic_library_cache.find(lib_path);
469 auto const& elf = it->value.debug_info->elf();
470 auto symbol = elf.symbolicate(address - first_region->base());
471
472 auto source_position = it->value.debug_info->get_source_position(address - first_region->base());
473 return { { lib_name, symbol, source_position } };
474}
475
476DeprecatedString Emulator::create_backtrace_line(FlatPtr address)
477{
478 auto maybe_symbol = symbol_at(address);
479 if (!maybe_symbol.has_value()) {
480 return DeprecatedString::formatted("=={}== {:p}", getpid(), address);
481 }
482 if (!maybe_symbol->source_position.has_value()) {
483 return DeprecatedString::formatted("=={}== {:p} [{}]: {}", getpid(), address, maybe_symbol->lib_name, maybe_symbol->symbol);
484 }
485
486 auto const& source_position = maybe_symbol->source_position.value();
487 return DeprecatedString::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);
488}
489
490void Emulator::dump_backtrace(Vector<FlatPtr> const& backtrace)
491{
492 for (auto const& address : backtrace) {
493 reportln("{}"sv, create_backtrace_line(address));
494 }
495}
496
497void Emulator::dump_backtrace()
498{
499 dump_backtrace(raw_backtrace());
500}
501
502void Emulator::emit_profile_sample(Stream& output)
503{
504 if (!is_in_region_of_interest())
505 return;
506 StringBuilder builder;
507 timeval tv {};
508 gettimeofday(&tv, nullptr);
509 builder.appendff(R"~(, {{"type": "sample", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [)~", getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000);
510 builder.join(',', raw_backtrace());
511 builder.append("]}\n"sv);
512 output.write_until_depleted(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
513}
514
515void Emulator::emit_profile_event(Stream& output, StringView event_name, DeprecatedString const& contents)
516{
517 StringBuilder builder;
518 timeval tv {};
519 gettimeofday(&tv, nullptr);
520 builder.appendff(R"~(, {{"type": "{}", "pid": {}, "tid": {}, "timestamp": {}, "lost_samples": 0, "stack": [], {}}})~", event_name, getpid(), gettid(), tv.tv_sec * 1000 + tv.tv_usec / 1000, contents);
521 builder.append('\n');
522 output.write_until_depleted(builder.string_view().bytes()).release_value_but_fixme_should_propagate_errors();
523}
524
525DeprecatedString Emulator::create_instruction_line(FlatPtr address, X86::Instruction const& insn)
526{
527 auto symbol = symbol_at(address);
528 if (!symbol.has_value() || !symbol->source_position.has_value())
529 return DeprecatedString::formatted("{:p}: {}", address, insn.to_deprecated_string(address));
530
531 return DeprecatedString::formatted("{:p}: {} \e[34;1m{}\e[0m:{}", address, insn.to_deprecated_string(address), LexicalPath::basename(symbol->source_position->file_path), symbol->source_position.value().line_number);
532}
533
534static void emulator_signal_handler(int signum, siginfo_t* signal_info, void* context)
535{
536 Emulator::the().did_receive_signal(signum, { *signal_info, *reinterpret_cast<ucontext_t*>(context) });
537}
538
539void Emulator::register_signal_handlers()
540{
541 struct sigaction action {
542 .sa_sigaction = emulator_signal_handler,
543 .sa_mask = 0,
544 .sa_flags = SA_SIGINFO,
545 };
546 sigemptyset(&action.sa_mask);
547
548 for (int signum = 0; signum < NSIG; ++signum)
549 sigaction(signum, &action, nullptr);
550}
551
552enum class DefaultSignalAction {
553 Terminate,
554 Ignore,
555 DumpCore,
556 Stop,
557 Continue,
558};
559
560static DefaultSignalAction default_signal_action(int signal)
561{
562 VERIFY(signal && signal < NSIG);
563
564 switch (signal) {
565 case SIGHUP:
566 case SIGINT:
567 case SIGKILL:
568 case SIGPIPE:
569 case SIGALRM:
570 case SIGUSR1:
571 case SIGUSR2:
572 case SIGVTALRM:
573 case SIGSTKFLT:
574 case SIGIO:
575 case SIGPROF:
576 case SIGTERM:
577 return DefaultSignalAction::Terminate;
578 case SIGCHLD:
579 case SIGURG:
580 case SIGWINCH:
581 case SIGINFO:
582 return DefaultSignalAction::Ignore;
583 case SIGQUIT:
584 case SIGILL:
585 case SIGTRAP:
586 case SIGABRT:
587 case SIGBUS:
588 case SIGFPE:
589 case SIGSEGV:
590 case SIGXCPU:
591 case SIGXFSZ:
592 case SIGSYS:
593 return DefaultSignalAction::DumpCore;
594 case SIGCONT:
595 return DefaultSignalAction::Continue;
596 case SIGSTOP:
597 case SIGTSTP:
598 case SIGTTIN:
599 case SIGTTOU:
600 return DefaultSignalAction::Stop;
601 }
602 VERIFY_NOT_REACHED();
603}
604
605void Emulator::dispatch_one_pending_signal()
606{
607 int signum = -1;
608 for (signum = 1; signum < NSIG; ++signum) {
609 int mask = 1 << signum;
610 if (m_pending_signals & mask)
611 break;
612 }
613 VERIFY(signum != -1);
614 m_pending_signals &= ~(1 << signum);
615
616 if (((1 << (signum - 1)) & m_signal_mask) != 0)
617 return;
618
619 auto& handler = m_signal_handler[signum];
620
621 if (handler.handler == 0) {
622 // SIG_DFL
623 auto action = default_signal_action(signum);
624 if (action == DefaultSignalAction::Ignore)
625 return;
626 reportln("\n=={}== Got signal {} ({}), no handler registered"sv, getpid(), signum, strsignal(signum));
627 dump_backtrace();
628 m_shutdown = true;
629 return;
630 }
631
632 if (handler.handler == 1) {
633 // SIG_IGN
634 return;
635 }
636
637 reportln("\n=={}== Got signal {} ({}), handler at {:p}"sv, getpid(), signum, strsignal(signum), handler.handler);
638
639 auto old_esp = m_cpu->esp().value();
640
641 auto signal_info = m_signal_data[signum];
642 signal_info.context.uc_sigmask = m_signal_mask;
643 signal_info.context.uc_stack = {
644 .ss_sp = bit_cast<void*>(old_esp),
645 .ss_flags = 0,
646 .ss_size = 0,
647 };
648 signal_info.context.uc_mcontext = __mcontext {
649 .eax = m_cpu->eax().value(),
650 .ecx = m_cpu->ecx().value(),
651 .edx = m_cpu->edx().value(),
652 .ebx = m_cpu->ebx().value(),
653 .esp = m_cpu->esp().value(),
654 .ebp = m_cpu->ebp().value(),
655 .esi = m_cpu->esi().value(),
656 .edi = m_cpu->edi().value(),
657 .eip = m_cpu->eip(),
658 .eflags = m_cpu->eflags(),
659 .cs = m_cpu->cs(),
660 .ss = m_cpu->ss(),
661 .ds = m_cpu->ds(),
662 .es = m_cpu->es(),
663 // ???
664 .fs = 0,
665 .gs = 0,
666 };
667
668 // Align the stack to 16 bytes.
669 // Note that we push some elements on to the stack before the return address,
670 // so we need to account for this here.
671 constexpr static FlatPtr elements_pushed_on_stack_before_handler_address = 1; // one slot for a saved register
672 FlatPtr const extra_bytes_pushed_on_stack_before_handler_address = sizeof(ucontext_t) + sizeof(siginfo_t);
673 FlatPtr stack_alignment = (old_esp - elements_pushed_on_stack_before_handler_address * sizeof(FlatPtr) + extra_bytes_pushed_on_stack_before_handler_address) % 16;
674 // Also note that we have to skip the thread red-zone (if needed), so do that here.
675 old_esp -= stack_alignment;
676
677 m_cpu->set_esp(shadow_wrap_with_taint_from(old_esp, m_cpu->esp()));
678
679 m_cpu->push32(shadow_wrap_as_initialized(0u)); // syscall return value slot
680
681 m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.context), sizeof(ucontext_t));
682 auto pointer_to_ucontext = m_cpu->esp().value();
683
684 m_cpu->push_buffer(bit_cast<u8 const*>(&signal_info.signal_info), sizeof(siginfo_t));
685 auto pointer_to_signal_info = m_cpu->esp().value();
686
687 // FPU state, leave a 512-byte gap. FIXME: Fill this in.
688 m_cpu->set_esp({ m_cpu->esp().value() - 512, m_cpu->esp().shadow() });
689
690 // Leave one empty slot to align the stack for a handler call.
691 m_cpu->push32(shadow_wrap_as_initialized(0u));
692 m_cpu->push32(shadow_wrap_as_initialized(pointer_to_ucontext));
693 m_cpu->push32(shadow_wrap_as_initialized(pointer_to_signal_info));
694 m_cpu->push32(shadow_wrap_as_initialized(static_cast<u32>(signum)));
695
696 m_cpu->push32(shadow_wrap_as_initialized<u32>(handler.handler));
697
698 m_cpu->set_eip(m_signal_trampoline);
699}
700
701// Make sure the compiler doesn't "optimize away" this function:
702static void signal_trampoline_dummy() __attribute__((used));
703NEVER_INLINE void signal_trampoline_dummy()
704{
705 // The trampoline preserves the current eax, pushes the signal code and
706 // then calls the signal handler. We do this because, when interrupting a
707 // blocking syscall, that syscall may return some special error code in eax;
708 // This error code would likely be overwritten by the signal handler, so it's
709 // necessary to preserve it here.
710 constexpr static auto offset_to_first_register_slot = sizeof(__ucontext) + sizeof(siginfo) + 512 + 4 * sizeof(FlatPtr);
711 asm(
712 ".intel_syntax noprefix\n"
713 ".globl asm_signal_trampoline\n"
714 "asm_signal_trampoline:\n"
715 // stack state: 0, ucontext, signal_info, (alignment = 16), fpu_state (alignment = 16), 0, ucontext*, siginfo*, signal, (alignment = 16), handler
716
717 // Pop the handler into ecx
718 "pop ecx\n" // save handler
719 // we have to save eax 'cause it might be the return value from a syscall
720 "mov [esp+%P2], eax\n"
721 // Note that the stack is currently aligned to 16 bytes as we popped the extra entries above.
722 // and it's already setup to call the handler with the expected values on the stack.
723 // call the signal handler
724 "call ecx\n"
725 // drop the 4 arguments
726 "add esp, 16\n"
727 // Current stack state is just saved_eax, ucontext, signal_info, fpu_state?.
728 // syscall SC_sigreturn
729 "mov eax, %P0\n"
730 "int 0x82\n"
731 ".globl asm_signal_trampoline_end\n"
732 "asm_signal_trampoline_end:\n"
733 ".att_syntax"
734 :
735 : "i"(Syscall::SC_sigreturn),
736 "i"(offset_to_first_register_slot),
737 "i"(offset_to_first_register_slot - sizeof(FlatPtr)));
738}
739
740extern "C" void asm_signal_trampoline(void);
741extern "C" void asm_signal_trampoline_end(void);
742
743void Emulator::setup_signal_trampoline()
744{
745 m_range_allocator.reserve_user_range(VirtualAddress(signal_trampoline_location), 4096);
746 auto trampoline_region = make<SimpleRegion>(signal_trampoline_location, 4096);
747
748 u8* trampoline = (u8*)asm_signal_trampoline;
749 u8* trampoline_end = (u8*)asm_signal_trampoline_end;
750 size_t trampoline_size = trampoline_end - trampoline;
751
752 u8* code_ptr = trampoline_region->data();
753 memcpy(code_ptr, trampoline, trampoline_size);
754
755 m_signal_trampoline = trampoline_region->base();
756 mmu().add_region(move(trampoline_region));
757}
758
759void Emulator::dump_regions() const
760{
761 const_cast<SoftMMU&>(m_mmu).for_each_region([&](Region const& region) {
762 reportln("{:p}-{:p} {:c}{:c}{:c} {} {}{}{} "sv,
763 region.base(),
764 region.end() - 1,
765 region.is_readable() ? 'R' : '-',
766 region.is_writable() ? 'W' : '-',
767 region.is_executable() ? 'X' : '-',
768 is<MmapRegion>(region) ? static_cast<MmapRegion const&>(region).name() : "",
769 is<MmapRegion>(region) ? "(mmap) " : "",
770 region.is_stack() ? "(stack) " : "",
771 region.is_text() ? "(text) " : "");
772 return IterationDecision::Continue;
773 });
774}
775
776bool Emulator::is_in_libsystem() const
777{
778 return m_cpu->base_eip() >= m_libsystem_start && m_cpu->base_eip() < m_libsystem_end;
779}
780
781bool Emulator::is_in_loader_code() const
782{
783 if (!m_loader_text_base.has_value() || !m_loader_text_size.has_value())
784 return false;
785 return (m_cpu->base_eip() >= m_loader_text_base.value() && m_cpu->base_eip() < m_loader_text_base.value() + m_loader_text_size.value());
786}
787
788}