/src/libzmq/src/random.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | /* SPDX-License-Identifier: MPL-2.0 */ |
2 | | |
3 | | #include "precompiled.hpp" |
4 | | #include <stdlib.h> |
5 | | |
6 | | #if !defined ZMQ_HAVE_WINDOWS |
7 | | #include <unistd.h> |
8 | | #endif |
9 | | |
10 | | #include "random.hpp" |
11 | | #include "stdint.hpp" |
12 | | #include "clock.hpp" |
13 | | #include "mutex.hpp" |
14 | | #include "macros.hpp" |
15 | | |
16 | | #if defined(ZMQ_USE_LIBSODIUM) |
17 | | #include "sodium.h" |
18 | | #endif |
19 | | |
20 | | void zmq::seed_random () |
21 | 0 | { |
22 | | #if defined ZMQ_HAVE_WINDOWS |
23 | | const int pid = static_cast<int> (GetCurrentProcessId ()); |
24 | | #else |
25 | 0 | int pid = static_cast<int> (getpid ()); |
26 | 0 | #endif |
27 | 0 | srand (static_cast<unsigned int> (clock_t::now_us () + pid)); |
28 | 0 | } |
29 | | |
30 | | uint32_t zmq::generate_random () |
31 | 0 | { |
32 | | // Compensate for the fact that rand() returns signed integer. |
33 | 0 | const uint32_t low = static_cast<uint32_t> (rand ()); |
34 | 0 | uint32_t high = static_cast<uint32_t> (rand ()); |
35 | 0 | high <<= (sizeof (int) * 8 - 1); |
36 | 0 | return high | low; |
37 | 0 | } |
38 | | |
39 | | static void manage_random (bool init_) |
40 | 0 | { |
41 | 0 | #if defined(ZMQ_USE_LIBSODIUM) |
42 | 0 | if (init_) { |
43 | | // sodium_init() is now documented as thread-safe in recent versions |
44 | 0 | int rc = sodium_init (); |
45 | 0 | zmq_assert (rc != -1); |
46 | 0 | #if defined(ZMQ_LIBSODIUM_RANDOMBYTES_CLOSE) |
47 | 0 | } else { |
48 | | // randombytes_close either a no-op or not threadsafe |
49 | | // doing this without refcounting can cause crashes |
50 | | // if called while a context is active |
51 | 0 | randombytes_close (); |
52 | 0 | #endif |
53 | 0 | } |
54 | | #else |
55 | | LIBZMQ_UNUSED (init_); |
56 | | #endif |
57 | 0 | } |
58 | | |
59 | | void zmq::random_open () |
60 | 0 | { |
61 | 0 | manage_random (true); |
62 | 0 | } |
63 | | |
64 | | void zmq::random_close () |
65 | 0 | { |
66 | 0 | manage_random (false); |
67 | 0 | } |