1 /******************************************************************************
2  *
3  *  Copyright (C) 2016 Google, Inc.
4  *
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 #pragma once
20 
21 #include <stdbool.h>
22 #include <stdint.h>
23 
24 #define UNUSED_ATTR __attribute__((unused))
25 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
26 #define INVALID_FD (-1)
27 
28 #define CONCAT(a, b) a##b
29 
30 // Use during compile time to check conditional values
31 // NOTE: The the failures will present as a generic error
32 // "error: initialization makes pointer from integer without a cast"
33 // but the file and line number will present the condition that
34 // failed.
35 #define DUMMY_COUNTER(c) CONCAT(__osi_dummy_, c)
36 #define DUMMY_PTR DUMMY_COUNTER(__COUNTER__)
37 
38 // base/macros.h defines a COMPILE_ASSERT macro to the C++11 keyword
39 // "static_assert" (it undef's COMPILE_ASSERT before redefining it).
40 // C++ code that includes base and osi/include/osi.h can thus easily default to
41 // the definition from libbase but we should check here to avoid compile errors.
42 #ifndef COMPILE_ASSERT
43 #define COMPILE_ASSERT(COND) \
44   typedef int failed_compile_assert[(COND) ? 1 : -1] __attribute__((unused))
45 #endif  // COMPILE_ASSERT
46 
47 // Macros for safe integer to pointer conversion. In the C language, data is
48 // commonly cast to opaque pointer containers and back for generic parameter
49 // passing in callbacks. These macros should be used sparingly in new code
50 // (never in C++ code). Whenever integers need to be passed as a pointer, use
51 // these macros.
52 #define PTR_TO_UINT(p) ((unsigned int)((uintptr_t)(p)))
53 #define UINT_TO_PTR(u) ((void*)((uintptr_t)(u)))
54 
55 #define PTR_TO_INT(p) ((int)((intptr_t)(p)))
56 #define INT_TO_PTR(i) ((void*)((intptr_t)(i)))
57 
58 // Obtain a random number between 0 and INT_MAX inclusive.
59 // Taken from a system random source such as /dev/random.
60 // No guarantees of distribution are made.
61 // Effort is made for this to come from a real random source.
62 int osi_rand(void);
63 
64 // Re-run |fn| system call until the system call doesn't cause EINTR.
65 #define OSI_NO_INTR(fn) \
66   do {                  \
67   } while ((fn) == -1 && errno == EINTR)
68