diff --git a/collector/lib/AbortHandler.cpp b/collector/lib/AbortHandler.cpp index ff108df7829..2c2dbafa081 100644 --- a/collector/lib/AbortHandler.cpp +++ b/collector/lib/AbortHandler.cpp @@ -74,8 +74,9 @@ extern "C" void AbortHandler(int signum) { } } - if (n_frames == max_frames) + if (n_frames == max_frames) { write(STDERR_FILENO, "[truncated]\n", 13); + } // Write a message to stderr using only reentrant functions. num_bytes = snprintf(message_buffer, message_buffer_size, diff --git a/collector/lib/CollectorConfig.cpp b/collector/lib/CollectorConfig.cpp index 965ec607274..a876c872f75 100644 --- a/collector/lib/CollectorConfig.cpp +++ b/collector/lib/CollectorConfig.cpp @@ -237,8 +237,9 @@ void CollectorConfig::InitCollectorConfig(CollectorArgs* args) { } for (const std::string& str : ignored_networks.value()) { - if (str.empty()) + if (str.empty()) { continue; + } std::optional net = IPNet::parse(str); @@ -251,8 +252,9 @@ void CollectorConfig::InitCollectorConfig(CollectorArgs* args) { } for (const std::string& str : non_aggregated_networks.value()) { - if (str.empty()) + if (str.empty()) { continue; + } std::optional net = IPNet::parse(str); diff --git a/collector/lib/CollectorService.cpp b/collector/lib/CollectorService.cpp index 4b41300d9d3..7c7e8faa1a1 100644 --- a/collector/lib/CollectorService.cpp +++ b/collector/lib/CollectorService.cpp @@ -130,7 +130,9 @@ void CollectorService::RunForever() { CLOG(INFO) << "Shutting down collector."; - if (net_status_notifier) net_status_notifier->Stop(); + if (net_status_notifier) { + net_status_notifier->Stop(); + } // Shut down these first since they access the system inspector object. exporter.stop(); server.close(); diff --git a/collector/lib/CollectorStatsExporter.cpp b/collector/lib/CollectorStatsExporter.cpp index a78a4d3b8cf..713558d16a9 100644 --- a/collector/lib/CollectorStatsExporter.cpp +++ b/collector/lib/CollectorStatsExporter.cpp @@ -241,12 +241,20 @@ void CollectorStatsExporter::run() { nUserspace += userspace; - if (counters.userspace) counters.userspace->Set(userspace); - - if (counters.parse_micros_total) counters.parse_micros_total->Set(parse_micros_total); - if (counters.process_micros_total) counters.process_micros_total->Set(process_micros_total); - - if (counters.parse_micros_avg) counters.parse_micros_avg->Set(userspace ? parse_micros_total / userspace : 0); + if (counters.userspace) { + counters.userspace->Set(userspace); + } + + if (counters.parse_micros_total) { + counters.parse_micros_total->Set(parse_micros_total); + } + if (counters.process_micros_total) { + counters.process_micros_total->Set(process_micros_total); + } + + if (counters.parse_micros_avg) { + counters.parse_micros_avg->Set(userspace ? parse_micros_total / userspace : 0); + } } userspaceEvents->Set(nUserspace); diff --git a/collector/lib/Containers.h b/collector/lib/Containers.h index 33960614c5e..271fac9a6e5 100644 --- a/collector/lib/Containers.h +++ b/collector/lib/Containers.h @@ -22,7 +22,9 @@ using MappedType = WithConst; template ValueType* Find(C& container, const typename C::key_type& key) { auto it = container.find(key); - if (it == container.end()) return nullptr; + if (it == container.end()) { + return nullptr; + } return &*it; } @@ -37,7 +39,9 @@ bool Contains(const C& container, const typename C::key_type& key) { template MappedType* Lookup(M& map, const typename M::key_type& key) { auto* val = Find(map, key); - if (!val) return nullptr; + if (!val) { + return nullptr; + } return &val->second; } diff --git a/collector/lib/DuplexGRPC.h b/collector/lib/DuplexGRPC.h index 89df5c7c127..425488328f4 100644 --- a/collector/lib/DuplexGRPC.h +++ b/collector/lib/DuplexGRPC.h @@ -506,7 +506,9 @@ class DuplexClient : public virtual IDuplexClient { while (result && op_res.op != op_desc.op) { result = ProcessSingle(nullptr, deadline, &op_res); } - if (!result) return result; + if (!result) { + return result; + } return Result(op_res.ok); } @@ -561,14 +563,18 @@ class DuplexClientReaderWriter : public DuplexClientWriter { auto deadline = ToDeadline(time_spec); auto result = PollAll(DuplexClient::CAN_READ, deadline); - if (!result) return result; + if (!result) { + return result; + } // We can read, but the read buffer is not valid -> there has been an error. This is the last read. if (!read_buf_valid_) { return Result(Status::ERROR); } - if (obj) *obj = std::move(read_buf_); + if (obj) { + *obj = std::move(read_buf_); + } ReadNext(); return Result(Status::OK); @@ -666,7 +672,9 @@ class DuplexClientReaderWriter : public DuplexClientWriter { this->SetFlags(Done(Op::SHUTDOWN)); } - if (flags_out) *flags_out = this->flags_; + if (flags_out) { + *flags_out = this->flags_; + } return Result(next_status); } diff --git a/collector/lib/FileSystem.h b/collector/lib/FileSystem.h index ee4acf8be4a..3d36cabc987 100644 --- a/collector/lib/FileSystem.h +++ b/collector/lib/FileSystem.h @@ -93,14 +93,18 @@ class DirHandle : public ResourceWrapper { DirHandle(FDHandle&& fd) : ResourceWrapper(fdopendir(fd.release())) {} FDHandle openat(const char* path, int mode) const { - if (!valid()) return -1; + if (!valid()) { + return -1; + } return ::openat(dirfd(get()), path, mode); } int fd() const { return ::dirfd(get()); } struct dirent* read() { - if (!valid()) return nullptr; + if (!valid()) { + return nullptr; + } return readdir(get()); } diff --git a/collector/lib/NRadix.cpp b/collector/lib/NRadix.cpp index f3966962fca..911be3b1404 100644 --- a/collector/lib/NRadix.cpp +++ b/collector/lib/NRadix.cpp @@ -61,14 +61,18 @@ bool NRadixTree::Insert(const IPNet& network) const { next = node->left_; } - if (!next) break; + if (!next) { + break; + } bit >>= 1; node = next; if (bit == 0) { // We have walked 128 bits, stop. - if (++i >= Address::kU64MaxLen) break; + if (++i >= Address::kU64MaxLen) { + break; + } // Reset and move to lower part. bit = 0x8000000000000000ULL; @@ -105,7 +109,9 @@ bool NRadixTree::Insert(const IPNet& network) const { if (bit == 0) { // We have walked all 128 bits, stop. - if (++i >= Address::kU64MaxLen) break; + if (++i >= Address::kU64MaxLen) { + break; + } bit = 0x8000000000000000ULL; if (network.bits() >= 64) { @@ -120,7 +126,9 @@ bool NRadixTree::Insert(const IPNet& network) const { } IPNet NRadixTree::Find(const IPNet& network) const { - if (network.IsNull()) return {}; + if (network.IsNull()) { + return {}; + } if (network.bits() == 0) { CLOG(ERROR) << "Cannot handle CIDR " << network << " with /0, in network tree"; @@ -148,7 +156,9 @@ IPNet NRadixTree::Find(const IPNet& network) const { // All network bits are traversed. If a supernet was found along the way, `ret` holds it, // else there does not exist any supernet containing the search network/address. - if (!(*net_mask_p & bit)) break; + if (!(*net_mask_p & bit)) { + break; + } bit >>= 1; @@ -177,7 +187,9 @@ IPNet NRadixTree::Find(const Address& addr) const { } void getAll(nRadixNode* node, std::vector& ret) { - if (!node) return; + if (!node) { + return; + } if (node->value_) { ret.push_back(*node->value_); @@ -199,14 +211,20 @@ bool isAnyIPNetSubsetUtil(Address::Family family, const nRadixNode* n1, const nR // If we have found networks from both trees belonging to same family, we have the answer. if (containing_net && contained_net) { if (family == Address::Family::UNKNOWN) { - if (containing_net->family() == contained_net->family()) return true; + if (containing_net->family() == contained_net->family()) { + return true; + } } else { - if (containing_net->family() == family && contained_net->family() == family) return true; + if (containing_net->family() == family && contained_net->family() == family) { + return true; + } } } // There are no more networks down the path in second tree, so stop. - if (!n2) return false; + if (!n2) { + return false; + } if (n1 && n1->value_) { containing_net = n1->value_; diff --git a/collector/lib/NRadix.h b/collector/lib/NRadix.h index 606b905b732..5cec2663ae0 100644 --- a/collector/lib/NRadix.h +++ b/collector/lib/NRadix.h @@ -54,7 +54,9 @@ struct nRadixNode { } nRadixNode& operator=(const nRadixNode& other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } auto* new_node = new nRadixNode(other); std::swap(*new_node, *this); delete new_node; @@ -92,7 +94,9 @@ class NRadixTree { } NRadixTree& operator=(const NRadixTree& other) { - if (this == &other) return *this; + if (this == &other) { + return *this; + } delete root_; // This calls the node copy constructor which in turn copies all the nodes. root_ = new nRadixNode(*other.root_); diff --git a/collector/lib/NetworkConnection.h b/collector/lib/NetworkConnection.h index bb1a9f91bec..e51486fe6b0 100644 --- a/collector/lib/NetworkConnection.h +++ b/collector/lib/NetworkConnection.h @@ -227,7 +227,9 @@ class IPNet { } size_t Hash() const { - if (is_addr_) return HashAll(address_.array(), mask_, bits_); + if (is_addr_) { + return HashAll(address_.array(), mask_, bits_); + } return HashAll(mask_, bits_); } @@ -411,11 +413,19 @@ inline bool IsRelevantEndpoint(const Endpoint& ep) { // operating systems adhere to the IANA-recommended range. Therefore, the return value is not a bool, but instead an // int which indicates the confidence that the port is in fact ephemeral. inline int IsEphemeralPort(uint16_t port) { - if (port >= 49152) return 4; // IANA range - if (port >= 32768) return 3; // Modern Linux kernel range - if (port >= 1025 && port <= 5000) return 2; // FreeBSD (partial) + Windows <=XP range - if (port == 1024) return 1; // FreeBSD - return 0; // not ephemeral according to any range + if (port >= 49152) { + return 4; // IANA range + } + if (port >= 32768) { + return 3; // Modern Linux kernel range + } + if (port >= 1025 && port <= 5000) { + return 2; // FreeBSD (partial) + Windows <=XP range + } + if (port == 1024) { + return 1; // FreeBSD + } + return 0; // not ephemeral according to any range } // PrivateIPv4Networks return private IPv4 networks. diff --git a/collector/lib/NetworkConnectionInfoServiceComm.cpp b/collector/lib/NetworkConnectionInfoServiceComm.cpp index 0f822a3b5e1..3c9353b9dde 100644 --- a/collector/lib/NetworkConnectionInfoServiceComm.cpp +++ b/collector/lib/NetworkConnectionInfoServiceComm.cpp @@ -38,13 +38,16 @@ bool NetworkConnectionInfoServiceComm::WaitForConnectionReady(const std::functio void NetworkConnectionInfoServiceComm::TryCancel() { WITH_LOCK(context_mutex_) { - if (context_) context_->TryCancel(); + if (context_) { + context_->TryCancel(); + } } } std::unique_ptr> NetworkConnectionInfoServiceComm::PushNetworkConnectionInfoOpenStream(std::function receive_func) { - if (!context_) + if (!context_) { ResetClientContext(); + } if (channel_) { return DuplexClient::CreateWithReadCallback( diff --git a/collector/lib/NetworkSignalHandler.cpp b/collector/lib/NetworkSignalHandler.cpp index 9aab28ddd66..9e35003960c 100644 --- a/collector/lib/NetworkSignalHandler.cpp +++ b/collector/lib/NetworkSignalHandler.cpp @@ -55,7 +55,9 @@ NetworkSignalHandler::NetworkSignalHandler(sinsp* inspector, std::shared_ptr NetworkSignalHandler::GetConnection(sinsp_evt* evt) { auto* fd_info = evt->get_fd_info(); - if (!fd_info) return std::nullopt; + if (!fd_info) { + return std::nullopt; + } // With collect_connection_status_ set, we can prevent reporting of asynchronous // connections which fail. @@ -117,13 +119,17 @@ std::optional NetworkSignalHandler::GetConnection(sinsp_evt* evt) { const Endpoint* remote = is_server ? &client : &server; const std::string* container_id = event_extractor_->get_container_id(evt); - if (!container_id) return std::nullopt; + if (!container_id) { + return std::nullopt; + } return {Connection(*container_id, *local, *remote, l4proto, is_server)}; } SignalHandler::Result NetworkSignalHandler::HandleSignal(sinsp_evt* evt) { auto modifier = modifiers[evt->get_type()]; - if (modifier == Modifier::INVALID) return SignalHandler::IGNORED; + if (modifier == Modifier::INVALID) { + return SignalHandler::IGNORED; + } auto result = GetConnection(evt); if (!result.has_value() || !IsRelevantConnection(*result)) { diff --git a/collector/lib/NetworkStatusNotifier.cpp b/collector/lib/NetworkStatusNotifier.cpp index d944b30b932..d6f93c15671 100644 --- a/collector/lib/NetworkStatusNotifier.cpp +++ b/collector/lib/NetworkStatusNotifier.cpp @@ -317,7 +317,9 @@ void NetworkStatusNotifier::RunSingleAfterglow(IDuplexClientWriterm_args.begin(); it != system_inspector_threadinfo_->m_args.end();) { args << *it++; - if (it != system_inspector_threadinfo_->m_args.end()) args << " "; + if (it != system_inspector_threadinfo_->m_args.end()) { + args << " "; + } } return args.str(); } diff --git a/collector/lib/ProcessSignalFormatter.cpp b/collector/lib/ProcessSignalFormatter.cpp index 4b923a0fcc1..c56edff95fc 100644 --- a/collector/lib/ProcessSignalFormatter.cpp +++ b/collector/lib/ProcessSignalFormatter.cpp @@ -37,11 +37,15 @@ static EventMap process_signals = { }; std::string extract_proc_args(sinsp_threadinfo* tinfo) { - if (tinfo->m_args.empty()) return ""; + if (tinfo->m_args.empty()) { + return ""; + } std::ostringstream args; for (auto it = tinfo->m_args.begin(); it != tinfo->m_args.end();) { args << *it++; - if (it != tinfo->m_args.end()) args << " "; + if (it != tinfo->m_args.end()) { + args << " "; + } } return args.str(); } @@ -67,7 +71,9 @@ const SignalStreamMessage* ProcessSignalFormatter::ToProtoMessage(sinsp_evt* eve } ProcessSignal* process_signal = CreateProcessSignal(event); - if (!process_signal) return nullptr; + if (!process_signal) { + return nullptr; + } Signal* signal = Allocate(); signal->set_allocated_process_signal(process_signal); @@ -86,7 +92,9 @@ const SignalStreamMessage* ProcessSignalFormatter::ToProtoMessage(sinsp_threadin } ProcessSignal* process_signal = CreateProcessSignal(tinfo); - if (!process_signal) return nullptr; + if (!process_signal) { + return nullptr; + } Signal* signal = Allocate(); signal->set_allocated_process_signal(process_signal); @@ -121,14 +129,22 @@ ProcessSignal* ProcessSignalFormatter::CreateProcessSignal(sinsp_evt* event) { } // set process arguments - if (const char* args = event_extractor_->get_proc_args(event)) signal->set_args(args); + if (const char* args = event_extractor_->get_proc_args(event)) { + signal->set_args(args); + } // set pid - if (const int64_t* pid = event_extractor_->get_pid(event)) signal->set_pid(*pid); + if (const int64_t* pid = event_extractor_->get_pid(event)) { + signal->set_pid(*pid); + } // set user and group id credentials - if (const uint32_t* uid = event_extractor_->get_uid(event)) signal->set_uid(*uid); - if (const uint32_t* gid = event_extractor_->get_gid(event)) signal->set_gid(*gid); + if (const uint32_t* uid = event_extractor_->get_uid(event)) { + signal->set_uid(*uid); + } + if (const uint32_t* gid = event_extractor_->get_gid(event)) { + signal->set_gid(*gid); + } // set time auto timestamp = Allocate(); @@ -256,7 +272,9 @@ bool ProcessSignalFormatter::ValidateProcessDetails(sinsp_evt* event) { int ProcessSignalFormatter::GetTotalStringLength(const std::vector& lineage) { int totalStringLength = 0; - for (LineageInfo l : lineage) totalStringLength += l.parent_exec_file_path().size(); + for (LineageInfo l : lineage) { + totalStringLength += l.parent_exec_file_path().size(); + } return totalStringLength; } @@ -271,17 +289,25 @@ void ProcessSignalFormatter::CountLineage(const std::vector& lineag void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, std::vector& lineage) { - if (tinfo == NULL) return; + if (tinfo == NULL) { + return; + } sinsp_threadinfo* mt = NULL; if (tinfo->is_main_thread()) { mt = tinfo; } else { mt = tinfo->get_main_thread(); - if (mt == NULL) return; + if (mt == NULL) { + return; + } } sinsp_threadinfo::visitor_func_t visitor = [this, &lineage](sinsp_threadinfo* pt) { - if (pt == NULL) return false; - if (pt->m_pid == 0) return false; + if (pt == NULL) { + return false; + } + if (pt->m_pid == 0) { + return false; + } // // Collection of process lineage information should stop at the container @@ -302,7 +328,9 @@ void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, return false; } - if (pt->m_vpid == -1) return false; + if (pt->m_vpid == -1) { + return false; + } // Collapse parent child processes that have the same path if (lineage.empty() || (lineage.back().parent_exec_file_path() != pt->m_exepath)) { @@ -313,7 +341,9 @@ void ProcessSignalFormatter::GetProcessLineage(sinsp_threadinfo* tinfo, } // Limit max number of ancestors - if (lineage.size() >= 10) return false; + if (lineage.size() >= 10) { + return false; + } return true; }; diff --git a/collector/lib/ProcfsScraper.cpp b/collector/lib/ProcfsScraper.cpp index ecaf7e6c29e..b7b075c93b0 100644 --- a/collector/lib/ProcfsScraper.cpp +++ b/collector/lib/ProcfsScraper.cpp @@ -24,12 +24,16 @@ namespace { // rep_find applies find n times, always advancing past the found character in each subsequent application. std::string_view::size_type rep_find(int n, std::string_view str, char c) { - if (n <= 0) return std::string_view::npos; + if (n <= 0) { + return std::string_view::npos; + } std::string_view::size_type pos = 0; while (--n > 0) { pos = str.find(c, pos); - if (pos == std::string_view::npos) return std::string_view::npos; + if (pos == std::string_view::npos) { + return std::string_view::npos; + } pos++; } return str.find(c, pos); @@ -37,7 +41,9 @@ std::string_view::size_type rep_find(int n, std::string_view str, char c) { // nextfield advances to the next field in a space-delimited string. const char* nextfield(const char* p, const char* endp) { - while (p < endp && *p && !std::isspace(*p)) p++; + while (p < endp && *p && !std::isspace(*p)) { + p++; + } while (p < endp && *p && std::isspace(*++p)) ; return (p < endp && *p) ? p : nullptr; @@ -58,18 +64,28 @@ const char* rep_nextfield(int n, const char* p, const char* endp) { bool ReadINode(int dirfd, const char* path, const char* prefix, ino_t* inode) { char linkbuf[64]; ssize_t nread = readlinkat(dirfd, path, linkbuf, sizeof(linkbuf)); - if (nread <= 0 || nread >= ssizeof(linkbuf) - 1) return false; + if (nread <= 0 || nread >= ssizeof(linkbuf) - 1) { + return false; + } linkbuf[nread] = '\0'; - if (linkbuf[nread - 1] != ']') return false; + if (linkbuf[nread - 1] != ']') { + return false; + } size_t prefix_len = std::strlen(prefix); - if (std::strncmp(linkbuf, prefix, prefix_len) != 0) return false; - if (std::strncmp(linkbuf + prefix_len, ":[", 2) != 0) return false; + if (std::strncmp(linkbuf, prefix, prefix_len) != 0) { + return false; + } + if (std::strncmp(linkbuf + prefix_len, ":[", 2) != 0) { + return false; + } // Parse inode value as decimal char* endp; uintmax_t parsed = std::strtoumax(linkbuf + prefix_len + 2, &endp, 10); - if (*endp != ']') return false; + if (*endp != ']') { + return false; + } *inode = static_cast(parsed); return true; } @@ -113,10 +129,14 @@ bool GetSocketINodes(int dirfd, uint64_t pid, UnorderedSet* sock_ino } while (auto curr = fd_dir.read()) { - if (!std::isdigit(curr->d_name[0])) continue; // only look at fd entries, ignore '.' and '..'. + if (!std::isdigit(curr->d_name[0])) { + continue; // only look at fd entries, ignore '.' and '..'. + } ino_t inode; - if (!ReadINode(fd_dir.fd(), curr->d_name, "socket", &inode)) continue; // ignore non-socket fds + if (!ReadINode(fd_dir.fd(), curr->d_name, "socket", &inode)) { + continue; // ignore non-socket fds + } sock_inodes->emplace(inode, pid); } @@ -128,15 +148,21 @@ bool GetSocketINodes(int dirfd, uint64_t pid, UnorderedSet* sock_ino // the cgroup. std::optional GetContainerID(int dirfd) { FileHandle cgroups_file(FDHandle(openat(dirfd, "cgroup", O_RDONLY)), "r"); - if (!cgroups_file.valid()) return {}; + if (!cgroups_file.valid()) { + return {}; + } thread_local char* linebuf; thread_local size_t linebuf_cap; ssize_t line_len; while ((line_len = getline(&linebuf, &linebuf_cap, cgroups_file.get())) != -1) { - if (!line_len) continue; - if (linebuf[line_len - 1] == '\n') line_len--; + if (!line_len) { + continue; + } + if (linebuf[line_len - 1] == '\n') { + line_len--; + } std::string_view line(linebuf, line_len); auto short_container_id = ExtractContainerID(line); @@ -154,13 +180,17 @@ std::optional GetContainerID(int dirfd) { // IsHexChar checks if the given character is an (uppercase) hexadecimal character. bool IsHexChar(char c) { - if (std::isdigit(c)) return true; + if (std::isdigit(c)) { + return true; + } return c >= 'A' && c <= 'F'; } // HexCharToVal returns the numeric value of a single (uppercase) hexadecimal digit. unsigned char HexCharToVal(char c) { - if (std::isdigit(c)) return c - '0'; + if (std::isdigit(c)) { + return c - '0'; + } return 10 + (c - 'A'); } @@ -176,7 +206,9 @@ int ReadHexBytes(const char* p, const char* endp, void* buf, int chunk_size, int for (; i < num_bytes && p < endp - 2; i++) { char high = *p++; char low = *p++; - if (!IsHexChar(high) || !IsHexChar(low)) break; + if (!IsHexChar(high) || !IsHexChar(low)) { + break; + } *bbuf++ = HexCharToVal(high) << 4 | HexCharToVal(low); if (reverse && i % chunk_size == chunk_size - 1) { @@ -217,13 +249,19 @@ const char* ParseEndpoint(const char* p, const char* endp, Address::Family famil int addr_len = Address::Length(family); int nread = ReadHexBytes(p, endp, addr_data.data(), 4, addr_len / 4, needs_byteorder_swap); - if (nread != addr_len) return nullptr; + if (nread != addr_len) { + return nullptr; + } p += nread * 2; - if (*p++ != ':') return nullptr; + if (*p++ != ':') { + return nullptr; + } uint16_t port; nread = ReadHexBytes(p, endp, &port, sizeof(port), 1, needs_byteorder_swap); - if (nread != sizeof(port)) return nullptr; + if (nread != sizeof(port)) { + return nullptr; + } p += nread * 2; *endpoint = Endpoint(Address(family, addr_data), port); @@ -233,35 +271,53 @@ const char* ParseEndpoint(const char* p, const char* endp, Address::Family famil // ParseConnLine parses an entire line in the `net/tcp[6]` file. bool ParseConnLine(const char* p, const char* endp, Address::Family family, ConnLineData* data) { // Strip leading spaces. - while (std::isspace(*p)) p++; + while (std::isspace(*p)) { + p++; + } // 0: sl p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 1: local_address p = ParseEndpoint(p, endp, family, &data->local); - if (!p) return false; + if (!p) { + return false; + } p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 2: rem_address p = ParseEndpoint(p, endp, family, &data->remote); - if (!p) return false; + if (!p) { + return false; + } p = nextfield(p, endp); - if (!p) return false; + if (!p) { + return false; + } // 3: st int nread = ReadHexBytes(p, endp, &data->state, 1, 1, false); - if (nread != 1) return false; + if (nread != 1) { + return false; + } p += nread * 2; p = rep_nextfield(6, p, endp); - if (!p) return false; + if (!p) { + return false; + } // 9: inode char* parse_endp; uintmax_t inode = strtoumax(p, &parse_endp, 10); - if (*parse_endp && !std::isspace(*parse_endp)) return false; + if (*parse_endp && !std::isspace(*parse_endp)) { + return false; + } data->inode = static_cast(inode); return true; @@ -270,11 +326,15 @@ bool ParseConnLine(const char* p, const char* endp, Address::Family family, Conn // LocalIsServer returns true if the connection between local and remote looks like the local end is the server (taking // the set of listening endpoints into account), and false otherwise. bool LocalIsServer(const Endpoint& local, const Endpoint& remote, const UnorderedSet& listen_endpoints) { - if (Contains(listen_endpoints, local)) return true; + if (Contains(listen_endpoints, local)) { + return true; + } // Check if we are listening on the given port on any interface. Endpoint local_any(Address::Any(local.address().family()), local.port()); - if (Contains(listen_endpoints, local_any)) return true; + if (Contains(listen_endpoints, local_any)) { + return true; + } // We didn't find an entry for listening on this address, but closing a listen socket does not terminate established // connections. We hence have to resort to inspecting the port number to see which one seems more likely to be @@ -287,13 +347,17 @@ bool ReadConnectionsFromFile(Address::Family family, L4Proto l4proto, std::FILE* UnorderedMap* connections, UnorderedMap* listen_endpoints) { char line[512]; - if (!std::fgets(line, sizeof(line), f)) return false; // ignore the first *header) line. + if (!std::fgets(line, sizeof(line), f)) { + return false; // ignore the first *header) line. + } UnorderedSet all_listen_endpoints; while (std::fgets(line, sizeof(line), f)) { ConnLineData data; - if (!ParseConnLine(line, line + sizeof(line), family, &data)) continue; + if (!ParseConnLine(line, line + sizeof(line), family, &data)) { + continue; + } if (data.state == TCP_LISTEN) { // listen socket all_listen_endpoints.insert(data.local); if (data.inode && listen_endpoints) { @@ -307,7 +371,9 @@ bool ReadConnectionsFromFile(Address::Family family, L4Proto l4proto, std::FILE* continue; } - if (!data.inode) continue; // socket was closed or otherwise unavailable + if (!data.inode) { + continue; // socket was closed or otherwise unavailable + } auto& conn_info = (*connections)[data.inode]; conn_info.local = data.local; conn_info.remote = data.remote; @@ -367,15 +433,21 @@ void ResolveSocketInodes(const SocketsByContainer& sockets_by_container, const C const auto& container_id = container_sockets.first; for (const auto& netns_sockets : container_sockets.second) { const auto* ns_network_data = Lookup(conns_by_ns, netns_sockets.first); - if (!ns_network_data) continue; + if (!ns_network_data) { + continue; + } for (const auto& socket : netns_sockets.second) { if (const auto* conn = Lookup(ns_network_data->connections, socket.inode())) { Connection connection(container_id, conn->local, conn->remote, conn->l4proto, conn->is_server); - if (!IsRelevantConnection(connection)) continue; + if (!IsRelevantConnection(connection)) { + continue; + } connections->push_back(std::move(connection)); } else if (listen_endpoints) { if (const auto* ep = Lookup(ns_network_data->listen_endpoints, socket.inode())) { - if (!IsRelevantEndpoint(ep->endpoint)) continue; + if (!IsRelevantEndpoint(ep->endpoint)) { + continue; + } std::shared_ptr process; @@ -408,7 +480,9 @@ bool ReadContainerConnections(const char* proc_path, std::shared_ptrd_name[0])) continue; // only look for entries + if (!std::isdigit(curr->d_name[0])) { + continue; // only look for entries + } long long pid = strtoll(curr->d_name, 0, 10); FDHandle dirfd = procdir.openat(curr->d_name, O_RDONLY); @@ -482,8 +556,9 @@ bool ReadProcessExe(const char* process_id, int dirfd, std::string& comm, std::s comm = exe_path = buffer; - if (buffer[0] == '/') + if (buffer[0] == '/') { comm = strrchr(buffer, '/') + 1; + } return true; } diff --git a/collector/lib/RateLimit.cpp b/collector/lib/RateLimit.cpp index 785f3235d00..d65d6b36304 100644 --- a/collector/lib/RateLimit.cpp +++ b/collector/lib/RateLimit.cpp @@ -22,15 +22,21 @@ int64_t Limiter::Tokens(TokenBucket* b) { } bool Limiter::AllowN(TokenBucket* b, int64_t n) { - if (!b->last_time) fill_bucket(b); + if (!b->last_time) { + fill_bucket(b); + } int64_t refill = refill_count(b); b->tokens += refill * burst_size_; b->last_time += refill * refill_time_; - if (b->tokens >= burst_size_) fill_bucket(b); + if (b->tokens >= burst_size_) { + fill_bucket(b); + } - if (n > b->tokens) return false; + if (n > b->tokens) { + return false; + } b->tokens -= n; diff --git a/collector/lib/StoppableThread.h b/collector/lib/StoppableThread.h index dc1ea80ef1e..4a2151a6f14 100644 --- a/collector/lib/StoppableThread.h +++ b/collector/lib/StoppableThread.h @@ -18,7 +18,9 @@ class StoppableThread { public: template bool Start(Args&&... args) { - if (!prepareStart()) return false; + if (!prepareStart()) { + return false; + } return doStart(new std::thread(std::forward(args)...)); } void Stop(); diff --git a/collector/lib/Utility.cpp b/collector/lib/Utility.cpp index 792d6582e06..4cb69bb6bcf 100644 --- a/collector/lib/Utility.cpp +++ b/collector/lib/Utility.cpp @@ -96,31 +96,37 @@ std::string Base64Decode(std::string const& encoded_string) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { - for (i = 0; i < 4; i++) + for (i = 0; i < 4; i++) { char_array_4[i] = base64_chars.find(char_array_4[i]); + } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (i = 0; (i < 3); i++) + for (i = 0; (i < 3); i++) { ret += char_array_3[i]; + } i = 0; } } if (i) { - for (j = i; j < 4; j++) + for (j = i; j < 4; j++) { char_array_4[j] = 0; + } - for (j = 0; j < 4; j++) + for (j = 0; j < 4; j++) { char_array_4[j] = base64_chars.find(char_array_4[j]); + } char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; - for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; + for (j = 0; (j < i - 1); j++) { + ret += char_array_3[j]; + } } return ret; @@ -128,7 +134,9 @@ std::string Base64Decode(std::string const& encoded_string) { std::string GetHostPath(const std::string& file) { const char* host_root = std::getenv("COLLECTOR_HOST_ROOT"); - if (!host_root) host_root = ""; + if (!host_root) { + host_root = ""; + } std::string host_file(host_root); // Check if we are joining paths without a seperator, if (host_file.length() && file.length() && @@ -141,7 +149,9 @@ std::string GetHostPath(const std::string& file) { const char* GetSNIHostname() { const char* hostname = std::getenv("SNI_HOSTNAME"); - if (hostname && *hostname) return hostname; + if (hostname && *hostname) { + return hostname; + } // if the environment variable is not defined, then default // to sensor.stackrox diff --git a/collector/lib/optionparser.h b/collector/lib/optionparser.h index a5a8e194f6c..3aa6f195d00 100644 --- a/collector/lib/optionparser.h +++ b/collector/lib/optionparser.h @@ -43,9 +43,9 @@ * @brief This is the only file required to use The Lean Mean C++ Option Parser. * Just \#include it and you're set. * - * The Lean Mean C++ Option Parser handles the program's command line arguments + * The Lean Mean C++ Option Parser handles the program's command line arguments * (argc, argv). - * It supports the short and long option formats of getopt(), getopt_long() + * It supports the short and long option formats of getopt(), getopt_long() * and getopt_long_only() but has a more convenient interface. * The following features set it apart from other option parsers: * @@ -82,7 +82,7 @@ * @endcode * * @n - * Despite these features the code size remains tiny. + * Despite these features the code size remains tiny. * It is smaller than uClibc's GNU getopt() and just a * couple 100 bytes larger than uClibc's SUSv3 getopt(). @n * (This does not include the usage formatter, of course. But you don't have to use that.) @@ -217,22 +217,19 @@ #define OPTIONPARSER_H_ /** @brief The namespace of The Lean Mean C++ Option Parser. */ -namespace option -{ +namespace option { #ifdef _MSC_VER -#include -#pragma intrinsic(_BitScanReverse) -struct MSC_Builtin_CLZ -{ - static int builtin_clz(unsigned x) - { +# include +# pragma intrinsic(_BitScanReverse) +struct MSC_Builtin_CLZ { + static int builtin_clz(unsigned x) { unsigned long index; _BitScanReverse(&index, x); - return 32-index; // int is always 32bit on Windows, even for target x64 + return 32 - index; // int is always 32bit on Windows, even for target x64 } }; -#define __builtin_clz(x) MSC_Builtin_CLZ::builtin_clz(x) +# define __builtin_clz(x) MSC_Builtin_CLZ::builtin_clz(x) #endif class Option; @@ -243,8 +240,7 @@ class Option; * In the case that no argument is provided for an option that takes an * optional argument, return codes @c ARG_OK and @c ARG_IGNORE are equivalent. */ -enum ArgStatus -{ +enum ArgStatus { //! The option does not take an argument. ARG_NONE, //! The argument is acceptable for the option. @@ -307,8 +303,7 @@ typedef ArgStatus (*CheckArg)(const Option& option, bool msg); * }; * @endcode */ -struct Descriptor -{ +struct Descriptor { /** * @brief Index of this option's linked list in the array filled in by the parser. * @@ -434,11 +429,11 @@ struct Descriptor * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) * fname = opt->arg; ... @endcode */ -class Option -{ +class Option { Option* next_; Option* prev_; -public: + + public: /** * @brief Pointer to this Option's Descriptor. * @@ -525,8 +520,7 @@ class Option * } * @endcode */ - int type() const - { + int type() const { return desc == 0 ? 0 : desc->type; } @@ -534,8 +528,7 @@ class Option * @brief Returns Descriptor::index of this Option's Descriptor, or -1 if this Option * is invalid (unused). */ - int index() const - { + int index() const { return desc == 0 ? -1 : (int)desc->index; } @@ -551,12 +544,10 @@ class Option * * Returns 0 when called for an unused/invalid option. */ - int count() - { + int count() { int c = (desc == 0 ? 0 : 1); Option* p = first(); - while (!p->isLast()) - { + while (!p->isLast()) { ++c; p = p->next_; }; @@ -571,8 +562,7 @@ class Option * * Returns true for an unused/invalid option. */ - bool isFirst() const - { + bool isFirst() const { return isTagged(prev_); } @@ -584,8 +574,7 @@ class Option * * Returns true for an unused/invalid option. */ - bool isLast() const - { + bool isLast() const { return isTagged(next_); } @@ -600,11 +589,11 @@ class Option * This method may be called on an unused/invalid option and will return a pointer to the * option itself. */ - Option* first() - { + Option* first() { Option* p = this; - while (!p->isFirst()) + while (!p->isFirst()) { p = p->prev_; + } return p; } @@ -624,8 +613,7 @@ class Option * Descriptor::type and all you have to do is check last()->type() to get * the state listed last on the command line. */ - Option* last() - { + Option* last() { return first()->prevwrap(); } @@ -637,8 +625,7 @@ class Option * option with the same Descriptor::index that precedes this option on the command * line. */ - Option* prev() - { + Option* prev() { return isFirst() ? 0 : prev_; } @@ -650,8 +637,7 @@ class Option * option with the same Descriptor::index that precedes this option on the command * line. */ - Option* prevwrap() - { + Option* prevwrap() { return untag(prev_); } @@ -663,8 +649,7 @@ class Option * option with the same Descriptor::index that follows this option on the command * line. */ - Option* next() - { + Option* next() { return isLast() ? 0 : next_; } @@ -676,8 +661,7 @@ class Option * option with the same Descriptor::index that follows this option on the command * line. */ - Option* nextwrap() - { + Option* nextwrap() { return untag(next_); } @@ -691,8 +675,7 @@ class Option * @c new_last must not yet be part of a list, or that list will become corrupted, because * this method does not unchain @c new_last from an existing list. */ - void append(Option* new_last) - { + void append(Option* new_last) { Option* p = last(); Option* f = first(); p->next_ = new_last; @@ -717,8 +700,7 @@ class Option * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) * fname = opt->arg; ... @endcode */ - operator const Option*() const - { + operator const Option*() const { return desc ? this : 0; } @@ -738,8 +720,7 @@ class Option * @code for (Option* opt = options[FILE]; opt; opt = opt->next()) * fname = opt->arg; ... @endcode */ - operator Option*() - { + operator Option*() { return desc ? this : 0; } @@ -747,9 +728,7 @@ class Option * @brief Creates a new Option that is a one-element linked list and has NULL * @ref desc, @ref name, @ref arg and @ref namelen. */ - Option() : - desc(0), name(0), arg(0), namelen(0) - { + Option() : desc(0), name(0), arg(0), namelen(0) { prev_ = tag(this); next_ = tag(this); } @@ -762,8 +741,7 @@ class Option * short option and @ref namelen will be set to 1. Otherwise the length will extend to * the first '=' character or the string's 0-terminator. */ - Option(const Descriptor* desc_, const char* name_, const char* arg_) - { + Option(const Descriptor* desc_, const char* name_, const char* arg_) { init(desc_, name_, arg_); } @@ -772,8 +750,7 @@ class Option * * After this operation @c *this will be a one-element linked list. */ - void operator=(const Option& orig) - { + void operator=(const Option& orig) { init(orig.desc, orig.name, orig.arg); } @@ -782,12 +759,11 @@ class Option * * After this operation @c *this will be a one-element linked list. */ - Option(const Option& orig) - { + Option(const Option& orig) { init(orig.desc, orig.name, orig.arg); } -private: + private: /** * @internal * @brief Sets the fields of this Option to the given values (extracting @c name if necessary). @@ -796,36 +772,35 @@ class Option * short option and @ref namelen will be set to 1. Otherwise the length will extend to * the first '=' character or the string's 0-terminator. */ - void init(const Descriptor* desc_, const char* name_, const char* arg_) - { + void init(const Descriptor* desc_, const char* name_, const char* arg_) { desc = desc_; name = name_; arg = arg_; prev_ = tag(this); next_ = tag(this); namelen = 0; - if (name == 0) + if (name == 0) { return; + } namelen = 1; - if (name[0] != '-') + if (name[0] != '-') { return; - while (name[namelen] != 0 && name[namelen] != '=') + } + while (name[namelen] != 0 && name[namelen] != '=') { ++namelen; + } } - static Option* tag(Option* ptr) - { - return (Option*) ((unsigned long long) ptr | 1); + static Option* tag(Option* ptr) { + return (Option*)((unsigned long long)ptr | 1); } - static Option* untag(Option* ptr) - { - return (Option*) ((unsigned long long) ptr & ~1ull); + static Option* untag(Option* ptr) { + return (Option*)((unsigned long long)ptr & ~1ull); } - static bool isTagged(Option* ptr) - { - return ((unsigned long long) ptr & 1); + static bool isTagged(Option* ptr) { + return ((unsigned long long)ptr & 1); } }; @@ -883,21 +858,19 @@ class Option * }; * @endcode */ -struct Arg -{ +struct Arg { //! @brief For options that don't take an argument: Returns ARG_NONE. - static ArgStatus None(const Option&, bool) - { + static ArgStatus None(const Option&, bool) { return ARG_NONE; } //! @brief Returns ARG_OK if the argument is attached and ARG_IGNORE otherwise. - static ArgStatus Optional(const Option& option, bool) - { - if (option.arg && option.name[option.namelen] != 0) + static ArgStatus Optional(const Option& option, bool) { + if (option.arg && option.name[option.namelen] != 0) { return ARG_OK; - else + } else { return ARG_IGNORE; + } } }; @@ -910,8 +883,7 @@ struct Arg * Stats work cumulative. You can first pass in your default options and then the real * options and afterwards the counts will reflect the union. */ -struct Stats -{ +struct Stats { /** * @brief Number of elements needed for a @c buffer[] array to be used for * @ref Parser::parse() "parsing" the same argument vectors that were fed @@ -939,8 +911,7 @@ struct Stats /** * @brief Creates a Stats object with counts set to 1 (for the sentinel element). */ - Stats() : - buffer_max(1), options_max(1) // 1 more than necessary as sentinel + Stats() : buffer_max(1), options_max(1) // 1 more than necessary as sentinel { } @@ -953,35 +924,31 @@ struct Stats * The calls to Stats methods must match the later calls to Parser methods. * See Parser::parse() for the meaning of the arguments. */ - Stats(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) : - buffer_max(1), options_max(1) // 1 more than necessary as sentinel + Stats(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) : buffer_max(1), options_max(1) // 1 more than necessary as sentinel { add(gnu, usage, argc, argv, min_abbr_len, single_minus_longopt); } //! @brief Stats(...) with non-const argv. - Stats(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) : - buffer_max(1), options_max(1) // 1 more than necessary as sentinel + Stats(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) : buffer_max(1), options_max(1) // 1 more than necessary as sentinel { - add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); + add(gnu, usage, argc, (const char**)argv, min_abbr_len, single_minus_longopt); } //! @brief POSIX Stats(...) (gnu==false). - Stats(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) : - buffer_max(1), options_max(1) // 1 more than necessary as sentinel + Stats(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) : buffer_max(1), options_max(1) // 1 more than necessary as sentinel { add(false, usage, argc, argv, min_abbr_len, single_minus_longopt); } //! @brief POSIX Stats(...) (gnu==false) with non-const argv. - Stats(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) : - buffer_max(1), options_max(1) // 1 more than necessary as sentinel + Stats(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) : buffer_max(1), options_max(1) // 1 more than necessary as sentinel { - add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); + add(false, usage, argc, (const char**)argv, min_abbr_len, single_minus_longopt); } /** @@ -993,30 +960,28 @@ struct Stats * The calls to Stats methods must match the later calls to Parser methods. * See Parser::parse() for the meaning of the arguments. */ - void add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // + void add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // bool single_minus_longopt = false); //! @brief add() with non-const argv. - void add(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) - { - add(gnu, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); + void add(bool gnu, const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) { + add(gnu, usage, argc, (const char**)argv, min_abbr_len, single_minus_longopt); } //! @brief POSIX add() (gnu==false). - void add(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) - { + void add(const Descriptor usage[], int argc, const char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) { add(false, usage, argc, argv, min_abbr_len, single_minus_longopt); } //! @brief POSIX add() (gnu==false) with non-const argv. - void add(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // - bool single_minus_longopt = false) - { - add(false, usage, argc, (const char**) argv, min_abbr_len, single_minus_longopt); + void add(const Descriptor usage[], int argc, char** argv, int min_abbr_len = 0, // + bool single_minus_longopt = false) { + add(false, usage, argc, (const char**)argv, min_abbr_len, single_minus_longopt); } -private: + + private: class CountOptionsAction; }; @@ -1040,20 +1005,16 @@ struct Stats * ... * @endcode */ -class Parser -{ - int op_count; //!< @internal @brief see optionsCount() - int nonop_count; //!< @internal @brief see nonOptionsCount() - const char** nonop_args; //!< @internal @brief see nonOptions() - bool err; //!< @internal @brief see error() -public: - +class Parser { + int op_count; //!< @internal @brief see optionsCount() + int nonop_count; //!< @internal @brief see nonOptionsCount() + const char** nonop_args; //!< @internal @brief see nonOptions() + bool err; //!< @internal @brief see error() + public: /** * @brief Creates a new Parser. */ - Parser() : - op_count(0), nonop_count(0), nonop_args(0), err(false) - { + Parser() : op_count(0), nonop_count(0), nonop_args(0), err(false) { } /** @@ -1061,34 +1022,26 @@ class Parser * @copydetails parse() */ Parser(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], - int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : - op_count(0), nonop_count(0), nonop_args(0), err(false) - { + int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : op_count(0), nonop_count(0), nonop_args(0), err(false) { parse(gnu, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } //! @brief Parser(...) with non-const argv. Parser(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], - int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : - op_count(0), nonop_count(0), nonop_args(0), err(false) - { - parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); + int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) : op_count(0), nonop_count(0), nonop_args(0), err(false) { + parse(gnu, usage, argc, (const char**)argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } //! @brief POSIX Parser(...) (gnu==false). Parser(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], int min_abbr_len = 0, - bool single_minus_longopt = false, int bufmax = -1) : - op_count(0), nonop_count(0), nonop_args(0), err(false) - { + bool single_minus_longopt = false, int bufmax = -1) : op_count(0), nonop_count(0), nonop_args(0), err(false) { parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } //! @brief POSIX Parser(...) (gnu==false) with non-const argv. Parser(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0, - bool single_minus_longopt = false, int bufmax = -1) : - op_count(0), nonop_count(0), nonop_args(0), err(false) - { - parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); + bool single_minus_longopt = false, int bufmax = -1) : op_count(0), nonop_count(0), nonop_args(0), err(false) { + parse(false, usage, argc, (const char**)argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } /** @@ -1152,23 +1105,20 @@ class Parser //! @brief parse() with non-const argv. void parse(bool gnu, const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], - int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) - { - parse(gnu, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); + int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) { + parse(gnu, usage, argc, (const char**)argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } //! @brief POSIX parse() (gnu==false). void parse(const Descriptor usage[], int argc, const char** argv, Option options[], Option buffer[], - int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) - { + int min_abbr_len = 0, bool single_minus_longopt = false, int bufmax = -1) { parse(false, usage, argc, argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } //! @brief POSIX parse() (gnu==false) with non-const argv. void parse(const Descriptor usage[], int argc, char** argv, Option options[], Option buffer[], int min_abbr_len = 0, - bool single_minus_longopt = false, int bufmax = -1) - { - parse(false, usage, argc, (const char**) argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); + bool single_minus_longopt = false, int bufmax = -1) { + parse(false, usage, argc, (const char**)argv, options, buffer, min_abbr_len, single_minus_longopt, bufmax); } /** @@ -1180,8 +1130,7 @@ class Parser * @li The count (and the buffer[]) includes unknown options if they are collected * (see Descriptor::longopt). */ - int optionsCount() - { + int optionsCount() { return op_count; } @@ -1199,8 +1148,7 @@ class Parser * user does not supply any non-option arguments the defaults will still be in * effect. */ - int nonOptionsCount() - { + int nonOptionsCount() { return nonop_count; } @@ -1215,16 +1163,14 @@ class Parser * that actually encounter non-option arguments. A parse() call that encounters only * options, will not change nonOptions(). */ - const char** nonOptions() - { + const char** nonOptions() { return nonop_args; } /** * @brief Returns nonOptions()[i] (@e without checking if i is in range!). */ - const char* nonOption(int i) - { + const char* nonOption(int i) { return nonOptions()[i]; } @@ -1243,12 +1189,11 @@ class Parser * @endcode * */ - bool error() - { + bool error() { return err; } -private: + private: friend struct Stats; class StoreOptionAction; struct Action; @@ -1275,11 +1220,12 @@ class Parser * streq("foo=bar", "foo") == false * @endcode */ - static bool streq(const char* st1, const char* st2) - { - while (*st1 != 0) - if (*st1++ != *st2++) + static bool streq(const char* st1, const char* st2) { + while (*st1 != 0) { + if (*st1++ != *st2++) { return false; + } + } return (*st2 == 0 || *st2 == '='); } @@ -1307,11 +1253,9 @@ class Parser * streqabbr("foo", "foo" ,) == true * @endcode */ - static bool streqabbr(const char* st1, const char* st2, long long min) - { + static bool streqabbr(const char* st1, const char* st2, long long min) { const char* st1start = st1; - while (*st1 != 0 && (*st1 == *st2)) - { + while (*st1 != 0 && (*st1 == *st2)) { ++st1; ++st2; } @@ -1325,10 +1269,10 @@ class Parser * * Returns @c true for @c ch==0 . */ - static bool instr(char ch, const char* st) - { - while (*st != 0 && *st != ch) + static bool instr(char ch, const char* st) { + while (*st != 0 && *st != ch) { ++st; + } return *st == ch; } @@ -1337,10 +1281,8 @@ class Parser * @brief Rotates args[-count],...,args[-1],args[0] to become * args[0],args[-count],...,args[-1]. */ - static void shift(const char** args, int count) - { - for (int i = 0; i > -count; --i) - { + static void shift(const char** args, int count) { + for (int i = 0; i > -count; --i) { const char* temp = args[i]; args[i] = args[i - 1]; args[i - 1] = temp; @@ -1353,8 +1295,7 @@ class Parser * @brief Interface for actions Parser::workhorse() should perform for each Option it * parses. */ -struct Parser::Action -{ +struct Parser::Action { /** * @brief Called by Parser::workhorse() for each Option that has been successfully * parsed (including unknown @@ -1363,8 +1304,7 @@ struct Parser::Action * * Returns @c false iff a fatal error has occured and the parse should be aborted. */ - virtual bool perform(Option&) - { + virtual bool perform(Option&) { return true; } @@ -1376,10 +1316,9 @@ struct Parser::Action * @return * @c false iff a fatal error has occurred. */ - virtual bool finished(int numargs, const char** args) - { - (void) numargs; - (void) args; + virtual bool finished(int numargs, const char** args) { + (void)numargs; + (void)args; return true; } }; @@ -1389,23 +1328,21 @@ struct Parser::Action * @brief An Action to pass to Parser::workhorse() that will increment a counter for * each parsed Option. */ -class Stats::CountOptionsAction: public Parser::Action -{ +class Stats::CountOptionsAction : public Parser::Action { unsigned* buffer_max; -public: + + public: /** * Creates a new CountOptionsAction that will increase @c *buffer_max_ for each * parsed Option. */ - CountOptionsAction(unsigned* buffer_max_) : - buffer_max(buffer_max_) - { + CountOptionsAction(unsigned* buffer_max_) : buffer_max(buffer_max_) { } - bool perform(Option&) - { - if (*buffer_max == 0x7fffffff) - return false; // overflow protection: don't accept number of options that doesn't fit signed int + bool perform(Option&) { + if (*buffer_max == 0x7fffffff) { + return false; // overflow protection: don't accept number of options that doesn't fit signed int + } ++*buffer_max; return true; } @@ -1416,13 +1353,12 @@ class Stats::CountOptionsAction: public Parser::Action * @brief An Action to pass to Parser::workhorse() that will store each parsed Option in * appropriate arrays (see Parser::parse()). */ -class Parser::StoreOptionAction: public Parser::Action -{ +class Parser::StoreOptionAction : public Parser::Action { Parser& parser; Option* options; Option* buffer; - int bufmax; //! Number of slots in @c buffer. @c -1 means "large enough". -public: + int bufmax; //! Number of slots in @c buffer. @c -1 means "large enough". + public: /** * @brief Creates a new StoreOption action. * @param parser_ the parser whose op_count should be updated. @@ -1430,43 +1366,40 @@ class Parser::StoreOptionAction: public Parser::Action * @param buffer_ each Option is appended to this array as long as there's a free slot. * @param bufmax_ number of slots in @c buffer_. @c -1 means "large enough". */ - StoreOptionAction(Parser& parser_, Option options_[], Option buffer_[], int bufmax_) : - parser(parser_), options(options_), buffer(buffer_), bufmax(bufmax_) - { + StoreOptionAction(Parser& parser_, Option options_[], Option buffer_[], int bufmax_) : parser(parser_), options(options_), buffer(buffer_), bufmax(bufmax_) { // find first empty slot in buffer (if any) int bufidx = 0; - while ((bufmax < 0 || bufidx < bufmax) && buffer[bufidx]) + while ((bufmax < 0 || bufidx < bufmax) && buffer[bufidx]) { ++bufidx; + } // set parser's optionCount parser.op_count = bufidx; } - bool perform(Option& option) - { - if (bufmax < 0 || parser.op_count < bufmax) - { - if (parser.op_count == 0x7fffffff) - return false; // overflow protection: don't accept number of options that doesn't fit signed int + bool perform(Option& option) { + if (bufmax < 0 || parser.op_count < bufmax) { + if (parser.op_count == 0x7fffffff) { + return false; // overflow protection: don't accept number of options that doesn't fit signed int + } buffer[parser.op_count] = option; int idx = buffer[parser.op_count].desc->index; - if (options[idx]) + if (options[idx]) { options[idx].append(buffer[parser.op_count]); - else + } else { options[idx] = buffer[parser.op_count]; + } ++parser.op_count; } - return true; // NOTE: an option that is discarded because of a full buffer is not fatal + return true; // NOTE: an option that is discarded because of a full buffer is not fatal } - bool finished(int numargs, const char** args) - { + bool finished(int numargs, const char** args) { // only overwrite non-option argument list if there's at least 1 // new non-option argument. Otherwise we keep the old list. This // makes it easy to use default non-option arguments. - if (numargs > 0) - { + if (numargs > 0) { parser.nonop_count = numargs; parser.nonop_args = args; } @@ -1476,21 +1409,19 @@ class Parser::StoreOptionAction: public Parser::Action }; inline void Parser::parse(bool gnu, const Descriptor usage[], int argc, const char** argv, Option options[], - Option buffer[], int min_abbr_len, bool single_minus_longopt, int bufmax) -{ + Option buffer[], int min_abbr_len, bool single_minus_longopt, int bufmax) { StoreOptionAction action(*this, options, buffer, bufmax); err = !workhorse(gnu, usage, argc, argv, action, single_minus_longopt, true, min_abbr_len); } inline void Stats::add(bool gnu, const Descriptor usage[], int argc, const char** argv, int min_abbr_len, - bool single_minus_longopt) -{ + bool single_minus_longopt) { // determine size of options array. This is the greatest index used in the usage + 1 int i = 0; - while (usage[i].shortopt != 0) - { - if (usage[i].index + 1 >= options_max) - options_max = (usage[i].index + 1) + 1; // 1 more than necessary as sentinel + while (usage[i].shortopt != 0) { + if (usage[i].index + 1 >= options_max) { + options_max = (usage[i].index + 1) + 1; // 1 more than necessary as sentinel + } ++i; } @@ -1500,120 +1431,123 @@ inline void Stats::add(bool gnu, const Descriptor usage[], int argc, const char* } inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, const char** args, Action& action, - bool single_minus_longopt, bool print_errors, int min_abbr_len) -{ + bool single_minus_longopt, bool print_errors, int min_abbr_len) { // protect against NULL pointer - if (args == 0) + if (args == 0) { numargs = 0; + } int nonops = 0; - while (numargs != 0 && *args != 0) - { - const char* param = *args; // param can be --long-option, -srto or non-option argument + while (numargs != 0 && *args != 0) { + const char* param = *args; // param can be --long-option, -srto or non-option argument // in POSIX mode the first non-option argument terminates the option list // a lone minus character is a non-option argument - if (param[0] != '-' || param[1] == 0) - { - if (gnu) - { + if (param[0] != '-' || param[1] == 0) { + if (gnu) { ++nonops; ++args; - if (numargs > 0) + if (numargs > 0) { --numargs; + } continue; - } - else + } else { break; + } } // -- terminates the option list. The -- itself is skipped. - if (param[1] == '-' && param[2] == 0) - { + if (param[1] == '-' && param[2] == 0) { shift(args, nonops); ++args; - if (numargs > 0) + if (numargs > 0) { --numargs; + } break; } bool handle_short_options; const char* longopt_name; - if (param[1] == '-') // if --long-option + if (param[1] == '-') // if --long-option { handle_short_options = false; longopt_name = param + 2; - } - else - { + } else { handle_short_options = true; - longopt_name = param + 1; //for testing a potential -long-option + longopt_name = param + 1; // for testing a potential -long-option } bool try_single_minus_longopt = single_minus_longopt; - bool have_more_args = (numargs > 1 || numargs < 0); // is referencing argv[1] valid? + bool have_more_args = (numargs > 1 || numargs < 0); // is referencing argv[1] valid? - do // loop over short options in group, for long options the body is executed only once + do // loop over short options in group, for long options the body is executed only once { int idx; const char* optarg; /******************** long option **********************/ - if (handle_short_options == false || try_single_minus_longopt) - { + if (handle_short_options == false || try_single_minus_longopt) { idx = 0; - while (usage[idx].longopt != 0 && !streq(usage[idx].longopt, longopt_name)) + while (usage[idx].longopt != 0 && !streq(usage[idx].longopt, longopt_name)) { ++idx; + } - if (usage[idx].longopt == 0 && min_abbr_len > 0) // if we should try to match abbreviated long options + if (usage[idx].longopt == 0 && min_abbr_len > 0) // if we should try to match abbreviated long options { int i1 = 0; - while (usage[i1].longopt != 0 && !streqabbr(usage[i1].longopt, longopt_name, min_abbr_len)) + while (usage[i1].longopt != 0 && !streqabbr(usage[i1].longopt, longopt_name, min_abbr_len)) { ++i1; - if (usage[i1].longopt != 0) - { // now test if the match is unambiguous by checking for another match + } + if (usage[i1].longopt != 0) { // now test if the match is unambiguous by checking for another match int i2 = i1 + 1; - while (usage[i2].longopt != 0 && !streqabbr(usage[i2].longopt, longopt_name, min_abbr_len)) + while (usage[i2].longopt != 0 && !streqabbr(usage[i2].longopt, longopt_name, min_abbr_len)) { ++i2; + } - if (usage[i2].longopt == 0) // if there was no second match it's unambiguous, so accept i1 as idx + if (usage[i2].longopt == 0) { // if there was no second match it's unambiguous, so accept i1 as idx idx = i1; + } } } // if we found something, disable handle_short_options (only relevant if single_minus_longopt) - if (usage[idx].longopt != 0) + if (usage[idx].longopt != 0) { handle_short_options = false; + } - try_single_minus_longopt = false; // prevent looking for longopt in the middle of shortopt group + try_single_minus_longopt = false; // prevent looking for longopt in the middle of shortopt group optarg = longopt_name; - while (*optarg != 0 && *optarg != '=') + while (*optarg != 0 && *optarg != '=') { ++optarg; - if (*optarg == '=') // attached argument + } + if (*optarg == '=') { // attached argument ++optarg; - else + } else { // possibly detached argument optarg = (have_more_args ? args[1] : 0); + } } /************************ short option ***********************************/ - if (handle_short_options) - { - if (*++param == 0) // point at the 1st/next option character - break; // end of short option group + if (handle_short_options) { + if (*++param == 0) { // point at the 1st/next option character + break; // end of short option group + } idx = 0; - while (usage[idx].shortopt != 0 && !instr(*param, usage[idx].shortopt)) + while (usage[idx].shortopt != 0 && !instr(*param, usage[idx].shortopt)) { ++idx; + } - if (param[1] == 0) // if the potential argument is separate + if (param[1] == 0) { // if the potential argument is separate optarg = (have_more_args ? args[1] : 0); - else + } else { // if the potential argument is attached optarg = param + 1; + } } const Descriptor* descriptor = &usage[idx]; @@ -1622,25 +1556,24 @@ inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, c { // look for dummy entry (shortopt == "" and longopt == "") to use as Descriptor for unknown options idx = 0; - while (usage[idx].shortopt != 0 && (usage[idx].shortopt[0] != 0 || usage[idx].longopt[0] != 0)) + while (usage[idx].shortopt != 0 && (usage[idx].shortopt[0] != 0 || usage[idx].longopt[0] != 0)) { ++idx; + } descriptor = (usage[idx].shortopt == 0 ? 0 : &usage[idx]); } - if (descriptor != 0) - { + if (descriptor != 0) { Option option(descriptor, param, optarg); - switch (descriptor->check_arg(option, print_errors)) - { + switch (descriptor->check_arg(option, print_errors)) { case ARG_ILLEGAL: - return false; // fatal + return false; // fatal case ARG_OK: // skip one element of the argument vector, if it's a separated argument - if (optarg != 0 && have_more_args && optarg == args[1]) - { + if (optarg != 0 && have_more_args && optarg == args[1]) { shift(args, nonops); - if (numargs > 0) + if (numargs > 0) { --numargs; + } ++args; } @@ -1654,27 +1587,31 @@ inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, c break; } - if (!action.perform(option)) + if (!action.perform(option)) { return false; + } } } while (handle_short_options); shift(args, nonops); ++args; - if (numargs > 0) + if (numargs > 0) { --numargs; + } - } // while + } // while - if (numargs > 0 && *args == 0) // It's a bug in the caller if numargs is greater than the actual number - numargs = 0; // of arguments, but as a service to the user we fix this if we spot it. + if (numargs > 0 && *args == 0) { // It's a bug in the caller if numargs is greater than the actual number + numargs = 0; // of arguments, but as a service to the user we fix this if we spot it. + } - if (numargs < 0) // if we don't know the number of remaining non-option arguments - { // we need to count them + if (numargs < 0) // if we don't know the number of remaining non-option arguments + { // we need to count them numargs = 0; - while (args[numargs] != 0) + while (args[numargs] != 0) { ++numargs; + } } return action.finished(numargs + nonops, args - nonops); @@ -1684,19 +1621,16 @@ inline bool Parser::workhorse(bool gnu, const Descriptor usage[], int numargs, c * @internal * @brief The implementation of option::printUsage(). */ -struct PrintUsageImplementation -{ +struct PrintUsageImplementation { /** * @internal * @brief Interface for Functors that write (part of) a string somewhere. */ - struct IStringWriter - { + struct IStringWriter { /** * @brief Writes the given number of chars beginning at the given pointer somewhere. */ - virtual void operator()(const char*, int) - { + virtual void operator()(const char*, int) { } }; @@ -1705,19 +1639,15 @@ struct PrintUsageImplementation * @brief Encapsulates a function with signature func(string, size) where * string can be initialized with a const char* and size with an int. */ - template - struct FunctionWriter: public IStringWriter - { + template + struct FunctionWriter : public IStringWriter { Function* write; - virtual void operator()(const char* str, int size) - { + virtual void operator()(const char* str, int size) { (*write)(str, size); } - FunctionWriter(Function* w) : - write(w) - { + FunctionWriter(Function* w) : write(w) { } }; @@ -1726,19 +1656,15 @@ struct PrintUsageImplementation * @brief Encapsulates a reference to an object with a write(string, size) * method like that of @c std::ostream. */ - template - struct OStreamWriter: public IStringWriter - { + template + struct OStreamWriter : public IStringWriter { OStream& ostream; - virtual void operator()(const char* str, int size) - { + virtual void operator()(const char* str, int size) { ostream.write(str, size); } - OStreamWriter(OStream& o) : - ostream(o) - { + OStreamWriter(OStream& o) : ostream(o) { } }; @@ -1747,19 +1673,15 @@ struct PrintUsageImplementation * @brief Like OStreamWriter but encapsulates a @c const reference, which is * typically a temporary object of a user class. */ - template - struct TemporaryWriter: public IStringWriter - { + template + struct TemporaryWriter : public IStringWriter { const Temporary& userstream; - virtual void operator()(const char* str, int size) - { + virtual void operator()(const char* str, int size) { userstream.write(str, size); } - TemporaryWriter(const Temporary& u) : - userstream(u) - { + TemporaryWriter(const Temporary& u) : userstream(u) { } }; @@ -1769,20 +1691,16 @@ struct PrintUsageImplementation * signature of the @c write() system call) * where fd can be initialized from an int, string from a const char* and size from an int. */ - template - struct SyscallWriter: public IStringWriter - { + template + struct SyscallWriter : public IStringWriter { Syscall* write; int fd; - virtual void operator()(const char* str, int size) - { + virtual void operator()(const char* str, int size) { (*write)(fd, str, size); } - SyscallWriter(Syscall* w, int f) : - write(w), fd(f) - { + SyscallWriter(Syscall* w, int f) : write(w), fd(f) { } }; @@ -1790,20 +1708,16 @@ struct PrintUsageImplementation * @internal * @brief Encapsulates a function with the same signature as @c std::fwrite(). */ - template - struct StreamWriter: public IStringWriter - { + template + struct StreamWriter : public IStringWriter { Function* fwrite; Stream* stream; - virtual void operator()(const char* str, int size) - { + virtual void operator()(const char* str, int size) { (*fwrite)(str, size, 1, stream); } - StreamWriter(Function* w, Stream* s) : - fwrite(w), stream(s) - { + StreamWriter(Function* w, Stream* s) : fwrite(w), stream(s) { } }; @@ -1811,8 +1725,7 @@ struct PrintUsageImplementation * @internal * @brief Sets i1 = max(i1, i2) */ - static void upmax(int& i1, int i2) - { + static void upmax(int& i1, int i2) { i1 = (i1 >= i2 ? i1 : i2); } @@ -1827,20 +1740,18 @@ struct PrintUsageImplementation * @param[in,out] x the current indentation. Set to @c want_x by this method. * @param want_x the desired indentation. */ - static void indent(IStringWriter& write, int& x, int want_x) - { + static void indent(IStringWriter& write, int& x, int want_x) { int indent = want_x - x; - if (indent < 0) - { + if (indent < 0) { write("\n", 1); indent = want_x; } - if (indent > 0) - { + if (indent > 0) { char space = ' '; - for (int i = 0; i < indent; ++i) + for (int i = 0; i < indent; ++i) { write(&space, 1); + } x = want_x; } } @@ -1863,15 +1774,12 @@ struct PrintUsageImplementation * 1B000...... * @endcode */ - static bool isWideChar(unsigned ch) - { - if (ch == 0x303F) + static bool isWideChar(unsigned ch) { + if (ch == 0x303F) { return false; + } - return ((0x1100 <= ch && ch <= 0x115F) || (0x2329 <= ch && ch <= 0x232A) || (0x2E80 <= ch && ch <= 0xA4C6) - || (0xA960 <= ch && ch <= 0xA97C) || (0xAC00 <= ch && ch <= 0xD7FB) || (0xF900 <= ch && ch <= 0xFAFF) - || (0xFE10 <= ch && ch <= 0xFE6B) || (0xFF01 <= ch && ch <= 0xFF60) || (0xFFE0 <= ch && ch <= 0xFFE6) - || (0x1B000 <= ch)); + return ((0x1100 <= ch && ch <= 0x115F) || (0x2329 <= ch && ch <= 0x232A) || (0x2E80 <= ch && ch <= 0xA4C6) || (0xA960 <= ch && ch <= 0xA97C) || (0xAC00 <= ch && ch <= 0xD7FB) || (0xF900 <= ch && ch <= 0xFAFF) || (0xFE10 <= ch && ch <= 0xFE6B) || (0xFF01 <= ch && ch <= 0xFF60) || (0xFFE0 <= ch && ch <= 0xFFE6) || (0x1B000 <= ch)); } /** @@ -1910,55 +1818,50 @@ struct PrintUsageImplementation * the same number of columns will be returned for each row. * */ - class LinePartIterator - { - const Descriptor* tablestart; //!< The 1st descriptor of the current table. - const Descriptor* rowdesc; //!< The Descriptor that contains the current row. - const char* rowstart; //!< Ptr to 1st character of current row within rowdesc->help. - const char* ptr; //!< Ptr to current part within the current row. - int col; //!< Index of current column. - int len; //!< Length of the current part (that ptr points at) in BYTES - int screenlen; //!< Length of the current part in screen columns (taking narrow/wide chars into account). - int max_line_in_block; //!< Greatest index of a line within the block. This is the number of \\v within the cell with the most \\vs. - int line_in_block; //!< Line index within the current cell of the current part. - int target_line_in_block; //!< Line index of the parts we should return to the user on this iteration. - bool hit_target_line; //!< Flag whether we encountered a part with line index target_line_in_block in the current cell. - - /** - * @brief Determines the byte and character lengths of the part at @ref ptr and + class LinePartIterator { + const Descriptor* tablestart; //!< The 1st descriptor of the current table. + const Descriptor* rowdesc; //!< The Descriptor that contains the current row. + const char* rowstart; //!< Ptr to 1st character of current row within rowdesc->help. + const char* ptr; //!< Ptr to current part within the current row. + int col; //!< Index of current column. + int len; //!< Length of the current part (that ptr points at) in BYTES + int screenlen; //!< Length of the current part in screen columns (taking narrow/wide chars into account). + int max_line_in_block; //!< Greatest index of a line within the block. This is the number of \\v within the cell with the most \\vs. + int line_in_block; //!< Line index within the current cell of the current part. + int target_line_in_block; //!< Line index of the parts we should return to the user on this iteration. + bool hit_target_line; //!< Flag whether we encountered a part with line index target_line_in_block in the current cell. + + /** + * @brief Determines the byte and character lengths of the part at @ref ptr and * stores them in @ref len and @ref screenlen respectively. */ - void update_length() - { + void update_length() { screenlen = 0; - for (len = 0; ptr[len] != 0 && ptr[len] != '\v' && ptr[len] != '\t' && ptr[len] != '\n'; ++len) - { + for (len = 0; ptr[len] != 0 && ptr[len] != '\v' && ptr[len] != '\t' && ptr[len] != '\n'; ++len) { ++screenlen; - unsigned ch = (unsigned char) ptr[len]; - if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte + unsigned ch = (unsigned char)ptr[len]; + if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte { // int __builtin_clz (unsigned int x) // Returns the number of leading 0-bits in x, starting at the most significant bit - unsigned mask = (unsigned) -1 >> __builtin_clz(ch ^ 0xff); - ch = ch & mask; // mask out length bits, we don't verify their correctness - while (((unsigned char) ptr[len + 1] ^ 0x80) <= 0x3F) // while next byte is continuation byte + unsigned mask = (unsigned)-1 >> __builtin_clz(ch ^ 0xff); + ch = ch & mask; // mask out length bits, we don't verify their correctness + while (((unsigned char)ptr[len + 1] ^ 0x80) <= 0x3F) // while next byte is continuation byte { - ch = (ch << 6) ^ (unsigned char) ptr[len + 1] ^ 0x80; // add continuation to char code + ch = (ch << 6) ^ (unsigned char)ptr[len + 1] ^ 0x80; // add continuation to char code ++len; } // ch is the decoded unicode code point - if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case + if (ch >= 0x1100 && isWideChar(ch)) { // the test for 0x1100 is here to avoid the function call in the Latin case ++screenlen; + } } } } - public: + public: //! @brief Creates an iterator for @c usage. - LinePartIterator(const Descriptor usage[]) : - tablestart(usage), rowdesc(0), rowstart(0), ptr(0), col(-1), len(0), max_line_in_block(0), line_in_block(0), - target_line_in_block(0), hit_target_line(true) - { + LinePartIterator(const Descriptor usage[]) : tablestart(usage), rowdesc(0), rowstart(0), ptr(0), col(-1), len(0), max_line_in_block(0), line_in_block(0), target_line_in_block(0), hit_target_line(true) { } /** @@ -1966,19 +1869,19 @@ struct PrintUsageImplementation * LinePartIterator to move to the 1st table. * @retval false if moving to next table failed because no further table exists. */ - bool nextTable() - { + bool nextTable() { // If this is NOT the first time nextTable() is called after the constructor, // then skip to the next table break (i.e. a Descriptor with help == 0) - if (rowdesc != 0) - { - while (tablestart->help != 0 && tablestart->shortopt != 0) + if (rowdesc != 0) { + while (tablestart->help != 0 && tablestart->shortopt != 0) { ++tablestart; + } } // Find the next table after the break (if any) - while (tablestart->help == 0 && tablestart->shortopt != 0) + while (tablestart->help == 0 && tablestart->shortopt != 0) { ++tablestart; + } restartTable(); return rowstart != 0; @@ -1987,8 +1890,7 @@ struct PrintUsageImplementation /** * @brief Reset iteration to the beginning of the current table. */ - void restartTable() - { + void restartTable() { rowdesc = tablestart; rowstart = tablestart->help; ptr = 0; @@ -1999,26 +1901,24 @@ struct PrintUsageImplementation * @ref nextTable() to move to the 1st row of the table. * @retval false if moving to next row failed because no further row exists. */ - bool nextRow() - { - if (ptr == 0) - { + bool nextRow() { + if (ptr == 0) { restartRow(); return rowstart != 0; } - while (*ptr != 0 && *ptr != '\n') + while (*ptr != 0 && *ptr != '\n') { ++ptr; + } - if (*ptr == 0) - { - if ((rowdesc + 1)->help == 0) // table break + if (*ptr == 0) { + if ((rowdesc + 1)->help == 0) { // table break return false; + } ++rowdesc; rowstart = rowdesc->help; - } - else // if (*ptr == '\n') + } else // if (*ptr == '\n') { rowstart = ptr + 1; } @@ -2030,8 +1930,7 @@ struct PrintUsageImplementation /** * @brief Reset iteration to the beginning of the current row. */ - void restartRow() - { + void restartRow() { ptr = rowstart; col = -1; len = 0; @@ -2049,30 +1948,27 @@ struct PrintUsageImplementation * * See @ref LinePartIterator for details about the iteration. */ - bool next() - { - if (ptr == 0) + bool next() { + if (ptr == 0) { return false; + } - if (col == -1) - { + if (col == -1) { col = 0; update_length(); return true; } ptr += len; - while (true) - { - switch (*ptr) - { + while (true) { + switch (*ptr) { case '\v': upmax(max_line_in_block, ++line_in_block); ++ptr; break; case '\t': - if (!hit_target_line) // if previous column did not have the targetline - { // then "insert" a 0-length part + if (!hit_target_line) // if previous column did not have the targetline + { // then "insert" a 0-length part update_length(); hit_target_line = true; return true; @@ -2085,15 +1981,14 @@ struct PrintUsageImplementation break; case 0: case '\n': - if (!hit_target_line) // if previous column did not have the targetline - { // then "insert" a 0-length part + if (!hit_target_line) // if previous column did not have the targetline + { // then "insert" a 0-length part update_length(); hit_target_line = true; return true; } - if (++target_line_in_block > max_line_in_block) - { + if (++target_line_in_block > max_line_in_block) { update_length(); return false; } @@ -2106,23 +2001,21 @@ struct PrintUsageImplementation default: ++ptr; continue; - } // switch + } // switch - if (line_in_block == target_line_in_block) - { + if (line_in_block == target_line_in_block) { update_length(); hit_target_line = true; return true; } - } // while + } // while } /** * @brief Returns the index (counting from 0) of the column in which * the part pointed to by @ref data() is located. */ - int column() - { + int column() { return col; } @@ -2130,16 +2023,14 @@ struct PrintUsageImplementation * @brief Returns the index (counting from 0) of the line within the current column * this part belongs to. */ - int line() - { - return target_line_in_block; // NOT line_in_block !!! It would be wrong if !hit_target_line + int line() { + return target_line_in_block; // NOT line_in_block !!! It would be wrong if !hit_target_line } /** * @brief Returns the length of the part pointed to by @ref data() in raw chars (not UTF-8 characters). */ - int length() - { + int length() { return len; } @@ -2147,16 +2038,14 @@ struct PrintUsageImplementation * @brief Returns the width in screen columns of the part pointed to by @ref data(). * Takes multi-byte UTF-8 sequences and wide characters into account. */ - int screenLength() - { + int screenLength() { return screenlen; } /** * @brief Returns the current part of the iteration. */ - const char* data() - { + const char* data() { return ptr; } }; @@ -2185,9 +2074,8 @@ struct PrintUsageImplementation * output the string must be output piecemeal, interleaved with * the data from the other columns. */ - class LineWrapper - { - static const int bufmask = 15; //!< Must be a power of 2 minus 1. + class LineWrapper { + static const int bufmask = 15; //!< Must be a power of 2 minus 1. /** * @brief Ring buffer for length component of pair (data, length). */ @@ -2207,8 +2095,8 @@ struct PrintUsageImplementation * @brief The width of the column to line wrap. */ int width; - int head; //!< @brief index for next write - int tail; //!< @brief index for next read - 1 (i.e. increment tail BEFORE read) + int head; //!< @brief index for next write + int tail; //!< @brief index for next read - 1 (i.e. increment tail BEFORE read) /** * @brief Multiple methods of LineWrapper may decide to flush part of the buffer to @@ -2219,26 +2107,22 @@ struct PrintUsageImplementation */ bool wrote_something; - bool buf_empty() - { + bool buf_empty() { return ((tail + 1) & bufmask) == head; } - bool buf_full() - { + bool buf_full() { return tail == head; } - void buf_store(const char* data, int len) - { + void buf_store(const char* data, int len) { lenbuf[head] = len; datbuf[head] = data; head = (head + 1) & bufmask; } //! @brief Call BEFORE reading ...buf[tail]. - void buf_next() - { + void buf_next() { tail = (tail + 1) & bufmask; } @@ -2246,10 +2130,10 @@ struct PrintUsageImplementation * @brief Writes (data,len) into the ring buffer. If the buffer is full, a single line * is flushed out of the buffer into @c write. */ - void output(IStringWriter& write, const char* data, int len) - { - if (buf_full()) + void output(IStringWriter& write, const char* data, int len) { + if (buf_full()) { write_one_line(write); + } buf_store(data, len); } @@ -2257,39 +2141,38 @@ struct PrintUsageImplementation /** * @brief Writes a single line of output from the buffer to @c write. */ - void write_one_line(IStringWriter& write) - { - if (wrote_something) // if we already wrote something, we need to start a new line + void write_one_line(IStringWriter& write) { + if (wrote_something) // if we already wrote something, we need to start a new line { write("\n", 1); int _ = 0; indent(write, _, x); } - if (!buf_empty()) - { + if (!buf_empty()) { buf_next(); write(datbuf[tail], lenbuf[tail]); } wrote_something = true; } - public: + public: /** * @brief Writes out all remaining data from the LineWrapper using @c write. * Unlike @ref process() this method indents all lines including the first and * will output a \\n at the end (but only if something has been written). */ - void flush(IStringWriter& write) - { - if (buf_empty()) + void flush(IStringWriter& write) { + if (buf_empty()) { return; + } int _ = 0; indent(write, _, x); wrote_something = false; - while (!buf_empty()) + while (!buf_empty()) { write_one_line(write); + } write("\n", 1); } @@ -2311,42 +2194,39 @@ struct PrintUsageImplementation * @param data the new chunk of data to write. * @param len the length of the chunk of data to write. */ - void process(IStringWriter& write, const char* data, int len) - { + void process(IStringWriter& write, const char* data, int len) { wrote_something = false; - while (len > 0) - { - if (len <= width) // quick test that works because utf8width <= len (all wide chars have at least 2 bytes) + while (len > 0) { + if (len <= width) // quick test that works because utf8width <= len (all wide chars have at least 2 bytes) { output(write, data, len); len = 0; - } - else // if (len > width) it's possible (but not guaranteed) that utf8len > width + } else // if (len > width) it's possible (but not guaranteed) that utf8len > width { int utf8width = 0; int maxi = 0; - while (maxi < len && utf8width < width) - { + while (maxi < len && utf8width < width) { int charbytes = 1; - unsigned ch = (unsigned char) data[maxi]; - if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte + unsigned ch = (unsigned char)data[maxi]; + if (ch > 0xC1) // everything <= 0xC1 (yes, even 0xC1 itself) is not a valid UTF-8 start byte { // int __builtin_clz (unsigned int x) // Returns the number of leading 0-bits in x, starting at the most significant bit - unsigned mask = (unsigned) -1 >> __builtin_clz(ch ^ 0xff); - ch = ch & mask; // mask out length bits, we don't verify their correctness - while ((maxi + charbytes < len) && // - (((unsigned char) data[maxi + charbytes] ^ 0x80) <= 0x3F)) // while next byte is continuation byte + unsigned mask = (unsigned)-1 >> __builtin_clz(ch ^ 0xff); + ch = ch & mask; // mask out length bits, we don't verify their correctness + while ((maxi + charbytes < len) && // + (((unsigned char)data[maxi + charbytes] ^ 0x80) <= 0x3F)) // while next byte is continuation byte { - ch = (ch << 6) ^ (unsigned char) data[maxi + charbytes] ^ 0x80; // add continuation to char code + ch = (ch << 6) ^ (unsigned char)data[maxi + charbytes] ^ 0x80; // add continuation to char code ++charbytes; } // ch is the decoded unicode code point - if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case + if (ch >= 0x1100 && isWideChar(ch)) // the test for 0x1100 is here to avoid the function call in the Latin case { - if (utf8width + 2 > width) + if (utf8width + 2 > width) { break; + } ++utf8width; } } @@ -2357,26 +2237,24 @@ struct PrintUsageImplementation // data[maxi-1] is the last byte of the UTF-8 sequence of the last character that fits // onto the 1st line. If maxi == len, all characters fit on the line. - if (maxi == len) - { + if (maxi == len) { output(write, data, len); len = 0; - } - else // if (maxi < len) at least 1 character (data[maxi] that is) doesn't fit on the line + } else // if (maxi < len) at least 1 character (data[maxi] that is) doesn't fit on the line { int i; - for (i = maxi; i >= 0; --i) - if (data[i] == ' ') + for (i = maxi; i >= 0; --i) { + if (data[i] == ' ') { break; + } + } - if (i >= 0) - { + if (i >= 0) { output(write, data, i); data += i + 1; len -= i + 1; - } - else // did not find a space to split at => split before data[maxi] - { // data[maxi] is always the beginning of a character, never a continuation byte + } else // did not find a space to split at => split before data[maxi] + { // data[maxi] is always the beginning of a character, never a continuation byte output(write, data, maxi); data += maxi; len -= maxi; @@ -2384,8 +2262,9 @@ struct PrintUsageImplementation } } } - if (!wrote_something) // if we didn't already write something to make space in the buffer - write_one_line(write); // write at most one line of actual output + if (!wrote_something) { // if we didn't already write something to make space in the buffer + write_one_line(write); // write at most one line of actual output + } } /** @@ -2394,11 +2273,10 @@ struct PrintUsageImplementation * * @c x1 gives the indentation LineWrapper uses if it needs to indent. */ - LineWrapper(int x1, int x2) : - x(x1), width(x2 - x1), head(0), tail(bufmask) - { - if (width < 2) // because of wide characters we need at least width 2 or the code breaks + LineWrapper(int x1, int x2) : x(x1), width(x2 - x1), head(0), tail(bufmask) { + if (width < 2) { // because of wide characters we need at least width 2 or the code breaks width = 2; + } } }; @@ -2407,52 +2285,50 @@ struct PrintUsageImplementation * @brief This is the implementation that is shared between all printUsage() templates. * Because all printUsage() templates share this implementation, there is no template bloat. */ - static void printUsage(IStringWriter& write, const Descriptor usage[], int width = 80, // - int last_column_min_percent = 50, int last_column_own_line_max_percent = 75) - { - if (width < 1) // protect against nonsense values + static void printUsage(IStringWriter& write, const Descriptor usage[], int width = 80, // + int last_column_min_percent = 50, int last_column_own_line_max_percent = 75) { + if (width < 1) { // protect against nonsense values width = 80; + } - if (width > 10000) // protect against overflow in the following computation + if (width > 10000) { // protect against overflow in the following computation width = 10000; + } int last_column_min_width = ((width * last_column_min_percent) + 50) / 100; int last_column_own_line_max_width = ((width * last_column_own_line_max_percent) + 50) / 100; - if (last_column_own_line_max_width == 0) + if (last_column_own_line_max_width == 0) { last_column_own_line_max_width = 1; + } LinePartIterator part(usage); - while (part.nextTable()) - { - + while (part.nextTable()) { /***************** Determine column widths *******************************/ - const int maxcolumns = 8; // 8 columns are enough for everyone + const int maxcolumns = 8; // 8 columns are enough for everyone int col_width[maxcolumns]; int lastcolumn; int leftwidth; int overlong_column_threshold = 10000; - do - { + do { lastcolumn = 0; - for (int i = 0; i < maxcolumns; ++i) + for (int i = 0; i < maxcolumns; ++i) { col_width[i] = 0; + } part.restartTable(); - while (part.nextRow()) - { - while (part.next()) - { - if (part.column() < maxcolumns) - { + while (part.nextRow()) { + while (part.next()) { + if (part.column() < maxcolumns) { upmax(lastcolumn, part.column()); - if (part.screenLength() < overlong_column_threshold) + if (part.screenLength() < overlong_column_threshold) { // We don't let rows that don't use table separators (\t or \v) influence // the width of column 0. This allows the user to interject section headers // or explanatory paragraphs that do not participate in the table layout. - if (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' - || part.data()[part.length()] == '\v') + if (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' || part.data()[part.length()] == '\v') { upmax(col_width[part.column()], part.screenLength()); + } + } } } } @@ -2470,8 +2346,7 @@ struct PrintUsageImplementation leftwidth = 0; overlong_column_threshold = 0; - for (int i = 0; i < lastcolumn; ++i) - { + for (int i = 0; i < lastcolumn; ++i) { leftwidth += col_width[i]; upmax(overlong_column_threshold, col_width[i]); } @@ -2482,17 +2357,16 @@ struct PrintUsageImplementation int tabstop[maxcolumns]; tabstop[0] = 0; - for (int i = 1; i < maxcolumns; ++i) + for (int i = 1; i < maxcolumns; ++i) { tabstop[i] = tabstop[i - 1] + col_width[i - 1]; + } int rightwidth = width - tabstop[lastcolumn]; bool print_last_column_on_own_line = false; if (rightwidth < last_column_min_width && // if we don't have the minimum requested width for the last column - ( col_width[lastcolumn] == 0 || // and all last columns are > overlong_column_threshold - rightwidth < col_width[lastcolumn] // or there is at least one last column that requires more than the space available - ) - ) - { + (col_width[lastcolumn] == 0 || // and all last columns are > overlong_column_threshold + rightwidth < col_width[lastcolumn] // or there is at least one last column that requires more than the space available + )) { print_last_column_on_own_line = true; rightwidth = last_column_own_line_max_width; } @@ -2505,8 +2379,9 @@ struct PrintUsageImplementation // rightwidth==width => rightwidth>=last_column_min_width (unless someone passes // a bullshit value >100 for last_column_min_percent) => the above if condition // is false => print_last_column_on_own_line==false - if (lastcolumn == 0) + if (lastcolumn == 0) { print_last_column_on_own_line = false; + } LineWrapper lastColumnLineWrapper(width - rightwidth, width); LineWrapper interjectionLineWrapper(0, width); @@ -2515,50 +2390,43 @@ struct PrintUsageImplementation /***************** Print out all rows of the table *************************************/ - while (part.nextRow()) - { + while (part.nextRow()) { int x = -1; - while (part.next()) - { - if (part.column() > lastcolumn) - continue; // drop excess columns (can happen if lastcolumn == maxcolumns-1) + while (part.next()) { + if (part.column() > lastcolumn) { + continue; // drop excess columns (can happen if lastcolumn == maxcolumns-1) + } - if (part.column() == 0) - { - if (x >= 0) + if (part.column() == 0) { + if (x >= 0) { write("\n", 1); + } x = 0; } indent(write, x, tabstop[part.column()]); - if ((part.column() < lastcolumn) - && (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' - || part.data()[part.length()] == '\v')) - { + if ((part.column() < lastcolumn) && (part.column() > 0 || part.line() > 0 || part.data()[part.length()] == '\t' || part.data()[part.length()] == '\v')) { write(part.data(), part.length()); x += part.screenLength(); - } - else // either part.column() == lastcolumn or we are in the special case of - // an interjection that doesn't contain \v or \t + } else // either part.column() == lastcolumn or we are in the special case of + // an interjection that doesn't contain \v or \t { // NOTE: This code block is not necessarily executed for // each line, because some rows may have fewer columns. LineWrapper& lineWrapper = (part.column() == 0) ? interjectionLineWrapper : lastColumnLineWrapper; - if (!print_last_column_on_own_line || part.column() != lastcolumn) + if (!print_last_column_on_own_line || part.column() != lastcolumn) { lineWrapper.process(write, part.data(), part.length()); + } } - } // while + } // while - if (print_last_column_on_own_line) - { + if (print_last_column_on_own_line) { part.restartRow(); - while (part.next()) - { - if (part.column() == lastcolumn) - { + while (part.next()) { + if (part.column() == lastcolumn) { write("\n", 1); int _ = 0; indent(write, _, width - rightwidth); @@ -2573,9 +2441,7 @@ struct PrintUsageImplementation } } } - -} -; +}; /** * @brief Outputs a nicely formatted usage string with support for multi-column formatting @@ -2774,48 +2640,42 @@ struct PrintUsageImplementation * 67890 * @endcode */ -template +template void printUsage(OStream& prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, - int last_column_own_line_max_percent = 75) -{ + int last_column_own_line_max_percent = 75) { PrintUsageImplementation::OStreamWriter write(prn); PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); } -template +template void printUsage(Function* prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, - int last_column_own_line_max_percent = 75) -{ + int last_column_own_line_max_percent = 75) { PrintUsageImplementation::FunctionWriter write(prn); PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); } -template +template void printUsage(const Temporary& prn, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, - int last_column_own_line_max_percent = 75) -{ + int last_column_own_line_max_percent = 75) { PrintUsageImplementation::TemporaryWriter write(prn); PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); } -template +template void printUsage(Syscall* prn, int fd, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, - int last_column_own_line_max_percent = 75) -{ + int last_column_own_line_max_percent = 75) { PrintUsageImplementation::SyscallWriter write(prn, fd); PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); } -template -void printUsage(Function* prn, Stream* stream, const Descriptor usage[], int width = 80, int last_column_min_percent = - 50, - int last_column_own_line_max_percent = 75) -{ +template +void printUsage(Function* prn, Stream* stream, const Descriptor usage[], int width = 80, int last_column_min_percent = 50, + int last_column_own_line_max_percent = 75) { PrintUsageImplementation::StreamWriter write(prn, stream); PrintUsageImplementation::printUsage(write, usage, width, last_column_min_percent, last_column_own_line_max_percent); } -} +} // namespace option // namespace option #endif /* OPTIONPARSER_H_ */ diff --git a/collector/lib/system-inspector/Service.cpp b/collector/lib/system-inspector/Service.cpp index 04a7056d664..99b9fd2cbff 100644 --- a/collector/lib/system-inspector/Service.cpp +++ b/collector/lib/system-inspector/Service.cpp @@ -141,7 +141,9 @@ sinsp_evt* Service::GetNext() { auto parse_start = NowMicros(); auto res = inspector_->next(&event); - if (res != SCAP_SUCCESS || event == nullptr) return nullptr; + if (res != SCAP_SUCCESS || event == nullptr) { + return nullptr; + } #ifdef TRACE_SINSP_EVENTS // Do not allow to change sinsp events tracing at runtime, as the output @@ -157,7 +159,9 @@ sinsp_evt* Service::GetNext() { } #endif - if (event->get_category() & EC_INTERNAL) return nullptr; + if (event->get_category() & EC_INTERNAL) { + return nullptr; + } HostInfo& host_info = HostInfo::Instance(); @@ -259,12 +263,16 @@ void Service::Run(const std::atomic& control) { ServePendingProcessRequests(); sinsp_evt* evt = GetNext(); - if (!evt) continue; + if (!evt) { + continue; + } auto process_start = NowMicros(); for (auto it = signal_handlers_.begin(); it != signal_handlers_.end(); it++) { auto& signal_handler = *it; - if (!signal_handler.ShouldHandle(evt)) continue; + if (!signal_handler.ShouldHandle(evt)) { + continue; + } LogUnreasonableEventTime(process_start, evt); auto result = signal_handler.handler->HandleSignal(evt); if (result == SignalHandler::NEEDS_REFRESH) { @@ -335,7 +343,9 @@ void Service::CleanUp() { auto& request = pending_process_requests_.front(); auto callback = request.second.lock(); - if (callback) (*callback)(0); + if (callback) { + (*callback)(0); + } pending_process_requests_.pop_front(); } @@ -344,7 +354,9 @@ void Service::CleanUp() { bool Service::GetStats(system_inspector::Stats* stats) const { std::lock_guard libsinsp_lock(libsinsp_mutex_); std::lock_guard running_lock(running_mutex_); - if (!running_ || !inspector_) return false; + if (!running_ || !inspector_) { + return false; + } scap_stats kernel_stats; std::shared_ptr userspace_stats; @@ -359,8 +371,9 @@ bool Service::GetStats(system_inspector::Stats* stats) const { stats->nPreemptions = kernel_stats.n_preemptions; stats->nThreadCacheSize = inspector_->m_thread_manager->get_thread_count(); - if (userspace_stats != nullptr) + if (userspace_stats != nullptr) { stats->nDropsThreadCache = userspace_stats->m_n_drops_full_threadtable; + } return true; } diff --git a/collector/test/ConnTrackerTest.cpp b/collector/test/ConnTrackerTest.cpp index 84a40ff93c0..83e07445a6b 100644 --- a/collector/test/ConnTrackerTest.cpp +++ b/collector/test/ConnTrackerTest.cpp @@ -1223,16 +1223,18 @@ TEST(ConnTrackerTest, TestUpdateOldStateActiveExpiredConnectionRemovedFromOldSta void GetNextAddress(int address_parts[4], int& port) { for (int i = 0; i < 4; i++) { address_parts[i]++; - if (address_parts[i] < 256) + if (address_parts[i] < 256) { break; - else { + } else { address_parts[i] = 0; } } if (address_parts[3] == 256) { port++; - for (int i = 0; i < 4; i++) address_parts[i] = 0; + for (int i = 0; i < 4; i++) { + address_parts[i] = 0; + } } } @@ -1258,9 +1260,13 @@ void CreateFakeState(ConnMap& afterglow_state, int num_endpoints, int num_connec afterglow_state.insert({tempConn1, ConnStatus(time_micros, false)}); afterglow_state.insert({tempConn2, ConnStatus(time_micros, false)}); connection_idx += 2; - if (connection_idx > num_connections) break; + if (connection_idx > num_connections) { + break; + } + } + if (connection_idx > num_connections) { + break; } - if (connection_idx > num_connections) break; } } diff --git a/collector/test/NetworkStatusNotifierTest.cpp b/collector/test/NetworkStatusNotifierTest.cpp index 8cbcced3063..c6834c6ba13 100644 --- a/collector/test/NetworkStatusNotifierTest.cpp +++ b/collector/test/NetworkStatusNotifierTest.cpp @@ -42,8 +42,9 @@ class Semaphore { void acquire() { std::unique_lock lock(mutex_); - while (value_ <= 0) + while (value_ <= 0) { cond_.wait(lock); + } value_--; } @@ -52,9 +53,11 @@ class Semaphore { auto deadline = std::chrono::steady_clock::now() + rel_time; std::unique_lock lock(mutex_); - while (value_ <= 0) - if (cond_.wait_until(lock, deadline) == std::cv_status::timeout) + while (value_ <= 0) { + if (cond_.wait_until(lock, deadline) == std::cv_status::timeout) { return false; + } + } value_--; return true; } diff --git a/collector/test/ProtoAllocatorTest.cpp b/collector/test/ProtoAllocatorTest.cpp index 8809714412b..f0bdf0b9c33 100644 --- a/collector/test/ProtoAllocatorTest.cpp +++ b/collector/test/ProtoAllocatorTest.cpp @@ -11,8 +11,9 @@ namespace { TEST(ProtoAllocator, OverflowDefaultPool) { ProtoAllocator allocator; - for (unsigned int i = 0; i <= ProtoAllocator::kDefaultPoolSize / sizeof(sensor::NetworkConnectionInfoMessage); i++) + for (unsigned int i = 0; i <= ProtoAllocator::kDefaultPoolSize / sizeof(sensor::NetworkConnectionInfoMessage); i++) { allocator.AllocateRoot(); + } allocator.Reset(); }