Defines a broad set of APIs that allow the client application to query build and runtime properties of the enclosing system.
Runtime capabilities are boolean properties of a platform that can't be determined at compile-time. They may vary from device to device, but they will not change over the course of a single execution. They often specify particular behavior of other APIs within the bounds of their operating range.
Values
kSbSystemCapabilityReversedEnterAndBack
- Whether this system has reversed Enter and Back keys.kSbSystemCapabilityCanQueryGPUMemoryStats
- Whether this system has the ability to report on GPU memory usage.If (and only if) a system has this capcability willSbSystemGetTotalGPUMemory() and SbSystemGetUsedGPUMemory() be valid tocall.Enumeration of network connection types.
Values
kSbSystemConnectionTypeWired
- The system is on a wired connection.kSbSystemConnectionTypeWireless
- The system is on a wireless connection.kSbSystemConnectionTypeUnknown
- The system connection type is unknown.Enumeration of device types.
Values
kSbSystemDeviceTypeBlueRayDiskPlayer
- Blue-ray Disc Player (BDP).kSbSystemDeviceTypeGameConsole
- A relatively high-powered TV device used primarily for playing games.kSbSystemDeviceTypeOverTheTopBox
- Over the top (OTT) devices stream content via the Internet over anothertype of network, e.g. cable or satellite.kSbSystemDeviceTypeSetTopBox
- Set top boxes (STBs) stream content primarily over cable or satellite.Some STBs can also stream OTT content via the Internet.kSbSystemDeviceTypeTV
- A Smart TV is a TV that can directly run applications that stream OTTcontent via the Internet.kSbSystemDeviceTypeDesktopPC
- Desktop PC.kSbSystemDeviceTypeAndroidTV
- An Android TV Device.kSbSystemDeviceTypeUnknown
- Unknown device.Enumeration of special paths that the platform can define.
Values
kSbSystemPathContentDirectory
- Path to where the local content files that ship with the binary areavailable.kSbSystemPathCacheDirectory
- Path to the directory that can be used as a local file cache, ifavailable.kSbSystemPathDebugOutputDirectory
- Path to the directory where debug output (e.g. logs, trace output,screenshots) can be written into.kSbSystemPathFontDirectory
- Path to a directory where system font files can be found. Should only bespecified on platforms that provide fonts usable by Starboard applications.kSbSystemPathFontConfigurationDirectory
- Path to a directory where system font configuration metadata can befound. May be the same directory as |kSbSystemPathFontDirectory|, but notnecessarily. Should only be specified on platforms that provide fontsusable by Starboard applications.kSbSystemPathSourceDirectory
- Path to the directory containing the root of the source tree.kSbSystemPathTempDirectory
- Path to a directory where temporary files can be written.kSbSystemPathTestOutputDirectory
- Path to a directory where test results can be written.kSbSystemPathExecutableFile
- Full path to the executable file.Possible responses for SbSystemPlatformErrorCallback
.
Values
kSbSystemPlatformErrorResponsePositive
kSbSystemPlatformErrorResponseNegative
Enumeration of possible values for the type
parameter passed to the SbSystemRaisePlatformError
function.
Values
kSbSystemPlatformErrorTypeConnectionError
- Cobalt received a network connection error, or a network disconnectionevent. If the |response| passed to |SbSystemPlatformErrorCallback| is|kSbSystemPlatformErrorResponsePositive| then the request should beretried, otherwise the app should be stopped.kSbSystemPlatformErrorTypeUserSignedOut
- The current user is not signed in.System properties that can be queried for. Many of these are used in User-Agent string generation.
Values
kSbSystemPropertyChipsetModelNumber
- The full model number of the main platform chipset, including anyvendor-specific prefixes.kSbSystemPropertyFirmwareVersion
- The production firmware version number which the device is currentlyrunning.kSbSystemPropertyFriendlyName
- A friendly name for this actual device. It may include user-personalizationlike “Upstairs Bedroom.” It may be displayed to users as part of some kindof device selection (e.g. in-app DIAL).kSbSystemPropertyManufacturerName
- A deprecated alias for |kSbSystemPropertyBrandName|.kSbSystemPropertyBrandName
- The name of the brand under which the device is being sold.kSbSystemPropertyModelName
- The final production model number of the device.kSbSystemPropertyModelYear
- The year the device was launched, e.g. “2016”.kSbSystemPropertyNetworkOperatorName
- The name of the network operator that owns the target device, ifapplicable.kSbSystemPropertyPlatformName
- The name of the operating system and platform, suitable for inclusion in aUser-Agent, say.kSbSystemPropertyPlatformUuid
- A universally-unique ID for the current user.kSbSystemPropertySpeechApiKey
- The Google Speech API key. The platform manufacturer is responsiblefor registering a Google Speech API key for their products. In the APIConsole (http://developers.google.com/console), you can enable theSpeech APIs and generate a Speech API key.kSbSystemPropertyUserAgentAuxField
- A field that, if available, is appended to the user agentPrivate structure used to represent a raised platform error.
Description
Binary searches a sorted table base
of element_count
objects, each element element_width
bytes in size for an element that comparator
compares equal to key
.
This function is meant to be a drop-in replacement for bsearch
.
Declaration and definitions
#include "starboard/system.h" void* SbSystemBinarySearch(const void* /*key*/, const void* /*base*/, size_t /*element_count*/, size_t /*element_width*/, SbSystemComparator /*comparator*/) { return NULL; }
Parameters
Description
Breaks the current program into the debugger, if a debugger is attached. If a debugger is not attached, this function aborts the program.
Declaration and definitions
#include "starboard/system.h" void SbSystemBreakIntoDebugger() { #if SB_IS(COMPILER_GCC) __builtin_unreachable(); #endif }
Description
Clears the last error set by a Starboard call in the current thread.
Declaration and definitions
#include "starboard/system.h" void SbSystemClearLastError() { }
Description
Clears a platform error that was previously raised by a call to SbSystemRaisePlatformError
. The platform may use this, for example, to close a dialog that was opened in response to the error.
Declaration and definitions
#include "starboard/system.h" void SbSystemClearPlatformError(SbSystemPlatformError handle) { SB_UNREFERENCED_PARAMETER(handle); }
Parameters
Description
Returns the device's current network connection type.
Declaration and definitions
#include "starboard/system.h" SbSystemConnectionType SbSystemGetConnectionType() { return kSbSystemConnectionTypeUnknown; }
Description
Returns the type of the device.
Declaration and definitions
#include "starboard/system.h" SbSystemDeviceType SbSystemGetDeviceType() { return kSbSystemDeviceTypeUnknown; }
Description
Generates a human-readable string for an error. The return value specifies the total desired length of the string.
Declaration and definitions
#include "starboard/system.h" int SbSystemGetErrorString(SbSystemError /*error*/, char* /*out_string*/, int /*string_length*/) { return 0; }
Parameters
Description
Gets the last platform-specific error code produced by any Starboard call in the current thread for diagnostic purposes. Semantic reactions to Starboard function call results should be modeled explicitly.
Declaration and definitions
#include "starboard/system.h" SbSystemError SbSystemGetLastError() { return 0; }
Description
Gets the system's current POSIX-style Locale ID. The locale represents the location, language, and cultural conventions that the system wants to use, which affects which text is displayed to the user as well as how displayed numbers, dates, currency, and similar values are formatted.
At its simplest, the locale ID can just be a BCP 47 language code, like en_US
. Currently, POSIX also wants to include the encoding as in en_US.UTF8
. POSIX also allows a couple very bare-bones locales, like “C” or “POSIX”, but they are not supported here. POSIX also supports different locale settings for a few different purposes, but Starboard only exposes one locale at a time.
RFC 5646 describes BCP 47 language codes: https://tools.ietf.org/html/bcp47
For more information than you probably want about POSIX locales, see: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html
Declaration and definitions
#include "starboard/system.h" const char* SbSystemGetLocaleId() { return NULL; }
Description
Returns the number of processor cores available to this application. If the process is sandboxed to a subset of the physical cores, the function returns that sandboxed limit.
Declaration and definitions
#include "starboard/system.h" int SbSystemGetNumberOfProcessors() { return 1; }
Description
Retrieves the platform-defined system path specified by path_id
and places it as a zero-terminated string into the user-allocated out_path
unless it is longer than path_length
- 1. This implementation must be thread-safe.
This function returns true
if the path is retrieved successfully. It returns false
under any of the following conditions and, in any such case, out_path
is not changed:
Declaration and definitions
#include "starboard/system.h" bool SbSystemGetPath(SbSystemPathId /*path_id*/, char* /*out_path*/, int /*path_size*/) { return false; }
Parameters
Description
Retrieves the platform-defined system property specified by property_id
and places its value as a zero-terminated string into the user-allocated out_value
unless it is longer than value_length
- 1. This implementation must be thread-safe.
This function returns true
if the property is retrieved successfully. It returns false
under any of the following conditions and, in any such case, out_value
is not changed:
Declaration and definitions
#include "starboard/system.h" bool SbSystemGetProperty(SbSystemPropertyId /*property_id*/, char* /*out_value*/, int /*value_length*/) { return false; }
Parameters
Description
A cryptographically secure random number generator that produces an arbitrary, non-negative number of buffer_size
random, non-negative bytes. The generated number is placed in out_buffer
. This function does not require manual seeding.
Declaration and definitions
#include "starboard/system.h" void SbSystemGetRandomData(void* /*out_buffer*/, int /*buffer_size*/) { }
#include "starboard/system.h" #include "starboard/file.h" #include "starboard/log.h" #include "starboard/mutex.h" #include "starboard/once.h" namespace { // We keep the open file descriptor for /dev/urandom around so we don't need to // reopen it (which is expensive). class URandomFile { public: URandomFile() { file_ = SbFileOpen("/dev/urandom", kSbFileOpenOnly | kSbFileRead, NULL, NULL); SB_DCHECK(SbFileIsValid(file_)) << "Cannot open /dev/urandom"; } ~URandomFile() { SbFileClose(file_); } SbFile file() const { return file_; } private: SbFile file_; }; // A file that will produce any number of very random bytes. URandomFile* g_urandom_file = NULL; // Control to initialize g_urandom_file. SbOnceControl g_urandom_file_once = SB_ONCE_INITIALIZER; // Lazily initialize g_urandom_file. void InitializeRandom() { SB_DCHECK(g_urandom_file == NULL); g_urandom_file = new URandomFile(); } } // namespace void SbSystemGetRandomData(void* out_buffer, int buffer_size) { SB_DCHECK(out_buffer); char* buffer = reinterpret_cast<char*>(out_buffer); int remaining = buffer_size; bool once_result = SbOnce(&g_urandom_file_once, &InitializeRandom); SB_DCHECK(once_result); SbFile file = g_urandom_file->file(); do { // This is unsynchronized access to the File that could happen from multiple // threads. It doesn't appear that there is any locking in the Chromium // POSIX implementation that is very similar. int result = SbFileRead(file, buffer, remaining); if (result <= 0) break; remaining -= result; buffer += result; } while (remaining); SB_CHECK(remaining == 0); }
Parameters
Description
A cryptographically secure random number generator that gets 64 random bits and returns them as an uint64_t
. This function does not require manual seeding.
Declaration
SB_EXPORT uint64_t SbSystemGetRandomUInt64();
Description
Places up to stack_size
instruction pointer addresses of the current execution stack into out_stack
. The return value specifies the number of entries added.
The returned stack frames are in “downward” order from the calling frame toward the entry point of the thread. So, if all the stack frames do not fit, the ones truncated will be the less interesting ones toward the thread entry point.
This function is used in crash signal handlers and, therefore, it must be async-signal-safe on platforms that support signals. The following document discusses what it means to be async-signal-safe on POSIX: http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03
Declaration and definitions
#include "starboard/system.h" int SbSystemGetStack(void** /*out_stack*/, int /*stack_size*/) { return 0; }
#include "starboard/system.h" #include <execinfo.h> #include <algorithm> int SbSystemGetStack(void** out_stack, int stack_size) { int count = std::max(backtrace(out_stack, stack_size), 0); if (count < 1) { // No stack, for some reason. return count; } // We have an extra stack frame (for this very function), so let's remove it. for (int i = 1; i < count; ++i) { out_stack[i - 1] = out_stack[i]; } return count - 1; }
Parameters
Description
Returns the total CPU memory (in bytes) potentially available to this application. If the process is sandboxed to a maximum allowable limit, the function returns the lesser of the physical and sandbox limits.
Declaration and definitions
#include "starboard/system.h" int64_t SbSystemGetTotalCPUMemory() { return 0; }
#include "starboard/system.h" #include <unistd.h> #include "starboard/log.h" int64_t SbSystemGetTotalCPUMemory() { long pages = sysconf(_SC_PHYS_PAGES); // NOLINT[runtime/int] long page_size = sysconf(_SC_PAGE_SIZE); // NOLINT[runtime/int] if (pages == -1 || page_size == -1) { SB_NOTREACHED(); return 0; } return static_cast<int64_t>(pages) * page_size; }
Description
Returns the total GPU memory (in bytes) available for use by this application. This function may only be called the return value for calls to SbSystemHasCapability(kSbSystemCapabilityCanQueryGPUMemoryStats) is true
.
Declaration and definitions
#include "starboard/system.h" int64_t SbSystemGetTotalGPUMemory() { return 0; }
Description
Returns the total physical CPU memory (in bytes) used by this application. This value should always be less than (or, in particularly exciting situations, equal to) SbSystemGetTotalCPUMemory().
Declaration and definitions
#include "starboard/system.h" int64_t SbSystemGetUsedCPUMemory() { return 0; }
#include "starboard/system.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/sysinfo.h> #include <sys/types.h> #include <unistd.h> #include "starboard/file.h" #include "starboard/log.h" #include "starboard/string.h" // We find the current amount of used memory on Linux by opening // '/proc/self/status' and scan the file for its "VmRSS" entry. Essentially, // we need to parse a buffer that has the following format: // // xxxxxx: 45327 kB // yyyyyy: 23 kB // VmRSS: 87432 kB // zzzzzz: 3213 kB // ... // // And here, we would want to return the value 87432 * 1024. // See http://man7.org/linux/man-pages/man5/proc.5.html for more details. // Searches for the value of VmRSS and returns it. Will modify |buffer| in // order to do so quickly and easily. int64_t SearchForVmRSSValue(char* buffer, size_t length) { // Search for the string ""VmRSS:". const char kSearchString[] = "\nVmRSS:"; enum State { // We are currently searching for kSearchString kSearchingForSearchString, // We found the search string and are advancing through spaces/tabs until // we see a number. kAdvancingSpacesToNumber, // We found the number and are now searching for the end of it. kFindingEndOfNumber, }; State state = kSearchingForSearchString; const char* number_start = NULL; for (size_t i = 0; i < length - sizeof(kSearchString); ++i) { if (state == kSearchingForSearchString) { if (SbStringCompare(&buffer[i], kSearchString, sizeof(kSearchString) - 1) == 0) { // Advance until we find a number. state = kAdvancingSpacesToNumber; i += sizeof(kSearchString) - 2; } } else if (state == kAdvancingSpacesToNumber) { if (buffer[i] >= '0' && buffer[i] <= '9') { // We found the start of the number, record where that is and then // continue searching for the end of the number. number_start = &buffer[i]; state = kFindingEndOfNumber; } } else { SB_DCHECK(state == kFindingEndOfNumber); if (buffer[i] < '0' || buffer[i] > '9') { // Drop a null at the end of the number so that we can call atoi() on // it and return. buffer[i] = '\0'; return SbStringAToI(number_start); } } } SB_LOG(ERROR) << "Could not find 'VmRSS:' in /proc/self/status."; return 0; } int64_t SbSystemGetUsedCPUMemory() { // Read our process' current physical memory usage from /proc/self/status. // This requires a bit of parsing through the output to find the value for // the "VmRSS" field which indicates used physical memory. starboard::ScopedFile status_file("/proc/self/status", kSbFileOpenOnly | kSbFileRead); if (!status_file.IsValid()) { SB_LOG(ERROR) << "Error opening /proc/self/status in order to query self memory " "usage."; return 0; } // Read the entire file into memory. const int kBufferSize = 2048; char buffer[kBufferSize]; int remaining = kBufferSize; char* output_pointer = buffer; do { int result = status_file.Read(output_pointer, remaining); if (result <= 0) break; remaining -= result; output_pointer += result; } while (remaining); // Return the result, multiplied by 1024 because it is given in kilobytes. return SearchForVmRSSValue(buffer, static_cast<size_t>(output_pointer - buffer)) * 1024; }
Description
Returns the current amount of GPU memory (in bytes) that is currently being used by this application. This function may only be called if the return value for calls to SbSystemHasCapability(kSbSystemCapabilityCanQueryGPUMemoryStats) is true
.
Declaration and definitions
#include "starboard/system.h" int64_t SbSystemGetUsedGPUMemory() { return 0; }
Description
Returns whether the platform has the runtime capability specified by capability_id
. Returns false for any unknown capabilities. This implementation must be thread-safe.
Declaration and definitions
#include "starboard/system.h" bool SbSystemHasCapability(SbSystemCapabilityId /*capability_id*/) { return false; }
Parameters
Description
Hides the system splash screen on systems that support a splash screen that is displayed while the application is loading. This function may be called from any thread and must be idempotent.
Declaration and definitions
#include "starboard/system.h" void SbSystemHideSplashScreen() {}
Description
Attempts to determine whether the current program is running inside or attached to a debugger. The function returns false
if neither of those cases is true.
Declaration and definitions
#include "starboard/system.h" bool SbSystemIsDebuggerAttached() { return false; }
#include "starboard/system.h" #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "starboard/log.h" #include "starboard/shared/posix/file_internal.h" #include "starboard/shared/posix/handle_eintr.h" // Adapted from base/debug/debugger_posix.cc bool SbSystemIsDebuggerAttached() { // We can look in /proc/self/status for TracerPid. We are likely used in // crash handling, so we are careful not to use the heap or have side effects. // Another option that is common is to try to ptrace yourself, but then we // can't detach without forking(), and that's not so great. // NOTE: This code MUST be async-signal safe (it's used by in-process stack // dumping signal handler). NO malloc or stdio is allowed here. int status_fd = open("/proc/self/status", O_RDONLY); if (status_fd == -1) return false; // We assume our line will be in the first 1024 characters and that we can // read this much all at once. In practice this will generally be true. // This simplifies and speeds up things considerably. char buf[1024]; ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf) - 1)); SB_DCHECK(num_read < sizeof(buf)); if (HANDLE_EINTR(close(status_fd)) < 0) return false; if (num_read <= 0) return false; buf[num_read] = '\0'; const char tracer[] = "TracerPid:\t"; char* pid_index = strstr(buf, tracer); if (pid_index == NULL) return false; // Our pid is 0 without a debugger, assume this for any pid starting with 0. pid_index += strlen(tracer); return pid_index < (buf + num_read) && *pid_index != '0'; }
Description
Checks whether a SbSystemPlatformError
is valid.
Declaration
static SB_C_INLINE bool SbSystemPlatformErrorIsValid( SbSystemPlatformError handle) { return handle != kSbSystemPlatformErrorInvalid; }
Parameters
Description
Cobalt calls this function to notify the platform that an error has occurred in the application that the platform may need to handle. The platform is expected to then notify the user of the error and to provide a means for any required interaction, such as by showing a dialog.
The return value is a handle that may be used in a subsequent call to SbClearPlatformError
. For example, the handle could be used to programatically dismiss a dialog that was raised in response to the error. The lifetime of the object referenced by the handle is until the user reacts to the error or the error is dismissed by a call to SbSystemClearPlatformError, whichever happens first. Note that if the platform cannot respond to the error, then this function should return kSbSystemPlatformErrorInvalid
.
This function may be called from any thread, and it is the platform's responsibility to decide how to handle an error received while a previous error is still pending. If that platform can only handle one error at a time, then it may queue the second error or ignore it by returning kSbSystemPlatformErrorInvalid
.
Declaration and definitions
#include "starboard/system.h" #include "starboard/log.h" SbSystemPlatformError SbSystemRaisePlatformError( SbSystemPlatformErrorType type, SbSystemPlatformErrorCallback callback, void* user_data) { SB_UNREFERENCED_PARAMETER(callback); SB_UNREFERENCED_PARAMETER(user_data); std::string message; switch (type) { case kSbSystemPlatformErrorTypeConnectionError: message = "Connection error."; break; #if SB_API_VERSION < 6 case kSbSystemPlatformErrorTypeUserSignedOut: message = "User is not signed in."; break; case kSbSystemPlatformErrorTypeUserAgeRestricted: message = "User is age restricted."; break; #endif default: message = "<unknown>"; break; } SB_DLOG(INFO) << "SbSystemRaisePlatformError: " << message; return kSbSystemPlatformErrorInvalid; }
Parameters
Description
Requests that the application move into the Paused state at the next convenient point. This should roughly correspond to “unfocused application” in a traditional window manager, where the application may be partially visible.
This function eventually causes a kSbEventTypePause
event to be dispatched to the application. Before the kSbEventTypePause
event is dispatched, some work may continue to be done, and unrelated system events may be dispatched.
Declaration and definitions
#include "starboard/system.h" void SbSystemRequestPause() { }
Description
Requests that the application be terminated gracefully at the next convenient point. In the meantime, some work may continue to be done, and unrelated system events may be dispatched. This function eventually causes a kSbEventTypeStop
event to be dispatched to the application. When the process finally terminates, it returns error_level
, if that has any meaning on the current platform.
Declaration and definitions
#include "starboard/system.h" void SbSystemRequestStop(int /*error_level*/) { }
Parameters
Description
Requests that the application move into the Suspended state at the next convenient point. This should roughly correspond to “minimization” in a traditional window manager, where the application is no longer visible.
This function eventually causes a kSbEventTypeSuspend
event to be dispatched to the application. Before the kSbEventTypeSuspend
event is dispatched, some work may continue to be done, and unrelated system events may be dispatched.
In the Suspended state, the application will be resident, but probably not running. The expectation is that an external system event will bring the application out of the Suspended state.
Declaration and definitions
#include "starboard/system.h" void SbSystemRequestSuspend() { }
Description
Requests that the application move into the Started state at the next convenient point. This should roughly correspond to a “focused application” in a traditional window manager, where the application is fully visible and the primary receiver of input events.
This function eventually causes a kSbEventTypeUnpause
event to be dispatched to the application. Before kSbEventTypeUnpause
is dispatched, some work may continue to be done, and unrelated system events may be dispatched.
Declaration and definitions
#include "starboard/system.h" void SbSystemRequestUnpause() { }
Description
Sorts an array of elements base
, with element_count
elements of element_width
bytes each, using comparator
as the comparison function.
This function is meant to be a drop-in replacement for qsort
.
Declaration and definitions
#include "starboard/system.h" void SbSystemSort(void* /*base*/, size_t /*element_count*/, size_t /*element_width*/, SbSystemComparator /*comparator*/) { }
Parameters
Description
Looks up address
as an instruction pointer and places up to (buffer_size - 1
) characters of the symbol associated with it in out_buffer
, which must not be NULL. out_buffer
will be NULL-terminated.
The return value indicates whether the function found a reasonable match for address
. If the return value is false
, then out_buffer
is not modified.
This function is used in crash signal handlers and, therefore, it must be async-signal-safe on platforms that support signals.
Declaration and definitions
#include "starboard/system.h" bool SbSystemSymbolize(const void* /*address*/, char* /*out_buffer*/, int /*buffer_size*/) { return false; }
#include "starboard/system.h" #include "base/third_party/symbolize/symbolize.h" bool SbSystemSymbolize(const void* address, char* out_buffer, int buffer_size) { // I believe this casting-away const in the implementation is better than the // alternative of removing const-ness from the address parameter. return google::Symbolize(const_cast<void*>(address), out_buffer, buffer_size); }
Parameters