id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
17,533
child_process.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/child_process.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/child_process.h> #ifndef ANDROID #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #endif #include <atomic> #include <fstream> #include <mutex> #include <unordered_map> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <sys/eventfd.h> #include <sys/signalfd.h> #include <assert.h> #include <sys/wait.h> #ifndef ANDROID namespace io = boost::iostreams; #endif namespace { struct DeathObserverImpl : public core::posix::ChildProcess::DeathObserver { DeathObserverImpl(const std::shared_ptr<core::posix::SignalTrap>& trap) : on_sig_child_connection { trap->signal_raised().connect([this](core::posix::Signal signal) { switch (signal) { case core::posix::Signal::sig_chld: on_sig_child(); break; default: break; } }) } { if (!trap->has(core::posix::Signal::sig_chld)) throw std::logic_error( "DeathObserver::DeathObserverImpl: Given SignalTrap" " instance does not trap Signal::sig_chld."); } bool add(const core::posix::ChildProcess& process) override { if (process.pid() == -1) return false; std::lock_guard<std::mutex> lg(guard); bool added = false; auto new_process = std::make_pair(process.pid(), process); std::tie(std::ignore, added) = children.insert(new_process); if (added) { // The process may have died between it's instantiation and it // being added to the children map. Check that it's still alive. int status{-1}; if (::waitpid(process.pid(), &status, WNOHANG) != 0) // child no longer alive { // we missed the SIGCHLD signal so we must now manually // inform our subscribers. signals.child_died(new_process.second); children.erase(new_process.first); return false; } } return added; } bool has(const core::posix::ChildProcess& process) const override { std::lock_guard<std::mutex> lg(guard); return children.count(process.pid()) > 0; } const core::Signal<core::posix::ChildProcess>& child_died() const override { return signals.child_died; } void on_sig_child() override { pid_t pid{-1}; int status{-1}; while (true) { pid = ::waitpid(0, &status, WNOHANG); if (pid == -1) { if (errno == ECHILD) { break; // No more children } continue; // Ignore stray SIGCHLD signals } else if (pid == 0) { break; // No more children } else { std::lock_guard<std::mutex> lg(guard); auto it = children.find(pid); if (it != children.end()) { if (WIFSIGNALED(status) || WIFEXITED(status)) { signals.child_died(it->second); children.erase(it); } } } } } mutable std::mutex guard; std::unordered_map<pid_t, core::posix::ChildProcess> children; core::ScopedConnection on_sig_child_connection; struct { core::Signal<core::posix::ChildProcess> child_died; } signals; }; } std::unique_ptr<core::posix::ChildProcess::DeathObserver> core::posix::ChildProcess::DeathObserver::create_once_with_signal_trap( std::shared_ptr<core::posix::SignalTrap> trap) { static std::atomic<bool> has_been_created_once{false}; if (has_been_created_once.exchange(true)) throw std::runtime_error { "DeathObserver::create_once_with_signal_trap: " "Cannot create more than one instance." }; try { std::unique_ptr<core::posix::ChildProcess::DeathObserver> result { new DeathObserverImpl{trap} }; return result; } catch(...) { // We make sure that a throwing c'tor does not impact our ability to // retry creation of a DeathObserver instance. has_been_created_once.store(false); std::rethrow_exception(std::current_exception()); } assert(false && "We should never reach here."); // Silence the compiler. return std::unique_ptr<core::posix::ChildProcess::DeathObserver>{}; } namespace core { namespace posix { ChildProcess::Pipe ChildProcess::Pipe::invalid() { static Pipe p; static std::once_flag flag; std::call_once(flag, [&]() { p.close_read_fd(); p.close_write_fd(); }); return p; } ChildProcess::Pipe::Pipe() { int rc = ::pipe(fds); if (rc == -1) throw std::system_error(errno, std::system_category()); } ChildProcess::Pipe::Pipe(const ChildProcess::Pipe& rhs) : fds{-1, -1} { if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); } ChildProcess::Pipe::~Pipe() { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); } int ChildProcess::Pipe::read_fd() const { return fds[0]; } void ChildProcess::Pipe::close_read_fd() { if (fds[0] != -1) { ::close(fds[0]); fds[0] = -1; } } int ChildProcess::Pipe::write_fd() const { return fds[1]; } void ChildProcess::Pipe::close_write_fd() { if (fds[1] != -1) { ::close(fds[1]); fds[1] = -1; } } ChildProcess::Pipe& ChildProcess::Pipe::operator=(const ChildProcess::Pipe& rhs) { if (fds[0] != -1) ::close(fds[0]); if (fds[1] != -1) ::close(fds[1]); if (rhs.fds[0] != -1) fds[0] = ::dup(rhs.fds[0]); else fds[0] = -1; if (rhs.fds[1] != -1) fds[1] = ::dup(rhs.fds[1]); else fds[1] = -1; return *this; } struct ChildProcess::Private { // stdin and stdout are always "relative" to the childprocess, i.e., we // write to stdin of the child process and read from its stdout. Private(pid_t pid, const ChildProcess::Pipe& stderr, const ChildProcess::Pipe& stdin, const ChildProcess::Pipe& stdout) : pipes{stderr, stdin, stdout}, #ifndef ANDROID serr(pipes.stderr.read_fd(), io::never_close_handle), sin(pipes.stdin.write_fd(), io::never_close_handle), sout(pipes.stdout.read_fd(), io::never_close_handle), cerr(&serr), cin(&sin), cout(&sout), #endif original_parent_pid(::getpid()), original_child_pid(pid) { } ~Private() { // Check if we are in the original parent process. if (original_parent_pid == getpid() && !dont_kill_on_cleanup) { // If so, check if we are considering a valid pid here. // If so, we kill the original child. if (original_child_pid != -1) ::kill(original_child_pid, SIGKILL); } } struct { ChildProcess::Pipe stdin; ChildProcess::Pipe stdout; ChildProcess::Pipe stderr; } pipes; #ifndef ANDROID io::stream_buffer<io::file_descriptor_source> serr; io::stream_buffer<io::file_descriptor_sink> sin; io::stream_buffer<io::file_descriptor_source> sout; std::istream cerr; std::ostream cin; std::istream cout; #endif // We need to store the original parent pid as we might have been forked // and with our automatic cleanup in place, it might happen that the d'tor // is called from the child process. pid_t original_parent_pid; pid_t original_child_pid; bool dont_kill_on_cleanup = false; }; ChildProcess ChildProcess::invalid() { // We take the init process as child. static const pid_t invalid_pid = 1; return ChildProcess(invalid_pid, Pipe::invalid(), Pipe::invalid(), Pipe::invalid()); } ChildProcess::ChildProcess(pid_t pid, const ChildProcess::Pipe& stdin_pipe, const ChildProcess::Pipe& stdout_pipe, const ChildProcess::Pipe& stderr_pipe) : Process(pid), d(new Private{pid, stdin_pipe, stdout_pipe, stderr_pipe}) { } ChildProcess::~ChildProcess() { } wait::Result ChildProcess::wait_for(const wait::Flags& flags) { int status = -1; pid_t result_pid = ::waitpid(pid(), std::addressof(status), static_cast<int>(flags)); if (result_pid == -1) throw std::system_error(errno, std::system_category()); wait::Result result; if (result_pid == 0) { result.status = wait::Result::Status::no_state_change; return result; } if (WIFEXITED(status)) { result.status = wait::Result::Status::exited; result.detail.if_exited.status = static_cast<exit::Status>(WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { result.status = wait::Result::Status::signaled; result.detail.if_signaled.signal = static_cast<Signal>(WTERMSIG(status)); result.detail.if_signaled.core_dumped = WCOREDUMP(status); } else if (WIFSTOPPED(status)) { result.status = wait::Result::Status::stopped; result.detail.if_stopped.signal = static_cast<Signal>(WSTOPSIG(status)); } #ifndef ANDROID else if (WIFCONTINUED(status)) { result.status = wait::Result::Status::continued; } #endif return result; } void ChildProcess::dont_kill_on_cleanup() { d->dont_kill_on_cleanup = true; } #ifndef ANDROID std::istream& ChildProcess::cerr() { return d->cerr; } std::ostream& ChildProcess::cin() { return d->cin; } std::istream& ChildProcess::cout() { return d->cout; } #endif } }
10,823
C++
.cpp
360
23.105556
89
0.591884
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,534
backtrace.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/backtrace.cpp
/* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include "backtrace.h" #include <cxxabi.h> #include <execinfo.h> namespace bt = core::posix::backtrace; namespace impl { std::tuple<std::string, bool> demangle(const std::string& symbol) { int status = 1; auto result = abi::__cxa_demangle(symbol.c_str(), nullptr, nullptr, &status); if (!result || status != 0) { return std::make_tuple(std::string(), false); } std::string s{result}; ::free(result); return std::make_tuple(s, true); } struct Frame : public bt::Frame { struct Symbol : public bt::Frame::Symbol { Symbol(const char* symbol) : raw_(symbol) { auto first = raw_.find_first_of("("); auto last = raw_.find_last_of(")"); if (first != std::string::npos && last != std::string::npos) { auto mangled_symbol = raw_.substr(first+1, (last-1) - (first+1)); auto plus = mangled_symbol.find_first_of("+"); if (plus != std::string::npos) mangled_symbol.erase(plus); std::tie(demangled_, is_cxx_) = demangle(mangled_symbol); if (!is_cxx_) demangled_ = raw_; } } bool is_cxx() const { return is_cxx_; } std::string demangled() const { return demangled_; } std::string raw() const { return raw_; } std::string raw_; std::string demangled_; bool is_cxx_ = false; }; std::size_t depth_; void* frame_pointer_; Symbol symbol_; Frame(std::size_t depth, void* frame_pointer, const char* symbol) : depth_(depth), frame_pointer_(frame_pointer), symbol_(symbol) { } std::size_t depth() const { return depth_; } virtual void* frame_pointer() const { return frame_pointer_; } const Symbol& symbol() const { return symbol_; } }; } std::shared_ptr<bt::Frame::Symbol> bt::Frame::Symbol::for_testing_from_raw_symbol(const char* symbol) { return std::shared_ptr<bt::Frame::Symbol>(new impl::Frame::Symbol(symbol)); } void bt::visit_with_handler(const bt::FrameHandler& handler) { static const unsigned int max_frames=64; void *frames[max_frames]; auto frame_count = ::backtrace(frames, max_frames); auto symbols = ::backtrace_symbols(frames, frame_count); struct Scope { Scope(char** symbols) : symbols(symbols) { } ~Scope() { ::free(symbols); } char** symbols = nullptr; } scope{symbols}; for (int i = 0; i < frame_count; i++) { impl::Frame frame(i, frames[i], symbols[i]); if (!handler(frame)) return; } }
3,728
C++
.cpp
125
22.024
101
0.562552
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,535
fork.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/fork.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/exit.h> #include <core/posix/fork.h> #ifndef ANDROID #include "backtrace.h" #endif #include <iomanip> #include <iostream> #include <system_error> #include <unistd.h> namespace { void redirect_stream_to_fd(int fd, int stream) { auto rc = ::dup2(fd, stream); if (rc == -1) throw std::system_error(errno, std::system_category()); } void print_backtrace(std::ostream& out, const std::string& line_prefix) { #ifndef ANDROID core::posix::backtrace::visit_with_handler([&out, line_prefix](const core::posix::backtrace::Frame& frame) { out << line_prefix << std::dec << std::setw(2) << frame.depth() << "@" << std::hex << std::setw(14) << frame.frame_pointer() << ": " << (frame.symbol().is_cxx() ? frame.symbol().demangled() : frame.symbol().raw()) << std::endl; return true; }); #endif } } namespace core { namespace posix { bool is_child(pid_t pid) { return pid == 0; } ChildProcess fork(const std::function<posix::exit::Status()>& main, const StandardStream& flags) { ChildProcess::Pipe stdin_pipe{ChildProcess::Pipe::invalid()}; ChildProcess::Pipe stdout_pipe{ChildProcess::Pipe::invalid()}; ChildProcess::Pipe stderr_pipe{ChildProcess::Pipe::invalid()}; if ((flags & StandardStream::stdin) != StandardStream::empty) stdin_pipe = ChildProcess::Pipe(); if ((flags & StandardStream::stdout) != StandardStream::empty) stdout_pipe = ChildProcess::Pipe(); if ((flags & StandardStream::stderr) != StandardStream::empty) stderr_pipe = ChildProcess::Pipe(); pid_t pid = ::fork(); if (pid == -1) throw std::system_error(errno, std::system_category()); if (is_child(pid)) { posix::exit::Status result = posix::exit::Status::failure; try { stdin_pipe.close_write_fd(); stdout_pipe.close_read_fd(); stderr_pipe.close_read_fd(); // We replace stdin and stdout of the child process first: if ((flags & StandardStream::stdin) != StandardStream::empty) redirect_stream_to_fd(stdin_pipe.read_fd(), STDIN_FILENO); if ((flags & StandardStream::stdout) != StandardStream::empty) redirect_stream_to_fd(stdout_pipe.write_fd(), STDOUT_FILENO); if ((flags & StandardStream::stderr) != StandardStream::empty) redirect_stream_to_fd(stderr_pipe.write_fd(), STDERR_FILENO); result = main(); } catch(const std::exception& e) { std::cerr << "core::posix::fork(): An unhandled std::exception occured in the child process:" << std::endl << " what(): " << e.what() << std::endl; print_backtrace(std::cerr, " "); } catch(...) { std::cerr << "core::posix::fork(): An unhandled exception occured in the child process." << std::endl; print_backtrace(std::cerr, " "); } // We have to ensure that we exit here. Otherwise, we run into // all sorts of weird issues. ::exit(static_cast<int>(result)); } // We are in the parent process, and create a process object // corresponding to the newly forked process. stdin_pipe.close_read_fd(); stdout_pipe.close_write_fd(); stderr_pipe.close_write_fd(); return ChildProcess(pid, stdin_pipe, stdout_pipe, stderr_pipe); } ChildProcess vfork(const std::function<posix::exit::Status()>& main, const StandardStream& flags) { ChildProcess::Pipe stdin_pipe, stdout_pipe, stderr_pipe; pid_t pid = ::vfork(); if (pid == -1) throw std::system_error(errno, std::system_category()); if (is_child(pid)) { posix::exit::Status result = posix::exit::Status::failure; try { // We replace stdin and stdout of the child process first: stdin_pipe.close_write_fd(); stdout_pipe.close_read_fd(); stderr_pipe.close_read_fd(); // We replace stdin and stdout of the child process first: if ((flags & StandardStream::stdin) != StandardStream::empty) redirect_stream_to_fd(stdin_pipe.read_fd(), STDIN_FILENO); if ((flags & StandardStream::stdout) != StandardStream::empty) redirect_stream_to_fd(stdout_pipe.write_fd(), STDOUT_FILENO); if ((flags & StandardStream::stderr) != StandardStream::empty) redirect_stream_to_fd(stderr_pipe.write_fd(), STDERR_FILENO); result = main(); } catch(const std::exception& e) { std::cerr << "core::posix::fork(): An unhandled std::exception occured in the child process:" << std::endl << " what(): " << e.what() << std::endl; print_backtrace(std::cerr, " "); } catch(...) { std::cerr << "core::posix::fork(): An unhandled exception occured in the child process." << std::endl; print_backtrace(std::cerr, " "); } // We have to ensure that we exit here. Otherwise, we run into // all sorts of weird issues. ::exit(static_cast<int>(result)); } // We are in the parent process, and create a process object // corresponding to the newly forked process. // Close the parent's pipe end stdin_pipe.close_read_fd(); stdout_pipe.close_write_fd(); stderr_pipe.close_write_fd(); return ChildProcess(pid, stdin_pipe, stdout_pipe, stderr_pipe); } } }
6,418
C++
.cpp
157
33.140127
140
0.608151
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,536
signalable.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/signalable.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/signalable.h> namespace core { namespace posix { struct Signalable::Private { pid_t pid; }; Signalable::Signalable(pid_t pid) : d(new Private{pid}) { } void Signalable::send_signal_or_throw(Signal signal) { auto result = ::kill(d->pid, static_cast<int>(signal)); if (result == -1) throw std::system_error(errno, std::system_category()); } void Signalable::send_signal(Signal signal, std::error_code& e) noexcept { auto result = ::kill(d->pid, static_cast<int>(signal)); if (result == -1) { e = std::error_code(errno, std::system_category()); } } } }
1,330
C++
.cpp
45
27.022222
75
0.717868
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,537
signal.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/signal.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/signalable.h> #include <poll.h> #include <pthread.h> #include <sys/eventfd.h> #include <sys/signalfd.h> #include <unistd.h> #include <atomic> namespace impl { void set_thread_signal_mask(::sigset_t* new_mask, ::sigset_t* old_mask) { ::pthread_sigmask(SIG_BLOCK, new_mask, old_mask); } void set_process_signal_mask(::sigset_t* new_mask, ::sigset_t* old_mask) { ::sigprocmask(SIG_BLOCK, new_mask, old_mask); } class SignalTrap : public core::posix::SignalTrap { public: enum class Scope { process, thread }; enum class State { not_running, running }; SignalTrap(Scope scope, std::initializer_list<core::posix::Signal> blocked_signals) : scope(scope), state(State::not_running), event_fd(::eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)) { if (event_fd == -1) throw std::system_error(errno, std::system_category()); ::sigemptyset(&blocked_signals_mask); for(auto signal : blocked_signals) ::sigaddset(&blocked_signals_mask, static_cast<int>(signal)); switch (scope) { case Scope::process: set_process_signal_mask(&blocked_signals_mask, &old_signals_mask); break; case Scope::thread: set_thread_signal_mask(&blocked_signals_mask, &old_signals_mask); break; default: break; } } ~SignalTrap() { switch (scope) { case Scope::process: set_process_signal_mask(&old_signals_mask, nullptr); break; case Scope::thread: set_thread_signal_mask(&old_signals_mask, nullptr); break; default: break; } ::close(event_fd); } bool has(core::posix::Signal signal) override { return ::sigismember(&blocked_signals_mask, static_cast<int>(signal)); } void run() override { static constexpr int signal_fd_idx = 0; static constexpr int event_fd_idx = 1; static constexpr int signal_info_buffer_size = 5; if (state.load() == State::running) throw std::runtime_error("SignalTrap::run can only be run once."); state.store(State::running); // Make sure we clean up the signal fd whenever // we leave the scope of run. struct Scope { ~Scope() { if (signal_fd != -1) ::close(signal_fd); } int signal_fd; } scope{::signalfd(-1, &blocked_signals_mask, SFD_CLOEXEC | SFD_NONBLOCK)}; if (scope.signal_fd == -1) throw std::system_error(errno, std::system_category()); pollfd fds[2]; signalfd_siginfo signal_info[signal_info_buffer_size]; for (;;) { fds[signal_fd_idx] = {scope.signal_fd, POLLIN, 0}; fds[event_fd_idx] = {event_fd, POLLIN, 0}; auto rc = ::poll(fds, 2, -1); if (rc == -1) { if (errno == EINTR) continue; break; } if (rc == 0) continue; if (fds[signal_fd_idx].revents & POLLIN) { auto result = ::read(scope.signal_fd, signal_info, sizeof(signal_info)); for (unsigned int i = 0; i < result / sizeof(signalfd_siginfo); i++) { if (has(static_cast<core::posix::Signal>(signal_info[i].ssi_signo))) { on_signal_raised( static_cast<core::posix::Signal>( signal_info[i].ssi_signo)); } } } if (fds[event_fd_idx].revents & POLLIN) { std::int64_t value{1}; // Consciously void-ing the return value here. // Not much we can do about an error. auto result = ::read(event_fd, &value, sizeof(value)); (void) result; break; } } state.store(State::not_running); } void stop() override { static const std::int64_t value = {1}; if (sizeof(value) != ::write(event_fd, &value, sizeof(value))) throw std::system_error(errno, std::system_category()); } core::Signal<core::posix::Signal>& signal_raised() override { return on_signal_raised; } private: Scope scope; std::atomic<State> state; int event_fd; core::Signal<core::posix::Signal> on_signal_raised; ::sigset_t old_signals_mask; ::sigset_t blocked_signals_mask; }; } std::shared_ptr<core::posix::SignalTrap> core::posix::trap_signals_for_process( std::initializer_list<core::posix::Signal> blocked_signals) { return std::make_shared<impl::SignalTrap>( impl::SignalTrap::Scope::process, blocked_signals); } std::shared_ptr<core::posix::SignalTrap> core::posix::trap_signals_for_all_subsequent_threads( std::initializer_list<core::posix::Signal> blocked_signals) { return std::make_shared<impl::SignalTrap>( impl::SignalTrap::Scope::thread, blocked_signals); }
6,101
C++
.cpp
182
24.664835
94
0.570092
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,538
wait.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/wait.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/wait.h> namespace core { namespace posix { namespace wait { Flags operator|(Flags l, Flags r) { return static_cast<Flags>(static_cast<std::uint8_t>(l) | static_cast<std::uint8_t>(r)); } } } }
927
C++
.cpp
31
28.129032
91
0.751121
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,539
process.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/process.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/process.h> #include <core/posix/signal.h> #include <sys/types.h> #include <unistd.h> #include <iostream> namespace core { namespace posix { struct Process::Private { pid_t pid; }; Process Process::invalid() { static const pid_t invalid_pid = 0; Process p(invalid_pid); p.d->pid = -1; return p; } Process::Process(pid_t pid) : Signalable(pid), d(new Private{pid}) { if (pid < 0) throw std::runtime_error("Cannot construct instance for invalid pid."); } Process::~Process() noexcept { } pid_t Process::pid() const { return d->pid; } ProcessGroup Process::process_group_or_throw() const { pid_t pgid = ::getpgid(pid()); if (pgid == -1) throw std::system_error(errno, std::system_category()); return ProcessGroup(pgid); } ProcessGroup Process::process_group(std::error_code& se) const noexcept(true) { pid_t pgid = ::getpgid(pid()); if (pgid == -1) { se = std::error_code(errno, std::system_category()); } return ProcessGroup(pgid); } } }
1,775
C++
.cpp
69
22.855072
79
0.701838
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,540
this_process.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/this_process.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/this_process.h> #include <core/posix/process.h> #include <boost/algorithm/string.hpp> #include <iostream> #include <mutex> #include <sstream> #include <vector> #include <cerrno> #include <cstdlib> #if defined(_GNU_SOURCE) #include <unistd.h> #else extern char** environ; #endif namespace core { namespace posix { namespace this_process { namespace env { namespace { std::mutex& env_guard() { static std::mutex m; return m; } } void for_each(const std::function<void(const std::string&, const std::string&)>& functor) noexcept(true) { std::lock_guard<std::mutex> lg(env_guard()); auto it = ::environ; while (it != nullptr && *it != nullptr) { std::string line(*it); functor(line.substr(0,line.find_first_of('=')), line.substr(line.find_first_of('=')+1)); ++it; } } std::string get_or_throw(const std::string& key) { std::lock_guard<std::mutex> lg(env_guard()); auto result = ::getenv(key.c_str()); if (result == nullptr) { std::stringstream ss; ss << "Variable with name " << key << " is not defined in the environment"; throw std::runtime_error(ss.str()); } return std::string{result}; } std::string get(const std::string& key, const std::string& default_value) noexcept(true) { std::lock_guard<std::mutex> lg(env_guard()); auto result = ::getenv(key.c_str()); return std::string{result ? result : default_value}; } void unset_or_throw(const std::string& key) { std::lock_guard<std::mutex> lg(env_guard()); auto rc = ::unsetenv(key.c_str()); if (rc == -1) throw std::system_error(errno, std::system_category()); } bool unset(const std::string& key, std::error_code& se) noexcept(true) { std::lock_guard<std::mutex> lg(env_guard()); auto rc = ::unsetenv(key.c_str()); if (rc == -1) { se = std::error_code(errno, std::system_category()); return false; } return true; } void set_or_throw(const std::string& key, const std::string& value) { std::lock_guard<std::mutex> lg(env_guard()); static const int overwrite = 0; auto rc = ::setenv(key.c_str(), value.c_str(), overwrite); if (rc == -1) throw std::system_error(errno, std::system_category()); } bool set(const std::string &key, const std::string &value, std::error_code& se) noexcept(true) { std::lock_guard<std::mutex> lg(env_guard()); static const int overwrite = 0; auto rc = ::setenv(key.c_str(), value.c_str(), overwrite); if (rc == -1) { se = std::error_code(errno, std::system_category()); return false; } return true; } } Process instance() noexcept(true) { static const Process self{getpid()}; return self; } Process parent() noexcept(true) { return Process(getppid()); } std::istream& cin() noexcept(true) { return std::cin; } std::ostream& cout() noexcept(true) { return std::cout; } std::ostream& cerr() noexcept(true) { return std::cerr; } } } }
3,821
C++
.cpp
145
22.586207
104
0.65184
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,541
exec.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/exec.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/exec.h> #include <core/posix/fork.h> #include <core/posix/standard_stream.h> #include <iostream> #include <cstring> #include <unistd.h> namespace core { namespace posix { ChildProcess exec(const std::string& fn, const std::vector<std::string>& argv, const std::map<std::string, std::string>& env, const StandardStream& flags) { std::function<void()> null_function = [](){}; return exec(fn, argv, env, flags, null_function); } ChildProcess exec(const std::string& fn, const std::vector<std::string>& argv, const std::map<std::string, std::string>& env, const StandardStream& flags, const std::function<void()>& child_setup) { return posix::fork([fn, argv, env, child_setup]() { char** it; char** pargv; char** penv; it = pargv = new char*[argv.size()+2]; *it = ::strdup(fn.c_str()); it++; for (auto element : argv) { *it = ::strdup(element.c_str()); it++; } *it = nullptr; it = penv = new char*[env.size()+1]; for (auto pair : env) { *it = ::strdup((pair.first + "=" + pair.second).c_str()); it++; } *it = nullptr; child_setup(); return static_cast<posix::exit::Status>(execve(fn.c_str(), pargv, penv)); }, flags); } } }
2,172
C++
.cpp
66
26.742424
81
0.609547
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,542
process_group.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/process_group.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/process_group.h> namespace core { namespace posix { struct ProcessGroup::Private { pid_t id; }; pid_t ProcessGroup::id() const { return d->id; } ProcessGroup::ProcessGroup(pid_t id) : Signalable(-id), // We rely on ::kill to deliver signals, thus negate the id (see man 2 kill). d(new Private{id}) { } ProcessGroup ProcessGroup::invalid() { static const pid_t invalid_pid = 1; return ProcessGroup(invalid_pid); } } }
1,177
C++
.cpp
42
25.857143
100
0.741135
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,543
oom_adj.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/linux/proc/process/oom_adj.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/linux/proc/process/oom_adj.h> #include <core/posix/process.h> #include <fstream> #include <sstream> #include <stdexcept> #include <linux/oom.h> namespace core { namespace posix { namespace linux { namespace proc { namespace process { int OomAdj::disable_value() { return OOM_DISABLE; } int OomAdj::min_value() { return OOM_ADJUST_MIN; } int OomAdj::max_value() { return OOM_ADJUST_MAX; } const posix::Process& operator>>(const posix::Process& process, OomAdj& adj) { std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_adj"; std::ifstream in(ss.str()); in >> adj.value; return process; } const posix::Process& operator<<(const posix::Process& process, const OomAdj& adj) { if (!adj.is_valid()) throw std::logic_error("Value for adjusting the oom score is invalid."); std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_adj"; std::ofstream out(ss.str()); out << adj.value; return process; } } } } } }
1,722
C++
.cpp
66
23.742424
82
0.71568
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,544
stat.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/linux/proc/process/stat.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/linux/proc/process/stat.h> #include <core/posix/process.h> #include <fstream> #include <istream> #include <sstream> namespace core { namespace posix { namespace linux { namespace proc { namespace process { std::istream& operator>>(std::istream& in, State& state) { char c; in >> c; state = static_cast<State>(c); return in; } std::istream& operator>>(std::istream& in, Stat& stat) { in >> stat.pid >> stat.executable >> stat.state >> stat.parent >> stat.process_group >> stat.session_id >> stat.tty_nr >> stat.controlling_process_group >> stat.kernel_flags >> stat.minor_faults_count >> stat.minor_faults_count_by_children >> stat.major_faults_count >> stat.major_faults_count_by_children >> stat.time.user >> stat.time.system >> stat.time.user_for_children >> stat.time.system_for_children >> stat.priority >> stat.nice >> stat.thread_count >> stat.time_before_next_sig_alarm >> stat.start_time >> stat.size.virt >> stat.size.resident_set >> stat.size.resident_set_limit >> stat.addresses.start_code >> stat.addresses.end_code >> stat.addresses.start_stack >> stat.addresses.stack_pointer >> stat.addresses.instruction_pointer >> stat.signals.pending >> stat.signals.blocked >> stat.signals.ignored >> stat.signals.caught >> stat.channel >> stat.swap_count >> stat.swap_count_children >> stat.exit_signal >> stat.cpu_count >> stat.realtime_priority >> stat.scheduling_policy >> stat.aggregated_block_io_delays >> stat.guest_time >> stat.guest_time_children; return in; } const posix::Process& operator>>(const posix::Process& process, Stat& stat) { std::stringstream ss; ss << "/proc/" << process.pid() << "/stat"; std::ifstream in(ss.str()); in >> stat; return process; } } } } } }
2,755
C++
.cpp
97
23.690722
75
0.65697
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,545
oom_score_adj.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/linux/proc/process/oom_score_adj.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/linux/proc/process/oom_score_adj.h> #include <core/posix/process.h> #include <fstream> #include <sstream> #include <stdexcept> #include <linux/oom.h> namespace core { namespace posix { namespace linux { namespace proc { namespace process { int OomScoreAdj::min_value() { return OOM_SCORE_ADJ_MIN; } int OomScoreAdj::max_value() { return OOM_SCORE_ADJ_MAX; } const posix::Process& operator>>(const posix::Process& process, OomScoreAdj& score_adj) { std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score_adj"; std::ifstream in(ss.str()); in >> score_adj.value; return process; } const posix::Process& operator<<(const posix::Process& process, const OomScoreAdj& score_adj) { if (!score_adj.is_valid()) throw std::logic_error("Value for adjusting the oom score is invalid."); std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score_adj"; std::ofstream out(ss.str()); out << score_adj.value; return process; } } } } } }
1,739
C++
.cpp
62
25.693548
93
0.722456
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,546
oom_score.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/linux/proc/process/oom_score.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/linux/proc/process/oom_score.h> #include <core/posix/process.h> #include <fstream> #include <sstream> namespace core { namespace posix { namespace linux { namespace proc { namespace process { const posix::Process& operator>>(const posix::Process& process, OomScore& score) { std::stringstream ss; ss << "/proc/" << process.pid() << "/oom_score"; std::ifstream in(ss.str()); in >> score.value; return process; } } } } } }
1,172
C++
.cpp
43
25.325581
80
0.742194
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,547
state.cpp
anbox_anbox/external/process-cpp-minimal/src/core/posix/linux/proc/process/state.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/posix/linux/proc/process/state.h> #include <core/posix/process.h> #include <istream> namespace core { namespace posix { namespace linux { namespace proc { namespace process { } } } } }
913
C++
.cpp
35
24.428571
75
0.768083
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,548
fork_and_run.cpp
anbox_anbox/external/process-cpp-minimal/src/core/testing/fork_and_run.cpp
/* * Copyright © 2012-2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> */ #include <core/testing/fork_and_run.h> #include <core/posix/exit.h> #include <core/posix/fork.h> #include <core/posix/wait.h> core::testing::ForkAndRunResult core::testing::operator|( core::testing::ForkAndRunResult lhs, core::testing::ForkAndRunResult rhs) { return static_cast<core::testing::ForkAndRunResult>( static_cast<unsigned int> (lhs) | static_cast<unsigned int>(rhs)); } core::testing::ForkAndRunResult core::testing::operator&( core::testing::ForkAndRunResult lhs, core::testing::ForkAndRunResult rhs) { return static_cast<core::testing::ForkAndRunResult>( static_cast<unsigned int> (lhs) & static_cast<unsigned int>(rhs)); } core::testing::ForkAndRunResult core::testing::fork_and_run( const std::function<core::posix::exit::Status()>& service, const std::function<core::posix::exit::Status()>& client) { core::testing::ForkAndRunResult result = core::testing::ForkAndRunResult::empty; auto service_process = core::posix::fork(service, core::posix::StandardStream::empty); auto client_process = core::posix::fork(client, core::posix::StandardStream::empty); auto client_result = client_process.wait_for(core::posix::wait::Flags::untraced); switch (client_result.status) { case core::posix::wait::Result::Status::exited: if (client_result.detail.if_exited.status == core::posix::exit::Status::failure) result = result | core::testing::ForkAndRunResult::client_failed; break; default: result = result | core::testing::ForkAndRunResult::client_failed; break; } service_process.send_signal_or_throw(core::posix::Signal::sig_term); auto service_result = service_process.wait_for(core::posix::wait::Flags::untraced); switch (service_result.status) { case core::posix::wait::Result::Status::exited: if (service_result.detail.if_exited.status == core::posix::exit::Status::failure) result = result | core::testing::ForkAndRunResult::service_failed; break; default: result = result | core::testing::ForkAndRunResult::service_failed; break; } return result; }
2,931
C++
.cpp
67
38.671642
90
0.705016
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,549
cross_process_sync.cpp
anbox_anbox/external/process-cpp-minimal/src/core/testing/cross_process_sync.cpp
/* * Copyright © 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voss <thomas.voss@canonical.com> */ #include <core/testing/cross_process_sync.h> #include <system_error> #include <poll.h> #include <unistd.h> namespace { const int read_fd = 0; const int write_fd = 1; } core::testing::CrossProcessSync::CrossProcessSync() : counter(0) { if (::pipe(fds) < 0) throw std::system_error(errno, std::system_category()); } core::testing::CrossProcessSync::CrossProcessSync(const CrossProcessSync& rhs) : counter(rhs.counter) { fds[0] = ::dup(rhs.fds[0]); fds[1] = ::dup(rhs.fds[1]); } core::testing::CrossProcessSync::~CrossProcessSync() noexcept { ::close(fds[0]); ::close(fds[1]); } core::testing::CrossProcessSync& core::testing::CrossProcessSync::operator=(const core::testing::CrossProcessSync& rhs) { ::close(fds[0]); ::close(fds[1]); fds[0] = ::dup(rhs.fds[0]); fds[1] = ::dup(rhs.fds[1]); counter = rhs.counter; return *this; } void core::testing::CrossProcessSync::try_signal_ready_for(const std::chrono::milliseconds& duration) { static const short empty_revents = 0; pollfd poll_fd[1] = { { fds[write_fd], POLLOUT, empty_revents } }; int rc = -1; if ((rc = ::poll(poll_fd, 1, duration.count())) < 0) throw std::system_error(errno, std::system_category()); else if (rc == 0) throw Error::Timeout{}; static const std::uint32_t value = 1; if (sizeof(value) != write(fds[write_fd], std::addressof(value), sizeof(value))) throw std::system_error(errno, std::system_category()); } std::uint32_t core::testing::CrossProcessSync::wait_for_signal_ready_for(const std::chrono::milliseconds& duration) { static const short empty_revents = 0; pollfd poll_fd[1] = { { fds[read_fd], POLLIN, empty_revents } }; int rc = -1; if ((rc = ::poll(poll_fd, 1, duration.count())) < 0) throw std::system_error(errno, std::system_category()); else if (rc == 0) throw Error::Timeout{}; std::uint32_t value = 0; if (sizeof(value) != read(fds[read_fd], std::addressof(value), sizeof(value))) throw std::system_error(errno, std::system_category()); if (value != 1) throw std::system_error(errno, std::system_category()); counter += value; return counter; }
2,911
C++
.cpp
80
32.75
119
0.677809
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,558
main.cpp
anbox_anbox/src/main.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/daemon.h" #include "anbox/utils.h" int main(int argc, char **argv) { anbox::Daemon daemon; return daemon.Run(anbox::utils::collect_arguments(argc, argv)); }
853
C++
.cpp
22
36.818182
76
0.752714
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,559
daemon.cpp
anbox_anbox/src/anbox/daemon.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <signal.h> #include <sys/prctl.h> #include "anbox/system_configuration.h" #include "anbox/daemon.h" #include "anbox/logger.h" #include "anbox/cmds/container_manager.h" #include "anbox/cmds/session_manager.h" #include "anbox/cmds/system_info.h" #include "anbox/cmds/launch.h" #include "anbox/cmds/version.h" #include "anbox/cmds/wait_ready.h" #include "anbox/cmds/check_features.h" #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace anbox { Daemon::Daemon() : cmd{cli::Name{"anbox"}, cli::Usage{"anbox"}, cli::Description{"The Android in a Box runtime"}} { cmd.command(std::make_shared<cmds::Version>()) .command(std::make_shared<cmds::SessionManager>()) .command(std::make_shared<cmds::Launch>()) .command(std::make_shared<cmds::ContainerManager>()) .command(std::make_shared<cmds::SystemInfo>()) .command(std::make_shared<cmds::WaitReady>()) .command(std::make_shared<cmds::CheckFeatures>()); Log().Init(anbox::Logger::Severity::kWarning); const auto log_level = utils::get_env_value("ANBOX_LOG_LEVEL", ""); if (!log_level.empty() && !Log().SetSeverityFromString(log_level)) WARNING("Failed to set logging severity to '%s'", log_level); } int Daemon::Run(const std::vector<std::string> &arguments) try { auto argv = arguments; if (arguments.size() == 0) argv = {"help"}; return cmd.run({std::cin, std::cout, argv}); } catch (std::exception &err) { ERROR("%s", err.what()); return EXIT_FAILURE; } } // namespace anbox
2,203
C++
.cpp
55
37.4
76
0.717025
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,562
cli.cpp
anbox_anbox/src/anbox/cli.cpp
/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> * */ #include <boost/format.hpp> #include <boost/program_options.hpp> #include "anbox/cli.h" namespace cli = anbox::cli; namespace po = boost::program_options; namespace { namespace pattern { static constexpr const char* help_for_command_with_subcommands = "NAME:\n" " %1% - %2%\n" "\n" "USAGE:\n" " %3% [command options] [arguments...]"; static constexpr const char* commands = "COMMANDS:"; static constexpr const char* command = " %1% %2%"; static constexpr const char* options = "OPTIONS:"; static constexpr const char* option = " --%1% %2%"; } void add_to_desc_for_flags(po::options_description& desc, const std::set<cli::Flag::Ptr>& flags) { for (auto flag : flags) { po::value_semantic *spec = nullptr; flag->specify_option(spec); if (!spec) continue; desc.add_options()(flag->name().as_string().c_str(), spec, flag->description().as_string().c_str()); } } } std::vector<std::string> cli::args(int argc, char** argv) { std::vector<std::string> result; for (int i = 1; i < argc; i++) result.push_back(argv[i]); return result; } const cli::Name& cli::Flag::name() const { return name_; } const cli::Description& cli::Flag::description() const { return description_; } cli::Flag::Flag(const Name& name, const Description& description) : name_{name}, description_{description} {} cli::Command::FlagsWithInvalidValue::FlagsWithInvalidValue() : std::runtime_error{"Flags with invalid value"} {} cli::Command::FlagsMissing::FlagsMissing() : std::runtime_error{"Flags are missing in command invocation"} {} cli::Name cli::Command::name() const { return name_; } cli::Usage cli::Command::usage() const { return usage_; } cli::Description cli::Command::description() const { return description_; } bool cli::Command::hidden() const { return hidden_; } cli::Command::Command(const cli::Name& name, const cli::Usage& usage, const cli::Description& description, bool hidden) : name_(name), usage_(usage), description_(description), hidden_(hidden) {} cli::CommandWithSubcommands::CommandWithSubcommands( const Name& name, const Usage& usage, const Description& description) : Command{name, usage, description} { command(std::make_shared<cmd::Help>(*this)); } cli::CommandWithSubcommands& cli::CommandWithSubcommands::command( const Command::Ptr& command) { commands_[command->name().as_string()] = command; return *this; } cli::CommandWithSubcommands& cli::CommandWithSubcommands::flag( const Flag::Ptr& flag) { flags_.insert(flag); return *this; } void cli::CommandWithSubcommands::help(std::ostream& out) { out << boost::format(pattern::help_for_command_with_subcommands) % name().as_string() % usage().as_string() % name().as_string() << std::endl; if (flags_.size() > 0) { out << std::endl << pattern::options << std::endl; for (const auto& flag : flags_) out << boost::format(pattern::option) % flag->name() % flag->description() << std::endl; } if (commands_.size() > 0) { out << std::endl << pattern::commands << std::endl; for (const auto& cmd : commands_) { if (cmd.second && !cmd.second->hidden()) out << boost::format(pattern::command) % cmd.second->name() % cmd.second->description() << std::endl; } } } int cli::CommandWithSubcommands::run(const cli::Command::Context& ctxt) { po::positional_options_description pdesc; pdesc.add("command", 1); po::options_description desc("Options"); desc.add_options()("command", po::value<std::string>()->required(), "the command to be executed"); add_to_desc_for_flags(desc, flags_); try { po::variables_map vm; auto parsed = po::command_line_parser(ctxt.args) .options(desc) .positional(pdesc) .style(po::command_line_style::unix_style) .allow_unregistered() .run(); po::store(parsed, vm); po::notify(vm); auto cmd = commands_[vm["command"].as<std::string>()]; if (!cmd) { ctxt.cout << "Unknown command '" << vm["command"].as<std::string>() << "'" << std::endl; help(ctxt.cout); return EXIT_FAILURE; } return cmd->run(cli::Command::Context{ ctxt.cin, ctxt.cout, po::collect_unrecognized(parsed.options, po::include_positional)}); } catch (const po::error& e) { ctxt.cout << e.what() << std::endl; help(ctxt.cout); return EXIT_FAILURE; } return EXIT_FAILURE; } cli::CommandWithFlagsAndAction::CommandWithFlagsAndAction( const Name& name, const Usage& usage, const Description& description, bool hidden) : Command{name, usage, description, hidden} {} cli::CommandWithFlagsAndAction& cli::CommandWithFlagsAndAction::flag( const Flag::Ptr& flag) { flags_.insert(flag); return *this; } cli::CommandWithFlagsAndAction& cli::CommandWithFlagsAndAction::action( const Action& action) { action_ = action; return *this; } int cli::CommandWithFlagsAndAction::run(const Context& ctxt) { po::options_description cd(name().as_string()); bool help_requested{false}; cd.add_options()("help", po::bool_switch(&help_requested), "produces a help message"); add_to_desc_for_flags(cd, flags_); try { po::variables_map vm; auto parsed = po::command_line_parser(ctxt.args) .options(cd) .style(po::command_line_style::unix_style) .allow_unregistered() .run(); po::store(parsed, vm); po::notify(vm); if (help_requested) { help(ctxt.cout); return EXIT_SUCCESS; } return action_(cli::Command::Context{ ctxt.cin, ctxt.cout, po::collect_unrecognized(parsed.options, po::include_positional)}); } catch (const po::error& e) { ctxt.cout << e.what() << std::endl; help(ctxt.cout); return EXIT_FAILURE; } return EXIT_FAILURE; } void cli::CommandWithFlagsAndAction::help(std::ostream& out) { out << boost::format(pattern::help_for_command_with_subcommands) % name().as_string() % description().as_string() % name().as_string() << std::endl; if (flags_.size() > 0) { out << std::endl << boost::format(pattern::options) << std::endl; for (const auto& flag : flags_) out << boost::format(pattern::option) % flag->name() % flag->description() << std::endl; } } cli::cmd::Help::Help(Command& cmd) : Command{cli::Name{"help"}, cli::Usage{"Print a short help message"}, cli::Description{"Print a short help message"}}, command{cmd} {} // From Command int cli::cmd::Help::run(const Context& context) { command.help(context.cout); return EXIT_FAILURE; } void cli::cmd::Help::help(std::ostream& out) { command.help(out); }
7,717
C++
.cpp
202
32.782178
86
0.644885
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,564
not_reachable.cpp
anbox_anbox/src/anbox/not_reachable.cpp
/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> * */ #include "anbox/not_reachable.h" #include <boost/format.hpp> anbox::util::NotReachable::NotReachable(const std::string& function, const std::string& file, std::uint32_t line) : std::logic_error{ (boost::format{"Code should not be reachable: %1% in %2%:%3%"} % function % file % line) .str()} {} void anbox::util::not_reachable(const std::string& function, const std::string& file, std::uint32_t line) { throw NotReachable{function, file, line}; }
1,317
C++
.cpp
31
35.870968
78
0.656006
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,565
utils.cpp
anbox_anbox/src/anbox/utils.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <boost/filesystem.hpp> #include <boost/throw_exception.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <fcntl.h> #include <mntent.h> #include <sys/stat.h> #include <sys/types.h> #include "anbox/utils.h" namespace fs = boost::filesystem; namespace anbox::utils { std::vector<std::string> collect_arguments(int argc, char **argv) { std::vector<std::string> result; for (int i = 1; i < argc; i++) result.push_back(argv[i]); return result; } std::string read_file_if_exists_or_throw(const std::string &file_path) { if (!boost::filesystem::is_regular(boost::filesystem::path(file_path))) BOOST_THROW_EXCEPTION(std::runtime_error("File does not exist")); std::ifstream file; file.open(file_path, std::ifstream::in); std::stringstream buffer; buffer << file.rdbuf(); return buffer.str(); } bool write_to_file(const std::string &file_path, const std::string &content) { std::ofstream of; of.open(file_path, std::ofstream::out); of << content; of.close(); return true; } int write_to_fd(int fd, const char *content, ssize_t len) { while (len > 0) { const auto res = write(fd, content, len); if (res < 0 && errno == EINTR) continue; if (res <= 0) { if (res == 0) /* Unexpected short write, should not happen when writing to a file */ errno = ENOSPC; return -1; } len -= res; content += res; } return 0; } int write_file_at(int dirfd, const char *path, const char *content) { const auto fd = openat(dirfd, path, O_RDWR | O_CLOEXEC, 0); if (fd == -1) return -1; auto res = 0; if (content) res = write_to_fd(fd, content, strlen(content)); const auto errsv = errno; close(fd); errno = errsv; return res; } bool string_starts_with(const std::string &text, const std::string &prefix) { return text.compare(0, prefix.size(), prefix) == 0; } std::vector<std::string> string_split(const std::string &text, char sep) { std::vector<std::string> tokens; return boost::algorithm::split(tokens, text, boost::is_from_range(sep, sep), boost::algorithm::token_compress_on); } std::string strip_surrounding_quotes(const std::string &text) { auto result = text; if (text[0] == '\"' && text[text.length() - 1] == '\"') result = text.substr(1, text.length() - 2); return result; } std::string hex_dump(const uint8_t *data, uint32_t size) { unsigned char buff[17]; const uint8_t *pc = data; std::stringstream buffer; if (size == 0) { buffer << "NULL" << std::endl; return buffer.str(); } uint32_t i; for (i = 0; i < size; i++) { if ((i % 16) == 0) { if (i != 0) buffer << string_format(" %s", buff) << std::endl; buffer << string_format("%02x ", i); } buffer << string_format(" %02x", static_cast<int>(pc[i])); if ((pc[i] < 0x20) || (pc[i] > 0x7e)) buff[i % 16] = '.'; else buff[i % 16] = pc[i]; buff[(i % 16) + 1] = '\0'; } while ((i % 16) != 0) { buffer << " "; i++; } buffer << string_format(" %s", buff) << std::endl; return buffer.str(); } std::string get_env_value(const std::string &name, const std::string &default_value) { char *value = getenv(name.c_str()); if (!value) return default_value; return std::string(value); } bool is_env_set(const std::string &name) { return getenv(name.c_str()) != nullptr; } void ensure_paths(const std::vector<std::string> &paths) { for (const auto &path : paths) { if (!fs::is_directory(fs::path(path))) fs::create_directories(fs::path(path)); } } std::string prefix_dir_from_env(const std::string &path, const std::string &env_var) { static auto snap_data_path = anbox::utils::get_env_value(env_var, ""); auto result = path; if (!snap_data_path.empty()) result = anbox::utils::string_format("%s%s", snap_data_path, path); return result; } std::string process_get_exe_path(const pid_t &pid) { auto exe_path = string_format("/proc/%d/exe", pid); return boost::filesystem::read_symlink(exe_path).string(); } bool is_mounted(const std::string &path) { FILE *mtab = nullptr; struct mntent *part = nullptr; bool is_mounted = false; if ((mtab = setmntent("/etc/mtab", "r")) != nullptr) { while ((part = getmntent(mtab)) != nullptr) { if ((part->mnt_fsname != nullptr) && (strcmp(part->mnt_fsname, path.c_str())) == 0) { is_mounted = true; break; } } endmntent(mtab); } return is_mounted; } std::string find_program_on_path(const std::string &name) { struct stat sb; std::string path = std::string(getenv("PATH")); size_t start_pos = 0, end_pos = 0; while ((end_pos = path.find(':', start_pos)) != std::string::npos) { const auto current_path = path.substr(start_pos, end_pos - start_pos) + "/" + name; if ((::stat(current_path.c_str(), &sb) == 0) && (sb.st_mode & S_IXOTH)) return current_path; start_pos = end_pos + 1; } return ""; } }
5,811
C++
.cpp
173
29.971098
116
0.644298
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,566
device.cpp
anbox_anbox/src/anbox/input/device.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/input/device.h" #include "anbox/logger.h" #include "anbox/network/delegate_connection_creator.h" #include "anbox/network/delegate_message_processor.h" #include "anbox/network/local_socket_messenger.h" #include "anbox/qemu/null_message_processor.h" #include <time.h> namespace anbox::input { std::shared_ptr<Device> Device::create( const std::string &path, const std::shared_ptr<Runtime> &runtime) { auto sp = std::make_shared<Device>(); auto delegate_connector = std::make_shared< network::DelegateConnectionCreator<boost::asio::local::stream_protocol>>( [sp](std::shared_ptr<boost::asio::local::stream_protocol::socket> const &socket) { sp->new_client(socket); }); sp->connector_ = std::make_shared<network::PublishedSocketConnector>( path, runtime, delegate_connector); // The socket is created with user permissions (e.g. rwx------), // which prevents the container from accessing it. Make sure it is writable. ::chmod(path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); return sp; } Device::Device() : next_connection_id_(0), connections_( std::make_shared<network::Connections<network::SocketConnection>>()) { ::memset(&info_, 0, sizeof(info_)); } Device::~Device() {} void Device::send_events(const std::vector<Event> &events) { struct CompatEvent { // NOTE: A bit dirty but as we're running currently a 64 bit container // struct input_event has a different size. We rebuild the struct here // to reach the correct size. std::uint64_t sec; std::uint64_t usec; std::uint16_t type; std::uint16_t code; std::uint32_t value; }; struct timespec spec; clock_gettime(CLOCK_MONOTONIC, &spec); auto data = new CompatEvent[events.size()]; int n = 0; for (const auto &event : events) { data[n].sec = spec.tv_sec; data[n].usec = spec.tv_nsec / 1000; data[n].type = event.type; data[n].code = event.code; data[n].value = event.value; n++; } for (unsigned n = 0; n < connections_->size(); n++) { connections_->at(n)->send(reinterpret_cast<const char *>(data), events.size() * sizeof(struct CompatEvent)); } } void Device::set_name(const std::string &name) { snprintf(info_.name, 80, "%s", name.c_str()); } void Device::set_driver_version(const int &version) { info_.driver_version = version; } void Device::set_input_id(const struct input_id &id) { info_.id.bustype = id.bustype; info_.id.product = id.product; info_.id.vendor = id.vendor; info_.id.version = id.version; } void Device::set_physical_location(const std::string &physical_location) { snprintf(info_.physical_location, 80, "%s", physical_location.c_str()); } void Device::set_key_bit(const std::uint64_t &bit) { set_bit(info_.key_bitmask, bit); } void Device::set_abs_bit(const std::uint64_t &bit) { set_bit(info_.abs_bitmask, bit); } void Device::set_rel_bit(const std::uint64_t &bit) { set_bit(info_.rel_bitmask, bit); } void Device::set_sw_bit(const std::uint64_t &bit) { set_bit(info_.sw_bitmask, bit); } void Device::set_led_bit(const std::uint64_t &bit) { set_bit(info_.led_bitmask, bit); } void Device::set_ff_bit(const std::uint64_t &bit) { set_bit(info_.ff_bitmask, bit); } void Device::set_prop_bit(const std::uint64_t &bit) { set_bit(info_.prop_bitmask, bit); } void Device::set_abs_min(const std::uint64_t &bit, const std::uint32_t &value) { info_.abs_min[bit] = value; } void Device::set_abs_max(const std::uint64_t &bit, const std::uint32_t &value) { info_.abs_max[bit] = value; } void Device::set_bit(std::uint8_t *array, const std::uint64_t &bit) { array[bit / 8] |= (1 << (bit % 8)); } void Device::set_unique_id(const std::string &unique_id) { snprintf(info_.unique_id, 80, "%s", unique_id.c_str()); } std::string Device::socket_path() const { return connector_->socket_file(); } int Device::next_id() { return next_connection_id_++; } void Device::new_client( std::shared_ptr<boost::asio::local::stream_protocol::socket> const &socket) { auto const messenger = std::make_shared<network::LocalSocketMessenger>(socket); auto const &connection = std::make_shared<network::SocketConnection>( messenger, messenger, next_id(), connections_, std::make_shared<qemu::NullMessageProcessor>()); connection->set_name("input-device"); connections_->add(connection); // Send all necessary information about our device so that the remote // side can properly configure itself for this input device connection->send(reinterpret_cast<char const *>(&info_), sizeof(info_)); } }
5,341
C++
.cpp
138
35.463768
83
0.695089
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,568
management_api_message_processor.cpp
anbox_anbox/src/anbox/container/management_api_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/management_api_message_processor.h" #include "anbox/container/management_api_skeleton.h" #include "anbox/rpc/template_message_processor.h" #include "anbox_bridge.pb.h" #include "anbox_container.pb.h" namespace anbox::container { ManagementApiMessageProcessor::ManagementApiMessageProcessor( const std::shared_ptr<network::MessageSender> &sender, const std::shared_ptr<rpc::PendingCallCache> &pending_calls, const std::shared_ptr<ManagementApiSkeleton> &server) : rpc::MessageProcessor(sender, pending_calls), server_(server) {} ManagementApiMessageProcessor::~ManagementApiMessageProcessor() {} void ManagementApiMessageProcessor::dispatch(rpc::Invocation const &invocation) { if (invocation.method_name() == "start_container") invoke(this, server_.get(), &ManagementApiSkeleton::start_container, invocation); else if (invocation.method_name() == "stop_container") invoke(this, server_.get(), &ManagementApiSkeleton::stop_container, invocation); } void ManagementApiMessageProcessor::process_event_sequence( const std::string &) {} }
1,771
C++
.cpp
37
45.459459
85
0.774436
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,569
lxc_container.cpp
anbox_anbox/src/anbox/container/lxc_container.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/android/ip_config_builder.h" #include "anbox/common/binder_device_allocator.h" #include "anbox/common/binder_device.h" #include "anbox/container/lxc_container.h" #include "anbox/system_configuration.h" #include "anbox/logger.h" #include "anbox/utils.h" #include <map> #include <stdexcept> #include <fstream> #include <sstream> #include <boost/filesystem.hpp> #include <boost/throw_exception.hpp> #include <sys/capability.h> #include <sys/prctl.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <unistd.h> namespace fs = boost::filesystem; namespace { constexpr unsigned int unprivileged_uid{100000}; constexpr unsigned int android_system_uid{1000}; constexpr const char *default_container_ip_address{"192.168.250.2"}; constexpr const std::uint32_t default_container_ip_prefix_length{24}; constexpr const char *default_host_ip_address{"192.168.250.1"}; constexpr const char *default_dns_server{"8.8.8.8"}; constexpr int num_needed_binders{1}; #ifdef ENABLE_LXC2_SUPPORT constexpr const char *lxc_config_idmap_key{"lxc.id_map"}; constexpr const char *lxc_config_net_type_key{"lxc.network.type"}; constexpr const char *lxc_config_net_flags_key{"lxc.network.flags"}; constexpr const char *lxc_config_net_link_key{"lxc.network.link"}; constexpr const char *lxc_config_pty_max_key{"lxc.pts"}; constexpr const char *lxc_config_tty_max_key{"lxc.tty"}; constexpr const char *lxc_config_uts_name_key{"lxc.utsname"}; constexpr const char *lxc_config_tty_dir_key{"lxc.devttydir"}; constexpr const char *lxc_config_init_cmd_key{"lxc.init_cmd"}; constexpr const char *lxc_config_rootfs_path_key{"lxc.rootfs"}; constexpr const char *lxc_config_log_level_key{"lxc.loglevel"}; constexpr const char *lxc_config_log_file_key{"lxc.logfile"}; constexpr const char *lxc_config_apparmor_profile_key{"lxc.aa_profile"}; #else constexpr const char *lxc_config_idmap_key{"lxc.idmap"}; constexpr const char *lxc_config_net_type_key{"lxc.net.0.type"}; constexpr const char *lxc_config_net_flags_key{"lxc.net.0.flags"}; constexpr const char *lxc_config_net_link_key{"lxc.net.0.link"}; constexpr const char *lxc_config_pty_max_key{"lxc.pty.max"}; constexpr const char *lxc_config_tty_max_key{"lxc.tty.max"}; constexpr const char *lxc_config_uts_name_key{"lxc.uts.name"}; constexpr const char *lxc_config_tty_dir_key{"lxc.tty.dir"}; constexpr const char *lxc_config_init_cmd_key{"lxc.init.cmd"}; constexpr const char *lxc_config_rootfs_path_key{"lxc.rootfs.path"}; constexpr const char *lxc_config_log_level_key{"lxc.log.level"}; constexpr const char *lxc_config_log_file_key{"lxc.log.file"}; constexpr const char *lxc_config_apparmor_profile_key{"lxc.apparmor.profile"}; #endif constexpr int device_major(dev_t dev) { return int(((dev >> 8) & 0xfff) | ((dev >> 32) & (0xfffff000))); } constexpr int device_minor(dev_t dev) { return int((dev & 0xff) | ((dev >> 12) & (0xffffff00))); } } // namespace namespace anbox::container { LxcContainer::LxcContainer(bool privileged, bool rootfs_overlay, const std::string& container_network_address, const std::string &container_network_gateway, const std::vector<std::string> &container_network_dns_servers, const network::Credentials &creds) : state_(State::inactive), container_(nullptr), privileged_(privileged), rootfs_overlay_(rootfs_overlay), container_network_address_(container_network_address), container_network_gateway_(container_network_gateway), container_network_dns_servers_(container_network_dns_servers), creds_(creds) { utils::ensure_paths({ SystemConfiguration::instance().container_config_dir(), SystemConfiguration::instance().container_state_dir(), SystemConfiguration::instance().log_dir(), }); } LxcContainer::~LxcContainer() { stop(); if (container_) lxc_container_put(container_); } std::vector<std::string> get_id_map(uid_t uid, gid_t gid) { const auto base_id = unprivileged_uid; const auto max_id = 100000; std::vector<std::string> config; config.push_back(utils::string_format("u 0 %d %d", base_id, android_system_uid - 1)); config.push_back(utils::string_format("g 0 %d %d", base_id, android_system_uid - 1)); // We need to bind the user id for the one running the client side // process as he is the owner of various socket files we bind mount // into the container. config.push_back(utils::string_format("u %d %d 1", android_system_uid, uid)); config.push_back(utils::string_format("g %d %d 1", android_system_uid, gid)); config.push_back(utils::string_format("u %d %d %d", android_system_uid + 1, base_id + android_system_uid + 1, max_id - android_system_uid)); config.push_back(utils::string_format("g %d %d %d", android_system_uid + 1, base_id + android_system_uid + 1, max_id - android_system_uid)); return config; } void LxcContainer::setup_id_map() { auto config = get_id_map(creds_.uid(), creds_.gid()); for (std::string val : config) set_config_item(lxc_config_idmap_key, val); } void LxcContainer::setup_network() { if (!fs::exists("/sys/class/net/anbox0")) { WARNING("Anbox bridge interface 'anbox0' doesn't exist. Network functionality will not be available"); return; } set_config_item(lxc_config_net_type_key, "veth"); set_config_item(lxc_config_net_flags_key, "up"); set_config_item(lxc_config_net_link_key, "anbox0"); // Instead of relying on DHCP we will give Android a static IP configuration // for the virtual ethernet interface LXC creates for us. This will be bridged // to the host and will allows us to have reliable network connectivity and // not depend on any other system service. android::IpConfigBuilder ip_conf; ip_conf.set_version(android::IpConfigBuilder::Version::Version2); ip_conf.set_assignment(android::IpConfigBuilder::Assignment::Static); std::string address = default_container_ip_address; std::uint32_t ip_prefix_length = default_container_ip_prefix_length; if (!container_network_address_.empty()) { auto tokens = utils::string_split(container_network_address_, '/'); if (tokens.size() == 1 || tokens.size() == 2) address = tokens[0]; if (tokens.size() == 2) ip_prefix_length = atoi(tokens[1].c_str()); } ip_conf.set_link_address(address, ip_prefix_length); std::string gateway = default_host_ip_address; if (!container_network_gateway_.empty()) gateway = container_network_gateway_; ip_conf.set_gateway(gateway); if (container_network_dns_servers_.size() > 0) ip_conf.set_dns_servers(container_network_dns_servers_); else ip_conf.set_dns_servers({default_dns_server}); ip_conf.set_id(0); std::vector<std::uint8_t> buffer(512); common::BinaryWriter writer(buffer.begin(), buffer.end()); const auto size = ip_conf.write(writer); const auto data_ethernet_path = fs::path("data") / "misc" / "ethernet"; const auto ip_conf_dir = SystemConfiguration::instance().data_dir() / data_ethernet_path; if (!fs::exists(ip_conf_dir)) fs::create_directories(ip_conf_dir); // We have to walk through the created directory hierachy now and // ensure the permissions are set correctly. Otherwise the Android // system will fail to boot as it isn't allowed to write anything // into these directories. As previous versions of Anbox which were // published to our users did this incorrectly we need to check on // every startup if those directories are still owned by root and // if they are we move them over to the unprivileged user. auto path = SystemConfiguration::instance().data_dir(); for (auto iter = data_ethernet_path.begin(); iter != data_ethernet_path.end(); iter++) { path /= *iter; struct stat st; if (stat(path.c_str(), &st) < 0) { WARNING("Cannot retrieve permissions of path %s", path); continue; } if (st.st_uid != 0 && st.st_gid != 0) continue; if (::chown(path.c_str(), unprivileged_uid, unprivileged_uid) < 0) WARNING("Failed to set owner for path '%s'", path); } const auto ip_conf_path = ip_conf_dir / "ipconfig.txt"; if (fs::exists(ip_conf_path)) fs::remove(ip_conf_path); std::ofstream f(ip_conf_path.string(), std::ofstream::binary); if (f.is_open()) { f.write(reinterpret_cast<const char*>(buffer.data()), size); f.close(); } else { ERROR("Failed to write IP configuration. Network functionality will not be available."); } } void LxcContainer::add_device(const std::string& device, const DeviceSpecification& spec) { struct stat st; const std::string *old_device_name; if (!spec.old_device_name.empty()) old_device_name = &spec.old_device_name; else old_device_name = &device; int r = stat(old_device_name->c_str(), &st); if (r < 0) { const auto msg = utils::string_format("Failed to retrieve information about device %s", device); throw std::runtime_error(msg); } const auto major = device_major(st.st_rdev); const auto minor = device_minor(st.st_rdev); const auto mode = ((st.st_mode >> 9) << 9) | (spec.permission & ~(1 << 9)); const auto new_device_name = fs::basename(device); const auto devices_path = fs::path(SystemConfiguration::instance().container_devices_dir()); const auto new_device_path = (devices_path / new_device_name).string(); const auto encoded_device_number = (minor & 0xff) | (major << 8) | ((minor & !0xff) << 12); r = mknod(new_device_path.c_str(), mode, encoded_device_number); if (r < 0) { auto msg = utils::string_format("Failed to create node for device %s: %s", device, strerror(errno)); throw std::runtime_error(msg); } auto base_uid = unprivileged_uid; if (privileged_) base_uid = 0; const auto shifted_uid = base_uid + st.st_uid; const auto shifted_gid = base_uid + st.st_gid; r = chown(new_device_path.c_str(), shifted_uid, shifted_gid); if (r < 0) { auto msg = utils::string_format("Failed to change ownership of new node for %s: %s", device, strerror(errno)); throw std::runtime_error(msg); } // Needed as mknod respects the umask r = chmod(new_device_path.c_str(), mode); if (r < 0) { auto msg = utils::string_format("Failed to change mode of new node for %s: %s", device, strerror(errno)); throw::std::runtime_error(msg); } auto target_path = device; // Strip a leading slash as LXC doesn't like that if (utils::string_starts_with(device, "/")) target_path = device.substr(1, device.length() - 1); const auto entry = utils::string_format("%s %s none bind,create=file,optional 0 0", new_device_path, target_path); set_config_item("lxc.mount.entry", entry); } bool LxcContainer::create_binder_devices(unsigned int device_count, std::vector<std::unique_ptr<common::BinderDevice>>& devices) { // We will always allocate a static set of binders devices even if the container // doesn't use all of them for (unsigned int n = 0; n < device_count; n++) { auto device = common::BinderDeviceAllocator::new_device(); if (!device) return false; DEBUG("Allocated binder device %s", device->path()); devices.push_back(std::move(device)); } return true; } void LxcContainer::start(const Configuration &configuration) { if (getuid() != 0) throw std::runtime_error("You have to start the container as root"); if (container_ && container_->is_running(container_)) { WARNING("Container already started, stopping it now"); container_->stop(container_); } if (!container_) { const auto container_config_dir = SystemConfiguration::instance().container_config_dir(); DEBUG("Containers are stored in %s", container_config_dir); // Remove container config to be be able to rewrite it ::unlink(utils::string_format("%s/default/config", container_config_dir).c_str()); container_ = lxc_container_new("default", container_config_dir.c_str()); if (!container_) throw std::runtime_error("Failed to create LXC container instance"); // If container is still running (for example after a crash) we stop it here // to ensure its configuration is synchronized. if (container_->is_running(container_)) container_->stop(container_); } // We can mount proc/sys as rw here as we will run the container unprivileged // in the end set_config_item("lxc.mount.auto", "proc:mixed sys:mixed cgroup:mixed"); set_config_item("lxc.autodev", "1"); set_config_item(lxc_config_pty_max_key, "1024"); set_config_item(lxc_config_tty_max_key, "0"); set_config_item(lxc_config_uts_name_key, "anbox"); set_config_item("lxc.group.devices.deny", ""); set_config_item("lxc.group.devices.allow", ""); // We can't move bind-mounts, so don't use /dev/lxc/ set_config_item(lxc_config_tty_dir_key, ""); set_config_item("lxc.environment", "PATH=/system/bin:/system/sbin:/system/xbin"); set_config_item(lxc_config_init_cmd_key, "/anbox-init.sh"); // forbid android from waking up the system (https://github.com/anbox/anbox/issues/1436) set_config_item("lxc.cap.drop", "wake_alarm"); #ifdef ENABLE_SNAP_CONFINEMENT // If we're running inside the snap environment snap-confine already created a // cgroup for us we need to use as otherwise presevering a namespace wont help. if (utils::is_env_set("SNAP")) set_config_item("lxc.namespace.keep", "cgroup"); #endif auto rootfs_path = SystemConfiguration::instance().rootfs_dir(); if (rootfs_overlay_) rootfs_path = SystemConfiguration::instance().combined_rootfs_dir(); DEBUG("Using rootfs path %s", rootfs_path); set_config_item(lxc_config_rootfs_path_key, rootfs_path); set_config_item(lxc_config_log_level_key, "0"); const auto log_path = SystemConfiguration::instance().log_dir(); set_config_item(lxc_config_log_file_key, utils::string_format("%s/container.log", log_path).c_str()); // set RLIMIT_NICE to 1 so binder_linux does not complain set_config_item("lxc.prlimit.nice", "1"); #ifndef ENABLE_LXC2_SUPPORT // Dump the console output to disk to have a chance to debug early boot problems set_config_item("lxc.console.logfile", utils::string_format("%s/console.log", log_path).c_str()); set_config_item("lxc.console.rotate", "1"); #endif setup_network(); #ifdef ENABLE_SNAP_CONFINEMENT // We take the AppArmor profile snapd has defined for us as part of the // anbox-support interface. The container manager itself runs within a // child profile snap.anbox.container-manager//lxc too. set_config_item("lxc.apparmor.profile", "snap.anbox.container-manager//container"); #else set_config_item(lxc_config_apparmor_profile_key, "unconfined"); #endif if (!privileged_) setup_id_map(); auto bind_mounts = configuration.bind_mounts; auto devices = configuration.devices; // If we have binderfs support we can dynamically allocate all our devices if (common::BinderDeviceAllocator::is_supported()) { DEBUG("Using binderfs to allocate our own binder nodes"); std::vector<std::unique_ptr<common::BinderDevice>> binder_devices; if (!create_binder_devices(num_needed_binders, binder_devices) || binder_devices.size() != num_needed_binders) throw std::runtime_error("Failed to allocate necessary binder devices"); bind_mounts.insert({binder_devices[0]->path().string(), "/dev/binder"}); binder_devices_ = std::move(binder_devices); } else { DEBUG("Using static binder device /dev/binder"); devices.insert({"/dev/binder", { 0666 }}); } for (const auto &bind_mount : bind_mounts) { std::string create_type = "file"; if (fs::is_directory(bind_mount.first)) create_type = "dir"; auto target_path = bind_mount.second; // The target path needs to be absolute and pointing to the right // location inside the target rootfs as otherwise we get problems // when running in confined environments like snap's. if (!utils::string_starts_with(target_path, "/")) target_path = std::string("/") + target_path; target_path = rootfs_path + target_path; const auto entry = utils::string_format("%s %s none bind,create=%s,optional 0 0", bind_mount.first, target_path, create_type); set_config_item("lxc.mount.entry", entry); } // Additional devices we need in our container devices.insert({"/dev/console", {0600}}); devices.insert({"/dev/full", {0666}}); devices.insert({"/dev/null", {0666}}); devices.insert({"/dev/random", {0666}}); devices.insert({"/dev/tty", {0666}}); devices.insert({"/dev/urandom", {0666}}); devices.insert({"/dev/zero", {0666}}); devices.insert({"/dev/tun", {0660, "/dev/net/tun"}}); devices.insert({"/dev/ashmem", {0666}}); // Remove all left over devices from last time first before // creating any new ones const auto devices_dir = SystemConfiguration::instance().container_devices_dir(); fs::remove_all(devices_dir); fs::create_directories(devices_dir); for (const auto& device : devices) add_device(device.first, device.second); // If we have any additional properties we add them at the top of default.prop // within the Android rootfs which we overlay with a bind mount. if (configuration.extra_properties.size() > 0) { const auto container_state_dir = SystemConfiguration::instance().container_state_dir(); auto old_default_prop_path = fs::path(rootfs_path) / "default.prop"; auto new_default_prop_path = fs::path(container_state_dir) / "default.prop"; auto default_prop_content = utils::read_file_if_exists_or_throw(old_default_prop_path.string()); std::ofstream default_props; default_props.open(new_default_prop_path.string(), std::ios_base::out); if (!default_props.is_open()) throw std::runtime_error("Failed to open new default properties file"); default_props << "# Properties added by Anbox" << std::endl; for (const auto& prop : configuration.extra_properties) default_props << prop << std::endl; default_props << std::endl << default_prop_content << std::endl; default_props.close(); set_config_item("lxc.mount.entry", utils::string_format("%s %s/default.prop none bind,optional,ro 0 0", new_default_prop_path.string(), rootfs_path)); } fs::path bindtab = SystemConfiguration::instance().data_dir() / "bindtab"; if ( fs::exists(bindtab) && fs::is_regular_file(bindtab) ) { std::ifstream bindtab_data; bindtab_data.open(bindtab.string(), std::ios_base::in); if (bindtab_data.is_open()) { std::string bind_mnt; while (std::getline(bindtab_data, bind_mnt)) { if (bind_mnt.rfind("/", 0) == 0) set_config_item("lxc.mount.entry", bind_mnt); } } } if (!container_->save_config(container_, nullptr)) throw std::runtime_error("Failed to save container configuration"); if (!container_->start(container_, 0, nullptr)) throw std::runtime_error("Failed to start container"); state_ = Container::State::running; DEBUG("Container successfully started"); } void LxcContainer::stop() { if (!container_ || !container_->is_running(container_)) return; if (!container_->stop(container_)) throw std::runtime_error("Failed to stop container"); state_ = Container::State::inactive; binder_devices_.clear(); DEBUG("Container successfully stopped"); } void LxcContainer::set_config_item(const std::string &key, const std::string &value) { if (!container_->set_config_item(container_, key.c_str(), value.c_str())) { const auto msg = utils::string_format("Failed to set config item %s", key); throw std::runtime_error(msg); } } Container::State LxcContainer::state() { return state_; } }
20,898
C++
.cpp
437
42.915332
130
0.687027
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,570
client.cpp
anbox_anbox/src/anbox/container/client.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/client.h" #include "anbox/system_configuration.h" #include "anbox/container/management_api_stub.h" #include "anbox/logger.h" #include "anbox/network/local_socket_messenger.h" #include "anbox/rpc/channel.h" #include "anbox/rpc/message_processor.h" #include "anbox/rpc/pending_call_cache.h" namespace ba = boost::asio; namespace bs = boost::system; namespace anbox::container { Client::Client(const std::shared_ptr<Runtime> &rt) : messenger_(std::make_shared<network::LocalSocketMessenger>( SystemConfiguration::instance().container_socket_path(), rt)), pending_calls_(std::make_shared<rpc::PendingCallCache>()), rpc_channel_(std::make_shared<rpc::Channel>(pending_calls_, messenger_)), management_api_(std::make_shared<ManagementApiStub>(rpc_channel_)), processor_( std::make_shared<rpc::MessageProcessor>(messenger_, pending_calls_)) { read_next_message(); } Client::~Client() {} void Client::start(const Configuration &configuration) { try { management_api_->start_container(configuration); } catch (const std::exception &e) { ERROR("Failed to start container: %s", e.what()); if (terminate_callback_) terminate_callback_(); } } void Client::stop() { management_api_->stop_container(); } void Client::register_terminate_handler(const TerminateCallback &callback) { terminate_callback_ = callback; } void Client::read_next_message() { auto callback = std::bind(&Client::on_read_size, this, std::placeholders::_1, std::placeholders::_2); messenger_->async_receive_msg(callback, ba::buffer(buffer_)); } void Client::on_read_size(const boost::system::error_code &error, std::size_t bytes_read) { if (error) { if (terminate_callback_) terminate_callback_(); return; } std::vector<std::uint8_t> data(bytes_read); std::copy(buffer_.data(), buffer_.data() + bytes_read, data.data()); if (processor_->process_data(data)) read_next_message(); } }
2,708
C++
.cpp
70
35.042857
80
0.710807
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,571
container.cpp
anbox_anbox/src/anbox/container/container.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/container.h" namespace anbox::container { Container::~Container() {} }
772
C++
.cpp
20
36.8
76
0.76032
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,572
management_api_stub.cpp
anbox_anbox/src/anbox/container/management_api_stub.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/management_api_stub.h" #include "anbox/logger.h" #include "anbox/rpc/channel.h" #include "anbox_container.pb.h" #include "anbox_rpc.pb.h" #ifdef USE_PROTOBUF_CALLBACK_HEADER #include <google/protobuf/stubs/callback.h> #endif namespace anbox::container { const std::chrono::milliseconds ManagementApiStub::stop_waiting_timeout{3000}; ManagementApiStub::ManagementApiStub( const std::shared_ptr<rpc::Channel> &channel) : channel_(channel) {} ManagementApiStub::~ManagementApiStub() {} void ManagementApiStub::start_container(const Configuration &configuration) { auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::container::StartContainer message; auto message_configuration = new protobuf::container::Configuration; for (const auto &item : configuration.bind_mounts) { auto bind_mount_message = message_configuration->add_bind_mounts(); bind_mount_message->set_source(item.first); bind_mount_message->set_target(item.second); } for (const auto &item : configuration.devices) { auto device_message = message_configuration->add_devices(); device_message->set_path(item.first); device_message->set_permission(item.second.permission); } for (const auto &prop : configuration.extra_properties) message_configuration->add_extra_properties(prop); message.set_allocated_configuration(message_configuration); { std::lock_guard<decltype(mutex_)> lock(mutex_); c->wh.expect_result(); } channel_->call_method("start_container", &message, c->response.get(), google::protobuf::NewCallback(this, &ManagementApiStub::container_started, c.get())); c->wh.wait_for_all(); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } void ManagementApiStub::container_started(Request<protobuf::rpc::Void> *request) { request->wh.result_received(); } void ManagementApiStub::stop_container() { auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::container::StopContainer message; message.set_force(false); { std::lock_guard<decltype(mutex_)> lock(mutex_); c->wh.expect_result(); } channel_->call_method("stop_container", &message, c->response.get(), google::protobuf::NewCallback(this, &ManagementApiStub::container_stopped, c.get())); // If container manager dies before session manager, the session manager // cannot exit if it waits for all, so just wait for 3 seconds. c->wh.wait_for_pending(stop_waiting_timeout); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } void ManagementApiStub::container_stopped(Request<protobuf::rpc::Void> *request) { request->wh.result_received(); } }
3,391
C++
.cpp
78
40.474359
91
0.745438
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,573
management_api_skeleton.cpp
anbox_anbox/src/anbox/container/management_api_skeleton.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/management_api_skeleton.h" #include "anbox/container/configuration.h" #include "anbox/container/container.h" #include "anbox/defer_action.h" #include "anbox/logger.h" #include "anbox/utils.h" #include "anbox_container.pb.h" #include "anbox_rpc.pb.h" #ifdef USE_PROTOBUF_CALLBACK_HEADER #include <google/protobuf/stubs/callback.h> #endif namespace anbox::container { ManagementApiSkeleton::ManagementApiSkeleton( const std::shared_ptr<Container> &container) : container_(container) { } ManagementApiSkeleton::~ManagementApiSkeleton() {} void ManagementApiSkeleton::start_container( anbox::protobuf::container::StartContainer const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { DEBUG(""); if (container_->state() == Container::State::running) { response->set_error("Container is already running"); done->Run(); return; } Configuration container_configuration; const auto configuration = request->configuration(); for (int n = 0; n < configuration.bind_mounts_size(); n++) { const auto bind_mount = configuration.bind_mounts(n); container_configuration.bind_mounts.insert({bind_mount.source(), bind_mount.target()}); } for (int n = 0; n < configuration.devices_size(); n++) { const auto device = configuration.devices(n); container_configuration.devices.insert({device.path(), {device.permission()}}); } for (int n = 0; n < configuration.extra_properties_size(); n++) { const auto prop = configuration.extra_properties(n); container_configuration.extra_properties.push_back(prop); } try { container_->start(container_configuration); } catch (std::exception &err) { response->set_error(utils::string_format("Failed to start container: %s", err.what())); } done->Run(); } void ManagementApiSkeleton::stop_container( anbox::protobuf::container::StopContainer const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { (void)request; if (container_->state() != Container::State::running) { response->set_error("Container is not running"); done->Run(); return; } try { container_->stop(); } catch (std::exception &err) { response->set_error(utils::string_format("Failed to stop container: %s", err.what())); } done->Run(); } }
3,035
C++
.cpp
79
35.341772
91
0.726438
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,574
service.cpp
anbox_anbox/src/anbox/container/service.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/container/service.h" #include "anbox/system_configuration.h" #include "anbox/container/lxc_container.h" #include "anbox/container/management_api_message_processor.h" #include "anbox/container/management_api_skeleton.h" #include "anbox/logger.h" #include "anbox/network/delegate_connection_creator.h" #include "anbox/network/delegate_message_processor.h" #include "anbox/network/local_socket_messenger.h" #include "anbox/qemu/null_message_processor.h" #include "anbox/rpc/channel.h" #include "anbox/rpc/pending_call_cache.h" #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace anbox::container { std::shared_ptr<Service> Service::create(const std::shared_ptr<Runtime> &rt, const Configuration &config) { auto sp = std::shared_ptr<Service>(new Service(rt, config)); auto wp = std::weak_ptr<Service>(sp); auto delegate_connector = std::make_shared<network::DelegateConnectionCreator<boost::asio::local::stream_protocol>>( [wp](std::shared_ptr<boost::asio::local::stream_protocol::socket> const &socket) { if (auto service = wp.lock()) service->new_client(socket); }); const auto container_socket_path = SystemConfiguration::instance().container_socket_path(); const auto socket_parent_path = fs::path(container_socket_path).parent_path(); if (!fs::exists(socket_parent_path)) fs::create_directories(socket_parent_path); sp->connector_ = std::make_shared<network::PublishedSocketConnector>(container_socket_path, rt, delegate_connector); // Make sure others can connect to our socket ::chmod(container_socket_path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); DEBUG("Everything setup. Waiting for incoming connections."); return sp; } Service::Service(const std::shared_ptr<Runtime> &rt, const Configuration &config) : dispatcher_(anbox::common::create_dispatcher_for_runtime(rt)), next_connection_id_(0), connections_(std::make_shared<network::Connections<network::SocketConnection>>()), config_(config) { } Service::~Service() { connections_->clear(); } int Service::next_id() { return next_connection_id_++; } void Service::new_client(std::shared_ptr<boost::asio::local::stream_protocol::socket> const &socket) { if (connections_->size() >= 1) { socket->close(); return; } auto const messenger = std::make_shared<network::LocalSocketMessenger>(socket); DEBUG("Got connection from pid %d", messenger->creds().pid()); auto pending_calls = std::make_shared<rpc::PendingCallCache>(); auto rpc_channel = std::make_shared<rpc::Channel>(pending_calls, messenger); auto server = std::make_shared<container::ManagementApiSkeleton>( std::make_shared<LxcContainer>(config_.privileged, config_.rootfs_overlay, config_.container_network_address, config_.container_network_gateway, config_.container_network_dns_servers, messenger->creds())); auto processor = std::make_shared<container::ManagementApiMessageProcessor>( messenger, pending_calls, server); auto const &connection = std::make_shared<network::SocketConnection>( messenger, messenger, next_id(), connections_, processor); connection->set_name("container-service"); connections_->add(connection); connection->read_next_message(); } }
4,229
C++
.cpp
85
43.729412
118
0.69777
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,575
launcher_storage.cpp
anbox_anbox/src/anbox/application/launcher_storage.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/application/launcher_storage.h" #include "anbox/utils.h" #include "anbox/logger.h" #include <algorithm> #include <fstream> #include <iostream> namespace fs = boost::filesystem; namespace { // This will always point us to the right executable when we're running within // a snap environment. constexpr const char *snap_exe_path{"/snap/bin/anbox"}; } namespace anbox::application { LauncherStorage::LauncherStorage(const fs::path &path) : path_(path) {} LauncherStorage::~LauncherStorage() {} void LauncherStorage::reset() { if (fs::exists(path_)) { for(auto & p : boost::filesystem::directory_iterator(path_)) { if (fs::is_regular_file(p)){ auto str = p.path().filename().string(); if (boost::starts_with(str, "anbox-")) fs::remove(p); } } } } std::string LauncherStorage::clean_package_name(const std::string &package_name) { auto cleaned_package_name = package_name; std::replace(cleaned_package_name.begin(), cleaned_package_name.end(), '.', '-'); return cleaned_package_name; } fs::path LauncherStorage::path_for_item(const std::string &package_name) { return path_ / utils::string_format("anbox-%s.desktop", package_name); } fs::path LauncherStorage::path_for_item_icon(const std::string &package_name) { return path_ / utils::string_format("anbox-%s.png", package_name); } void LauncherStorage::add_or_update(const Database::Item &item) { if (!fs::exists(path_)) fs::create_directories(path_); auto package_name = item.package; std::replace(package_name.begin(), package_name.end(), '.', '-'); auto exe_path = utils::process_get_exe_path(getpid()); if (utils::get_env_value("SNAP").length() > 0) exe_path = snap_exe_path; std::string exec = utils::string_format("%s launch ", exe_path); if (!item.launch_intent.action.empty()) exec += utils::string_format("--action=%s ", item.launch_intent.action); if (!item.launch_intent.type.empty()) exec += utils::string_format("--type=%s ", item.launch_intent.type); if (!item.launch_intent.uri.empty()) exec += utils::string_format("--uri=%s ", item.launch_intent.uri); if (!item.launch_intent.package.empty()) exec += utils::string_format("--package=%s ", item.launch_intent.package); if (!item.launch_intent.component.empty()) exec += utils::string_format("--component=%s ", item.launch_intent.component); const auto item_icon_path = path_for_item_icon(package_name); if (auto desktop_item = std::ofstream(path_for_item(package_name).string())) { desktop_item << "[Desktop Entry]" << std::endl << "Type=Application" << std::endl << "Name=" << item.name << std::endl << "Exec=" << exec << std::endl << "Terminal=false" << std::endl << "Categories=Anbox;" << std::endl << "Icon=" << item_icon_path.string() << std::endl; } else { BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create desktop item")); } if (auto icon = std::ofstream(item_icon_path.string())) icon.write(item.icon.data(), item.icon.size()); else BOOST_THROW_EXCEPTION(std::runtime_error("Failed to write icon")); } void LauncherStorage::remove(const Database::Item &item) { auto package_name = clean_package_name(item.package); const auto item_path = path_for_item(package_name); if (fs::exists(item_path)) fs::remove(item_path); const auto item_icon_path = path_for_item_icon(package_name); if (fs::exists(item_icon_path)) fs::remove(item_icon_path); } }
4,255
C++
.cpp
99
38.878788
83
0.680058
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,576
database.cpp
anbox_anbox/src/anbox/application/database.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/application/database.h" #include "anbox/application/launcher_storage.h" #include "anbox/system_configuration.h" #include "anbox/logger.h" namespace anbox::application { const Database::Item Database::Unknown{}; Database::Database() : storage_(std::make_shared<LauncherStorage>(SystemConfiguration::instance().application_item_dir())) {} Database::~Database() {} void Database::store_or_update(const Item &item) { if (!done_reset) { storage_->reset(); done_reset = true; } storage_->add_or_update(item); items_[item.package] = item; // We don't need to store the icon data anymore at this point as the // launcher is already stored it on the disk. items_[item.package].icon.clear(); } void Database::remove(const Item &item) { auto iter = items_.find(item.package); if (iter == items_.end()) return; storage_->remove(item); items_.erase(iter); } const Database::Item& Database::find_by_package(const std::string &package) const { auto iter = items_.find(package); if (iter == items_.end()) return Unknown; return iter->second; } }
1,773
C++
.cpp
50
33.1
104
0.732517
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,577
sensor_type.cpp
anbox_anbox/src/anbox/application/sensor_type.cpp
#include "anbox/application/sensor_type.h" #include <string> #include <map> namespace anbox::application { SensorType SensorTypeHelper::FromString(const std::string& str) { static std::map<std::string, SensorType> nameToType; if (nameToType.size() == 0) { nameToType["acceleration"] = SensorType::AccelerationSensor; nameToType["magnetic-field"] = SensorType::MagneticFieldSensor; nameToType["orientation"] = SensorType::OrientationSensor; nameToType["temperature"] = SensorType::TemperatureSensor; nameToType["proximity"] = SensorType::ProximitySensor; nameToType["light"] = SensorType::LightSensor; nameToType["pressure"] = SensorType::PressureSensor; nameToType["humidity"] = SensorType::HumiditySensor; } if (nameToType.find(str) != nameToType.end()) return nameToType[str]; else return SensorType::UnknownSensor; } }
875
C++
.cpp
22
36.363636
67
0.751765
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,578
sensors_server.cpp
anbox_anbox/src/anbox/dbus/sensors_server.cpp
/* * Copyright (C) 2020 Tomasz Grobelny <tomasz@grobelny.net> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/dbus/sensors_server.h" #include "anbox/android/intent.h" #include "anbox/application/sensor_type.h" #include "anbox/logger.h" #include "sdbus-c++/Error.h" sdbus::Struct<double, double, double> SensorsServer::Acceleration() { if (impl_->disabled_sensors & anbox::application::SensorType::AccelerationSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Acceleration sensor is disabled"); return sdbus::Struct<double, double, double>(impl_->acceleration); } void SensorsServer::Acceleration(const sdbus::Struct<double, double, double>& value) { if (impl_->disabled_sensors & anbox::application::SensorType::AccelerationSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Acceleration sensor is disabled"); impl_->acceleration = value; } sdbus::Struct<double, double, double> SensorsServer::MagneticField() { if (impl_->disabled_sensors & anbox::application::SensorType::MagneticFieldSensor) throw sdbus::Error("org.anbox.SensorDisabled", "MagneticField sensor is disabled"); return sdbus::Struct<double, double, double>(impl_->magneticField); } void SensorsServer::MagneticField(const sdbus::Struct<double, double, double>& value) { if (impl_->disabled_sensors & anbox::application::SensorType::MagneticFieldSensor) throw sdbus::Error("org.anbox.SensorDisabled", "MagneticField sensor is disabled"); impl_->magneticField = value; } sdbus::Struct<double, double, double> SensorsServer::Orientation() { if (impl_->disabled_sensors & anbox::application::SensorType::OrientationSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Orientation sensor is disabled"); return sdbus::Struct<double, double, double>(impl_->orientation); } void SensorsServer::Orientation(const sdbus::Struct<double, double, double>& value) { if (impl_->disabled_sensors & anbox::application::SensorType::OrientationSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Orientation sensor is disabled"); impl_->orientation = value; } double SensorsServer::Temperature() { if (impl_->disabled_sensors & anbox::application::SensorType::TemperatureSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Temperature sensor is disabled"); return impl_->temperature; } void SensorsServer::Temperature(const double& value) { if (impl_->disabled_sensors & anbox::application::SensorType::TemperatureSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Temperature sensor is disabled"); impl_->temperature = value; } double SensorsServer::Proximity() { if (impl_->disabled_sensors & anbox::application::SensorType::ProximitySensor) throw sdbus::Error("org.anbox.SensorDisabled", "Proximity sensor is disabled"); return impl_->proximity; } void SensorsServer::Proximity(const double& value) { if (impl_->disabled_sensors & anbox::application::SensorType::ProximitySensor) throw sdbus::Error("org.anbox.SensorDisabled", "Proximity sensor is disabled"); impl_->proximity = value; } double SensorsServer::Light() { if (impl_->disabled_sensors & anbox::application::SensorType::LightSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Light sensor is disabled"); return impl_->light; } void SensorsServer::Light(const double& value) { if (impl_->disabled_sensors & anbox::application::SensorType::LightSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Light sensor is disabled"); impl_->light = value; } double SensorsServer::Pressure() { if (impl_->disabled_sensors & anbox::application::SensorType::PressureSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Pressure sensor is disabled"); return impl_->pressure; } void SensorsServer::Pressure(const double& value) { if (impl_->disabled_sensors & anbox::application::SensorType::PressureSensor) throw sdbus::Error("org.anbox.SensorDisabled", "Pressure sensor is disabled"); impl_->pressure = value; } double SensorsServer::Humidity() { if (impl_->disabled_sensors & anbox::application::SensorType::HumiditySensor) throw sdbus::Error("org.anbox.SensorDisabled", "Humidity sensor is disabled"); return impl_->humidity; } void SensorsServer::Humidity(const double& value) { if (impl_->disabled_sensors & anbox::application::SensorType::HumiditySensor) throw sdbus::Error("org.anbox.SensorDisabled", "Humidity sensor is disabled"); impl_->humidity = value; }
5,036
C++
.cpp
101
47.267327
87
0.76022
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,579
bus.cpp
anbox_anbox/src/anbox/dbus/bus.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/dbus/bus.h" #include "anbox/logger.h" namespace anbox::dbus { Bus::Bus(Type type) { int ret = 0; switch (type) { case Type::Session: ret = sd_bus_open_user(&bus_); break; case Type::System: ret = sd_bus_open_system(&bus_); break; default: throw std::invalid_argument("Invalid bus type"); } if (ret < 0 || !bus_) throw std::runtime_error("Failed to connect to DBus"); } Bus::~Bus() { stop(); if (bus_) sd_bus_unref(bus_); } bool Bus::has_service_with_name(const std::string &name) { auto r = sd_bus_get_name_creds(bus_, name.c_str(), 0, nullptr); return r >= 0; } sd_bus* Bus::raw() { return bus_; } void Bus::run_async() { running_ = true; worker_thread_ = std::thread(&Bus::worker_main, this); } void Bus::stop() { running_ = false; if (worker_thread_.joinable()) worker_thread_.join(); } void Bus::worker_main() { while (running_) { auto ret = sd_bus_process(bus_, nullptr); if (ret < 0) break; if (ret > 0) continue; ret = sd_bus_wait(bus_, 1000 * 500); if (ret < 0) break; } } }
1,888
C++
.cpp
71
22.352113
76
0.631433
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,580
application_manager_client.cpp
anbox_anbox/src/anbox/dbus/application_manager_client.cpp
/* * Copyright (C) 2020 Tomasz Grobelny <tomasz@grobelny.net> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "application_manager_client.h" bool ApplicationManagerClient::TryLaunch(anbox::android::Intent intent, anbox::wm::Stack::Id stack) { try { DEBUG("Sending launch intent %s to Android ..", intent); std::map<std::string, sdbus::Variant> intentDict; std::ostringstream launch_stack; launch_stack << stack; if (intent.action.length()) intentDict["action"] = sdbus::Variant(intent.action); if (intent.component.length()) intentDict["component"] = sdbus::Variant(intent.component); if (intent.package.length()) intentDict["package"] = sdbus::Variant(intent.package); if (intent.type.length()) intentDict["type"] = sdbus::Variant(intent.type); if (intent.uri.length()) intentDict["uri"] = sdbus::Variant(intent.uri); this->Launch(intentDict, launch_stack.str()); } catch (const std::exception &err) { ERROR("Failed to launch activity: %s", err.what()); return false; } catch (...) { ERROR("Failed to launch activity"); return false; } return true; }
1,730
C++
.cpp
43
36.581395
101
0.70962
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,581
application_manager_server.cpp
anbox_anbox/src/anbox/dbus/application_manager_server.cpp
/* * Copyright (C) 2020 Tomasz Grobelny <tomasz@grobelny.net> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/dbus/application_manager_server.h" #include <sstream> #include "anbox/android/intent.h" #include "anbox/logger.h" void ApplicationManagerServer::Launch(const std::map<std::string, sdbus::Variant>& intentDict, const std::string& stack) { anbox::android::Intent intent; intent.package = intentDict.count("package") ? intentDict.at("package").get<std::string>() : intent.package; intent.component = intentDict.count("component") ? intentDict.at("component").get<std::string>() : intent.component; intent.action = intentDict.count("action") ? intentDict.at("action").get<std::string>() : intent.action; intent.type = intentDict.count("type") ? intentDict.at("type").get<std::string>() : intent.type; intent.uri = intentDict.count("uri") ? intentDict.at("uri").get<std::string>() : intent.uri; anbox::wm::Stack::Id launch_stack = anbox::wm::Stack::Id::Default; if (stack.length() > 0) { auto s = std::string(stack); std::istringstream i(s); i >> launch_stack; } if (intent.package.length() == 0) { throw sdbus::Error("org.anbox.InvalidArgument", "No package specified"); } try { if (!impl_->ready()) throw std::runtime_error("Anbox not yet ready to launch applications"); DEBUG("Launching %s", intent); impl_->launch(intent, anbox::graphics::Rect::Invalid, launch_stack); } catch (std::exception& err) { ERROR("Failed to launch application: %s", err.what()); throw sdbus::Error("org.anbox.InternalError", err.what()); } } bool ApplicationManagerServer::Ready() { return impl_->ready(); }
2,259
C++
.cpp
49
43.163265
122
0.714351
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,582
gps_server.cpp
anbox_anbox/src/anbox/dbus/gps_server.cpp
/* * Copyright (C) 2020 Tomasz Grobelny <tomasz@grobelny.net> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/dbus/gps_server.h" #include "anbox/android/intent.h" #include "anbox/logger.h" using namespace std; void GpsServer::PushSentence(const string& sentence) { gps_info_broker_->newNmeaSentence(sentence); }
904
C++
.cpp
23
37.391304
76
0.767389
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,584
platform_message_processor.cpp
anbox_anbox/src/anbox/bridge/platform_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/bridge/platform_message_processor.h" #include "anbox/bridge/platform_api_skeleton.h" #include "anbox/logger.h" #include "anbox/rpc/template_message_processor.h" #include "anbox_bridge.pb.h" namespace anbox::bridge { PlatformMessageProcessor::PlatformMessageProcessor( const std::shared_ptr<network::MessageSender> &sender, const std::shared_ptr<PlatformApiSkeleton> &server, const std::shared_ptr<rpc::PendingCallCache> &pending_calls) : rpc::MessageProcessor(sender, pending_calls), server_(server) {} PlatformMessageProcessor::~PlatformMessageProcessor() {} void PlatformMessageProcessor::dispatch(rpc::Invocation const &invocation) { if (invocation.method_name() == "set_clipboard_data") invoke(this, server_.get(), &PlatformApiSkeleton::set_clipboard_data, invocation); else if (invocation.method_name() == "get_clipboard_data") invoke(this, server_.get(), &PlatformApiSkeleton::get_clipboard_data, invocation); } void PlatformMessageProcessor::process_event_sequence( const std::string &raw_events) { anbox::protobuf::bridge::EventSequence seq; if (!seq.ParseFromString(raw_events)) { WARNING("Failed to parse events from raw string"); return; } if (seq.has_boot_finished()) server_->handle_boot_finished_event(seq.boot_finished()); if (seq.has_window_state_update()) server_->handle_window_state_update_event(seq.window_state_update()); if (seq.has_application_list_update()) server_->handle_application_list_update_event( seq.application_list_update()); } }
2,236
C++
.cpp
50
41.8
86
0.755168
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,585
android_api_stub.cpp
anbox_anbox/src/anbox/bridge/android_api_stub.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/bridge/android_api_stub.h" #include "anbox/system_configuration.h" #include "anbox/logger.h" #include "anbox/rpc/channel.h" #include "anbox/utils.h" #include "anbox/wm/stack.h" #include "anbox_bridge.pb.h" #include "anbox_rpc.pb.h" #include <boost/filesystem.hpp> #ifdef USE_PROTOBUF_CALLBACK_HEADER #include <google/protobuf/stubs/callback.h> #endif namespace fs = boost::filesystem; namespace { constexpr const std::chrono::milliseconds default_rpc_call_timeout{30000}; } // namespace namespace anbox::bridge { AndroidApiStub::AndroidApiStub() {} AndroidApiStub::~AndroidApiStub() {} void AndroidApiStub::set_rpc_channel( const std::shared_ptr<rpc::Channel> &channel) { channel_ = channel; } void AndroidApiStub::reset_rpc_channel() { channel_.reset(); } void AndroidApiStub::ensure_rpc_channel() { if (!channel_) throw std::runtime_error("No remote client connected"); } void AndroidApiStub::launch(const android::Intent &intent, const graphics::Rect &launch_bounds, const wm::Stack::Id &stack) { ensure_rpc_channel(); auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::bridge::LaunchApplication message; { std::lock_guard<decltype(mutex_)> lock(mutex_); launch_wait_handle_.expect_result(); } switch (stack) { case wm::Stack::Id::Default: message.set_stack(::anbox::protobuf::bridge::LaunchApplication_Stack_DEFAULT); break; case wm::Stack::Id::Fullscreen: message.set_stack(::anbox::protobuf::bridge::LaunchApplication_Stack_FULLSCREEN); break; case wm::Stack::Id::Freeform: message.set_stack(::anbox::protobuf::bridge::LaunchApplication_Stack_FREEFORM); break; default: break; } if (launch_bounds != graphics::Rect::Invalid) { auto rect = message.mutable_launch_bounds(); rect->set_left(launch_bounds_.left()); rect->set_top(launch_bounds_.top()); rect->set_right(launch_bounds_.right()); rect->set_bottom(launch_bounds_.bottom()); } auto launch_intent = message.mutable_intent(); if (!intent.action.empty()) launch_intent->set_action(intent.action); if (!intent.uri.empty()) launch_intent->set_uri(intent.uri); if (!intent.type.empty()) launch_intent->set_type(intent.type); if (!intent.package.empty()) launch_intent->set_package(intent.package); if (!intent.component.empty()) launch_intent->set_component(intent.component); for (const auto &category : intent.categories) { auto c = launch_intent->add_categories(); *c = category; } channel_->call_method( "launch_application", &message, c->response.get(), google::protobuf::NewCallback(this, &AndroidApiStub::application_launched, c.get())); launch_wait_handle_.wait_for_pending(default_rpc_call_timeout); if (!launch_wait_handle_.has_result()) throw std::runtime_error("RPC call timed out"); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } core::Property<bool>& AndroidApiStub::ready() { return ready_; } void AndroidApiStub::application_launched( Request<protobuf::rpc::Void> *request) { (void)request; launch_wait_handle_.result_received(); } void AndroidApiStub::set_focused_task(const std::int32_t &id) { ensure_rpc_channel(); auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::bridge::SetFocusedTask message; message.set_id(id); { std::lock_guard<decltype(mutex_)> lock(mutex_); set_focused_task_handle_.expect_result(); } channel_->call_method("set_focused_task", &message, c->response.get(), google::protobuf::NewCallback( this, &AndroidApiStub::focused_task_set, c.get())); set_focused_task_handle_.wait_for_pending(default_rpc_call_timeout); if (!set_focused_task_handle_.has_result()) throw std::runtime_error("RPC call timed out"); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } void AndroidApiStub::focused_task_set(Request<protobuf::rpc::Void> *request) { (void)request; set_focused_task_handle_.result_received(); } void AndroidApiStub::remove_task(const std::int32_t &id) { ensure_rpc_channel(); auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::bridge::RemoveTask message; message.set_id(id); { std::lock_guard<decltype(mutex_)> lock(mutex_); remove_task_handle_.expect_result(); } channel_->call_method("remove_task", &message, c->response.get(), google::protobuf::NewCallback( this, &AndroidApiStub::task_removed, c.get())); remove_task_handle_.wait_for_pending(default_rpc_call_timeout); if (!remove_task_handle_.has_result()) throw std::runtime_error("RPC call timed out"); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } void AndroidApiStub::task_removed(Request<protobuf::rpc::Void> *request) { (void)request; remove_task_handle_.result_received(); } void AndroidApiStub::resize_task(const std::int32_t &id, const anbox::graphics::Rect &rect, const std::int32_t &resize_mode) { ensure_rpc_channel(); auto c = std::make_shared<Request<protobuf::rpc::Void>>(); protobuf::bridge::ResizeTask message; message.set_id(id); message.set_resize_mode(resize_mode); auto r = message.mutable_rect(); r->set_left(rect.left()); r->set_top(rect.top()); r->set_right(rect.right()); r->set_bottom(rect.bottom()); { std::lock_guard<decltype(mutex_)> lock(mutex_); resize_task_handle_.expect_result(); } channel_->call_method("resize_task", &message, c->response.get(), google::protobuf::NewCallback( this, &AndroidApiStub::task_resized, c.get())); resize_task_handle_.wait_for_pending(default_rpc_call_timeout); if (!resize_task_handle_.has_result()) throw std::runtime_error("RPC call timed out"); if (c->response->has_error()) throw std::runtime_error(c->response->error()); } void AndroidApiStub::task_resized(Request<protobuf::rpc::Void> *request) { (void)request; resize_task_handle_.result_received(); } }
6,953
C++
.cpp
172
35.651163
85
0.688661
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,586
platform_api_skeleton.cpp
anbox_anbox/src/anbox/bridge/platform_api_skeleton.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/bridge/platform_api_skeleton.h" #include "anbox/application/database.h" #include "anbox/platform/base_platform.h" #include "anbox/wm/manager.h" #include "anbox/wm/window_state.h" #include "anbox/logger.h" #if defined(Status) #undef Status #endif // defined(Status) #include "anbox_bridge.pb.h" #ifdef USE_PROTOBUF_CALLBACK_HEADER #include <google/protobuf/stubs/callback.h> #endif namespace anbox::bridge { PlatformApiSkeleton::PlatformApiSkeleton( const std::shared_ptr<rpc::PendingCallCache> &pending_calls, const std::shared_ptr<platform::BasePlatform> &platform, const std::shared_ptr<wm::Manager> &window_manager, const std::shared_ptr<application::Database> &app_db) : pending_calls_(pending_calls), platform_(platform), window_manager_(window_manager), app_db_(app_db) {} PlatformApiSkeleton::~PlatformApiSkeleton() {} void PlatformApiSkeleton::set_clipboard_data(anbox::protobuf::bridge::ClipboardData const *request, anbox::protobuf::rpc::Void *response, google::protobuf::Closure *done) { (void)response; if (request->has_text()) platform_->set_clipboard_data(platform::BasePlatform::ClipboardData{request->text()}); done->Run(); } void PlatformApiSkeleton::get_clipboard_data(anbox::protobuf::rpc::Void const *request, anbox::protobuf::bridge::ClipboardData *response, google::protobuf::Closure *done) { (void)request; auto data = platform_->get_clipboard_data(); if (!data.text.empty()) response->set_text(data.text); done->Run(); } void PlatformApiSkeleton::handle_boot_finished_event(const anbox::protobuf::bridge::BootFinishedEvent&) { if (boot_finished_handler_) boot_finished_handler_(); } void PlatformApiSkeleton::handle_window_state_update_event(const anbox::protobuf::bridge::WindowStateUpdateEvent &event) { auto convert_window_state = []( const ::anbox::protobuf::bridge::WindowStateUpdateEvent_WindowState &window) { return wm::WindowState( wm::Display::Id(window.display_id()), window.has_surface(), graphics::Rect(window.frame_left(), window.frame_top(), window.frame_right(), window.frame_bottom()), window.package_name(), wm::Task::Id(window.task_id()), wm::Stack::Id(window.stack_id())); }; wm::WindowState::List updated; for (int n = 0; n < event.windows_size(); n++) { const auto window = event.windows(n); updated.push_back(convert_window_state(window)); } wm::WindowState::List removed; for (int n = 0; n < event.removed_windows_size(); n++) { const auto window = event.removed_windows(n); removed.push_back(convert_window_state(window)); } window_manager_->apply_window_state_update(updated, removed); } void PlatformApiSkeleton::handle_application_list_update_event(const anbox::protobuf::bridge::ApplicationListUpdateEvent &event) { for (int n = 0; n < event.removed_applications_size(); n++) { application::Database::Item item; const auto app = event.removed_applications(n); item.package = app.package(); if (item.package.empty()) continue; app_db_->remove(item); } for (int n = 0; n < event.applications_size(); n++) { application::Database::Item item; const auto app = event.applications(n); item.name = app.name(); item.package = app.package(); const auto li = app.launch_intent(); item.launch_intent.action = li.action(); item.launch_intent.uri = li.uri(); item.launch_intent.type = li.uri(); item.launch_intent.package = li.package(); item.launch_intent.component = li.component(); for (int m = 0; m < li.categories_size(); m++) item.launch_intent.categories.push_back(li.categories(m)); item.icon = std::vector<char>(app.icon().begin(), app.icon().end()); if (item.package.empty()) continue; app_db_->store_or_update(item); } } void PlatformApiSkeleton::register_boot_finished_handler(const std::function<void()> &action) { boot_finished_handler_ = action; } }
4,883
C++
.cpp
116
36.758621
130
0.686577
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,587
opengles_message_processor.cpp
anbox_anbox/src/anbox/graphics/opengles_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/opengles_message_processor.h" #include "anbox/graphics/emugl/RenderThread.h" #include "anbox/logger.h" #include "anbox/network/connections.h" #include "anbox/network/delegate_message_processor.h" #include <condition_variable> #include <functional> #include <queue> namespace anbox::graphics { std::mutex OpenGlesMessageProcessor::global_lock{}; OpenGlesMessageProcessor::OpenGlesMessageProcessor( const std::shared_ptr<Renderer> &renderer, const std::shared_ptr<network::SocketMessenger> &messenger) : messenger_(messenger), stream_(std::make_shared<BufferedIOStream>(messenger_)) { // We have to read the client flags first before we can continue // processing the actual commands unsigned int client_flags = 0; auto err = messenger_->receive_msg( boost::asio::buffer(&client_flags, sizeof(unsigned int))); if (err) ERROR("%s", err.message()); render_thread_.reset(RenderThread::create(renderer, stream_.get(), std::ref(global_lock))); if (!render_thread_->start()) BOOST_THROW_EXCEPTION( std::runtime_error("Failed to start renderer thread")); } OpenGlesMessageProcessor::~OpenGlesMessageProcessor() { render_thread_->forceStop(); render_thread_->wait(nullptr); } bool OpenGlesMessageProcessor::process_data( network::MessageBuffer &&data) { auto stream = std::static_pointer_cast<BufferedIOStream>(stream_); stream->post_data(std::move(data)); return true; } }
2,134
C++
.cpp
53
37.641509
93
0.754098
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,589
opengles_socket_connection.cpp
anbox_anbox/src/anbox/graphics/opengles_socket_connection.cpp
/* * Copyright © 2018 The UBports project * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Marius Gripsgard <marius@ubports.com> */ #include "anbox/logger.h" #include "anbox/network/message_receiver.h" #include "anbox/network/message_sender.h" #include "anbox/graphics/opengles_socket_connection.h" #include "anbox/graphics/buffered_io_stream.h" #include <boost/signals2.hpp> #include <boost/throw_exception.hpp> #include <stdexcept> #include <sys/socket.h> #include <sys/types.h> namespace ba = boost::asio; namespace bs = boost::system; namespace anbox { namespace graphics { OpenGlesSocketConnection::OpenGlesSocketConnection( std::shared_ptr<network::MessageReceiver> const& message_receiver, std::shared_ptr<network::MessageSender> const& message_sender, int id, std::shared_ptr<network::Connections<network::SocketConnection>> const& connections, std::shared_ptr<network::MessageProcessor> const& processor): SocketConnection(message_receiver, message_sender, id, connections, processor) {} void OpenGlesSocketConnection::read_next_message() { auto callback = std::bind(&OpenGlesSocketConnection::on_read_size, this, std::placeholders::_1, std::placeholders::_2); message_receiver_->async_receive_msg(callback, ba::buffer(buffer_)); } void OpenGlesSocketConnection::on_read_size(const boost::system::error_code& error, std::size_t bytes_read) { if (error) { connections_->remove(id()); return; } Buffer data{}; data.resize_noinit(bytes_read); // Use memcpy here, its faster then std::copy memcpy(data.data(), buffer_.data(), bytes_read); if (processor_->process_data(std::move(data))) read_next_message(); else connections_->remove(id()); } } // namespace anbox } // namespace graphics
2,377
C++
.cpp
59
36.898305
121
0.737093
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,590
single_window_composer_strategy.cpp
anbox_anbox/src/anbox/graphics/single_window_composer_strategy.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/single_window_composer_strategy.h" #include "anbox/wm/manager.h" #include "anbox/utils.h" #include "anbox/logger.h" namespace { const constexpr char *sprite_name{"Sprite"}; } namespace anbox::graphics { SingleWindowComposerStrategy::SingleWindowComposerStrategy(const std::shared_ptr<wm::Manager> &wm) : wm_(wm) {} std::map<std::shared_ptr<wm::Window>, RenderableList> SingleWindowComposerStrategy::process_layers(const RenderableList &renderables) { WindowRenderableList win_layers; // FIXME there will be only one window in single-window mode ever so it // doesn't matter which task auto window = wm_->find_window_for_task(0); // Filter out any unwanted layers like the one responsible for the mouse // cursor which we don't want to render. RenderableList final_renderables; for (const auto &r : renderables) { if (r.name() == sprite_name) continue; final_renderables.push_back(r); } win_layers.insert({window, final_renderables}); return win_layers; } }
1,697
C++
.cpp
42
38.071429
135
0.75697
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,592
buffer_queue.cpp
anbox_anbox/src/anbox/graphics/buffer_queue.cpp
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "anbox/graphics/buffer_queue.h" namespace anbox::graphics { BufferQueue::BufferQueue(size_t capacity) : capacity_(capacity), buffers_(new Buffer[capacity]) {} int BufferQueue::try_push_locked(Buffer &&buffer) { if (closed_) return -EIO; if (count_ >= capacity_) return -EAGAIN; size_t pos = pos_ + count_; if (pos >= capacity_) pos -= capacity_; buffers_[pos] = std::move(buffer); if (count_++ == 0) can_pop_.notify_one(); return 0; } int BufferQueue::push_locked( Buffer &&buffer, std::unique_lock<std::mutex> &lock) { while (count_ == capacity_) { if (closed_) return -EIO; can_push_.wait(lock); } return try_push_locked(std::move(buffer)); } int BufferQueue::try_pop_locked(Buffer *buffer) { if (count_ == 0) return closed_ ? -EIO : -EAGAIN; *buffer = std::move(buffers_[pos_]); size_t pos = pos_ + 1; if (pos >= capacity_) pos -= capacity_; pos_ = pos; if (count_-- == capacity_) can_push_.notify_one(); return 0; } int BufferQueue::pop_locked( Buffer *buffer, std::unique_lock<std::mutex> &lock) { while (count_ == 0) { if (closed_) // Closed queue is empty. return -EIO; can_pop_.wait(lock); } return try_pop_locked(buffer); } // Close the queue, it is no longer possible to push new items // to it (i.e. push() will always return Result::Error), or to // read from an empty queue (i.e. pop() will always return // Result::Error once the queue becomes empty). void BufferQueue::close_locked() { closed_ = true; // Wake any potential waiters. if (count_ == capacity_) { can_push_.notify_all(); } if (count_ == 0) { can_pop_.notify_all(); } } }
2,314
C++
.cpp
76
27.5
75
0.672662
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,593
layer_composer.cpp
anbox_anbox/src/anbox/graphics/layer_composer.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/layer_composer.h" #include "anbox/graphics/emugl/Renderer.h" #include "anbox/logger.h" #include "anbox/wm/manager.h" namespace anbox::graphics { LayerComposer::LayerComposer(const std::shared_ptr<Renderer> renderer, const std::shared_ptr<Strategy> &strategy) : renderer_(renderer), strategy_(strategy) {} LayerComposer::~LayerComposer() {} void LayerComposer::submit_layers(const RenderableList &renderables) { auto win_layers = strategy_->process_layers(renderables); for (auto &w : win_layers) { renderer_->draw(w.first->native_handle(), Rect{0, 0, w.first->frame().width(), w.first->frame().height()}, w.second); } } }
1,378
C++
.cpp
33
38.575758
113
0.728018
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,594
density.cpp
anbox_anbox/src/anbox/graphics/density.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/density.h" namespace anbox::graphics { DensityType current_density() { return DensityType::medium; } int dp_to_pixel(unsigned int dp) { return dp * static_cast<unsigned int>(current_density()) / static_cast<unsigned int>(DensityType::medium); } }
952
C++
.cpp
25
36.24
108
0.76
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,595
multi_window_composer_strategy.cpp
anbox_anbox/src/anbox/graphics/multi_window_composer_strategy.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/multi_window_composer_strategy.h" #include "anbox/wm/manager.h" #include "anbox/utils.h" namespace anbox::graphics { MultiWindowComposerStrategy::MultiWindowComposerStrategy(const std::shared_ptr<wm::Manager> &wm) : wm_(wm) {} std::map<std::shared_ptr<wm::Window>, RenderableList> MultiWindowComposerStrategy::process_layers(const RenderableList &renderables) { WindowRenderableList win_layers; for (const auto &renderable : renderables) { // Ignore all surfaces which are not meant for a task if (!utils::string_starts_with(renderable.name(), "org.anbox.surface.")) continue; wm::Task::Id task_id = 0; if (sscanf(renderable.name().c_str(), "org.anbox.surface.%d", &task_id) != 1 || !task_id) continue; auto w = wm_->find_window_for_task(task_id); if (!w) continue; if (win_layers.find(w) == win_layers.end()) { win_layers.insert({w, {renderable}}); continue; } win_layers[w].push_back(renderable); } for (auto &w : win_layers) { const auto &renderables = w.second; RenderableList final_renderables; auto new_window_frame = Rect::Invalid; auto max_layer_area = -1; for (auto &r : renderables) { const auto layer_area = r.screen_position().width() * r.screen_position().height(); // We always prioritize layers which are lower in the list we got // from SurfaceFlinger as they are already ordered. if (layer_area < max_layer_area) continue; max_layer_area = layer_area; new_window_frame = r.screen_position(); } for (auto &r : renderables) { // As we get absolute display coordinates from the Android hwcomposer we // need to recalculate all layer coordinates into relatives ones to the // window they are drawn into. auto rect = Rect{ r.screen_position().left() - new_window_frame.left() + r.crop().left(), r.screen_position().top() - new_window_frame.top() + r.crop().top(), r.screen_position().right() - new_window_frame.left() + r.crop().left(), r.screen_position().bottom() - new_window_frame.top() + r.crop().top()}; auto new_renderable = r; new_renderable.set_screen_position(rect); final_renderables.push_back(new_renderable); } w.second = final_renderables; } return win_layers; } }
3,037
C++
.cpp
70
38.642857
134
0.686188
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,596
buffered_io_stream.cpp
anbox_anbox/src/anbox/graphics/buffered_io_stream.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/graphics/buffered_io_stream.h" #include "anbox/logger.h" namespace anbox::graphics { BufferedIOStream::BufferedIOStream( const std::shared_ptr<anbox::network::SocketMessenger> &messenger, size_t buffer_size) : IOStream(buffer_size), messenger_(messenger), in_queue_(1024U), out_queue_(16U), worker_thread_(&BufferedIOStream::thread_main, this) { write_buffer_.resize_noinit(buffer_size); } BufferedIOStream::~BufferedIOStream() { forceStop(); if (worker_thread_.joinable()) worker_thread_.join(); } void *BufferedIOStream::allocBuffer(size_t min_size) { std::unique_lock<std::mutex> l(out_lock_); if (write_buffer_.size() < min_size) write_buffer_.resize_noinit(min_size); return write_buffer_.data(); } size_t BufferedIOStream::commitBuffer(size_t size) { std::unique_lock<std::mutex> l(out_lock_); assert(size <= write_buffer_.size()); if (write_buffer_.isAllocated()) { write_buffer_.resize(size); out_queue_.push_locked(std::move(write_buffer_), l); } else { out_queue_.push_locked( Buffer{write_buffer_.data(), write_buffer_.data() + size}, l); } return size; } const unsigned char *BufferedIOStream::read(void *buf, size_t *inout_len) { std::unique_lock<std::mutex> l(lock_); size_t wanted = *inout_len; size_t count = 0U; auto dst = static_cast<uint8_t *>(buf); while (count < wanted) { if (read_buffer_left_ > 0) { size_t avail = std::min<size_t>(wanted - count, read_buffer_left_); memcpy(dst + count, read_buffer_.data() + (read_buffer_.size() - read_buffer_left_), avail); count += avail; read_buffer_left_ -= avail; continue; } bool blocking = (count == 0); auto result = -EIO; if (blocking) result = in_queue_.pop_locked(&read_buffer_, l); else result = in_queue_.try_pop_locked(&read_buffer_); if (result == 0) { read_buffer_left_ = read_buffer_.size(); continue; } if (count > 0) break; // If we end up here something went wrong and we couldn't read // any valid data. return nullptr; } *inout_len = count; return static_cast<const unsigned char *>(buf); } void BufferedIOStream::forceStop() { std::lock_guard<std::mutex> l(lock_); in_queue_.close_locked(); out_queue_.close_locked(); } void BufferedIOStream::post_data(Buffer &&data) { std::unique_lock<std::mutex> l(lock_); in_queue_.push_locked(std::move(data), l); } bool BufferedIOStream::needs_data() { std::unique_lock<std::mutex> l(lock_); return !in_queue_.can_pop_locked(); } void BufferedIOStream::thread_main() { while (true) { std::unique_lock<std::mutex> l(out_lock_); Buffer buffer; const auto result = out_queue_.pop_locked(&buffer, l); if (result != 0 && result != -EAGAIN) break; auto bytes_left = buffer.size(); while (bytes_left > 0) { const auto written = messenger_->send_raw( buffer.data() + (buffer.size() - bytes_left), bytes_left); if (written < 0) { if (errno != EINTR && errno != EAGAIN) { ERROR("Failed to write data: %s", std::strerror(errno)); break; } // Socket is busy, lets try again } else bytes_left -= written; } } } }
3,977
C++
.cpp
118
29.474576
77
0.659641
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,598
RenderControl.cpp
anbox_anbox/src/anbox/graphics/emugl/RenderControl.cpp
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "anbox/graphics/emugl/RenderControl.h" #include "anbox/graphics/emugl/DispatchTables.h" #include "anbox/graphics/emugl/DisplayManager.h" #include "anbox/graphics/emugl/RenderThreadInfo.h" #include "anbox/graphics/emugl/Renderer.h" #include "anbox/graphics/emugl/RendererConfig.h" #include "anbox/graphics/layer_composer.h" #include "anbox/logger.h" #include "external/android-emugl/shared/OpenglCodecCommon/ChecksumCalculatorThreadInfo.h" #include "external/android-emugl/host/include/OpenGLESDispatch/EGLDispatch.h" #include <map> #include <string> #include <sstream> static const GLint rendererVersion = 1; static std::shared_ptr<anbox::graphics::LayerComposer> composer; static std::shared_ptr<Renderer> renderer; void registerLayerComposer( const std::shared_ptr<anbox::graphics::LayerComposer> &c) { composer = c; } void registerRenderer(const std::shared_ptr<Renderer> &r) { renderer = r; } static GLint rcGetRendererVersion() { return rendererVersion; } static EGLint rcGetEGLVersion(EGLint *major, EGLint *minor) { if (!renderer) return EGL_FALSE; *major = static_cast<EGLint>(renderer->getCaps().eglMajor); *minor = static_cast<EGLint>(renderer->getCaps().eglMinor); return EGL_TRUE; } static std::string filter_extensions(const std::string& extensions, const std::vector<std::string>& whitelist) { std::stringstream approved_extensions; auto extension_list = anbox::utils::string_split(extensions, ' '); for (const auto& ext : extension_list) { if (std::find(whitelist.begin(), whitelist.end(), ext) == whitelist.end()) continue; if (approved_extensions.tellp() > 0) approved_extensions << " "; approved_extensions << ext; } return approved_extensions.str(); } static EGLint rcQueryEGLString(EGLenum name, void* buffer, EGLint bufferSize) { if (!renderer) return 0; std::string result = s_egl.eglQueryString(renderer->getDisplay(), name); if (result.empty()) return 0; if (name == EGL_EXTENSIONS) { // We need to drop a few extensions from the list reported by the driver // as not all are well enough support by our EGL implementation. std::vector<std::string> whitelisted_extensions = { "EGL_KHR_image_base", "EGL_KHR_gl_texture_2D_image", }; result = filter_extensions(result, whitelisted_extensions); } int len = result.length() + 1; if (!buffer || len > bufferSize) { return -len; } strcpy(static_cast<char*>(buffer), result.c_str()); return len; } static EGLint rcGetGLString(EGLenum name, void* buffer, EGLint bufferSize) { RenderThreadInfo* tInfo = RenderThreadInfo::get(); std::string result; if (tInfo && tInfo->currContext) { const char* str = nullptr; if (tInfo->currContext->isGL2()) str = reinterpret_cast<const char*>(s_gles2.glGetString(name)); else str = reinterpret_cast<const char*>(s_gles1.glGetString(name)); if (str) result += str; } // We're forcing version 2.0 no matter what the host provides as // our emulation layer isn't prepared for anything newer (yet). // This goes in parallel with filtering the extension set for // any unwanted extensions. If we don't force the right version // here certain parts of the system will assume API conditions // which aren't met. if (name == GL_VERSION) result = "OpenGL ES 2.0"; else if (name == GL_EXTENSIONS) { // We need to drop a few extensions from the list reported by the driver // as not all are well enough support by our GL implementation. std::vector<std::string> whitelisted_extensions = { "GL_OES_EGL_image", "GL_OES_EGL_image_external", "GL_OES_depth24", "GL_OES_depth32", "GL_OES_element_index_uint", "GL_OES_texture_float", "GL_OES_texture_float_linear", "GL_OES_compressed_paletted_texture", "GL_OES_compressed_ETC1_RGB8_texture", "GL_OES_depth_texture", "GL_OES_texture_half_float", "GL_OES_texture_half_float_linear", "GL_OES_packed_depth_stencil", "GL_OES_vertex_half_float", "GL_OES_standard_derivatives", "GL_OES_texture_npot", "GL_OES_rgb8_rgba8", }; result = filter_extensions(result, whitelisted_extensions); } int nextBufferSize = result.size() + 1; if (!buffer || nextBufferSize > bufferSize) return -nextBufferSize; snprintf(static_cast<char*>(buffer), nextBufferSize, "%s", result.c_str()); return nextBufferSize; } static EGLint rcGetNumConfigs(uint32_t *p_numAttribs) { int numConfigs = 0, numAttribs = 0; renderer->getConfigs()->getPackInfo(&numConfigs, &numAttribs); if (p_numAttribs) { *p_numAttribs = static_cast<uint32_t>(numAttribs); } return numConfigs; } static EGLint rcGetConfigs(uint32_t bufSize, GLuint *buffer) { GLuint bufferSize = static_cast<GLuint>(bufSize); return renderer->getConfigs()->packConfigs(bufferSize, buffer); } static EGLint rcChooseConfig(EGLint *attribs, uint32_t attribs_size, uint32_t *configs, uint32_t configs_size) { if (!renderer || attribs_size == 0) return 0; return renderer->getConfigs()->chooseConfig(attribs, reinterpret_cast<EGLint *>(configs), static_cast<EGLint>(configs_size)); } static EGLint rcGetFBParam(EGLint param) { if (!renderer) return 0; EGLint ret = 0; switch (param) { case FB_WIDTH: ret = static_cast<EGLint>(anbox::graphics::emugl::DisplayInfo::get()->vertical_resolution()); break; case FB_HEIGHT: ret = static_cast<EGLint>(anbox::graphics::emugl::DisplayInfo::get()->horizontal_resolution()); break; case FB_XDPI: ret = 72; // XXX: should be implemented break; case FB_YDPI: ret = 72; // XXX: should be implemented break; case FB_FPS: ret = 60; break; case FB_MIN_SWAP_INTERVAL: ret = 1; // XXX: should be implemented break; case FB_MAX_SWAP_INTERVAL: ret = 1; // XXX: should be implemented break; default: break; } return ret; } static uint32_t rcCreateContext(uint32_t config, uint32_t share, uint32_t glVersion) { if (!renderer) return 0; // To make it consistent with the guest, create GLES2 context when GL // version==2 or 3 HandleType ret = renderer->createRenderContext(config, share, glVersion == 2 || glVersion == 3); return ret; } static void rcDestroyContext(uint32_t context) { if (!renderer) return; renderer->DestroyRenderContext(context); } static uint32_t rcCreateWindowSurface(uint32_t config, uint32_t width, uint32_t height) { if (!renderer) return 0; return renderer->createWindowSurface(config, width, height); } static void rcDestroyWindowSurface(uint32_t windowSurface) { if (!renderer) return; renderer->DestroyWindowSurface(windowSurface); } static uint32_t rcCreateColorBuffer(uint32_t width, uint32_t height, GLenum internalFormat) { if (!renderer) return 0; return renderer->createColorBuffer(width, height, internalFormat); } static int rcOpenColorBuffer2(uint32_t colorbuffer) { if (!renderer) return -1; return renderer->openColorBuffer(colorbuffer); } // Deprecated, kept for compatibility with old system images only. // Use rcOpenColorBuffer2 instead. static void rcOpenColorBuffer(uint32_t colorbuffer) { (void)rcOpenColorBuffer2(colorbuffer); } static void rcCloseColorBuffer(uint32_t colorbuffer) { if (!renderer) return; renderer->closeColorBuffer(colorbuffer); } static int rcFlushWindowColorBuffer(uint32_t windowSurface) { if (!renderer) return -1; if (!renderer->flushWindowSurfaceColorBuffer(windowSurface)) return -1; return 0; } static void rcSetWindowColorBuffer(uint32_t windowSurface, uint32_t colorBuffer) { if (!renderer) return; renderer->setWindowSurfaceColorBuffer(windowSurface, colorBuffer); } static EGLint rcMakeCurrent(uint32_t context, uint32_t drawSurf, uint32_t readSurf) { if (!renderer) return EGL_FALSE; bool ret = renderer->bindContext(context, drawSurf, readSurf); return (ret ? EGL_TRUE : EGL_FALSE); } static void rcFBPost(uint32_t) { WARNING("Not implemented"); } static void rcFBSetSwapInterval(EGLint) { // XXX: TBD - should be implemented } static void rcBindTexture(uint32_t colorBuffer) { if (!renderer) return; renderer->bindColorBufferToTexture(colorBuffer); } static void rcBindRenderbuffer(uint32_t colorBuffer) { if (!renderer) return; renderer->bindColorBufferToRenderbuffer(colorBuffer); } static EGLint rcColorBufferCacheFlush(uint32_t, EGLint, int) { // XXX: TBD - should be implemented return 0; } static void rcReadColorBuffer(uint32_t colorBuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void *pixels) { if (!renderer) return; renderer->readColorBuffer(colorBuffer, x, y, width, height, format, type, pixels); } static int rcUpdateColorBuffer(uint32_t colorBuffer, GLint x, GLint y, GLint width, GLint height, GLenum format, GLenum type, void *pixels) { if (!renderer) return -1; renderer->updateColorBuffer(colorBuffer, x, y, width, height, format, type, pixels); return 0; } static uint32_t rcCreateClientImage(uint32_t context, EGLenum target, GLuint buffer) { if (!renderer) return 0; return renderer->createClientImage(context, target, buffer); } static int rcDestroyClientImage(uint32_t image) { if (!renderer) return 0; return renderer->destroyClientImage(image); } static void rcSelectChecksumCalculator(uint32_t protocol, uint32_t) { ChecksumCalculatorThreadInfo::setVersion(protocol); } int rcGetNumDisplays() { // For now we only support a single display but that single display // will contain more than one display so that we simply spawn up a big // virtual display which should match the real display arrangement // in most cases. return 1; } int rcGetDisplayWidth(uint32_t display_id) { (void)display_id; return static_cast<int>(anbox::graphics::emugl::DisplayInfo::get()->vertical_resolution()); } int rcGetDisplayHeight(uint32_t display_id) { (void)display_id; return static_cast<int>(anbox::graphics::emugl::DisplayInfo::get()->horizontal_resolution()); } int rcGetDisplayDpiX(uint32_t display_id) { (void)display_id; return 120; } int rcGetDisplayDpiY(uint32_t display_id) { (void)display_id; return 120; } int rcGetDisplayVsyncPeriod(uint32_t display_id) { (void)display_id; return 1; } static std::vector<Renderable> frame_layers; bool is_layer_blacklisted(const std::string &name) { static std::vector<std::string> blacklist = { // The 'Sprite' layer is the mouse cursor Android uses as soon // as it has a pointer input device available. We don't want to // display this layer at all but don't have a good way of disabling // the cursor on the Android side yet. "Sprite", }; return std::find(blacklist.begin(), blacklist.end(), name) != blacklist.end(); } void rcPostLayer(const char *name, uint32_t color_buffer, float alpha, int32_t sourceCropLeft, int32_t sourceCropTop, int32_t sourceCropRight, int32_t sourceCropBottom, int32_t displayFrameLeft, int32_t displayFrameTop, int32_t displayFrameRight, int32_t displayFrameBottom) { Renderable r{ name, color_buffer, alpha, {displayFrameLeft, displayFrameTop, displayFrameRight, displayFrameBottom}, {sourceCropLeft, sourceCropTop, sourceCropRight, sourceCropBottom}}; frame_layers.push_back(r); } void rcPostAllLayersDone() { if (composer) composer->submit_layers(frame_layers); frame_layers.clear(); } void initRenderControlContext(renderControl_decoder_context_t *dec) { dec->rcGetRendererVersion = rcGetRendererVersion; dec->rcGetEGLVersion = rcGetEGLVersion; dec->rcQueryEGLString = rcQueryEGLString; dec->rcGetGLString = rcGetGLString; dec->rcGetNumConfigs = rcGetNumConfigs; dec->rcGetConfigs = rcGetConfigs; dec->rcChooseConfig = rcChooseConfig; dec->rcGetFBParam = rcGetFBParam; dec->rcCreateContext = rcCreateContext; dec->rcDestroyContext = rcDestroyContext; dec->rcCreateWindowSurface = rcCreateWindowSurface; dec->rcDestroyWindowSurface = rcDestroyWindowSurface; dec->rcCreateColorBuffer = rcCreateColorBuffer; dec->rcOpenColorBuffer = rcOpenColorBuffer; dec->rcCloseColorBuffer = rcCloseColorBuffer; dec->rcSetWindowColorBuffer = rcSetWindowColorBuffer; dec->rcFlushWindowColorBuffer = rcFlushWindowColorBuffer; dec->rcMakeCurrent = rcMakeCurrent; dec->rcFBPost = rcFBPost; dec->rcFBSetSwapInterval = rcFBSetSwapInterval; dec->rcBindTexture = rcBindTexture; dec->rcBindRenderbuffer = rcBindRenderbuffer; dec->rcColorBufferCacheFlush = rcColorBufferCacheFlush; dec->rcReadColorBuffer = rcReadColorBuffer; dec->rcUpdateColorBuffer = rcUpdateColorBuffer; dec->rcOpenColorBuffer2 = rcOpenColorBuffer2; dec->rcCreateClientImage = rcCreateClientImage; dec->rcDestroyClientImage = rcDestroyClientImage; dec->rcSelectChecksumCalculator = rcSelectChecksumCalculator; dec->rcGetNumDisplays = rcGetNumDisplays; dec->rcGetDisplayWidth = rcGetDisplayWidth; dec->rcGetDisplayHeight = rcGetDisplayHeight; dec->rcGetDisplayDpiX = rcGetDisplayDpiX; dec->rcGetDisplayDpiY = rcGetDisplayDpiY; dec->rcGetDisplayVsyncPeriod = rcGetDisplayVsyncPeriod; dec->rcPostLayer = rcPostLayer; dec->rcPostAllLayersDone = rcPostAllLayersDone; }
14,517
C++
.cpp
389
32.691517
112
0.719342
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,600
TimeUtils.cpp
anbox_anbox/src/anbox/graphics/emugl/TimeUtils.cpp
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "anbox/graphics/emugl/TimeUtils.h" #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <unistd.h> long long GetCurrentTimeMS() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); long long iDiff = (now.tv_sec * 1000LL) + now.tv_nsec / 1000000LL; return iDiff; } void TimeSleepMS(int p_mili) { usleep(p_mili * 1000); }
966
C++
.cpp
27
34.333333
74
0.760428
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,601
DisplayManager.cpp
anbox_anbox/src/anbox/graphics/emugl/DisplayManager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "DisplayManager.h" namespace anbox::graphics::emugl { std::shared_ptr<DisplayInfo> DisplayInfo::get() { static auto info = std::make_shared<DisplayInfo>(); return info; } void DisplayInfo::set_resolution(const std::uint32_t &vertical, const std::uint32_t horizontal) { vertical_resolution_ = vertical; horizontal_resolution_ = horizontal; } std::uint32_t DisplayInfo::vertical_resolution() const { return vertical_resolution_; } std::uint32_t DisplayInfo::horizontal_resolution() const { return horizontal_resolution_; } }
1,218
C++
.cpp
29
40.068966
97
0.763713
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,602
Renderable.cpp
anbox_anbox/src/anbox/graphics/emugl/Renderable.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "anbox/graphics/emugl/Renderable.h" Renderable::Renderable(const std::string &name, const std::uint32_t &buffer, float alpha, const anbox::graphics::Rect &screen_position, const anbox::graphics::Rect &crop, const glm::mat4 &transformation) : name_(name), buffer_(buffer), screen_position_(screen_position), crop_(crop), transformation_(transformation), alpha_(alpha) {} Renderable::~Renderable() {} std::string Renderable::name() const { return name_; } std::uint32_t Renderable::buffer() const { return buffer_; } anbox::graphics::Rect Renderable::screen_position() const { return screen_position_; } anbox::graphics::Rect Renderable::crop() const { return crop_; } glm::mat4 Renderable::transformation() const { return transformation_; } float Renderable::alpha() const { return alpha_; } void Renderable::set_screen_position( const anbox::graphics::Rect &screen_position) { screen_position_ = screen_position; } std::ostream &operator<<(std::ostream &out, const Renderable &r) { return out << "{ name " << r.name() << " buffer " << r.buffer() << " screen position " << r.screen_position() << " crop " << r.crop() << " alpha " << r.alpha(); }
1,905
C++
.cpp
44
38.886364
89
0.685946
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,606
ReadBuffer.cpp
anbox_anbox/src/anbox/graphics/emugl/ReadBuffer.cpp
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "anbox/graphics/emugl/ReadBuffer.h" #include "anbox/logger.h" #include <assert.h> #include <limits.h> #include <string.h> ReadBuffer::ReadBuffer(size_t bufsize) { m_size = bufsize; m_buf = static_cast<unsigned char*>(malloc(m_size * sizeof(unsigned char))); m_validData = 0; m_readPtr = m_buf; } ReadBuffer::~ReadBuffer() { free(m_buf); } int ReadBuffer::getData(IOStream* stream) { if (stream == NULL) return -1; if ((m_validData > 0) && (m_readPtr > m_buf)) { memmove(m_buf, m_readPtr, m_validData); } // get fresh data into the buffer; size_t len = m_size - m_validData; if (len == 0) { // we need to inc our buffer size_t new_size = m_size * 2; unsigned char* new_buf; if (new_size < m_size) { // overflow check new_size = INT_MAX; } new_buf = static_cast<unsigned char*>(realloc(m_buf, new_size)); if (!new_buf) { ERROR("Failed to alloc %zu bytes for ReadBuffer", new_size); return -1; } m_size = new_size; m_buf = new_buf; len = m_size - m_validData; } m_readPtr = m_buf; if (NULL != stream->read(m_buf + m_validData, &len)) { m_validData += len; return len; } return -1; } void ReadBuffer::consume(size_t amount) { assert(amount <= m_validData); m_validData -= amount; m_readPtr += amount; }
1,927
C++
.cpp
62
28.193548
78
0.68084
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,613
multi_window_manager.cpp
anbox_anbox/src/anbox/wm/multi_window_manager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/application/database.h" #include "anbox/wm/multi_window_manager.h" #include "anbox/platform/base_platform.h" #include "anbox/bridge/android_api_stub.h" #include "anbox/logger.h" #include <algorithm> namespace anbox::wm { MultiWindowManager::MultiWindowManager(const std::weak_ptr<platform::BasePlatform> &platform, const std::shared_ptr<bridge::AndroidApiStub> &android_api_stub, const std::shared_ptr<application::Database> &app_db) : platform_(platform), android_api_stub_(android_api_stub), app_db_(app_db) {} MultiWindowManager::~MultiWindowManager() {} void MultiWindowManager::apply_window_state_update(const WindowState::List &updated, const WindowState::List &removed) { std::lock_guard<std::mutex> l(mutex_); // Base on the update we get from the Android WindowManagerService we will // create different window instances with the properties supplied. Incoming // layer updates from SurfaceFlinger will be mapped later into those windows // and eventually composited there via GLES (e.g. for popups, ..) std::map<Task::Id, WindowState::List> task_updates; for (const auto &window : updated) { // Ignore all windows which are not part of the freeform task stack if (window.stack() != Stack::Id::Freeform) continue; // And also those which don't have a surface mapped at the moment if (!window.has_surface()) continue; // If we know that task already we first collect all window updates // for it so we can apply all of them together. auto w = windows_.find(window.task()); if (w != windows_.end()) { auto t = task_updates.find(window.task()); if (t == task_updates.end()) task_updates.insert({window.task(), {window}}); else task_updates[window.task()].push_back(window); continue; } auto title = window.package_name(); auto app = app_db_->find_by_package(window.package_name()); if (app.valid()) title = app.name; if (auto p = platform_.lock()) { auto w = p->create_window(window.task(), window.frame(), title); if (w) { w->attach(); windows_.insert({window.task(), w}); } else { // FIXME can we call this here safely or do we need to schedule the removal? remove_task(window.task()); } } } // Send updates we collected per task down to the corresponding window // so that they can update themself. for (const auto &u : task_updates) { auto w = windows_.find(u.first); if (w == windows_.end()) continue; w->second->update_state(u.second); } // As final step we process all windows we need to remove as they // got killed on the other side. We need to respect here that we // also get removals for windows which are part of a task which is // still in use by other windows. for (const auto &window : removed) { auto w = windows_.find(window.task()); if (w == windows_.end()) continue; if (task_updates.find(window.task()) == task_updates.end()) { auto platform_window = w->second; platform_window->release(); windows_.erase(w); } } } std::shared_ptr<Window> MultiWindowManager::find_window_for_task(const Task::Id &task) { std::lock_guard<std::mutex> l(mutex_); for (const auto &w : windows_) { if (w.second->task() == task) return w.second; } return nullptr; } void MultiWindowManager::resize_task(const Task::Id &task, const anbox::graphics::Rect &rect, const std::int32_t &resize_mode) { android_api_stub_->resize_task(task, rect, resize_mode); } void MultiWindowManager::set_focused_task(const Task::Id &task) { android_api_stub_->set_focused_task(task); } void MultiWindowManager::remove_task(const Task::Id &task) { android_api_stub_->remove_task(task); } }
4,598
C++
.cpp
106
38.113208
103
0.675833
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,614
task.cpp
anbox_anbox/src/anbox/wm/task.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/wm/task.h" namespace anbox::wm { Task::Id Task::Invalid = -1; }
755
C++
.cpp
20
35.95
76
0.752044
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,616
display.cpp
anbox_anbox/src/anbox/wm/display.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/wm/display.h" namespace anbox::wm { Display::Id Display::Invalid = -1; Display::Id Display::Default = 0; }
798
C++
.cpp
21
36.238095
76
0.753866
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,617
window_state.cpp
anbox_anbox/src/anbox/wm/window_state.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/wm/window_state.h" namespace anbox::wm { WindowState::WindowState() : display_(Display::Invalid), has_surface_(false), frame_(graphics::Rect::Invalid), package_name_(""), task_(Task::Invalid), stack_(Stack::Id::Invalid) {} WindowState::WindowState(const Display::Id &display, bool has_surface, const graphics::Rect &frame, const std::string &package_name, const Task::Id &task, const Stack::Id &stack) : display_(display), has_surface_(has_surface), frame_(frame), package_name_(package_name), task_(task), stack_(stack) {} WindowState::~WindowState() {} }
1,393
C++
.cpp
37
32.297297
79
0.672579
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,618
manager.cpp
anbox_anbox/src/anbox/wm/manager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/wm/manager.h" namespace anbox::wm { Manager::~Manager() {} }
752
C++
.cpp
20
35.8
76
0.753762
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,621
environment_file.cpp
anbox_anbox/src/anbox/utils/environment_file.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/utils/environment_file.h" #include "anbox/utils.h" #include <fstream> namespace anbox::utils { EnvironmentFile::EnvironmentFile(const boost::filesystem::path &path) { std::ifstream in(path.string()); std::string line; while (std::getline(in, line)) { auto tokens = utils::string_split(line, '='); if (tokens.size() != 2) continue; data_[tokens[0]] = utils::strip_surrounding_quotes(tokens[1]); } } std::string EnvironmentFile::value(const std::string &key, const std::string &default_value) const { auto iter = data_.find(key); if (iter == data_.end()) return default_value; return iter->second; } }
1,325
C++
.cpp
37
33.351351
100
0.726848
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,622
intent.cpp
anbox_anbox/src/anbox/android/intent.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/android/intent.h" #include <ostream> namespace anbox::android { bool Intent::valid() const { // At the moment we only support component+package for intents // (see android/service/android_api_skeleton.cpp for more details) return !(component.empty() && package.empty()); } std::ostream &operator<<(std::ostream &out, const Intent &intent) { out << "["; if (!intent.action.empty()) out << " " << "action=" << intent.action << " "; if (!intent.uri.empty()) out << " " << "uri=" << intent.uri << " "; if (!intent.type.empty()) out << " " << "type=" << intent.type << " "; if (intent.flags > 0) out << " " << "flags=" << intent.flags << " "; if (!intent.package.empty()) out << " " << "package=" << intent.package << " "; if (!intent.component.empty()) out << "component=" << intent.component << " "; if (intent.categories.size() > 0) { out << "categories=[ "; for (const auto &category : intent.categories) out << category << " "; out << "] "; } out << "]"; return out; } }
1,730
C++
.cpp
47
34.06383
76
0.650595
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,623
ip_config_builder.cpp
anbox_anbox/src/anbox/android/ip_config_builder.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/android/ip_config_builder.h" #include <boost/endian/buffers.hpp> #include <ostream> #include <sstream> namespace { constexpr const char *assignment_key{"ipAssignment"}; constexpr const char *link_address_key{"linkAddress"}; constexpr const char *gateway_key{"gateway"}; constexpr const char *dns_key{"dns"}; constexpr const char *id_key{"id"}; constexpr const char *eos_key{"eos"}; constexpr const char *assignment_static{"STATIC"}; constexpr const char *assignment_dhcp{"DHCP"}; constexpr const char *assignment_unknown{"UNKNOWN"}; constexpr const std::uint32_t is_default_gateway{0}; constexpr const std::uint32_t gateway_is_present{1}; namespace aa = anbox::android; std::string assignment_to_string(const aa::IpConfigBuilder::Assignment &value) { switch (value) { case anbox::android::IpConfigBuilder::Assignment::Static: return assignment_static; break; case anbox::android::IpConfigBuilder::Assignment::DHCP: return assignment_dhcp; break; default: break; } return assignment_unknown; } } namespace anbox::android { std::size_t IpConfigBuilder::write(common::BinaryWriter &writer) { writer.set_byte_order(common::BinaryWriter::Order::Big); // See http://androidxref.com/7.1.1_r6/xref/frameworks/base/services/core/java/com/android/server/net/IpConfigStore.java // for more details on the binary file format used here. writer.write_uint32(static_cast<std::uint32_t>(version_)); writer.write_string_with_size(assignment_key); writer.write_string_with_size(assignment_to_string(assignment_)); writer.write_string_with_size(link_address_key); writer.write_string_with_size(link_.address); writer.write_uint32(link_.prefix_length); writer.write_string_with_size(gateway_key); writer.write_uint32(is_default_gateway); writer.write_uint32(gateway_is_present); writer.write_string_with_size(gateway_); writer.write_string_with_size(dns_key); for (const auto &server : dns_servers_) writer.write_string_with_size(server); writer.write_string_with_size(id_key); writer.write_uint32(id_); writer.write_string_with_size(eos_key); return writer.bytes_written(); } void IpConfigBuilder::set_version(const Version &version) { version_ = version; } void IpConfigBuilder::set_assignment(const Assignment &assignment) { assignment_ = assignment; } void IpConfigBuilder::set_link_address(const std::string &address, uint32_t prefix_length) { link_.address = address; link_.prefix_length = prefix_length; } void IpConfigBuilder::set_gateway(const std::string &gateway) { gateway_ = gateway; } void IpConfigBuilder::set_dns_servers(const std::vector<std::string> &dns_servers) { dns_servers_ = dns_servers; } void IpConfigBuilder::set_id(uint32_t id) { id_ = id; } }
3,451
C++
.cpp
90
35.966667
122
0.762275
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,624
splash_screen.cpp
anbox_anbox/src/anbox/ui/splash_screen.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/ui/splash_screen.h" #include "anbox/system_configuration.h" #include "anbox/utils.h" #include "anbox/logger.h" #include <SDL2/SDL_image.h> namespace anbox::ui { SplashScreen::SplashScreen() { #ifdef SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR // Don't disable compositing // Available since SDL 2.0.8 SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0"); #endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) { const auto message = utils::string_format("Failed to initialize SDL: %s", SDL_GetError()); BOOST_THROW_EXCEPTION(std::runtime_error(message)); } const auto width = 1024, height = 768; window_ = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS); if (!window_) { const auto message = utils::string_format("Failed to create window: %s", SDL_GetError()); BOOST_THROW_EXCEPTION(std::runtime_error(message)); } auto surface = SDL_GetWindowSurface(window_); if (!surface) BOOST_THROW_EXCEPTION(std::runtime_error("Could not retrieve surface for our window")); SDL_FillRect(surface, nullptr, SDL_MapRGB(surface->format, 0xee, 0xee, 0xee)); SDL_UpdateWindowSurface(window_); auto renderer = SDL_GetRenderer(window_); if (!renderer) { DEBUG("Window has no associated renderer yet, creating one ..."); renderer = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { const auto msg = utils::string_format("Could not create renderer: %s", SDL_GetError()); BOOST_THROW_EXCEPTION(std::runtime_error(msg)); } } const auto icon_path = utils::string_format("%s/ui/loading-screen.png", SystemConfiguration::instance().resource_dir()); auto img = IMG_LoadTexture(renderer, icon_path.c_str()); if (!img) { const auto msg = utils::string_format("Failed to create texture from %s", icon_path); BOOST_THROW_EXCEPTION(std::runtime_error(msg)); } SDL_RenderClear(renderer); SDL_Rect r{0, 0, width, height}; SDL_RenderCopy(renderer, img, nullptr, &r); SDL_RenderPresent(renderer); SDL_ShowWindow(window_); event_thread_ = std::thread(&SplashScreen::process_events, this); } SplashScreen::~SplashScreen() { if (event_thread_running_) { event_thread_running_ = false; if (event_thread_.joinable()) event_thread_.join(); } if (window_) SDL_DestroyWindow(window_); } void SplashScreen::process_events() { event_thread_running_ = true; while (event_thread_running_) { SDL_Event event; while (SDL_WaitEventTimeout(&event, 100)) { // Keep running until we're terminated } } } }
3,361
C++
.cpp
85
36.011765
122
0.712052
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,625
binder_device.cpp
anbox_anbox/src/anbox/common/binder_device.cpp
/* * Copyright (C) 2018 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/binder_device.h" #include "anbox/common/binderfs.h" #include "anbox/defer_action.h" #include "anbox/logger.h" #include "anbox/utils.h" #include <system_error> #include <cerrno> #include <fcntl.h> #include <linux/loop.h> #include <sys/ioctl.h> #include <sys/stat.h> namespace anbox::common { std::unique_ptr<BinderDevice> BinderDevice::create(const std::string& path) { return std::unique_ptr<BinderDevice>(new BinderDevice(path)); } BinderDevice::BinderDevice(const std::string& path) : path_{path} { if (::chmod(path.c_str(), 0666) < 0) ERROR("Failed to change permissions of binder node %s: %s", path, std::strerror(errno)); } BinderDevice::~BinderDevice() { if (::unlink(path_.c_str()) < 0) ERROR("Failed to remove binder node %s: %s", path_, std::strerror(errno)); } }
1,476
C++
.cpp
41
34.073171
92
0.735664
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,626
message_channel.cpp
anbox_anbox/src/anbox/common/message_channel.cpp
// Copyright 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "anbox/common/message_channel.h" namespace anbox::common { MessageChannelBase::MessageChannelBase(size_t capacity) : pos_(0U), count_(0U), capacity_(capacity), lock_(), can_read_(), can_write_() {} MessageChannelBase::~MessageChannelBase() {} size_t MessageChannelBase::before_write() { std::unique_lock<std::mutex> l(lock_, std::defer_lock); lock_.lock(); while (count_ >= capacity_) can_write_.wait(l); size_t result = pos_ + count_; if (result >= capacity_) result -= capacity_; return result; } void MessageChannelBase::after_write() { count_++; can_read_.notify_one(); lock_.unlock(); } size_t MessageChannelBase::before_read() { std::unique_lock<std::mutex> l(lock_, std::defer_lock); lock_.lock(); while (count_ == 0) can_read_.wait(l); return pos_; } void MessageChannelBase::after_read() { if (++pos_ == capacity_) pos_ = 0U; count_--; can_write_.notify_one(); lock_.unlock(); } }
1,852
C++
.cpp
52
27.903846
78
0.596315
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,628
mount_entry.cpp
anbox_anbox/src/anbox/common/mount_entry.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/mount_entry.h" #include "anbox/common/loop_device.h" #include "anbox/logger.h" #include <sys/mount.h> namespace anbox::common { std::shared_ptr<MountEntry> MountEntry::create(const boost::filesystem::path &src, const boost::filesystem::path &target, const std::string &fs_type, unsigned long flags, const std::string &data) { auto entry = std::shared_ptr<MountEntry>(new MountEntry(target)); if (!entry) return nullptr; const void *mount_data = nullptr; if (!data.empty()) mount_data = reinterpret_cast<const void*>(data.c_str()); DEBUG("Mounting %s on %s ...", src, target); if (::mount(src.c_str(), target.c_str(), !fs_type.empty() ? fs_type.c_str() : nullptr, flags, mount_data) < 0) { ERROR("Failed to mount %s: %s", target, strerror(errno)); return nullptr; } entry->active_ = true; return entry; } std::shared_ptr<MountEntry> MountEntry::create(const std::shared_ptr<LoopDevice> &loop, const boost::filesystem::path &target, const std::string &fs_type, unsigned long flags, const std::string &data) { auto entry = create(loop->path(), target, fs_type, flags, data); if (!entry) return nullptr; entry->loop_ = loop; return entry; } std::shared_ptr<MountEntry> MountEntry::create(const boost::filesystem::path &target) { auto entry = std::shared_ptr<MountEntry>(new MountEntry(target)); if (!entry) return nullptr; entry->active_ = true; return entry; } MountEntry::MountEntry(const boost::filesystem::path &target) : active_{false}, target_{target} {} MountEntry::~MountEntry() { if (!active_) return; ::umount(target_.c_str()); } }
2,412
C++
.cpp
60
36
126
0.68849
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,629
loop_device_allocator.cpp
anbox_anbox/src/anbox/common/loop_device_allocator.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/loop_device_allocator.h" #include "anbox/common/loop_device.h" #include "anbox/defer_action.h" #include "anbox/utils.h" #include <boost/filesystem.hpp> #include <linux/loop.h> #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <system_error> namespace fs = boost::filesystem; namespace { const constexpr char *loop_control_path{"/dev/loop-control"}; const constexpr char *base_loop_path{"/dev/loop"}; } namespace anbox::common { std::shared_ptr<LoopDevice> LoopDeviceAllocator::new_device() { const auto ctl_fd = ::open(loop_control_path, O_RDWR); if (ctl_fd < 0) throw std::system_error{errno, std::system_category()}; DeferAction close_ctl_fd{[&]() { ::close(ctl_fd); }}; const auto device_nr = ::ioctl(ctl_fd, LOOP_CTL_GET_FREE); if (device_nr < 0) throw std::system_error{errno, std::system_category()}; return LoopDevice::create(utils::string_format("%s%d", base_loop_path, device_nr)); } }
1,641
C++
.cpp
43
36.139535
85
0.736941
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,630
binder_device_allocator.cpp
anbox_anbox/src/anbox/common/binder_device_allocator.cpp
/* * Copyright (C) 2018 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/binder_device_allocator.h" #include "anbox/common/binder_device.h" #include "anbox/common/binderfs.h" #include "anbox/defer_action.h" #include "anbox/logger.h" #include "anbox/utils.h" #include <boost/filesystem.hpp> #include <cerrno> #include <fcntl.h> #include <linux/loop.h> #include <sys/ioctl.h> #include <system_error> namespace fs = boost::filesystem; namespace { const constexpr char* binderfs_base_path{BINDERFS_PATH}; const constexpr char* binderfs_control_path{BINDERFS_PATH "/binder-control"}; const constexpr char* default_binder_device_name{"binder"}; } // namespace namespace anbox::common { bool BinderDeviceAllocator::is_supported() { return fs::exists(binderfs_control_path); } std::unique_ptr<BinderDevice> BinderDeviceAllocator::new_device() { static uint32_t next_id = 0; const auto ctl_fd = ::open(binderfs_control_path, O_RDWR); if (ctl_fd < 0) { ERROR("Failed to access binder control: %s", std::strerror(errno)); return nullptr; } DeferAction close_ctl_fd{[&]() { ::close(ctl_fd); }}; binderfs_device dev; std::memset(&dev, 0, sizeof(binderfs_device)); const auto device_name = utils::string_format("%s%d", default_binder_device_name, next_id++); if (device_name.length() > BINDERFS_MAX_NAME) { ERROR("Invalid binder device name: %s", device_name); return nullptr; } std::memcpy(dev.name, device_name.c_str(), device_name.length()); if (::ioctl(ctl_fd, BINDER_CTL_ADD, &dev) < 0) { ERROR("Failed to allocate new binder node: %s", std::strerror(errno)); return nullptr; } const auto path = utils::string_format("%s/%s", binderfs_base_path, device_name); if (!fs::exists(path)) { ERROR("Allocated binder device %s is missing", path); return nullptr; } return BinderDevice::create(path); } }
2,479
C++
.cpp
66
35.075758
95
0.72769
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,632
dispatcher.cpp
anbox_anbox/src/anbox/common/dispatcher.cpp
/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> * */ #include "anbox/common/dispatcher.h" namespace { struct AsioStrandDispatcher : public anbox::common::Dispatcher { public: AsioStrandDispatcher(const std::shared_ptr<anbox::Runtime>& rt) : rt{rt}, strand{rt->service()} {} void dispatch(const Task& task) override { strand.post(task); } private: std::shared_ptr<anbox::Runtime> rt; boost::asio::io_service::strand strand; }; } std::shared_ptr<anbox::common::Dispatcher> anbox::common::create_dispatcher_for_runtime( const std::shared_ptr<anbox::Runtime>& rt) { return std::make_shared<AsioStrandDispatcher>(rt); }
1,302
C++
.cpp
35
34.942857
78
0.747227
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,633
binary_writer.cpp
anbox_anbox/src/anbox/common/binary_writer.cpp
/* * Copyright (C) 2016 Thomas Voss <thomas.voss.bochum@gmail.com> * Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/binary_writer.h" #include <cstring> #include <stdexcept> #include <boost/endian/buffers.hpp> #include <boost/endian/conversion.hpp> namespace { bool is_little_endian() { static const std::uint32_t v = 1; return (*reinterpret_cast<const std::uint8_t*>(&v) == 1); } } namespace anbox::common { BinaryWriter::BinaryWriter(std::vector<std::uint8_t>::iterator begin, std::vector<std::uint8_t>::iterator end) : begin_{begin}, current_{begin}, end_{end}, byte_order_{is_little_endian() ? Order::Little : Order::Big} {} void BinaryWriter::set_byte_order(Order order) { byte_order_ = order; } void BinaryWriter::write_uint16(std::uint16_t value) { if (current_ + sizeof(value) > end_) throw std::out_of_range{"Write buffer exhausted"}; std::uint16_t v = value; switch (byte_order_) { case Order::Big: v = boost::endian::native_to_big(value); break; case Order::Little: v = boost::endian::native_to_little(value); break; default: break; } memcpy(&(*current_), &v, sizeof(std::uint16_t)); current_ += sizeof(v); } void BinaryWriter::write_uint32(std::uint32_t value) { if (current_ + sizeof(value) > end_) throw std::out_of_range{"Write buffer exhausted"}; std::uint32_t v = value; switch (byte_order_) { case Order::Big: v = boost::endian::native_to_big(value); break; case Order::Little: v = boost::endian::native_to_little(value); break; default: break; } memcpy(&(*current_), &v, sizeof(std::uint32_t)); current_ += sizeof(v); } void BinaryWriter::write_string(const char *s, std::size_t size) { if (current_ + size > end_) throw std::out_of_range{"Write buffer exhausted"}; memcpy(&(*current_), s, size); current_ += size; } void BinaryWriter::write_string_with_size(const std::string &str) { write_string_with_size(str.c_str(), str.length()); } void BinaryWriter::write_string_with_size(const char *s, std::size_t size) { write_uint16(size); write_string(s, size); } std::size_t BinaryWriter::bytes_written() const { return current_ - begin_; } }
2,860
C++
.cpp
87
29.908046
76
0.689155
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,634
loop_device.cpp
anbox_anbox/src/anbox/common/loop_device.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/common/loop_device.h" #include "anbox/defer_action.h" #include <system_error> #include <linux/loop.h> #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> namespace anbox::common { std::shared_ptr<LoopDevice> LoopDevice::create(const boost::filesystem::path &path) { const auto fd = ::open(path.c_str(), O_RDWR); if (fd < 0) throw std::system_error{errno, std::system_category()}; return std::shared_ptr<LoopDevice>(new LoopDevice(Fd{fd}, path)); } LoopDevice::LoopDevice(Fd fd, const boost::filesystem::path &path) : fd_{fd}, path_{path} {} LoopDevice::~LoopDevice() { if (fd_ < 0) return; ::ioctl(fd_, LOOP_CLR_FD); ::close(fd_); } bool LoopDevice::attach_file(const boost::filesystem::path &file_path) { if (fd_ < 0) return false; int file_fd = ::open(file_path.c_str(), O_RDONLY); if (file_fd < 0) return false; DeferAction close_file_fd{[&]() { ::close(file_fd); }}; if (::ioctl(fd_, LOOP_SET_FD, file_fd) < 0) return false; return true; } }
1,703
C++
.cpp
50
31.6
85
0.706277
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,635
container_manager.cpp
anbox_anbox/src/anbox/cmds/container_manager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/cmds/container_manager.h" #include "anbox/container/service.h" #include "anbox/common/loop_device_allocator.h" #include "anbox/logger.h" #include "anbox/runtime.h" #include "anbox/system_configuration.h" #include "core/posix/signal.h" #include "core/posix/exec.h" #include <sys/mount.h> #include <linux/loop.h> #include <fcntl.h> namespace fs = boost::filesystem; namespace { constexpr unsigned int unprivileged_user_id{100000}; } anbox::cmds::ContainerManager::ContainerManager() : CommandWithFlagsAndAction{ cli::Name{"container-manager"}, cli::Usage{"container-manager"}, cli::Description{"Start the container manager service"}, true} { flag(cli::make_flag(cli::Name{"android-image"}, cli::Description{"Path to the Android rootfs image file if not stored in the data path"}, android_img_path_)); flag(cli::make_flag(cli::Name{"data-path"}, cli::Description{"Path where the container and its data is stored"}, data_path_)); flag(cli::make_flag(cli::Name{"privileged"}, cli::Description{"Run Android container in privileged mode"}, privileged_)); flag(cli::make_flag(cli::Name{"daemon"}, cli::Description{"Mark service as being started as systemd daemon"}, daemon_)); flag(cli::make_flag(cli::Name{"use-rootfs-overlay"}, cli::Description{"Use an overlay for the Android rootfs"}, enable_rootfs_overlay_)); flag(cli::make_flag(cli::Name{"force-squashfuse"}, cli::Description{"Force using squashfuse for mounting the Android rootfs"}, enable_squashfuse_)); flag(cli::make_flag(cli::Name{"container-network-address"}, cli::Description{"Assign the specified network address to the Android container"}, container_network_address_)); flag(cli::make_flag(cli::Name{"container-network-gateway"}, cli::Description{"Assign the specified network gateway to the Android container"}, container_network_gateway_)); flag(cli::make_flag(cli::Name{"container-network-dns-servers"}, cli::Description{"Assign the specified DNS servers to the Android container"}, container_network_dns_servers_)); action([&](const cli::Command::Context&) { try { if (!daemon_) { WARNING("You are running the container manager manually which is most likely not"); WARNING("what you want. The container manager is normally started by systemd or"); WARNING("another init system. If you still want to run the container-manager"); WARNING("you can get rid of this warning by starting with the --daemon option."); WARNING(""); } if (geteuid() != 0) { ERROR("You are not running the container-manager as root. Generally you don't"); ERROR("want to run the container-manager manually unless you're a developer"); ERROR("as it is started by the init system of your operating system."); return EXIT_FAILURE; } auto trap = core::posix::trap_signals_for_process( {core::posix::Signal::sig_term, core::posix::Signal::sig_int}); trap->signal_raised().connect([trap](const core::posix::Signal& signal) { INFO("Signal %i received. Good night.", static_cast<int>(signal)); trap->stop(); }); if (!data_path_.empty()) SystemConfiguration::instance().set_data_path(data_path_); if (!fs::exists(data_path_)) fs::create_directories(data_path_); if (!setup_mounts()) return EXIT_FAILURE; auto rt = Runtime::create(); container::Service::Configuration config; config.privileged = privileged_; config.rootfs_overlay = enable_rootfs_overlay_; config.container_network_address = container_network_address_; config.container_network_gateway = container_network_gateway_; if (container_network_dns_servers_.length() > 0) config.container_network_dns_servers = utils::string_split(container_network_dns_servers_, ','); auto service = container::Service::create(rt, config); rt->start(); trap->run(); rt->stop(); return EXIT_SUCCESS; } catch (std::exception &err) { ERROR("%s", err.what()); return EXIT_FAILURE; } }); } anbox::cmds::ContainerManager::~ContainerManager() {} bool anbox::cmds::ContainerManager::setup_mounts() { fs::path android_img_path = android_img_path_; if (android_img_path.empty()) android_img_path = SystemConfiguration::instance().data_dir() / "android.img"; if (!fs::exists(android_img_path)) { ERROR("Android image does not exist at path %s", android_img_path); return false; } const auto android_rootfs_dir = SystemConfiguration::instance().rootfs_dir(); if (utils::is_mounted(android_rootfs_dir)) { ERROR("Androd rootfs is already mounted!?"); return false; } if (!fs::exists(android_rootfs_dir)) fs::create_directory(android_rootfs_dir); // We prefer using the kernel for mounting the squashfs image but // for some cases (unprivileged containers) where no loop support // is available we do the mount instead via squashfuse which will // work entirely in userspace. if (!fs::exists("/dev/loop-control") && !enable_squashfuse_) { WARNING("/dev/loop-control not found. Falling back to squashfuse."); enable_squashfuse_ = true; } if (!enable_squashfuse_) { std::shared_ptr<common::LoopDevice> loop_device; try { loop_device = common::LoopDeviceAllocator::new_device(); } catch (const std::exception& e) { ERROR("Could not create loopback device: %s", e.what()); return false; } catch (...) { ERROR("Could not create loopback device"); return false; } if (!loop_device->attach_file(android_img_path)) { ERROR("Failed to attach Android rootfs image to loopback device"); return false; } auto m = common::MountEntry::create(loop_device, android_rootfs_dir, "squashfs", MS_MGC_VAL | MS_RDONLY | MS_PRIVATE); if (!m) { ERROR("Failed to mount Android rootfs"); return false; } mounts_.push_back(m); } else if (fs::exists("/dev/fuse") && !utils::find_program_on_path("squashfuse").empty()) { std::vector<std::string> args = { "-t", "fuse.squashfuse", // Allow other users than root to access the rootfs "-o", "allow_other", android_img_path.string(), android_rootfs_dir, }; // Easiest is here to go with the standard mount program as that // will handle everything for us which is relevant to get the // squashfs via squashfuse properly mount without having to // reimplement all the details. Once the mount call comes back // without an error we can expect the image to be mounted. auto child = core::posix::exec("/bin/mount", args, {}, core::posix::StandardStream::empty, []() {}); const auto result = child.wait_for(core::posix::wait::Flags::untraced); if (result.status != core::posix::wait::Result::Status::exited || result.detail.if_exited.status != core::posix::exit::Status::success) { ERROR("Failed to mount squashfs Android image"); return false; } auto m = common::MountEntry::create(android_rootfs_dir); if (!m) { ERROR("Failed to create mount entry for Android rootfs"); return false; } mounts_.push_back(m); } else { ERROR("No loop device or FUSE support found. Can't setup Android rootfs!"); return false; } auto final_android_rootfs_dir = android_rootfs_dir; if (enable_rootfs_overlay_) { if (!setup_rootfs_overlay()) return false; final_android_rootfs_dir = SystemConfiguration::instance().combined_rootfs_dir(); } for (const auto &dir_name : std::vector<std::string>{"cache", "data"}) { auto target_dir_path = fs::path(final_android_rootfs_dir) / dir_name; auto src_dir_path = SystemConfiguration::instance().data_dir() / dir_name; if (!fs::exists(src_dir_path)) { if (!fs::create_directory(src_dir_path)) { ERROR("Failed to create Android %s directory", dir_name); mounts_.clear(); return false; } if (::chown(src_dir_path.c_str(), unprivileged_user_id, unprivileged_user_id) != 0) { ERROR("Failed to allow access for unprivileged user on %s directory of the rootfs", dir_name); mounts_.clear(); return false; } } auto m = common::MountEntry::create(src_dir_path, target_dir_path, "", MS_MGC_VAL | MS_BIND | MS_PRIVATE); if (!m) { ERROR("Failed to mount Android %s directory", dir_name); mounts_.clear(); return false; } mounts_.push_back(m); } // Unmounting needs to happen in reverse order std::reverse(mounts_.begin(), mounts_.end()); return true; } bool anbox::cmds::ContainerManager::setup_rootfs_overlay() { const auto combined_rootfs_path = SystemConfiguration::instance().combined_rootfs_dir(); if (!fs::exists(combined_rootfs_path)) fs::create_directories(combined_rootfs_path); const auto overlay_path = SystemConfiguration::instance().overlay_dir(); if (!fs::exists(overlay_path)) fs::create_directories(overlay_path); const auto rootfs_path = SystemConfiguration::instance().rootfs_dir(); const auto overlay_config = utils::string_format("lowerdir=%s:%s", overlay_path, rootfs_path); auto m = common::MountEntry::create("overlay", combined_rootfs_path, "overlay", MS_RDONLY, overlay_config.c_str()); if (!m) { ERROR("Failed to setup rootfs overlay"); mounts_.clear(); return false; } mounts_.push_back(m); DEBUG("Successfully setup rootfs overlay"); return true; }
10,605
C++
.cpp
235
38.680851
122
0.661729
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,636
launch.cpp
anbox_anbox/src/anbox/cmds/launch.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/cmds/launch.h" #include "anbox/dbus/bus.h" #include "anbox/dbus/interface.h" #include "anbox/dbus/application_manager_client.h" #include "anbox/ui/splash_screen.h" #include "anbox/system_configuration.h" #include "anbox/logger.h" #include "core/posix/exec.h" #include "core/posix/fork.h" #include "core/posix/signal.h" #include <boost/filesystem.hpp> #include <fcntl.h> #include <sys/stat.h> namespace fs = boost::filesystem; namespace { constexpr unsigned int max_session_mgr_wait_attempts{10}; const std::chrono::seconds session_mgr_wait_interval{5}; constexpr unsigned int max_dbus_service_wait_attempts{10}; const std::chrono::seconds dbus_service_wait_interval{5}; static int redirect_to_null(int flags, int fd) { int fd2; if ((fd2 = open("/dev/null", flags)) < 0) return -1; if (fd2 == fd) return fd; if (dup2(fd2, fd) < 0) return -1; close(fd2); return fd; } } // namespace bool anbox::cmds::Launch::launch_session_manager_dbus(sd_bus* bus) { sd_bus_error err = SD_BUS_ERROR_NULL; sd_bus_message* msg = nullptr; int r; r = sd_bus_call_method(bus, "org.anbox", "/", "org.freedesktop.DBus.Peer", "Ping", &err, &msg, ""); sd_bus_error_free(&err); sd_bus_message_unref(msg); if (r < 0) { ERROR("Failed to start session manager instance via dbus"); return false; } DEBUG("Started session manager, will now try to connect .."); return true; } bool anbox::cmds::Launch::launch_session_manager() { std::vector<std::string> args = {"session-manager"}; const auto should_force_software_rendering = utils::get_env_value("ANBOX_FORCE_SOFTWARE_RENDERING", "false"); if (should_force_software_rendering == "true") args.push_back("--software-rendering"); std::map<std::string,std::string> env; core::posix::this_process::env::for_each([&](const std::string &name, const std::string &value) { env.insert({name, value}); }); const auto exe_path = utils::process_get_exe_path(::getpid()); if (!fs::exists(exe_path)) { ERROR("Can't find correct anbox executable to run. Found %s but does not exist", exe_path); return false; } try { auto flags = core::posix::StandardStream::empty; auto child = core::posix::fork([&]() { // We redirect all in/out/err to /dev/null as they can't be seen // anywhere. All logging output will directly go to syslog as we // will become a session leader below which will get us rid of a // controlling terminal. if (redirect_to_null(O_RDONLY, 0) < 0 || redirect_to_null(O_WRONLY, 1) < 0 || redirect_to_null(O_WRONLY, 2) < 0) { ERROR("Failed to redirect stdout/stderr/stdin: %s", strerror(errno)); return core::posix::exit::Status::failure; } // As we forked one time already we're sure that our process is // not the session leader anymore so we can safely become the // new one and lead the process group. if (setsid() < 0) { ERROR("Failed to become new session leader: %s", strerror(errno)); return core::posix::exit::Status::failure; } umask(0077); if (chdir("/") < 0) { ERROR("Failed to change current directory: %s", strerror(errno)); return core::posix::exit::Status::failure; } auto grandchild = core::posix::exec(exe_path, args, env, flags); grandchild.dont_kill_on_cleanup(); return core::posix::exit::Status::success; }, flags); // We don't wait for the grandchild but the child as we use double forking // here to break through the process hierarchy and make the grandchild a // direct child of the init process so it keeps running on its own and // indepent of our short living process here. child.wait_for(core::posix::wait::Flags::untraced); DEBUG("Started session manager, will now try to connect .."); } catch (...) { ERROR("Failed to start session manager instance"); } return true; } anbox::cmds::Launch::Launch() : CommandWithFlagsAndAction{ cli::Name{"launch"}, cli::Usage{"launch"}, cli::Description{"Launch an Activity by sending an intent"}} { flag(cli::make_flag(cli::Name{"action"}, cli::Description{"Action of the intent"}, intent_.action)); flag(cli::make_flag(cli::Name{"type"}, cli::Description{"MIME type for the intent"}, intent_.type)); flag(cli::make_flag(cli::Name{"uri"}, cli::Description{"URI used as data within the intent"}, intent_.uri)); flag(cli::make_flag(cli::Name{"package"}, cli::Description{"Package the intent should go to"}, intent_.package)); flag(cli::make_flag(cli::Name{"component"}, cli::Description{"Component of a package the intent should go"}, intent_.component)); flag(cli::make_flag(cli::Name{"stack"}, cli::Description{"Which window stack the activity should be started on. Possible: default, fullscreen, freeform"}, stack_)); flag(cli::make_flag(cli::Name{"use-system-dbus"}, cli::Description{"Use system instead of session DBus"}, use_system_dbus_)); action([this](const cli::Command::Context&) { if (!intent_.valid()) { ERROR("The intent you provided is invalid. Please provide a correct launch intent."); ERROR("For example to launch the application manager, run:"); ERROR("$ anbox launch --package=org.anbox.appmgr --component=org.anbox.appmgr.AppViewActivity"); return EXIT_FAILURE; } auto bus_type = anbox::dbus::Bus::Type::Session; if (use_system_dbus_) bus_type = anbox::dbus::Bus::Type::System; auto bus = std::make_shared<anbox::dbus::Bus>(bus_type); std::shared_ptr<ui::SplashScreen> ss; if (!bus->has_service_with_name(dbus::interface::Service::name())) { DEBUG("Session manager is not yet running, trying to start it"); if (!( launch_session_manager_dbus(bus->raw()) || launch_session_manager() )) return EXIT_FAILURE; // Give us a splash screen as long as we're trying to connect // with the session manager so the user knows something is // happening after he started Anbox. ss = std::make_shared<ui::SplashScreen>(); } unsigned int n = 0; while (n < max_dbus_service_wait_attempts) { if (bus->has_service_with_name(dbus::interface::Service::name())) break; std::this_thread::sleep_for(dbus_service_wait_interval); n++; } auto connection = use_system_dbus_ ? sdbus::createSystemBusConnection() : sdbus::createSessionBusConnection(); ApplicationManagerClient client(*connection, dbus::interface::Service::name(), dbus::interface::Service::path()); n = 0; while (n < max_session_mgr_wait_attempts) { if (client.Ready()) break; std::this_thread::sleep_for(session_mgr_wait_interval); n++; } if (!client.Ready()) { ERROR("Session manager failed to become ready"); return EXIT_FAILURE; } // If we have a splash screen now is the time to drop it as we're // going to launch the real application now. ss.reset(); return client.TryLaunch(intent_, stack_) ? EXIT_SUCCESS : EXIT_FAILURE; }); }
8,191
C++
.cpp
192
36.25
136
0.647443
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,637
install.cpp
anbox_anbox/src/anbox/cmds/install.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/cmds/install.h" #include "anbox/dbus/stub/application_manager.h" #include <core/dbus/asio/executor.h> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; anbox::cmds::Install::Install() : CommandWithFlagsAndAction{ cli::Name{"install"}, cli::Usage{"install"}, cli::Description{ "Install specified application in the Android container"}} { flag(cli::make_flag(cli::Name{"apk"}, cli::Description{"Path to APK to install"}, apk_)); action([this](const cli::Command::Context&) { if (apk_.length() == 0) BOOST_THROW_EXCEPTION(std::runtime_error("No APK to install specified")); if (!fs::is_regular_file(apk_)) BOOST_THROW_EXCEPTION( std::runtime_error("Specified APK file does not exist")); auto bus = std::make_shared<core::dbus::Bus>(core::dbus::WellKnownBus::session); bus->install_executor(core::dbus::asio::make_executor(bus)); auto stub = dbus::stub::ApplicationManager::create_for_bus(bus); stub->install(apk_); return EXIT_SUCCESS; }); }
1,778
C++
.cpp
42
37.809524
79
0.698321
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,638
session_manager.cpp
anbox_anbox/src/anbox/cmds/session_manager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <boost/algorithm/string/split.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-default" #include <sys/prctl.h> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include "anbox/application/database.h" #include "anbox/application/launcher_storage.h" #include "anbox/application/sensor_type.h" #include "anbox/application/sensors_state.h" #include "anbox/application/gps_info_broker.h" #include "anbox/audio/server.h" #include "anbox/bridge/android_api_stub.h" #include "anbox/bridge/platform_api_skeleton.h" #include "anbox/bridge/platform_message_processor.h" #include "anbox/cmds/session_manager.h" #include "anbox/common/dispatcher.h" #include "anbox/container/client.h" #include "anbox/dbus/application_manager_server.h" #include "anbox/dbus/gps_server.h" #include "anbox/dbus/sensors_server.h" #include "anbox/dbus/bus.h" #include "anbox/dbus/interface.h" #include "anbox/dbus/sensors_server.h" #include "anbox/graphics/emugl/Renderer.h" #include "anbox/graphics/gl_renderer_server.h" #include "anbox/input/manager.h" #include "anbox/logger.h" #include "anbox/network/published_socket_connector.h" #include "anbox/platform/base_platform.h" #include "anbox/qemu/pipe_connection_creator.h" #include "anbox/rpc/channel.h" #include "anbox/rpc/connection_creator.h" #include "anbox/runtime.h" #include "anbox/system_configuration.h" #include "anbox/wm/multi_window_manager.h" #include "anbox/wm/single_window_manager.h" #include "core/posix/signal.h" #include "external/xdg/xdg.h" #pragma GCC diagnostic pop namespace fs = boost::filesystem; namespace { constexpr const char *default_appmgr_package{"org.anbox.appmgr"}; constexpr const char *default_appmgr_component{"org.anbox.appmgr.AppViewActivity"}; const boost::posix_time::milliseconds default_appmgr_startup_delay{50}; const anbox::graphics::Rect default_single_window_size{0, 0, 1024, 768}; class NullConnectionCreator : public anbox::network::ConnectionCreator< boost::asio::local::stream_protocol> { public: void create_connection_for( std::shared_ptr<boost::asio::local::stream_protocol::socket> const &socket) override { WARNING("Not implemented"); socket->close(); } }; } // namespace void anbox::cmds::SessionManager::launch_appmgr_if_needed(const std::shared_ptr<bridge::AndroidApiStub> &android_api_stub) { if (!single_window_) return; android::Intent launch_intent; launch_intent.package = default_appmgr_package; launch_intent.component = default_appmgr_component; // As this will only be executed in single window mode we don't have // to specify and launch bounds. android_api_stub->launch(launch_intent, graphics::Rect::Invalid, wm::Stack::Id::Default); } anbox::cmds::SessionManager::SessionManager() : CommandWithFlagsAndAction{cli::Name{"session-manager"}, cli::Usage{"session-manager"}, cli::Description{"Run the the anbox session manager"}}, window_size_(default_single_window_size) { // Just for the purpose to allow QtMir (or unity8) to find this on our // /proc/*/cmdline // for proper confinement etc. flag(cli::make_flag(cli::Name{"desktop_file_hint"}, cli::Description{"Desktop file hint for QtMir/Unity8"}, desktop_file_hint_)); flag(cli::make_flag(cli::Name{"single-window"}, cli::Description{"Start in single window mode."}, single_window_)); flag(cli::make_flag(cli::Name{"window-size"}, cli::Description{"Size of the window in single window mode, e.g. --window-size=1024,768"}, window_size_)); flag(cli::make_flag(cli::Name{"standalone"}, cli::Description{"Prevents the Container Manager from starting the default container (Experimental)"}, standalone_)); flag(cli::make_flag(cli::Name{"experimental"}, cli::Description{"Allows users to use experimental features"}, experimental_)); flag(cli::make_flag(cli::Name{"use-system-dbus"}, cli::Description{"Use system instead of session DBus"}, use_system_dbus_)); flag(cli::make_flag(cli::Name{"software-rendering"}, cli::Description{"Use software rendering instead of hardware accelerated GL rendering"}, use_software_rendering_)); flag(cli::make_flag(cli::Name{"no-touch-emulation"}, cli::Description{"Disable touch emulation applied on mouse inputs"}, no_touch_emulation_)); flag(cli::make_flag(cli::Name{"server-side-decoration"}, cli::Description{"Prefer to use server-side decoration instead of client-side decoration"}, server_side_decoration_)); flag(cli::make_flag(cli::Name{"disabled-sensors"}, cli::Description{"Sensors to disable, comma delimited"}, disabled_sensors_)); flag(cli::make_flag(cli::Name{"rootless"}, cli::Description{"Run in rootless window mode"}, rootless_)); action([this](const cli::Command::Context &) { auto trap = core::posix::trap_signals_for_process( {core::posix::Signal::sig_term, core::posix::Signal::sig_int}); trap->signal_raised().connect([trap](const core::posix::Signal &signal) { INFO("Signal %i received. Good night.", static_cast<int>(signal)); trap->stop(); }); if (standalone_ && !experimental_) { ERROR("Experimental features selected, but --experimental flag not set"); return EXIT_FAILURE; } if ((!fs::exists("/dev/binder") && !fs::exists(BINDERFS_PATH)) || !fs::exists("/dev/ashmem")) { ERROR("Failed to start as either binder or ashmem kernel drivers are not loaded"); return EXIT_FAILURE; } utils::ensure_paths({ SystemConfiguration::instance().socket_dir(), SystemConfiguration::instance().input_device_dir(), }); auto rt = Runtime::create(); auto dispatcher = anbox::common::create_dispatcher_for_runtime(rt); if (!standalone_) { container_ = std::make_shared<container::Client>(rt); container_->register_terminate_handler([&]() { WARNING("Lost connection to container manager, terminating."); trap->stop(); }); } auto input_manager = std::make_shared<input::Manager>(rt); auto android_api_stub = std::make_shared<bridge::AndroidApiStub>(); auto display_frame = graphics::Rect::Invalid; if (single_window_) display_frame = window_size_; const auto should_enable_touch_emulation = utils::get_env_value("ANBOX_ENABLE_TOUCH_EMULATION", "true"); if (should_enable_touch_emulation == "false" || no_touch_emulation_) no_touch_emulation_ = true; const auto should_force_server_side_decoration = utils::get_env_value("ANBOX_FORCE_SERVER_SIDE_DECORATION", "false"); if (should_force_server_side_decoration == "true") server_side_decoration_ = true; platform::Configuration platform_config; platform_config.single_window = single_window_; platform_config.no_touch_emulation = no_touch_emulation_; platform_config.display_frame = display_frame; platform_config.server_side_decoration = server_side_decoration_; platform_config.rootless = rootless_; auto platform = platform::create(utils::get_env_value("ANBOX_PLATFORM", "sdl"), input_manager, platform_config); if (!platform) return EXIT_FAILURE; auto app_db = std::make_shared<application::Database>(); std::shared_ptr<wm::Manager> window_manager; bool using_single_window = false; if (platform->supports_multi_window() && !single_window_) window_manager = std::make_shared<wm::MultiWindowManager>(platform, android_api_stub, app_db); else { window_manager = std::make_shared<wm::SingleWindowManager>(platform, display_frame, app_db); using_single_window = true; } const auto should_force_software_rendering = utils::get_env_value("ANBOX_FORCE_SOFTWARE_RENDERING", "false"); auto gl_driver = graphics::GLRendererServer::Config::Driver::Host; if (should_force_software_rendering == "true" || use_software_rendering_) gl_driver = graphics::GLRendererServer::Config::Driver::Software; graphics::GLRendererServer::Config renderer_config{ gl_driver, single_window_}; auto gl_server = std::make_shared<graphics::GLRendererServer>(renderer_config, window_manager); platform->set_window_manager(window_manager); platform->set_renderer(gl_server->renderer()); window_manager->setup(); auto app_manager = std::static_pointer_cast<application::Manager>(android_api_stub); if (!using_single_window) { // When we're not running single window mode we need to restrict ourself to // only launch applications in freeform mode as otherwise the window tracking // doesn't work. app_manager = std::make_shared<application::RestrictedManager>( android_api_stub, wm::Stack::Id::Freeform); } auto audio_server = std::make_shared<audio::Server>(rt, platform); const auto socket_path = SystemConfiguration::instance().socket_dir(); auto sensors_state = std::make_shared<application::SensorsState>(); std::stringstream disabled_sensors_stream(disabled_sensors_); std::string disabled_sensor_name; while (std::getline(disabled_sensors_stream, disabled_sensor_name, ',')) { sensors_state->disabled_sensors |= application::SensorTypeHelper::FromString(disabled_sensor_name); } auto gps_info_broker = std::make_shared<application::GpsInfoBroker>(); // The qemu pipe is used as a very fast communication channel between guest // and host for things like the GLES emulation/translation, the RIL or ADB. auto qemu_pipe_connector = std::make_shared<network::PublishedSocketConnector>( utils::string_format("%s/qemu_pipe", socket_path), rt, std::make_shared<qemu::PipeConnectionCreator>(gl_server->renderer(), rt, sensors_state, gps_info_broker)); boost::asio::deadline_timer appmgr_start_timer(rt->service()); auto bridge_connector = std::make_shared<network::PublishedSocketConnector>( utils::string_format("%s/anbox_bridge", socket_path), rt, std::make_shared<rpc::ConnectionCreator>( [&](const std::shared_ptr<network::MessageSender> &sender) { auto pending_calls = std::make_shared<rpc::PendingCallCache>(); auto rpc_channel = std::make_shared<rpc::Channel>(pending_calls, sender); // This is safe as long as we only support a single client. If we // support // more than one one day we need proper dispatching to the right // one. android_api_stub->set_rpc_channel(rpc_channel); auto server = std::make_shared<bridge::PlatformApiSkeleton>( pending_calls, platform, window_manager, app_db); server->register_boot_finished_handler([&]() { DEBUG("Android successfully booted"); android_api_stub->ready().set(true); appmgr_start_timer.expires_from_now(default_appmgr_startup_delay); appmgr_start_timer.async_wait([&](const boost::system::error_code &err) { if (err != boost::system::errc::success) return; launch_appmgr_if_needed(android_api_stub); }); }); return std::make_shared<bridge::PlatformMessageProcessor>( sender, server, pending_calls); })); container::Configuration container_configuration; // Instruct healthd to fake battery level as it may take it from other connected // devices like mouse or keyboard and will incorrectly show a system popup to // shutdown the Android system because of low battery. This prevents any kind of // input as focus is bound to the system popup exclusively. // // See https://github.com/anbox/anbox/issues/780 for further details. container_configuration.extra_properties.push_back("ro.boot.fake_battery=1"); if (server_side_decoration_) container_configuration.extra_properties.push_back("ro.anbox.no_decorations=1"); if (!standalone_) { container_configuration.bind_mounts = { {qemu_pipe_connector->socket_file(), "/dev/qemu_pipe"}, {bridge_connector->socket_file(), "/dev/anbox_bridge"}, {audio_server->socket_file(), "/dev/anbox_audio"}, {SystemConfiguration::instance().input_device_dir(), "/dev/input"}, }; container_configuration.devices = { {"/dev/fuse", {0666}}, }; dispatcher->dispatch([&]() { container_->start(container_configuration); }); } auto connection = use_system_dbus_ ? sdbus::createSystemBusConnection(dbus::interface::Service::name()) : sdbus::createSessionBusConnection(dbus::interface::Service::name()); ApplicationManagerServer appManagerServer(*connection, dbus::interface::Service::path(), app_manager); SensorsServer sensorsServer(*connection, dbus::interface::Service::path(), sensors_state); GpsServer gpsServer(*connection, dbus::interface::Service::path(), gps_info_broker); connection->enterEventLoopAsync(); rt->start(); trap->run(); if (!standalone_) { // Stop the container which should close all open connections we have on // our side and should terminate all services. container_->stop(); } rt->stop(); return EXIT_SUCCESS; }); }
14,609
C++
.cpp
286
43.496503
124
0.672878
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,639
wait_ready.cpp
anbox_anbox/src/anbox/cmds/wait_ready.cpp
/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> * */ #include "anbox/cmds/wait_ready.h" #include "anbox/dbus/application_manager_client.h" #include "anbox/dbus/bus.h" #include "anbox/dbus/interface.h" namespace { constexpr const unsigned int max_wait_attempts{30}; } anbox::cmds::WaitReady::WaitReady() : CommandWithFlagsAndAction{ cli::Name{"wait-ready"}, cli::Usage{"wait-ready"}, cli::Description{"Wait until the Android system has successfully booted"}} { flag(cli::make_flag(cli::Name{"use-system-dbus"}, cli::Description{"Use system instead of session DBus"}, use_system_dbus_)); action([this](const cli::Command::Context&) { auto bus_type = anbox::dbus::Bus::Type::Session; if (use_system_dbus_) bus_type = anbox::dbus::Bus::Type::System; auto bus = std::make_shared<anbox::dbus::Bus>(bus_type); auto connection = use_system_dbus_ ? sdbus::createSystemBusConnection() : sdbus::createSessionBusConnection(); ApplicationManagerClient client(*connection, dbus::interface::Service::name(), dbus::interface::Service::path()); unsigned int n = 0; while (n < max_wait_attempts) { if (client.Ready()) return EXIT_SUCCESS; std::this_thread::sleep_for(std::chrono::seconds{1}); n++; } return EXIT_FAILURE; }); }
2,072
C++
.cpp
51
35.313725
117
0.680417
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,640
check_features.cpp
anbox_anbox/src/anbox/cmds/check_features.cpp
/* * Copyright (C) 2018 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/cmds/check_features.h" #include "anbox/utils.h" #include "cpu_features_macros.h" #if defined(CPU_FEATURES_ARCH_X86) #include "cpuinfo_x86.h" #endif namespace { std::vector<std::string> cpu_whitelist = { // QEMU does not necessarily expose correctly that it supports SSE and friends even // when started with `-cpu qemu64,+ssse3,+sse4.1,+sse4.2,+x2apic` "QEMU", // The following CPUs do not support AVX and without it cpu_features can't detect // if SSE & friends are supported. See https://github.com/google/cpu_features/issues/4 // Intel Core i7 M620 "M 620", // Intel Core i5 M460 "M 460", // Intel Celeron N2840 "N2840", // Intel Core i7 Q720 "Q 720", // Intel Pentium T4500 "T4500", // Intel Core i7 Q720 "Q 720", // Intel Xeon E5520 "E5520" // Intel Core2 Duo T6500 "T6500" }; } // namespace anbox::cmds::CheckFeatures::CheckFeatures() : CommandWithFlagsAndAction{ cli::Name{"check-features"}, cli::Usage{"check-features"}, cli::Description{"Check that the host system supports all necessary features"}} { action([this](const cli::Command::Context&) { (void)this; #if defined(CPU_FEATURES_ARCH_X86) const auto info = cpu_features::GetX86Info(); std::vector<std::string> missing_features; #define CHECK_BOOL(x, name) \ if (!x) \ missing_features.push_back(name) CHECK_BOOL(info.features.sse4_1, "SSE 4.1"); CHECK_BOOL(info.features.sse4_2, "SSE 4.2"); CHECK_BOOL(info.features.ssse3, "SSSE 3"); char brand_string[49]; cpu_features::FillX86BrandString(brand_string); std::string brand(brand_string); // Check if we have a CPU which's features we can't detect correctly auto is_whitelisted = false; for (const auto &entry : cpu_whitelist) { if (brand.find(entry) != std::string::npos) { is_whitelisted = true; break; } } if (missing_features.size() > 0 && !is_whitelisted && !sanity_check_for_features()) { std::cerr << "The CPU of your computer (" << brand_string << ") does not support all" << std::endl << "features Anbox requires." << std::endl << "It is missing support for the following features: "; for (size_t n = 0; n < missing_features.size(); n++) { const auto feature = missing_features[n]; std::cerr << feature; if (n < missing_features.size() - 1) std::cerr << ", "; } std::cerr << std::endl; std::cerr << "You can for example find more information about SSE" << std::endl << "here https://en.wikipedia.org/wiki/Streaming_SIMD_Extensions" << std::endl; return EXIT_FAILURE; } std::cout << "Your computer does meet all requirements to run Anbox" << std::endl; return EXIT_SUCCESS; #else std::cerr << "You're running Anbox on a not yet supported architecture" << std::endl; return EXIT_FAILURE; #endif }); } // In case that the CPU supports AVX we take the decision as from our analysis // of the output from the cpu_features library. If it does not we have to check // further via the compiler builtins if we the CPU supports all mandatory features // or not. In case that any is missing we will fail the test. // // This uses the compiler builtin function __builtin_cpu_supports which allows us // to detect certain CPU features. // See https://gcc.gnu.org/onlinedocs/gcc/x86-Built-in-Functions.html bool anbox::cmds::CheckFeatures::sanity_check_for_features() { #if defined(CPU_FEATURES_ARCH_X86) if (__builtin_cpu_supports("avx")) return true; std::vector<std::string> missing_features; #define CHECK_FEATURE(name) \ if (!__builtin_cpu_supports(name)) \ missing_features.push_back(name); CHECK_FEATURE("sse4.1"); CHECK_FEATURE("sse4.2"); CHECK_FEATURE("ssse3"); return missing_features.empty(); #else return true; #endif }
4,575
C++
.cpp
120
34.133333
104
0.686739
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,641
version.cpp
anbox_anbox/src/anbox/cmds/version.cpp
/* * Copyright (C) 2016 Canonical, Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <thomas.voss@canonical.com> * */ #include "anbox/cmds/version.h" #include "anbox/build/config.h" #include "anbox/utils.h" anbox::cmds::Version::Version() : CommandWithFlagsAndAction{ cli::Name{"version"}, cli::Usage{"version"}, cli::Description{"Print the version of the daemon"}} { action([](const cli::Command::Context& ctxt) { ctxt.cout << "anbox " << build::version << std::endl; return 0; }); }
1,118
C++
.cpp
30
34.433333
78
0.71639
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,642
system_info.cpp
anbox_anbox/src/anbox/cmds/system_info.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/cmds/system_info.h" #include "anbox/graphics/emugl/RenderApi.h" #include "anbox/graphics/emugl/DispatchTables.h" #include "anbox/utils/environment_file.h" #include "anbox/logger.h" #include "anbox/build/config.h" #include <sstream> #include <fstream> #include <boost/filesystem.hpp> #include "OpenGLESDispatch/EGLDispatch.h" #include "cpu_features_macros.h" #if defined(CPU_FEATURES_ARCH_X86) #include "cpuinfo_x86.h" #endif namespace fs = boost::filesystem; namespace { constexpr const char *os_release_path{"/etc/os-release"}; constexpr const char *host_os_release_path{"/var/lib/snapd/hostfs/etc/os-release"}; constexpr const char *proc_version_path{"/proc/version"}; constexpr const char *binder_path{"/dev/binder"}; constexpr const char *binderfs_path{"/dev/binderfs"}; constexpr const char *ashmem_path{"/dev/ashmem"}; constexpr const char *os_release_name{"NAME"}; constexpr const char *os_release_version{"VERSION"}; class SystemInformation { public: SystemInformation() { collect_cpu_info(); collect_os_info(); collect_kernel_info(); collect_graphics_info(); } std::string to_text() const { std::stringstream s; s << "version: " << anbox::build::version << std::endl; if (anbox::utils::is_env_set("SNAP_REVISION")) { s << "snap-revision: " << anbox::utils::get_env_value("SNAP_REVISION") << std::endl; } s << "cpu:" << std::endl << " arch: " << cpu_info_.arch << std::endl << " brand: " << cpu_info_.brand << std::endl << " features: " << std::endl; for (const auto& feature : cpu_info_.features) s << " - " << feature << std::endl; s << "os:" << std::endl << " name: " << os_info_.name << std::endl << " version: " << os_info_.version << std::endl << " snap-based: " << std::boolalpha << os_info_.snap_based << std::endl; s << "kernel:" << std::endl << " version: " << kernel_info_.version << std::endl << " binder: " << std::boolalpha << kernel_info_.binder << std::endl << " binderfs: " << std::boolalpha << kernel_info_.binderfs << std::endl << " ashmem: " << std::boolalpha << kernel_info_.ashmem << std::endl; auto print_extensions = [](const std::vector<std::string> &extensions) { std::stringstream s; if (extensions.size() > 0) { s << std::endl; for (const auto &ext : extensions) { if (ext.length() == 0) continue; s << " - " << ext << std::endl; } } else { s << " []" << std::endl; } return s.str(); }; s << "graphics:" << std::endl << " egl:" << std::endl << " vendor: " << graphics_info_.egl_vendor << std::endl << " version: " << graphics_info_.egl_version << std::endl << " extensions:" << print_extensions(graphics_info_.egl_extensions) << " gles2:" << std::endl << " vendor: " << graphics_info_.gles2_vendor << std::endl << " vendor: " << graphics_info_.gles2_version << std::endl << " extensions:" << print_extensions(graphics_info_.gles2_extensions); return s.str(); } private: void collect_cpu_info() { #if defined(CPU_FEATURES_ARCH_X86) cpu_info_.arch = "x86"; const auto info = cpu_features::GetX86Info(); if (info.features.aes) cpu_info_.features.push_back("aes"); if (info.features.sse4_1) cpu_info_.features.push_back("sse4_1"); if (info.features.sse4_2) cpu_info_.features.push_back("sse4_2"); if (info.features.avx) cpu_info_.features.push_back("avx"); if (info.features.avx2) cpu_info_.features.push_back("avx2"); char brand_string[49]; cpu_features::FillX86BrandString(brand_string); cpu_info_.brand = brand_string; #endif } void collect_os_info() { os_info_.snap_based = !anbox::utils::get_env_value("SNAP").empty(); fs::path path = os_release_path; // If we're running from within a snap the best we can do is to // access the hostfs and read the os-release file from there. if (os_info_.snap_based && fs::exists(host_os_release_path)) path = host_os_release_path; // Double check that there aren't any permission errors when trying // to access the file (e.g. because of snap confinement) if (fs::exists(path)) { anbox::utils::EnvironmentFile os_release(path); os_info_.name = os_release.value(os_release_name); os_info_.version = os_release.value(os_release_version); } } void collect_kernel_info() { if (fs::exists(proc_version_path)) { std::ifstream in(proc_version_path); std::getline(in, kernel_info_.version); } kernel_info_.binder = fs::exists(binder_path); kernel_info_.binderfs = fs::exists(binderfs_path); kernel_info_.ashmem = fs::exists(ashmem_path); } void collect_graphics_info() { auto gl_libs = anbox::graphics::emugl::default_gl_libraries(); if (!anbox::graphics::emugl::initialize(gl_libs, nullptr, nullptr)) { return; } auto display = s_egl.eglGetDisplay(0); if (display != EGL_NO_DISPLAY) { s_egl.eglInitialize(display, nullptr, nullptr); auto egl_safe_get_string = [display](EGLint item) { auto str = s_egl.eglQueryString(display, item); if (!str) return std::string("n/a"); return std::string(reinterpret_cast<const char*>(str)); }; graphics_info_.egl_vendor = egl_safe_get_string(EGL_VENDOR); graphics_info_.egl_version = egl_safe_get_string(EGL_VERSION); const auto egl_extensions = egl_safe_get_string(EGL_EXTENSIONS); graphics_info_.egl_extensions = anbox::utils::string_split(egl_extensions, ' '); GLint config_attribs[] = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, EGL_NONE}; EGLConfig config; int n; if (s_egl.eglChooseConfig(display, config_attribs, &config, 1, &n) && n > 0) { GLint attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; auto context = s_egl.eglCreateContext(display, config, nullptr, attribs); if (context != EGL_NO_CONTEXT) { // We require surfaceless-context support here for now. If eglMakeCurrent fails // glGetString will return null below which we handle correctly. s_egl.eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context); auto gl_safe_get_string = [](GLint item) { auto str = s_gles2.glGetString(item); if (!str) return std::string("n/a"); return std::string(reinterpret_cast<const char*>(str)); }; graphics_info_.gles2_vendor = gl_safe_get_string(GL_VENDOR); graphics_info_.gles2_version = gl_safe_get_string(GL_VERSION); const auto gl_extensions = gl_safe_get_string(GL_EXTENSIONS); graphics_info_.gles2_extensions = anbox::utils::string_split(gl_extensions, ' '); s_egl.eglMakeCurrent(display, nullptr, nullptr, nullptr); s_egl.eglDestroyContext(display, context); } } } } struct { std::string arch; std::string brand; std::vector<std::string> features; } cpu_info_; struct { bool snap_based = false; std::string name = "n/a"; std::string version = "n/a"; } os_info_; struct { std::string version = "n/a"; bool binder = false; bool binderfs = false; bool ashmem = false; } kernel_info_; struct { std::string egl_vendor = "n/a"; std::string egl_version = "n/a"; std::vector<std::string> egl_extensions; std::string gles2_vendor = "n/a"; std::string gles2_version = "n/a"; std::vector<std::string> gles2_extensions; } graphics_info_; }; std::ostream &operator<<(std::ostream &out, const SystemInformation &info) { out << info.to_text(); return out; } } anbox::cmds::SystemInfo::SystemInfo() : CommandWithFlagsAndAction{ cli::Name{"system-info"}, cli::Usage{"system-info"}, cli::Description{"Print various information about the system we're running on"}} { action([](const cli::Command::Context&) { SystemInformation si; std::cout << si; return EXIT_SUCCESS; }); }
8,958
C++
.cpp
228
33.741228
92
0.633832
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,643
server.cpp
anbox_anbox/src/anbox/audio/server.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/audio/server.h" #include "anbox/audio/sink.h" #include "anbox/network/published_socket_connector.h" #include "anbox/network/delegate_connection_creator.h" #include "anbox/network/local_socket_messenger.h" #include "anbox/network/message_processor.h" #include "anbox/common/type_traits.h" #include "anbox/system_configuration.h" #include "anbox/utils.h" #include "anbox/logger.h" using namespace std::placeholders; namespace { class AudioForwarder : public anbox::network::MessageProcessor { public: AudioForwarder(const std::shared_ptr<anbox::audio::Sink> &sink) : sink_(sink) { } bool process_data(const std::vector<std::uint8_t> &data) override { sink_->write_data(data); return true; } private: std::shared_ptr<anbox::audio::Sink> sink_; }; } namespace anbox::audio { Server::Server(const std::shared_ptr<Runtime>& rt, const std::shared_ptr<platform::BasePlatform> &platform) : platform_(platform), socket_file_(utils::string_format("%s/anbox_audio", SystemConfiguration::instance().socket_dir())), connector_(std::make_shared<network::PublishedSocketConnector>( socket_file_, rt, std::make_shared<network::DelegateConnectionCreator<boost::asio::local::stream_protocol>>(std::bind(&Server::create_connection_for, this, _1)))), connections_(std::make_shared<network::Connections<network::SocketConnection>>()), next_id_(0) { // FIXME: currently creating the socket creates it with the rights of // the user we're running as. As this one is mapped into the container ::chmod(socket_file_.c_str(), 0777); } Server::~Server() {} void Server::create_connection_for(std::shared_ptr<boost::asio::basic_stream_socket<boost::asio::local::stream_protocol>> const& socket) { auto const messenger = std::make_shared<network::LocalSocketMessenger>(socket); // We have to read the client flags first before we can continue // processing the actual commands ClientInfo client_info; auto err = messenger->receive_msg( boost::asio::buffer(&client_info, sizeof(ClientInfo))); if (err) { ERROR("Failed to read client info: %s", err.message()); return; } std::shared_ptr<network::MessageProcessor> processor; switch (client_info.type) { case ClientInfo::Type::Playback: processor = std::make_shared<AudioForwarder>(platform_->create_audio_sink()); break; case ClientInfo::Type::Recording: break; default: ERROR("Invalid client type %d", static_cast<int>(client_info.type)); return; } // Everything ok, so approve the client by sending the requesting client // info back. Once we have more things to negotiate we will send a modified // client info struct back. messenger->send(reinterpret_cast<char*>(&client_info), sizeof(client_info)); auto connection = std::make_shared<network::SocketConnection>( messenger, messenger, next_id(), connections_, processor); connections_->add(connection); connection->read_next_message(); } int Server::next_id() { return next_id_.fetch_add(1); } }
3,728
C++
.cpp
91
37.923077
158
0.735229
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,644
qemud_message_processor.cpp
anbox_anbox/src/anbox/qemu/qemud_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/qemud_message_processor.h" #include "anbox/logger.h" #include "anbox/utils.h" #include <string.h> namespace { static constexpr const long header_size{4}; } // namespace namespace anbox::qemu { QemudMessageProcessor::QemudMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : messenger_(messenger) {} QemudMessageProcessor::~QemudMessageProcessor() {} bool QemudMessageProcessor::process_data(const std::vector<std::uint8_t> &data) { for (const auto &byte : data) buffer_.push_back(byte); return process_commands(); } bool QemudMessageProcessor::process_commands() { while (true) { if (buffer_.size() < header_size) break; char header[header_size] = {0}; ::memcpy(header, buffer_.data(), header_size); unsigned int body_size = 0; ::sscanf(header, "%04x", &body_size); // Double check that we have enough data to ready the whole body. If // not we have to wait until we have everything. size_t total_size = header_size + body_size; if (buffer_.size() < total_size) break; std::string command; // Make sure we only copy as much bytes as we have to and not more command.insert(0, reinterpret_cast<const char *>(buffer_.data()) + header_size, body_size); handle_command(command); const auto consumed = header_size + body_size; buffer_.erase(buffer_.begin(), buffer_.begin() + consumed); const auto remaining = buffer_.size() - consumed; if (remaining <= 0) break; } return true; } void QemudMessageProcessor::send_header(const size_t &size) { char header[header_size + 1]; std::snprintf(header, header_size + 1, "%04zx", size); messenger_->send(header, header_size); } void QemudMessageProcessor::finish_message() { // Send terminating NULL byte messenger_->send(static_cast<const char *>(""), 1); } }
2,591
C++
.cpp
70
33.328571
81
0.70607
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,645
sensors_message_processor.cpp
anbox_anbox/src/anbox/qemu/sensors_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/sensors_message_processor.h" #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/predicate.hpp> #include <chrono> #include <iostream> #include <thread> #include "anbox/application/sensor_type.h" #include "anbox/logger.h" using namespace std; using namespace anbox::application; namespace std { std::ostream& operator<<(std::ostream& os, std::tuple<double, double, double> t) { os << std::get<0>(t) << ":" << std::get<1>(t) << ":" << std::get<2>(t); return os; } } // namespace std namespace anbox::qemu { SensorsMessageProcessor::SensorsMessageProcessor( shared_ptr<network::SocketMessenger> messenger, shared_ptr<application::SensorsState> sensorsState) : QemudMessageProcessor(messenger), sensors_state_(sensorsState) { enabledSensors_ = 0; thread_ = std::thread([this]() { for (;;) { auto enabledSensors = enabledSensors_.load(); if (enabledSensors & SensorType::AccelerationSensor) send_message(utils::string_format("acceleration:%1%", sensors_state_->acceleration)); if (enabledSensors & SensorType::MagneticFieldSensor) send_message(utils::string_format("magnetic:%1%", sensors_state_->magneticField)); if (enabledSensors & SensorType::OrientationSensor) send_message(utils::string_format("orientation:%1%", sensors_state_->orientation)); if (enabledSensors & SensorType::TemperatureSensor) send_message(utils::string_format("temperature:%1%", sensors_state_->temperature)); if (enabledSensors & SensorType::ProximitySensor) send_message(utils::string_format("proximity:%1%", sensors_state_->proximity)); if (enabledSensors & SensorType::LightSensor) send_message(utils::string_format("light:%1%", sensors_state_->light)); if (enabledSensors & SensorType::PressureSensor) send_message(utils::string_format("pressure:%1%", sensors_state_->pressure)); if (enabledSensors & SensorType::HumiditySensor) send_message(utils::string_format("humidity:%1%", sensors_state_->humidity)); if (enabledSensors) { struct timeval tv; gettimeofday(&tv, NULL); send_message(utils::string_format("sync:%d", tv.tv_sec * 1000000LL + tv.tv_usec)); } if (!run_thread_.load()) break; this_thread::sleep_for(delay_.load() * 1ms); } }); } SensorsMessageProcessor::~SensorsMessageProcessor() { run_thread_ = false; thread_.join(); } void SensorsMessageProcessor::handle_command(const string& command) { int value; std::vector<string> parts; boost::split(parts, command, boost::is_any_of(":")); if (command == "list-sensors") { uint32_t enabledSensors = 0; enabledSensors |= SensorType::AccelerationSensor; enabledSensors |= SensorType::MagneticFieldSensor; enabledSensors |= SensorType::OrientationSensor; enabledSensors |= SensorType::TemperatureSensor; enabledSensors |= SensorType::ProximitySensor; enabledSensors |= SensorType::LightSensor; enabledSensors |= SensorType::PressureSensor; enabledSensors |= SensorType::HumiditySensor; enabledSensors &= ~sensors_state_->disabled_sensors; send_message(to_string(enabledSensors)); } else if (sscanf(command.c_str(), "set-delay:%d", &value)) { delay_ = value; } else if (parts.size() == 3 && parts[0] == "set") { auto st = SensorTypeHelper::FromString(parts[1]); if (parts[2] == "1") { enabledSensors_ |= st; } else { enabledSensors_ &= ~st; } } else { ERROR("Unknown command: " + command); } } // namespace qemu void SensorsMessageProcessor::send_message(const string& msg) { send_header(msg.length()); messenger_->send(msg.c_str(), msg.length()); } }
4,412
C++
.cpp
105
37.87619
103
0.704376
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,646
gsm_message_processor.cpp
anbox_anbox/src/anbox/qemu/gsm_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/gsm_message_processor.h" #include "anbox/logger.h" #include "anbox/qemu/at_parser.h" #include <algorithm> #include <functional> using namespace std::placeholders; namespace anbox::qemu { GsmMessageProcessor::GsmMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : messenger_(messenger), parser_(std::make_shared<AtParser>()) { auto ok_reply = [&](const std::string &) { send_reply("OK"); }; parser_->register_command("E0Q0V1", ok_reply); parser_->register_command("S0=0", ok_reply); parser_->register_command( "+CTEC", std::bind(&GsmMessageProcessor::handle_ctec, this, _1)); parser_->register_command("+CMEE=1", ok_reply); parser_->register_command("+CCWA=1", ok_reply); parser_->register_command("+CMOD=0", ok_reply); parser_->register_command("+CMUT=0", ok_reply); parser_->register_command("+CSSN=0,1", ok_reply); parser_->register_command("+COLP=0", ok_reply); parser_->register_command("+CSCS=\"HEX\"", ok_reply); parser_->register_command("+CUSD=1", ok_reply); parser_->register_command("+CGEREP=1,0", ok_reply); parser_->register_command( "+CMGF", std::bind(&GsmMessageProcessor::handle_cmgf, this, _1)); parser_->register_command("%CPI=3", ok_reply); parser_->register_command("%CSTAT=1", ok_reply); parser_->register_command( "+CREG", std::bind(&GsmMessageProcessor::handle_creg, this, _1)); parser_->register_command( "+CGREG", std::bind(&GsmMessageProcessor::handle_cgreg, this, _1)); parser_->register_command( "+CFUN", std::bind(&GsmMessageProcessor::handle_cfun, this, _1)); } GsmMessageProcessor::~GsmMessageProcessor() {} bool GsmMessageProcessor::process_data(const std::vector<std::uint8_t> &data) { for (const auto &byte : data) buffer_.push_back(byte); parser_->process_data(buffer_); return true; } void GsmMessageProcessor::send_reply(const std::string &message) { auto reply = utils::string_format("%s\rOK\n", message); std::vector<std::uint8_t> data; std::copy(reply.begin(), reply.end(), std::back_inserter(data)); messenger_->send(reinterpret_cast<const char *>(data.data()), data.size()); } void GsmMessageProcessor::handle_ctec(const std::string &command) { if (command == "+CTEC=?") send_reply("+CTEC: 0,1,2,3"); else if (command == "+CTEC?") send_reply(utils::string_format( "+CTEC: %d,%x", static_cast<unsigned int>(technology::gsm), 0x0f)); } void GsmMessageProcessor::handle_cmgf(const std::string &command) { if (command == "+CMGF=0") send_reply(""); } void GsmMessageProcessor::handle_creg(const std::string &command) { if (command == "+CREG=?") send_reply("+CREG: (0-2)"); else if (command == "+CREG?") send_reply(utils::string_format("+CREF: %d,%d", 0, 0)); else if (utils::string_starts_with(command, "+CREG=")) send_reply(""); } void GsmMessageProcessor::handle_cgreg(const std::string &command) { if (command == "+CGREG=?") send_reply("+CGREG: (0-2)"); else if (command == "+CGREG?") send_reply(utils::string_format("+CGREG: %d,%d", 0, 0)); else if (utils::string_starts_with(command, "+CGREG=")) send_reply(""); } void GsmMessageProcessor::handle_cfun(const std::string &command) { if (command == "+CFUN?") send_reply(utils::string_format("+CFUN: %d", 1)); else if (utils::string_starts_with(command, "+CFUN=")) send_reply(""); } }
4,069
C++
.cpp
96
39.427083
79
0.689899
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,647
null_message_processor.cpp
anbox_anbox/src/anbox/qemu/null_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/null_message_processor.h" #include "anbox/logger.h" #include "anbox/utils.h" #include <string.h> namespace anbox::qemu { NullMessageProcessor::NullMessageProcessor() {} NullMessageProcessor::~NullMessageProcessor() {} bool NullMessageProcessor::process_data(const std::vector<std::uint8_t> &data) { (void)data; return true; } }
1,031
C++
.cpp
28
35
80
0.765766
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,649
fingerprint_message_processor.cpp
anbox_anbox/src/anbox/qemu/fingerprint_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/fingerprint_message_processor.h" #include "anbox/logger.h" namespace anbox::qemu { FingerprintMessageProcessor::FingerprintMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : QemudMessageProcessor(messenger) {} FingerprintMessageProcessor::~FingerprintMessageProcessor() {} void FingerprintMessageProcessor::handle_command(const std::string &command) { if (command == "listen") listen(); } void FingerprintMessageProcessor::listen() { char buf[12]; snprintf(buf, sizeof(buf), "off"); send_header(strlen(buf)); messenger_->send(buf, strlen(buf)); finish_message(); } }
1,315
C++
.cpp
34
36.529412
78
0.765857
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,650
boot_properties_message_processor.cpp
anbox_anbox/src/anbox/qemu/boot_properties_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu//boot_properties_message_processor.h" #include "anbox/graphics/density.h" #include "anbox/utils.h" namespace anbox::qemu { BootPropertiesMessageProcessor::BootPropertiesMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : QemudMessageProcessor(messenger) {} BootPropertiesMessageProcessor::~BootPropertiesMessageProcessor() {} void BootPropertiesMessageProcessor::handle_command( const std::string &command) { if (command == "list") list_properties(); } void BootPropertiesMessageProcessor::list_properties() { std::vector<std::string> properties = { // TODO(morphis): Using HDPI here for now but should be adjusted to the // device we're running on utils::string_format("ro.sf.lcd_density=%d", static_cast<int>(graphics::current_density())), }; for (const auto &prop : properties) { send_header(prop.length()); messenger_->send(prop.c_str(), prop.length()); } finish_message(); } }
1,661
C++
.cpp
41
37.780488
98
0.749071
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,651
hwcontrol_message_processor.cpp
anbox_anbox/src/anbox/qemu/hwcontrol_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/hwcontrol_message_processor.h" #include "anbox/logger.h" namespace anbox::qemu { HwControlMessageProcessor::HwControlMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : QemudMessageProcessor(messenger) {} HwControlMessageProcessor::~HwControlMessageProcessor() {} void HwControlMessageProcessor::handle_command(const std::string &command) { #if 0 if (command == "power:screen_state:wake") DEBUG("Got screen wake command"); else if (command == "power:screen_state:standby") DEBUG("Got screen standby command"); else if (utils::string_starts_with(command, "power:light:brightness:lcd_backlight")) DEBUG("Got LCD backligh brightness control command"); else DEBUG("Unknown command '%s'", command); #else (void)command; #endif } }
1,510
C++
.cpp
38
36.736842
88
0.748809
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,652
bootanimation_message_processor.cpp
anbox_anbox/src/anbox/qemu/bootanimation_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu//bootanimation_message_processor.h" #include "anbox/logger.h" #include <fstream> namespace anbox::qemu { BootAnimationMessageProcessor::BootAnimationMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger, const std::string &icon_path) : QemudMessageProcessor(messenger), icon_path_(icon_path) {} BootAnimationMessageProcessor::~BootAnimationMessageProcessor() {} void BootAnimationMessageProcessor::handle_command(const std::string &command) { if (command == "retrieve-icon") retrieve_icon(); } void BootAnimationMessageProcessor::retrieve_icon() { std::ifstream icon_file(icon_path_, std::ifstream::binary); std::array<char, 1024> buffer; while (icon_file.read(buffer.data(), buffer.size())) { const auto bytes_read = icon_file.gcount(); messenger_->send(buffer.data(), bytes_read); DEBUG("Sending %d bytes", bytes_read); } } }
1,587
C++
.cpp
38
39.289474
80
0.756809
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,653
gps_message_processor.cpp
anbox_anbox/src/anbox/qemu/gps_message_processor.cpp
/* * Copyright (C) 2020 Tomasz Grobelny <tomasz@grobelny.net> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/gps_message_processor.h" #include <string.h> #include "anbox/logger.h" namespace anbox::qemu { GpsMessageProcessor::GpsMessageProcessor(const std::shared_ptr<network::SocketMessenger> &messenger, const std::shared_ptr<anbox::application::GpsInfoBroker> &gpsInfoBroker) : messenger_(messenger), gps_info_broker_(gpsInfoBroker) { connection_ = gps_info_broker_->newNmeaSentence.connect([this](const std::string &sentence) { auto dataToSend = sentence + "\n"; messenger_->send(dataToSend.data(), dataToSend.length()); }); } GpsMessageProcessor::~GpsMessageProcessor() { gps_info_broker_->newNmeaSentence.disconnect(connection_); } bool GpsMessageProcessor::process_data(const std::vector<std::uint8_t> &data) { ERROR("Got unexpected GPS data: " + std::to_string(data.size())); return true; } }
1,515
C++
.cpp
34
42.441176
232
0.75813
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
17,654
at_parser.cpp
anbox_anbox/src/anbox/qemu/at_parser.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu//at_parser.h" #include "anbox/logger.h" #include "anbox/utils.h" namespace anbox::qemu { AtParser::AtParser() {} void AtParser::register_command(const std::string &command, CommandHandler handler) { handlers_.insert({command, handler}); } void AtParser::process_data(std::vector<std::uint8_t> &data) { size_t bytes_processed = 0; for (size_t pos = 0; pos < data.size();) { const auto byte = data.at(pos); if (byte == '\n' || byte == '\r') { std::string command; command.insert( 0, reinterpret_cast<const char *>(data.data()) + bytes_processed, pos - bytes_processed); bytes_processed += (pos - bytes_processed) + 1; processs_command(command); } pos++; } data.erase(data.begin(), data.begin() + bytes_processed); } void AtParser::processs_command(const std::string &command) { if (!utils::string_starts_with(command, "AT")) { WARNING("Invalid AT command: '%s'", command); return; } // Strip AT prefix from command auto real_command = command.substr(2, command.length() - 2); DEBUG("command: %s", real_command); CommandHandler handler = nullptr; for (const auto &iter : handlers_) { if (utils::string_starts_with(real_command, iter.first)) { handler = iter.second; break; } } if (!handler) { WARNING("No handler for command '%s' available", real_command); return; } handler(real_command); } }
2,156
C++
.cpp
63
30.285714
76
0.676908
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,655
adb_message_processor.cpp
anbox_anbox/src/anbox/qemu/adb_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/adb_message_processor.h" #include "anbox/network/delegate_connection_creator.h" #include "anbox/network/delegate_message_processor.h" #include "anbox/network/tcp_socket_messenger.h" #include "anbox/utils.h" #include <fstream> #include <functional> namespace { const unsigned short default_adb_client_port{5037}; // For the listening port we have to use an odd port in the 5555-5585 range so // the host can find us on start. See // https://developer.android.com/studio/command-line/adb.html. const unsigned short default_host_listen_port{5559}; constexpr const char *loopback_address{"127.0.0.1"}; const std::string accept_command{"accept"}; const std::string ok_command{"ok"}; const std::string ko_command{"ko"}; const std::string start_command{"start"}; // This timeount should be too high to not cause a too long wait time for the // user until we connect to the adb host instance after it appeared and not // too short to not put unnecessary burden on the CPU. const boost::posix_time::seconds default_adb_wait_time{1}; } using namespace std::placeholders; namespace anbox::qemu { std::mutex AdbMessageProcessor::active_instance_{}; AdbMessageProcessor::AdbMessageProcessor( const std::shared_ptr<Runtime> &rt, const std::shared_ptr<network::SocketMessenger> &messenger) : runtime_(rt), state_(waiting_for_guest_accept_command), expected_command_(accept_command), messenger_(messenger), lock_(active_instance_, std::defer_lock) { } AdbMessageProcessor::~AdbMessageProcessor() { state_ = closed_by_host; host_connector_.reset(); } void AdbMessageProcessor::advance_state() { switch (state_) { case waiting_for_guest_accept_command: // Try to get a lock here as if we already have another processor // running we don't have to do anything here until that one is done. // The container directly starts a second connection once the first // one is established but will not use it until the active one is closed. lock_.lock(); if (state_ == closed_by_host) { host_connector_.reset(); return; } wait_for_host_connection(); break; case waiting_for_host_connection: messenger_->send(reinterpret_cast<const char *>(ok_command.data()), ok_command.size()); state_ = waiting_for_guest_start_command; expected_command_ = start_command; break; case waiting_for_guest_start_command: state_ = proxying_data; read_next_host_message(); break; case proxying_data: break; case closed_by_host: // Close the connection to the container as our adb host connection // turned down. The container will try to establish a connection // immediately again and we will handle that by waiting for the // host adb to run up again. messenger_->close(); break; case closed_by_container: // In this case the container will close the pipe connection and this // message processor will be deleted once the owning socket connection // is closed. break; default: break; } } void AdbMessageProcessor::wait_for_host_connection() { if (state_ != waiting_for_guest_accept_command) return; if (!host_connector_) { host_connector_ = std::make_shared<network::TcpSocketConnector>( boost::asio::ip::address_v4::from_string(loopback_address), default_host_listen_port, runtime_, std::make_shared< network::DelegateConnectionCreator<boost::asio::ip::tcp>>( std::bind(&AdbMessageProcessor::on_host_connection, this, _1))); } try { // Notify the adb host instance so that it knows on which port our // proxy is waiting for incoming connections. auto messenger = std::make_shared<network::TcpSocketMessenger>( boost::asio::ip::address_v4::from_string(loopback_address), default_adb_client_port, runtime_); auto message = utils::string_format("host:emulator:%d", default_host_listen_port); auto handshake = utils::string_format("%04x%s", message.size(), message.c_str()); messenger->send(handshake.data(), handshake.size()); } catch (...) { // Server not up. No problem, it will contact us when started. } } void AdbMessageProcessor::on_host_connection(std::shared_ptr<boost::asio::basic_stream_socket<boost::asio::ip::tcp>> const &socket) { host_messenger_ = std::make_shared<network::TcpSocketMessenger>(socket); // set_no_delay() reduces the latency of sending data, at the cost // of creating more TCP packets on the connection. It's useful when // doing lots of small send() calls, like the ADB protocol requires. // And since this is on localhost, the packet increase should not be // noticeable. host_messenger_->set_no_delay(); // Let adb inside the container know that we have a connection to // the adb host instance messenger_->send(reinterpret_cast<const char *>(ok_command.data()), ok_command.size()); state_ = waiting_for_guest_start_command; expected_command_ = start_command; } void AdbMessageProcessor::read_next_host_message() { auto callback = std::bind(&AdbMessageProcessor::on_host_read_size, this, _1, _2); host_messenger_->async_receive_msg(callback, boost::asio::buffer(host_buffer_)); } void AdbMessageProcessor::on_host_read_size(const boost::system::error_code &error, std::size_t bytes_read) { if (error) { // When AdbMessageProcessor is destroyed on program termination, the sockets // are closed and the standing operations are canceled. But, the callback is // still called even in that case, and the object has already been // deleted. We detect that condition by looking at the error code and avoid // touching *this in that case. if (error == boost::system::errc::operation_canceled) return; // For other errors, we assume the connection with the host is dropped. We // close the connection to the container's adbd, which will trigger the // deletion of this AdbMessageProcessor instance and free resources (most // importantly, default_host_listen_port and the lock). The standing // connection that adbd opened can then proceed and wait for the host to be // up again. state_ = closed_by_host; messenger_->close(); return; } messenger_->send(reinterpret_cast<const char *>(host_buffer_.data()), bytes_read); read_next_host_message(); } bool AdbMessageProcessor::process_data(const std::vector<std::uint8_t> &data) { if (state_ == proxying_data) { host_messenger_->send(reinterpret_cast<const char *>(data.data()), data.size()); return true; } for (const auto &byte : data) buffer_.push_back(byte); if (expected_command_.size() > 0 && buffer_.size() >= expected_command_.size()) { if (::memcmp(buffer_.data(), expected_command_.data(), data.size()) != 0) { // We got not the command we expected and will terminate here return false; } buffer_.erase(buffer_.begin(), buffer_.begin() + expected_command_.size()); expected_command_.clear(); advance_state(); } return true; } }
7,851
C++
.cpp
180
39.222222
133
0.707091
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,656
telephony_manager.cpp
anbox_anbox/src/anbox/qemu/telephony_manager.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/telephony_manager.h" #include "anbox/dbus/ofono.h" #include "anbox/logger.h" namespace anbox::qemu { TelephonyManager::TelephonyManager(const core::dbus::Bus::Ptr &bus) : bus_(bus) { ofono_ = core::dbus::Service::use_service(bus_, "org.ofono"); modem_ = ofono_->object_for_path({"/ril_0"}); auto netreg_prop_changed = modem_->get_signal< org::ofono::NetworkRegistration::Signals::PropertyChanged>(); netreg_prop_changed->connect( [&](const org::ofono::NetworkRegistration::Signals::PropertyChanged:: ArgumentType &arguments) { DEBUG("org::ofono::NetworkRegistration::PropertyChanged"); }); } TelephonyManager::~TelephonyManager() {} }
1,385
C++
.cpp
34
37.676471
76
0.727745
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,657
camera_message_processor.cpp
anbox_anbox/src/anbox/qemu/camera_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/qemu/camera_message_processor.h" #include "anbox/logger.h" namespace anbox::qemu { CameraMessageProcessor::CameraMessageProcessor( const std::shared_ptr<network::SocketMessenger> &messenger) : messenger_(messenger) {} CameraMessageProcessor::~CameraMessageProcessor() {} bool CameraMessageProcessor::process_data( const std::vector<std::uint8_t> &data) { for (const auto &byte : data) buffer_.push_back(byte); process_commands(); return true; } void CameraMessageProcessor::process_commands() { while (buffer_.size() > 0) { size_t size = 0; while (size < buffer_.size()) { if (buffer_.at(size) == 0x0) break; size++; } std::string command; command.insert(0, reinterpret_cast<const char *>(buffer_.data()), size); buffer_.erase(buffer_.begin(), buffer_.begin() + size + 1); handle_command(command); } } void CameraMessageProcessor::handle_command(const std::string &command) { if (command == "list") list(); } void CameraMessageProcessor::list() { char buf[5]; snprintf(buf, 5, "\n"); messenger_->send(buf, strlen(buf)); } }
1,794
C++
.cpp
51
32.313725
76
0.719561
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,659
platform.cpp
anbox_anbox/src/anbox/platform/sdl/platform.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wswitch-default" #include "anbox/platform/sdl/platform.h" #include "anbox/input/device.h" #include "anbox/input/manager.h" #include "anbox/logger.h" #include "anbox/platform/sdl/keycode_converter.h" #include "anbox/platform/sdl/window.h" #include "anbox/platform/sdl/audio_sink.h" #include "anbox/wm/manager.h" #include <boost/throw_exception.hpp> #include <signal.h> #include <sys/types.h> #pragma GCC diagnostic pop namespace anbox::platform::sdl { Platform::Platform( const std::shared_ptr<input::Manager> &input_manager, const Configuration &config) : input_manager_(input_manager), event_thread_running_(false), config_(config) { // Don't block the screensaver from kicking in. It will be blocked // by the desktop shell already and we don't have to do this again. // If we would leave this enabled it will prevent systems from // suspending correctly. SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1"); #ifdef SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR // Don't disable compositing // Available since SDL 2.0.8 SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0"); #endif #ifdef SDL_HINT_TOUCH_MOUSE_EVENTS // Don't emulate mouse events from touch, we're handling touch ourselves. // Available since SDL 2.0.10 SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); #endif auto sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_EVENTS; if (config_.rootless) sdl_init_flags = SDL_INIT_AUDIO | SDL_INIT_EVENTS; if (SDL_Init(sdl_init_flags) < 0) { const auto message = utils::string_format("Failed to initialize SDL: %s", SDL_GetError()); BOOST_THROW_EXCEPTION(std::runtime_error(message)); } auto display_frame = graphics::Rect::Invalid; if (config_.display_frame == graphics::Rect::Invalid) { // We would need to init video to fetch display info if (config_.rootless) SDL_VideoInit(NULL); for (auto n = 0; n < SDL_GetNumVideoDisplays(); n++) { SDL_Rect r; if (SDL_GetDisplayBounds(n, &r) != 0) continue; graphics::Rect frame{r.x, r.y, r.x + r.w, r.y + r.h}; if (display_frame == graphics::Rect::Invalid) display_frame = frame; else display_frame.merge(frame); } if (config_.rootless) SDL_VideoQuit(); if (display_frame == graphics::Rect::Invalid) BOOST_THROW_EXCEPTION( std::runtime_error("No valid display configuration found")); } else { display_frame = config_.display_frame; window_size_immutable_ = true; } graphics::emugl::DisplayInfo::get()->set_resolution(display_frame.width(), display_frame.height()); display_frame_ = display_frame; pointer_ = input_manager->create_device(); pointer_->set_name("anbox-pointer"); pointer_->set_driver_version(1); pointer_->set_input_id({BUS_VIRTUAL, 2, 2, 2}); pointer_->set_physical_location("none"); pointer_->set_key_bit(BTN_MOUSE); // NOTE: We don't use REL_X/REL_Y in reality but have to specify them here // to allow InputFlinger to detect we're a cursor device. pointer_->set_rel_bit(REL_X); pointer_->set_rel_bit(REL_Y); pointer_->set_rel_bit(REL_HWHEEL); pointer_->set_rel_bit(REL_WHEEL); pointer_->set_prop_bit(INPUT_PROP_POINTER); keyboard_ = input_manager->create_device(); keyboard_->set_name("anbox-keyboard"); keyboard_->set_driver_version(1); keyboard_->set_input_id({BUS_VIRTUAL, 3, 3, 3}); keyboard_->set_physical_location("none"); keyboard_->set_key_bit(BTN_MISC); keyboard_->set_key_bit(KEY_OK); touch_ = input_manager->create_device(); touch_->set_name("anbox-touch"); touch_->set_driver_version(1); touch_->set_input_id({BUS_VIRTUAL, 4, 4, 4}); touch_->set_physical_location("none"); touch_->set_abs_bit(ABS_MT_SLOT); touch_->set_abs_max(ABS_MT_SLOT, 10); touch_->set_abs_bit(ABS_MT_TOUCH_MAJOR); touch_->set_abs_max(ABS_MT_TOUCH_MAJOR, 127); touch_->set_abs_bit(ABS_MT_TOUCH_MINOR); touch_->set_abs_max(ABS_MT_TOUCH_MINOR, 127); touch_->set_abs_bit(ABS_MT_POSITION_X); touch_->set_abs_max(ABS_MT_POSITION_X, display_frame.width()); touch_->set_abs_bit(ABS_MT_POSITION_Y); touch_->set_abs_max(ABS_MT_POSITION_Y, display_frame.height()); touch_->set_abs_bit(ABS_MT_TRACKING_ID); touch_->set_abs_max(ABS_MT_TRACKING_ID, MAX_TRACKING_ID); touch_->set_prop_bit(INPUT_PROP_DIRECT); for (int i = 0; i < MAX_FINGERS; i++) touch_slots[i] = -1; event_thread_ = std::thread(&Platform::process_events, this); } Platform::~Platform() { if (event_thread_running_) { event_thread_running_ = false; event_thread_.join(); } } void Platform::set_renderer(const std::shared_ptr<Renderer> &renderer) { renderer_ = renderer; } void Platform::set_window_manager(const std::shared_ptr<wm::Manager> &window_manager) { window_manager_ = window_manager; } void Platform::process_events() { event_thread_running_ = true; while (event_thread_running_) { SDL_Event event; while (SDL_WaitEventTimeout(&event, 100)) { switch (event.type) { case SDL_QUIT: video_has_been_closed_ = true; DEBUG("SDL_QUIT"); break; case SDL_WINDOWEVENT: for (auto &iter : windows_) { if (auto w = iter.second.lock()) { if (w->window_id() == event.window.windowID) { w->process_event(event); break; } } } break; case SDL_KEYDOWN: case SDL_KEYUP: if (keyboard_) process_input_event(event); break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: process_input_event(event); break; default: break; } } } } void Platform::process_input_event(const SDL_Event &event) { std::vector<input::Event> mouse_events; std::vector<input::Event> keyboard_events; std::vector<input::Event> touch_events; std::int32_t x = 0; std::int32_t y = 0; switch (event.type) { // Mouse case SDL_MOUSEBUTTONDOWN: if (config_.no_touch_emulation) { mouse_events.push_back({EV_KEY, BTN_LEFT, 1}); } else { x = event.button.x; y = event.button.y; if (!adjust_coordinates(x, y)) break; push_finger_down(x, y, emulated_touch_id_, touch_events); } break; case SDL_MOUSEBUTTONUP: if (config_.no_touch_emulation) { mouse_events.push_back({EV_KEY, BTN_LEFT, 0}); } else { push_finger_up(emulated_touch_id_, touch_events); } break; case SDL_MOUSEMOTION: x = event.motion.x; y = event.motion.y; if (!adjust_coordinates(x, y)) break; if (config_.no_touch_emulation) { // NOTE: Sending relative move events doesn't really work and we have // changes in libinputflinger to take ABS_X/ABS_Y instead for absolute // position events. mouse_events.push_back({EV_ABS, ABS_X, x}); mouse_events.push_back({EV_ABS, ABS_Y, y}); // We're sending relative position updates here too but they will be only // used by the Android side EventHub/InputReader to determine if the cursor // was moved. They are not used to find out the exact position. mouse_events.push_back({EV_REL, REL_X, event.motion.xrel}); mouse_events.push_back({EV_REL, REL_Y, event.motion.yrel}); } else { push_finger_motion(x, y, emulated_touch_id_, touch_events); } break; case SDL_MOUSEWHEEL: if (!config_.no_touch_emulation) { SDL_GetMouseState(&x, &y); if (!adjust_coordinates(x, y)) break; mouse_events.push_back({EV_ABS, ABS_X, x}); mouse_events.push_back({EV_ABS, ABS_Y, y}); } mouse_events.push_back( {EV_REL, REL_WHEEL, static_cast<std::int32_t>(event.wheel.y)}); break; // Keyboard case SDL_KEYDOWN: { const auto code = KeycodeConverter::convert(event.key.keysym.scancode); if (code == KEY_RESERVED) break; keyboard_events.push_back({EV_KEY, code, 1}); break; } case SDL_KEYUP: { const auto code = KeycodeConverter::convert(event.key.keysym.scancode); if (code == KEY_RESERVED) break; keyboard_events.push_back({EV_KEY, code, 0}); break; } // Touch screen case SDL_FINGERDOWN: { if (!calculate_touch_coordinates(event, x, y)) break; push_finger_down(x, y, event.tfinger.fingerId, touch_events); break; } case SDL_FINGERUP: { push_finger_up(event.tfinger.fingerId, touch_events); break; } case SDL_FINGERMOTION: { if (!calculate_touch_coordinates(event, x, y)) break; push_finger_motion(x, y, event.tfinger.fingerId, touch_events); break; } default: break; } if (mouse_events.size() > 0) { mouse_events.push_back({EV_SYN, SYN_REPORT, 0}); pointer_->send_events(mouse_events); } if (keyboard_events.size() > 0) keyboard_->send_events(keyboard_events); if (touch_events.size() > 0) touch_->send_events(touch_events); } int Platform::find_touch_slot(int id){ for (int i = 0; i < MAX_FINGERS; i++) { if (touch_slots[i] == id) return i; } return -1; } void Platform::push_slot(std::vector<input::Event> &touch_events, int slot){ if (last_slot != slot) { touch_events.push_back({EV_ABS, ABS_MT_SLOT, slot}); last_slot = slot; } } void Platform::push_finger_down(int x, int y, int finger_id, std::vector<input::Event> &touch_events){ int slot = find_touch_slot(-1); if (slot == -1) { DEBUG("no free slot!"); return; } touch_slots[slot] = finger_id; push_slot(touch_events, slot); touch_events.push_back({EV_ABS, ABS_MT_TRACKING_ID, static_cast<std::int32_t>(finger_id % MAX_TRACKING_ID + 1)}); touch_events.push_back({EV_ABS, ABS_MT_POSITION_X, x}); touch_events.push_back({EV_ABS, ABS_MT_POSITION_Y, y}); touch_events.push_back({EV_SYN, SYN_REPORT, 0}); } void Platform::push_finger_up(int finger_id, std::vector<input::Event> &touch_events){ int slot = find_touch_slot(finger_id); if (slot == -1) return; push_slot(touch_events, slot); touch_events.push_back({EV_ABS, ABS_MT_TRACKING_ID, -1}); touch_events.push_back({EV_SYN, SYN_REPORT, 0}); touch_slots[slot] = -1; } void Platform::push_finger_motion(int x, int y, int finger_id, std::vector<input::Event> &touch_events){ int slot = find_touch_slot(finger_id); if (slot == -1) return; push_slot(touch_events, slot); touch_events.push_back({EV_ABS, ABS_MT_POSITION_X, x}); touch_events.push_back({EV_ABS, ABS_MT_POSITION_Y, y}); touch_events.push_back({EV_SYN, SYN_REPORT, 0}); } bool Platform::adjust_coordinates(std::int32_t &x, std::int32_t &y) { SDL_Window *window = nullptr; if (!config_.single_window) { window = SDL_GetWindowFromID(focused_sdl_window_id_); return adjust_coordinates(window, x, y); } else { // When running the whole Android system in a single window we don't // need to reacalculate and the pointer position as they are already // relative to our window. return true; } } bool Platform::adjust_coordinates(SDL_Window *window, std::int32_t &x, std::int32_t &y) { std::int32_t rel_x = 0; std::int32_t rel_y = 0; if (!window) { return false; } // As we get only absolute coordindates relative to our window we have to // calculate the correct position based on the current focused window SDL_GetWindowPosition(window, &rel_x, &rel_y); x += rel_x; y += rel_y; return true; } bool Platform::calculate_touch_coordinates(const SDL_Event &event, std::int32_t &x, std::int32_t &y) { SDL_Window *window = nullptr; window = SDL_GetWindowFromID(focused_sdl_window_id_); // before SDL 2.0.7 on X11 tfinger coordinates are not normalized if (!SDL_VERSION_ATLEAST(2,0,7) && (event.tfinger.x > 1 || event.tfinger.y > 1)) { x = event.tfinger.x; y = event.tfinger.y; } else { if (window) { SDL_GetWindowSize(window, &x, &y); x *= event.tfinger.x; y *= event.tfinger.y; } else { x = display_frame_.width() * event.tfinger.x; y = display_frame_.height() * event.tfinger.y; } } if (config_.single_window) { // When running the whole Android system in a single window we don't // need to reacalculate and the pointer position as they are already // relative to our window. return true; } else { return adjust_coordinates(window, x, y); } } Window::Id Platform::next_window_id() { static Window::Id next_id = 0; return next_id++; } std::shared_ptr<wm::Window> Platform::create_window( const anbox::wm::Task::Id &task, const anbox::graphics::Rect &frame, const std::string &title) { if (!renderer_) { ERROR("Can't create window without a renderer set"); return nullptr; } // Force video init again after sdl has closed if (config_.rootless && video_has_been_closed_) { DEBUG("forcing video init"); SDL_VideoInit(NULL); video_has_been_closed_ = false; } auto id = next_window_id(); auto w = std::make_shared<Window>(renderer_, id, task, shared_from_this(), frame, title, !window_size_immutable_, !config_.server_side_decoration); focused_sdl_window_id_ = w->window_id(); windows_.insert({id, w}); return w; } void Platform::window_deleted(const Window::Id &id) { auto w = windows_.find(id); if (w == windows_.end()) { WARNING("Got window removed event for unknown window (id %d)", id); return; } if (auto window = w->second.lock()) window_manager_->remove_task(window->task()); windows_.erase(w); } void Platform::window_wants_focus(const Window::Id &id) { auto w = windows_.find(id); if (w == windows_.end()) return; if (auto window = w->second.lock()) { focused_sdl_window_id_ = window->window_id(); window_manager_->set_focused_task(window->task()); } } void Platform::window_moved(const Window::Id &id, const std::int32_t &x, const std::int32_t &y) { auto w = windows_.find(id); if (w == windows_.end()) return; if (auto window = w->second.lock()) { auto new_frame = window->frame(); new_frame.translate(x, y); window->update_frame(new_frame); window_manager_->resize_task(window->task(), new_frame, 3); } } void Platform::window_resized(const Window::Id &id, const std::int32_t &width, const std::int32_t &height) { auto w = windows_.find(id); if (w == windows_.end()) return; if (auto window = w->second.lock()) { auto new_frame = window->frame(); new_frame.resize(width, height); // We need to update the window frame in advance here as otherwise we may // get a movement event before we got an update of the actual layer // representing this window and then we're back to the original size of // the task. window->update_frame(new_frame); window_manager_->resize_task(window->task(), new_frame, 3); } } void Platform::set_clipboard_data(const ClipboardData &data) { if (data.text.empty()) return; SDL_SetClipboardText(data.text.c_str()); } Platform::ClipboardData Platform::get_clipboard_data() { if (!SDL_HasClipboardText()) return ClipboardData{}; auto text = SDL_GetClipboardText(); if (!text) return ClipboardData{}; auto data = ClipboardData{text}; SDL_free(text); return data; } std::shared_ptr<audio::Sink> Platform::create_audio_sink() { return std::make_shared<AudioSink>(); } std::shared_ptr<audio::Source> Platform::create_audio_source() { ERROR("Not implemented"); return nullptr; } bool Platform::supports_multi_window() const { return true; } }
16,833
C++
.cpp
466
30.963519
117
0.650984
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,660
mir_display_connection.cpp
anbox_anbox/src/anbox/platform/sdl/mir_display_connection.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/platform/sdlmir_display_connection.h" #include "anbox/logger.h" #include <boost/throw_exception.hpp> #include <stdexcept> #include <string> namespace { static const MirDisplayOutput *find_active_output( const MirDisplayConfiguration *conf) { const MirDisplayOutput *output = NULL; int d; for (d = 0; d < (int)conf->num_outputs; d++) { const MirDisplayOutput *out = conf->outputs + d; if (out->used && out->connected && out->num_modes && out->current_mode < out->num_modes) { output = out; break; } } return output; } } namespace anbox::sdl { MirDisplayConnection::MirDisplayConnection() : connection_(nullptr), output_id_(-1), vertical_resolution_(0), horizontal_resolution_(0) { auto xdg_runtime_dir = ::getenv("XDG_RUNTIME_DIR"); if (!xdg_runtime_dir) BOOST_THROW_EXCEPTION(std::runtime_error("Failed to find XDG_RUNTIME_DIR")); std::string socket_path = xdg_runtime_dir; socket_path += "/mir_socket"; connection_ = mir_connect_sync(socket_path.c_str(), "anbox"); if (!mir_connection_is_valid(connection_)) { std::string msg; msg += "Failed to connect with Mir server: "; msg += mir_connection_get_error_message(connection_); BOOST_THROW_EXCEPTION(std::runtime_error(msg.c_str())); } mir_connection_set_display_config_change_callback( connection_, [](MirConnection *connection, void *context) { auto thiz = reinterpret_cast<MirDisplayConnection *>(context); DEBUG(""); }, this); MirDisplayConfiguration *display_config = mir_connection_create_display_config(connection_); const MirDisplayOutput *output = find_active_output(display_config); if (!output) BOOST_THROW_EXCEPTION( std::runtime_error("Failed to find active output display")); DEBUG("Selecting output id %d", output->output_id); output_id_ = output->output_id; const MirDisplayMode *mode = &output->modes[output->current_mode]; vertical_resolution_ = mode->vertical_resolution; horizontal_resolution_ = mode->horizontal_resolution; mir_display_config_destroy(display_config); } MirDisplayConnection::~MirDisplayConnection() { mir_connection_release(connection_); } MirConnection *MirDisplayConnection::connection() const { return connection_; } MirPixelFormat MirDisplayConnection::default_pixel_format() const { MirPixelFormat format; unsigned int nformats; mir_connection_get_available_surface_formats(connection_, &format, 1, &nformats); return format; } EGLNativeDisplayType MirDisplayConnection::native_display() const { return mir_connection_get_egl_native_display(connection_); } int MirDisplayConnection::output_id() const { return output_id_; } int MirDisplayConnection::vertical_resolution() const { return vertical_resolution_; } int MirDisplayConnection::horizontal_resolution() const { return horizontal_resolution_; } }
3,653
C++
.cpp
97
33.762887
80
0.723181
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,663
audio_sink.cpp
anbox_anbox/src/anbox/platform/sdl/audio_sink.cpp
/* * Copyright (C) 2017 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/platform/sdl/audio_sink.h" #include "anbox/logger.h" #include <stdexcept> #include <boost/throw_exception.hpp> namespace { const constexpr size_t max_queue_size{16}; } namespace anbox::platform::sdl { AudioSink::AudioSink() : device_id_(0), queue_(max_queue_size) { } AudioSink::~AudioSink() {} void AudioSink::on_data_requested(void *user_data, std::uint8_t *buffer, int size) { auto thiz = static_cast<AudioSink*>(user_data); thiz->read_data(buffer, size); } bool AudioSink::connect_audio() { if (device_id_ > 0) return true; SDL_memset(&spec_, 0, sizeof(spec_)); spec_.freq = 44100; spec_.format = AUDIO_S16; spec_.channels = 2; spec_.samples = 1024; spec_.callback = &AudioSink::on_data_requested; spec_.userdata = this; device_id_ = SDL_OpenAudioDevice(nullptr, 0, &spec_, nullptr, 0); if (!device_id_) return false; SDL_PauseAudioDevice(device_id_, 0); return true; } void AudioSink::disconnect_audio() { if (device_id_ == 0) return; SDL_CloseAudioDevice(device_id_); device_id_ = 0; } void AudioSink::read_data(std::uint8_t *buffer, int size) { std::unique_lock<std::mutex> l(lock_); const auto wanted = size; int count = 0; auto dst = buffer; while (count < wanted) { if (read_buffer_left_ > 0) { size_t avail = std::min<size_t>(wanted - count, read_buffer_left_); memcpy(dst + count, read_buffer_.data() + (read_buffer_.size() - read_buffer_left_), avail); count += avail; read_buffer_left_ -= avail; continue; } bool blocking = (count == 0); auto result = -EIO; if (blocking) result = queue_.pop_locked(&read_buffer_, l); else result = queue_.try_pop_locked(&read_buffer_); if (result == 0) { read_buffer_left_ = read_buffer_.size(); continue; } if (count > 0) break; return; } } void AudioSink::write_data(const std::vector<std::uint8_t> &data) { std::unique_lock<std::mutex> l(lock_); if (!connect_audio()) { WARNING("Audio server not connected, skipping %d bytes", data.size()); return; } graphics::Buffer buffer{data.data(), data.data() + data.size()}; queue_.push_locked(std::move(buffer), l); } }
2,923
C++
.cpp
94
27.595745
84
0.673193
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,668
fd_socket_transmission.cpp
anbox_anbox/src/anbox/network/fd_socket_transmission.cpp
/* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authored by: Kevin DuBois <kevin.dubois@canonical.com> */ #include "anbox/network/fd_socket_transmission.h" #include "anbox/common/variable_length_array.h" #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <boost/exception/errinfo_errno.hpp> #include <boost/throw_exception.hpp> #include <stdexcept> namespace anbox { socket_error::socket_error(std::string const& message) : std::system_error(errno, std::system_category(), message) {} socket_disconnected_error::socket_disconnected_error(std::string const& message) : std::system_error(errno, std::system_category(), message) {} fd_reception_error::fd_reception_error(std::string const& message) : std::runtime_error(message) {} void send_fds(Fd const& socket, std::vector<Fd> const& fds) { if (fds.size() > 0) { // We send dummy data struct iovec iov; char dummy_iov_data = 'M'; iov.iov_base = &dummy_iov_data; iov.iov_len = 1; // Allocate space for control message static auto const builtin_n_fds = 5; static auto const builtin_cmsg_space = CMSG_SPACE(builtin_n_fds * sizeof(int)); auto const fds_bytes = fds.size() * sizeof(int); VariableLengthArray<builtin_cmsg_space> control{CMSG_SPACE(fds_bytes)}; // Silence valgrind uninitialized memory complaint memset(control.data(), 0, control.size()); // Message to send struct msghdr header; header.msg_name = NULL; header.msg_namelen = 0; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_controllen = control.size(); header.msg_control = control.data(); header.msg_flags = 0; // Control message contains file descriptors struct cmsghdr* message = CMSG_FIRSTHDR(&header); message->cmsg_len = CMSG_LEN(fds_bytes); message->cmsg_level = SOL_SOCKET; message->cmsg_type = SCM_RIGHTS; int* const data = reinterpret_cast<int*>(CMSG_DATA(message)); int i = 0; for (auto& fd : fds) data[i++] = fd; auto const sent = sendmsg(socket, &header, MSG_NOSIGNAL); if (sent < 0) BOOST_THROW_EXCEPTION(std::runtime_error("Failed to send fds: " + std::string(strerror(errno)))); } } bool socket_error_is_transient(int error_code) { return (error_code == EINTR); } void receive_data(Fd const& socket, void* buffer, size_t bytes_requested, std::vector<Fd>& fds) { if (bytes_requested == 0) BOOST_THROW_EXCEPTION(std::logic_error("Attempted to receive 0 bytes")); size_t bytes_read{0}; unsigned fds_read{0}; while (bytes_read < bytes_requested) { // Store the data in the buffer requested struct iovec iov; iov.iov_base = static_cast<uint8_t*>(buffer) + bytes_read; iov.iov_len = bytes_requested - bytes_read; // Allocate space for control message static auto const builtin_n_fds = 5; static auto const builtin_cmsg_space = CMSG_SPACE(builtin_n_fds * sizeof(int)); auto const fds_bytes = (fds.size() - fds_read) * sizeof(int); VariableLengthArray<builtin_cmsg_space> control{CMSG_SPACE(fds_bytes)}; // Message to read struct msghdr header; header.msg_name = NULL; header.msg_namelen = 0; header.msg_iov = &iov; header.msg_iovlen = 1; header.msg_controllen = control.size(); header.msg_control = control.data(); header.msg_flags = 0; ssize_t const result = recvmsg(socket, &header, MSG_NOSIGNAL | MSG_WAITALL); if (result == 0) BOOST_THROW_EXCEPTION(socket_disconnected_error( "Failed to read message from server: server has shutdown")); if (result < 0) { if (socket_error_is_transient(errno)) continue; if (errno == EAGAIN) continue; if (errno == EPIPE) BOOST_THROW_EXCEPTION( boost::enable_error_info( socket_disconnected_error("Failed to read message from server")) << boost::errinfo_errno(errno)); BOOST_THROW_EXCEPTION(boost::enable_error_info(socket_error( "Failed to read message from server")) << boost::errinfo_errno(errno)); } bytes_read += result; // If we get a proper control message, copy the received // file descriptors back to the caller struct cmsghdr const* const cmsg = CMSG_FIRSTHDR(&header); if (cmsg) { if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type == SCM_CREDENTIALS)) BOOST_THROW_EXCEPTION( fd_reception_error("received SCM_CREDENTIALS when expecting fd")); if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) BOOST_THROW_EXCEPTION(fd_reception_error( "Invalid control message for receiving file descriptors")); int const* const data = reinterpret_cast<int const*> CMSG_DATA(cmsg); ptrdiff_t const header_size = reinterpret_cast<char const*>(data) - reinterpret_cast<char const*>(cmsg); int const nfds = (cmsg->cmsg_len - header_size) / sizeof(int); // NOTE: This relies on the file descriptor cmsg being read // (and written) atomically. if (cmsg->cmsg_len > CMSG_LEN(fds_bytes) || (header.msg_flags & MSG_CTRUNC)) { for (int i = 0; i < nfds; i++) ::close(data[i]); BOOST_THROW_EXCEPTION( std::runtime_error("Received more fds than expected")); } // We can't properly pass Fds through google::protobuf::Message, // which is where these get shoved. // // When we have our own RPC generator plugin and aren't using deprecated // Protobuf features this can go away. for (int i = 0; i < nfds; i++) fds[fds_read + i] = Fd{IntOwnedFd{data[i]}}; fds_read += nfds; } } if (fds_read < fds.size()) { for (auto fd : fds) if (fd >= 0) ::close(fd); fds.clear(); BOOST_THROW_EXCEPTION( std::runtime_error("Received fewer fds than expected")); } } } // namespace anbox
6,655
C++
.cpp
156
36.532051
80
0.65709
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
17,669
delegate_message_processor.cpp
anbox_anbox/src/anbox/network/delegate_message_processor.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/network/delegate_message_processor.h" namespace anbox::network { DelegateMessageProcessor::DelegateMessageProcessor( std::function<bool(const std::vector<std::uint8_t> &)> process_data) : process_data_(process_data) {} DelegateMessageProcessor::~DelegateMessageProcessor() {} bool DelegateMessageProcessor::process_data( const std::vector<std::uint8_t> &data) { if (!process_data_) return false; return process_data_(data); } }
1,138
C++
.cpp
28
38.392857
76
0.761302
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,671
connection_context.cpp
anbox_anbox/src/anbox/network/connection_context.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/network/connection_context.h" namespace anbox::network { ConnectionContext::ConnectionContext( std::function<void()> const connect_handler, Connector const* connector) : connect_handler(connect_handler), connector(connector) {} }
932
C++
.cpp
22
40.136364
76
0.766004
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
17,673
credentials.cpp
anbox_anbox/src/anbox/network/credentials.cpp
/* * Copyright (C) 2016 Simon Fels <morphis@gravedo.de> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "anbox/network/credentials.h" namespace anbox::network { Credentials::Credentials(pid_t pid, uid_t uid, gid_t gid) : pid_{pid}, uid_{uid}, gid_{gid} {} pid_t Credentials::pid() const { return pid_; } uid_t Credentials::uid() const { return uid_; } gid_t Credentials::gid() const { return gid_; } }
989
C++
.cpp
24
39.25
76
0.736733
anbox/anbox
8,865
1,152
381
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false