1 /*
2 * Copyright (C) 2015 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 "shell_protocol.h"
18
19 #include <string.h>
20
21 #include <algorithm>
22
23 #include "adb_io.h"
24
ShellProtocol(borrowed_fd fd)25 ShellProtocol::ShellProtocol(borrowed_fd fd) : fd_(fd) {
26 buffer_[0] = kIdInvalid;
27 }
28
~ShellProtocol()29 ShellProtocol::~ShellProtocol() {
30 }
31
Read()32 bool ShellProtocol::Read() {
33 // Only read a new header if we've finished the last packet.
34 if (!bytes_left_) {
35 if (!ReadFdExactly(fd_, buffer_, kHeaderSize)) {
36 return false;
37 }
38
39 length_t packet_length;
40 memcpy(&packet_length, &buffer_[1], sizeof(packet_length));
41 bytes_left_ = packet_length;
42 data_length_ = 0;
43 }
44
45 size_t read_length = std::min(bytes_left_, data_capacity());
46 if (read_length && !ReadFdExactly(fd_, data(), read_length)) {
47 return false;
48 }
49
50 bytes_left_ -= read_length;
51 data_length_ = read_length;
52
53 return true;
54 }
55
Write(Id id,size_t length)56 bool ShellProtocol::Write(Id id, size_t length) {
57 buffer_[0] = id;
58 length_t typed_length = length;
59 memcpy(&buffer_[1], &typed_length, sizeof(typed_length));
60
61 return WriteFdExactly(fd_, buffer_, kHeaderSize + length);
62 }
63