1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _CHRE_RE_H_
18 #define _CHRE_RE_H_
19 
20 /**
21  * Some of the core Runtime Environment utilities of the Context Hub
22  * Runtime Environment.
23  *
24  * This includes functions for memory allocation, logging, and timers.
25  */
26 
27 #include <stdarg.h>
28 #include <stdbool.h>
29 #include <stdint.h>
30 #include <stdlib.h>
31 
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35 
36 /**
37  * The instance ID for the CHRE.
38  *
39  * This ID is used to identify events generated by the CHRE (as
40  * opposed to events generated by another nanoapp).
41  */
42 #define CHRE_INSTANCE_ID  UINT32_C(0)
43 
44 /**
45  * A timer ID representing an invalid timer.
46  *
47  * This valid is returned by chreTimerSet() if a timer cannot be
48  * started.
49  */
50 #define CHRE_TIMER_INVALID  UINT32_C(-1)
51 
52 
53 
54 /**
55  * Logging levels used to indicate severity level of logging messages.
56  *
57  * CHRE_LOG_ERROR: Something fatal has happened, i.e. something that will have
58  *     user-visible consequences and won't be recoverable without explicitly
59  *     deleting some data, uninstalling applications, wiping the data
60  *     partitions or reflashing the entire phone (or worse).
61  * CHRE_LOG_WARN: Something that will have user-visible consequences but is
62  *     likely to be recoverable without data loss by performing some explicit
63  *     action, ranging from waiting or restarting an app all the way to
64  *     re-downloading a new version of an application or rebooting the device.
65  * CHRE_LOG_INFO: Something interesting to most people happened, i.e. when a
66  *     situation is detected that is likely to have widespread impact, though
67  *     isn't necessarily an error.
68  * CHRE_LOG_DEBUG: Used to further note what is happening on the device that
69  *     could be relevant to investigate and debug unexpected behaviors. You
70  *     should log only what is needed to gather enough information about what
71  *     is going on about your component.
72  *
73  * There is currently no API to turn on/off logging by level, but we anticipate
74  * adding such in future releases.
75  *
76  * @see chreLog
77  */
78 enum chreLogLevel {
79     CHRE_LOG_ERROR,
80     CHRE_LOG_WARN,
81     CHRE_LOG_INFO,
82     CHRE_LOG_DEBUG
83 };
84 
85 
86 
87 /**
88  * Get the application ID.
89  *
90  * The application ID is set by the loader of the nanoapp.  This is not
91  * assured to be unique among all nanoapps running in the system.
92  *
93  * @returns The application ID.
94  */
95 uint64_t chreGetAppId(void);
96 
97 /**
98  * Get the instance ID.
99  *
100  * The instance ID is the CHRE handle to this nanoapp.  This is assured
101  * to be unique among all nanoapps running in the system, and to be
102  * different from the CHRE_INSTANCE_ID.  This is the ID used to communicate
103  * between nanoapps.
104  *
105  * @returns The instance ID
106  */
107 uint32_t chreGetInstanceId(void);
108 
109 /**
110  * A method for logging information about the system.
111  *
112  * A log entry can have a variety of levels (@see LogLevel).  This function
113  * allows a variable number of arguments, in a printf-style format.
114  *
115  * A nanoapp needs to be able to rely upon consistent printf format
116  * recognition across any platform, and thus we establish formats which
117  * are required to be handled by every CHRE implementation.  Some of the
118  * integral formats may seem obscure, but this API heavily uses types like
119  * uint32_t and uint16_t.  The platform independent macros for those printf
120  * formats, like PRId32 or PRIx16, end up using some of these "obscure"
121  * formats on some platforms, and thus are required.
122  *
123  * For the initial N release, our emphasis is on correctly getting information
124  * into the log, and minimizing the requirements for CHRE implementations
125  * beyond that.  We're not as concerned about how the information is visually
126  * displayed.  As a result, there are a number of format sub-specifiers which
127  * are "OPTIONAL" for the N implementation.  "OPTIONAL" in this context means
128  * that a CHRE implementation is allowed to essentially ignore the specifier,
129  * but it must understand the specifier enough in order to properly skip it.
130  *
131  * For a nanoapp author, an OPTIONAL format means you might not get exactly
132  * what you want on every CHRE implementation, but you will always get
133  * something sane.
134  *
135  * To be clearer, here's an example with the OPTIONAL 0-padding for integers
136  * for different hypothetical CHRE implementations.
137  * Compliant, chose to implement OPTIONAL format:
138  *   chreLog(level, "%04x", 20) ==> "0014"
139  * Compliant, chose not to implement OPTIONAL format:
140  *   chreLog(level, "%04x", 20) ==> "14"
141  * Non-compliant, discarded format because the '0' was assumed to be incorrect:
142  *   chreLog(level, "%04x", 20) ==> ""
143  *
144  * Note that some of the OPTIONAL specifiers will probably become
145  * required in future APIs.
146  *
147  * We also have NOT_SUPPORTED specifiers.  Nanoapp authors should not use any
148  * NOT_SUPPORTED specifiers, as unexpected things could happen on any given
149  * CHRE implementation.  A CHRE implementation is allowed to support this
150  * (for example, when using shared code which already supports this), but
151  * nanoapp authors need to avoid these.
152  *
153  *
154  * Unless specifically noted as OPTIONAL or NOT_SUPPORTED, format
155  * (sub-)specifiers listed below are required.
156  *
157  * OPTIONAL format sub-specifiers:
158  * - '-' (left-justify within the given field width)
159  * - '+' (preceed the result with a '+' sign if it is positive)
160  * - ' ' (preceed the result with a blank space if no sign is going to be
161  *        output)
162  * - '#' (For 'o', 'x' or 'X', preceed output with "0", "0x" or "0X",
163  *        respectively.  For floating point, unconditionally output a decimal
164  *        point.)
165  * - '0' (left pad the number with zeroes instead of spaces when <width>
166  *        needs padding)
167  * - <width> (A number representing the minimum number of characters to be
168  *            output, left-padding with blank spaces if needed to meet the
169  *            minimum)
170  * - '.'<precision> (A number which has different meaning depending on context.)
171  *    - Integer context: Minimum number of digits to output, padding with
172  *          leading zeros if needed to meet the minimum.
173  *    - 'f' context: Number of digits to output after the decimal
174  *          point (to the right of it).
175  *    - 's' context: Maximum number of characters to output.
176  *
177  * Integral format specifiers:
178  * - 'd' (signed)
179  * - 'u' (unsigned)
180  * - 'o' (octal)
181  * - 'x' (hexadecimal, lower case)
182  * - 'X' (hexadecimal, upper case)
183  *
184  * Integral format sub-specifiers (as prefixes to an above integral format):
185  * - 'hh' (char)
186  * - 'h' (short)
187  * - 'l' (long)
188  * - 'll' (long long)
189  * - 'z' (size_t)
190  * - 't' (ptrdiff_t)
191  *
192  * Other format specifiers:
193  * - 'f' (floating point)
194  * - 'c' (character)
195  * - 's' (character string, terminated by '\0')
196  * - 'p' (pointer)
197  * - '%' (escaping the percent sign (i.e. "%%" becomes "%"))
198  *
199  * NOT_SUPPORTED specifiers:
200  * - 'n' (output nothing, but fill in a given pointer with the number
201  *        of characters written so far)
202  * - '*' (indicates that the width/precision value comes from one of the
203  *        arguments to the function)
204  * - 'e', 'E' (scientific notation output)
205  * - 'g', 'G' (Shortest floating point representation)
206  *
207  * @param level  The severity level for this message.
208  * @param formatStr  Either the entirety of the message, or a printf-style
209  *     format string of the format documented above.
210  * @param ...  A variable number of arguments necessary for the given
211  *     'formatStr' (there may be no additional arguments for some 'formatStr's).
212  */
213 void chreLog(enum chreLogLevel level, const char *formatStr, ...);
214 
215 /**
216  * Get the system time.
217  *
218  * This returns a time in nanoseconds in reference to some arbitrary
219  * time in the past.  This method is only useful for determining timing
220  * between events on the system, and is not useful for determining
221  * any sort of absolute time.
222  *
223  * This value must always increase (and must never roll over).  This
224  * value has no meaning across CHRE reboots.
225  *
226  * @returns The system time, in nanoseconds.
227  */
228 uint64_t chreGetTime(void);
229 
230 /**
231  * Set a timer.
232  *
233  * When the timer fires, nanoappHandleEvent will be invoked with
234  * CHRE_EVENT_TIMER and with the given 'cookie'.
235  *
236  * A CHRE implementation is required to provide at least 32
237  * timers.  However, there's no assurance there will be any available
238  * for any given nanoapp (if it's loaded late, etc).
239  *
240  * @param duration  Time, in nanoseconds, before the timer fires.
241  * @param cookie  Argument that will be sent to nanoappHandleEvent upon the
242  *     timer firing.  This is allowed to be NULL and does not need to be
243  *     a valid pointer (assuming the nanoappHandleEvent code is expecting such).
244  * @param oneShot  If true, the timer will just fire once.  If false, the
245  *     timer will continue to refire every 'duration', until this timer is
246  *     canceled (@see chreTimerCancel).
247  *
248  * @returns  The timer ID.  If the system is unable to set a timer
249  *     (no more available timers, etc.) then CHRE_TIMER_INVALID will
250  *     be returned.
251  *
252  * @see nanoappHandleEvent
253  */
254 uint32_t chreTimerSet(uint64_t duration, const void* cookie, bool oneShot);
255 
256 /**
257  * Cancel a timer.
258  *
259  * After this method returns, the CHRE assures there will be no more
260  * events sent from this timer, and any enqueued events from this timer
261  * will need to be evicted from the queue by the CHRE.
262  *
263  * @param timerId  A timer ID obtained by this nanoapp via chreTimerSet().
264  * @returns true if the timer was cancelled, false otherwise.  We may
265  *     fail to cancel the timer if it's a one shot which (just) fired,
266  *     or if the given timer ID is not owned by the calling app.
267  */
268 bool chreTimerCancel(uint32_t timerId);
269 
270 /**
271  * Terminate this nanoapp.
272  *
273  * This takes effect immediately.
274  *
275  * The CHRE will no longer execute this nanoapp.  The CHRE will not invoke
276  * nanoappEnd(), nor will it call any memory free callbacks in the nanoapp.
277  *
278  * The CHRE will unload/evict this nanoapp's code.
279  *
280  * @param abortCode  A value indicating the reason for aborting.  (Note that
281  *    in this version of the API, there is no way for anyone to access this
282  *    code, but future APIs may expose it.)
283  * @returns Never.  This method does not return, as the CHRE stops nanoapp
284  *    execution immediately.
285  */
286 void chreAbort(uint32_t abortCode);
287 
288 /**
289  * Allocate a given number of bytes from the system heap.
290  *
291  * The nanoapp is required to free this memory via chreHeapFree() prior to
292  * the nanoapp ending.
293  *
294  * While the CHRE implementation is required to free up heap resources of
295  * a nanoapp when unloading it, future requirements and tests focused on
296  * nanoapps themselves may check for memory leaks, and will require nanoapps
297  * to properly manage their heap resources.
298  *
299  * @param bytes  The number of bytes requested.
300  * @returns  A pointer to 'bytes' contiguous bytes of heap memory, or NULL
301  *     if the allocation could not be performed.  This pointer must be suitably
302  *     aligned for any kind of variable.
303  *
304  * @see chreHeapFree.
305  */
306 void* chreHeapAlloc(uint32_t bytes);
307 
308 /**
309  * Free a heap allocation.
310  *
311  * This allocation must be from a value returned from a chreHeapAlloc() call
312  * made by this nanoapp.  In other words, it is illegal to free memory
313  * allocated by another nanoapp (or the CHRE).
314  *
315  * @param ptr  'ptr' is required to be a value returned from chreHeapAlloc().
316  *     Note that since chreHeapAlloc can return NULL, CHRE
317  *     implementations must safely handle 'ptr' being NULL.
318  *
319  * @see chreHeapAlloc.
320  */
321 void chreHeapFree(void* ptr);
322 
323 
324 #ifdef __cplusplus
325 }
326 #endif
327 
328 #endif  /* _CHRE_RE_H_ */
329 
330