Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 1 | // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "base/rand_util.h" |
| 6 | |
Scott Graham | fe0e9f46 | 2017-09-18 21:25:04 | [diff] [blame] | 7 | #include <zircon/syscalls.h> |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 8 | |
| 9 | #include <algorithm> |
| 10 | |
| 11 | #include "base/logging.h" |
| 12 | |
| 13 | namespace base { |
| 14 | |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 15 | void RandBytes(void* output, size_t output_length) { |
| 16 | size_t remaining = output_length; |
| 17 | unsigned char* cur = reinterpret_cast<unsigned char*>(output); |
Sergey Ulanov | fdc62f8e | 2017-08-01 19:51:00 | [diff] [blame] | 18 | while (remaining > 0) { |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 19 | // The syscall has a maximum number of bytes that can be read at once. |
| 20 | size_t read_len = |
Scott Graham | fe0e9f46 | 2017-09-18 21:25:04 | [diff] [blame] | 21 | std::min(remaining, static_cast<size_t>(ZX_CPRNG_DRAW_MAX_LEN)); |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 22 | |
| 23 | size_t actual; |
Scott Graham | fe0e9f46 | 2017-09-18 21:25:04 | [diff] [blame] | 24 | zx_status_t status = zx_cprng_draw(cur, read_len, &actual); |
| 25 | CHECK(status == ZX_OK && read_len == actual); |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 26 | |
| 27 | CHECK(remaining >= actual); |
| 28 | remaining -= actual; |
| 29 | cur += actual; |
Sergey Ulanov | fdc62f8e | 2017-08-01 19:51:00 | [diff] [blame] | 30 | } |
Scott Graham | 4ffd63b | 2017-06-01 18:03:33 | [diff] [blame] | 31 | } |
| 32 | |
| 33 | } // namespace base |