Steven Moreland | f183fdd | 2020-10-27 00:12:12 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2020 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 "Utils.h" |
| 18 | |
Andrei Homescu | c24c879 | 2022-04-19 00:24:51 +0000 | [diff] [blame^] | 19 | #include <android-base/file.h> |
Steven Moreland | f183fdd | 2020-10-27 00:12:12 +0000 | [diff] [blame] | 20 | #include <string.h> |
| 21 | |
Yifan Hong | b675ffe | 2021-08-05 16:37:17 -0700 | [diff] [blame] | 22 | using android::base::ErrnoError; |
| 23 | using android::base::Result; |
| 24 | |
Steven Moreland | f183fdd | 2020-10-27 00:12:12 +0000 | [diff] [blame] | 25 | namespace android { |
| 26 | |
| 27 | void zeroMemory(uint8_t* data, size_t size) { |
| 28 | memset(data, 0, size); |
| 29 | } |
| 30 | |
Yifan Hong | b675ffe | 2021-08-05 16:37:17 -0700 | [diff] [blame] | 31 | Result<void> setNonBlocking(android::base::borrowed_fd fd) { |
| 32 | int flags = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_GETFL)); |
| 33 | if (flags == -1) { |
| 34 | return ErrnoError() << "Could not get flags for fd"; |
| 35 | } |
| 36 | if (int ret = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_SETFL, flags | O_NONBLOCK)); ret == -1) { |
| 37 | return ErrnoError() << "Could not set non-blocking flag for fd"; |
| 38 | } |
| 39 | return {}; |
| 40 | } |
| 41 | |
Andrei Homescu | c24c879 | 2022-04-19 00:24:51 +0000 | [diff] [blame^] | 42 | status_t getRandomBytes(uint8_t* data, size_t size) { |
| 43 | int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)); |
| 44 | if (ret == -1) { |
| 45 | return -errno; |
| 46 | } |
| 47 | |
| 48 | base::unique_fd fd(ret); |
| 49 | if (!base::ReadFully(fd, data, size)) { |
| 50 | return -errno; |
| 51 | } |
| 52 | return OK; |
| 53 | } |
| 54 | |
Yifan Hong | b675ffe | 2021-08-05 16:37:17 -0700 | [diff] [blame] | 55 | } // namespace android |