Coverage Report

Created: 2025-11-24 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssh/openbsd-compat/arc4random_uniform.c
Line
Count
Source
1
/*  $OpenBSD: arc4random_uniform.c,v 1.3 2019/01/20 02:59:07 bcook Exp $  */
2
3
/*
4
 * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
19
/* OPENBSD ORIGINAL: lib/libc/crypto/arc4random_uniform.c */
20
21
#include "includes.h"
22
23
#include <stdint.h>
24
#include <stdlib.h>
25
26
#ifndef HAVE_ARC4RANDOM_UNIFORM
27
/*
28
 * Calculate a uniformly distributed random number less than upper_bound
29
 * avoiding "modulo bias".
30
 *
31
 * Uniformity is achieved by generating new random numbers until the one
32
 * returned is outside the range [0, 2**32 % upper_bound).  This
33
 * guarantees the selected random number will be inside
34
 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
35
 * after reduction modulo upper_bound.
36
 */
37
uint32_t
38
arc4random_uniform(uint32_t upper_bound)
39
0
{
40
0
  uint32_t r, min;
41
42
0
  if (upper_bound < 2)
43
0
    return 0;
44
45
  /* 2**32 % x == (2**32 - x) % x */
46
0
  min = -upper_bound % upper_bound;
47
48
  /*
49
   * This could theoretically loop forever but each retry has
50
   * p > 0.5 (worst case, usually far better) of selecting a
51
   * number inside the range we need, so it should rarely need
52
   * to re-roll.
53
   */
54
0
  for (;;) {
55
0
    r = arc4random();
56
0
    if (r >= min)
57
0
      break;
58
0
  }
59
60
0
  return r % upper_bound;
61
0
}
62
#endif /* !HAVE_ARC4RANDOM_UNIFORM */