Debian Codegraph @

runtime/dyninst/arith.c

raw
1 /* -*- linux-c -*- */
2 /* Math functions
3 * Copyright (C) 2005-2012 Red Hat Inc.
4 *
5 * This file is part of systemtap, and is free software. You can
6 * redistribute it and/or modify it under the terms of the GNU General
7 * Public License (GPL); either version 2, or (at your option) any
8 * later version.
9 */
10
11 #ifndef _STAPDYN_ARITH_C_
12 #define _STAPDYN_ARITH_C_
13
14 /** @file arith.
15 * @brief Implements various arithmetic-related helper functions
16 */
17
18
19 /** Divide x by y. In case of division-by-zero,
20 * set context error string, and return 0
21 */
22 static int64_t _stp_div64 (const char **error, int64_t x, int64_t y)
23 {
24 // check for division-by-zero
25 if (unlikely (y == 0)) {
26 if (error) *error = "division by 0";
27 return 0;
28 }
29
30 if (unlikely (y == -1))
31 return -x;
32
33 return x/y;
34 }
35
36
37 /** Modulo x by y. In case of division-by-zero,
38 * set context error string, and return any 0
39 */
40 static int64_t _stp_mod64 (const char **error, int64_t x, int64_t y)
41 {
42 // check for division-by-zero
43 if (unlikely (y == 0)) {
44 if (error) *error = "division by 0";
45 return 0;
46 }
47
48 if (unlikely (y == 1 || y == -1))
49 return 0;
50
51 return x%y;
52 }
53
54
55 static unsigned long _stp_random_u_init(void)
56 {
57 unsigned long seed;
58 ssize_t count = 0;
59
60 int fd = open("/dev/urandom", O_RDONLY);
61 if (fd >= 0) {
62 count = read(fd, &seed, sizeof(seed));
63 close(fd);
64 }
65
66 /* If urandom fails for any reason, this is a crude fallback */
67 if (count != sizeof(seed)) {
68 struct timespec ts;
69 (void)clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
70 seed = ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
71 }
72
73 return seed;
74 }
75
76 /** Return a random integer between 0 and n - 1.
77 * @param n how far from zero to go. Make it positive but less than a million or so.
78 */
79 static unsigned long _stp_random_u (unsigned long n)
80 {
81 static unsigned long seed;
82 static int initialized_p = 0;
83
84 if (unlikely (! initialized_p)) {
85 seed = _stp_random_u_init();
86 initialized_p = 1;
87 }
88
89 /* from glibc rand man page */
90 seed = seed * 1103515245 + 12345;
91
92 return (n == 0 ? 0 : seed % n);
93 }
94
95
96 /** Return a random integer between -n and n.
97 * @param n how far from zero to go. Make it positive but less than a million or so.
98 */
99 static int _stp_random_pm (unsigned n)
100 {
101 return -(int)n + (int)_stp_random_u (2*n + 1);
102 }
103
104 #endif /* _STAPDYN_ARITH_C_ */
105