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 // IWYU pragma: private, include "chre_api/chre.h"
18 // IWYU pragma: friend chre/.*\.h
19
20 #ifndef _CHRE_RE_H_
21 #define _CHRE_RE_H_
22
23 /**
24 * @file
25 * Some of the core Runtime Environment utilities of the Context Hub
26 * Runtime Environment.
27 *
28 * This includes functions for memory allocation, logging, and timers.
29 */
30
31 #include <stdarg.h>
32 #include <stdbool.h>
33 #include <stdint.h>
34 #include <stdlib.h>
35
36 #include <chre/toolchain.h>
37
38 #ifdef __cplusplus
39 extern "C" {
40 #endif
41
42 /**
43 * The instance ID for the CHRE.
44 *
45 * This ID is used to identify events generated by the CHRE (as
46 * opposed to events generated by another nanoapp).
47 */
48 #define CHRE_INSTANCE_ID UINT32_C(0)
49
50 /**
51 * A timer ID representing an invalid timer.
52 *
53 * This valid is returned by chreTimerSet() if a timer cannot be
54 * started.
55 */
56 #define CHRE_TIMER_INVALID UINT32_C(-1)
57
58
59 /**
60 * The maximum size, in characters including null terminator, guaranteed for
61 * logging debug data with one call of chreDebugDumpLog() without getting
62 * truncated.
63 *
64 * @see chreDebugDumpLog
65 * @since v1.4
66 */
67 #define CHRE_DEBUG_DUMP_MINIMUM_MAX_SIZE 1000
68
69 /**
70 * The set of flags that may be returned by chreGetCapabilities()
71 * @defgroup CHRE_CAPABILITIES
72 * @{
73 */
74
75 //! None of the optional capabilities are supported
76 #define CHRE_CAPABILITIES_NONE (UINT32_C(0))
77
78 //! Support for reliable messages.
79 //! @see chreSendReliableMessageAsync()
80 #define CHRE_CAPABILITIES_RELIABLE_MESSAGES (UINT32_C(1) << 0)
81
82 /** @} */
83
84 /**
85 * Logging levels used to indicate severity level of logging messages.
86 *
87 * CHRE_LOG_ERROR: Something fatal has happened, i.e. something that will have
88 * user-visible consequences and won't be recoverable without explicitly
89 * deleting some data, uninstalling applications, wiping the data
90 * partitions or reflashing the entire phone (or worse).
91 * CHRE_LOG_WARN: Something that will have user-visible consequences but is
92 * likely to be recoverable without data loss by performing some explicit
93 * action, ranging from waiting or restarting an app all the way to
94 * re-downloading a new version of an application or rebooting the device.
95 * CHRE_LOG_INFO: Something interesting to most people happened, i.e. when a
96 * situation is detected that is likely to have widespread impact, though
97 * isn't necessarily an error.
98 * CHRE_LOG_DEBUG: Used to further note what is happening on the device that
99 * could be relevant to investigate and debug unexpected behaviors. You
100 * should log only what is needed to gather enough information about what
101 * is going on about your component.
102 *
103 * There is currently no API to turn on/off logging by level, but we anticipate
104 * adding such in future releases.
105 *
106 * @see chreLog
107 */
108 enum chreLogLevel {
109 CHRE_LOG_ERROR,
110 CHRE_LOG_WARN,
111 CHRE_LOG_INFO,
112 CHRE_LOG_DEBUG
113 };
114
115 /**
116 * Retrieves a set of flags indicating the CHRE optional features supported by
117 * the current implementation. The value returned by this function must be
118 * consistent for the entire duration of the nanoapp's execution.
119 *
120 * The client must allow for more flags to be set in this response than it knows
121 * about, for example if the implementation supports a newer version of the API
122 * than the client was compiled against.
123 *
124 * @return A bitmask with zero or more CHRE_CAPABILITIES_* flags set.
125 *
126 * @since v1.10
127 */
128 uint32_t chreGetCapabilities(void);
129
130 /**
131 * Returns the maximum size in bytes of a message sent to the host.
132 * This function will always return a value greater than or equal to
133 * CHRE_MESSAGE_TO_HOST_MAX_SIZE. If the capability
134 * CHRE_CAPABILITIES_RELIABLE_MESSAGES is enabled, this function will
135 * return a value greater than or equal to 32000.
136 *
137 * On v1.9 or earlier platforms, this will always return CHRE_MESSAGE_TO_HOST_MAX_SIZE.
138 *
139 * @return The maximum message size in bytes.
140 *
141 * @since v1.10
142 */
143 uint32_t chreGetMessageToHostMaxSize(void);
144
145 /**
146 * Get the application ID.
147 *
148 * The application ID is set by the loader of the nanoapp. This is not
149 * assured to be unique among all nanoapps running in the system.
150 *
151 * @return The application ID.
152 */
153 uint64_t chreGetAppId(void);
154
155 /**
156 * Get the instance ID.
157 *
158 * The instance ID is the CHRE handle to this nanoapp. This is assured
159 * to be unique among all nanoapps running in the system, and to be
160 * different from the CHRE_INSTANCE_ID. This is the ID used to communicate
161 * between nanoapps.
162 *
163 * @return The instance ID
164 */
165 uint32_t chreGetInstanceId(void);
166
167 /**
168 * A method for logging information about the system.
169 *
170 * The chreLog logging activity alone must not cause host wake-ups. For
171 * example, logs could be buffered in internal memory when the host is asleep,
172 * and delivered when appropriate (e.g. the host wakes up). If done this way,
173 * the internal buffer is recommended to be large enough (at least a few KB), so
174 * that multiple messages can be buffered. When these logs are sent to the host,
175 * they are strongly recommended to be made visible under the tag 'CHRE' in
176 * logcat - a future version of the CHRE API may make this a hard requirement.
177 *
178 * A log entry can have a variety of levels (@see LogLevel). This function
179 * allows a variable number of arguments, in a printf-style format.
180 *
181 * A nanoapp needs to be able to rely upon consistent printf format
182 * recognition across any platform, and thus we establish formats which
183 * are required to be handled by every CHRE implementation. Some of the
184 * integral formats may seem obscure, but this API heavily uses types like
185 * uint32_t and uint16_t. The platform independent macros for those printf
186 * formats, like PRId32 or PRIx16, end up using some of these "obscure"
187 * formats on some platforms, and thus are required.
188 *
189 * For the initial N release, our emphasis is on correctly getting information
190 * into the log, and minimizing the requirements for CHRE implementations
191 * beyond that. We're not as concerned about how the information is visually
192 * displayed. As a result, there are a number of format sub-specifiers which
193 * are "OPTIONAL" for the N implementation. "OPTIONAL" in this context means
194 * that a CHRE implementation is allowed to essentially ignore the specifier,
195 * but it must understand the specifier enough in order to properly skip it.
196 *
197 * For a nanoapp author, an OPTIONAL format means you might not get exactly
198 * what you want on every CHRE implementation, but you will always get
199 * something valid.
200 *
201 * To be clearer, here's an example with the OPTIONAL 0-padding for integers
202 * for different hypothetical CHRE implementations.
203 * Compliant, chose to implement OPTIONAL format:
204 * chreLog(level, "%04x", 20) ==> "0014"
205 * Compliant, chose not to implement OPTIONAL format:
206 * chreLog(level, "%04x", 20) ==> "14"
207 * Non-compliant, discarded format because the '0' was assumed to be incorrect:
208 * chreLog(level, "%04x", 20) ==> ""
209 *
210 * Note that some of the OPTIONAL specifiers will probably become
211 * required in future APIs.
212 *
213 * We also have NOT_SUPPORTED specifiers. Nanoapp authors should not use any
214 * NOT_SUPPORTED specifiers, as unexpected things could happen on any given
215 * CHRE implementation. A CHRE implementation is allowed to support this
216 * (for example, when using shared code which already supports this), but
217 * nanoapp authors need to avoid these.
218 *
219 * Unless specifically noted as OPTIONAL or NOT_SUPPORTED, format
220 * (sub-)specifiers listed below are required.
221 *
222 * While all CHRE implementations must support chreLog(), some platform
223 * implementations may support enhanced logging functionality only possible
224 * through a macro. This improved functionality is supported through
225 * platform-specific customization of the log macros provided in
226 * chre/util/nanoapp/log.h. All nanoapps are recommended to use these log
227 * macros where possible, as they will fall back to chreLog() as needed.
228 *
229 * OPTIONAL format sub-specifiers:
230 * - '-' (left-justify within the given field width)
231 * - '+' (precede the result with a '+' sign if it is positive)
232 * - ' ' (precede the result with a blank space if no sign is going to be
233 * output)
234 * - '#' (For 'o', 'x' or 'X', precede output with "0", "0x" or "0X",
235 * respectively. For floating point, unconditionally output a decimal
236 * point.)
237 * - '0' (left pad the number with zeroes instead of spaces when <width>
238 * needs padding)
239 * - <width> (A number representing the minimum number of characters to be
240 * output, left-padding with blank spaces if needed to meet the
241 * minimum)
242 * - '.'<precision> (A number which has different meaning depending on context.)
243 * - Integer context: Minimum number of digits to output, padding with
244 * leading zeros if needed to meet the minimum.
245 * - 'f' context: Number of digits to output after the decimal
246 * point (to the right of it).
247 * - 's' context: Maximum number of characters to output.
248 *
249 * Integral format specifiers:
250 * - 'd' (signed)
251 * - 'u' (unsigned)
252 * - 'o' (octal)
253 * - 'x' (hexadecimal, lower case)
254 * - 'X' (hexadecimal, upper case)
255 *
256 * Integral format sub-specifiers (as prefixes to an above integral format):
257 * - 'hh' (char)
258 * - 'h' (short)
259 * - 'l' (long)
260 * - 'll' (long long)
261 * - 'z' (size_t)
262 * - 't' (ptrdiff_t)
263 *
264 * Other format specifiers:
265 * - 'f' (floating point)
266 * - 'c' (character)
267 * - 's' (character string, terminated by '\0')
268 * - 'p' (pointer)
269 * - '%' (escaping the percent sign (i.e. "%%" becomes "%"))
270 *
271 * NOT_SUPPORTED specifiers:
272 * - 'n' (output nothing, but fill in a given pointer with the number
273 * of characters written so far)
274 * - '*' (indicates that the width/precision value comes from one of the
275 * arguments to the function)
276 * - 'e', 'E' (scientific notation output)
277 * - 'g', 'G' (Shortest floating point representation)
278 *
279 * @param level The severity level for this message.
280 * @param formatStr Either the entirety of the message, or a printf-style
281 * format string of the format documented above.
282 * @param ... A variable number of arguments necessary for the given
283 * 'formatStr' (there may be no additional arguments for some 'formatStr's).
284 */
285 CHRE_PRINTF_ATTR(2, 3)
286 void chreLog(enum chreLogLevel level, const char *formatStr, ...);
287
288 /**
289 * Get the system time.
290 *
291 * This returns a time in nanoseconds in reference to some arbitrary
292 * time in the past. This method is only useful for determining timing
293 * between events on the system, and is not useful for determining
294 * any sort of absolute time.
295 *
296 * This value must always increase (and must never roll over). This
297 * value has no meaning across CHRE reboots.
298 *
299 * @return The system time, in nanoseconds.
300 */
301 uint64_t chreGetTime(void);
302
303 /**
304 * Retrieves CHRE's current estimated offset between the local CHRE clock
305 * exposed in chreGetTime(), and the host-side clock exposed in the Android API
306 * SystemClock.elapsedRealtimeNanos(). This offset is formed as host time minus
307 * CHRE time, so that it can be added to the value returned by chreGetTime() to
308 * determine the current estimate of the host time.
309 *
310 * A call to this function must not require waking up the host and should return
311 * quickly.
312 *
313 * This function must always return a valid value from the earliest point that
314 * it can be called by a nanoapp. In other words, it is not valid to return
315 * some fixed/invalid value while waiting for the initial offset estimate to be
316 * determined - this initial offset must be ready before nanoapps are started.
317 *
318 * @return An estimate of the offset between CHRE's time returned in
319 * chreGetTime() and the time on the host given in the Android API
320 * SystemClock.elapsedRealtimeNanos(), accurate to within +/- 10
321 * milliseconds, such that adding this offset to chreGetTime() produces the
322 * estimated current time on the host. This value may change over time to
323 * account for drift, etc., so multiple calls to this API may produce
324 * different results.
325 *
326 * @since v1.1
327 */
328 int64_t chreGetEstimatedHostTimeOffset(void);
329
330 /**
331 * Convenience function to retrieve CHRE's estimate of the current time on the
332 * host, corresponding to the Android API SystemClock.elapsedRealtimeNanos().
333 *
334 * @return An estimate of the current time on the host, accurate to within
335 * +/- 10 milliseconds. This estimate is *not* guaranteed to be
336 * monotonically increasing, and may move backwards as a result of receiving
337 * new information from the host.
338 *
339 * @since v1.1
340 */
chreGetEstimatedHostTime(void)341 static inline uint64_t chreGetEstimatedHostTime(void) {
342 int64_t offset = chreGetEstimatedHostTimeOffset();
343 uint64_t time = chreGetTime();
344
345 // Just casting time to int64_t and adding the (potentially negative) offset
346 // should be OK under most conditions, but this way avoids issues if
347 // time >= 2^63, which is technically allowed since we don't specify a start
348 // value for chreGetTime(), though one would assume 0 is roughly boot time.
349 if (offset >= 0) {
350 time += (uint64_t) offset;
351 } else {
352 // Assuming chreGetEstimatedHostTimeOffset() is implemented properly,
353 // this will never underflow, because offset = hostTime - chreTime,
354 // and both times are monotonically increasing (e.g. when determining
355 // the offset, if hostTime is 0 and chreTime is 100 we'll have
356 // offset = -100, but chreGetTime() will always return >= 100 after that
357 // point).
358 time -= (uint64_t) (offset * -1);
359 }
360
361 return time;
362 }
363
364 /**
365 * Set a timer.
366 *
367 * When the timer fires, nanoappHandleEvent will be invoked with
368 * CHRE_EVENT_TIMER and with the given 'cookie'.
369 *
370 * A CHRE implementation is required to provide at least 32
371 * timers. However, there's no assurance there will be any available
372 * for any given nanoapp (if it's loaded late, etc).
373 *
374 * @param duration Time, in nanoseconds, before the timer fires.
375 * @param cookie Argument that will be sent to nanoappHandleEvent upon the
376 * timer firing. This is allowed to be NULL and does not need to be
377 * a valid pointer (assuming the nanoappHandleEvent code is expecting such).
378 * @param oneShot If true, the timer will just fire once. If false, the
379 * timer will continue to refire every 'duration', until this timer is
380 * canceled (@see chreTimerCancel).
381 *
382 * @return The timer ID. If the system is unable to set a timer
383 * (no more available timers, etc.) then CHRE_TIMER_INVALID will
384 * be returned.
385 *
386 * @see nanoappHandleEvent
387 */
388 uint32_t chreTimerSet(uint64_t duration, const void *cookie, bool oneShot);
389
390 /**
391 * Cancel a timer.
392 *
393 * After this method returns, the CHRE assures there will be no more
394 * events sent from this timer, and any enqueued events from this timer
395 * will need to be evicted from the queue by the CHRE.
396 *
397 * @param timerId A timer ID obtained by this nanoapp via chreTimerSet().
398 * @return true if the timer was cancelled, false otherwise. We may
399 * fail to cancel the timer if it's a one shot which (just) fired,
400 * or if the given timer ID is not owned by the calling app.
401 */
402 bool chreTimerCancel(uint32_t timerId);
403
404 /**
405 * Terminate this nanoapp.
406 *
407 * This takes effect immediately.
408 *
409 * The CHRE will no longer execute this nanoapp. The CHRE will not invoke
410 * nanoappEnd(), nor will it call any memory free callbacks in the nanoapp.
411 *
412 * The CHRE will unload/evict this nanoapp's code.
413 *
414 * @param abortCode A value indicating the reason for aborting. (Note that
415 * in this version of the API, there is no way for anyone to access this
416 * code, but future APIs may expose it.)
417 * @return Never. This method does not return, as the CHRE stops nanoapp
418 * execution immediately.
419 */
420 void chreAbort(uint32_t abortCode) CHRE_NO_RETURN;
421
422 /**
423 * Allocate a given number of bytes from the system heap.
424 *
425 * The nanoapp is required to free this memory via chreHeapFree() prior to
426 * the nanoapp ending.
427 *
428 * While the CHRE implementation is required to free up heap resources of
429 * a nanoapp when unloading it, future requirements and tests focused on
430 * nanoapps themselves may check for memory leaks, and will require nanoapps
431 * to properly manage their heap resources.
432 *
433 * @param bytes The number of bytes requested.
434 * @return A pointer to 'bytes' contiguous bytes of heap memory, or NULL
435 * if the allocation could not be performed. This pointer must be suitably
436 * aligned for any kind of variable.
437 *
438 * @see chreHeapFree.
439 */
440 CHRE_MALLOC_ATTR
441 void *chreHeapAlloc(uint32_t bytes);
442
443 /**
444 * Free a heap allocation.
445 *
446 * This allocation must be from a value returned from a chreHeapAlloc() call
447 * made by this nanoapp. In other words, it is illegal to free memory
448 * allocated by another nanoapp (or the CHRE).
449 *
450 * @param ptr 'ptr' is required to be a value returned from chreHeapAlloc().
451 * Note that since chreHeapAlloc can return NULL, CHRE
452 * implementations must safely handle 'ptr' being NULL.
453 *
454 * @see chreHeapAlloc.
455 */
456 void chreHeapFree(void *ptr);
457
458 /**
459 * Logs the nanoapp's debug data into debug dumps.
460 *
461 * A debug dump is a string representation of information that can be used to
462 * diagnose and debug issues. While chreLog() is useful for logging events as
463 * they happen, the debug dump is a complementary function typically used to
464 * output a snapshot of a nanoapp's state, history, vital statistics, etc. The
465 * CHRE framework is required to pass this information to the debug method in
466 * the Context Hub HAL, where it can be captured in Android bugreports, etc.
467 *
468 * This function must only be called while handling CHRE_EVENT_DEBUG_DUMP,
469 * otherwise it will have no effect. A nanoapp can call this function multiple
470 * times while handling the event. If the resulting formatted string from a
471 * single call to this function is longer than CHRE_DEBUG_DUMP_MINIMUM_MAX_SIZE
472 * characters, it may get truncated.
473 *
474 * @param formatStr A printf-style format string of the format documented in
475 * chreLog().
476 * @param ... A variable number of arguments necessary for the given 'formatStr'
477 * (there may be no additional arguments for some 'formatStr's).
478 *
479 * @see chreConfigureDebugDumpEvent
480 * @see chreLog
481 *
482 * @since v1.4
483 */
484 CHRE_PRINTF_ATTR(1, 2)
485 void chreDebugDumpLog(const char *formatStr, ...);
486
487 #ifdef __cplusplus
488 }
489 #endif
490
491 #endif /* _CHRE_RE_H_ */
492
493