1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "adbconnection/common.h"
18 
19 #include <sys/socket.h>
20 
21 #include <string_view>
22 
23 namespace {
24 using namespace std::string_view_literals;
25 constexpr std::string_view kJdwpControlName = "\0jdwp-control"sv;
26 static_assert(kJdwpControlName.size() <= sizeof(reinterpret_cast<sockaddr_un*>(0)->sun_path));
27 }  // namespace
28 
get_control_socket_addr()29 std::tuple<sockaddr_un, socklen_t> get_control_socket_addr() {
30   sockaddr_un addr = {};
31   addr.sun_family = AF_UNIX;
32   memcpy(addr.sun_path, kJdwpControlName.data(), kJdwpControlName.size());
33   socklen_t addrlen = offsetof(sockaddr_un, sun_path) + kJdwpControlName.size();
34 
35   return {addr, addrlen};
36 }
37 
toProtobuf() const38 adb::proto::ProcessEntry ProcessInfo::toProtobuf() const {
39   adb::proto::ProcessEntry process;
40   process.set_pid(pid);
41   process.set_user_id(user_id);
42   process.set_debuggable(debuggable);
43   process.set_profileable(profileable);
44   process.set_architecture(architecture);
45   process.set_process_name(process_name);
46   for (std::string package_name : package_names) {
47     process.add_package_names(package_name);
48   }
49   process.set_waiting_for_debugger(waiting_for_debugger);
50   process.set_uid(uid);
51   return process;
52 }
53 
parseProtobufString(const std::string & proto)54 std::optional<ProcessInfo> ProcessInfo::parseProtobufString(const std::string& proto) {
55   adb::proto::ProcessEntry process_entry_proto;
56   if (!process_entry_proto.ParseFromString(proto)) {
57     return {};
58   }
59 
60   ProcessInfo process_info;
61   process_info.pid = process_entry_proto.pid();
62   process_info.user_id = process_entry_proto.user_id();
63   process_info.debuggable = process_entry_proto.debuggable();
64   process_info.profileable = process_entry_proto.profileable();
65   process_info.architecture = process_entry_proto.architecture();
66   process_info.process_name = process_entry_proto.process_name();
67   for (int i = 0; i < process_entry_proto.package_names_size(); i++) {
68     process_info.package_names.insert(process_entry_proto.package_names(i));
69   }
70   process_info.waiting_for_debugger = process_entry_proto.waiting_for_debugger();
71   process_info.uid = process_entry_proto.uid();
72   return process_info;
73 }