blob: 1a746884b798e2aba3ae5ade66bacf11a3a1601f [file] [log] [blame]
Dan Albertcc731cc2015-02-24 21:26:58 -08001/*
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#define TRACE_TAG TRACE_RWX
18
19#include "sysdeps.h"
20#include "adb_io.h"
21
22#include <unistd.h>
23
24#include "adb_trace.h"
25#include "transport.h"
26
27bool ReadFdExactly(int fd, void* buf, size_t len) {
28 char* p = reinterpret_cast<char*>(buf);
29
30#if ADB_TRACE
31 size_t len0 = len;
32#endif
33
34 D("readx: fd=%d wanted=%zu\n", fd, len);
35 while (len > 0) {
Dan Albertbac34742015-02-25 17:51:28 -080036 int r = adb_read(fd, p, len);
Dan Albertcc731cc2015-02-24 21:26:58 -080037 if (r > 0) {
38 len -= r;
39 p += r;
40 } else if (r == -1) {
41 D("readx: fd=%d error %d: %s\n", fd, errno, strerror(errno));
42 return false;
43 } else {
44 D("readx: fd=%d disconnected\n", fd);
45 errno = 0;
46 return false;
47 }
48 }
49
50#if ADB_TRACE
51 D("readx: fd=%d wanted=%zu got=%zu\n", fd, len0, len0 - len);
52 if (ADB_TRACING) {
53 dump_hex(reinterpret_cast<const unsigned char*>(buf), len0);
54 }
55#endif
56
57 return true;
58}
59
60bool WriteFdExactly(int fd, const void* buf, size_t len) {
61 const char* p = reinterpret_cast<const char*>(buf);
62 int r;
63
64#if ADB_TRACE
65 D("writex: fd=%d len=%d: ", fd, (int)len);
66 if (ADB_TRACING) {
67 dump_hex(reinterpret_cast<const unsigned char*>(buf), len);
68 }
69#endif
70
71 while (len > 0) {
Dan Albertbac34742015-02-25 17:51:28 -080072 r = adb_write(fd, p, len);
Dan Albertcc731cc2015-02-24 21:26:58 -080073 if (r == -1) {
74 D("writex: fd=%d error %d: %s\n", fd, errno, strerror(errno));
75 if (errno == EAGAIN) {
76 adb_sleep_ms(1); // just yield some cpu time
77 continue;
78 } else if (errno == EPIPE) {
79 D("writex: fd=%d disconnected\n", fd);
80 errno = 0;
81 return false;
Dan Albert08f66bc2015-03-19 18:09:59 -070082 } else {
83 return false;
Dan Albertcc731cc2015-02-24 21:26:58 -080084 }
85 } else {
86 len -= r;
87 p += r;
88 }
89 }
90 return true;
91}
92
93bool WriteStringFully(int fd, const char* str) {
94 return WriteFdExactly(fd, str, strlen(str));
95}