blob: 73d6c1aca1159407f130fffd3a9404ab22b1c6a8 [file] [log] [blame]
Marie Janssen093f0132016-03-10 11:27:53 -08001/******************************************************************************
2 *
Jakub Pawlowski5b790fe2017-09-18 09:00:20 -07003 * Copyright 2016 Google, Inc.
Marie Janssen093f0132016-03-10 11:27:53 -08004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19#define LOG_TAG "bt_osi_rand"
20
Jack Hef2af1c42016-12-13 01:59:12 -080021#include <base/logging.h>
Marie Janssen093f0132016-03-10 11:27:53 -080022#include <errno.h>
23#include <fcntl.h>
Mark Salyzyn6aee1e82016-10-17 09:43:39 -070024#include <stdio.h>
Marie Janssen093f0132016-03-10 11:27:53 -080025#include <string.h>
Marie Janssen093f0132016-03-10 11:27:53 -080026#include <sys/stat.h>
Myles Watsonb55040c2016-10-19 13:15:34 -070027#include <sys/types.h>
Marie Janssen093f0132016-03-10 11:27:53 -080028#include <unistd.h>
29
30#include "osi/include/log.h"
31#include "osi/include/osi.h"
32
33#define RANDOM_PATH "/dev/urandom"
34
35int osi_rand(void) {
36 int rand;
37 int rand_fd = open(RANDOM_PATH, O_RDONLY);
38
39 if (rand_fd == INVALID_FD) {
40 LOG_ERROR(LOG_TAG, "%s can't open rand fd %s: %s ", __func__, RANDOM_PATH,
41 strerror(errno));
Myles Watson1dc4b362017-03-21 10:28:20 -070042 CHECK(rand_fd != INVALID_FD);
Marie Janssen093f0132016-03-10 11:27:53 -080043 }
44
45 ssize_t read_bytes = read(rand_fd, &rand, sizeof(rand));
46 close(rand_fd);
47
Jack Hef2af1c42016-12-13 01:59:12 -080048 CHECK(read_bytes == sizeof(rand));
Marie Janssen093f0132016-03-10 11:27:53 -080049
Myles Watsonb55040c2016-10-19 13:15:34 -070050 if (rand < 0) rand = -rand;
Marie Janssen093f0132016-03-10 11:27:53 -080051
52 return rand;
53}