1 /*
2 * Copyright (C) 2019 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 <https/Support.h>
18
19 #include <cassert>
20 #include <cstdint>
21 #include <cstdio>
22 #include <ctype.h>
23 #include <fcntl.h>
24 #include <iomanip>
25 #include <ios>
26 #include <iostream>
27 #include <sys/errno.h>
28 #include <sstream>
29
makeFdNonblocking(int fd)30 void makeFdNonblocking(int fd) {
31 int flags = fcntl(fd, F_GETFL, 0);
32 if (flags < 0) { flags = 0; }
33 DEBUG_ONLY(int res = )fcntl(fd, F_SETFL, flags | O_NONBLOCK);
34 assert(res >= 0);
35 }
36
hexdump(const void * _data,size_t size)37 std::string hexdump(const void* _data, size_t size) {
38 std::stringstream ss;
39 const uint8_t *data = static_cast<const uint8_t *>(_data);
40
41 size_t offset = 0;
42 while (offset < size) {
43 ss << "0x" << std::hex << std::setw(8) << std::setfill('0') << offset << ": ";
44
45 for (size_t col = 0; col < 16; ++col) {
46 if (offset + col < size) {
47 ss << std::setw(2) << static_cast<int>(data[offset + col]) << " ";
48 } else {
49 ss << " ";
50 }
51
52 if (col == 7) {
53 ss << " ";
54 }
55 }
56
57 ss << " ";
58
59 for (size_t col = 0; col < 16; ++col) {
60 if (offset + col < size && isprint(data[offset + col])) {
61 ss << static_cast<char>(data[offset + col]);
62 } else if (offset + col < size) {
63 ss << ".";
64 }
65 }
66
67 ss << std::endl;
68
69 offset += 16;
70 }
71 return ss.str();
72 }
73
U16_AT(const uint8_t * ptr)74 uint16_t U16_AT(const uint8_t *ptr) {
75 return ptr[0] << 8 | ptr[1];
76 }
77
U32_AT(const uint8_t * ptr)78 uint32_t U32_AT(const uint8_t *ptr) {
79 return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
80 }
81
U64_AT(const uint8_t * ptr)82 uint64_t U64_AT(const uint8_t *ptr) {
83 return ((uint64_t)U32_AT(ptr)) << 32 | U32_AT(ptr + 4);
84 }
85
U16LE_AT(const uint8_t * ptr)86 uint16_t U16LE_AT(const uint8_t *ptr) {
87 return ptr[0] | (ptr[1] << 8);
88 }
89
U32LE_AT(const uint8_t * ptr)90 uint32_t U32LE_AT(const uint8_t *ptr) {
91 return ptr[3] << 24 | ptr[2] << 16 | ptr[1] << 8 | ptr[0];
92 }
93
U64LE_AT(const uint8_t * ptr)94 uint64_t U64LE_AT(const uint8_t *ptr) {
95 return ((uint64_t)U32LE_AT(ptr + 4)) << 32 | U32LE_AT(ptr);
96 }
97
STR_AT(const uint8_t * ptr,size_t size)98 std::string STR_AT(const uint8_t *ptr, size_t size) {
99 return std::string((const char*)ptr, size);
100 }
101