Global: replaces NULL to nullptr

This commit is contained in:
李通洲
2026-07-10 18:08:04 +08:00
parent 873454191f
commit ba18705d2e
387 changed files with 2411 additions and 2411 deletions
+3 -3
View File
@@ -23,13 +23,13 @@ bool ffListPop(FFlist* list, uint32_t elementSize, void* __restrict result);
static inline void ffListInit(FFlist* list) { static inline void ffListInit(FFlist* list) {
list->capacity = 0; list->capacity = 0;
list->length = 0; list->length = 0;
list->data = NULL; list->data = nullptr;
} }
static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) { static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) {
ffListInit(list); ffListInit(list);
list->capacity = capacity; list->capacity = capacity;
list->data = __builtin_expect(capacity == 0, 0) ? NULL : (uint8_t*) malloc((size_t) capacity * elementSize); list->data = __builtin_expect(capacity == 0, 0) ? nullptr : (uint8_t*) malloc((size_t) capacity * elementSize);
} }
FF_A_NODISCARD static inline FFlist ffListCreate() { FF_A_NODISCARD static inline FFlist ffListCreate() {
@@ -87,7 +87,7 @@ static inline void ffListDestroy(FFlist* list) {
// Avoid free-after-use. These 3 assignments are cheap so don't remove them // Avoid free-after-use. These 3 assignments are cheap so don't remove them
list->capacity = list->length = 0; list->capacity = list->length = 0;
free(list->data); free(list->data);
list->data = NULL; list->data = nullptr;
} }
static inline void ffListClear(FFlist* list) { static inline void ffListClear(FFlist* list) {
+16 -16
View File
@@ -90,7 +90,7 @@ void ffStrbufLowerCase(FFstrbuf* strbuf);
// Function alters the buffer to extract lines or delimited segments (replaces the delimiter with '\0') // Function alters the buffer to extract lines or delimited segments (replaces the delimiter with '\0')
// so that buffer MUST be heap allocated (NOT a static string) // so that buffer MUST be heap allocated (NOT a static string)
// `lineptr` must be `NULL` and `n` MUST be `0` for the first call // `lineptr` must be `nullptr` and `n` MUST be `0` for the first call
// Caller MUST NOT free `*lineptr` // Caller MUST NOT free `*lineptr`
bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer); bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer);
void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer); void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer);
@@ -103,7 +103,7 @@ void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf
* @param[in,out] lineptr The pointer to a pointer that will be set to the start of the line * @param[in,out] lineptr The pointer to a pointer that will be set to the start of the line
(points to buffer's internal memory address to avoid memory allocation and copy). (points to buffer's internal memory address to avoid memory allocation and copy).
MUST NOT be freed by the caller, unlike `getline(3)`. MUST NOT be freed by the caller, unlike `getline(3)`.
* MUST be NULL for the first call. * MUST be nullptr for the first call.
* @param[in,out] n The pointer to the size of the buffer of lineptr. * @param[in,out] n The pointer to the size of the buffer of lineptr.
MUST be 0 for the first call. MUST be 0 for the first call.
* @param[in] buffer The buffer to read from. * @param[in] buffer The buffer to read from.
@@ -186,7 +186,7 @@ static inline void ffStrbufDestroy(FFstrbuf* strbuf) {
} }
FF_A_NODISCARD static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) { FF_A_NODISCARD static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) {
assert(strbuf != NULL); assert(strbuf != nullptr);
if (strbuf->allocated == 0) { if (strbuf->allocated == 0) {
return 0; return 0;
} }
@@ -210,7 +210,7 @@ static inline void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) {
static inline void ffStrbufClear(FFstrbuf* strbuf) { static inline void ffStrbufClear(FFstrbuf* strbuf) {
assert(strbuf != NULL); assert(strbuf != nullptr);
extern char* CHAR_NULL_PTR; extern char* CHAR_NULL_PTR;
if (strbuf->allocated == 0) { if (strbuf->allocated == 0) {
@@ -244,7 +244,7 @@ static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) {
} }
static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) { static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
if (__builtin_expect(value == NULL || length == 0, false)) { if (__builtin_expect(value == nullptr || length == 0, false)) {
return; return;
} }
if (__builtin_expect(ffStrbufGetFree(strbuf) < length, false)) { if (__builtin_expect(ffStrbufGetFree(strbuf) < length, false)) {
@@ -258,7 +258,7 @@ static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const cha
static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) { static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) {
assert(value != strbuf); assert(value != strbuf);
if (value == NULL) { if (value == nullptr) {
return; return;
} }
ffStrbufAppendNS(strbuf, value->length, value->chars); ffStrbufAppendNS(strbuf, value->length, value->chars);
@@ -269,9 +269,9 @@ static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) {
} }
static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) { static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) {
assert(strbuf != NULL); assert(strbuf != nullptr);
if (value == NULL) { if (value == nullptr) {
ffStrbufClear(strbuf); ffStrbufClear(strbuf);
} else { } else {
ffStrbufSetNS(strbuf, (uint32_t) strlen(value), value); ffStrbufSetNS(strbuf, (uint32_t) strlen(value), value);
@@ -279,7 +279,7 @@ static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) {
} }
static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
assert(strbuf != NULL); assert(strbuf != nullptr);
if (yyjson_is_str(jsonVal)) { if (yyjson_is_str(jsonVal)) {
ffStrbufSetNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal)); ffStrbufSetNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal));
@@ -291,7 +291,7 @@ static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
} }
static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) { static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) {
if (value == NULL) { if (value == nullptr) {
return; return;
} }
ffStrbufAppendNS(strbuf, (uint32_t) strlen(value), value); ffStrbufAppendNS(strbuf, (uint32_t) strlen(value), value);
@@ -339,7 +339,7 @@ static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) {
free(strbuf->chars); free(strbuf->chars);
} }
if (value != NULL) { if (value != nullptr) {
ffStrbufInitStatic(strbuf, value); ffStrbufInitStatic(strbuf, value);
} else { } else {
ffStrbufInit(strbuf); ffStrbufInit(strbuf);
@@ -374,14 +374,14 @@ FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateS(const char* str) {
} }
static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) { static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) {
if (value == NULL) { if (value == nullptr) {
return; return;
} }
ffStrbufPrependNS(strbuf, value->length, value->chars); ffStrbufPrependNS(strbuf, value->length, value->chars);
} }
static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) { static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) {
if (value == NULL) { if (value == nullptr) {
return; return;
} }
ffStrbufPrependNS(strbuf, (uint32_t) strlen(value), value); ffStrbufPrependNS(strbuf, (uint32_t) strlen(value), value);
@@ -421,11 +421,11 @@ static inline FF_A_NODISCARD bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, c
} }
static inline FF_A_NODISCARD bool ffStrbufContainC(const FFstrbuf* strbuf, char c) { static inline FF_A_NODISCARD bool ffStrbufContainC(const FFstrbuf* strbuf, char c) {
return memchr(strbuf->chars, c, strbuf->length) != NULL; return memchr(strbuf->chars, c, strbuf->length) != nullptr;
} }
static inline FF_A_NODISCARD bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) { static inline FF_A_NODISCARD bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) {
return strstr(strbuf->chars, str) != NULL; return strstr(strbuf->chars, str) != nullptr;
} }
static inline FF_A_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) { static inline FF_A_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) {
@@ -433,7 +433,7 @@ static inline FF_A_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const
} }
static inline FF_A_NODISCARD bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) { static inline FF_A_NODISCARD bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) {
return strcasestr(strbuf->chars, str) != NULL; return strcasestr(strbuf->chars, str) != nullptr;
} }
static inline FF_A_NODISCARD bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) { static inline FF_A_NODISCARD bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) {
+25 -25
View File
@@ -5,13 +5,13 @@ const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result) {
if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt64Type, result)) { if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt64Type, result)) {
return "Number type is not SInt64"; return "Number type is not SInt64";
} }
return NULL; return nullptr;
} else if (CFGetTypeID(cf) == CFDataGetTypeID()) { } else if (CFGetTypeID(cf) == CFDataGetTypeID()) {
if (CFDataGetLength((CFDataRef) cf) != sizeof(int64_t)) { if (CFDataGetLength((CFDataRef) cf) != sizeof(int64_t)) {
return "Data length is not sizeof(int64_t)"; return "Data length is not sizeof(int64_t)";
} }
CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(int64_t)), (uint8_t*) result); CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(int64_t)), (uint8_t*) result);
return NULL; return nullptr;
} }
return "TypeID is neither 'CFNumber' nor 'CFData'"; return "TypeID is neither 'CFNumber' nor 'CFData'";
@@ -22,13 +22,13 @@ const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result) {
if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt32Type, result)) { if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt32Type, result)) {
return "Number type is not SInt32"; return "Number type is not SInt32";
} }
return NULL; return nullptr;
} else if (CFGetTypeID(cf) == CFDataGetTypeID()) { } else if (CFGetTypeID(cf) == CFDataGetTypeID()) {
if (CFDataGetLength((CFDataRef) cf) != sizeof(*result)) { if (CFDataGetLength((CFDataRef) cf) != sizeof(*result)) {
return "Data length is not sizeof(int32_t)"; return "Data length is not sizeof(int32_t)";
} }
CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(*result)), (uint8_t*) result); CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(*result)), (uint8_t*) result);
return NULL; return nullptr;
} }
return "TypeID is neither 'CFNumber' nor 'CFData'"; return "TypeID is neither 'CFNumber' nor 'CFData'";
@@ -40,7 +40,7 @@ const char* ffCfNumGetDouble(CFTypeRef cf, double* result) {
!CFNumberGetValue((CFNumberRef) cf, kCFNumberFloatType, result)) { !CFNumberGetValue((CFNumberRef) cf, kCFNumberFloatType, result)) {
return "Number type is not Double or Float"; return "Number type is not Double or Float";
} }
return NULL; return nullptr;
} }
return "TypeID is neither 'CFNumber'"; return "TypeID is neither 'CFNumber'";
@@ -54,13 +54,13 @@ const char* ffCfDateGetEpoch(CFTypeRef cf, uint64_t* result) {
CFAbsoluteTime absTime = CFDateGetAbsoluteTime((CFDateRef) cf); CFAbsoluteTime absTime = CFDateGetAbsoluteTime((CFDateRef) cf);
// Convert from seconds to milliseconds and add the difference between 1970 and 2001 in milliseconds // Convert from seconds to milliseconds and add the difference between 1970 and 2001 in milliseconds
*result = (uint64_t) ((absTime + 978307200 /*kCFAbsoluteTimeIntervalSince1970*/) * 1000); *result = (uint64_t) ((absTime + 978307200 /*kCFAbsoluteTimeIntervalSince1970*/) * 1000);
return NULL; return nullptr;
} }
const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) {
ffStrbufClear(result); ffStrbufClear(result);
if (!cf) { if (!cf) {
return NULL; return nullptr;
} }
if (CFGetTypeID(cf) == CFStringGetTypeID()) { if (CFGetTypeID(cf) == CFStringGetTypeID()) {
@@ -72,7 +72,7 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) {
} else { } else {
uint32_t length = (uint32_t) CFStringGetLength(cfStr); uint32_t length = (uint32_t) CFStringGetLength(cfStr);
if (length == 0) { if (length == 0) {
return NULL; return nullptr;
} }
ffStrbufEnsureFixedLengthFree(result, (uint32_t) CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8)); ffStrbufEnsureFixedLengthFree(result, (uint32_t) CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8));
if (!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) { if (!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) {
@@ -86,7 +86,7 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) {
CFDataRef cfData = (CFDataRef) cf; CFDataRef cfData = (CFDataRef) cf;
uint32_t length = (uint32_t) CFDataGetLength(cfData); uint32_t length = (uint32_t) CFDataGetLength(cfData);
if (length == 0) { if (length == 0) {
return NULL; return nullptr;
} }
ffStrbufEnsureFixedLengthFree(result, length + 1); ffStrbufEnsureFixedLengthFree(result, length + 1);
CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars);
@@ -96,20 +96,20 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) {
return "TypeID is neither 'CFString' nor 'CFData'"; return "TypeID is neither 'CFString' nor 'CFData'";
} }
return NULL; return nullptr;
} }
const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) { const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) {
ffStrbufClear(result); ffStrbufClear(result);
if (!cf) { if (!cf) {
return NULL; return nullptr;
} }
if (CFGetTypeID(cf) == CFDataGetTypeID()) { if (CFGetTypeID(cf) == CFDataGetTypeID()) {
CFDataRef cfData = (CFDataRef) cf; CFDataRef cfData = (CFDataRef) cf;
uint32_t length = (uint32_t) CFDataGetLength(cfData); uint32_t length = (uint32_t) CFDataGetLength(cfData);
if (length == 0) { if (length == 0) {
return NULL; return nullptr;
} }
ffStrbufEnsureFixedLengthFree(result, length + 1); ffStrbufEnsureFixedLengthFree(result, length + 1);
CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars);
@@ -119,12 +119,12 @@ const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) {
return "TypeID is not 'CFData'"; return "TypeID is not 'CFData'";
} }
return NULL; return nullptr;
} }
const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -133,7 +133,7 @@ const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* r
const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -142,7 +142,7 @@ const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstr
const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) { const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) {
CFBooleanRef cf = (CFBooleanRef) CFDictionaryGetValue(dict, key); CFBooleanRef cf = (CFBooleanRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -151,12 +151,12 @@ const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result)
} }
*result = CFBooleanGetValue(cf); *result = CFBooleanGetValue(cf);
return NULL; return nullptr;
} }
const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) { const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -165,7 +165,7 @@ const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) {
const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* result) { const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -174,7 +174,7 @@ const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* res
const char* ffCfDictGetDouble(CFDictionaryRef dict, CFStringRef key, double* result) { const char* ffCfDictGetDouble(CFDictionaryRef dict, CFStringRef key, double* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -183,7 +183,7 @@ const char* ffCfDictGetDouble(CFDictionaryRef dict, CFStringRef key, double* res
const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offset, uint32_t size, uint8_t* result, uint32_t* length) { const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offset, uint32_t size, uint8_t* result, uint32_t* length) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
@@ -202,22 +202,22 @@ const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offs
} }
CFDataGetBytes((CFDataRef) cf, CFRangeMake(offset, size), result); CFDataGetBytes((CFDataRef) cf, CFRangeMake(offset, size), result);
return NULL; return nullptr;
} }
const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result) { const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result) {
CFDictionaryRef cf = (CFDictionaryRef) CFDictionaryGetValue(dict, key); CFDictionaryRef cf = (CFDictionaryRef) CFDictionaryGetValue(dict, key);
if (cf == NULL || CFGetTypeID(cf) != CFDictionaryGetTypeID()) { if (cf == nullptr || CFGetTypeID(cf) != CFDictionaryGetTypeID()) {
return "TypeID is not 'CFDictionary'"; return "TypeID is not 'CFDictionary'";
} }
*result = cf; *result = cf;
return NULL; return nullptr;
} }
const char* ffCfDictGetDateAsEpoch(CFDictionaryRef dict, CFStringRef key, uint64_t* result) { const char* ffCfDictGetDateAsEpoch(CFDictionaryRef dict, CFStringRef key, uint64_t* result) {
CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key);
if (cf == NULL) { if (cf == nullptr) {
return "CFDictionaryGetValue() failed"; return "CFDictionaryGetValue() failed";
} }
+1 -1
View File
@@ -4,7 +4,7 @@
#include <CoreFoundation/CoreFoundation.h> #include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h> #include <IOKit/IOKitLib.h>
// Return error info if failed, NULL otherwise // Return error info if failed, nullptr otherwise
const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result); const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result);
const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result); const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result);
const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result); const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result);
+10 -10
View File
@@ -86,7 +86,7 @@ static const char* smcCall(io_connect_t conn, uint32_t selector, SmcKeyData_t* i
if (IOConnectCallStructMethod(conn, selector, inputStructure, size, outputStructure, &size) != kIOReturnSuccess) { if (IOConnectCallStructMethod(conn, selector, inputStructure, size, outputStructure, &size) != kIOReturnSuccess) {
return "IOConnectCallStructMethod(conn) failed"; return "IOConnectCallStructMethod(conn) failed";
} }
return NULL; return nullptr;
} }
// Provides key info, using a cache to dramatically improve the energy impact of smcFanControl // Provides key info, using a cache to dramatically improve the energy impact of smcFanControl
@@ -103,7 +103,7 @@ static const char* smcGetKeyInfo(io_connect_t conn, const uint32_t key, SmcKeyDa
} }
*key_info = outputStructure.keyInfo; *key_info = outputStructure.keyInfo;
return NULL; return nullptr;
} }
static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcVal_t* val) { static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcVal_t* val) {
@@ -130,7 +130,7 @@ static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcV
memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes));
return NULL; return nullptr;
} }
static const char* smcOpen(io_connect_t* conn) { static const char* smcOpen(io_connect_t* conn) {
@@ -143,13 +143,13 @@ static const char* smcOpen(io_connect_t* conn) {
return "IOServiceOpen() failed"; return "IOServiceOpen() failed";
} }
return NULL; return nullptr;
} }
static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, double* value) { static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, double* value) {
SmcVal_t val = { 0 }; SmcVal_t val = { 0 };
const char* error = smcReadSmcVal(conn, key, &val); const char* error = smcReadSmcVal(conn, key, &val);
if (error != NULL) { if (error != nullptr) {
return error; return error;
} }
if (val.dataSize == 0) { if (val.dataSize == 0) {
@@ -270,7 +270,7 @@ static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, doubl
default: default:
return "Unsupported SMC data type"; return "Unsupported SMC data type";
} }
return NULL; return nullptr;
} }
static bool detectTemp(io_connect_t conn, const char* sensor, double* sum) { static bool detectTemp(io_connect_t conn, const char* sensor, double* sum) {
@@ -291,7 +291,7 @@ static io_connect_t conn;
const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) { const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) {
if (!conn) { if (!conn) {
if (smcOpen(&conn) != NULL) { if (smcOpen(&conn) != nullptr) {
conn = (io_connect_t) -1; conn = (io_connect_t) -1;
} }
} }
@@ -303,12 +303,12 @@ const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) {
return "Could not read SMC temperature"; return "Could not read SMC temperature";
} }
return NULL; return nullptr;
} }
const char* ffDetectSmcTemps(enum FFTempType type, double* result) { const char* ffDetectSmcTemps(enum FFTempType type, double* result) {
if (!conn) { if (!conn) {
if (smcOpen(&conn) != NULL) { if (smcOpen(&conn) != nullptr) {
conn = (io_connect_t) -1; conn = (io_connect_t) -1;
} }
} }
@@ -461,5 +461,5 @@ const char* ffDetectSmcTemps(enum FFTempType type, double* result) {
*result /= count; *result /= count;
return NULL; return nullptr;
} }
+1 -1
View File
@@ -11,7 +11,7 @@
* @param userdata User-provided data passed to the callback function * @param userdata User-provided data passed to the callback function
* @param minLength Minimum length of strings to extract * @param minLength Minimum length of strings to extract
* *
* @return NULL on success, error message on failure. * @return nullptr on success, error message on failure.
* @note This function won't return an error if no strings are found. * @note This function won't return an error if no strings are found.
* Always check if strings are correctly extracted after this function all. * Always check if strings are correctly extracted after this function all.
*/ */
+2 -2
View File
@@ -26,7 +26,7 @@ typedef struct FFDBusData {
DBusConnection* connection; DBusConnection* connection;
} FFDBusData; } FFDBusData;
const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); // Returns an error message or NULL on success const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); // Returns an error message or nullptr on success
bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result); bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result);
bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result); bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result);
bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint64_t* result); bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint64_t* result);
@@ -38,7 +38,7 @@ bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* ob
void ffDBusDestroyData(FFDBusData* data); void ffDBusDestroyData(FFDBusData* data);
static inline DBusMessage* ffDBusGetAllProperties(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface) { static inline DBusMessage* ffDBusGetAllProperties(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface) {
return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface, NULL); return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface, nullptr);
} }
#define FF_DBUS_AUTO_DESTROY_DATA FF_A_CLEANUP(ffDBusDestroyData) #define FF_DBUS_AUTO_DESTROY_DATA FF_A_CLEANUP(ffDBusDestroyData)
+2 -2
View File
@@ -6,11 +6,11 @@
static inline const char* ffFindFileName(const char* file) { static inline const char* ffFindFileName(const char* file) {
const char* lastSlash = __builtin_strrchr(file, '/'); const char* lastSlash = __builtin_strrchr(file, '/');
#ifdef _WIN32 #ifdef _WIN32
if (lastSlash == NULL) { if (lastSlash == nullptr) {
lastSlash = __builtin_strrchr(file, '\\'); lastSlash = __builtin_strrchr(file, '\\');
} }
#endif #endif
if (lastSlash != NULL) { if (lastSlash != nullptr) {
return lastSlash + 1; return lastSlash + 1;
} }
return file; return file;
+1 -1
View File
@@ -21,5 +21,5 @@ void ffFontInitWithSpace(FFfont* font, const char* rawName);
void ffFontDestroy(FFfont* font); void ffFontDestroy(FFfont* font);
static inline void ffFontInitCopy(FFfont* font, const char* name) { static inline void ffFontInitCopy(FFfont* font, const char* name) {
ffFontInitValues(font, name, NULL); ffFontInitValues(font, name, nullptr);
} }
+6 -6
View File
@@ -57,7 +57,7 @@ static void getExePath(FFPlatform* platform) {
4, 4,
exePath, exePath,
&exePathLen, &exePathLen,
NULL, nullptr,
0) < 0) 0) < 0)
exePathLen = 0; exePathLen = 0;
else { else {
@@ -68,7 +68,7 @@ static void getExePath(FFPlatform* platform) {
// Current implementation uses argv[0], which can be easily spoofed. // Current implementation uses argv[0], which can be easily spoofed.
// See #2195 // See #2195
size_t exePathLen = 0; size_t exePathLen = 0;
kvm_t* kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL); kvm_t* kd = kvm_openfiles(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr);
if (kd) { if (kd) {
int kpCount; int kpCount;
struct kinfo_proc* kp = kvm_getprocs(kd, KERN_PROC_PID, (pid_t) platform->pid, sizeof(*kp), &kpCount); struct kinfo_proc* kp = kvm_getprocs(kd, KERN_PROC_PID, (pid_t) platform->pid, sizeof(*kp), &kpCount);
@@ -77,7 +77,7 @@ static void getExePath(FFPlatform* platform) {
if (argv && argv[0]) { if (argv && argv[0]) {
char* arg0 = argv[0]; char* arg0 = argv[0];
if (arg0[0]) { if (arg0[0]) {
if (strchr(arg0, '/') != NULL) // likely a path (absolute or relative) if (strchr(arg0, '/') != nullptr) // likely a path (absolute or relative)
{ {
exePathLen = strlen(arg0); exePathLen = strlen(arg0);
if (exePathLen < ARRAY_SIZE(exePath)) { if (exePathLen < ARRAY_SIZE(exePath)) {
@@ -88,7 +88,7 @@ static void getExePath(FFPlatform* platform) {
} }
} else { } else {
FF_STRBUF_AUTO_DESTROY tmpPath = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY tmpPath = ffStrbufCreate();
if (ffFindExecutableInPath(arg0, &tmpPath) == NULL && tmpPath.length < ARRAY_SIZE(exePath)) { if (ffFindExecutableInPath(arg0, &tmpPath) == nullptr && tmpPath.length < ARRAY_SIZE(exePath)) {
memcpy(exePath, tmpPath.chars, tmpPath.length + 1); memcpy(exePath, tmpPath.chars, tmpPath.length + 1);
exePathLen = tmpPath.length; exePathLen = tmpPath.length;
} }
@@ -282,7 +282,7 @@ static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) {
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__)
size_t length = sizeof(info->pageSize); size_t length = sizeof(info->pageSize);
sysctl((int[]) { CTL_HW, HW_PAGESIZE }, 2, &info->pageSize, &length, NULL, 0); sysctl((int[]) { CTL_HW, HW_PAGESIZE }, 2, &info->pageSize, &length, nullptr, 0);
#else #else
info->pageSize = (uint32_t) sysconf(_SC_PAGESIZE); info->pageSize = (uint32_t) sysconf(_SC_PAGESIZE);
#endif #endif
@@ -290,7 +290,7 @@ static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) {
static void getCwd(FFPlatform* platform) { static void getCwd(FFPlatform* platform) {
char cwd[PATH_MAX]; char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) { if (getcwd(cwd, sizeof(cwd)) != nullptr) {
ffStrbufSetS(&platform->cwd, cwd); ffStrbufSetS(&platform->cwd, cwd);
ffStrbufEnsureEndsWithC(&platform->cwd, '/'); ffStrbufEnsureEndsWithC(&platform->cwd, '/');
} }
+18 -18
View File
@@ -21,10 +21,10 @@ static void getExePath(FFPlatform* platform) {
ffGetPeb()->ProcessParameters->ImagePathName.Buffer, ffGetPeb()->ProcessParameters->ImagePathName.Buffer,
GENERIC_READ, GENERIC_READ,
FILE_SHARE_READ, FILE_SHARE_READ,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_BACKUP_SEMANTICS,
NULL); nullptr);
if (hPath != INVALID_HANDLE_VALUE) { if (hPath != INVALID_HANDLE_VALUE) {
DWORD len = GetFinalPathNameByHandleW(hPath, exePathW, MAX_PATH, FILE_NAME_NORMALIZED); DWORD len = GetFinalPathNameByHandleW(hPath, exePathW, MAX_PATH, FILE_NAME_NORMALIZED);
if (len > 0 && len < MAX_PATH) { if (len > 0 && len < MAX_PATH) {
@@ -44,8 +44,8 @@ static void getExePath(FFPlatform* platform) {
} }
static void getHomeDir(FFPlatform* platform) { static void getHomeDir(FFPlatform* platform) {
PWSTR pPath = NULL; PWSTR pPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pPath))) { if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, nullptr, &pPath))) {
ffStrbufSetWS(&platform->homeDir, pPath); ffStrbufSetWS(&platform->homeDir, pPath);
ffStrbufReplaceAllC(&platform->homeDir, '\\', '/'); ffStrbufReplaceAllC(&platform->homeDir, '\\', '/');
ffStrbufEnsureEndsWithC(&platform->homeDir, '/'); ffStrbufEnsureEndsWithC(&platform->homeDir, '/');
@@ -58,8 +58,8 @@ static void getHomeDir(FFPlatform* platform) {
} }
static void getCacheDir(FFPlatform* platform) { static void getCacheDir(FFPlatform* platform) {
PWSTR pPath = NULL; PWSTR pPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &pPath))) { if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, nullptr, &pPath))) {
ffStrbufSetWS(&platform->cacheDir, pPath); ffStrbufSetWS(&platform->cacheDir, pPath);
ffStrbufReplaceAllC(&platform->cacheDir, '\\', '/'); ffStrbufReplaceAllC(&platform->cacheDir, '\\', '/');
ffStrbufEnsureEndsWithC(&platform->cacheDir, '/'); ffStrbufEnsureEndsWithC(&platform->cacheDir, '/');
@@ -71,8 +71,8 @@ static void getCacheDir(FFPlatform* platform) {
} }
static void platformPathAddKnownFolder(FFlist* dirs, REFKNOWNFOLDERID folderId) { static void platformPathAddKnownFolder(FFlist* dirs, REFKNOWNFOLDERID folderId) {
PWSTR pPath = NULL; PWSTR pPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, NULL, &pPath))) { if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, nullptr, &pPath))) {
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateWS(pPath); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateWS(pPath);
CoTaskMemFree(pPath); CoTaskMemFree(pPath);
ffStrbufReplaceAllC(&buffer, '\\', '/'); ffStrbufReplaceAllC(&buffer, '\\', '/');
@@ -107,7 +107,7 @@ static void getConfigDirs(FFPlatform* platform) {
if (getenv("MSYSTEM")) { if (getenv("MSYSTEM")) {
// We are in MSYS2 / Git Bash // We are in MSYS2 / Git Bash
platformPathAddEnvSuffix(&platform->configDirs, "HOME", ".config/"); platformPathAddEnvSuffix(&platform->configDirs, "HOME", ".config/");
platformPathAddEnvSuffix(&platform->configDirs, "HOME", NULL); platformPathAddEnvSuffix(&platform->configDirs, "HOME", nullptr);
platformPathAddEnvSuffix(&platform->configDirs, "MINGW_PREFIX", "etc"); platformPathAddEnvSuffix(&platform->configDirs, "MINGW_PREFIX", "etc");
} }
@@ -122,7 +122,7 @@ static void getDataDirs(FFPlatform* platform) {
if (getenv("MSYSTEM") && getenv("HOME")) { if (getenv("MSYSTEM") && getenv("HOME")) {
// We are in MSYS2 / Git Bash // We are in MSYS2 / Git Bash
platformPathAddEnvSuffix(&platform->dataDirs, "HOME", ".local/share/"); platformPathAddEnvSuffix(&platform->dataDirs, "HOME", ".local/share/");
platformPathAddEnvSuffix(&platform->dataDirs, "HOME", NULL); platformPathAddEnvSuffix(&platform->dataDirs, "HOME", nullptr);
platformPathAddEnvSuffix(&platform->dataDirs, "MINGW_PREFIX", "share"); platformPathAddEnvSuffix(&platform->dataDirs, "MINGW_PREFIX", "share");
} }
ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/"); ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/");
@@ -142,8 +142,8 @@ static void getUserName(FFPlatform* platform) {
NTSYSAPI NTSTATUS NTAPI LsaGetUserName( NTSYSAPI NTSTATUS NTAPI LsaGetUserName(
_Outptr_ PLSA_UNICODE_STRING * UserName, _Outptr_ PLSA_UNICODE_STRING * UserName,
_Outptr_opt_ PLSA_UNICODE_STRING * DomainName); _Outptr_opt_ PLSA_UNICODE_STRING * DomainName);
PLSA_UNICODE_STRING userName = NULL; PLSA_UNICODE_STRING userName = nullptr;
if (NT_SUCCESS(LsaGetUserName(&userName, NULL))) { if (NT_SUCCESS(LsaGetUserName(&userName, nullptr))) {
ffStrbufSetNWS(&platform->userName, userName->Length / sizeof(wchar_t), userName->Buffer); ffStrbufSetNWS(&platform->userName, userName->Length / sizeof(wchar_t), userName->Buffer);
RtlFreeUnicodeString(userName); // Required. userName.Buffer is allocated separately RtlFreeUnicodeString(userName); // Required. userName.Buffer is allocated separately
LsaFreeMemory(userName); LsaFreeMemory(userName);
@@ -187,18 +187,18 @@ static const char* detectWine(void) {
const char* __cdecl wine_get_version(void); const char* __cdecl wine_get_version(void);
void* hntdll = ffLibraryGetModule(L"ntdll.dll"); void* hntdll = ffLibraryGetModule(L"ntdll.dll");
if (!hntdll) { if (!hntdll) {
return NULL; return nullptr;
} }
FF_LIBRARY_LOAD_SYMBOL_LAZY(hntdll, wine_get_version); FF_LIBRARY_LOAD_SYMBOL_LAZY(hntdll, wine_get_version);
if (!ffwine_get_version) { if (!ffwine_get_version) {
return NULL; return nullptr;
} }
return ffwine_get_version(); return ffwine_get_version();
} }
static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) { static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) {
FF_AUTO_CLOSE_FD HANDLE hKey = NULL; FF_AUTO_CLOSE_FD HANDLE hKey = nullptr;
if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, nullptr)) {
return; return;
} }
@@ -207,7 +207,7 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) {
FF_ARG(ubr, L"UBR"), FF_ARG(ubr, L"UBR"),
FF_ARG(info->version, L"BuildLabEx"), FF_ARG(info->version, L"BuildLabEx"),
}, },
NULL); nullptr);
PPEB_FULL peb = ffGetPeb(); PPEB_FULL peb = ffGetPeb();
@@ -228,7 +228,7 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) {
static void getSystemPageSize(FFPlatformSysinfo* info) { static void getSystemPageSize(FFPlatformSysinfo* info) {
SYSTEM_BASIC_INFORMATION sbi; SYSTEM_BASIC_INFORMATION sbi;
if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), NULL))) { if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), nullptr))) {
info->pageSize = sbi.PhysicalPageSize; info->pageSize = sbi.PhysicalPageSize;
} else { } else {
info->pageSize = 4096; info->pageSize = 4096;
+17 -17
View File
@@ -20,9 +20,9 @@ void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate) {
} }
void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) { void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
assert(format != NULL); assert(format != nullptr);
char* buffer = NULL; char* buffer = nullptr;
int len = vasprintf(&buffer, format, arguments); int len = vasprintf(&buffer, format, arguments);
assert(len >= 0); assert(len >= 0);
@@ -32,7 +32,7 @@ void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
// Takes ownership of `heapStr`. The caller must not free `heapStr` after calling this // Takes ownership of `heapStr`. The caller must not free `heapStr` after calling this
// function; the memory will be managed and freed via the associated FFstrbuf. // function; the memory will be managed and freed via the associated FFstrbuf.
void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr) { void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr) {
assert(heapStr != NULL); assert(heapStr != nullptr);
strbuf->length = length; strbuf->length = length;
size_t allocSize = ffMallocUsableSize(heapStr); size_t allocSize = ffMallocUsableSize(heapStr);
@@ -116,7 +116,7 @@ void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) {
} }
void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)) { void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)) {
if (value == NULL) { if (value == nullptr) {
return; return;
} }
@@ -134,7 +134,7 @@ void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transfo
} }
void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) { void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
assert(format != NULL); assert(format != nullptr);
va_list copy; va_list copy;
va_copy(copy, arguments); va_copy(copy, arguments);
@@ -155,12 +155,12 @@ void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
} }
const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until) { const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until) {
if (value == NULL) { if (value == nullptr) {
return NULL; return nullptr;
} }
const char* end = strchr(value, until); const char* end = strchr(value, until);
if (end == NULL) { if (end == nullptr) {
ffStrbufAppendS(strbuf, value); ffStrbufAppendS(strbuf, value);
} else { } else {
ffStrbufAppendNS(strbuf, (uint32_t) (end - value), value); ffStrbufAppendNS(strbuf, (uint32_t) (end - value), value);
@@ -169,7 +169,7 @@ const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char unti
} }
void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) { void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) {
assert(format != NULL); assert(format != nullptr);
va_list arguments; va_list arguments;
va_start(arguments, format); va_start(arguments, format);
@@ -186,7 +186,7 @@ void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) {
} }
void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) { void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) {
assert(format != NULL); assert(format != nullptr);
va_list arguments; va_list arguments;
va_start(arguments, format); va_start(arguments, format);
@@ -195,7 +195,7 @@ void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) {
} }
void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) { void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
if (value == NULL || length == 0) { if (value == nullptr || length == 0) {
return; return;
} }
@@ -213,14 +213,14 @@ void ffStrbufPrependC(FFstrbuf* strbuf, char c) {
} }
void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) { void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
assert(strbuf != NULL); assert(strbuf != nullptr);
if (length == 0) { if (length == 0) {
ffStrbufClear(strbuf); ffStrbufClear(strbuf);
return; return;
} }
assert(value != NULL); assert(value != nullptr);
if (strbuf->allocated <= length) { if (strbuf->allocated <= length) {
char* newBuf = malloc(sizeof(char) * (length + 1)); char* newBuf = malloc(sizeof(char) * (length + 1));
@@ -533,7 +533,7 @@ void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value) {
unsafe_yyjson_set_sint(&val, value); unsafe_yyjson_set_sint(&val, value);
char* end = yyjson_write_number(&val, start); char* end = yyjson_write_number(&val, start);
assert(end != NULL); assert(end != nullptr);
strbuf->length += (uint32_t) (end - start); strbuf->length += (uint32_t) (end - start);
} }
@@ -546,7 +546,7 @@ void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value) {
unsafe_yyjson_set_uint(&val, value); unsafe_yyjson_set_uint(&val, value);
char* end = yyjson_write_number(&val, start); char* end = yyjson_write_number(&val, start);
assert(end != NULL); assert(end != nullptr);
strbuf->length += (uint32_t) (end - start); strbuf->length += (uint32_t) (end - start);
} }
@@ -713,7 +713,7 @@ bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const
for (const char* p = comp; p < comp + compLength;) { for (const char* p = comp; p < comp + compLength;) {
const char* colon = memchr(p, separator, (size_t) (comp + compLength - p)); const char* colon = memchr(p, separator, (size_t) (comp + compLength - p));
if (colon == NULL) { if (colon == nullptr) {
uint32_t remainingLen = (uint32_t) (comp + compLength - p); uint32_t remainingLen = (uint32_t) (comp + compLength - p);
return strbuf->length == remainingLen && memcmp(strbuf->chars, p, remainingLen) == 0; return strbuf->length == remainingLen && memcmp(strbuf->chars, p, remainingLen) == 0;
} }
@@ -741,7 +741,7 @@ bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength
for (const char* p = comp; p < comp + compLength;) { for (const char* p = comp; p < comp + compLength;) {
const char* colon = memchr(p, separator, (size_t) (comp + compLength - p)); const char* colon = memchr(p, separator, (size_t) (comp + compLength - p));
if (colon == NULL) { if (colon == nullptr) {
uint32_t remainingLen = (uint32_t) (comp + compLength - p); uint32_t remainingLen = (uint32_t) (comp + compLength - p);
return strbuf->length == remainingLen && strncasecmp(strbuf->chars, p, remainingLen) == 0; return strbuf->length == remainingLen && strncasecmp(strbuf->chars, p, remainingLen) == 0;
} }
+10 -10
View File
@@ -20,7 +20,7 @@ typedef struct {
static inline void wrapMunmap(FFMemoryMapping* mapping) { static inline void wrapMunmap(FFMemoryMapping* mapping) {
assert(mapping); assert(mapping);
if (mapping->data == NULL || mapping->data == MAP_FAILED) { if (mapping->data == nullptr || mapping->data == MAP_FAILED) {
return; return;
} }
munmap((void*) mapping->data, mapping->length); munmap((void*) mapping->data, mapping->length);
@@ -31,12 +31,12 @@ static inline void wrapMunmap(FFMemoryMapping* mapping) {
*/ */
static inline const void* readData(const FFMemoryMapping* mapping, size_t size, off_t offset) { static inline const void* readData(const FFMemoryMapping* mapping, size_t size, off_t offset) {
if (offset < 0) { if (offset < 0) {
return NULL; return nullptr;
} }
size_t start = (size_t) offset; size_t start = (size_t) offset;
if (start > mapping->length || size > mapping->length - start) { if (start > mapping->length || size > mapping->length - start) {
return NULL; return nullptr;
} }
return mapping->data + start; return mapping->data + start;
@@ -99,7 +99,7 @@ static bool handleMachSection(const FFMemoryMapping* mapping, const char* name,
* @param userdata User data for the callback * @param userdata User data for the callback
* @param minLength Minimum string length to extract * @param minLength Minimum string length to extract
* *
* @return NULL on success, error message on failure * @return nullptr on success, error message on failure
*/ */
static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, bool is_64, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, bool is_64, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) {
uint32_t ncmds; uint32_t ncmds;
@@ -124,7 +124,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset,
} }
off_t commandOffset = loadCommandsOffset; off_t commandOffset = loadCommandsOffset;
const struct load_command* cmd = NULL; const struct load_command* cmd = nullptr;
for (uint32_t i = 0U; i < ncmds; i++, commandOffset += cmd->cmdsize) { for (uint32_t i = 0U; i < ncmds; i++, commandOffset += cmd->cmdsize) {
cmd = readData(mapping, sizeof(*cmd), commandOffset); cmd = readData(mapping, sizeof(*cmd), commandOffset);
if (!cmd) { if (!cmd) {
@@ -153,7 +153,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset,
} }
if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) { if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) {
return NULL; return nullptr;
} }
} }
} else if (cmd->cmd == LC_SEGMENT) { } else if (cmd->cmd == LC_SEGMENT) {
@@ -174,13 +174,13 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset,
} }
if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) { if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) {
return NULL; return nullptr;
} }
} }
} }
} }
return NULL; return nullptr;
} }
/** /**
@@ -195,7 +195,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset,
* @param userdata User data for the callback * @param userdata User data for the callback
* @param minLength Minimum string length to extract * @param minLength Minimum string length to extract
* *
* @return NULL on success, error message on failure * @return nullptr on success, error message on failure
*/ */
static const char* dumpFatHeader(const FFMemoryMapping* mapping, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { static const char* dumpFatHeader(const FFMemoryMapping* mapping, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) {
const struct fat_header* headerRaw = readData(mapping, sizeof(struct fat_header), 0); const struct fat_header* headerRaw = readData(mapping, sizeof(struct fat_header), 0);
@@ -274,7 +274,7 @@ const char* ffBinaryExtractStrings(const char* machoFile, bool (*cb)(const char*
} }
FF_A_CLEANUP(wrapMunmap) FFMemoryMapping mapping = { FF_A_CLEANUP(wrapMunmap) FFMemoryMapping mapping = {
.data = mmap(NULL, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0), .data = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0),
.length = (size_t) st.st_size, .length = (size_t) st.st_size,
}; };
if (mapping.data == MAP_FAILED) { if (mapping.data == MAP_FAILED) {
+13 -13
View File
@@ -56,10 +56,10 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_strptr) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_strptr)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_end) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_end)
libelf = NULL; libelf = nullptr;
} }
if (elfData.ffelf_end == NULL) { if (elfData.ffelf_end == nullptr) {
return "load libelf failed"; return "load libelf failed";
} }
@@ -69,8 +69,8 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s
return "open() failed"; return "open() failed";
} }
Elf* elf = elfData.ffelf_begin(fd, ELF_C_READ, NULL); Elf* elf = elfData.ffelf_begin(fd, ELF_C_READ, nullptr);
if (elf == NULL) { if (elf == nullptr) {
return "elf_begin() failed"; return "elf_begin() failed";
} }
@@ -82,27 +82,27 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s
} }
// Iterate through all sections, looking for .rodata which contains string literals // Iterate through all sections, looking for .rodata which contains string literals
Elf_Scn* scn = NULL; Elf_Scn* scn = nullptr;
while ((scn = elfData.ffelf_nextscn(elf, scn)) != NULL) { while ((scn = elfData.ffelf_nextscn(elf, scn)) != nullptr) {
// Try 64-bit section header first, then 32-bit if that fails // Try 64-bit section header first, then 32-bit if that fails
Elf64_Shdr* shdr64 = elfData.ffelf64_getshdr(scn); Elf64_Shdr* shdr64 = elfData.ffelf64_getshdr(scn);
Elf32_Shdr* shdr32 = NULL; Elf32_Shdr* shdr32 = nullptr;
if (shdr64 == NULL) { if (shdr64 == nullptr) {
shdr32 = elfData.ffelf32_getshdr(scn); shdr32 = elfData.ffelf32_getshdr(scn);
if (shdr32 == NULL) { if (shdr32 == nullptr) {
continue; continue;
} }
} }
// Get the section name and check if it's .rodata // Get the section name and check if it's .rodata
const char* name = elfData.ffelf_strptr(elf, shstrndx, shdr64 ? shdr64->sh_name : shdr32->sh_name); const char* name = elfData.ffelf_strptr(elf, shstrndx, shdr64 ? shdr64->sh_name : shdr32->sh_name);
if (name == NULL || !ffStrEquals(name, ".rodata")) { if (name == nullptr || !ffStrEquals(name, ".rodata")) {
continue; continue;
} }
// Get the section data // Get the section data
Elf_Data* data = elfData.ffelf_getdata(scn, NULL); Elf_Data* data = elfData.ffelf_getdata(scn, nullptr);
if (data == NULL) { if (data == nullptr) {
continue; continue;
} }
@@ -131,7 +131,7 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s
} }
elfData.ffelf_end(elf); elfData.ffelf_end(elf);
return NULL; return nullptr;
} }
#else #else
+6 -6
View File
@@ -15,19 +15,19 @@
* Each string found is passed to the callback function for processing. * Each string found is passed to the callback function for processing.
*/ */
const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) {
FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (hFile == INVALID_HANDLE_VALUE) { if (hFile == INVALID_HANDLE_VALUE) {
return "CreateFileA() failed"; return "CreateFileA() failed";
} }
FF_AUTO_CLOSE_FD HANDLE hSection = NULL; FF_AUTO_CLOSE_FD HANDLE hSection = nullptr;
if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, NULL, NULL, PAGE_READONLY, SEC_COMMIT, hFile))) { if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, nullptr, nullptr, PAGE_READONLY, SEC_COMMIT, hFile))) {
return "NtCreateSection() failed"; return "NtCreateSection() failed";
} }
PVOID base = NULL; PVOID base = nullptr;
SIZE_T viewSize = 0; SIZE_T viewSize = 0;
if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_READONLY))) { if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, nullptr, &viewSize, ViewUnmap, 0, PAGE_READONLY))) {
return "NtMapViewOfSection() failed"; return "NtMapViewOfSection() failed";
} }
@@ -67,5 +67,5 @@ const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* st
} }
NtUnmapViewOfSection(NtCurrentProcess(), base); NtUnmapViewOfSection(NtCurrentProcess(), base);
return NULL; return nullptr;
} }
+7 -7
View File
@@ -15,12 +15,12 @@ bool ffParseModuleOptions(const char* key, const char* value) {
return false; return false;
} }
if (value && !*value) { if (value && !*value) {
value = NULL; value = nullptr;
} }
for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(key[2]) - 'A']; *modules; ++modules) { for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(key[2]) - 'A']; *modules; ++modules) {
FFModuleBaseInfo* baseInfo = *modules; FFModuleBaseInfo* baseInfo = *modules;
const char* subKey = ffOptionTestPrefix(key, baseInfo->name); const char* subKey = ffOptionTestPrefix(key, baseInfo->name);
if (subKey != NULL) { if (subKey != nullptr) {
if (subKey[0] == '\0' || subKey[0] == '-') // Key is exactly the module name or has a leading '-' if (subKey[0] == '\0' || subKey[0] == '-') // Key is exactly the module name or has a leading '-'
{ {
fprintf(stderr, "Error: unknown module key %s\n", key); fprintf(stderr, "Error: unknown module key %s\n", key);
@@ -64,7 +64,7 @@ bool ffParseModuleOptions(const char* key, const char* value) {
} }
void ffPrepareCommandOption(FFdata* data) { void ffPrepareCommandOption(FFdata* data) {
char* moduleType = NULL; char* moduleType = nullptr;
size_t moduleLen = 0; size_t moduleLen = 0;
while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) {
#define FF_IF_MODULE_MATCH(moduleNameConstant) if (moduleLen == strlen(moduleNameConstant) && ffStrEqualsIgnCase(moduleType, moduleNameConstant) && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':')) #define FF_IF_MODULE_MATCH(moduleNameConstant) if (moduleLen == strlen(moduleNameConstant) && ffStrEqualsIgnCase(moduleType, moduleNameConstant) && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':'))
@@ -177,7 +177,7 @@ static bool parseStructureCommand(
if (ffStrEqualsIgnCase(line, baseInfo->name)) { if (ffStrEqualsIgnCase(line, baseInfo->name)) {
uint8_t optionBuf[FF_OPTION_MAX_SIZE]; uint8_t optionBuf[FF_OPTION_MAX_SIZE];
baseInfo->initOptions(optionBuf); baseInfo->initOptions(optionBuf);
if (data->resultDoc != NULL) { if (data->resultDoc != nullptr) {
fn(data, baseInfo, optionBuf); fn(data, baseInfo, optionBuf);
} else { } else {
baseInfo->printModule(optionBuf); baseInfo->printModule(optionBuf);
@@ -194,7 +194,7 @@ static bool parseStructureCommand(
yyjson_mut_obj_add_str(doc, module, "type", line); yyjson_mut_obj_add_str(doc, module, "type", line);
yyjson_mut_obj_add_str(doc, module, "error", "Unknown module type"); yyjson_mut_obj_add_str(doc, module, "error", "Unknown module type");
} else { } else {
ffPrintError(line, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "<no implementation provided>"); ffPrintError(line, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "<no implementation provided>");
} }
return false; return false;
} }
@@ -203,7 +203,7 @@ void ffPrintCommandOption(FFdata* data) {
// Parse the structure and call the modules // Parse the structure and call the modules
int32_t thres = instance.config.display.stat; int32_t thres = instance.config.display.stat;
char* moduleType = NULL; char* moduleType = nullptr;
size_t moduleLen = 0; size_t moduleLen = 0;
while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) {
if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) {
@@ -249,7 +249,7 @@ void ffMigrateCommandOptionToJsonc(FFdata* data) {
ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string
} }
char* moduleType = NULL; char* moduleType = nullptr;
size_t moduleLen = 0; size_t moduleLen = 0;
while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) {
if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) {
+17 -17
View File
@@ -19,7 +19,7 @@ static bool loadLibSymbols(FFDBusLibrary* lib) {
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_unref, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_unref, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_send_with_reply_and_block, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_send_with_reply_and_block, false)
FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_unref, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_unref, false)
dbus = NULL; // don't auto dlclose dbus = nullptr; // don't auto dlclose
return true; return true;
} }
@@ -33,27 +33,27 @@ static const FFDBusLibrary* loadLib(void) {
loadSuccess = loadLibSymbols(&lib); loadSuccess = loadLibSymbols(&lib);
} }
return loadSuccess ? &lib : NULL; return loadSuccess ? &lib : nullptr;
} }
const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data) { const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data) {
data->lib = loadLib(); data->lib = loadLib();
if (data->lib == NULL) { if (data->lib == nullptr) {
return "Failed to load DBus library"; return "Failed to load DBus library";
} }
data->connection = data->lib->ffdbus_bus_get(busType, NULL); data->connection = data->lib->ffdbus_bus_get(busType, nullptr);
if (data->connection == NULL) { if (data->connection == nullptr) {
return "Failed to connect to DBus"; return "Failed to connect to DBus";
} }
return NULL; return nullptr;
} }
void ffDBusDestroyData(FFDBusData* data) { void ffDBusDestroyData(FFDBusData* data) {
if (data->connection != NULL) { if (data->connection != nullptr) {
data->lib->ffdbus_connection_unref(data->connection); data->lib->ffdbus_connection_unref(data->connection);
data->connection = NULL; data->connection = nullptr;
} }
} }
@@ -61,7 +61,7 @@ bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result)
int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter); int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter);
if (argType == DBUS_TYPE_STRING || argType == DBUS_TYPE_OBJECT_PATH) { if (argType == DBUS_TYPE_STRING || argType == DBUS_TYPE_OBJECT_PATH) {
const char* value = NULL; const char* value = nullptr;
dbus->lib->ffdbus_message_iter_get_basic(iter, &value); dbus->lib->ffdbus_message_iter_get_basic(iter, &value);
if (!ffStrSet(value)) { if (!ffStrSet(value)) {
@@ -254,8 +254,8 @@ bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int64_t* result) {
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2) { DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2) {
DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, interface, method); DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, interface, method);
if (message == NULL) { if (message == nullptr) {
return NULL; return nullptr;
} }
if (arg1) { if (arg1) {
@@ -266,7 +266,7 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c
} }
} }
DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL); DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, nullptr);
dbus->lib->ffdbus_message_unref(message); dbus->lib->ffdbus_message_unref(message);
@@ -275,8 +275,8 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c
DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) { DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) {
DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, "org.freedesktop.DBus.Properties", "Get"); DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, "org.freedesktop.DBus.Properties", "Get");
if (message == NULL) { if (message == nullptr) {
return NULL; return nullptr;
} }
dbus->lib->ffdbus_message_append_args(message, dbus->lib->ffdbus_message_append_args(message,
@@ -286,7 +286,7 @@ DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char
&property, &property,
DBUS_TYPE_INVALID); DBUS_TYPE_INVALID);
DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL); DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, nullptr);
dbus->lib->ffdbus_message_unref(message); dbus->lib->ffdbus_message_unref(message);
@@ -295,7 +295,7 @@ DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char
bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result) { bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result) {
DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property);
if (reply == NULL) { if (reply == nullptr) {
return false; return false;
} }
@@ -314,7 +314,7 @@ bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char*
bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint64_t* result) { bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint64_t* result) {
DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property);
if (reply == NULL) { if (reply == nullptr) {
return false; return false;
} }
+2 -2
View File
@@ -10,12 +10,12 @@ const char* ffDebugWin32Error(DWORD errorCode) {
wchar_t bufferW[256]; wchar_t bufferW[256];
ULONG len = FormatMessageW( ULONG len = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, nullptr,
(DWORD) errorCode, (DWORD) errorCode,
0, 0,
bufferW, bufferW,
ARRAY_SIZE(bufferW), ARRAY_SIZE(bufferW),
NULL); nullptr);
if (len == 0) { if (len == 0) {
snprintf(buffer, sizeof(buffer), "Unknown error code (%lu)", errorCode); snprintf(buffer, sizeof(buffer), "Unknown error code (%lu)", errorCode);
+7 -7
View File
@@ -16,7 +16,7 @@ void ffFontInit(FFfont* font) {
} }
static void strbufAppendNSExcludingC(FFstrbuf* strbuf, uint32_t length, const char* value, char exclude) { static void strbufAppendNSExcludingC(FFstrbuf* strbuf, uint32_t length, const char* value, char exclude) {
if (value == NULL || length == 0) { if (value == nullptr || length == 0) {
return; return;
} }
@@ -151,7 +151,7 @@ static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* altern
ffStrStartsWithIgnCase(wordStart, "Black") || ffStrStartsWithIgnCase(wordStart, "Black") ||
ffStrStartsWithIgnCase(wordStart, "Condensed") || ffStrStartsWithIgnCase(wordStart, "Condensed") ||
ffStrStartsWithIgnCase(wordStart, "Expanded")) { ffStrStartsWithIgnCase(wordStart, "Expanded")) {
if (alternativeBuffer == NULL) { if (alternativeBuffer == nullptr) {
alternativeBuffer = FF_LIST_ADD(FFstrbuf, font->styles); alternativeBuffer = FF_LIST_ADD(FFstrbuf, font->styles);
ffStrbufInit(alternativeBuffer); ffStrbufInit(alternativeBuffer);
} }
@@ -169,7 +169,7 @@ static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* altern
return; return;
} }
if (alternativeBuffer != NULL) { if (alternativeBuffer != nullptr) {
strbufAppendNSExcludingC(alternativeBuffer, wordLength, wordStart, '-'); strbufAppendNSExcludingC(alternativeBuffer, wordLength, wordStart, '-');
return; return;
} }
@@ -184,7 +184,7 @@ void ffFontInitPango(FFfont* font, const char* data) {
ffFontInit(font); ffFontInit(font);
while (*data != '\0' && *data != '`' && *data != '\\') { while (*data != '\0' && *data != '`' && *data != '\\') {
fontPangoParseWord(&data, font, NULL); fontPangoParseWord(&data, font, nullptr);
} }
fontInitPretty(font); fontInitPretty(font);
@@ -329,8 +329,8 @@ void ffFontInitXft(FFfont* font, const char* xft) {
} }
// Try parse trailing "-<number>" as size, otherwise entire head is name // Try parse trailing "-<number>" as size, otherwise entire head is name
const char* dashPos = NULL; const char* dashPos = nullptr;
const char* sizeStart = NULL; const char* sizeStart = nullptr;
for (const char* q = headEnd; q > headStart;) { for (const char* q = headEnd; q > headStart;) {
--q; --q;
@@ -488,7 +488,7 @@ void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf
void ffFontInitWithSpace(FFfont* font, const char* rawName) { void ffFontInitWithSpace(FFfont* font, const char* rawName) {
const char* pspace = strrchr(rawName, ' '); const char* pspace = strrchr(rawName, ' ');
if (pspace == NULL) { if (pspace == nullptr) {
ffFontInitCopy(font, rawName); ffFontInitCopy(font, rawName);
return; return;
} }
+18 -18
View File
@@ -78,7 +78,7 @@ static uint32_t getArgumentIndex(const char* placeholderValue, uint32_t numArgs,
} }
if (firstChar >= '0' && firstChar <= '9') { if (firstChar >= '0' && firstChar <= '9') {
char* pEnd = NULL; char* pEnd = nullptr;
uint32_t result = (uint32_t) strtoul(placeholderValue, &pEnd, 10); uint32_t result = (uint32_t) strtoul(placeholderValue, &pEnd, 10);
if (result > numArgs) { if (result > numArgs) {
return UINT32_MAX; return UINT32_MAX;
@@ -109,7 +109,7 @@ static inline void appendInvalidPlaceholder(FFstrbuf* buffer, const char* start,
} }
static inline bool formatArgSet(const FFformatarg* arg) { static inline bool formatArgSet(const FFformatarg* arg) {
return arg->value != NULL && ((arg->type == FF_ARG_TYPE_DOUBLE && *(double*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_FLOAT && *(float*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_INT && *(int32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*) arg->value)->length > 0) || (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*) arg->value)) || (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT64 && *(uint64_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_BOOL && *(bool*) arg->value) || (arg->type == FF_ARG_TYPE_LIST && ((FFlist*) arg->value)->length > 0)); return arg->value != nullptr && ((arg->type == FF_ARG_TYPE_DOUBLE && *(double*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_FLOAT && *(float*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_INT && *(int32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*) arg->value)->length > 0) || (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*) arg->value)) || (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT64 && *(uint64_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_BOOL && *(bool*) arg->value) || (arg->type == FF_ARG_TYPE_LIST && ((FFlist*) arg->value)->length > 0));
} }
FF_A_UNUSED static inline void normalizeArgName(FFstrbuf* dst, const char* src) { FF_A_UNUSED static inline void normalizeArgName(FFstrbuf* dst, const char* src) {
@@ -131,7 +131,7 @@ FF_A_UNUSED static inline void normalizeArgName(FFstrbuf* dst, const char* src)
#include "common/lua.h" #include "common/lua.h"
static void appendLuaError(FFstrbuf* buffer, const char* prefix, lua_State* L) { static void appendLuaError(FFstrbuf* buffer, const char* prefix, lua_State* L) {
const char* err = lua_tolstring(L, -1, NULL); const char* err = lua_tolstring(L, -1, nullptr);
if (err) { if (err) {
const char* tmp = strchr(err, ':'); const char* tmp = strchr(err, ':');
if (tmp) { if (tmp) {
@@ -228,12 +228,12 @@ static bool parseLuaString(FFstrbuf* buffer, const char* script, uint32_t script
ffStrbufAppendS(buffer, "Lua result error: no result"); ffStrbufAppendS(buffer, "Lua result error: no result");
} else { } else {
// Convert first result to string // Convert first result to string
const char* res = lua_tolstring(L, 1, NULL); const char* res = lua_tolstring(L, 1, nullptr);
if (res) { if (res) {
ffStrbufAppendS(buffer, res); ffStrbufAppendS(buffer, res);
} else { } else {
luaL_tolstring(L, 1, NULL); luaL_tolstring(L, 1, nullptr);
const char* sval = lua_tolstring(L, -1, NULL); const char* sval = lua_tolstring(L, -1, nullptr);
if (sval) { if (sval) {
ffStrbufAppendS(buffer, sval); ffStrbufAppendS(buffer, sval);
} }
@@ -273,10 +273,10 @@ struct FFQuickJSData {
static const char* loadQuickJSState(void) { static const char* loadQuickJSState(void) {
if (qjsData.inited) { if (qjsData.inited) {
if (qjsData.ctx == NULL) { if (qjsData.ctx == nullptr) {
return "QuickJS is not available"; return "QuickJS is not available";
} }
return NULL; return nullptr;
} }
qjsData.inited = true; qjsData.inited = true;
@@ -301,20 +301,20 @@ static const char* loadQuickJSState(void) {
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libqjs, qjsData, JS_FreeValue) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libqjs, qjsData, JS_FreeValue)
qjsData.rt = qjsData.ffJS_NewRuntime(); qjsData.rt = qjsData.ffJS_NewRuntime();
if (qjsData.rt == NULL) { if (qjsData.rt == nullptr) {
return "JS_NewRuntime() failed"; return "JS_NewRuntime() failed";
} }
qjsData.ctx = qjsData.ffJS_NewContext(qjsData.rt); qjsData.ctx = qjsData.ffJS_NewContext(qjsData.rt);
if (qjsData.ctx == NULL) { if (qjsData.ctx == nullptr) {
qjsData.ffJS_FreeRuntime(qjsData.rt); qjsData.ffJS_FreeRuntime(qjsData.rt);
qjsData.rt = NULL; qjsData.rt = nullptr;
return "JS_NewContext() failed"; return "JS_NewContext() failed";
} }
libqjs = NULL; // don't close quickjs libqjs = nullptr; // don't close quickjs
return NULL; return nullptr;
} }
static bool parseQuickJSString(FFstrbuf* buffer, const char* script, uint32_t scriptLen, uint32_t numArgs, const FFformatarg* arguments) { static bool parseQuickJSString(FFstrbuf* buffer, const char* script, uint32_t scriptLen, uint32_t numArgs, const FFformatarg* arguments) {
@@ -401,7 +401,7 @@ static bool parseQuickJSString(FFstrbuf* buffer, const char* script, uint32_t sc
bool ret = false; bool ret = false;
if (JS_IsException(result)) { if (JS_IsException(result)) {
JSValue exc = qjsData.ffJS_GetException(ctx); JSValue exc = qjsData.ffJS_GetException(ctx);
const char* message = qjsData.ffJS_ToCStringLen2(ctx, NULL, exc, false); const char* message = qjsData.ffJS_ToCStringLen2(ctx, nullptr, exc, false);
qjsData.ffJS_FreeValue(ctx, exc); qjsData.ffJS_FreeValue(ctx, exc);
ffStrbufAppendF(buffer, "Qjs runtime error: %s", message ?: "unknown"); ffStrbufAppendF(buffer, "Qjs runtime error: %s", message ?: "unknown");
if (message) { if (message) {
@@ -587,7 +587,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3
// test for constant or env var, if so evaluate it // test for constant or env var, if so evaluate it
if (firstChar == '$') { if (firstChar == '$') {
char* pend = NULL; char* pend = nullptr;
int32_t indexSigned = (int32_t) strtol(placeholderValue.chars + 1, &pend, 10); int32_t indexSigned = (int32_t) strtol(placeholderValue.chars + 1, &pend, 10);
if (pend == placeholderValue.chars + 1) { if (pend == placeholderValue.chars + 1) {
// treat placeholder as an environment variable // treat placeholder as an environment variable
@@ -620,7 +620,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3
cSep = *pSep; cSep = *pSep;
*pSep = '\0'; *pSep = '\0';
} else { } else {
pSep = NULL; pSep = nullptr;
} }
uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments); uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments);
@@ -646,7 +646,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3
FF_STRBUF_AUTO_DESTROY trailingEscape = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY trailingEscape = ffStrbufCreate();
skipAnsiEscape(&tempString, buffer, &trailingEscape); skipAnsiEscape(&tempString, buffer, &trailingEscape);
char* pEnd = NULL; char* pEnd = nullptr;
int32_t start = (int32_t) strtol(pSep + 1, &pEnd, 10); int32_t start = (int32_t) strtol(pSep + 1, &pEnd, 10);
if (start < 0) { if (start < 0) {
start = (int32_t) tempString.length + start; start = (int32_t) tempString.length + start;
@@ -680,7 +680,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3
continue; continue;
} }
} else { } else {
char* pEnd = NULL; char* pEnd = nullptr;
int32_t truncLength = (int32_t) strtol(pSep + 1, &pEnd, 10); int32_t truncLength = (int32_t) strtol(pSep + 1, &pEnd, 10);
if (*pEnd != '\0') { if (*pEnd != '\0') {
*pSep = cSep; *pSep = cSep;
+7 -7
View File
@@ -123,26 +123,26 @@ void ffStart(void) {
#ifdef _WIN32 #ifdef _WIN32
SetErrorMode(SEM_FAILCRITICALERRORS); SetErrorMode(SEM_FAILCRITICALERRORS);
if (instance.config.display.noBuffer) { if (instance.config.display.noBuffer) {
setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdout, nullptr, _IONBF, 0);
} else { } else {
setvbuf(stdout, NULL, _IOFBF, 4096); setvbuf(stdout, nullptr, _IOFBF, 4096);
} }
SetConsoleCtrlHandler(consoleHandler, TRUE); SetConsoleCtrlHandler(consoleHandler, TRUE);
#else #else
if (instance.config.display.noBuffer) { if (instance.config.display.noBuffer) {
setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdout, nullptr, _IONBF, 0);
} }
struct sigaction action; struct sigaction action;
sigemptyset(&action.sa_mask); sigemptyset(&action.sa_mask);
action.sa_flags = 0; action.sa_flags = 0;
action.sa_handler = exitSignalHandler; action.sa_handler = exitSignalHandler;
sigaction(SIGINT, &action, NULL); sigaction(SIGINT, &action, nullptr);
sigaction(SIGTERM, &action, NULL); sigaction(SIGTERM, &action, nullptr);
sigaction(SIGQUIT, &action, NULL); sigaction(SIGQUIT, &action, nullptr);
sigset_t newmask; sigset_t newmask;
sigemptyset(&newmask); sigemptyset(&newmask);
sigaddset(&newmask, SIGCHLD); sigaddset(&newmask, SIGCHLD);
sigprocmask(SIG_BLOCK, &newmask, NULL); sigprocmask(SIG_BLOCK, &newmask, nullptr);
#endif #endif
// reset everything to default before we start printing // reset everything to default before we start printing
+9 -9
View File
@@ -22,8 +22,8 @@
static void createSubfolders(const char* fileName) { static void createSubfolders(const char* fileName) {
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate();
const char* token = NULL; const char* token = nullptr;
while ((token = strchr(fileName, '/')) != NULL) { while ((token = strchr(fileName, '/')) != nullptr) {
ffStrbufAppendNS(&path, (uint32_t) (token - fileName + 1), fileName); ffStrbufAppendNS(&path, (uint32_t) (token - fileName + 1), fileName);
mkdir(path.chars, S_IRWXU | S_IRGRP | S_IROTH); mkdir(path.chars, S_IRWXU | S_IRGRP | S_IROTH);
fileName = token + 1; fileName = token + 1;
@@ -119,7 +119,7 @@ bool ffPathExpandEnv(const char* in, FFstrbuf* out) {
| GLOB_BRACE | GLOB_BRACE
#endif #endif
, ,
NULL, nullptr,
&gb) != 0) &gb) != 0)
return false; return false;
@@ -174,7 +174,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
fd_set rd; fd_set rd;
FD_ZERO(&rd); FD_ZERO(&rd);
FD_SET(ftty, &rd); FD_SET(ftty, &rd);
if (select(ftty + 1, &rd, NULL, NULL, &(struct timeval) { .tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000 }) <= 0) { if (select(ftty + 1, &rd, nullptr, nullptr, &(struct timeval) { .tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000 }) <= 0) {
return "select(/dev/tty) timeout or failed"; return "select(/dev/tty) timeout or failed";
} }
} }
@@ -213,7 +213,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
va_end(args); va_end(args);
return NULL; return nullptr;
} }
bool ffSuppressIO(bool suppress) { bool ffSuppressIO(bool suppress) {
@@ -258,14 +258,14 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta
} }
FF_AUTO_CLOSE_DIR DIR* dir = fdopendir(dfd); FF_AUTO_CLOSE_DIR DIR* dir = fdopendir(dfd);
if (dir == NULL) { if (dir == nullptr) {
close(dfd); close(dfd);
return; // Should not happen return; // Should not happen
} }
uint32_t folderLength = folder->length; uint32_t folderLength = folder->length;
if (pretty && folderName != NULL) { if (pretty && folderName != nullptr) {
for (uint8_t i = 0; i < indentation - 1; i++) { for (uint8_t i = 0; i < indentation - 1; i++) {
fputs(" | ", stdout); fputs(" | ", stdout);
} }
@@ -274,7 +274,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta
struct dirent* entry; struct dirent* entry;
while ((entry = readdir(dir)) != NULL) { while ((entry = readdir(dir)) != nullptr) {
if (entry->d_name[0] == '.') { // skip hidden files if (entry->d_name[0] == '.') { // skip hidden files
continue; continue;
} }
@@ -316,7 +316,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta
void ffListFilesRecursively(const char* path, bool pretty) { void ffListFilesRecursively(const char* path, bool pretty) {
FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path);
ffStrbufEnsureEndsWithC(&folder, '/'); ffStrbufEnsureEndsWithC(&folder, '/');
listFilesRecursively(folder.length, &folder, 0, NULL, pretty); listFilesRecursively(folder.length, &folder, 0, nullptr, pretty);
} }
FFNativeFD ffGetNullFD(void) { FFNativeFD ffGetNullFD(void) {
+25 -25
View File
@@ -20,10 +20,10 @@ static bool createSubfolders(wchar_t* fileName) {
fileName, fileName,
FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS,
NULL); nullptr);
ptr[3] = saved; ptr[3] = saved;
if (hRoot == INVALID_HANDLE_VALUE) { if (hRoot == INVALID_HANDLE_VALUE) {
@@ -36,12 +36,12 @@ static bool createSubfolders(wchar_t* fileName) {
// UNC path: \\server\share\... // UNC path: \\server\share\...
else if (ptr[0] == L'\\' && ptr[1] == L'\\') { else if (ptr[0] == L'\\' && ptr[1] == L'\\') {
wchar_t* serverEnd = wcschr(ptr + 2, L'\\'); wchar_t* serverEnd = wcschr(ptr + 2, L'\\');
if (serverEnd == NULL) { if (serverEnd == nullptr) {
return false; return false;
} }
wchar_t* shareEnd = wcschr(serverEnd + 1, L'\\'); wchar_t* shareEnd = wcschr(serverEnd + 1, L'\\');
if (shareEnd == NULL) { if (shareEnd == nullptr) {
return true; // no parent subfolder exists before file name return true; // no parent subfolder exists before file name
} }
@@ -52,10 +52,10 @@ static bool createSubfolders(wchar_t* fileName) {
fileName, fileName,
FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS,
NULL); nullptr);
*shareEnd = saved; *shareEnd = saved;
if (hRoot == INVALID_HANDLE_VALUE) { if (hRoot == INVALID_HANDLE_VALUE) {
@@ -73,10 +73,10 @@ static bool createSubfolders(wchar_t* fileName) {
driveRoot, driveRoot,
FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS,
NULL); nullptr);
if (hRoot == INVALID_HANDLE_VALUE) { if (hRoot == INVALID_HANDLE_VALUE) {
return false; return false;
} }
@@ -86,7 +86,7 @@ static bool createSubfolders(wchar_t* fileName) {
while (true) { while (true) {
wchar_t* token = wcschr(ptr, L'\\'); wchar_t* token = wcschr(ptr, L'\\');
if (token == NULL) { if (token == nullptr) {
break; break;
} }
@@ -113,12 +113,12 @@ static bool createSubfolders(wchar_t* fileName) {
.Attributes = OBJ_CASE_INSENSITIVE, .Attributes = OBJ_CASE_INSENSITIVE,
}, },
&iosb, &iosb,
NULL, nullptr,
FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN_IF, FILE_OPEN_IF,
FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT,
NULL, nullptr,
0); 0);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
@@ -157,13 +157,13 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) {
} }
} }
HANDLE FF_AUTO_CLOSE_FD handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE FF_AUTO_CLOSE_FD handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE) { if (handle == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_PATH_NOT_FOUND) { if (GetLastError() == ERROR_PATH_NOT_FOUND) {
if (!createSubfolders(fileNameW)) { if (!createSubfolders(fileNameW)) {
return false; return false;
} }
handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (handle == INVALID_HANDLE_VALUE) { if (handle == INVALID_HANDLE_VALUE) {
return false; return false;
} }
@@ -173,7 +173,7 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) {
} }
DWORD written; DWORD written;
return !!WriteFile(handle, data, (DWORD) dataSize, &written, NULL); return !!WriteFile(handle, data, (DWORD) dataSize, &written, nullptr);
} }
static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t length) { static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t length) {
@@ -181,7 +181,7 @@ static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t leng
DWORD bytesRead = 0; DWORD bytesRead = 0;
while ( while (
length > 0 && length > 0 &&
ReadFile(handle, buffer->chars + buffer->length, length, &bytesRead, NULL) != FALSE && ReadFile(handle, buffer->chars + buffer->length, length, &bytesRead, nullptr) != FALSE &&
bytesRead > 0) { bytesRead > 0) {
buffer->length += (uint32_t) bytesRead; buffer->length += (uint32_t) bytesRead;
length -= (uint32_t) bytesRead; length -= (uint32_t) bytesRead;
@@ -193,7 +193,7 @@ static inline void readUntilEOF(HANDLE handle, FFstrbuf* buffer) {
uint32_t available = ffStrbufGetFree(buffer); uint32_t available = ffStrbufGetFree(buffer);
DWORD bytesRead = 0; DWORD bytesRead = 0;
while ( while (
ReadFile(handle, buffer->chars + buffer->length, available, &bytesRead, NULL) != FALSE && ReadFile(handle, buffer->chars + buffer->length, available, &bytesRead, nullptr) != FALSE &&
bytesRead > 0) { bytesRead > 0) {
buffer->length += (uint32_t) bytesRead; buffer->length += (uint32_t) bytesRead;
if ((uint32_t) bytesRead == available) { if ((uint32_t) bytesRead == available) {
@@ -282,7 +282,7 @@ bool ffPathExpandEnv(const char* in, FFstrbuf* out) {
len /= sizeof(wchar_t); // convert from bytes to characters len /= sizeof(wchar_t); // convert from bytes to characters
SIZE_T outLen; // in characters, including null terminator SIZE_T outLen; // in characters, including null terminator
if (!NT_SUCCESS(RtlExpandEnvironmentStrings(NULL, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) { if (!NT_SUCCESS(RtlExpandEnvironmentStrings(nullptr, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) {
return false; return false;
} }
@@ -336,7 +336,7 @@ bool ffSuppressIO(bool suppress) {
void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) { void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) {
uint32_t folderLength = folder->length; uint32_t folderLength = folder->length;
if (pretty && folderName != NULL) { if (pretty && folderName != nullptr) {
for (uint8_t i = 0; i < indentation - 1; i++) { for (uint8_t i = 0; i < indentation - 1; i++) {
fputs(" | ", stdout); fputs(" | ", stdout);
} }
@@ -381,7 +381,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta
void ffListFilesRecursively(const char* path, bool pretty) { void ffListFilesRecursively(const char* path, bool pretty) {
FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path);
ffStrbufEnsureEndsWithC(&folder, '/'); ffStrbufEnsureEndsWithC(&folder, '/');
listFilesRecursively(folder.length, &folder, 0, NULL, pretty); listFilesRecursively(folder.length, &folder, 0, nullptr, pretty);
} }
const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) { const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) {
@@ -390,7 +390,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
DWORD inputMode = 0; DWORD inputMode = 0;
bool hasInputMode = !!GetConsoleMode(hInput, &inputMode); bool hasInputMode = !!GetConsoleMode(hInput, &inputMode);
if (!hasInputMode) { if (!hasInputMode) {
hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL); hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, nullptr);
hInput = hConin; hInput = hConin;
hasInputMode = !!GetConsoleMode(hInput, &inputMode); hasInputMode = !!GetConsoleMode(hInput, &inputMode);
} }
@@ -404,10 +404,10 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE; FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE;
DWORD outputMode; DWORD outputMode;
if (!GetConsoleMode(hOutput, &outputMode)) { if (!GetConsoleMode(hOutput, &outputMode)) {
hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, nullptr);
hOutput = hConout; hOutput = hConout;
} }
WriteFile(hOutput, request, (DWORD) strlen(request), &bytes, NULL); WriteFile(hOutput, request, (DWORD) strlen(request), &bytes, nullptr);
} }
while (true) { while (true) {
@@ -441,7 +441,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
while (true) { while (true) {
DWORD bytes = 0; DWORD bytes = 0;
if (!ReadFile(hInput, buffer + bytesRead, (DWORD) (sizeof(buffer) - 1 - bytesRead), &bytes, NULL) || bytes == 0) { if (!ReadFile(hInput, buffer + bytesRead, (DWORD) (sizeof(buffer) - 1 - bytesRead), &bytes, nullptr) || bytes == 0) {
va_end(args); va_end(args);
return "ReadFile() failed"; return "ReadFile() failed";
} }
@@ -473,7 +473,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char*
va_end(args); va_end(args);
return NULL; return nullptr;
} }
FFNativeFD ffGetNullFD(void) { FFNativeFD ffGetNullFD(void) {
@@ -490,7 +490,7 @@ FFNativeFD ffGetNullFD(void) {
0, 0,
&(SECURITY_ATTRIBUTES) { &(SECURITY_ATTRIBUTES) {
.nLength = sizeof(SECURITY_ATTRIBUTES), .nLength = sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = NULL, .lpSecurityDescriptor = nullptr,
.bInheritHandle = TRUE, .bInheritHandle = TRUE,
}); });
return hNullFile; return hNullFile;
+7 -7
View File
@@ -67,7 +67,7 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p
for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) {
if (intVal == pPair->value) { if (intVal == pPair->value) {
*result = pPair->value; *result = pPair->value;
return NULL; return nullptr;
} }
} }
@@ -77,7 +77,7 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p
for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) {
if (ffStrEqualsIgnCase(strVal, pPair->key)) { if (ffStrEqualsIgnCase(strVal, pPair->key)) {
*result = pPair->value; *result = pPair->value;
return NULL; return nullptr;
} }
} }
@@ -244,7 +244,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) {
yyjson_val* modules = yyjson_obj_get(root, "modules"); yyjson_val* modules = yyjson_obj_get(root, "modules");
if (!modules) { if (!modules) {
return NULL; return nullptr;
} }
if (!yyjson_is_arr(modules)) { if (!yyjson_is_arr(modules)) {
return "Property 'modules' must be an array of strings or objects"; return "Property 'modules' must be an array of strings or objects";
@@ -263,7 +263,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) {
yyjson_val* module = item; yyjson_val* module = item;
const char* type = yyjson_get_str(module); const char* type = yyjson_get_str(module);
if (type) { if (type) {
module = NULL; module = nullptr;
} else if (yyjson_is_obj(module)) { } else if (yyjson_is_obj(module)) {
yyjson_val* conditions = yyjson_obj_get(module, "condition"); yyjson_val* conditions = yyjson_obj_get(module, "condition");
if (conditions) { if (conditions) {
@@ -307,7 +307,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) {
return "module object must contain a \"type\" key ( case sensitive )"; return "module object must contain a \"type\" key ( case sensitive )";
} }
if (yyjson_obj_size(module) == 1) { // contains only Property type if (yyjson_obj_size(module) == 1) { // contains only Property type
module = NULL; module = nullptr;
} }
} else { } else {
return "modules must be an array of strings or objects"; return "modules must be an array of strings or objects";
@@ -347,7 +347,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) {
#endif #endif
} }
return NULL; return nullptr;
} }
void ffPrintJsonConfig(FFdata* data, bool prepare) { void ffPrintJsonConfig(FFdata* data, bool prepare) {
@@ -359,7 +359,7 @@ void ffPrintJsonConfig(FFdata* data, bool prepare) {
yyjson_mut_obj_add_str(jsonDoc, obj, "error", error); yyjson_mut_obj_add_str(jsonDoc, obj, "error", error);
yyjson_mut_doc_set_root(jsonDoc, obj); yyjson_mut_doc_set_root(jsonDoc, obj);
} else { } else {
ffPrintError("JsonConfig", 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error); ffPrintError("JsonConfig", 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error);
} }
} }
} }
+1 -1
View File
@@ -6,7 +6,7 @@
bool ffKmodLoaded(const char* modName) { bool ffKmodLoaded(const char* modName) {
FF_CFTYPE_AUTO_RELEASE CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, modName, kCFStringEncodingUTF8); FF_CFTYPE_AUTO_RELEASE CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, modName, kCFStringEncodingUTF8);
FF_CFTYPE_AUTO_RELEASE CFArrayRef identifiers = CFArrayCreate(kCFAllocatorDefault, (const void**) &name, 1, &kCFTypeArrayCallBacks); FF_CFTYPE_AUTO_RELEASE CFArrayRef identifiers = CFArrayCreate(kCFAllocatorDefault, (const void**) &name, 1, &kCFTypeArrayCallBacks);
FF_CFTYPE_AUTO_RELEASE CFArrayRef keys = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL); FF_CFTYPE_AUTO_RELEASE CFArrayRef keys = CFArrayCreate(kCFAllocatorDefault, nullptr, 0, nullptr);
FF_CFTYPE_AUTO_RELEASE CFDictionaryRef kextInfo = KextManagerCopyLoadedKextInfo(identifiers, keys); FF_CFTYPE_AUTO_RELEASE CFDictionaryRef kextInfo = KextManagerCopyLoadedKextInfo(identifiers, keys);
return CFDictionaryContainsKey(kextInfo, name); return CFDictionaryContainsKey(kextInfo, name);
} }
+2 -2
View File
@@ -3,7 +3,7 @@
bool ffKmodLoaded(const char* modName) { bool ffKmodLoaded(const char* modName) {
static FFstrbuf modules; static FFstrbuf modules;
if (modules.chars == NULL) { if (modules.chars == nullptr) {
ffStrbufInitS(&modules, "\n"); ffStrbufInitS(&modules, "\n");
ffAppendFileBuffer("/proc/modules", &modules); ffAppendFileBuffer("/proc/modules", &modules);
} }
@@ -21,5 +21,5 @@ bool ffKmodLoaded(const char* modName) {
temp[0] = '\n'; temp[0] = '\n';
memcpy(temp + 1, modName, len); memcpy(temp + 1, modName, len);
temp[1 + len] = ' '; temp[1 + len] = ' ';
return memmem(modules.chars, modules.length, temp, len + 2) != NULL; return memmem(modules.chars, modules.length, temp, len + 2) != nullptr;
} }
+2 -2
View File
@@ -10,9 +10,9 @@ typedef struct FF_A_PACKED FFNbsdModList {
} FFNbsdModList; } FFNbsdModList;
bool ffKmodLoaded(const char* modName) { bool ffKmodLoaded(const char* modName) {
static FFNbsdModList* list = NULL; static FFNbsdModList* list = nullptr;
if (list == NULL) { if (list == nullptr) {
struct iovec iov = {}; struct iovec iov = {};
for (size_t len = 8192;; len = iov.iov_len) { for (size_t len = 8192;; len = iov.iov_len) {
+1 -1
View File
@@ -5,7 +5,7 @@
bool ffKmodLoaded(const char* modName) { bool ffKmodLoaded(const char* modName) {
ULONG bufferSize = 0; ULONG bufferSize = 0;
NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &bufferSize); NtQuerySystemInformation(SystemModuleInformation, nullptr, 0, &bufferSize);
if (bufferSize == 0) { if (bufferSize == 0) {
return true; // ignore errors return true; // ignore errors
} }
+14 -14
View File
@@ -35,7 +35,7 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) {
// libX.dll.1 never exists on Windows, while libX-1.dll may exist // libX.dll.1 never exists on Windows, while libX-1.dll may exist
FF_UNUSED(maxVersion) FF_UNUSED(maxVersion)
if (result != NULL) { if (result != nullptr) {
return result; return result;
} }
@@ -50,11 +50,11 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) {
#else #else
if (result == NULL) { if (result == nullptr) {
FF_DEBUG("dlopen(\"%s\"): %s", path, dlerror()); FF_DEBUG("dlopen(\"%s\"): %s", path, dlerror());
} }
if (result != NULL || maxVersion < 0) { if (result != nullptr || maxVersion < 0) {
return result; return result;
} }
@@ -67,7 +67,7 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) {
ffStrbufAppendSInt(&pathbuf, i); ffStrbufAppendSInt(&pathbuf, i);
result = dlopen(pathbuf.chars, FF_DLOPEN_FLAGS); result = dlopen(pathbuf.chars, FF_DLOPEN_FLAGS);
if (result != NULL) { if (result != nullptr) {
break; break;
} else { } else {
FF_DEBUG("dlopen(\"%s\"): %s", pathbuf.chars, dlerror()); FF_DEBUG("dlopen(\"%s\"): %s", pathbuf.chars, dlerror());
@@ -90,7 +90,7 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...) {
do { do {
const char* pathRest = va_arg(defaultNames, const char*); const char* pathRest = va_arg(defaultNames, const char*);
if (pathRest == NULL) { if (pathRest == nullptr) {
break; break;
} }
@@ -115,11 +115,11 @@ void* dlopen(const char* path, FF_A_UNUSED int mode) {
NTSTATUS status = RtlUTF8ToUnicodeN(pathW, sizeof(pathW), &pathWBytes, path, (uint32_t) strlen(path) + 1); NTSTATUS status = RtlUTF8ToUnicodeN(pathW, sizeof(pathW), &pathWBytes, path, (uint32_t) strlen(path) + 1);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("RtlUTF8ToUnicodeN failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); FF_DEBUG("RtlUTF8ToUnicodeN failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status));
return NULL; return nullptr;
} }
PVOID module = NULL; PVOID module = nullptr;
status = LdrLoadDll(NULL, NULL, &(UNICODE_STRING) { status = LdrLoadDll(nullptr, nullptr, &(UNICODE_STRING) {
.Length = (USHORT) (pathWBytes - sizeof(wchar_t)), // Exclude null terminator .Length = (USHORT) (pathWBytes - sizeof(wchar_t)), // Exclude null terminator
.MaximumLength = (USHORT) pathWBytes, .MaximumLength = (USHORT) pathWBytes,
.Buffer = pathW, .Buffer = pathW,
@@ -128,7 +128,7 @@ void* dlopen(const char* path, FF_A_UNUSED int mode) {
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("LdrLoadDll failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); FF_DEBUG("LdrLoadDll failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status));
return NULL; return nullptr;
} }
return module; return module;
@@ -155,17 +155,17 @@ void* dlsym(void* handle, const char* symbol) {
&address); &address);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("LdrGetProcedureAddress failed for symbol %s with status 0x%08lX: %s", symbol, status, ffDebugNtStatus(status)); FF_DEBUG("LdrGetProcedureAddress failed for symbol %s with status 0x%08lX: %s", symbol, status, ffDebugNtStatus(status));
return NULL; return nullptr;
} }
return address; return address;
} }
void* ffLibraryGetModule(const wchar_t* libraryFileName) { void* ffLibraryGetModule(const wchar_t* libraryFileName) {
assert(libraryFileName != NULL && "Use \"ffGetPeb()->ImageBaseAddress\" instead"); assert(libraryFileName != nullptr && "Use \"ffGetPeb()->ImageBaseAddress\" instead");
void* module = NULL; void* module = nullptr;
USHORT libraryFileNameBytes = (USHORT) (wcslen(libraryFileName) * sizeof(wchar_t) + sizeof(wchar_t)); USHORT libraryFileNameBytes = (USHORT) (wcslen(libraryFileName) * sizeof(wchar_t) + sizeof(wchar_t));
NTSTATUS status = LdrGetDllHandle(NULL, NULL, &(UNICODE_STRING) { NTSTATUS status = LdrGetDllHandle(nullptr, nullptr, &(UNICODE_STRING) {
.Length = libraryFileNameBytes - sizeof(wchar_t), .Length = libraryFileNameBytes - sizeof(wchar_t),
.MaximumLength = libraryFileNameBytes, .MaximumLength = libraryFileNameBytes,
.Buffer = (wchar_t*) libraryFileName, .Buffer = (wchar_t*) libraryFileName,
@@ -173,7 +173,7 @@ void* ffLibraryGetModule(const wchar_t* libraryFileName) {
&module); &module);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("LdrGetDllHandle failed for library %ls with status 0x%08lX: %s", libraryFileName, status, ffDebugNtStatus(status)); FF_DEBUG("LdrGetDllHandle failed for library %ls with status 0x%08lX: %s", libraryFileName, status, ffDebugNtStatus(status));
return NULL; return nullptr;
} }
return module; return module;
} }
+8 -8
View File
@@ -109,7 +109,7 @@ static int yyjsonEncode(lua_State* L) {
pretty = (int) lua_toboolean(L, 2); pretty = (int) lua_toboolean(L, 2);
} }
yyjson_mut_doc* doc = yyjson_mut_doc_new(NULL); yyjson_mut_doc* doc = yyjson_mut_doc_new(nullptr);
if (__builtin_expect(!doc, false)) { if (__builtin_expect(!doc, false)) {
lua_pushlstring(L, "yyjson: yyjson_mut_doc_new() failed", strlen("yyjson: yyjson_mut_doc_new() failed")); lua_pushlstring(L, "yyjson: yyjson_mut_doc_new() failed", strlen("yyjson: yyjson_mut_doc_new() failed"));
return lua_error(L); return lua_error(L);
@@ -120,9 +120,9 @@ static int yyjsonEncode(lua_State* L) {
size_t jsonLen; size_t jsonLen;
yyjson_write_err err = {}; yyjson_write_err err = {};
FF_AUTO_FREE const char* jsonStr = yyjson_mut_write_opts(doc, YYJSON_WRITE_ALLOW_INF_AND_NAN | (pretty ? YYJSON_WRITE_PRETTY_TWO_SPACES : 0), NULL, &jsonLen, &err); FF_AUTO_FREE const char* jsonStr = yyjson_mut_write_opts(doc, YYJSON_WRITE_ALLOW_INF_AND_NAN | (pretty ? YYJSON_WRITE_PRETTY_TWO_SPACES : 0), nullptr, &jsonLen, &err);
if (__builtin_expect(jsonStr != NULL, true)) { if (__builtin_expect(jsonStr != nullptr, true)) {
lua_pushlstring(L, jsonStr, jsonLen); lua_pushlstring(L, jsonStr, jsonLen);
yyjson_mut_doc_free(doc); yyjson_mut_doc_free(doc);
return 1; return 1;
@@ -140,10 +140,10 @@ static int yyjsonEncode(lua_State* L) {
const char* ffLuaLoadState(void) { const char* ffLuaLoadState(void) {
if (luaData.inited) { if (luaData.inited) {
if (luaData.L == NULL) { if (luaData.L == nullptr) {
return "Lua library is not available"; return "Lua library is not available";
} }
return NULL; return nullptr;
} }
luaData.inited = true; luaData.inited = true;
@@ -211,7 +211,7 @@ const char* ffLuaLoadState(void) {
#endif #endif
lua_State* L = ffluaL_newstate(); lua_State* L = ffluaL_newstate();
if (L == NULL) { if (L == nullptr) {
return "luaL_newstate() failed"; return "luaL_newstate() failed";
} }
#if LUA_VERSION_NUM >= 505 #if LUA_VERSION_NUM >= 505
@@ -226,8 +226,8 @@ const char* ffLuaLoadState(void) {
lua_pushcfunction(L, yyjsonEncode); lua_pushcfunction(L, yyjsonEncode);
lua_setglobal(L, "json_encode"); lua_setglobal(L, "json_encode");
luaData.L = L; luaData.L = L;
liblua = NULL; // don't close lua liblua = nullptr; // don't close lua
return NULL; return nullptr;
} }
#endif #endif
+2 -2
View File
@@ -4,7 +4,7 @@
void* memrchr(const void* s, int c, size_t n) { void* memrchr(const void* s, int c, size_t n) {
if (n == 0) { if (n == 0) {
return NULL; return nullptr;
} }
const uint8_t uc = (uint8_t) c; const uint8_t uc = (uint8_t) c;
@@ -17,5 +17,5 @@ void* memrchr(const void* s, int c, size_t n) {
} }
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -52,7 +52,7 @@ get_rt_address(struct rt_msghdr* rtm, int desired) {
sa = (struct sockaddr*) (ROUNDUP(salen) + (char*) sa); sa = (struct sockaddr*) (ROUNDUP(salen) + (char*) sa);
} }
} }
return NULL; return nullptr;
} }
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
+5 -5
View File
@@ -39,20 +39,20 @@ get_rt_address(struct rt_msghdr* rtm, int desired) {
sa = (struct sockaddr*) (ROUNDUP(sa->sa_len) + (char*) sa); sa = (struct sockaddr*) (ROUNDUP(sa->sa_len) + (char*) sa);
} }
} }
return NULL; return nullptr;
} }
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY }; int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY };
size_t needed; size_t needed;
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { if (sysctl(mib, 6, nullptr, &needed, nullptr, 0) < 0 || needed == 0) {
return false; return false;
} }
FF_AUTO_FREE char* buf = malloc(needed); FF_AUTO_FREE char* buf = malloc(needed);
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { if (sysctl(mib, 6, buf, &needed, nullptr, 0) < 0) {
return false; return false;
} }
@@ -89,13 +89,13 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) {
int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET6, NET_RT_FLAGS, RTF_GATEWAY }; int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET6, NET_RT_FLAGS, RTF_GATEWAY };
size_t needed; size_t needed;
if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { if (sysctl(mib, 6, nullptr, &needed, nullptr, 0) < 0 || needed == 0) {
return false; return false;
} }
FF_AUTO_FREE char* buf = malloc(needed); FF_AUTO_FREE char* buf = malloc(needed);
if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { if (sysctl(mib, 6, buf, &needed, nullptr, 0) < 0) {
return false; return false;
} }
+8 -8
View File
@@ -29,7 +29,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
} }
FF_AUTO_FREE void* buffer = malloc((size_t) size); FF_AUTO_FREE void* buffer = malloc((size_t) size);
if (buffer == NULL) { if (buffer == nullptr) {
return false; return false;
} }
@@ -54,13 +54,13 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
} }
size_t addressSize = 0; size_t addressSize = 0;
if (interface->ifr_route.destination != NULL) { if (interface->ifr_route.destination != nullptr) {
addressSize += interface->ifr_route.destination->sa_len; addressSize += interface->ifr_route.destination->sa_len;
} }
if (interface->ifr_route.mask != NULL) { if (interface->ifr_route.mask != nullptr) {
addressSize += interface->ifr_route.mask->sa_len; addressSize += interface->ifr_route.mask->sa_len;
} }
if (interface->ifr_route.gateway != NULL) { if (interface->ifr_route.gateway != nullptr) {
addressSize += interface->ifr_route.gateway->sa_len; addressSize += interface->ifr_route.gateway->sa_len;
} }
@@ -88,7 +88,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) {
} }
FF_AUTO_FREE void* buffer = malloc((size_t) size); FF_AUTO_FREE void* buffer = malloc((size_t) size);
if (buffer == NULL) { if (buffer == nullptr) {
return false; return false;
} }
@@ -109,13 +109,13 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) {
} }
size_t addressSize = 0; size_t addressSize = 0;
if (interface->ifr_route.destination != NULL) { if (interface->ifr_route.destination != nullptr) {
addressSize += interface->ifr_route.destination->sa_len; addressSize += interface->ifr_route.destination->sa_len;
} }
if (interface->ifr_route.mask != NULL) { if (interface->ifr_route.mask != nullptr) {
addressSize += interface->ifr_route.mask->sa_len; addressSize += interface->ifr_route.mask->sa_len;
} }
if (interface->ifr_route.gateway != NULL) { if (interface->ifr_route.gateway != nullptr) {
addressSize += interface->ifr_route.gateway->sa_len; addressSize += interface->ifr_route.gateway->sa_len;
} }
+2 -2
View File
@@ -4,7 +4,7 @@
#include <iphlpapi.h> #include <iphlpapi.h>
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; PMIB_IPFORWARD_TABLE2 pIpForwardTable = nullptr;
if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET, &pIpForwardTable))) { if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET, &pIpForwardTable))) {
return false; return false;
@@ -48,7 +48,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) {
} }
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) {
PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; PMIB_IPFORWARD_TABLE2 pIpForwardTable = nullptr;
if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET6, &pIpForwardTable))) { if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET6, &pIpForwardTable))) {
return false; return false;
+5 -5
View File
@@ -29,9 +29,9 @@ const char* ffNetworkingLoadZlibLibrary(void) {
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateInit2_) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateInit2_)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflate) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflate)
FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateEnd) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateEnd)
zlib = NULL; // don't auto dlclose zlib = nullptr; // don't auto dlclose
} }
return zlibData.ffinflateEnd == NULL ? "Failed to load libz" : NULL; return zlibData.ffinflateEnd == nullptr ? "Failed to load libz" : nullptr;
} }
// Try to pre-read gzip header to determine uncompressed size // Try to pre-read gzip header to determine uncompressed size
@@ -64,14 +64,14 @@ static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) {
// Decompress gzip content // Decompress gzip content
bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) { bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) {
assert(headerEnd != NULL && *headerEnd == '\r'); assert(headerEnd != nullptr && *headerEnd == '\r');
// Calculate header size // Calculate header size
uint32_t headerSize = (uint32_t) (headerEnd - buffer->chars); uint32_t headerSize = (uint32_t) (headerEnd - buffer->chars);
*headerEnd = '\0'; // Replace delimiter with null character for easier processing *headerEnd = '\0'; // Replace delimiter with null character for easier processing
// Ensure Content-Encoding is in response headers, not in response body // Ensure Content-Encoding is in response headers, not in response body
bool hasGzip = strcasestr(buffer->chars, "\nContent-Encoding: gzip") != NULL; bool hasGzip = strcasestr(buffer->chars, "\nContent-Encoding: gzip") != nullptr;
*headerEnd = '\r'; // Restore delimiter *headerEnd = '\r'; // Restore delimiter
if (!hasGzip) { if (!hasGzip) {
@@ -165,7 +165,7 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) {
// Use decompressedBuffer.length (total) not decompressedSize (last chunk only) // Use decompressedBuffer.length (total) not decompressedSize (last chunk only)
FF_STRBUF_AUTO_DESTROY newBuffer = ffStrbufCreateA(headerSize + decompressedBuffer.length + 64); FF_STRBUF_AUTO_DESTROY newBuffer = ffStrbufCreateA(headerSize + decompressedBuffer.length + 64);
char* line = NULL; char* line = nullptr;
size_t len = 0; size_t len = 0;
while (ffStrbufGetline(&line, &len, buffer)) { while (ffStrbufGetline(&line, &len, buffer)) {
if (ffStrStartsWithIgnCase(line, "Content-Encoding:")) { if (ffStrStartsWithIgnCase(line, "Content-Encoding:")) {
+16 -16
View File
@@ -97,7 +97,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) {
}, },
1, 1,
&sent, &sent,
NULL) != 0) { nullptr) != 0) {
sent = 0; sent = 0;
} }
if (fcntl(state->sockfd, F_SETFL, 0) == -1) { if (fcntl(state->sockfd, F_SETFL, 0) == -1) {
@@ -123,9 +123,9 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) {
sent, sent,
strerror(errno)); strerror(errno));
freeaddrinfo(state->addr); freeaddrinfo(state->addr);
state->addr = NULL; state->addr = nullptr;
ffStrbufDestroy(&state->command); ffStrbufDestroy(&state->command);
return NULL; return nullptr;
} }
FF_DEBUG( FF_DEBUG(
@@ -149,7 +149,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) {
// Traditional connect and send function // Traditional connect and send function
static const char* connectAndSend(FFNetworkingState* state) { static const char* connectAndSend(FFNetworkingState* state) {
const char* ret = NULL; const char* ret = nullptr;
FF_DEBUG("Using traditional connection method to connect"); FF_DEBUG("Using traditional connection method to connect");
FF_DEBUG("Attempting connect() to server..."); FF_DEBUG("Attempting connect() to server...");
@@ -178,7 +178,7 @@ error:
exit: exit:
FF_DEBUG("Releasing address info and other resources"); FF_DEBUG("Releasing address info and other resources");
freeaddrinfo(state->addr); freeaddrinfo(state->addr);
state->addr = NULL; state->addr = nullptr;
ffStrbufDestroy(&state->command); ffStrbufDestroy(&state->command);
return ret; return ret;
@@ -212,7 +212,7 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos
FF_DEBUG("Thread ID initialized to 0"); FF_DEBUG("Thread ID initialized to 0");
#endif #endif
const char* ret = NULL; const char* ret = nullptr;
struct addrinfo hints = { struct addrinfo hints = {
.ai_family = state->ipv6 ? AF_INET6 : AF_INET, .ai_family = state->ipv6 ? AF_INET6 : AF_INET,
@@ -280,14 +280,14 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos
#endif #endif
} }
return NULL; return nullptr;
error: error:
FF_DEBUG("Error occurred during initialization"); FF_DEBUG("Error occurred during initialization");
if (state->addr != NULL) { if (state->addr != nullptr) {
FF_DEBUG("Releasing address information"); FF_DEBUG("Releasing address information");
freeaddrinfo(state->addr); freeaddrinfo(state->addr);
state->addr = NULL; state->addr = nullptr;
} }
if (state->sockfd > 0) { if (state->sockfd > 0) {
@@ -307,7 +307,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
#ifdef FF_HAVE_ZLIB #ifdef FF_HAVE_ZLIB
const char* zlibError = ffNetworkingLoadZlibLibrary(); const char* zlibError = ffNetworkingLoadZlibLibrary();
// Only enable compression if zlib library is successfully loaded // Only enable compression if zlib library is successfully loaded
if (zlibError == NULL) { if (zlibError == nullptr) {
FF_DEBUG("Successfully loaded zlib library, compression enabled"); FF_DEBUG("Successfully loaded zlib library, compression enabled");
} else { } else {
FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError);
@@ -322,16 +322,16 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
} }
const char* initResult = initNetworkingState(state, host, path, headers); const char* initResult = initNetworkingState(state, host, path, headers);
if (initResult != NULL) { if (initResult != nullptr) {
FF_DEBUG("Initialization failed: %s", initResult); FF_DEBUG("Initialization failed: %s", initResult);
return initResult; return initResult;
} }
FF_DEBUG("Network state initialization successful"); FF_DEBUG("Network state initialization successful");
const char* tfoResult = tryNonThreadingFastPath(state); const char* tfoResult = tryNonThreadingFastPath(state);
if (tfoResult == NULL) { if (tfoResult == nullptr) {
FF_DEBUG("TryNonThreadingFastPath() succeeded or in progress"); FF_DEBUG("TryNonThreadingFastPath() succeeded or in progress");
return NULL; return nullptr;
} }
FF_DEBUG("TryNonThreadingFastPath() failed: %s, trying traditional connection", tfoResult); FF_DEBUG("TryNonThreadingFastPath() failed: %s, trying traditional connection", tfoResult);
@@ -341,7 +341,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
state->thread = ffThreadCreate(connectAndSendThreadMain, state); state->thread = ffThreadCreate(connectAndSendThreadMain, state);
if (state->thread) { if (state->thread) {
FF_DEBUG("Thread creation successful: thread=%p", (void*) (uintptr_t) state->thread); FF_DEBUG("Thread creation successful: thread=%p", (void*) (uintptr_t) state->thread);
return NULL; return nullptr;
} }
FF_DEBUG("Thread creation failed"); FF_DEBUG("Thread creation failed");
} else { } else {
@@ -455,7 +455,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
// Check for Content-Length header to pre-allocate enough memory // Check for Content-Length header to pre-allocate enough memory
const char* clHeader = strcasestr(buffer->chars, "Content-Length:"); const char* clHeader = strcasestr(buffer->chars, "Content-Length:");
if (clHeader) { if (clHeader) {
contentLength = (uint32_t) strtoul(clHeader + 15, NULL, 10); contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10);
if (contentLength > 0) { if (contentLength > 0) {
FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength); FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength);
// Ensure buffer is large enough, adding header size and some margin // Ensure buffer is large enough, adding header size and some margin
@@ -505,5 +505,5 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
} }
#endif #endif
return NULL; return nullptr;
} }
+15 -15
View File
@@ -23,7 +23,7 @@ static const char* initWsaData(WSADATA* wsaData) {
} }
// Dummy socket needed for WSAIoctl // Dummy socket needed for WSAIoctl
SOCKET sockfd = WSASocketW(AF_INET, SOCK_STREAM, 0, NULL, 0, 0); SOCKET sockfd = WSASocketW(AF_INET, SOCK_STREAM, 0, nullptr, 0, 0);
if (sockfd == INVALID_SOCKET) { if (sockfd == INVALID_SOCKET) {
FF_DEBUG("WSASocketW(AF_INET, SOCK_STREAM) failed"); FF_DEBUG("WSASocketW(AF_INET, SOCK_STREAM) failed");
WSACleanup(); WSACleanup();
@@ -32,7 +32,7 @@ static const char* initWsaData(WSADATA* wsaData) {
DWORD dwBytes; DWORD dwBytes;
GUID guid = WSAID_CONNECTEX; GUID guid = WSAID_CONNECTEX;
if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &dwBytes, NULL, NULL) != 0) { if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &dwBytes, nullptr, nullptr) != 0) {
FF_DEBUG("WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER) failed"); FF_DEBUG("WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER) failed");
closesocket(sockfd); closesocket(sockfd);
WSACleanup(); WSACleanup();
@@ -42,7 +42,7 @@ static const char* initWsaData(WSADATA* wsaData) {
closesocket(sockfd); closesocket(sockfd);
FF_DEBUG("WinSock initialized successfully"); FF_DEBUG("WinSock initialized successfully");
return NULL; return nullptr;
} }
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) { const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) {
@@ -52,7 +52,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
#ifdef FF_HAVE_ZLIB #ifdef FF_HAVE_ZLIB
const char* zlibError = ffNetworkingLoadZlibLibrary(); const char* zlibError = ffNetworkingLoadZlibLibrary();
// Only enable compression if zlib library is successfully loaded // Only enable compression if zlib library is successfully loaded
if (zlibError == NULL) { if (zlibError == nullptr) {
FF_DEBUG("Successfully loaded zlib library, compression enabled"); FF_DEBUG("Successfully loaded zlib library, compression enabled");
} else { } else {
FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError);
@@ -69,7 +69,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
static WSADATA wsaData; static WSADATA wsaData;
if (wsaData.wVersion == 0) { if (wsaData.wVersion == 0) {
const char* error = initWsaData(&wsaData); const char* error = initWsaData(&wsaData);
if (error != NULL) { if (error != nullptr) {
wsaData.wVersion = (WORD) -1; wsaData.wVersion = (WORD) -1;
FF_DEBUG("WinSock initialization failed: %s", error); FF_DEBUG("WinSock initialization failed: %s", error);
return error; return error;
@@ -87,7 +87,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
}; };
wchar_t hostW[256]; wchar_t hostW[256];
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), NULL, host, (ULONG) strlen(host) + 1))) { if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), nullptr, host, (ULONG) strlen(host) + 1))) {
FF_DEBUG("Failed to convert host to wide string: %s", host); FF_DEBUG("Failed to convert host to wide string: %s", host);
return "Failed to convert host to wide string"; return "Failed to convert host to wide string";
} }
@@ -98,7 +98,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
return "GetAddrInfoW() failed"; return "GetAddrInfoW() failed";
} }
state->sockfd = WSASocketW(addr->ai_family, addr->ai_socktype, addr->ai_protocol, NULL, 0, 0); state->sockfd = WSASocketW(addr->ai_family, addr->ai_socktype, addr->ai_protocol, nullptr, 0, 0);
if (state->sockfd == INVALID_SOCKET) { if (state->sockfd == INVALID_SOCKET) {
FF_DEBUG("WSASocketW() failed"); FF_DEBUG("WSASocketW() failed");
FreeAddrInfoW(addr); FreeAddrInfoW(addr);
@@ -189,7 +189,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
BOOL result = ConnectEx(state->sockfd, addr->ai_addr, (int) addr->ai_addrlen, state->command.chars, state->command.length, &sent, &state->overlapped); BOOL result = ConnectEx(state->sockfd, addr->ai_addr, (int) addr->ai_addrlen, state->command.chars, state->command.length, &sent, &state->overlapped);
FreeAddrInfoW(addr); FreeAddrInfoW(addr);
addr = NULL; addr = nullptr;
if (!result) { if (!result) {
if (WSAGetLastError() != WSA_IO_PENDING) { if (WSAGetLastError() != WSA_IO_PENDING) {
@@ -207,7 +207,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
} }
// No need to cleanup state fields here since we need them in the receive function // No need to cleanup state fields here since we need them in the receive function
return NULL; return nullptr;
} }
const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) { const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) {
@@ -250,9 +250,9 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
FF_DEBUG("WSAGetOverlappedResult succeeded, %u bytes sent", (unsigned) transfer); FF_DEBUG("WSAGetOverlappedResult succeeded, %u bytes sent", (unsigned) transfer);
ffStrbufDestroy(&state->command); ffStrbufDestroy(&state->command);
WSACloseEvent(state->overlapped.hEvent); WSACloseEvent(state->overlapped.hEvent);
state->overlapped.hEvent = NULL; state->overlapped.hEvent = nullptr;
if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) != 0) { if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nullptr, 0) != 0) {
FF_DEBUG("Failed to update connect context: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); FF_DEBUG("Failed to update connect context: %s", ffDebugWin32Error((DWORD) WSAGetLastError()));
// Not a critical error, continue anyway // Not a critical error, continue anyway
} }
@@ -293,8 +293,8 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
1, 1,
&received, &received,
&recvFlags, &recvFlags,
NULL, nullptr,
NULL); nullptr);
if (recvResult == SOCKET_ERROR || received == 0) { if (recvResult == SOCKET_ERROR || received == 0) {
if (recvResult == 0 && received == 0) { if (recvResult == 0 && received == 0) {
@@ -320,7 +320,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
// Check for Content-Length header to pre-allocate enough memory // Check for Content-Length header to pre-allocate enough memory
const char* clHeader = strcasestr(buffer->chars, "Content-Length:"); const char* clHeader = strcasestr(buffer->chars, "Content-Length:");
if (clHeader) { if (clHeader) {
contentLength = (uint32_t) strtoul(clHeader + 15, NULL, 10); contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10);
if (contentLength > 0) { if (contentLength > 0) {
FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength); FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength);
// Ensure buffer is large enough, adding header size and some margin // Ensure buffer is large enough, adding header size and some margin
@@ -372,5 +372,5 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
} }
#endif #endif
return NULL; return nullptr;
} }
+10 -10
View File
@@ -5,19 +5,19 @@
#include <limits.h> #include <limits.h>
// Return start position of the inner key if the argument key belongs to the module specified, NULL otherwise // Return start position of the inner key if the argument key belongs to the module specified, nullptr otherwise
const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) { const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) {
assert(argumentKey && moduleName); assert(argumentKey && moduleName);
const char* subKey = argumentKey; const char* subKey = argumentKey;
if (!(subKey[0] == '-' && subKey[1] == '-')) { if (!(subKey[0] == '-' && subKey[1] == '-')) {
return NULL; return nullptr;
} }
subKey += 2; subKey += 2;
uint32_t moduleNameLen = (uint32_t) strlen(moduleName); uint32_t moduleNameLen = (uint32_t) strlen(moduleName);
if (strncasecmp(subKey, moduleName, moduleNameLen) != 0) { if (strncasecmp(subKey, moduleName, moduleNameLen) != 0) {
return NULL; return nullptr;
} }
subKey += moduleNameLen; subKey += moduleNameLen;
@@ -27,7 +27,7 @@ const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName)
} }
if (subKey[0] != '-') { if (subKey[0] != '-') {
return NULL; return nullptr;
} }
subKey += 1; subKey += 1;
@@ -36,7 +36,7 @@ const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName)
} }
void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer) { void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer) {
if (value == NULL) { if (value == nullptr) {
fprintf(stderr, "Error: usage: %s <str>\n", argumentKey); fprintf(stderr, "Error: usage: %s <str>\n", argumentKey);
exit(477); exit(477);
} }
@@ -45,7 +45,7 @@ void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* b
} }
uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) { uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) {
if (value == NULL) { if (value == nullptr) {
fprintf(stderr, "Error: usage: %s <num>\n", argumentKey); fprintf(stderr, "Error: usage: %s <num>\n", argumentKey);
exit(480); exit(480);
} }
@@ -61,7 +61,7 @@ uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) {
} }
int32_t ffOptionParseInt32(const char* argumentKey, const char* value) { int32_t ffOptionParseInt32(const char* argumentKey, const char* value) {
if (value == NULL) { if (value == nullptr) {
fprintf(stderr, "Error: usage: %s <num>\n", argumentKey); fprintf(stderr, "Error: usage: %s <num>\n", argumentKey);
exit(480); exit(480);
} }
@@ -77,7 +77,7 @@ int32_t ffOptionParseInt32(const char* argumentKey, const char* value) {
} }
int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]) { int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]) {
if (requestedKey == NULL) { if (requestedKey == nullptr) {
fprintf(stderr, "Error: usage: %s <value>\n", argumentKey); fprintf(stderr, "Error: usage: %s <value>\n", argumentKey);
exit(476); exit(476);
} }
@@ -139,7 +139,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) {
} else if (value[0] == '@') { } else if (value[0] == '@') {
// Xterm 256 color // Xterm 256 color
++value; ++value;
char* pend = NULL; char* pend = nullptr;
uint32_t color = (uint32_t) strtoul(value, &pend, 10); uint32_t color = (uint32_t) strtoul(value, &pend, 10);
if (pend == value || color > 255) { if (pend == value || color > 255) {
fprintf(stderr, "Error: invalid 256 color code found: %s\n", value); fprintf(stderr, "Error: invalid 256 color code found: %s\n", value);
@@ -153,7 +153,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) {
} else if (value[0] == '#') { } else if (value[0] == '#') {
// RGB color // RGB color
++value; ++value;
char* pend = NULL; char* pend = nullptr;
uint32_t rgb = (uint32_t) strtoul(value, &pend, 16); uint32_t rgb = (uint32_t) strtoul(value, &pend, 16);
if (pend == value) { if (pend == value) {
fprintf(stderr, "Error: invalid RGB color code found: %s\n", value); fprintf(stderr, "Error: invalid RGB color code found: %s\n", value);
+18 -18
View File
@@ -47,7 +47,7 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) {
} }
#endif #endif
return NULL; return nullptr;
} }
ffStrbufClear(result); ffStrbufClear(result);
return "Executable not found"; return "Executable not found";
@@ -60,13 +60,13 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) {
const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) {
char buffer[MAX_PATH + 1]; char buffer[MAX_PATH + 1];
DWORD length = SearchPathA(NULL, name, ".exe", sizeof(buffer), buffer, NULL); DWORD length = SearchPathA(nullptr, name, ".exe", sizeof(buffer), buffer, nullptr);
if (length == 0) { if (length == 0) {
ffStrbufClear(result); ffStrbufClear(result);
return "Executable not found"; return "Executable not found";
} }
ffStrbufSetS(result, buffer); ffStrbufSetS(result, buffer);
return NULL; return nullptr;
} }
static inline int winerr2Errno(DWORD err) { static inline int winerr2Errno(DWORD err) {
@@ -93,7 +93,7 @@ static inline int winerr2Errno(DWORD err) {
char* frealpath(HANDLE hFile, char* resolved_name) { char* frealpath(HANDLE hFile, char* resolved_name) {
if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !hFile, false)) { if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !hFile, false)) {
errno = EINVAL; errno = EINVAL;
return NULL; return nullptr;
} }
wchar_t resolvedNameW[MAX_PATH + 4]; /* +4 for "\\\\?\\" prefix */ wchar_t resolvedNameW[MAX_PATH + 4]; /* +4 for "\\\\?\\" prefix */
@@ -101,11 +101,11 @@ char* frealpath(HANDLE hFile, char* resolved_name) {
if (lenW == 0) { if (lenW == 0) {
errno = winerr2Errno(GetLastError()); errno = winerr2Errno(GetLastError());
return NULL; return nullptr;
} }
if (lenW >= ARRAY_SIZE(resolvedNameW)) { if (lenW >= ARRAY_SIZE(resolvedNameW)) {
errno = E2BIG; errno = E2BIG;
return NULL; return nullptr;
} }
lenW++; // Include null terminator lenW++; // Include null terminator
@@ -126,7 +126,7 @@ char* frealpath(HANDLE hFile, char* resolved_name) {
ULONG outBytes = 0; ULONG outBytes = 0;
if (!NT_SUCCESS(RtlUnicodeToUTF8N(resolved_name, MAX_PATH, &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { if (!NT_SUCCESS(RtlUnicodeToUTF8N(resolved_name, MAX_PATH, &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) {
errno = E2BIG; errno = E2BIG;
return NULL; return nullptr;
} }
} else { } else {
/* UTF-8 worst-case: up to 4 bytes per UTF-16 code unit */ /* UTF-8 worst-case: up to 4 bytes per UTF-16 code unit */
@@ -135,13 +135,13 @@ char* frealpath(HANDLE hFile, char* resolved_name) {
if (!NT_SUCCESS(RtlUnicodeToUTF8N(tmp, (ULONG) sizeof(tmp), &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { if (!NT_SUCCESS(RtlUnicodeToUTF8N(tmp, (ULONG) sizeof(tmp), &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) {
errno = E2BIG; errno = E2BIG;
return NULL; return nullptr;
} }
resolved_name = (char*) malloc(outBytes); resolved_name = (char*) malloc(outBytes);
if (!resolved_name) { if (!resolved_name) {
errno = ENOMEM; errno = ENOMEM;
return NULL; return nullptr;
} }
memcpy(resolved_name, tmp, outBytes); memcpy(resolved_name, tmp, outBytes);
@@ -153,7 +153,7 @@ char* frealpath(HANDLE hFile, char* resolved_name) {
char* realpath(const char* __restrict file_name, char* __restrict resolved_name) { char* realpath(const char* __restrict file_name, char* __restrict resolved_name) {
if (!file_name) { if (!file_name) {
errno = EINVAL; errno = EINVAL;
return NULL; return nullptr;
} }
wchar_t fileNameW[MAX_PATH]; wchar_t fileNameW[MAX_PATH];
@@ -161,21 +161,21 @@ char* realpath(const char* __restrict file_name, char* __restrict resolved_name)
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &lenBytes, file_name, (ULONG) strlen(file_name) + 1))) { if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &lenBytes, file_name, (ULONG) strlen(file_name) + 1))) {
errno = EINVAL; errno = EINVAL;
return NULL; return nullptr;
} }
FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileW( FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileW(
fileNameW, fileNameW,
0, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_BACKUP_SEMANTICS,
NULL); nullptr);
if (hFile == INVALID_HANDLE_VALUE) { if (hFile == INVALID_HANDLE_VALUE) {
errno = winerr2Errno(GetLastError()); errno = winerr2Errno(GetLastError());
return NULL; return nullptr;
} }
return frealpath(hFile, resolved_name); return frealpath(hFile, resolved_name);
@@ -189,13 +189,13 @@ ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) {
alignas(REPARSE_DATA_BUFFER) BYTE reparseBuf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; alignas(REPARSE_DATA_BUFFER) BYTE reparseBuf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
DWORD bytesReturned = 0; DWORD bytesReturned = 0;
if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, NULL)) { if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, nullptr, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, nullptr)) {
errno = winerr2Errno(GetLastError()); errno = winerr2Errno(GetLastError());
return -1; return -1;
} }
REPARSE_DATA_BUFFER* rp = (REPARSE_DATA_BUFFER*) reparseBuf; REPARSE_DATA_BUFFER* rp = (REPARSE_DATA_BUFFER*) reparseBuf;
const wchar_t* targetW = NULL; const wchar_t* targetW = nullptr;
USHORT targetBytes = 0; USHORT targetBytes = 0;
if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) { if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
@@ -262,10 +262,10 @@ ssize_t readlink(const char* path, char* buf, size_t bufsiz) {
pathW, pathW,
0, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, nullptr,
OPEN_EXISTING, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
NULL); nullptr);
if (hFile == INVALID_HANDLE_VALUE) { if (hFile == INVALID_HANDLE_VALUE) {
errno = winerr2Errno(GetLastError()); errno = winerr2Errno(GetLastError());
+3 -3
View File
@@ -17,7 +17,7 @@ static void appendOutputColor(FFstrbuf* buffer, const FFModuleArgs* module) {
const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFlags* result) { const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFlags* result) {
if (yyjson_is_uint(jsonVal)) { if (yyjson_is_uint(jsonVal)) {
*result = (FFPercentageTypeFlags) yyjson_get_uint(jsonVal); *result = (FFPercentageTypeFlags) yyjson_get_uint(jsonVal);
return NULL; return nullptr;
} }
if (yyjson_is_arr(jsonVal)) { if (yyjson_is_arr(jsonVal)) {
FFPercentageTypeFlags flags = 0; FFPercentageTypeFlags flags = 0;
@@ -45,7 +45,7 @@ const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFl
} }
*result = flags; *result = flags;
return NULL; return nullptr;
} }
return "Error: usage: percent.type must be a number or an array of strings"; return "Error: usage: percent.type must be a number or an array of strings";
@@ -90,7 +90,7 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf
bool monochrome = (percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed; bool monochrome = (percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed;
if (!options->pipe && options->barColorElapsed.length > 0 && monochrome) { if (!options->pipe && options->barColorElapsed.length > 0 && monochrome) {
const char* color = NULL; const char* color = nullptr;
if (!autoColorElapsed) { if (!autoColorElapsed) {
color = options->barColorElapsed.chars; color = options->barColorElapsed.chars;
} else if (green <= yellow) { } else if (green <= yellow) {
+3 -3
View File
@@ -7,7 +7,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu
ffLogoPrintLine(); ffLogoPrintLine();
// This is used by --set-keyless, in this case we want neither the module name nor the separator // This is used by --set-keyless, in this case we want neither the module name nor the separator
if (moduleName == NULL) { if (moduleName == nullptr) {
return; return;
} }
@@ -35,7 +35,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu
if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_STRING) { if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_STRING) {
ffPrintCharTimes(' ', instance.config.display.keyType >> FF_MODULE_KEY_TYPE_SPACE_SHIFT); ffPrintCharTimes(' ', instance.config.display.keyType >> FF_MODULE_KEY_TYPE_SPACE_SHIFT);
// NULL check is required for modules with custom keys, e.g. disk with the folder path // nullptr check is required for modules with custom keys, e.g. disk with the folder path
if ((printType & FF_PRINT_TYPE_NO_CUSTOM_KEY) || !moduleArgs || moduleArgs->key.length == 0) { if ((printType & FF_PRINT_TYPE_NO_CUSTOM_KEY) || !moduleArgs || moduleArgs->key.length == 0) {
fputs(moduleName, stdout); fputs(moduleName, stdout);
@@ -84,7 +84,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu
bool ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments) { bool ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments) {
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
bool success; bool success;
if (__builtin_expect(moduleArgs != NULL, 1)) { if (__builtin_expect(moduleArgs != nullptr, 1)) {
success = ffParseFormatString(&buffer, &moduleArgs->outputFormat, numArgs, arguments); success = ffParseFormatString(&buffer, &moduleArgs->outputFormat, numArgs, arguments);
} else { } else {
ffStrbufSetStatic(&buffer, "undefined format"); ffStrbufSetStatic(&buffer, "undefined format");
+21 -21
View File
@@ -79,7 +79,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
posix_spawn_file_actions_adddup2(&file_actions, pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO); posix_spawn_file_actions_adddup2(&file_actions, pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO);
posix_spawn_file_actions_adddup2(&file_actions, nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO); posix_spawn_file_actions_adddup2(&file_actions, nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO);
static char* oldLang = NULL; static char* oldLang = nullptr;
static int langIndex = -1; static int langIndex = -1;
if (langIndex >= 0) { if (langIndex >= 0) {
@@ -95,7 +95,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
} }
} }
if (langIndex < 0) { if (langIndex < 0) {
for (int i = 0; environ[i] != NULL; i++) { for (int i = 0; environ[i] != nullptr; i++) {
if (ffStrStartsWith(environ[i], "LANG=")) { if (ffStrStartsWith(environ[i], "LANG=")) {
langIndex = i; langIndex = i;
const char* langValue = environ[i] + 5; // Skip "LANG=" const char* langValue = environ[i] + 5; // Skip "LANG="
@@ -112,7 +112,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
} }
} }
int ret = posix_spawnp(&childPid, argv[0], &file_actions, NULL, argv, environ); int ret = posix_spawnp(&childPid, argv[0], &file_actions, nullptr, argv, environ);
if (oldLang) { if (oldLang) {
environ[langIndex] = oldLang; environ[langIndex] = oldLang;
@@ -153,7 +153,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
close(pipes[1]); close(pipes[1]);
outHandle->pid = childPid; outHandle->pid = childPid;
outHandle->pipeRead = pipes[0]; outHandle->pipeRead = pipes[0];
return NULL; return nullptr;
} }
const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
@@ -173,11 +173,11 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
int pollret = poll(&pollfd, 1, timeout); int pollret = poll(&pollfd, 1, timeout);
if (pollret == 0) { if (pollret == 0) {
kill(childPid, SIGTERM); kill(childPid, SIGTERM);
waitpid(childPid, NULL, 0); waitpid(childPid, nullptr, 0);
return "poll(&pollfd, 1, timeout) timeout (try increasing --processing-timeout)"; return "poll(&pollfd, 1, timeout) timeout (try increasing --processing-timeout)";
} else if (pollret < 0 || (pollfd.revents & POLLERR)) { } else if (pollret < 0 || (pollfd.revents & POLLERR)) {
kill(childPid, SIGTERM); kill(childPid, SIGTERM);
waitpid(childPid, NULL, 0); waitpid(childPid, nullptr, 0);
return pollret < 0 return pollret < 0
? "poll(&pollfd, 1, timeout) error: pollret < 0" ? "poll(&pollfd, 1, timeout) error: pollret < 0"
: "poll(&pollfd, 1, timeout) error: pollfd.revents & POLLERR"; : "poll(&pollfd, 1, timeout) error: pollfd.revents & POLLERR";
@@ -197,9 +197,9 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
return "command not found"; return "command not found";
} }
// We only handle 127 as an error. See `getTerminalVersionUrxvt` in `terminalshell.c` // We only handle 127 as an error. See `getTerminalVersionUrxvt` in `terminalshell.c`
return NULL; return nullptr;
} }
return NULL; return nullptr;
} else if (nRead < 0) { } else if (nRead < 0) {
break; break;
} }
@@ -278,11 +278,11 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
size_t len = 0; size_t len = 0;
int mibs[] = { CTL_KERN, KERN_PROCARGS2, pid }; int mibs[] = { CTL_KERN, KERN_PROCARGS2, pid };
if (sysctl(mibs, ARRAY_SIZE(mibs), NULL, &len, NULL, 0) == 0) { // try get arg0 if (sysctl(mibs, ARRAY_SIZE(mibs), nullptr, &len, nullptr, 0) == 0) { // try get arg0
// don't know why if don't let len longer, proArgs2 and len will change during the following sysctl() in old MacOS version. // don't know why if don't let len longer, proArgs2 and len will change during the following sysctl() in old MacOS version.
len++; len++;
FF_AUTO_FREE char* const procArgs2 = malloc(len); FF_AUTO_FREE char* const procArgs2 = malloc(len);
if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, NULL, 0) == 0) { if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, nullptr, 0) == 0) {
// https://gist.github.com/nonowarn/770696#file-getargv-c-L46 // https://gist.github.com/nonowarn/770696#file-getargv-c-L46
uint32_t argc = *(uint32_t*) procArgs2; uint32_t argc = *(uint32_t*) procArgs2;
const char* realExePath = procArgs2 + sizeof(argc); const char* realExePath = procArgs2 + sizeof(argc);
@@ -354,7 +354,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
4, 4,
args, args,
&size, &size,
NULL, nullptr,
0) == 0) 0) == 0)
ffStrbufSetNS(exePath, (uint32_t) (size - 1), args); ffStrbufSetNS(exePath, (uint32_t) (size - 1), args);
@@ -374,7 +374,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
4, 4,
args, args,
&size, &size,
NULL, nullptr,
0) == 0) { 0) == 0) {
char* arg0 = args; char* arg0 = args;
size_t arg0Len = strlen(args); size_t arg0Len = strlen(args);
@@ -423,7 +423,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
#elif defined(__OpenBSD__) #elif defined(__OpenBSD__)
kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr);
int count = 0; int count = 0;
const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count);
if (proc) { if (proc) {
@@ -488,7 +488,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
} }
buf[nRead] = '\0'; // pid (comm) state ppid pgrp session tty buf[nRead] = '\0'; // pid (comm) state ppid pgrp session tty
const char* pState = NULL; const char* pState = nullptr;
{ {
// comm in `/proc/pid/stat` is not encoded, and may contain ' ', ')' or even `\n` // comm in `/proc/pid/stat` is not encoded, and may contain ' ', ')' or even `\n`
@@ -542,7 +542,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
struct kinfo_proc proc; struct kinfo_proc proc;
size_t size = sizeof(proc); size_t size = sizeof(proc);
if (sysctl( if (sysctl(
(int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, NULL, 0)) { (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, nullptr, 0)) {
return "sysctl(KERN_PROC_PID) failed"; return "sysctl(KERN_PROC_PID) failed";
} }
@@ -568,7 +568,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
struct kinfo_proc proc; struct kinfo_proc proc;
size_t size = sizeof(proc); size_t size = sizeof(proc);
if (sysctl( if (sysctl(
(int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, NULL, 0)) { (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, nullptr, 0)) {
return "sysctl(KERN_PROC_PID) failed"; return "sysctl(KERN_PROC_PID) failed";
} }
@@ -580,7 +580,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
if (proc.ki_tdev != NODEV && proc.ki_flag & P_CONTROLT) { if (proc.ki_tdev != NODEV && proc.ki_flag & P_CONTROLT) {
const char* ttyName = devname(proc.ki_tdev, S_IFCHR); const char* ttyName = devname(proc.ki_tdev, S_IFCHR);
if (ffStrStartsWith(ttyName, "pts/")) { if (ffStrStartsWith(ttyName, "pts/")) {
*tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); *tty = (int32_t) strtol(ttyName + strlen("pts/"), nullptr, 10);
} else { } else {
*tty = -1; *tty = -1;
} }
@@ -594,7 +594,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
struct kinfo_proc2 proc; struct kinfo_proc2 proc;
size_t size = sizeof(proc); size_t size = sizeof(proc);
if (sysctl( if (sysctl(
(int[]) { CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1 }, 6, &proc, &size, NULL, 0) != 0) { (int[]) { CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1 }, 6, &proc, &size, nullptr, 0) != 0) {
return "sysctl(KERN_PROC_PID) failed"; return "sysctl(KERN_PROC_PID) failed";
} }
@@ -606,7 +606,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
if (proc.p_flag & P_CONTROLT) { if (proc.p_flag & P_CONTROLT) {
const char* ttyName = devname(proc.p_tdev, S_IFCHR); const char* ttyName = devname(proc.p_tdev, S_IFCHR);
if (ffStrStartsWith(ttyName, "pts/")) { if (ffStrStartsWith(ttyName, "pts/")) {
*tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); *tty = (int32_t) strtol(ttyName + strlen("pts/"), nullptr, 10);
} else { } else {
*tty = -1; *tty = -1;
} }
@@ -633,7 +633,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
#elif defined(__OpenBSD__) #elif defined(__OpenBSD__)
kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr);
int count = 0; int count = 0;
const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count);
if (proc) { if (proc) {
@@ -668,5 +668,5 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
#endif #endif
return NULL; return nullptr;
} }
+20 -20
View File
@@ -15,7 +15,7 @@ static void argvToCmdline(char* const argv[], FFstrbuf* result) {
// From https://gist.github.com/jin-x/cdd641d98887524b091fb1f82a68717d // From https://gist.github.com/jin-x/cdd641d98887524b091fb1f82a68717d
FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate();
for (int i = 0; argv[i] != NULL; i++) { for (int i = 0; argv[i] != nullptr; i++) {
ffStrbufSetS(&temp, argv[i]); ffStrbufSetS(&temp, argv[i]);
// Add slash (\) before double quotes (") and duplicate slashes before it // Add slash (\) before double quotes (") and duplicate slashes before it
for ( for (
@@ -63,7 +63,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
FF_PIPE_BUFSIZ, FF_PIPE_BUFSIZ,
FF_PIPE_BUFSIZ, FF_PIPE_BUFSIZ,
0, 0,
NULL); nullptr);
if (hChildPipeRead == INVALID_HANDLE_VALUE) { if (hChildPipeRead == INVALID_HANDLE_VALUE) {
return "CreateNamedPipeW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; return "CreateNamedPipeW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed";
} }
@@ -74,12 +74,12 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
0, 0,
&(SECURITY_ATTRIBUTES) { &(SECURITY_ATTRIBUTES) {
.nLength = sizeof(SECURITY_ATTRIBUTES), .nLength = sizeof(SECURITY_ATTRIBUTES),
.lpSecurityDescriptor = NULL, .lpSecurityDescriptor = nullptr,
.bInheritHandle = TRUE, .bInheritHandle = TRUE,
}, },
OPEN_EXISTING, OPEN_EXISTING,
0, 0,
NULL); nullptr);
if (hChildPipeWrite == INVALID_HANDLE_VALUE) { if (hChildPipeWrite == INVALID_HANDLE_VALUE) {
return "CreateFileW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; return "CreateFileW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed";
} }
@@ -97,26 +97,26 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
siStartInfo.hStdError = ffGetNullFD(); siStartInfo.hStdError = ffGetNullFD();
} }
FF_AUTO_FREE wchar_t* cmdline = NULL; FF_AUTO_FREE wchar_t* cmdline = nullptr;
{ {
FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate();
argvToCmdline(argv, &buf); argvToCmdline(argv, &buf);
uint32_t cmdlineBytes = (buf.length + 1) * sizeof(wchar_t); uint32_t cmdlineBytes = (buf.length + 1) * sizeof(wchar_t);
cmdline = malloc(cmdlineBytes); cmdline = malloc(cmdlineBytes);
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, NULL, buf.chars, buf.length + 1))) { if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, nullptr, buf.chars, buf.length + 1))) {
return "RtlUTF8ToUnicodeN() failed"; return "RtlUTF8ToUnicodeN() failed";
} }
} }
BOOL success = CreateProcessW( BOOL success = CreateProcessW(
NULL, // application name nullptr, // application name
cmdline, // command line cmdline, // command line
NULL, // process security attributes nullptr, // process security attributes
NULL, // primary thread security attributes nullptr, // primary thread security attributes
TRUE, // handles are inherited TRUE, // handles are inherited
0, // creation flags 0, // creation flags
NULL, // use parent's environment nullptr, // use parent's environment
NULL, // use parent's current directory nullptr, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer &siStartInfo, // STARTUPINFO pointer
&piProcInfo // receives PROCESS_INFORMATION &piProcInfo // receives PROCESS_INFORMATION
); );
@@ -134,7 +134,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
outHandle->pipeRead = hChildPipeRead; outHandle->pipeRead = hChildPipeRead;
hChildPipeRead = INVALID_HANDLE_VALUE; // ownership transferred, don't close it hChildPipeRead = INVALID_HANDLE_VALUE; // ownership transferred, don't close it
return NULL; return nullptr;
} }
static void terminateChildProcess(HANDLE hProcess, HANDLE hChildPipeRead, HANDLE hReadEvent, IO_STATUS_BLOCK* piosb) { static void terminateChildProcess(HANDLE hProcess, HANDLE hChildPipeRead, HANDLE hReadEvent, IO_STATUS_BLOCK* piosb) {
@@ -154,11 +154,11 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
int32_t timeout = instance.config.general.processingTimeout; int32_t timeout = instance.config.general.processingTimeout;
FF_AUTO_CLOSE_FD HANDLE hProcess = handle->pid; FF_AUTO_CLOSE_FD HANDLE hProcess = handle->pid;
FF_AUTO_CLOSE_FD HANDLE hChildPipeRead = handle->pipeRead; FF_AUTO_CLOSE_FD HANDLE hChildPipeRead = handle->pipeRead;
FF_AUTO_CLOSE_FD HANDLE hReadEvent = NULL; FF_AUTO_CLOSE_FD HANDLE hReadEvent = nullptr;
handle->pid = INVALID_HANDLE_VALUE; handle->pid = INVALID_HANDLE_VALUE;
handle->pipeRead = INVALID_HANDLE_VALUE; handle->pipeRead = INVALID_HANDLE_VALUE;
if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE))) { if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, nullptr, SynchronizationEvent, FALSE))) {
return "NtCreateEvent() failed"; return "NtCreateEvent() failed";
} }
@@ -169,13 +169,13 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
NTSTATUS status = NtReadFile( NTSTATUS status = NtReadFile(
hChildPipeRead, hChildPipeRead,
hReadEvent, hReadEvent,
NULL, nullptr,
NULL, nullptr,
&iosb, &iosb,
str, str,
(ULONG) sizeof(str), (ULONG) sizeof(str),
NULL, nullptr,
NULL); nullptr);
if (status == STATUS_PENDING) { if (status == STATUS_PENDING) {
switch (NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 })) { switch (NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 })) {
case STATUS_WAIT_0: case STATUS_WAIT_0:
@@ -198,7 +198,7 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) {
} }
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
terminateChildProcess(hProcess, hChildPipeRead, NULL, &iosb); terminateChildProcess(hProcess, hChildPipeRead, nullptr, &iosb);
return "NtReadFile(hChildPipeRead) failed"; return "NtReadFile(hChildPipeRead) failed";
} }
@@ -219,7 +219,7 @@ exit: {
} }
} }
return NULL; return nullptr;
} }
bool ffProcessGetInfoWindows(uint32_t pid, uint32_t* ppid, FFstrbuf* pname, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath, bool* gui) { bool ffProcessGetInfoWindows(uint32_t pid, uint32_t* ppid, FFstrbuf* pname, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath, bool* gui) {
+2 -2
View File
@@ -95,7 +95,7 @@ bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer) {
bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries) { bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries) {
FF_AUTO_CLOSE_FILE FILE* file = fopen(filename, "r"); FF_AUTO_CLOSE_FILE FILE* file = fopen(filename, "r");
if (file == NULL) { if (file == nullptr) {
return false; return false;
} }
@@ -115,7 +115,7 @@ bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquer
} }
if (!allSet) { if (!allSet) {
FF_AUTO_FREE char* line = NULL; FF_AUTO_FREE char* line = nullptr;
size_t len = 0; size_t len = 0;
while (getline(&line, &len, file) != -1) { while (getline(&line, &len, file) != -1) {
+59 -59
View File
@@ -19,10 +19,10 @@ typedef struct GVariantGetters {
static FFvariant getGVariantValue(GVariant* variant, FFvarianttype type, const GVariantGetters* variantGetters) { static FFvariant getGVariantValue(GVariant* variant, FFvarianttype type, const GVariantGetters* variantGetters) {
FFvariant result; FFvariant result;
if (variant == NULL) { if (variant == nullptr) {
result = FF_VARIANT_NULL; result = FF_VARIANT_NULL;
} else if (type == FF_VARIANT_TYPE_STRING) { } else if (type == FF_VARIANT_TYPE_STRING) {
result = (FFvariant) { .strValue = variantGetters->ffg_variant_dup_string(variant, NULL) }; // Dup string, so that variant itself can be freed result = (FFvariant) { .strValue = variantGetters->ffg_variant_dup_string(variant, nullptr) }; // Dup string, so that variant itself can be freed
} else if (type == FF_VARIANT_TYPE_BOOL) { } else if (type == FF_VARIANT_TYPE_BOOL) {
result = (FFvariant) { .boolValue = (bool) variantGetters->ffg_variant_get_boolean(variant), .boolValueSet = true }; result = (FFvariant) { .boolValue = (bool) variantGetters->ffg_variant_get_boolean(variant), .boolValueSet = true };
} else if (type == FF_VARIANT_TYPE_INT) { } else if (type == FF_VARIANT_TYPE_INT) {
@@ -57,27 +57,27 @@ static const GSettingsData* getGSettingsData(void) {
if (!data.inited) { if (!data.inited) {
data.inited = true; data.inited = true;
FF_LIBRARY_LOAD(libgsettings, NULL, "libgio-2.0" FF_LIBRARY_EXTENSION, 1); FF_LIBRARY_LOAD(libgsettings, nullptr, "libgio-2.0" FF_LIBRARY_EXTENSION, 1);
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_lookup, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_lookup, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_has_key, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_has_key, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_new_full, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_new_full, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_value, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_value, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_user_value, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_user_value, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_default_value, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_default_value, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_get_default, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_get_default, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_dup_string, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_dup_string, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_boolean, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_boolean, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_int32, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_int32, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_unref, NULL); FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_unref, nullptr);
data.schemaSource = data.ffg_settings_schema_source_get_default(); data.schemaSource = data.ffg_settings_schema_source_get_default();
if (data.schemaSource) { if (data.schemaSource) {
libgsettings = NULL; libgsettings = nullptr;
} }
} }
if (!data.schemaSource) { if (!data.schemaSource) {
return NULL; return nullptr;
} }
return &data; return &data;
@@ -85,12 +85,12 @@ static const GSettingsData* getGSettingsData(void) {
FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) { FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) {
const GSettingsData* data = getGSettingsData(); const GSettingsData* data = getGSettingsData();
if (data == NULL) { if (data == nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
GSettingsSchema* schema = data->ffg_settings_schema_source_lookup(data->schemaSource, schemaName, true); GSettingsSchema* schema = data->ffg_settings_schema_source_lookup(data->schemaSource, schemaName, true);
if (schema == NULL) { if (schema == nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
@@ -98,18 +98,18 @@ FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
GSettings* settings = data->ffg_settings_new_full(schema, NULL, path); GSettings* settings = data->ffg_settings_new_full(schema, nullptr, path);
if (settings == NULL) { if (settings == nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
GVariant* variant = data->ffg_settings_get_value(settings, key); GVariant* variant = data->ffg_settings_get_value(settings, key);
if (variant != NULL) { if (variant != nullptr) {
return getGVariantValue(variant, type, &data->variantGetters); return getGVariantValue(variant, type, &data->variantGetters);
} }
variant = data->ffg_settings_get_user_value(settings, key); variant = data->ffg_settings_get_user_value(settings, key);
if (variant != NULL) { if (variant != nullptr) {
return getGVariantValue(variant, type, &data->variantGetters); return getGVariantValue(variant, type, &data->variantGetters);
} }
@@ -141,21 +141,21 @@ static const DConfData* getDConfData(void) {
if (!data.inited) { if (!data.inited) {
data.inited = true; data.inited = true;
FF_LIBRARY_LOAD(libdconf, NULL, "libdconf" FF_LIBRARY_EXTENSION, 2); FF_LIBRARY_LOAD(libdconf, nullptr, "libdconf" FF_LIBRARY_EXTENSION, 2);
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_read_full, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_read_full, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_new, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_new, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_dup_string, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_dup_string, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_boolean, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_boolean, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_int32, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_int32, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_unref, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_unref, nullptr)
data.client = data.ffdconf_client_new(); data.client = data.ffdconf_client_new();
if (data.client) { if (data.client) {
libdconf = NULL; libdconf = nullptr;
} }
} }
if (!data.client) { if (!data.client) {
return NULL; return nullptr;
} }
return &data; return &data;
@@ -163,21 +163,21 @@ static const DConfData* getDConfData(void) {
FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) { FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) {
const DConfData* data = getDConfData(); const DConfData* data = getDConfData();
if (data == NULL) { if (data == nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
GVariant* variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_FLAGS_NONE, NULL); GVariant* variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_FLAGS_NONE, nullptr);
if (variant != NULL) { if (variant != nullptr) {
return getGVariantValue(variant, type, &data->variantGetters); return getGVariantValue(variant, type, &data->variantGetters);
} }
variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_USER_VALUE, NULL); variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_USER_VALUE, nullptr);
if (variant != NULL) { if (variant != nullptr) {
return getGVariantValue(variant, type, &data->variantGetters); return getGVariantValue(variant, type, &data->variantGetters);
} }
variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_DEFAULT_VALUE, NULL); variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_DEFAULT_VALUE, nullptr);
return getGVariantValue(variant, type, &data->variantGetters); return getGVariantValue(variant, type, &data->variantGetters);
} }
#else // FF_HAVE_DCONF #else // FF_HAVE_DCONF
@@ -192,7 +192,7 @@ FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaNa
if ( if (
(type == FF_VARIANT_TYPE_BOOL && gsettings.boolValueSet) || (type == FF_VARIANT_TYPE_BOOL && gsettings.boolValueSet) ||
(type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != NULL)) { (type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != nullptr)) {
return gsettings; return gsettings;
} }
@@ -204,7 +204,7 @@ FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaNa
FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) { FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) {
FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {};
if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
@@ -260,7 +260,7 @@ FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName,
FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb) { FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb) {
FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {};
if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) {
return FF_VARIANT_NULL; return FF_VARIANT_NULL;
} }
@@ -361,20 +361,20 @@ static const SQLiteData* getSQLiteData(void) {
if (!data.inited) { if (!data.inited) {
data.inited = true; data.inited = true;
FF_LIBRARY_LOAD(libsqlite, NULL, "libsqlite3" FF_LIBRARY_EXTENSION, 1); FF_LIBRARY_LOAD(libsqlite, nullptr, "libsqlite3" FF_LIBRARY_EXTENSION, 1);
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_open_v2, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_open_v2, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_prepare_v2, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_prepare_v2, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_step, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_step, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_data_count, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_data_count, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_int, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_int, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_text, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_text, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_finalize, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_finalize, nullptr)
FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_close, NULL) FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_close, nullptr)
libsqlite = NULL; libsqlite = nullptr;
} }
if (!data.ffsqlite3_close) { if (!data.ffsqlite3_close) {
return NULL; return nullptr;
} }
return &data; return &data;
@@ -386,17 +386,17 @@ int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) {
} }
const SQLiteData* data = getSQLiteData(); const SQLiteData* data = getSQLiteData();
if (data == NULL) { if (data == nullptr) {
return 0; return 0;
} }
sqlite3* db; sqlite3* db;
if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) { if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, nullptr) != SQLITE_OK) {
return 0; return 0;
} }
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, nullptr) != SQLITE_OK) {
data->ffsqlite3_close(db); data->ffsqlite3_close(db);
return 0; return 0;
} }
@@ -421,17 +421,17 @@ bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf*
} }
const SQLiteData* data = getSQLiteData(); const SQLiteData* data = getSQLiteData();
if (data == NULL) { if (data == nullptr) {
return false; return false;
} }
sqlite3* db; sqlite3* db;
if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK) {
return false; return false;
} }
sqlite3_stmt* stmt; sqlite3_stmt* stmt;
if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, nullptr) != SQLITE_OK) {
data->ffsqlite3_close(db); data->ffsqlite3_close(db);
return false; return false;
} }
@@ -514,12 +514,12 @@ typedef struct E_Config {
#define FF_EET_DATA_DESCRIPTOR_ADD_BASIC(edd, struct_type, member, type) \ #define FF_EET_DATA_DESCRIPTOR_ADD_BASIC(edd, struct_type, member, type) \
do { \ do { \
struct_type ___ett; \ struct_type ___ett; \
ffeet_data_descriptor_element_add(edd, #member, type, EET_G_UNKNOWN, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ NULL, NULL); \ ffeet_data_descriptor_element_add(edd, #member, type, EET_G_UNKNOWN, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ nullptr, nullptr); \
} while (0) } while (0)
#define FF_EET_DATA_DESCRIPTOR_ADD_LIST(edd, struct_type, member, subtype) \ #define FF_EET_DATA_DESCRIPTOR_ADD_LIST(edd, struct_type, member, subtype) \
do { \ do { \
struct_type ___ett; \ struct_type ___ett; \
ffeet_data_descriptor_element_add(edd, #member, EET_T_UNKNOW, EET_G_LIST, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ NULL, subtype); \ ffeet_data_descriptor_element_add(edd, #member, EET_T_UNKNOW, EET_G_LIST, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ nullptr, subtype); \
} while (0) } while (0)
bool ffSettingsGetEnlightenmentProperty(ffEnlightenmentSettings* result) { bool ffSettingsGetEnlightenmentProperty(ffEnlightenmentSettings* result) {
+4 -4
View File
@@ -27,16 +27,16 @@ void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result) {
const FFOptionsDisplay* options = &instance.config.display; const FFOptionsDisplay* options = &instance.config.display;
switch (options->sizeBinaryPrefix) { switch (options->sizeBinaryPrefix) {
case FF_SIZE_BINARY_PREFIX_TYPE_IEC: case FF_SIZE_BINARY_PREFIX_TYPE_IEC:
appendNum(result, bytes, 1024, (const char*[]) { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL }); appendNum(result, bytes, 1024, (const char*[]) { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", nullptr });
break; break;
case FF_SIZE_BINARY_PREFIX_TYPE_SI: case FF_SIZE_BINARY_PREFIX_TYPE_SI:
appendNum(result, bytes, 1000, (const char*[]) { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", NULL }); appendNum(result, bytes, 1000, (const char*[]) { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", nullptr });
break; break;
case FF_SIZE_BINARY_PREFIX_TYPE_JEDEC: case FF_SIZE_BINARY_PREFIX_TYPE_JEDEC:
appendNum(result, bytes, 1024, (const char*[]) { "B", "KB", "MB", "GB", "TB", NULL }); appendNum(result, bytes, 1024, (const char*[]) { "B", "KB", "MB", "GB", "TB", nullptr });
break; break;
default: default:
appendNum(result, bytes, 1024, (const char*[]) { "B", NULL }); appendNum(result, bytes, 1024, (const char*[]) { "B", nullptr });
break; break;
} }
} }
+20 -20
View File
@@ -63,7 +63,7 @@ const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header) {
} }
static bool parseSmbiosTable(const uint8_t* data, uint32_t length) { static bool parseSmbiosTable(const uint8_t* data, uint32_t length) {
const FFSmbiosHeader* endOfTable = NULL; const FFSmbiosHeader* endOfTable = nullptr;
FF_DEBUG("Parsing SMBIOS table structures with length %u bytes", length); FF_DEBUG("Parsing SMBIOS table structures with length %u bytes", length);
FF_A_UNUSED int structureCount = 0, totalCount = 0; FF_A_UNUSED int structureCount = 0, totalCount = 0;
@@ -214,7 +214,7 @@ static bool readPhysicalMemory(int fd, off_t address, size_t length, void* buffe
size_t pageOffset = (size_t) (address - alignedAddress); size_t pageOffset = (size_t) (address - alignedAddress);
size_t mapLength = pageOffset + length; size_t mapLength = pageOffset + length;
void* p = mmap(NULL, mapLength, PROT_READ, MAP_SHARED, fd, alignedAddress); void* p = mmap(nullptr, mapLength, PROT_READ, MAP_SHARED, fd, alignedAddress);
if (p == MAP_FAILED) { if (p == MAP_FAILED) {
FF_DEBUG("mmap failed at aligned address 0x%lx for %zu bytes: %s", FF_DEBUG("mmap failed at aligned address 0x%lx for %zu bytes: %s",
(unsigned long) alignedAddress, (unsigned long) alignedAddress,
@@ -457,7 +457,7 @@ static bool fillTableBufferPlatform(FFstrbuf* buffer) {
} while (address < lineEnd && (*address == ' ' || *address == '\t')); } while (address < lineEnd && (*address == ' ' || *address == '\t'));
errno = 0; errno = 0;
char* addressEnd = NULL; char* addressEnd = nullptr;
unsigned long long parsedAddress = strtoull(address, &addressEnd, 16); unsigned long long parsedAddress = strtoull(address, &addressEnd, 16);
if (errno != 0 || addressEnd == address || parsedAddress == 0) { if (errno != 0 || addressEnd == address || parsedAddress == 0) {
FF_DEBUG("Failed to parse OpenBSD SMBIOS table address from line: %.*s", FF_DEBUG("Failed to parse OpenBSD SMBIOS table address from line: %.*s",
@@ -541,7 +541,7 @@ static bool fillTableBufferPlatform(FFstrbuf* buffer) {
} }
#endif #endif
off_t entryAddress = (off_t) strtol(strEntryAddress.chars, NULL, 16); off_t entryAddress = (off_t) strtol(strEntryAddress.chars, nullptr, 16);
if (entryAddress == 0) { if (entryAddress == 0) {
FF_DEBUG("Invalid SMBIOS entry address: 0"); FF_DEBUG("Invalid SMBIOS entry address: 0");
return false; return false;
@@ -671,7 +671,7 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
if (!fillTableBufferFallback(&buffer)) { if (!fillTableBufferFallback(&buffer)) {
FF_DEBUG("Fallback SMBIOS retrieval also failed"); FF_DEBUG("Fallback SMBIOS retrieval also failed");
ffStrbufDestroy(&buffer); ffStrbufDestroy(&buffer);
return NULL; return nullptr;
} }
} }
@@ -682,7 +682,7 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
if (buffer.length == 0) { if (buffer.length == 0) {
FF_DEBUG("No valid SMBIOS data available"); FF_DEBUG("No valid SMBIOS data available");
return NULL; return nullptr;
} }
return &smbiosTable; return &smbiosTable;
@@ -717,13 +717,13 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
NtQuerySystemInformation(SystemFirmwareTableInformation, &sfti, sizeof(sfti), &bufSize); NtQuerySystemInformation(SystemFirmwareTableInformation, &sfti, sizeof(sfti), &bufSize);
if (bufSize <= sizeof(FFRawSmbiosData) + sizeof(sfti)) { if (bufSize <= sizeof(FFRawSmbiosData) + sizeof(sfti)) {
FF_DEBUG("Invalid firmware table size: %lu (must be > %zu)", bufSize, sizeof(FFRawSmbiosData) + sizeof(sfti)); FF_DEBUG("Invalid firmware table size: %lu (must be > %zu)", bufSize, sizeof(FFRawSmbiosData) + sizeof(sfti));
return NULL; return nullptr;
} }
if (bufSize != sfti.TableBufferLength + (ULONG) sizeof(sfti)) { if (bufSize != sfti.TableBufferLength + (ULONG) sizeof(sfti)) {
FF_DEBUG("Firmware table size mismatch: NtQuerySystemInformation returned %lu but expected %lu", FF_DEBUG("Firmware table size mismatch: NtQuerySystemInformation returned %lu but expected %lu",
bufSize, bufSize,
sfti.TableBufferLength + (ULONG) sizeof(sfti)); sfti.TableBufferLength + (ULONG) sizeof(sfti));
return NULL; return nullptr;
} }
FF_DEBUG("Firmware table size: %lu bytes", bufSize); FF_DEBUG("Firmware table size: %lu bytes", bufSize);
@@ -734,8 +734,8 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
if (!NT_SUCCESS(NtQuerySystemInformation(SystemFirmwareTableInformation, buffer, bufSize, &bufSize))) { if (!NT_SUCCESS(NtQuerySystemInformation(SystemFirmwareTableInformation, buffer, bufSize, &bufSize))) {
FF_DEBUG("NtQuerySystemInformation(SystemFirmwareTableInformation) failed"); FF_DEBUG("NtQuerySystemInformation(SystemFirmwareTableInformation) failed");
free(buffer); free(buffer);
buffer = NULL; buffer = nullptr;
return NULL; return nullptr;
} }
FFRawSmbiosData* rawData = (FFRawSmbiosData*) buffer->TableBuffer; FFRawSmbiosData* rawData = (FFRawSmbiosData*) buffer->TableBuffer;
@@ -746,14 +746,14 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
if (!parseSmbiosTable(rawData->SMBIOSTableData, rawData->Length)) { if (!parseSmbiosTable(rawData->SMBIOSTableData, rawData->Length)) {
free(buffer); free(buffer);
buffer = NULL; buffer = nullptr;
return NULL; return nullptr;
} }
} }
if (!buffer) { if (!buffer) {
FF_DEBUG("No valid SMBIOS data available"); FF_DEBUG("No valid SMBIOS data available");
return NULL; return nullptr;
} }
return &smbiosTable; return &smbiosTable;
} }
@@ -771,33 +771,33 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() {
if (!registryEntry) { if (!registryEntry) {
FF_DEBUG("IOServiceGetMatchingService() failed to find AppleSMBIOS"); FF_DEBUG("IOServiceGetMatchingService() failed to find AppleSMBIOS");
return NULL; return nullptr;
} }
FF_DEBUG("AppleSMBIOS service found, retrieving SMBIOS data"); FF_DEBUG("AppleSMBIOS service found, retrieving SMBIOS data");
smbiosDataBuffer = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("SMBIOS"), kCFAllocatorDefault, kNilOptions); smbiosDataBuffer = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("SMBIOS"), kCFAllocatorDefault, kNilOptions);
if (!smbiosDataBuffer) { if (!smbiosDataBuffer) {
FF_DEBUG("IORegistryEntryCreateCFProperty() failed to get SMBIOS data"); FF_DEBUG("IORegistryEntryCreateCFProperty() failed to get SMBIOS data");
return NULL; return nullptr;
} }
if (CFGetTypeID(smbiosDataBuffer) != CFDataGetTypeID()) { if (CFGetTypeID(smbiosDataBuffer) != CFDataGetTypeID()) {
FF_DEBUG("Unexpected SMBIOS data type: expected CFData"); FF_DEBUG("Unexpected SMBIOS data type: expected CFData");
CFRelease(smbiosDataBuffer); CFRelease(smbiosDataBuffer);
smbiosDataBuffer = NULL; smbiosDataBuffer = nullptr;
return NULL; return nullptr;
} }
FF_DEBUG("Successfully retrieved SMBIOS data: %lu bytes", CFDataGetLength(smbiosDataBuffer)); FF_DEBUG("Successfully retrieved SMBIOS data: %lu bytes", CFDataGetLength(smbiosDataBuffer));
if (!parseSmbiosTable((const uint8_t*) CFDataGetBytePtr(smbiosDataBuffer), (uint32_t) CFDataGetLength(smbiosDataBuffer))) { if (!parseSmbiosTable((const uint8_t*) CFDataGetBytePtr(smbiosDataBuffer), (uint32_t) CFDataGetLength(smbiosDataBuffer))) {
CFRelease(smbiosDataBuffer); CFRelease(smbiosDataBuffer);
smbiosDataBuffer = NULL; smbiosDataBuffer = nullptr;
return NULL; return nullptr;
} }
} }
if (!smbiosDataBuffer) { if (!smbiosDataBuffer) {
FF_DEBUG("No valid SMBIOS data available"); FF_DEBUG("No valid SMBIOS data available");
return NULL; return nullptr;
} }
return &smbiosTable; return &smbiosTable;
+14 -14
View File
@@ -5,26 +5,26 @@
#ifdef __OpenBSD__ #ifdef __OpenBSD__
const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) { const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) {
size_t neededLength; size_t neededLength;
if (sysctl((int[]) { mib1, mib2 }, 2, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator if (sysctl((int[]) { mib1, mib2 }, 2, nullptr, &neededLength, nullptr, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator
return "sysctl() length query failed"; return "sysctl() length query failed";
} }
ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); ffStrbufEnsureFree(result, (uint32_t) neededLength - 1);
if (sysctl((int[]) { mib1, mib2 }, 2, result->chars + result->length, &neededLength, NULL, 0) != 0) { if (sysctl((int[]) { mib1, mib2 }, 2, result->chars + result->length, &neededLength, nullptr, 0) != 0) {
return "sysctl() failed to retrieve string data"; return "sysctl() failed to retrieve string data";
} }
result->length += (uint32_t) neededLength - 1; result->length += (uint32_t) neededLength - 1;
result->chars[result->length] = '\0'; result->chars[result->length] = '\0';
return NULL; return nullptr;
} }
int ffSysctlGetInt(int mib1, int mib2, int defaultValue) { int ffSysctlGetInt(int mib1, int mib2, int defaultValue) {
int result; int result;
size_t neededLength = sizeof(result); size_t neededLength = sizeof(result);
if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, NULL, 0) != 0) { if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) {
return defaultValue; return defaultValue;
} }
return result; return result;
@@ -33,7 +33,7 @@ int ffSysctlGetInt(int mib1, int mib2, int defaultValue) {
int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) { int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) {
int64_t result; int64_t result;
size_t neededLength = sizeof(result); size_t neededLength = sizeof(result);
if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, NULL, 0) != 0) { if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) {
return defaultValue; return defaultValue;
} }
return result; return result;
@@ -41,13 +41,13 @@ int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) {
#else #else
const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { const char* ffSysctlGetString(const char* propName, FFstrbuf* result) {
size_t neededLength; size_t neededLength;
if (sysctlbyname(propName, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator if (sysctlbyname(propName, nullptr, &neededLength, nullptr, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator
return "sysctlbyname() failed"; return "sysctlbyname() failed";
} }
ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); ffStrbufEnsureFree(result, (uint32_t) neededLength - 1);
if (sysctlbyname(propName, result->chars + result->length, &neededLength, NULL, 0) != 0) { if (sysctlbyname(propName, result->chars + result->length, &neededLength, nullptr, 0) != 0) {
return "sysctlbyname() failed to retrieve string data"; return "sysctlbyname() failed to retrieve string data";
} }
@@ -55,13 +55,13 @@ const char* ffSysctlGetString(const char* propName, FFstrbuf* result) {
result->chars[result->length] = '\0'; result->chars[result->length] = '\0';
return NULL; return nullptr;
} }
int ffSysctlGetInt(const char* propName, int defaultValue) { int ffSysctlGetInt(const char* propName, int defaultValue) {
int result; int result;
size_t neededLength = sizeof(result); size_t neededLength = sizeof(result);
if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) {
return defaultValue; return defaultValue;
} }
return result; return result;
@@ -70,7 +70,7 @@ int ffSysctlGetInt(const char* propName, int defaultValue) {
int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) { int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) {
int64_t result; int64_t result;
size_t neededLength = sizeof(result); size_t neededLength = sizeof(result);
if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) {
return defaultValue; return defaultValue;
} }
return result; return result;
@@ -78,15 +78,15 @@ int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) {
#endif // OpenBSD #endif // OpenBSD
void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength) { void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength) {
if (sysctl(request, requestLength, NULL, resultLength, NULL, 0) != 0) { if (sysctl(request, requestLength, nullptr, resultLength, nullptr, 0) != 0) {
return NULL; return nullptr;
} }
void* data = malloc(*resultLength); void* data = malloc(*resultLength);
if (sysctl(request, requestLength, data, resultLength, NULL, 0) != 0) { if (sysctl(request, requestLength, data, resultLength, nullptr, 0) != 0) {
free(data); free(data);
return NULL; return nullptr;
} }
return data; return data;
+2 -2
View File
@@ -67,10 +67,10 @@ __attribute__((destructor, no_instrument_function)) void trace_fini() {
#if _WIN32 #if _WIN32
SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME); SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
SymInitialize(NtCurrentProcess(), NULL, TRUE); SymInitialize(NtCurrentProcess(), nullptr, TRUE);
#endif #endif
const char* fnName = NULL; const char* fnName = nullptr;
uint32_t count = atomic_load_explicit(&event_count, memory_order_acquire); uint32_t count = atomic_load_explicit(&event_count, memory_order_acquire);
for (uint32_t i = 0; i < count; ++i) { for (uint32_t i = 0; i < count; ++i) {
+6 -6
View File
@@ -46,7 +46,7 @@ static inline bool ffIsValidNativeFD(FFNativeFD fd) {
return fd >= 0; return fd >= 0;
#else #else
// https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443 // https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443
return fd != INVALID_HANDLE_VALUE && fd != NULL; return fd != INVALID_HANDLE_VALUE && fd != nullptr;
#endif #endif
} }
@@ -77,7 +77,7 @@ FF_A_NONNULL(3) static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize,
return write(fd, data, dataSize) != -1; return write(fd, data, dataSize) != -1;
#else #else
DWORD written; DWORD written;
return WriteFile(fd, data, (DWORD) dataSize, &written, NULL) && written == dataSize; return WriteFile(fd, data, (DWORD) dataSize, &written, nullptr) && written == dataSize;
#endif #endif
} }
@@ -96,7 +96,7 @@ FF_A_NONNULL(3) static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSiz
return read(fd, data, dataSize); return read(fd, data, dataSize);
#else #else
DWORD bytesRead; DWORD bytesRead;
if (!ReadFile(fd, data, (DWORD) dataSize, &bytesRead, NULL)) { if (!ReadFile(fd, data, (DWORD) dataSize, &bytesRead, nullptr)) {
return -1; return -1;
} }
@@ -111,7 +111,7 @@ FF_A_NONNULL(1, 3) static inline ssize_t ffReadFileData(const char* fileName, si
#ifndef _WIN32 #ifndef _WIN32
open(fileName, O_RDONLY | O_CLOEXEC); open(fileName, O_RDONLY | O_CLOEXEC);
#else #else
CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
#endif #endif
if (!ffIsValidNativeFD(fd)) { if (!ffIsValidNativeFD(fd)) {
@@ -135,7 +135,7 @@ FF_A_NONNULL(1, 2) static inline bool ffAppendFileBuffer(const char* fileName, F
#ifndef _WIN32 #ifndef _WIN32
open(fileName, O_RDONLY | O_CLOEXEC); open(fileName, O_RDONLY | O_CLOEXEC);
#else #else
CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
#endif #endif
if (!ffIsValidNativeFD(fd)) { if (!ffIsValidNativeFD(fd)) {
@@ -179,7 +179,7 @@ FF_A_NONNULL(1) static inline bool ffPathExists(const char* path, FFPathType pat
#ifdef _WIN32 #ifdef _WIN32
wchar_t wPath[MAX_PATH]; wchar_t wPath[MAX_PATH];
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), NULL, path, (ULONG) strlen(path) + 1))) { if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), nullptr, path, (ULONG) strlen(path) + 1))) {
return false; return false;
} }
+4 -4
View File
@@ -37,8 +37,8 @@ static inline void ffLibraryUnload(void** handle) {
#define FF_LIBRARY_LOAD(libraryObjectName, returnValue, libraryFileName, maxVersion, ...) \ #define FF_LIBRARY_LOAD(libraryObjectName, returnValue, libraryFileName, maxVersion, ...) \
void* FF_A_CLEANUP(ffLibraryUnload) libraryObjectName = ffLibraryLoadSingle(libraryFileName, maxVersion); \ void* FF_A_CLEANUP(ffLibraryUnload) libraryObjectName = ffLibraryLoadSingle(libraryFileName, maxVersion); \
__VA_OPT__(if (__builtin_expect(libraryObjectName == NULL, false)) libraryObjectName = ffLibraryLoadMulti(__VA_ARGS__, NULL);) \ __VA_OPT__(if (__builtin_expect(libraryObjectName == nullptr, false)) libraryObjectName = ffLibraryLoadMulti(__VA_ARGS__, nullptr);) \
if (__builtin_expect(libraryObjectName == NULL, false)) \ if (__builtin_expect(libraryObjectName == nullptr, false)) \
return returnValue; return returnValue;
#define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ #define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \
@@ -46,7 +46,7 @@ static inline void ffLibraryUnload(void** handle) {
#define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ #define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \
symbolMapping = (__typeof__(&symbolName)) dlsym(library, #symbolName); \ symbolMapping = (__typeof__(&symbolName)) dlsym(library, #symbolName); \
if (__builtin_expect(symbolMapping == NULL, false)) \ if (__builtin_expect(symbolMapping == nullptr, false)) \
return returnValue; return returnValue;
#define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ #define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \
@@ -78,7 +78,7 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...);
__typeof__(&symbolName) ff##symbolName; __typeof__(&symbolName) ff##symbolName;
#define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ #define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \
FF_A_UNUSED void* libraryObjectName = NULL; // Placeholder FF_A_UNUSED void* libraryObjectName = nullptr; // Placeholder
#define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ #define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \
FF_LIBRARY_LOAD(libraryObjectName, , libraryFileName, maxVersion, ##__VA_ARGS__) FF_LIBRARY_LOAD(libraryObjectName, , libraryFileName, maxVersion, ##__VA_ARGS__)
+1 -1
View File
@@ -18,7 +18,7 @@ typedef union FFvariant {
}; };
} FFvariant; } FFvariant;
#define FF_VARIANT_NULL ((FFvariant) { .strValue = NULL }) #define FF_VARIANT_NULL ((FFvariant) { .strValue = nullptr })
FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type); FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type);
FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type); FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type);
+1 -1
View File
@@ -84,7 +84,7 @@ static_assert(sizeof(FFSmbiosHeader) == 4, "FFSmbiosHeader should be 4 bytes");
static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) { static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) {
if (index == 0 || *start == '\0') { if (index == 0 || *start == '\0') {
return NULL; return nullptr;
} }
while (--index) { while (--index) {
start += strlen(start) + 1; start += strlen(start) + 1;
+5 -5
View File
@@ -18,7 +18,7 @@ __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch);
#define FF_STR(x) FF_STR_INDIR(x) #define FF_STR(x) FF_STR_INDIR(x)
static inline bool ffStrSet(const char* str) { static inline bool ffStrSet(const char* str) {
if (str == NULL) { if (str == nullptr) {
return false; return false;
} }
@@ -69,17 +69,17 @@ static inline bool ffStrEquals(const char* str, const char* compareTo) {
FF_A_ALWAYS_INLINE FF_A_ALWAYS_INLINE
static inline bool ffStrContains(const char* str, const char* compareTo) { static inline bool ffStrContains(const char* str, const char* compareTo) {
return strstr(str, compareTo) != NULL; return strstr(str, compareTo) != nullptr;
} }
FF_A_ALWAYS_INLINE FF_A_ALWAYS_INLINE
static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) { static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) {
return strcasestr(str, compareTo) != NULL; return strcasestr(str, compareTo) != nullptr;
} }
FF_A_ALWAYS_INLINE FF_A_ALWAYS_INLINE
static inline bool ffStrContainsC(const char* str, char compareTo) { static inline bool ffStrContainsC(const char* str, char compareTo) {
return strchr(str, compareTo) != NULL; return strchr(str, compareTo) != nullptr;
} }
FF_A_ALWAYS_INLINE FF_A_ALWAYS_INLINE
@@ -118,7 +118,7 @@ static inline int8_t ffHexCharToInt(char c) {
// Copies at most (dstBufSiz - 1) bytes from src to dst; dst is always null-terminated // Copies at most (dstBufSiz - 1) bytes from src to dst; dst is always null-terminated
static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) { static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) {
if (__builtin_expect(dst == NULL, false) || dstBufSiz == 0) { if (__builtin_expect(dst == nullptr, false) || dstBufSiz == 0) {
return dst; return dst;
} }
+7 -7
View File
@@ -18,7 +18,7 @@ static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
ReleaseSRWLockExclusive(mutex); ReleaseSRWLockExclusive(mutex);
} }
static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) { static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) {
return (FFThreadType) _beginthreadex(NULL, 0, func, data, 0, NULL); return (FFThreadType) _beginthreadex(nullptr, 0, func, data, 0, nullptr);
} }
#define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \
static __stdcall unsigned fn##ThreadMain(void* data) { \ static __stdcall unsigned fn##ThreadMain(void* data) { \
@@ -34,7 +34,7 @@ static inline void ffThreadDetach(FFThreadType thread) {
NtClose(thread); NtClose(thread);
} }
static inline bool ffThreadJoin(FFThreadType thread, uint32_t timeout) { static inline bool ffThreadJoin(FFThreadType thread, uint32_t timeout) {
if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? NULL : &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 }) != STATUS_WAIT_0) { if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? nullptr : &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 }) != STATUS_WAIT_0) {
TerminateThread(thread, (DWORD) -1); TerminateThread(thread, (DWORD) -1);
NtClose(thread); NtClose(thread);
return false; return false;
@@ -74,18 +74,18 @@ static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
#endif #endif
static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) { static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) {
FFThreadType newThread = 0; FFThreadType newThread = 0;
pthread_create(&newThread, NULL, func, data); pthread_create(&newThread, nullptr, func, data);
return newThread; return newThread;
} }
#define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \
static void* fn##ThreadMain(void* data) { \ static void* fn##ThreadMain(void* data) { \
fn((paramType) data); \ fn((paramType) data); \
return NULL; \ return nullptr; \
} }
#define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) \ #define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) \
static void* fn##ThreadMain() { \ static void* fn##ThreadMain() { \
fn(); \ fn(); \
return NULL; \ return nullptr; \
} }
static inline void ffThreadDetach(FFThreadType thread) { static inline void ffThreadDetach(FFThreadType thread) {
pthread_detach(thread); pthread_detach(thread);
@@ -97,7 +97,7 @@ static inline bool ffThreadJoin(FFThreadType thread, FF_A_UNUSED uint32_t timeou
if (clock_gettime(CLOCK_REALTIME, &ts) == 0) { if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {
ts.tv_sec += timeout / 1000; ts.tv_sec += timeout / 1000;
ts.tv_nsec += (timeout % 1000) * 1000000; ts.tv_nsec += (timeout % 1000) * 1000000;
if (pthread_timedjoin_np(thread, NULL, &ts) != 0) { if (pthread_timedjoin_np(thread, nullptr, &ts) != 0) {
pthread_kill(thread, SIGTERM); pthread_kill(thread, SIGTERM);
return false; return false;
} }
@@ -105,7 +105,7 @@ static inline bool ffThreadJoin(FFThreadType thread, FF_A_UNUSED uint32_t timeou
} }
} }
#endif #endif
pthread_join(thread, NULL); pthread_join(thread, nullptr);
return true; return true;
} }
static inline uintptr_t ffThreadGetCurrentId() { static inline uintptr_t ffThreadGetCurrentId() {
+1 -1
View File
@@ -58,7 +58,7 @@ static inline bool ffTimeSleep(uint32_t msec) {
interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals
return NT_SUCCESS(NtDelayExecution(TRUE, &interval)); return NT_SUCCESS(NtDelayExecution(TRUE, &interval));
#else #else
return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, NULL) == 0; return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, nullptr) == 0;
#endif #endif
} }
+5 -5
View File
@@ -21,14 +21,14 @@ static const char* doInitCom() {
return "RoInitialize() failed: unexpected error"; return "RoInitialize() failed: unexpected error";
case RPC_E_CHANGED_MODE: case RPC_E_CHANGED_MODE:
// COM was already initialized with a different concurrency model // COM was already initialized with a different concurrency model
return NULL; return nullptr;
default: default:
return "RoInitialize() failed: unknown error"; return "RoInitialize() failed: unknown error";
} }
} }
atexit(RoUninitializeWrap); atexit(RoUninitializeWrap);
return NULL; return nullptr;
} }
#else #else
#include <combaseapi.h> #include <combaseapi.h>
@@ -38,7 +38,7 @@ static void CoUninitializeWrap(void) {
} }
static const char* doInitCom() { static const char* doInitCom() {
HRESULT res = CoInitializeEx(NULL, COINIT_MULTITHREADED); HRESULT res = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (FAILED(res)) { if (FAILED(res)) {
switch (res) { switch (res) {
case E_INVALIDARG: case E_INVALIDARG:
@@ -47,14 +47,14 @@ static const char* doInitCom() {
return "CoInitializeEx() failed: out of memory"; return "CoInitializeEx() failed: out of memory";
case RPC_E_CHANGED_MODE: case RPC_E_CHANGED_MODE:
// COM was already initialized with a different concurrency model // COM was already initialized with a different concurrency model
return NULL; return nullptr;
default: default:
return "CoInitializeEx() failed: unknown error"; return "CoInitializeEx() failed: unknown error";
} }
} }
atexit(CoUninitializeWrap); atexit(CoUninitializeWrap);
return NULL; return nullptr;
} }
#endif #endif
+1 -1
View File
@@ -16,7 +16,7 @@ static inline void ffReleaseComObject(void* ppUnknown) {
#else #else
pUnknown->lpVtbl->Release(pUnknown); pUnknown->lpVtbl->Release(pUnknown);
#endif #endif
*(IUnknown**) ppUnknown = NULL; *(IUnknown**) ppUnknown = nullptr;
} }
} }
+4 -4
View File
@@ -7,7 +7,7 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) {
ssize_t pos = -1; ssize_t pos = -1;
int c; int c;
if (lineptr == NULL || stream == NULL || n == NULL) { if (lineptr == nullptr || stream == nullptr || n == nullptr) {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
@@ -19,9 +19,9 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) {
goto exit; goto exit;
} }
if (*lineptr == NULL) { if (*lineptr == nullptr) {
*lineptr = malloc(128); *lineptr = malloc(128);
if (*lineptr == NULL) { if (*lineptr == nullptr) {
goto exit; goto exit;
} }
*n = 128; *n = 128;
@@ -35,7 +35,7 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) {
new_size = 128; new_size = 128;
} }
char* new_ptr = realloc(*lineptr, new_size); char* new_ptr = realloc(*lineptr, new_size);
if (new_ptr == NULL) { if (new_ptr == nullptr) {
pos = -1; pos = -1;
goto exit; goto exit;
} }
+8 -8
View File
@@ -42,7 +42,7 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) {
NTSTATUS status = RtlOpenCurrentUser(KEY_READ, &result); NTSTATUS status = RtlOpenCurrentUser(KEY_READ, &result);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("RtlOpenCurrentUser() failed: %s", ffDebugNtStatus(status)); FF_DEBUG("RtlOpenCurrentUser() failed: %s", ffDebugNtStatus(status));
return NULL; return nullptr;
} }
break; break;
} }
@@ -51,13 +51,13 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) {
UNICODE_STRING path = RTL_CONSTANT_STRING(L"\\Registry\\Machine"); UNICODE_STRING path = RTL_CONSTANT_STRING(L"\\Registry\\Machine");
NTSTATUS status = NtOpenKey(&result, KEY_READ, &(OBJECT_ATTRIBUTES) { NTSTATUS status = NtOpenKey(&result, KEY_READ, &(OBJECT_ATTRIBUTES) {
.Length = sizeof(OBJECT_ATTRIBUTES), .Length = sizeof(OBJECT_ATTRIBUTES),
.RootDirectory = NULL, .RootDirectory = nullptr,
.ObjectName = &path, .ObjectName = &path,
.Attributes = OBJ_CASE_INSENSITIVE, .Attributes = OBJ_CASE_INSENSITIVE,
}); });
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("NtOpenKey(%ls) failed: %s (0x%08lx)", path.Buffer, ffDebugNtStatus(status), status); FF_DEBUG("NtOpenKey(%ls) failed: %s (0x%08lx)", path.Buffer, ffDebugNtStatus(status), status);
return NULL; return nullptr;
} }
break; break;
} }
@@ -65,7 +65,7 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) {
// Unsupported // Unsupported
FF_DEBUG("Unsupported root key: %p", hKey); FF_DEBUG("Unsupported root key: %p", hKey);
assert(false); assert(false);
return NULL; return nullptr;
} }
hRootKeys[(uintptr_t) hKey - (uintptr_t) HKEY_CLASSES_ROOT] = result; hRootKeys[(uintptr_t) hKey - (uintptr_t) HKEY_CLASSES_ROOT] = result;
FF_DEBUG("Opened root key %s -> %p", hKey2Str(result), result); FF_DEBUG("Opened root key %s -> %p", hKey2Str(result), result);
@@ -241,7 +241,7 @@ bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) {
}; };
alignas(KEY_VALUE_PARTIAL_INFORMATION) uint8_t staticBuffer[128 + sizeof(KEY_VALUE_PARTIAL_INFORMATION)]; alignas(KEY_VALUE_PARTIAL_INFORMATION) uint8_t staticBuffer[128 + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
FF_AUTO_FREE uint8_t* dynamicBuffer = NULL; FF_AUTO_FREE uint8_t* dynamicBuffer = nullptr;
KEY_VALUE_PARTIAL_INFORMATION* buffer = (KEY_VALUE_PARTIAL_INFORMATION*) &staticBuffer; KEY_VALUE_PARTIAL_INFORMATION* buffer = (KEY_VALUE_PARTIAL_INFORMATION*) &staticBuffer;
DWORD bufSize = sizeof(staticBuffer); DWORD bufSize = sizeof(staticBuffer);
@@ -287,9 +287,9 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs
for (uint32_t i = 0; i < argc; ++i) { for (uint32_t i = 0; i < argc; ++i) {
if (__builtin_expect(!argv[i].value, false)) { if (__builtin_expect(!argv[i].value, false)) {
FF_DEBUG("ffRegReadValues(argv[%u].value) is NULL", (unsigned) i); FF_DEBUG("ffRegReadValues(argv[%u].value) is nullptr", (unsigned) i);
if (error) { if (error) {
ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is NULL", (unsigned) i); ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is nullptr", (unsigned) i);
} }
return false; return false;
} }
@@ -307,7 +307,7 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs
bufferSize = 512; bufferSize = 512;
} }
FF_AUTO_FREE uint8_t* buffer = NULL; FF_AUTO_FREE uint8_t* buffer = nullptr;
while (true) { while (true) {
buffer = (uint8_t*) realloc(buffer, bufferSize); buffer = (uint8_t*) realloc(buffer, bufferSize);
+2 -2
View File
@@ -9,7 +9,7 @@ void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) {
} }
ULONG size_needed = 0; ULONG size_needed = 0;
NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); NTSTATUS status = RtlUnicodeToUTF8N(nullptr, 0, &size_needed, source, length * sizeof(wchar_t));
if (size_needed == 0) { if (size_needed == 0) {
ffStrbufSetF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); ffStrbufSetF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status);
@@ -29,7 +29,7 @@ void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source)
} }
ULONG size_needed = 0; ULONG size_needed = 0;
NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); NTSTATUS status = RtlUnicodeToUTF8N(nullptr, 0, &size_needed, source, length * sizeof(wchar_t));
if (size_needed == 0) { if (size_needed == 0) {
ffStrbufAppendF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); ffStrbufAppendF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status);
+9 -9
View File
@@ -17,11 +17,11 @@ static inline void wrapYyjsonFree(yyjson_doc** doc) {
static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) { static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) {
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL })) { if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, nullptr })) {
return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed";
} }
yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, nullptr, nullptr);
if (!doc) { if (!doc) {
return "Failed to parse battery info"; return "Failed to parse battery info";
} }
@@ -66,7 +66,7 @@ static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) {
battery->temperature = yyjson_get_num(yyjson_obj_get(root, "temperature")); battery->temperature = yyjson_get_num(yyjson_obj_get(root, "temperature"));
} }
return NULL; return nullptr;
} }
static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) {
@@ -74,8 +74,8 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) {
if (ffProcessAppendStdOut(&buf, (char*[]) { if (ffProcessAppendStdOut(&buf, (char*[]) {
"/system/bin/dumpsys", "/system/bin/dumpsys",
"battery", "battery",
NULL, nullptr,
}) != NULL || }) != nullptr ||
buf.length == 0) { buf.length == 0) {
return "Executing `/system/bin/dumpsys battery` failed"; // Only works in `adb shell`, or when rooted return "Executing `/system/bin/dumpsys battery` failed"; // Only works in `adb shell`, or when rooted
} }
@@ -88,7 +88,7 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) {
FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate();
if (!ffParsePropLines(start, "present: ", &temp) || !ffStrbufEqualS(&temp, "true")) { if (!ffParsePropLines(start, "present: ", &temp) || !ffStrbufEqualS(&temp, "true")) {
return NULL; return nullptr;
} }
ffStrbufClear(&temp); ffStrbufClear(&temp);
@@ -148,13 +148,13 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) {
ffParsePropLines(start, "technology: ", &battery->technology); ffParsePropLines(start, "technology: ", &battery->technology);
return NULL; return nullptr;
} }
const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
const char* error = parseTermuxApi(options, results); const char* error = parseTermuxApi(options, results);
if (error && parseDumpsys(options, results) == NULL) { if (error && parseDumpsys(options, results) == nullptr) {
return NULL; return nullptr;
} }
return error; return error;
} }
+10 -10
View File
@@ -15,18 +15,18 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
io_registry_entry_t registryEntry; io_registry_entry_t registryEntry;
while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryBattery = registryEntry; FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryBattery = registryEntry;
FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef properties = NULL; FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef properties = nullptr;
if (IORegistryEntryCreateCFProperties(entryBattery, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { if (IORegistryEntryCreateCFProperties(entryBattery, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) {
continue; continue;
} }
int currentCapacity, maxCapacity; int currentCapacity, maxCapacity;
if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != NULL || maxCapacity <= 0) { if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != nullptr || maxCapacity <= 0) {
continue; continue;
} }
if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), &currentCapacity) != NULL || currentCapacity <= 0) { if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), &currentCapacity) != nullptr || currentCapacity <= 0) {
continue; continue;
} }
@@ -63,7 +63,7 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
battery->cycleCount = cycleCount < 0 ? 0 : (uint32_t) cycleCount; battery->cycleCount = cycleCount < 0 ? 0 : (uint32_t) cycleCount;
battery->timeRemaining = -1; battery->timeRemaining = -1;
if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == NULL) { if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == nullptr) {
if (boolValue) { if (boolValue) {
battery->status |= FF_BATTERY_STATUS_AC_CONNECTED; battery->status |= FF_BATTERY_STATUS_AC_CONNECTED;
} else { } else {
@@ -76,24 +76,24 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
} }
} }
} }
if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == NULL && boolValue) { if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == nullptr && boolValue) {
battery->status |= FF_BATTERY_STATUS_CHARGING; battery->status |= FF_BATTERY_STATUS_CHARGING;
} }
if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == NULL && boolValue) { if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == nullptr && boolValue) {
battery->status |= FF_BATTERY_STATUS_CRITICAL; battery->status |= FF_BATTERY_STATUS_CRITICAL;
} }
int sbdsManufactureDate = 0; int sbdsManufactureDate = 0;
if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == NULL) { if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == nullptr) {
int day = sbdsManufactureDate & 0b11111; int day = sbdsManufactureDate & 0b11111;
int month = (sbdsManufactureDate >> 5) & 0b1111; int month = (sbdsManufactureDate >> 5) & 0b1111;
int year = (sbdsManufactureDate >> 9) + 1800; int year = (sbdsManufactureDate >> 9) + 1800;
ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", year, month, day); ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", year, month, day);
} else { } else {
CFDictionaryRef batteryData; CFDictionaryRef batteryData;
if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == NULL) { if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == nullptr) {
char manufactureDate[sizeof(uint64_t)]; char manufactureDate[sizeof(uint64_t)];
if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == NULL) { if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == nullptr) {
// https://github.com/AsahiLinux/linux/blob/b5c05cbffb0488c7618106926d522cc3b43d93d5/drivers/power/supply/macsmc_power.c#L410-L419 // https://github.com/AsahiLinux/linux/blob/b5c05cbffb0488c7618106926d522cc3b43d93d5/drivers/power/supply/macsmc_power.c#L410-L419
int year = (manufactureDate[0] - '0') * 10 + (manufactureDate[1] - '0') + 2000 - 8; int year = (manufactureDate[0] - '0') * 10 + (manufactureDate[1] - '0') + 2000 - 8;
int month = (manufactureDate[2] - '0') * 10 + (manufactureDate[3] - '0'); int month = (manufactureDate[2] - '0') * 10 + (manufactureDate[3] - '0');
@@ -113,5 +113,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
} }
} }
return NULL; return nullptr;
} }
+2 -2
View File
@@ -18,7 +18,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} }
if (units == 0) { if (units == 0) {
return NULL; return nullptr;
} }
FF_AUTO_CLOSE_FD int acpifd = open("/dev/acpi", O_RDONLY | O_CLOEXEC); FF_AUTO_CLOSE_FD int acpifd = open("/dev/acpi", O_RDONLY | O_CLOEXEC);
@@ -86,5 +86,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} }
#endif #endif
} }
return NULL; return nullptr;
} }
+2 -2
View File
@@ -50,7 +50,7 @@ const char* parseBattery(int dfd, const char* battId, FFlist* results) {
battery->status |= FF_BATTERY_STATUS_AC_CONNECTED; battery->status |= FF_BATTERY_STATUS_AC_CONNECTED;
} }
return NULL; return nullptr;
} }
const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* results) { const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* results) {
@@ -67,5 +67,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
parseBattery(dirfd(dir), entry->d_name, results); parseBattery(dirfd(dir), entry->d_name, results);
} }
return NULL; return nullptr;
} }
+4 -4
View File
@@ -175,14 +175,14 @@ static bool parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFl
const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/");
if (dirp == NULL) { if (dirp == nullptr) {
return "opendir(\"/sys/class/power_supply/\") == NULL"; return "opendir(\"/sys/class/power_supply/\") == nullptr";
} }
bool acConnected = false; bool acConnected = false;
struct dirent* entry; struct dirent* entry;
while ((entry = readdir(dirp)) != NULL) { while ((entry = readdir(dirp)) != nullptr) {
if (entry->d_name[0] == '.') { if (entry->d_name[0] == '.') {
continue; continue;
} }
@@ -199,5 +199,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
} }
} }
return NULL; return nullptr;
} }
+6 -6
View File
@@ -20,7 +20,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed";
} }
prop_dictionary_t root = NULL; prop_dictionary_t root = nullptr;
if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) { if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) {
return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed"; return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed";
} }
@@ -35,7 +35,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} }
prop_object_iterator_t itKey = prop_dictionary_iterator(root); prop_object_iterator_t itKey = prop_dictionary_iterator(root);
for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != NULL;) { for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != nullptr;) {
if (!ffStrStartsWith(prop_dictionary_keysym_value(key), "acpibat")) { if (!ffStrStartsWith(prop_dictionary_keysym_value(key), "acpibat")) {
continue; continue;
} }
@@ -44,12 +44,12 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
uint32_t max = 0, curr = 0, dischargeRate = 0; uint32_t max = 0, curr = 0, dischargeRate = 0;
bool charging = false, critical = false; bool charging = false, critical = false;
prop_object_iterator_t iter = prop_array_iterator(bat); prop_object_iterator_t iter = prop_array_iterator(bat);
for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != NULL;) { for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != nullptr;) {
if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) { if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) {
continue; continue;
} }
const char* desc = NULL; const char* desc = nullptr;
if (!prop_dictionary_get_string(dict, "description", &desc)) { if (!prop_dictionary_get_string(dict, "description", &desc)) {
continue; continue;
} }
@@ -64,7 +64,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} else if (ffStrEquals(desc, "charge")) { } else if (ffStrEquals(desc, "charge")) {
prop_dictionary_get_uint32(dict, "max-value", &max); prop_dictionary_get_uint32(dict, "max-value", &max);
prop_dictionary_get_uint32(dict, "cur-value", &curr); prop_dictionary_get_uint32(dict, "cur-value", &curr);
const char* state = NULL; const char* state = nullptr;
if (prop_dictionary_get_string(dict, "state", &state) && ffStrEquals(state, "critical")) { if (prop_dictionary_get_string(dict, "state", &state) && ffStrEquals(state, "critical")) {
critical = true; critical = true;
} }
@@ -105,5 +105,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
prop_object_iterator_release(itKey); prop_object_iterator_release(itKey);
prop_object_release(root); prop_object_release(root);
return NULL; return nullptr;
} }
+2 -2
View File
@@ -20,7 +20,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} }
if (info.battery_state == APM_BATTERY_ABSENT) { if (info.battery_state == APM_BATTERY_ABSENT) {
return NULL; return nullptr;
} }
FFBatteryResult* battery = FF_LIST_ADD(FFBatteryResult, *result); FFBatteryResult* battery = FF_LIST_ADD(FFBatteryResult, *result);
@@ -56,5 +56,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul
} }
} }
return NULL; return nullptr;
} }
+22 -22
View File
@@ -51,21 +51,21 @@ static FFBatteryWmiEntry* getBatteryEntry(FFlist* entries, FFlist* results, ULON
} }
static const char* queryWmiAllData(const GUID* guid, const char* guidStr, PWNODE_ALL_DATA* pAllData, ULONG* pBufferSize) { static const char* queryWmiAllData(const GUID* guid, const char* guidStr, PWNODE_ALL_DATA* pAllData, ULONG* pBufferSize) {
FF_AUTO_CLOSE_WMI_BLOCK HANDLE hBlock = NULL; FF_AUTO_CLOSE_WMI_BLOCK HANDLE hBlock = nullptr;
ULONG status = WmiOpenBlock(guid, WMIGUID_QUERY, &hBlock); ULONG status = WmiOpenBlock(guid, WMIGUID_QUERY, &hBlock);
if (status != ERROR_SUCCESS) { if (status != ERROR_SUCCESS) {
FF_DEBUG("WMI: WmiOpenBlock() failed for %s: %s", guidStr, ffDebugWin32Error(status)); FF_DEBUG("WMI: WmiOpenBlock() failed for %s: %s", guidStr, ffDebugWin32Error(status));
return "WmiOpenBlock() failed"; return "WmiOpenBlock() failed";
} }
status = WmiQueryAllDataW(hBlock, pBufferSize, NULL); status = WmiQueryAllDataW(hBlock, pBufferSize, nullptr);
if (status != ERROR_SUCCESS && status != ERROR_INSUFFICIENT_BUFFER) { if (status != ERROR_SUCCESS && status != ERROR_INSUFFICIENT_BUFFER) {
FF_DEBUG("WMI: first WmiQueryAllDataW() failed: %s", ffDebugWin32Error(status)); FF_DEBUG("WMI: first WmiQueryAllDataW() failed: %s", ffDebugWin32Error(status));
return "WmiQueryAllDataW(NULL) failed"; return "WmiQueryAllDataW(nullptr) failed";
} }
if (*pBufferSize == 0) { if (*pBufferSize == 0) {
return "WmiQueryAllDataW(NULL) returned no data"; return "WmiQueryAllDataW(nullptr) returned no data";
} }
if (*pBufferSize < sizeof(WNODE_ALL_DATA)) { if (*pBufferSize < sizeof(WNODE_ALL_DATA)) {
@@ -79,11 +79,11 @@ static const char* queryWmiAllData(const GUID* guid, const char* guidStr, PWNODE
if (status != ERROR_SUCCESS) { if (status != ERROR_SUCCESS) {
FF_DEBUG("WMI: second WmiQueryAllDataW failed: %s", ffDebugWin32Error(status)); FF_DEBUG("WMI: second WmiQueryAllDataW failed: %s", ffDebugWin32Error(status));
free(*pAllData); free(*pAllData);
*pAllData = NULL; *pAllData = nullptr;
return "WmiQueryAllDataW(*pAllData) failed"; return "WmiQueryAllDataW(*pAllData) failed";
} }
return NULL; return nullptr;
} }
static bool getInstanceData(const PWNODE_ALL_DATA allData, ULONG bufferSize, ULONG index, const uint8_t** instanceData, ULONG* instanceLength) { static bool getInstanceData(const PWNODE_ALL_DATA allData, ULONG bufferSize, ULONG index, const uint8_t** instanceData, ULONG* instanceLength) {
@@ -109,7 +109,7 @@ static bool getInstanceData(const PWNODE_ALL_DATA allData, ULONG bufferSize, ULO
static void detectStaticData(FFlist* entries, FFlist* results) { static void detectStaticData(FFlist* entries, FFlist* results) {
FF_DEBUG("detectStaticData"); FF_DEBUG("detectStaticData");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_STATIC_DATA_WMI_GUID, "BATTERY_STATIC_DATA_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_STATIC_DATA_WMI_GUID, "BATTERY_STATIC_DATA_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -117,7 +117,7 @@ static void detectStaticData(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < offsetof(BATTERY_WMI_STATIC_DATA, Strings)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < offsetof(BATTERY_WMI_STATIC_DATA, Strings)) {
continue; continue;
@@ -187,7 +187,7 @@ static void detectStaticData(FFlist* entries, FFlist* results) {
static void detectStatus(FFlist* entries, FFlist* results) { static void detectStatus(FFlist* entries, FFlist* results) {
FF_DEBUG("detectStatus"); FF_DEBUG("detectStatus");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_STATUS_WMI_GUID, "BATTERY_STATUS_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_STATUS_WMI_GUID, "BATTERY_STATUS_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -195,7 +195,7 @@ static void detectStatus(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_STATUS)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_STATUS)) {
continue; continue;
@@ -225,7 +225,7 @@ static void detectStatus(FFlist* entries, FFlist* results) {
static void detectRuntime(FFlist* entries, FFlist* results) { static void detectRuntime(FFlist* entries, FFlist* results) {
FF_DEBUG("detectRuntime"); FF_DEBUG("detectRuntime");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_RUNTIME_WMI_GUID, "BATTERY_RUNTIME_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_RUNTIME_WMI_GUID, "BATTERY_RUNTIME_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -233,7 +233,7 @@ static void detectRuntime(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_RUNTIME)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_RUNTIME)) {
continue; continue;
@@ -249,7 +249,7 @@ static void detectRuntime(FFlist* entries, FFlist* results) {
static void detectFullChargedCapacity(FFlist* entries, FFlist* results) { static void detectFullChargedCapacity(FFlist* entries, FFlist* results) {
FF_DEBUG("detectFullChargedCapacity"); FF_DEBUG("detectFullChargedCapacity");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID, "BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID, "BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -257,7 +257,7 @@ static void detectFullChargedCapacity(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_FULL_CHARGED_CAPACITY)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_FULL_CHARGED_CAPACITY)) {
continue; continue;
@@ -275,7 +275,7 @@ static void detectFullChargedCapacity(FFlist* entries, FFlist* results) {
static void detectCycleCount(FFlist* entries, FFlist* results) { static void detectCycleCount(FFlist* entries, FFlist* results) {
FF_DEBUG("detectCycleCount"); FF_DEBUG("detectCycleCount");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_CYCLE_COUNT_WMI_GUID, "BATTERY_CYCLE_COUNT_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_CYCLE_COUNT_WMI_GUID, "BATTERY_CYCLE_COUNT_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -283,7 +283,7 @@ static void detectCycleCount(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_CYCLE_COUNT)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_CYCLE_COUNT)) {
continue; continue;
@@ -296,7 +296,7 @@ static void detectCycleCount(FFlist* entries, FFlist* results) {
static void detectTemperature(FFlist* entries, FFlist* results) { static void detectTemperature(FFlist* entries, FFlist* results) {
FF_DEBUG("detectTemperature"); FF_DEBUG("detectTemperature");
FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr;
ULONG bufferSize = 0; ULONG bufferSize = 0;
const char* error = queryWmiAllData(&BATTERY_TEMPERATURE_WMI_GUID, "BATTERY_TEMPERATURE_WMI_GUID", &allData, &bufferSize); const char* error = queryWmiAllData(&BATTERY_TEMPERATURE_WMI_GUID, "BATTERY_TEMPERATURE_WMI_GUID", &allData, &bufferSize);
if (error) { if (error) {
@@ -304,7 +304,7 @@ static void detectTemperature(FFlist* entries, FFlist* results) {
} }
for (ULONG i = 0; i < allData->InstanceCount; ++i) { for (ULONG i = 0; i < allData->InstanceCount; ++i) {
const uint8_t* instanceData = NULL; const uint8_t* instanceData = nullptr;
ULONG instanceLength = 0; ULONG instanceLength = 0;
if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_TEMPERATURE)) { if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_TEMPERATURE)) {
continue; continue;
@@ -319,7 +319,7 @@ static const char* detectWithNtApi(FFBatteryResult* battery) {
// Reports summary battery information, not per battery // Reports summary battery information, not per battery
FF_DEBUG("NtApi: start detection"); FF_DEBUG("NtApi: start detection");
SYSTEM_BATTERY_STATE info; SYSTEM_BATTERY_STATE info;
NTSTATUS status = NtPowerInformation(SystemBatteryState, NULL, 0, &info, sizeof(info)); NTSTATUS status = NtPowerInformation(SystemBatteryState, nullptr, 0, &info, sizeof(info));
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
FF_DEBUG("NtApi: NtPowerInformation(SystemBatteryState) failed: %s", ffDebugNtStatus(status)); FF_DEBUG("NtApi: NtPowerInformation(SystemBatteryState) failed: %s", ffDebugNtStatus(status));
return "NtPowerInformation(SystemBatteryState) failed"; return "NtPowerInformation(SystemBatteryState) failed";
@@ -346,7 +346,7 @@ static const char* detectWithNtApi(FFBatteryResult* battery) {
battery->status |= FF_BATTERY_STATUS_CRITICAL; battery->status |= FF_BATTERY_STATUS_CRITICAL;
} }
battery->timeRemaining = info.EstimatedTime == BATTERY_UNKNOWN_TIME ? -1 : (int32_t) info.EstimatedTime; battery->timeRemaining = info.EstimatedTime == BATTERY_UNKNOWN_TIME ? -1 : (int32_t) info.EstimatedTime;
return NULL; return nullptr;
} }
const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
@@ -355,7 +355,7 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
FF_LIST_AUTO_DESTROY entries = ffListCreate(); FF_LIST_AUTO_DESTROY entries = ffListCreate();
detectStaticData(&entries, results); detectStaticData(&entries, results);
if (results->length == 0) { if (results->length == 0) {
return NULL; return nullptr;
} else if (results->length == 1) { } else if (results->length == 1) {
// Fast path for single battery // Fast path for single battery
detectWithNtApi(FF_LIST_FIRST(FFBatteryWmiEntry, entries)->result); detectWithNtApi(FF_LIST_FIRST(FFBatteryWmiEntry, entries)->result);
@@ -380,5 +380,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) {
} }
FF_DEBUG("WMI: finished detection, total results=%u", results->length); FF_DEBUG("WMI: finished detection, total results=%u", results->length);
return NULL; return nullptr;
} }
+1 -1
View File
@@ -12,5 +12,5 @@ const char* ffDetectBios(FFBiosResult* bios) {
ffStrbufSetStatic(&bios->type, "Bootloader"); ffStrbufSetStatic(&bios->type, "Bootloader");
return NULL; return nullptr;
} }
+2 -2
View File
@@ -13,7 +13,7 @@ const char* ffDetectBios(FFBiosResult* bios) {
return "IODeviceTree:/rom not found"; return "IODeviceTree:/rom not found";
} }
FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef deviceRomProps = NULL; FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef deviceRomProps = nullptr;
if (IORegistryEntryCreateCFProperties(deviceRom, &deviceRomProps, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { if (IORegistryEntryCreateCFProperties(deviceRom, &deviceRomProps, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) {
return "IORegistryEntryCreateCFProperties(deviceRom) failed"; return "IORegistryEntryCreateCFProperties(deviceRom) failed";
} }
@@ -54,5 +54,5 @@ const char* ffDetectBios(FFBiosResult* bios) {
} }
#endif #endif
return NULL; return nullptr;
} }
+1 -1
View File
@@ -27,5 +27,5 @@ const char* ffDetectBios(FFBiosResult* result) {
: "BIOS"); : "BIOS");
} }
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -17,5 +17,5 @@ const char* ffDetectBios(FFBiosResult* bios) {
} else { } else {
ffStrbufSetStatic(&bios->type, "BIOS"); ffStrbufSetStatic(&bios->type, "BIOS");
} }
return NULL; return nullptr;
} }
+5 -5
View File
@@ -4,17 +4,17 @@
#include "common/io.h" #include "common/io.h"
const char* ffDetectBios(FFBiosResult* bios) { const char* ffDetectBios(FFBiosResult* bios) {
if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == NULL) { if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == nullptr) {
ffCleanUpSmbiosValue(&bios->date); ffCleanUpSmbiosValue(&bios->date);
} }
if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == NULL) { if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == nullptr) {
ffCleanUpSmbiosValue(&bios->version); ffCleanUpSmbiosValue(&bios->version);
} }
if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == NULL) { if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == nullptr) {
ffCleanUpSmbiosValue(&bios->vendor); ffCleanUpSmbiosValue(&bios->vendor);
} }
if (ffSysctlGetString("machdep.bootmethod", &bios->type) != NULL) { if (ffSysctlGetString("machdep.bootmethod", &bios->type) != nullptr) {
ffStrbufSetStatic(&bios->type, ffPathExists("/dev/efi", FF_PATHTYPE_FILE) ? "UEFI" : "BIOS"); ffStrbufSetStatic(&bios->type, ffPathExists("/dev/efi", FF_PATHTYPE_FILE) ? "UEFI" : "BIOS");
} }
return NULL; return nullptr;
} }
+3 -3
View File
@@ -71,7 +71,7 @@ const char* ffDetectBios(FFBiosResult* bios) {
// Same as GetFirmwareType, but support (?) Windows 7 // Same as GetFirmwareType, but support (?) Windows 7
// https://ntdoc.m417z.com/system_information_class // https://ntdoc.m417z.com/system_information_class
SYSTEM_BOOT_ENVIRONMENT_INFORMATION sbei; SYSTEM_BOOT_ENVIRONMENT_INFORMATION sbei;
if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), NULL))) { if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), nullptr))) {
switch (sbei.FirmwareType) { switch (sbei.FirmwareType) {
case FirmwareTypeBios: case FirmwareTypeBios:
ffStrbufSetStatic(&bios->type, "BIOS"); ffStrbufSetStatic(&bios->type, "BIOS");
@@ -86,7 +86,7 @@ const char* ffDetectBios(FFBiosResult* bios) {
#elif __sun #elif __sun
di_node_t rootNode = di_init("/", DINFOPROP); di_node_t rootNode = di_init("/", DINFOPROP);
if (rootNode != DI_NODE_NIL) { if (rootNode != DI_NODE_NIL) {
char* efiVersion = NULL; char* efiVersion = nullptr;
if (di_prop_lookup_strings(DDI_DEV_T_ANY, rootNode, "efi-version", &efiVersion) > 0) { if (di_prop_lookup_strings(DDI_DEV_T_ANY, rootNode, "efi-version", &efiVersion) > 0) {
ffStrbufSetStatic(&bios->type, "UEFI"); ffStrbufSetStatic(&bios->type, "UEFI");
} else { } else {
@@ -103,5 +103,5 @@ const char* ffDetectBios(FFBiosResult* bios) {
ffStrbufSetStatic(&bios->type, deviceEfi ? "UEFI" : "BIOS"); ffStrbufSetStatic(&bios->type, deviceEfi ? "UEFI" : "BIOS");
#endif #endif
return NULL; return nullptr;
} }
+1 -1
View File
@@ -108,5 +108,5 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF
} }
} }
return NULL; return nullptr;
} }
+2 -2
View File
@@ -12,7 +12,7 @@ static int enumDev(FF_A_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist*
dev->devname dev->devname
#endif #endif
); );
ffStrbufInitS(&device->address, bt_ntoa(&dev->bdaddr, NULL)); ffStrbufInitS(&device->address, bt_ntoa(&dev->bdaddr, nullptr));
ffStrbufUpperCase(&device->address); ffStrbufUpperCase(&device->address);
ffStrbufInit(&device->type); ffStrbufInit(&device->type);
device->battery = 0; device->battery = 0;
@@ -26,5 +26,5 @@ const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FF_A_UNUS
return "bt_devenum() failed"; return "bt_devenum() failed";
} }
return NULL; return nullptr;
} }
+2 -2
View File
@@ -11,7 +11,7 @@ const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FFlist* d
LocalDevice* dev = LocalDevice::GetLocalDevice(); LocalDevice* dev = LocalDevice::GetLocalDevice();
if (!dev) { if (!dev) {
return NULL; return nullptr;
} }
BString devClass; BString devClass;
@@ -26,5 +26,5 @@ const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FFlist* d
// TODO: more devices? // TODO: more devices?
return NULL; return nullptr;
} }
+10 -10
View File
@@ -124,14 +124,14 @@ static void detectBluetoothProperty(FFDBusData* dbus, DBusMessageIter* iter, FFB
static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter) { static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter) {
if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) {
return NULL; return nullptr;
} }
DBusMessageIter dictIter; DBusMessageIter dictIter;
dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter);
if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_OBJECT_PATH) { if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_OBJECT_PATH) {
return NULL; return nullptr;
} }
const char* objectPath; const char* objectPath;
@@ -139,13 +139,13 @@ static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbu
// We don't want adapter objects // We don't want adapter objects
if (!ffStrContains(objectPath, "/dev_")) { if (!ffStrContains(objectPath, "/dev_")) {
return NULL; return nullptr;
} }
dbus->lib->ffdbus_message_iter_next(&dictIter); dbus->lib->ffdbus_message_iter_next(&dictIter);
if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) { if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) {
return NULL; return nullptr;
} }
DBusMessageIter arrayIter; DBusMessageIter arrayIter;
@@ -202,7 +202,7 @@ static const char* detectBluetooth(FFBluetoothOptions* options, FFlist* devices,
return error; return error;
} }
DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL, NULL); DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", nullptr, nullptr);
if (!managedObjects) { if (!managedObjects) {
return "Failed to call GetManagedObjects"; return "Failed to call GetManagedObjects";
} }
@@ -216,19 +216,19 @@ static const char* detectBluetooth(FFBluetoothOptions* options, FFlist* devices,
detectBluetoothRoot(options, devices, &dbus, &rootIter, connectedCount); detectBluetoothRoot(options, devices, &dbus, &rootIter, connectedCount);
dbus.lib->ffdbus_message_unref(managedObjects); dbus.lib->ffdbus_message_unref(managedObjects);
return NULL; return nullptr;
} }
static uint32_t connectedDevices(void) { static uint32_t connectedDevices(void) {
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth");
if (dirp == NULL) { if (dirp == nullptr) {
return 0; return 0;
} }
uint32_t result = 0; uint32_t result = 0;
struct dirent* entry; struct dirent* entry;
while ((entry = readdir(dirp)) != NULL) { while ((entry = readdir(dirp)) != nullptr) {
if (strchr(entry->d_name, ':') != NULL) { if (strchr(entry->d_name, ':') != nullptr) {
++result; ++result;
} }
} }
@@ -244,7 +244,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF
if (!options->showDisconnected) { if (!options->showDisconnected) {
connectedCount = (int32_t) connectedDevices(); connectedCount = (int32_t) connectedDevices();
if (connectedCount == 0) { if (connectedCount == 0) {
return NULL; return nullptr;
} }
} }
+4 -4
View File
@@ -35,7 +35,7 @@ static const char* ffBluetoothDetectBattery(FFlist* devices) {
} }
if (idListLength == 0) { if (idListLength == 0) {
return NULL; return nullptr;
} }
wchar_t* FF_AUTO_FREE idList = (wchar_t*) malloc((size_t) idListLength * sizeof(wchar_t)); wchar_t* FF_AUTO_FREE idList = (wchar_t*) malloc((size_t) idListLength * sizeof(wchar_t));
@@ -94,7 +94,7 @@ static const char* ffBluetoothDetectBattery(FFlist* devices) {
} }
} }
return NULL; return nullptr;
} }
const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) {
@@ -114,7 +114,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF
&btdi); &btdi);
if (!hFind) { if (!hFind) {
if (GetLastError() == ERROR_NO_MORE_ITEMS) { if (GetLastError() == ERROR_NO_MORE_ITEMS) {
return NULL; return nullptr;
} }
return "BluetoothFindFirstDevice() failed"; return "BluetoothFindFirstDevice() failed";
} }
@@ -219,5 +219,5 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF
ffBluetoothDetectBattery(devices); ffBluetoothDetectBattery(devices);
} }
return NULL; return nullptr;
} }
@@ -21,8 +21,8 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */)
"-xml", "-xml",
"-detailLevel", "-detailLevel",
"basic", "basic",
NULL nullptr
}) != NULL) }) != nullptr)
return "Starting `system_profiler SPBluetoothDataType -xml -detailLevel basic` failed"; return "Starting `system_profiler SPBluetoothDataType -xml -detailLevel basic` failed";
NSArray* arr = [NSPropertyListSerialization propertyListWithData:[NSData dataWithBytes:buffer.chars length:buffer.length] NSArray* arr = [NSPropertyListSerialization propertyListWithData:[NSData dataWithBytes:buffer.chars length:buffer.length]
@@ -65,5 +65,5 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */)
} }
} }
return NULL; return nullptr;
} }
@@ -73,14 +73,14 @@ static const char* detectBluetoothProperty(FFBluetoothRadioResult* device, FFDBu
ffDBusGetBool(dbus, &dictIter, &device->connectable); ffDBusGetBool(dbus, &dictIter, &device->connectable);
} }
return NULL; return nullptr;
} }
static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const char* hciName, FFDBusData* dbus) { static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const char* hciName, FFDBusData* dbus) {
char objPath[300]; char objPath[300];
snprintf(objPath, sizeof(objPath), "/org/bluez/%s", hciName); snprintf(objPath, sizeof(objPath), "/org/bluez/%s", hciName);
DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1", NULL); DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1", nullptr);
if (!properties) { if (!properties) {
return "Failed to call org.freedesktop.DBus.Properties.GetAll"; return "Failed to call org.freedesktop.DBus.Properties.GetAll";
} }
@@ -104,12 +104,12 @@ static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const cha
} while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); } while (dbus->lib->ffdbus_message_iter_next(&arrayIter));
dbus->lib->ffdbus_message_unref(properties); dbus->lib->ffdbus_message_unref(properties);
return NULL; return nullptr;
} }
static const char* detectBluetooth(FFlist* devices) { static const char* detectBluetooth(FFlist* devices) {
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth");
if (dirp == NULL) { if (dirp == nullptr) {
return "Failed to open /sys/class/bluetooth"; return "Failed to open /sys/class/bluetooth";
} }
@@ -120,12 +120,12 @@ static const char* detectBluetooth(FFlist* devices) {
} }
struct dirent* entry; struct dirent* entry;
while ((entry = readdir(dirp)) != NULL) { while ((entry = readdir(dirp)) != nullptr) {
if (entry->d_name[0] == '.') { if (entry->d_name[0] == '.') {
continue; continue;
} }
if (strchr(entry->d_name, ':') != NULL) { // ignore connected devices if (strchr(entry->d_name, ':') != nullptr) { // ignore connected devices
continue; continue;
} }
@@ -138,7 +138,7 @@ static const char* detectBluetooth(FFlist* devices) {
device->enabled = false; device->enabled = false;
detectBluetoothRoot(device, entry->d_name, &dbus); detectBluetoothRoot(device, entry->d_name, &dbus);
} }
return NULL; return nullptr;
} }
#endif #endif
@@ -58,7 +58,7 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */)
FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsConnectable) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsConnectable)
FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsDiscoverable) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsDiscoverable)
HANDLE hRadio = NULL; HANDLE hRadio = nullptr;
HBLUETOOTH_DEVICE_FIND hFind = ffBluetoothFindFirstRadio(&(BLUETOOTH_FIND_RADIO_PARAMS) { HBLUETOOTH_DEVICE_FIND hFind = ffBluetoothFindFirstRadio(&(BLUETOOTH_FIND_RADIO_PARAMS) {
.dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS) }, .dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS) },
&hRadio); &hRadio);
@@ -73,7 +73,7 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */)
do { do {
BTH_LOCAL_RADIO_INFO blri; BTH_LOCAL_RADIO_INFO blri;
DWORD returned; DWORD returned;
if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, NULL, 0, &blri, sizeof(blri), &returned, NULL)) { if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, nullptr, 0, &blri, sizeof(blri), &returned, nullptr)) {
continue; continue;
} }
@@ -95,5 +95,5 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */)
ffBluetoothFindRadioClose(hFind); ffBluetoothFindRadioClose(hFind);
return NULL; return nullptr;
} }
+1 -1
View File
@@ -5,5 +5,5 @@ const char* ffDetectBoard(FFBoardResult* board) {
if (!ffSettingsGetAndroidProperty("ro.product.board", &board->name)) { if (!ffSettingsGetAndroidProperty("ro.product.board", &board->name)) {
ffSettingsGetAndroidProperty("ro.board.platform", &board->name); ffSettingsGetAndroidProperty("ro.board.platform", &board->name);
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -28,5 +28,5 @@ const char* ffDetectBoard(FFBoardResult* result) {
ffCfStrGetString(manufacturer, &result->vendor); ffCfStrGetString(manufacturer, &result->vendor);
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -11,5 +11,5 @@ const char* ffDetectBoard(FFBoardResult* result) {
ffCleanUpSmbiosValue(&result->vendor); ffCleanUpSmbiosValue(&result->vendor);
ffSettingsGetFreeBSDKenv("smbios.planar.version", &result->version); ffSettingsGetFreeBSDKenv("smbios.planar.version", &result->version);
ffCleanUpSmbiosValue(&result->version); ffCleanUpSmbiosValue(&result->version);
return NULL; return nullptr;
} }
+1 -1
View File
@@ -22,5 +22,5 @@ const char* ffDetectBoard(FFBoardResult* board) {
ffStrbufSubstrBefore(&board->vendor, comma); ffStrbufSubstrBefore(&board->vendor, comma);
} }
} }
return NULL; return nullptr;
} }
+5 -5
View File
@@ -3,18 +3,18 @@
#include "common/smbios.h" #include "common/smbios.h"
const char* ffDetectBoard(FFBoardResult* board) { const char* ffDetectBoard(FFBoardResult* board) {
if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == NULL) { if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == nullptr) {
ffCleanUpSmbiosValue(&board->name); ffCleanUpSmbiosValue(&board->name);
} }
if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == NULL) { if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == nullptr) {
ffCleanUpSmbiosValue(&board->version); ffCleanUpSmbiosValue(&board->version);
} }
if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == NULL) { if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == nullptr) {
ffCleanUpSmbiosValue(&board->vendor); ffCleanUpSmbiosValue(&board->vendor);
} }
if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == NULL) { if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == nullptr) {
ffCleanUpSmbiosValue(&board->serial); ffCleanUpSmbiosValue(&board->serial);
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -42,5 +42,5 @@ const char* ffDetectBoard(FFBoardResult* board) {
ffStrbufSetStatic(&board->version, ffSmbiosLocateString(strings, data->Version)); ffStrbufSetStatic(&board->version, ffSmbiosLocateString(strings, data->Version));
ffCleanUpSmbiosValue(&board->version); ffCleanUpSmbiosValue(&board->version);
return NULL; return nullptr;
} }
+2 -2
View File
@@ -39,7 +39,7 @@ static const char* detectSecureBoot(bool* result) {
*result = *CFDataGetBytePtr((CFDataRef) prop) != 0x02 /* Permissive Security */; *result = *CFDataGetBytePtr((CFDataRef) prop) != 0x02 /* Permissive Security */;
#endif #endif
return NULL; return nullptr;
} }
const char* ffDetectBootmgr(FFBootmgrResult* result) { const char* ffDetectBootmgr(FFBootmgrResult* result) {
@@ -65,5 +65,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
detectSecureBoot(&result->secureBoot); detectSecureBoot(&result->secureBoot);
return NULL; return nullptr;
} }
+1 -1
View File
@@ -58,5 +58,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
result->secureBoot = !!buffer[0]; result->secureBoot = !!buffer[0];
} }
return NULL; return nullptr;
} }
+1 -1
View File
@@ -13,5 +13,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
// TODO: detectSecureBoot(&result->secureBoot); // TODO: detectSecureBoot(&result->secureBoot);
return NULL; return nullptr;
} }
+1 -1
View File
@@ -28,5 +28,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
result->secureBoot = buffer[4] == 1; result->secureBoot = buffer[4] == 1;
} }
return NULL; return nullptr;
} }
+9 -9
View File
@@ -7,7 +7,7 @@
#include <windows.h> #include <windows.h>
const char* enablePrivilege(const wchar_t* privilege) { const char* enablePrivilege(const wchar_t* privilege) {
FF_AUTO_CLOSE_FD HANDLE token = NULL; FF_AUTO_CLOSE_FD HANDLE token = nullptr;
if (!NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))) { if (!NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))) {
return "NtOpenProcessToken() failed"; return "NtOpenProcessToken() failed";
} }
@@ -17,11 +17,11 @@ const char* enablePrivilege(const wchar_t* privilege) {
.Privileges = { .Privileges = {
(LUID_AND_ATTRIBUTES) { .Attributes = SE_PRIVILEGE_ENABLED } }, (LUID_AND_ATTRIBUTES) { .Attributes = SE_PRIVILEGE_ENABLED } },
}; };
if (!LookupPrivilegeValueW(NULL, privilege, &tp.Privileges[0].Luid)) { if (!LookupPrivilegeValueW(nullptr, privilege, &tp.Privileges[0].Luid)) {
return "LookupPrivilegeValue() failed"; return "LookupPrivilegeValue() failed";
} }
NTSTATUS status = NtAdjustPrivilegesToken(token, false, &tp, sizeof(tp), NULL, NULL); NTSTATUS status = NtAdjustPrivilegesToken(token, false, &tp, sizeof(tp), nullptr, nullptr);
if (!NT_SUCCESS(status)) { if (!NT_SUCCESS(status)) {
return "NtAdjustPrivilegesToken() failed"; return "NtAdjustPrivilegesToken() failed";
} }
@@ -30,12 +30,12 @@ const char* enablePrivilege(const wchar_t* privilege) {
return "The token does not have the specified privilege; try sudo please"; return "The token does not have the specified privilege; try sudo please";
} }
return NULL; return nullptr;
} }
const char* ffDetectBootmgr(FFBootmgrResult* result) { const char* ffDetectBootmgr(FFBootmgrResult* result) {
const char* err = enablePrivilege(L"SeSystemEnvironmentPrivilege"); const char* err = enablePrivilege(L"SeSystemEnvironmentPrivilege");
if (err != NULL) { if (err != nullptr) {
return err; return err;
} }
@@ -45,7 +45,7 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
} }
ULONG size = sizeof(result->order); ULONG size = sizeof(result->order);
if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, NULL))) { if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, nullptr))) {
return "NtQuerySystemEnvironmentValueEx(BootCurrent) failed"; return "NtQuerySystemEnvironmentValueEx(BootCurrent) failed";
} }
if (size != sizeof(result->order)) { if (size != sizeof(result->order)) {
@@ -56,7 +56,7 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
wchar_t key[9]; wchar_t key[9];
swprintf(key, ARRAY_SIZE(key), L"Boot%04X", result->order); swprintf(key, ARRAY_SIZE(key), L"Boot%04X", result->order);
size = sizeof(buffer); size = sizeof(buffer);
if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, NULL))) { if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, nullptr))) {
return "NtQuerySystemEnvironmentValueEx(Boot####) failed"; return "NtQuerySystemEnvironmentValueEx(Boot####) failed";
} }
if (size < sizeof(FFEfiLoadOption) || size == ARRAY_SIZE(buffer)) { if (size < sizeof(FFEfiLoadOption) || size == ARRAY_SIZE(buffer)) {
@@ -66,9 +66,9 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) {
ffEfiFillLoadOption((FFEfiLoadOption*) buffer, result); ffEfiFillLoadOption((FFEfiLoadOption*) buffer, result);
SYSTEM_SECUREBOOT_INFORMATION ssi; SYSTEM_SECUREBOOT_INFORMATION ssi;
if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), NULL))) { if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), nullptr))) {
result->secureBoot = ssi.SecureBootEnabled; result->secureBoot = ssi.SecureBootEnabled;
} }
return NULL; return nullptr;
} }
+7 -7
View File
@@ -27,7 +27,7 @@ extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float* bright
// Works for internal display // Works for internal display
static const char* detectWithDisplayServices(const FFDisplayServerResult* displayServer, FFlist* result) { static const char* detectWithDisplayServices(const FFDisplayServerResult* displayServer, FFlist* result) {
if (DisplayServicesGetBrightness == NULL) { if (DisplayServicesGetBrightness == nullptr) {
return "DisplayServices function DisplayServicesGetBrightness is not available"; return "DisplayServices function DisplayServicesGetBrightness is not available";
} }
@@ -45,7 +45,7 @@ static const char* detectWithDisplayServices(const FFDisplayServerResult* displa
} }
} }
return NULL; return nullptr;
} }
#ifdef __aarch64__ #ifdef __aarch64__
@@ -63,7 +63,7 @@ static const char* detectWithDdcci(FF_A_UNUSED const FFDisplayServerResult* disp
io_registry_entry_t registryEntry; io_registry_entry_t registryEntry;
while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
FF_CFTYPE_AUTO_RELEASE IOAVServiceRef service = NULL; FF_CFTYPE_AUTO_RELEASE IOAVServiceRef service = nullptr;
{ {
FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryAv = registryEntry; FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryAv = registryEntry;
@@ -118,7 +118,7 @@ static const char* detectWithDdcci(FF_A_UNUSED const FFDisplayServerResult* disp
} }
} }
return NULL; return nullptr;
} }
#else #else
static IOOptionBits getSupportedTransactionType(void) { static IOOptionBits getSupportedTransactionType(void) {
@@ -181,7 +181,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F
} }
uint8_t i2cOut[12] = {}; uint8_t i2cOut[12] = {};
IOI2CConnectRef connect = NULL; IOI2CConnectRef connect = nullptr;
if (IOI2CInterfaceOpen(interface, kNilOptions, &connect) != KERN_SUCCESS) { if (IOI2CInterfaceOpen(interface, kNilOptions, &connect) != KERN_SUCCESS) {
continue; continue;
} }
@@ -227,7 +227,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F
} }
} }
return NULL; return nullptr;
} }
#endif #endif
@@ -240,5 +240,5 @@ const char* ffDetectBrightness(FFBrightnessOptions* options, FFlist* result) {
detectWithDdcci(displayServer, options, result); detectWithDdcci(displayServer, options, result);
} }
return NULL; return nullptr;
} }
+3 -3
View File
@@ -69,7 +69,7 @@ const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFlist* re
brightness->builtin = false; brightness->builtin = false;
} }
return NULL; return nullptr;
} }
#else #else
@@ -125,7 +125,7 @@ const char* detectWithBacklight(FF_A_UNUSED FFBrightnessOptions* options, FFlist
ffStrbufAppendS(&brightness->name, path + strlen("/dev/backlight/")); ffStrbufAppendS(&brightness->name, path + strlen("/dev/backlight/"));
} }
} }
return NULL; return nullptr;
} }
#else #else
@@ -143,5 +143,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist*
if (options->ddcciSleep != FF_BRIGHTNESS_DDCCI_SLEEP_SKIP && result->length == 0) { if (options->ddcciSleep != FF_BRIGHTNESS_DDCCI_SLEEP_SKIP && result->length == 0) {
detectWithDdcci(options, result); detectWithDdcci(options, result);
} }
return NULL; return nullptr;
} }
@@ -42,5 +42,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist*
} while (screen.SetToNext() == B_OK); } while (screen.SetToNext() == B_OK);
return NULL; return nullptr;
} }
+10 -10
View File
@@ -11,7 +11,7 @@ static const char* detectWithBacklight(FFlist* result) {
const char* backlightDirPath = "/sys/class/backlight/"; const char* backlightDirPath = "/sys/class/backlight/";
FF_AUTO_CLOSE_DIR DIR* dirp = opendir(backlightDirPath); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(backlightDirPath);
if (dirp == NULL) { if (dirp == nullptr) {
return "Failed to open `/sys/class/backlight/`"; return "Failed to open `/sys/class/backlight/`";
} }
@@ -23,7 +23,7 @@ static const char* detectWithBacklight(FFlist* result) {
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
struct dirent* entry; struct dirent* entry;
while ((entry = readdir(dirp)) != NULL) { while ((entry = readdir(dirp)) != nullptr) {
if (entry->d_name[0] == '.') { if (entry->d_name[0] == '.') {
continue; continue;
} }
@@ -72,7 +72,7 @@ static const char* detectWithBacklight(FFlist* result) {
ffStrbufSubstrBefore(&backlightDir, backlightDirLength); ffStrbufSubstrBefore(&backlightDir, backlightDirLength);
} }
return NULL; return nullptr;
} }
#ifdef FF_HAVE_DDCUTIL #ifdef FF_HAVE_DDCUTIL
@@ -103,7 +103,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl
if (ffddca_init) { if (ffddca_init) {
FF_SUPPRESS_IO(); FF_SUPPRESS_IO();
// Ref: https://github.com/rockowitz/ddcutil/issues/344 // Ref: https://github.com/rockowitz/ddcutil/issues/344
if (ffddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { if (ffddca_init(nullptr, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) {
return "ddca_init() failed"; return "ddca_init() failed";
} }
} else { } else {
@@ -112,11 +112,11 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl
ffddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0); ffddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0);
} }
libddcutil = NULL; // Don't dlclose libddcutil. See https://github.com/rockowitz/ddcutil/issues/330 libddcutil = nullptr; // Don't dlclose libddcutil. See https://github.com/rockowitz/ddcutil/issues/330
} }
#else #else
#if DDCUTIL_VMAJOR >= 2 #if DDCUTIL_VMAJOR >= 2
if (ddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { if (ddca_init(nullptr, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) {
return "ddca_init() failed"; return "ddca_init() failed";
} }
#else #else
@@ -124,7 +124,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl
#endif #endif
#endif #endif
FF_AUTO_FREE DDCA_Display_Info_List* infoList = NULL; FF_AUTO_FREE DDCA_Display_Info_List* infoList = nullptr;
if (ffddca_get_display_info_list2(false, &infoList) < 0) { if (ffddca_get_display_info_list2(false, &infoList) < 0) {
return "ddca_get_display_info_list2(false, &infoList) failed"; return "ddca_get_display_info_list2(false, &infoList) failed";
} }
@@ -138,7 +138,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl
DDCA_Display_Handle handle; DDCA_Display_Handle handle;
if (ffddca_open_display2(display->dref, false, &handle) >= 0) { if (ffddca_open_display2(display->dref, false, &handle) >= 0) {
DDCA_Any_Vcp_Value* vcpValue = NULL; DDCA_Any_Vcp_Value* vcpValue = nullptr;
if (ffddca_get_any_vcp_value_using_explicit_type(handle, 0x10 /*brightness*/, DDCA_NON_TABLE_VCP_VALUE, &vcpValue) >= 0) { if (ffddca_get_any_vcp_value_using_explicit_type(handle, 0x10 /*brightness*/, DDCA_NON_TABLE_VCP_VALUE, &vcpValue) >= 0) {
assert(vcpValue->value_type == DDCA_NON_TABLE_VCP_VALUE); assert(vcpValue->value_type == DDCA_NON_TABLE_VCP_VALUE);
int current = VALREC_CUR_VAL(vcpValue), max = VALREC_MAX_VAL(vcpValue); int current = VALREC_CUR_VAL(vcpValue), max = VALREC_MAX_VAL(vcpValue);
@@ -154,7 +154,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl
} }
} }
return NULL; return nullptr;
} }
#endif #endif
@@ -170,5 +170,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist*
} }
#endif #endif
return NULL; return nullptr;
} }
+1 -1
View File
@@ -22,5 +22,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist*
brightness->current = value; brightness->current = value;
brightness->builtin = true; brightness->builtin = true;
} }
return NULL; return nullptr;
} }

Some files were not shown because too many files have changed in this diff Show More