1// Copyright (c) 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8//     * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10//     * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14//     * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// ---
31// Author: Craig Silverstein
32//
33// A few routines that are useful for multiple tests in this directory.
34
35#include "config_for_unittests.h"
36#include <stdlib.h>           // for NULL, abort()
37// On FreeBSD, if you #include <sys/resource.h>, you have to get stdint first.
38#ifdef HAVE_STDINT_H
39#include <stdint.h>
40#endif
41#ifdef HAVE_SYS_RESOURCE_H
42#include <sys/resource.h>
43#endif
44#include "tests/testutil.h"
45
46
47// When compiled 64-bit and run on systems with swap several unittests will end
48// up trying to consume all of RAM+swap, and that can take quite some time.  By
49// limiting the address-space size we get sufficient coverage without blowing
50// out job limits.
51void SetTestResourceLimit() {
52#ifdef HAVE_SYS_RESOURCE_H
53  // The actual resource we need to set varies depending on which flavour of
54  // unix.  On Linux we need RLIMIT_AS because that covers the use of mmap.
55  // Otherwise hopefully RLIMIT_RSS is good enough.  (Unfortunately 64-bit
56  // and 32-bit headers disagree on the type of these constants!)
57#ifdef RLIMIT_AS
58#define USE_RESOURCE RLIMIT_AS
59#else
60#define USE_RESOURCE RLIMIT_RSS
61#endif
62
63  // Restrict the test to 1GiB, which should fit comfortably well on both
64  // 32-bit and 64-bit hosts, and executes in ~1s.
65  const rlim_t kMaxMem = 1<<30;
66
67  struct rlimit rlim;
68  if (getrlimit(USE_RESOURCE, &rlim) == 0) {
69    if (rlim.rlim_cur == RLIM_INFINITY || rlim.rlim_cur > kMaxMem) {
70      rlim.rlim_cur = kMaxMem;
71      setrlimit(USE_RESOURCE, &rlim); // ignore result
72    }
73  }
74#endif  /* HAVE_SYS_RESOURCE_H */
75}
76
77
78struct FunctionAndId {
79  void (*ptr_to_function)(int);
80  int id;
81};
82
83#if defined(NO_THREADS) || !(defined(HAVE_PTHREAD) || defined(_WIN32))
84
85extern "C" void RunThread(void (*fn)()) {
86  (*fn)();
87}
88
89extern "C" void RunManyThreads(void (*fn)(), int count) {
90  // I guess the best we can do is run fn sequentially, 'count' times
91  for (int i = 0; i < count; i++)
92    (*fn)();
93}
94
95extern "C" void RunManyThreadsWithId(void (*fn)(int), int count, int) {
96  for (int i = 0; i < count; i++)
97    (*fn)(i);    // stacksize doesn't make sense in a non-threaded context
98}
99
100#elif defined(_WIN32)
101
102#ifndef WIN32_LEAN_AND_MEAN
103#define WIN32_LEAN_AND_MEAN  /* We always want minimal includes */
104#endif
105#include <windows.h>
106
107extern "C" {
108  // This helper function has the signature that pthread_create wants.
109  DWORD WINAPI RunFunctionInThread(LPVOID ptr_to_ptr_to_fn) {
110    (**static_cast<void (**)()>(ptr_to_ptr_to_fn))();    // runs fn
111    return 0;
112  }
113
114  DWORD WINAPI RunFunctionInThreadWithId(LPVOID ptr_to_fnid) {
115    FunctionAndId* fn_and_id = static_cast<FunctionAndId*>(ptr_to_fnid);
116    (*fn_and_id->ptr_to_function)(fn_and_id->id);   // runs fn
117    return 0;
118  }
119
120  void RunManyThreads(void (*fn)(), int count) {
121    DWORD dummy;
122    HANDLE* hThread = new HANDLE[count];
123    for (int i = 0; i < count; i++) {
124      hThread[i] = CreateThread(NULL, 0, RunFunctionInThread, &fn, 0, &dummy);
125      if (hThread[i] == NULL)  ExitProcess(i);
126    }
127    WaitForMultipleObjects(count, hThread, TRUE, INFINITE);
128    for (int i = 0; i < count; i++) {
129      CloseHandle(hThread[i]);
130    }
131    delete[] hThread;
132  }
133
134  void RunThread(void (*fn)()) {
135    RunManyThreads(fn, 1);
136  }
137
138  void RunManyThreadsWithId(void (*fn)(int), int count, int stacksize) {
139    DWORD dummy;
140    HANDLE* hThread = new HANDLE[count];
141    FunctionAndId* fn_and_ids = new FunctionAndId[count];
142    for (int i = 0; i < count; i++) {
143      fn_and_ids[i].ptr_to_function = fn;
144      fn_and_ids[i].id = i;
145      hThread[i] = CreateThread(NULL, stacksize, RunFunctionInThreadWithId,
146                                &fn_and_ids[i], 0, &dummy);
147      if (hThread[i] == NULL)  ExitProcess(i);
148    }
149    WaitForMultipleObjects(count, hThread, TRUE, INFINITE);
150    for (int i = 0; i < count; i++) {
151      CloseHandle(hThread[i]);
152    }
153    delete[] fn_and_ids;
154    delete[] hThread;
155  }
156}
157
158#else  // not NO_THREADS, not !HAVE_PTHREAD, not _WIN32
159
160#include <pthread.h>
161
162#define SAFE_PTHREAD(fncall)  do { if ((fncall) != 0) abort(); } while (0)
163
164extern "C" {
165  // This helper function has the signature that pthread_create wants.
166  static void* RunFunctionInThread(void *ptr_to_ptr_to_fn) {
167    (**static_cast<void (**)()>(ptr_to_ptr_to_fn))();    // runs fn
168    return NULL;
169  }
170
171  static void* RunFunctionInThreadWithId(void *ptr_to_fnid) {
172    FunctionAndId* fn_and_id = static_cast<FunctionAndId*>(ptr_to_fnid);
173    (*fn_and_id->ptr_to_function)(fn_and_id->id);   // runs fn
174    return NULL;
175  }
176
177  // Run a function in a thread of its own and wait for it to finish.
178  // This is useful for tcmalloc testing, because each thread is
179  // handled separately in tcmalloc, so there's interesting stuff to
180  // test even if the threads are not running concurrently.
181  void RunThread(void (*fn)()) {
182    pthread_t thr;
183    // Even though fn is on the stack, it's safe to pass a pointer to it,
184    // because we pthread_join immediately (ie, before RunInThread exits).
185    SAFE_PTHREAD(pthread_create(&thr, NULL, RunFunctionInThread, &fn));
186    SAFE_PTHREAD(pthread_join(thr, NULL));
187  }
188
189  void RunManyThreads(void (*fn)(), int count) {
190    pthread_t* thr = new pthread_t[count];
191    for (int i = 0; i < count; i++) {
192      SAFE_PTHREAD(pthread_create(&thr[i], NULL, RunFunctionInThread, &fn));
193    }
194    for (int i = 0; i < count; i++) {
195      SAFE_PTHREAD(pthread_join(thr[i], NULL));
196    }
197    delete[] thr;
198  }
199
200  void RunManyThreadsWithId(void (*fn)(int), int count, int stacksize) {
201    pthread_attr_t attr;
202    pthread_attr_init(&attr);
203    pthread_attr_setstacksize(&attr, stacksize);
204
205    pthread_t* thr = new pthread_t[count];
206    FunctionAndId* fn_and_ids = new FunctionAndId[count];
207    for (int i = 0; i < count; i++) {
208      fn_and_ids[i].ptr_to_function = fn;
209      fn_and_ids[i].id = i;
210      SAFE_PTHREAD(pthread_create(&thr[i], &attr,
211                                  RunFunctionInThreadWithId, &fn_and_ids[i]));
212    }
213    for (int i = 0; i < count; i++) {
214      SAFE_PTHREAD(pthread_join(thr[i], NULL));
215    }
216    delete[] fn_and_ids;
217    delete[] thr;
218
219    pthread_attr_destroy(&attr);
220  }
221}
222
223#endif
224