blob: 95afaffe71a1341b7663233afc0ffef85699d7b3 [file] [log] [blame]
David Purselld0df2dd2015-08-31 15:36:18 -07001/*
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
Josh Gao076b5ba2018-07-25 16:07:26 -070017#include "shell_protocol.h"
David Purselld0df2dd2015-08-31 15:36:18 -070018
19#include <string.h>
20
21#include <algorithm>
22
23#include "adb_io.h"
24
Josh Gao90228a62019-04-25 14:04:57 -070025ShellProtocol::ShellProtocol(borrowed_fd fd) : fd_(fd) {
David Purselld0df2dd2015-08-31 15:36:18 -070026 buffer_[0] = kIdInvalid;
27}
28
29ShellProtocol::~ShellProtocol() {
30}
31
32bool 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
56bool 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}