blob: 191fde6f98eee291a84747e0f0fc028bc33d7cd3 [file] [log] [blame]
robert.swiecki3bb518c2010-10-14 00:48:24 +00001/*
2
3 honggfuzz - utilities
4 -----------------------------------------
5
6 Author: Robert Swiecki <swiecki@google.com>
7
8 Copyright 2010 by Google Inc. All Rights Reserved.
9
10 Licensed under the Apache License, Version 2.0 (the "License");
11 you may not use this file except in compliance with the License.
12 You may obtain a copy of the License at
13
14 http://www.apache.org/licenses/LICENSE-2.0
15
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
21
22*/
23
24#include <sys/types.h>
25#include <sys/stat.h>
26#include <fcntl.h>
27#include <sys/time.h>
28#include <stdlib.h>
29#include <unistd.h>
30#include <stdint.h>
31#include <math.h>
32#include <time.h>
33
34#include "common.h"
35#include "log.h"
36
37void util_rndInit(void
38 )
39{
40 struct timeval tv;
41
42 gettimeofday(&tv, NULL);
43 uint64_t seed = (uint64_t) tv.tv_sec ^ ((uint64_t) tv.tv_usec << 16);
44
45 LOGMSG(l_DEBUG, "srand48() reinitialized with %ld", (long)seed);
46 srand48((long)seed);
47}
48
49/*
50 * Yeah.. the distribution is not perfect, but it's not supposed to be
51 * cryptographically secure
52 */
53uint32_t util_rndGet(uint32_t min, uint32_t max)
54{
55 double rnd = drand48();
56
57 return (uint32_t) lrint(floor((rnd * (max - min + 1)) + min));
58}
59
60void util_getLocalTime(const char *fmt, char *buf, size_t len)
61{
62 struct tm ltime;
63
64 time_t t = time(NULL);
65
66 localtime_r(&t, &ltime);
67 strftime(buf, len, fmt, &ltime);
68}
69
70void util_nullifyStdio(void
71 )
72{
73 int fd = open("/dev/null", O_RDWR);
74
75 if (fd == -1) {
76 LOGMSG_P(l_ERROR, "Couldn't open '/dev/null'");
77 return;
78 }
79
80 dup2(fd, 0);
81 dup2(fd, 1);
82 dup2(fd, 2);
83
84 if (fd > 2) {
85 close(fd);
86 }
87
88 return;
89}
90
91bool util_redirectStdin(char *inputFile)
92{
93 int fd = open(inputFile, O_RDONLY);
94
95 if (fd == -1) {
96 LOGMSG_P(l_ERROR, "Couldn't open '%s'", inputFile);
97 return false;
98 }
99
100 dup2(fd, 0);
101 if (fd != 0) {
102 close(fd);
103 }
104
105 return true;
106}
107
108void util_recoverStdio(void
109 )
110{
111 int fd = open("/dev/tty", O_RDWR);
112
113 if (fd == -1) {
114 LOGMSG_P(l_ERROR, "Couldn't open '/dev/tty'");
115 return;
116 }
117
118 dup2(fd, 0);
119 dup2(fd, 1);
120 dup2(fd, 2);
121
122 if (fd > 2) {
123 close(fd);
124 }
125
126 return;
127}