diff --git a/.clang-tidy b/.clang-tidy index 82ea5c2108..41046ae7dc 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -10,6 +10,7 @@ Checks: [-*, cppcoreguidelines-virtual-class-destructor, # Skipping these temporarily because they are very noisy + -bugprone-forward-declaration-namespace, -bugprone-narrowing-conversions, -bugprone-unchecked-optional-access, -performance-unnecessary-value-param, @@ -63,3 +64,10 @@ Checks: [-*, -modernize-use-std-numbers, -modernize-use-std-print, ] + +HeaderFilterRegex: '.h' +ExcludeHeaderFilterRegex: '.*(auxil|3rdparty)/.*' +SystemHeaders: false +CheckOptions: + - key: modernize-use-default-member-init.UseAssignment + value: 'true' diff --git a/CHANGES b/CHANGES index dd0e70e345..b2ff8af546 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,21 @@ +8.0.0-dev.489 | 2025-06-23 10:36:38 -0700 + + * Deprecate BRO_PLUGIN_INSTALL_PATH constant (Tim Wojtulewicz, Corelight) + + * Make constants in IP::ParseResult uppercase, deprecate the old ones (Tim Wojtulewicz, Corelight) + + * Fix comparison against CapLen results in IPTunnel (Tim Wojtulewicz, Corelight) + + * Fix clang-tidy warnings in headers (Tim Wojtulewicz, Corelight) + + * Change clang-tidy configuration to also scan headers (Tim Wojtulewicz, Corelight) + + * Don't pass local source/binary directory to zeek_add_plugin for Redis backend (Tim Wojtulewicz, Corelight) + + * Update bifcl/binpac/gen-zam submodules with clang-tidy fixes (Tim Wojtulewicz, Corelight) + + * Avoid linting headers in external paths (Tim Wojtulewicz, Corelight) + 8.0.0-dev.447 | 2025-06-22 15:49:11 +0200 * GH-4594: Align WebSocket error in cluster with one in Broker (Benjamin Bannier, Corelight) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2dc52d478f..05ad9d0caa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1083,7 +1083,7 @@ set(USE_GEOIP false) find_package(LibMMDB) if (LIBMMDB_FOUND) set(USE_GEOIP true) - include_directories(BEFORE ${LibMMDB_INCLUDE_DIR}) + include_directories(BEFORE SYSTEM ${LibMMDB_INCLUDE_DIR}) list(APPEND OPTLIBS ${LibMMDB_LIBRARY}) endif () @@ -1091,7 +1091,7 @@ set(USE_KRB5 false) find_package(LibKrb5) if (LIBKRB5_FOUND) set(USE_KRB5 true) - include_directories(BEFORE ${LibKrb5_INCLUDE_DIR}) + include_directories(BEFORE SYSTEM ${LibKrb5_INCLUDE_DIR}) list(APPEND OPTLIBS ${LibKrb5_LIBRARY}) endif () @@ -1124,7 +1124,7 @@ endif () # dependencies which tend to be in standard system locations and thus cause the # system OpenSSL headers to still be picked up even if one specifies # --with-openssl (which may be common). -include_directories(BEFORE ${OPENSSL_INCLUDE_DIR}) +include_directories(BEFORE SYSTEM ${OPENSSL_INCLUDE_DIR}) # Determine if libfts is external to libc, i.e. musl find_package(FTS) diff --git a/VERSION b/VERSION index 67aaef6c49..22e4c84c99 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.0.0-dev.447 +8.0.0-dev.489 diff --git a/auxil/bifcl b/auxil/bifcl index 82eb0ce207..7f9204a4b2 160000 --- a/auxil/bifcl +++ b/auxil/bifcl @@ -1 +1 @@ -Subproject commit 82eb0ce207ef9d11bda880d3ff1287f9cd3b769e +Subproject commit 7f9204a4b294a8cacfff94409b79af2186fe6752 diff --git a/auxil/binpac b/auxil/binpac index e1bb430912..482afe31fb 160000 --- a/auxil/binpac +++ b/auxil/binpac @@ -1 +1 @@ -Subproject commit e1bb4309129abc475250d36ca6822624cd3036bb +Subproject commit 482afe31fb1e8b533f262b8f175d89d4cd972dda diff --git a/auxil/gen-zam b/auxil/gen-zam index f113c5f322..0af9a34884 160000 --- a/auxil/gen-zam +++ b/auxil/gen-zam @@ -1 +1 @@ -Subproject commit f113c5f3220263eca87c3ffaafae43fda3295ae3 +Subproject commit 0af9a348847e94c1a35cd026b13adecc40dcbaa1 diff --git a/cmake b/cmake index 26f313a644..e2211bc960 160000 --- a/cmake +++ b/cmake @@ -1 +1 @@ -Subproject commit 26f313a644e4430b0f2bd8dfbb1c992757ed84ae +Subproject commit e2211bc960fcd2ff8c50d8649ed4eca0d4a9c35c diff --git a/cmake_templates/zeek-config-paths.h.in b/cmake_templates/zeek-config-paths.h.in index be135e8b93..9cedf0d70e 100644 --- a/cmake_templates/zeek-config-paths.h.in +++ b/cmake_templates/zeek-config-paths.h.in @@ -2,10 +2,11 @@ #pragma once -#define ZEEK_SCRIPT_INSTALL_PATH "@ZEEK_SCRIPT_INSTALL_PATH@" -#define BRO_PLUGIN_INSTALL_PATH "@ZEEK_PLUGIN_DIR@" -#define ZEEK_PLUGIN_INSTALL_PATH "@ZEEK_PLUGIN_DIR@" -#define DEFAULT_ZEEKPATH "@DEFAULT_ZEEKPATH@" -#define ZEEK_SPICY_MODULE_PATH "@ZEEK_SPICY_MODULE_PATH@" -#define ZEEK_SPICY_LIBRARY_PATH "@ZEEK_SPICY_LIBRARY_PATH@" -#define ZEEK_SPICY_DATA_PATH "@ZEEK_SPICY_DATA_PATH@" +constexpr char ZEEK_SCRIPT_INSTALL_PATH[] = "@ZEEK_SCRIPT_INSTALL_PATH@"; +[[deprecated("Remove in v8.1. Use ZEEK_PLUGIN_INSTALL_PATH")]] constexpr char BRO_PLUGIN_INSTALL_PATH[] = + "@ZEEK_PLUGIN_DIR@"; +constexpr char ZEEK_PLUGIN_INSTALL_PATH[] = "@ZEEK_PLUGIN_DIR@"; +constexpr char DEFAULT_ZEEKPATH[] = "@DEFAULT_ZEEKPATH@"; +constexpr char ZEEK_SPICY_MODULE_PATH[] = "@ZEEK_SPICY_MODULE_PATH@"; +constexpr char ZEEK_SPICY_LIBRARY_PATH[] = "@ZEEK_SPICY_LIBRARY_PATH@"; +constexpr char ZEEK_SPICY_DATA_PATH[] = "@ZEEK_SPICY_DATA_PATH@"; diff --git a/cmake_templates/zeek-config.h.in b/cmake_templates/zeek-config.h.in index 9130ecc66e..ffbb08c1a8 100644 --- a/cmake_templates/zeek-config.h.in +++ b/cmake_templates/zeek-config.h.in @@ -1,4 +1,6 @@ // See the file "COPYING" in the main distribution directory for copyright. +// NOLINTBEGIN(modernize-macro-to-enum) +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #pragma once @@ -306,3 +308,6 @@ /* compiled with Spicy support */ #cmakedefine HAVE_SPICY + +// NOLINTEND(cppcoreguidelines-macro-usage) +// NOLINTEND(modernize-macro-to-enum) diff --git a/src/Anon.h b/src/Anon.h index 419a2afcf7..a8124e9c9a 100644 --- a/src/Anon.h +++ b/src/Anon.h @@ -20,14 +20,14 @@ namespace zeek::detail { // TODO: Anon.h may not be the right place to put these functions ... -enum ip_addr_anonymization_class_t { +enum ip_addr_anonymization_class_t : uint8_t { ORIG_ADDR, // client address RESP_ADDR, // server address OTHER_ADDR, NUM_ADDR_ANONYMIZATION_CLASSES, }; -enum ip_addr_anonymization_method_t { +enum ip_addr_anonymization_method_t : uint8_t { KEEP_ORIG_ADDR, SEQUENTIALLY_NUMBERED, RANDOM_MD5, diff --git a/src/Attr.h b/src/Attr.h index 06da50eb85..e44de83b20 100644 --- a/src/Attr.h +++ b/src/Attr.h @@ -24,7 +24,7 @@ namespace detail { class Expr; using ExprPtr = IntrusivePtr; -enum AttrTag { +enum AttrTag : uint8_t { ATTR_OPTIONAL, ATTR_DEFAULT, ATTR_DEFAULT_INSERT, // insert default value on failed lookups diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f8c5a42f51..31ae4fd073 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -465,15 +465,15 @@ set(MAIN_SRCS digest.h) set(THIRD_PARTY_SRCS - 3rdparty/zeek_inet_ntop.c - 3rdparty/bsd-getopt-long.c + $<$:3rdparty/sqlite3.c> 3rdparty/ConvertUTF.c + 3rdparty/bsd-getopt-long.c 3rdparty/in_cksum.cc 3rdparty/modp_numtoa.c 3rdparty/patricia.c 3rdparty/setsignal.c - $<$:3rdparty/sqlite3.c> - 3rdparty/strsep.c) + 3rdparty/strsep.c + 3rdparty/zeek_inet_ntop.c) if (USE_SQLITE AND WNOERROR_FLAG) set_source_files_properties(3rdparty/sqlite3.c PROPERTIES COMPILE_FLAGS ${WNOERROR_FLAG}) diff --git a/src/Conn.h b/src/Conn.h index 41fe4f4d85..95883b9b88 100644 --- a/src/Conn.h +++ b/src/Conn.h @@ -27,9 +27,6 @@ class RecordVal; using ValPtr = IntrusivePtr; using RecordValPtr = IntrusivePtr; -namespace session { -class Manager; -} namespace detail { class Specific_RE_Matcher; @@ -45,7 +42,7 @@ namespace packet_analysis::IP { class SessionAdapter; } -enum ConnEventToFlag { +enum ConnEventToFlag : uint8_t { NUL_IN_LINE, SINGULAR_CR, SINGULAR_LF, diff --git a/src/DNS_Mgr.cc b/src/DNS_Mgr.cc index e9e58208df..5604c18928 100644 --- a/src/DNS_Mgr.cc +++ b/src/DNS_Mgr.cc @@ -1414,6 +1414,8 @@ TableValPtr DNS_Mgr::empty_addr_set() { return make_intrusive(std::move(s)); } +DNS_Mgr::AsyncRequest::AsyncRequest(const IPAddr& addr) : addr(addr), type(T_PTR) {} + ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/DNS_Mgr.h b/src/DNS_Mgr.h index e7a7d8a3e7..6b7049c5f3 100644 --- a/src/DNS_Mgr.h +++ b/src/DNS_Mgr.h @@ -16,12 +16,15 @@ // These are defined in ares headers but we don't want to have to include // those headers here and create install dependencies on them. struct ares_channeldata; -typedef struct ares_channeldata* ares_channel; +using ares_channel = struct ares_channeldata*; + #ifndef T_PTR +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define T_PTR 12 #endif #ifndef T_TXT +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define T_TXT 16 #endif @@ -54,7 +57,7 @@ class DNS_Mapping; using DNS_MappingPtr = std::shared_ptr; class DNS_Request; -enum DNS_MgrMode { +enum DNS_MgrMode : uint8_t { DNS_PRIME, // used to prime the cache DNS_FORCE, // internal error if cache miss DNS_DEFAULT, // lookup names as they're requested @@ -320,7 +323,7 @@ protected: bool processed = false; AsyncRequest(std::string host, int request_type) : host(std::move(host)), type(request_type) {} - AsyncRequest(const IPAddr& addr) : addr(addr), type(T_PTR) {} + AsyncRequest(const IPAddr& addr); void Resolved(const std::string& name); void Resolved(TableValPtr addrs); diff --git a/src/DbgBreakpoint.h b/src/DbgBreakpoint.h index 18555acefe..b96c2ac0b1 100644 --- a/src/DbgBreakpoint.h +++ b/src/DbgBreakpoint.h @@ -12,9 +12,9 @@ namespace zeek::detail { class Stmt; class ParseLocationRec; -enum BreakCode { BC_NO_HIT, BC_HIT, BC_HIT_AND_DELETE }; +enum BreakCode : uint8_t { BC_NO_HIT, BC_HIT, BC_HIT_AND_DELETE }; class DbgBreakpoint { - enum Kind { BP_STMT = 0, BP_FUNC, BP_LINE, BP_TIME }; + enum Kind : uint8_t { BP_STMT = 0, BP_FUNC, BP_LINE, BP_TIME }; public: DbgBreakpoint(); diff --git a/src/Debug.h b/src/Debug.h index 422db2352f..3d256ca4a8 100644 --- a/src/Debug.h +++ b/src/Debug.h @@ -35,7 +35,7 @@ class DbgWatch; class DbgDisplay; // This needs to be defined before we do the includes that come after it. -enum ParseLocationRecType { PLR_UNKNOWN, PLR_FILE_AND_LINE, PLR_FUNCTION }; +enum ParseLocationRecType : uint8_t { PLR_UNKNOWN, PLR_FILE_AND_LINE, PLR_FUNCTION }; class ParseLocationRec { public: ParseLocationRecType type; diff --git a/src/DebugCmds.cc b/src/DebugCmds.cc index 6bfb08f581..708b8bc7aa 100644 --- a/src/DebugCmds.cc +++ b/src/DebugCmds.cc @@ -605,4 +605,6 @@ int dbg_cmd_trace(DebugCmd cmd, const vector& args) { return 0; } +int num_debug_cmds() { return static_cast(g_DebugCmdInfos.size()); } + } // namespace zeek::detail diff --git a/src/DebugCmds.h b/src/DebugCmds.h index 9be4095eb5..086f77f179 100644 --- a/src/DebugCmds.h +++ b/src/DebugCmds.h @@ -51,7 +51,7 @@ extern DebugCmdInfoQueue g_DebugCmdInfos; void init_global_dbg_constants(); -#define num_debug_cmds() (static_cast(g_DebugCmdInfos.size())) +extern int num_debug_cmds(); // Looks up the info record and returns it; if cmd is not found returns 0. const DebugCmdInfo* get_debug_cmd_info(DebugCmd cmd); @@ -68,6 +68,7 @@ int find_all_matching_cmds(const std::string& prefix, const char* array_of_match // These functions return <= 0 if failure, > 0 for success. // More particular return values are command-specific: see comments w/function. +// NOLINTNEXTLINE(modernize-use-using) typedef int DbgCmdFn(DebugCmd cmd, const std::vector& args); DbgCmdFn dbg_cmd_backtrace; diff --git a/src/DebugLogger.h b/src/DebugLogger.h index 04796fe17e..ec60197230 100644 --- a/src/DebugLogger.h +++ b/src/DebugLogger.h @@ -7,6 +7,7 @@ #ifdef DEBUG +#include #include #include #include @@ -15,6 +16,7 @@ #include // Needed to ignore __attribute__((format(printf))) on MSVC #endif +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #define DBG_LOG(stream, ...) \ if ( ::zeek::detail::debug_logger.IsEnabled(stream) ) \ ::zeek::detail::debug_logger.Log(stream, __VA_ARGS__) @@ -25,6 +27,7 @@ #define DBG_POP(stream) ::zeek::detail::debug_logger.PopIndent(stream) #define PLUGIN_DBG_LOG(plugin, ...) ::zeek::detail::debug_logger.Log(plugin, __VA_ARGS__) +// NOLINTEND(cppcoreguidelines-macro-usage) namespace zeek { @@ -35,7 +38,7 @@ class Plugin; // To add a new debugging stream, add a constant here as well as // an entry to DebugLogger::streams in DebugLogger.cc. -enum DebugStream { +enum DebugStream : uint8_t { DBG_SERIAL, // Serialization DBG_RULES, // Signature matching DBG_STRING, // String code @@ -67,10 +70,10 @@ namespace detail { class DebugLogger { public: // Output goes to stderr per default. - DebugLogger() : file(nullptr), all(false), verbose(false) {}; + DebugLogger() = default; ~DebugLogger(); - void OpenDebugLog(const char* filename = 0); + void OpenDebugLog(const char* filename = nullptr); void Log(DebugStream stream, const char* fmt, ...) __attribute__((format(printf, 3, 4))); void Log(const plugin::Plugin& plugin, const char* fmt, ...) __attribute__((format(printf, 3, 4))); @@ -98,14 +101,14 @@ public: void ShowStreamsHelp(); private: - FILE* file; - bool all; - bool verbose; + FILE* file = nullptr; + bool all = false; + bool verbose = false; struct Stream { - const char* prefix; - int indent; - bool enabled; + const char* prefix = nullptr; + int indent = 0; + bool enabled = false; }; std::set enabled_streams; @@ -123,9 +126,11 @@ extern DebugLogger debug_logger; } // namespace zeek #else +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #define DBG_LOG(...) #define DBG_LOG_VERBOSE(...) #define DBG_PUSH(stream) #define DBG_POP(stream) #define PLUGIN_DBG_LOG(plugin, ...) +// NOLINTEND(cppcoreguidelines-macro-usage) #endif diff --git a/src/Desc.h b/src/Desc.h index de09e37ad8..c2aa0bab3e 100644 --- a/src/Desc.h +++ b/src/Desc.h @@ -18,12 +18,12 @@ class IPPrefix; class File; class Type; -enum DescType { +enum DescType : uint8_t { DESC_READABLE, DESC_BINARY, }; -enum DescStyle { +enum DescStyle : uint8_t { STANDARD_STYLE, RAW_STYLE, }; diff --git a/src/Dict.h b/src/Dict.h index b53c7e6c99..44bcfeb4d4 100644 --- a/src/Dict.h +++ b/src/Dict.h @@ -30,7 +30,7 @@ namespace zeek { template class Dictionary; -enum DictOrder { ORDERED, UNORDERED }; +enum DictOrder : uint8_t { ORDERED, UNORDERED }; // A dict_delete_func that just calls delete. extern void generic_delete_func(void*); @@ -628,7 +628,7 @@ public: if ( max_entries < num_entries ) max_entries = num_entries; if ( num_entries > ThresholdEntries() ) - SizeUp(); + SizeUp(); // NOLINT(bugprone-branch-clone) // if space_distance is too great, performance decreases. we need to sizeup for // performance. @@ -790,11 +790,14 @@ public: int ExpectedCapacity() const { return bucket_capacity; } // Debugging -#define DUMPIF(f) \ - if ( f ) \ - Dump(1) - #ifdef ZEEK_DICT_DEBUG + void DumpIfInvalid(bool valid) const { + if ( ! valid ) { + Dump(1); + abort(); + } + } + void AssertValid() const { bool valid = true; int n = num_entries; @@ -805,8 +808,7 @@ public: n--; valid = (n == 0); - ASSERT(valid); - DUMPIF(! valid); + DumpIfInvalid(valid); // entries must clustered together for ( int i = 1; i < Capacity(); i++ ) { @@ -815,29 +817,28 @@ public: if ( table[i - 1].Empty() ) { valid = (table[i].distance == 0); - ASSERT(valid); - DUMPIF(! valid); + DumpIfInvalid(valid); } else { valid = (table[i].bucket >= table[i - 1].bucket); - ASSERT(valid); - DUMPIF(! valid); + DumpIfInvalid(valid); if ( table[i].bucket == table[i - 1].bucket ) { valid = (table[i].distance == table[i - 1].distance + 1); - ASSERT(valid); - DUMPIF(! valid); + DumpIfInvalid(valid); } else { valid = (table[i].distance <= table[i - 1].distance); - ASSERT(valid); - DUMPIF(! valid); + DumpIfInvalid(valid); } } } } + #endif // ZEEK_DICT_DEBUG + static constexpr size_t DICT_NUM_DISTANCES = 5; + void Dump(int level = 0) const { int key_size = 0; for ( int i = 0; i < Capacity(); i++ ) { @@ -848,7 +849,6 @@ public: continue; } -#define DICT_NUM_DISTANCES 5 int distances[DICT_NUM_DISTANCES]; int max_distance = 0; DistanceStats(max_distance, distances, DICT_NUM_DISTANCES); @@ -858,9 +858,9 @@ public: Capacity(), Length(), MaxLength(), (double)Length() / (table ? Capacity() : 1), max_distance, key_size / (Length() ? Length() : 1), log2_buckets, remaps, remap_end); if ( Length() > 0 ) { - for ( int i = 0; i < DICT_NUM_DISTANCES - 1; i++ ) - printf("[%d]%2d%% ", i, 100 * distances[i] / Length()); - printf("[%d+]%2d%% ", DICT_NUM_DISTANCES - 1, 100 * distances[DICT_NUM_DISTANCES - 1] / Length()); + for ( size_t i = 0; i < DICT_NUM_DISTANCES - 1; i++ ) + printf("[%zu]%2d%% ", i, 100 * distances[i] / Length()); + printf("[%zu+]%2d%% ", DICT_NUM_DISTANCES - 1, 100 * distances[DICT_NUM_DISTANCES - 1] / Length()); } else printf("\n"); @@ -880,7 +880,7 @@ public: } } - void DistanceStats(int& max_distance, int* distances = 0, int num_distances = 0) const { + void DistanceStats(int& max_distance, int* distances = nullptr, int num_distances = 0) const { max_distance = 0; for ( int i = 0; i < num_distances; i++ ) distances[i] = 0; @@ -937,8 +937,9 @@ public: for ( int idx = 0; idx < Capacity(); idx++ ) if ( ! table[idx].Empty() ) { std::string s((char*)table[idx].GetKey(), table[idx].key_size); - f << s << std::endl; + f << s << "\n"; } + f << std::flush; } } diff --git a/src/EventHandler.h b/src/EventHandler.h index 5f8472b2ce..775fd90408 100644 --- a/src/EventHandler.h +++ b/src/EventHandler.h @@ -104,6 +104,8 @@ public: return *this; } const EventHandlerPtr& operator=(const EventHandlerPtr& h) { + if ( this == &h ) + return *this; handler = h.handler; return *this; } diff --git a/src/EventRegistry.h b/src/EventRegistry.h index d4bfb5aa30..caa9a64153 100644 --- a/src/EventRegistry.h +++ b/src/EventRegistry.h @@ -18,7 +18,7 @@ namespace zeek { // The different kinds of event groups that exist. -enum class EventGroupKind { +enum class EventGroupKind : uint8_t { Attribute, Module, }; diff --git a/src/EventTrace.h b/src/EventTrace.h index eb3bd17cd8..2e70c6d244 100644 --- a/src/EventTrace.h +++ b/src/EventTrace.h @@ -292,7 +292,7 @@ public: // Adds to the trace an update for the given value. void AddDelta(ValPtr val, std::string rhs, bool needs_lhs, bool is_first_def) { auto& d = is_post ? post_deltas : deltas; - d.emplace_back(DeltaGen(val, rhs, needs_lhs, is_first_def)); + d.emplace_back(val, rhs, needs_lhs, is_first_def); } // Initially we analyze events pre-execution. When this flag diff --git a/src/Expr.cc b/src/Expr.cc index 06f142100f..6a9a05fa00 100644 --- a/src/Expr.cc +++ b/src/Expr.cc @@ -2782,7 +2782,7 @@ static void report_field_deprecation(const RecordType* rt, const Expr* e, int fi } FieldExpr::FieldExpr(ExprPtr arg_op, const char* arg_field_name) - : UnaryExpr(EXPR_FIELD, std::move(arg_op)), field_name(util::copy_string(arg_field_name)), td(nullptr), field(0) { + : UnaryExpr(EXPR_FIELD, std::move(arg_op)), field_name(util::copy_string(arg_field_name)) { if ( IsError() ) return; @@ -2863,7 +2863,7 @@ void FieldExpr::ExprDescribe(ODesc* d) const { } HasFieldExpr::HasFieldExpr(ExprPtr arg_op, const char* arg_field_name) - : UnaryExpr(EXPR_HAS_FIELD, std::move(arg_op)), field_name(arg_field_name), field(0) { + : UnaryExpr(EXPR_HAS_FIELD, std::move(arg_op)), field_name(arg_field_name) { if ( IsError() ) return; diff --git a/src/Expr.h b/src/Expr.h index 78576758a9..9745445c9f 100644 --- a/src/Expr.h +++ b/src/Expr.h @@ -33,7 +33,7 @@ using ScopePtr = IntrusivePtr; using ScriptFuncPtr = IntrusivePtr; using FunctionIngredientsPtr = std::shared_ptr; -enum ExprTag : int { +enum ExprTag : int8_t { EXPR_ANY = -1, EXPR_NAME, EXPR_CONST, @@ -232,10 +232,12 @@ public: bool IsParen() const { return paren; } // These are used by script optimization for AST analysis. + // NOLINTBEGIN(bugprone-macro-parentheses) #define ZEEK_EXPR_ACCESSOR_DECLS(ctype) \ const ctype* As##ctype() const; \ ctype* As##ctype(); \ IntrusivePtr As##ctype##Ptr(); + // NOLINTEND(bugprone-macro-parentheses) ZEEK_EXPR_ACCESSOR_DECLS(AddToExpr) ZEEK_EXPR_ACCESSOR_DECLS(AssignExpr) @@ -253,7 +255,7 @@ public: ZEEK_EXPR_ACCESSOR_DECLS(NameExpr) ZEEK_EXPR_ACCESSOR_DECLS(RefExpr) - void Describe(ODesc* d) const override final; + void Describe(ODesc* d) const final; virtual TraversalCode Traverse(TraversalCallback* cb) const = 0; @@ -511,8 +513,8 @@ public: bool HasReducedOps(Reducer* c) const override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; - ExprPtr GetOp1() const override final { return op; } - void SetOp1(ExprPtr _op) override final { op = std::move(_op); } + ExprPtr GetOp1() const final { return op; } + void SetOp1(ExprPtr _op) final { op = std::move(_op); } protected: UnaryExpr(ExprTag arg_tag, ExprPtr arg_op); @@ -547,11 +549,11 @@ public: bool HasReducedOps(Reducer* c) const override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; - ExprPtr GetOp1() const override final { return op1; } - ExprPtr GetOp2() const override final { return op2; } + ExprPtr GetOp1() const final { return op1; } + ExprPtr GetOp2() const final { return op2; } - void SetOp1(ExprPtr _op) override final { op1 = std::move(_op); } - void SetOp2(ExprPtr _op) override final { op2 = std::move(_op); } + void SetOp1(ExprPtr _op) final { op1 = std::move(_op); } + void SetOp2(ExprPtr _op) final { op2 = std::move(_op); } protected: BinaryExpr(ExprTag arg_tag, ExprPtr arg_op1, ExprPtr arg_op2) @@ -930,13 +932,13 @@ public: ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; StmtPtr ReduceToSingletons(Reducer* c) override; - ExprPtr GetOp1() const override final { return op1; } - ExprPtr GetOp2() const override final { return op2; } - ExprPtr GetOp3() const override final { return op3; } + ExprPtr GetOp1() const final { return op1; } + ExprPtr GetOp2() const final { return op2; } + ExprPtr GetOp3() const final { return op3; } - void SetOp1(ExprPtr _op) override final { op1 = std::move(_op); } - void SetOp2(ExprPtr _op) override final { op2 = std::move(_op); } - void SetOp3(ExprPtr _op) override final { op3 = std::move(_op); } + void SetOp1(ExprPtr _op) final { op1 = std::move(_op); } + void SetOp2(ExprPtr _op) final { op2 = std::move(_op); } + void SetOp3(ExprPtr _op) final { op3 = std::move(_op); } protected: void ExprDescribe(ODesc* d) const override; @@ -1144,8 +1146,8 @@ protected: void ExprDescribe(ODesc* d) const override; const char* field_name; - const TypeDecl* td; - int field; // -1 = attributes + const TypeDecl* td = nullptr; + int field = -1; }; // "rec?$fieldname" is true if the value of $fieldname in rec is not nil. @@ -1169,8 +1171,8 @@ protected: void ExprDescribe(ODesc* d) const override; - const char* field_name; - int field; + const char* field_name = nullptr; + int field = -1; }; class RecordConstructorExpr final : public Expr { @@ -1398,11 +1400,11 @@ public: bool HasReducedOps(Reducer* c) const override; ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; - ExprPtr GetOp1() const override final; - ExprPtr GetOp2() const override final; + ExprPtr GetOp1() const final; + ExprPtr GetOp2() const final; - void SetOp1(ExprPtr _op) override final; - void SetOp2(ExprPtr _op) override final; + void SetOp1(ExprPtr _op) final; + void SetOp2(ExprPtr _op) final; protected: void ExprDescribe(ODesc* d) const override; @@ -1597,8 +1599,8 @@ public: ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; StmtPtr ReduceToSingletons(Reducer* c) override; - ExprPtr GetOp1() const override final { return args; } - void SetOp1(ExprPtr _op) override final { args = {NewRef{}, _op->AsListExpr()}; } + ExprPtr GetOp1() const final { return args; } + void SetOp1(ExprPtr _op) final { args = {NewRef{}, _op->AsListExpr()}; } protected: void ExprDescribe(ODesc* d) const override; diff --git a/src/Func.h b/src/Func.h index b80498f389..3b47057d98 100644 --- a/src/Func.h +++ b/src/Func.h @@ -57,7 +57,7 @@ class Func : public Obj { public: static inline const FuncPtr nil; - enum Kind { SCRIPT_FUNC, BUILTIN_FUNC }; + enum Kind : uint8_t { SCRIPT_FUNC, BUILTIN_FUNC }; explicit Func(Kind arg_kind) : kind(arg_kind) {} @@ -351,7 +351,7 @@ public: protected: BuiltinFunc() { func = nullptr; - is_pure = 0; + is_pure = false; } built_in_func func; diff --git a/src/Hash.h b/src/Hash.h index 7d72957c03..73efdbfb1b 100644 --- a/src/Hash.h +++ b/src/Hash.h @@ -213,7 +213,7 @@ private: friend ValPtr BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const Args*); }; -enum HashKeyTag { HASH_KEY_INT, HASH_KEY_DOUBLE, HASH_KEY_STRING }; +enum HashKeyTag : uint8_t { HASH_KEY_INT, HASH_KEY_DOUBLE, HASH_KEY_STRING }; constexpr int NUM_HASH_KEYS = HASH_KEY_STRING + 1; diff --git a/src/ID.h b/src/ID.h index ec27ba7720..b1cc83a383 100644 --- a/src/ID.h +++ b/src/ID.h @@ -38,14 +38,14 @@ class Attributes; class Expr; using ExprPtr = IntrusivePtr; -enum InitClass { +enum InitClass : uint8_t { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, INIT_SKIP, }; -enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; +enum IDScope : uint8_t { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; class ID; using IDPtr = IntrusivePtr; diff --git a/src/IP.h b/src/IP.h index 5527fee3e8..3d372c6dff 100644 --- a/src/IP.h +++ b/src/IP.h @@ -33,6 +33,7 @@ class FragReassembler; } #ifndef IPPROTO_MOBILITY +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define IPPROTO_MOBILITY 135 #endif @@ -355,7 +356,7 @@ public: */ const u_char* Payload() const { if ( ip4 ) - return ((const u_char*)ip4) + ip4->ip_hl * 4; + return ((const u_char*)ip4) + (ip4->ip_hl * static_cast(4)); return ((const u_char*)ip6) + ip6_hdrs->TotalLength(); } @@ -366,7 +367,7 @@ public: */ const ip6_mobility* MobilityHeader() const { if ( ip4 ) - return nullptr; + return nullptr; // NOLINT(bugprone-branch-clone) else if ( (*ip6_hdrs)[ip6_hdrs->Size() - 1]->Type() != IPPROTO_MOBILITY ) return nullptr; else diff --git a/src/IPAddr.h b/src/IPAddr.h index 64e489ac62..8e71010e98 100644 --- a/src/IPAddr.h +++ b/src/IPAddr.h @@ -38,12 +38,16 @@ public: ConnKey(const ConnKey& rhs) { *this = rhs; } ConnKey(Val* v); + // FIXME: This is getting reworked as part of the connection tuple changes. Suppress + // the clang-tidy warning for the time being. + // NOLINTBEGIN(bugprone-suspicious-memory-comparison) bool operator<(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) < 0; } bool operator<=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) <= 0; } bool operator==(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) == 0; } bool operator!=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) != 0; } bool operator>=(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) >= 0; } bool operator>(const ConnKey& rhs) const { return memcmp(this, &rhs, sizeof(ConnKey)) > 0; } + // NOLINTEND(bugprone-suspicious-memory-comparison) ConnKey& operator=(const ConnKey& rhs); @@ -68,7 +72,7 @@ public: /** * Byte order. */ - enum ByteOrder { Host, Network }; + enum ByteOrder : uint8_t { Host, Network }; /** * Constructs the unspecified IPv6 address (all 128 bits zeroed). @@ -432,7 +436,7 @@ inline IPAddr::IPAddr(Family family, const uint32_t* bytes, ByteOrder order) { if ( order == Host ) { for ( unsigned int i = 0; i < 4; ++i ) { - uint32_t* p = (uint32_t*)&in6.s6_addr[i * 4]; + uint32_t* p = (uint32_t*)&in6.s6_addr[i * static_cast(4)]; *p = htonl(*p); } } diff --git a/src/List.h b/src/List.h index 5a02e4879d..e0d0c3e4b1 100644 --- a/src/List.h +++ b/src/List.h @@ -30,7 +30,7 @@ namespace zeek { -enum class ListOrder : int { ORDERED, UNORDERED }; +enum class ListOrder : uint8_t { ORDERED, UNORDERED }; template class List { @@ -38,7 +38,7 @@ public: constexpr static int DEFAULT_LIST_SIZE = 10; constexpr static int LIST_GROWTH_FACTOR = 2; - ~List() { free(entries); } + ~List() { free(static_cast(entries)); } explicit List(int size = 0) { num_entries = 0; @@ -50,6 +50,7 @@ public: max_entries = size; + // NOLINTNEXTLINE(bugprone-sizeof-expression) entries = (T*)util::safe_malloc(max_entries * sizeof(T)); } @@ -58,6 +59,7 @@ public: num_entries = b.num_entries; if ( max_entries ) + // NOLINTNEXTLINE(bugprone-sizeof-expression) entries = (T*)util::safe_malloc(max_entries * sizeof(T)); else entries = nullptr; @@ -66,7 +68,7 @@ public: entries[i] = b.entries[i]; } - List(List&& b) { + List(List&& b) noexcept { entries = b.entries; num_entries = b.num_entries; max_entries = b.max_entries; @@ -77,7 +79,9 @@ public: List(const T* arr, int n) { num_entries = max_entries = n; + // NOLINTNEXTLINE(bugprone-sizeof-expression) entries = (T*)util::safe_malloc(max_entries * sizeof(T)); + // NOLINTNEXTLINE(bugprone-bitwise-pointer-cast,bugprone-multi-level-implicit-pointer-conversion,bugprone-sizeof-expression) memcpy(entries, arr, n * sizeof(T)); } @@ -87,12 +91,13 @@ public: if ( this == &b ) return *this; - free(entries); + free(static_cast(entries)); max_entries = b.max_entries; num_entries = b.num_entries; if ( max_entries ) + // NOLINTNEXTLINE(bugprone-sizeof-expression) entries = (T*)util::safe_malloc(max_entries * sizeof(T)); else entries = nullptr; @@ -103,11 +108,11 @@ public: return *this; } - List& operator=(List&& b) { + List& operator=(List&& b) noexcept { if ( this == &b ) return *this; - free(entries); + free(static_cast(entries)); entries = b.entries; num_entries = b.num_entries; max_entries = b.max_entries; @@ -122,7 +127,7 @@ public: void clear() // remove all entries { - free(entries); + free(static_cast(entries)); entries = nullptr; num_entries = max_entries = 0; } @@ -138,6 +143,7 @@ public: new_size = num_entries; // do not lose any entries if ( new_size != max_entries ) { + // NOLINTNEXTLINE(bugprone-sizeof-expression) entries = (T*)util::safe_realloc((void*)entries, sizeof(T) * new_size); if ( entries ) max_entries = new_size; @@ -315,6 +321,7 @@ using name_list = PList; } // namespace zeek // Macro to visit each list element in turn. +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define loop_over_list(list, iterator) \ int iterator; \ - for ( iterator = 0; iterator < (list).length(); ++iterator ) + for ( (iterator) = 0; (iterator) < (list).length(); ++(iterator) ) diff --git a/src/MMDB.cc b/src/MMDB.cc index 1160409a3e..a4883c573a 100644 --- a/src/MMDB.cc +++ b/src/MMDB.cc @@ -72,7 +72,7 @@ static zeek::ValPtr mmdb_getvalue(MMDB_entry_data_s* entry_data, int status, int return nullptr; } -MMDB::MMDB() : mmdb{}, file_info{}, reported_error{false}, last_check{zeek::run_state::network_time} {} +MMDB::MMDB() : mmdb{}, file_info{}, last_check{zeek::run_state::network_time} {} MMDB::~MMDB() { Close(); } diff --git a/src/MMDB.h b/src/MMDB.h index 0d3af59638..d9bd4a2815 100644 --- a/src/MMDB.h +++ b/src/MMDB.h @@ -64,20 +64,20 @@ private: std::string filename; MMDB_s mmdb; struct stat file_info; - bool reported_error; // to ensure we emit builtin errors during opening only once. + bool reported_error = false; // to ensure we emit builtin errors during opening only once. double last_check; }; class LocDB : public MMDB { public: - bool OpenFromScriptConfig(); - std::string_view Description() { return "GeoIP location database"; } + bool OpenFromScriptConfig() override; + std::string_view Description() override { return "GeoIP location database"; } }; class AsnDB : public MMDB { public: - bool OpenFromScriptConfig(); - std::string_view Description() { return "GeoIP ASN database"; } + bool OpenFromScriptConfig() override; + std::string_view Description() override { return "GeoIP ASN database"; } }; #endif // USE_GEOIP diff --git a/src/NFA.h b/src/NFA.h index 8364dee6d6..62530b17e0 100644 --- a/src/NFA.h +++ b/src/NFA.h @@ -5,16 +5,16 @@ #include "zeek/List.h" #include "zeek/Obj.h" -#define NO_ACCEPT 0 +constexpr int NO_ACCEPT = 0; -#define NO_UPPER_BOUND -1 +constexpr int NO_UPPER_BOUND = -1; -#define SYM_BOL 256 -#define SYM_EOL 257 -#define NUM_SYM 258 +constexpr int SYM_BOL = 256; +constexpr int SYM_EOL = 257; +constexpr int NUM_SYM = 258; -#define SYM_EPSILON 259 -#define SYM_CCL 260 +constexpr int SYM_EPSILON = 259; +constexpr int SYM_CCL = 260; namespace zeek { diff --git a/src/Notifier.h b/src/Notifier.h index 592c491219..6da7d7c59f 100644 --- a/src/Notifier.h +++ b/src/Notifier.h @@ -99,6 +99,8 @@ extern Registry registry; */ class Modifiable { public: + virtual ~Modifiable(); + /** * Calling this method signals to all registered receivers that the * object has been modified. @@ -111,8 +113,6 @@ public: protected: friend class Registry; - virtual ~Modifiable(); - // Number of currently registered receivers. uint64_t num_receivers = 0; }; diff --git a/src/Obj.h b/src/Obj.h index 6faa669626..23bec817c6 100644 --- a/src/Obj.h +++ b/src/Obj.h @@ -92,10 +92,12 @@ public: const detail::Location* expr_location = nullptr) const; // Report internal errors. - void BadTag(const char* msg, const char* t1 = nullptr, const char* t2 = nullptr) const; + [[noreturn]] void BadTag(const char* msg, const char* t1 = nullptr, const char* t2 = nullptr) const; + + // NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define CHECK_TAG(t1, t2, text, tag_to_text_func) \ { \ - if ( t1 != t2 ) \ + if ( (t1) != (t2) ) \ BadTag(text, tag_to_text_func(t1), tag_to_text_func(t2)); \ } diff --git a/src/OpaqueVal.h b/src/OpaqueVal.h index 7bf96c2c7e..206670fbee 100644 --- a/src/OpaqueVal.h +++ b/src/OpaqueVal.h @@ -88,6 +88,8 @@ private: std::unordered_map _types; }; +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + /** * Macro to insert into an OpaqueVal-derived class's declaration. Overrides the "new" serialization methods * DoSerializeData and DoUnserializeData. @@ -100,12 +102,15 @@ private: const char* OpaqueName() const override { return #T; } \ static zeek::OpaqueValPtr OpaqueInstantiate() { return zeek::make_intrusive(); } + #define __OPAQUE_MERGE(a, b) a##b #define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x) /** Macro to insert into an OpaqueVal-derived class's implementation file. */ #define IMPLEMENT_OPAQUE_VALUE(T) static zeek::OpaqueMgr::Register __OPAQUE_ID(__LINE__)(#T); +// NOLINTEND(cppcoreguidelines-macro-usage) + /** * Base class for all opaque values. Opaque values are types that are managed * completely internally, with no further script-level operators provided @@ -229,14 +234,14 @@ public: static void hmac(const T& vlist, u_char key[ZEEK_MD5_DIGEST_LENGTH], u_char result[ZEEK_MD5_DIGEST_LENGTH]) { digest(vlist, result); - for ( int i = 0; i < ZEEK_MD5_DIGEST_LENGTH; ++i ) + for ( size_t i = 0; i < ZEEK_MD5_DIGEST_LENGTH; ++i ) result[i] ^= key[i]; detail::internal_md5(result, ZEEK_MD5_DIGEST_LENGTH, result); } MD5Val(); - ~MD5Val(); + ~MD5Val() override; ValPtr DoClone(CloneState* state) override; @@ -264,7 +269,7 @@ public: } SHA1Val(); - ~SHA1Val(); + ~SHA1Val() override; ValPtr DoClone(CloneState* state) override; @@ -292,7 +297,7 @@ public: } SHA256Val(); - ~SHA256Val(); + ~SHA256Val() override; ValPtr DoClone(CloneState* state) override; @@ -328,6 +333,10 @@ public: explicit BloomFilterVal(probabilistic::BloomFilter* bf); ~BloomFilterVal() override; + // Disable. + BloomFilterVal(const BloomFilterVal&) = delete; + BloomFilterVal& operator=(const BloomFilterVal&) = delete; + ValPtr DoClone(CloneState* state) override; const TypePtr& Type() const { return type; } @@ -350,10 +359,6 @@ protected: DECLARE_OPAQUE_VALUE_DATA(BloomFilterVal) private: - // Disable. - BloomFilterVal(const BloomFilterVal&); - BloomFilterVal& operator=(const BloomFilterVal&); - TypePtr type; detail::CompositeHash* hash; probabilistic::BloomFilter* bloom_filter; diff --git a/src/Pipe.h b/src/Pipe.h index 9cab4e24b1..8c615d304c 100644 --- a/src/Pipe.h +++ b/src/Pipe.h @@ -57,9 +57,9 @@ public: void UnsetFlags(int flags); private: - int fds[2]; - int flags[2]; - int status_flags[2]; + int fds[2] = {-1, -1}; + int flags[2] = {0}; + int status_flags[2] = {0}; }; /** @@ -119,7 +119,7 @@ public: void Swap() { swapped = ! swapped; } private: - Pipe pipes[2]; + Pipe pipes[2]; // NOLINT(modernize-use-default-member-init) bool swapped = false; }; diff --git a/src/RE.h b/src/RE.h index ee5234d42d..5ba41531f8 100644 --- a/src/RE.h +++ b/src/RE.h @@ -15,7 +15,7 @@ using cce_func = int (*)(int); // This method is automatically generated by flex and shouldn't be namespaced -extern int re_lex(void); +extern int re_lex(); namespace zeek { @@ -46,7 +46,7 @@ using MatchPos = uint64_t; using AcceptingMatchSet = std::map; using string_list = name_list; -enum match_type { MATCH_ANYWHERE, MATCH_EXACTLY }; +enum match_type : uint8_t { MATCH_ANYWHERE, MATCH_EXACTLY }; // A "specific" RE matcher will match one type of pattern: either // MATCH_ANYWHERE or MATCH_EXACTLY. diff --git a/src/Reassem.h b/src/Reassem.h index 450f3ed189..7522a1b950 100644 --- a/src/Reassem.h +++ b/src/Reassem.h @@ -14,7 +14,7 @@ namespace zeek { // Whenever subclassing the Reassembler class // you should add to this for known subclasses. -enum ReassemblerType { +enum ReassemblerType : uint8_t { REASSEM_UNKNOWN, REASSEM_TCP, REASSEM_FRAG, @@ -44,7 +44,7 @@ public: memcpy(block, other.block, size); } - DataBlock(DataBlock&& other) { + DataBlock(DataBlock&& other) noexcept { seq = other.seq; upper = other.upper; block = other.block; @@ -64,7 +64,7 @@ public: return *this; } - DataBlock& operator=(DataBlock&& other) { + DataBlock& operator=(DataBlock&& other) noexcept { if ( this == &other ) return *this; diff --git a/src/Reporter.h b/src/Reporter.h index 2a7d8496de..ce4fcae7d3 100644 --- a/src/Reporter.h +++ b/src/Reporter.h @@ -165,12 +165,10 @@ public: // stack of location so that the most recent is always the one that // will be assumed to be the current one. The pointer must remain // valid until the location is popped. - void PushLocation(const detail::Location* location) { - locations.push_back(std::pair(location, 0)); - } + void PushLocation(const detail::Location* location) { locations.emplace_back(location, nullptr); } void PushLocation(const detail::Location* loc1, const detail::Location* loc2) { - locations.push_back(std::pair(loc1, loc2)); + locations.emplace_back(loc1, loc2); } // Removes the top-most location information from stack. @@ -304,15 +302,15 @@ private: bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r); bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id); - enum class PermitWeird { Allow, Deny, Unknown }; + enum class PermitWeird : uint8_t { Allow, Deny, Unknown }; PermitWeird CheckGlobalWeirdLists(const char* name); bool EmitToStderr(bool flag); int errors; + int in_error_handler; bool via_events; bool syslog_open; - int in_error_handler; bool info_to_stderr; bool warnings_to_stderr; bool errors_to_stderr; diff --git a/src/Rule.h b/src/Rule.h index 7d91893260..d0a891ff88 100644 --- a/src/Rule.h +++ b/src/Rule.h @@ -36,7 +36,7 @@ public: const char* ID() const { return id; } unsigned int Index() const { return idx; } - enum PatternType { + enum PatternType : uint8_t { FILE_MAGIC, PAYLOAD, HTTP_REQUEST, diff --git a/src/RuleCondition.h b/src/RuleCondition.h index fb67072aff..74307dd7ed 100644 --- a/src/RuleCondition.h +++ b/src/RuleCondition.h @@ -22,7 +22,12 @@ public: virtual void PrintDebug() = 0; }; -enum RuleStateKind { RULE_STATE_ESTABLISHED = 1, RULE_STATE_ORIG = 2, RULE_STATE_RESP = 4, RULE_STATE_STATELESS = 8 }; +enum RuleStateKind : uint8_t { + RULE_STATE_ESTABLISHED = 1, + RULE_STATE_ORIG = 2, + RULE_STATE_RESP = 4, + RULE_STATE_STATELESS = 8 +}; // Implements the "tcp-state" keyword. class RuleConditionTCPState : public RuleCondition { @@ -53,7 +58,7 @@ private: // Implements "ip-options". class RuleConditionIPOptions : public RuleCondition { public: - enum Options { + enum Options : uint8_t { OPT_LSRR = 1, OPT_LSRRE = 2, OPT_RR = 4, @@ -83,7 +88,7 @@ public: // Implements "payload-size". class RuleConditionPayloadSize : public RuleCondition { public: - enum Comp { RULE_LE, RULE_GE, RULE_LT, RULE_GT, RULE_EQ, RULE_NE }; + enum Comp : uint8_t { RULE_LE, RULE_GE, RULE_LT, RULE_GT, RULE_EQ, RULE_NE }; RuleConditionPayloadSize(uint32_t arg_val, Comp arg_comp) { val = arg_val; diff --git a/src/RuleMatcher.h b/src/RuleMatcher.h index 9242ceb5c0..5fafb679b3 100644 --- a/src/RuleMatcher.h +++ b/src/RuleMatcher.h @@ -3,6 +3,7 @@ #pragma once #include // for u_char +#include #include #include #include @@ -22,9 +23,9 @@ extern void rules_error(const char* msg); extern void rules_error(const char* msg, const char* addl); extern void rules_error(zeek::detail::Rule* id, const char* msg); -extern int rules_lex(void); -extern int rules_parse(void); -extern "C" int rules_wrap(void); +extern int rules_lex(); +extern int rules_parse(); +extern "C" int rules_wrap(); extern int rules_line_number; extern const char* current_rule_file; @@ -78,8 +79,8 @@ extern uint32_t id_to_uint(const char* id); class RuleHdrTest { public: // Note: Adapt RuleHdrTest::PrintDebug() when changing these enums. - enum Comp { LE, GE, LT, GT, EQ, NE }; - enum Prot { NOPROT, IP, IPv6, ICMP, ICMPv6, TCP, UDP, NEXT, IPSrc, IPDst }; + enum Comp : uint8_t { LE, GE, LT, GT, EQ, NE }; + enum Prot : uint8_t { NOPROT, IP, IPv6, ICMP, ICMPv6, TCP, UDP, NEXT, IPSrc, IPDst }; RuleHdrTest(Prot arg_prot, uint32_t arg_offset, uint32_t arg_size, Comp arg_comp, maskedvalue_list* arg_vals); RuleHdrTest(Prot arg_prot, Comp arg_comp, std::vector arg_v); @@ -111,13 +112,11 @@ private: friend class RuleMatcher; struct PatternSet { - PatternSet() : re() {} - // If we're above the 'RE_level' (see RuleMatcher), this // expr contains all patterns on this node. If we're on // 'RE_level', it additionally contains all patterns // of any of its children. - Specific_RE_Matcher* re; + Specific_RE_Matcher* re = nullptr; // All the patterns and their rule indices. string_list patterns; @@ -267,7 +266,7 @@ public: * Ordered from greatest to least strength. Matches of the same strength * will be in the set in lexicographic order of the MIME type string. */ - using MIME_Matches = std::map, std::greater>; + using MIME_Matches = std::map, std::greater<>>; /** * Matches a chunk of data against file magic signatures. diff --git a/src/Scope.h b/src/Scope.h index 7167855a41..89c30e14c0 100644 --- a/src/Scope.h +++ b/src/Scope.h @@ -37,7 +37,7 @@ public: template void Insert(N&& name, I&& id) { - local[std::forward(name)] = std::forward(id); + local[std::forward(name)] = id; ordered_vars.push_back(std::forward(id)); } diff --git a/src/ScriptCoverageManager.cc b/src/ScriptCoverageManager.cc index a57394b8bf..abe5b2eee1 100644 --- a/src/ScriptCoverageManager.cc +++ b/src/ScriptCoverageManager.cc @@ -20,8 +20,6 @@ using namespace std; namespace zeek::detail { -ScriptCoverageManager::ScriptCoverageManager() : ignoring(0), delim('\t') {} - void ScriptCoverageManager::AddStmt(Stmt* s) { if ( ignoring != 0 || analysis_options.gen_ZAM ) return; diff --git a/src/ScriptCoverageManager.h b/src/ScriptCoverageManager.h index 6cd6852753..9bf7d558c1 100644 --- a/src/ScriptCoverageManager.h +++ b/src/ScriptCoverageManager.h @@ -19,9 +19,6 @@ using ObjPtr = IntrusivePtr; */ class ScriptCoverageManager { public: - ScriptCoverageManager(); - virtual ~ScriptCoverageManager() = default; - /** * Imports Zeek script Stmt usage information from file pointed to by * environment variable ZEEK_PROFILER_FILE. @@ -64,12 +61,12 @@ private: * Indicates whether new statements will not be considered as part of * coverage statistics because it was marked with the @no-test tag. */ - uint32_t ignoring; + uint32_t ignoring = 0; /** * The character to use to delimit ScriptCoverageManager output files. Default is '\t'. */ - char delim; + char delim = '\t'; /** * This maps Stmt location-desc pairs to the total number of times that diff --git a/src/SerializationFormat.cc b/src/SerializationFormat.cc index ab96b5d4ca..b932e97497 100644 --- a/src/SerializationFormat.cc +++ b/src/SerializationFormat.cc @@ -12,10 +12,7 @@ namespace zeek::detail { -const float SerializationFormat::GROWTH_FACTOR = 2.5; - -SerializationFormat::SerializationFormat() - : output(), output_size(), output_pos(), input(), input_len(), input_pos(), bytes_written(), bytes_read() {} +constexpr float SerializationFormat::GROWTH_FACTOR = 2.5; SerializationFormat::~SerializationFormat() { free(output); } diff --git a/src/SerializationFormat.h b/src/SerializationFormat.h index a0a2391fc9..c501301891 100644 --- a/src/SerializationFormat.h +++ b/src/SerializationFormat.h @@ -20,7 +20,7 @@ namespace detail { // Abstract base class. class SerializationFormat { public: - SerializationFormat(); + SerializationFormat() = default; virtual ~SerializationFormat(); // Unserialization. @@ -88,16 +88,16 @@ protected: static const uint32_t INITIAL_SIZE = 65536; static const float GROWTH_FACTOR; - char* output; - uint32_t output_size; - uint32_t output_pos; + char* output = nullptr; + uint32_t output_size = 0; + uint32_t output_pos = 0; - const char* input; - uint32_t input_len; - uint32_t input_pos; + const char* input = nullptr; + uint32_t input_len = 0; + uint32_t input_pos = 0; - int bytes_written; - int bytes_read; + int bytes_written = 0; + int bytes_read = 0; }; class BinarySerializationFormat final : public SerializationFormat { diff --git a/src/SmithWaterman.h b/src/SmithWaterman.h index fa0550f7d8..2eeb1c7bd5 100644 --- a/src/SmithWaterman.h +++ b/src/SmithWaterman.h @@ -40,6 +40,8 @@ public: using BSSAlignVec = std::vector; + Substring() = delete; + explicit Substring(const std::string& string) : String(string), _num(), _new(false) {} explicit Substring(const String& string) : String(string), _num(), _new(false) {} @@ -75,8 +77,6 @@ public: private: using DataMap = std::map; - Substring(); - // The alignments registered for this substring. BSSAlignVec _aligns; @@ -106,7 +106,7 @@ private: // We support two modes of operation: finding a single optimal alignment, // and repeated alignments. // -enum SWVariant { +enum SWVariant : uint8_t { SW_SINGLE = 0, // return a single, optimum alignment SW_MULTIPLE = 1, // find repeated, non-overlapping alignments }; diff --git a/src/Span.h b/src/Span.h index 57015cdbe3..96ce5e169b 100644 --- a/src/Span.h +++ b/src/Span.h @@ -20,7 +20,7 @@ public: using element_type = T; - using value_type = typename std::remove_cv::type; + using value_type = std::remove_cv_t; using index_type = size_t; diff --git a/src/Stmt.cc b/src/Stmt.cc index b72ee06ade..bbcc5a7243 100644 --- a/src/Stmt.cc +++ b/src/Stmt.cc @@ -642,7 +642,7 @@ void SwitchStmt::Init() { } SwitchStmt::SwitchStmt(ExprPtr index, case_list* arg_cases) - : ExprStmt(STMT_SWITCH, std::move(index)), cases(arg_cases), default_case_idx(-1) { + : ExprStmt(STMT_SWITCH, std::move(index)), cases(arg_cases) { Init(); bool have_exprs = false; diff --git a/src/Stmt.h b/src/Stmt.h index 9fac25752e..a0870c2896 100644 --- a/src/Stmt.h +++ b/src/Stmt.h @@ -21,6 +21,8 @@ class ZAMCompiler; // for "friend" declarations class ExprListStmt : public Stmt { public: + ~ExprListStmt() override; + const ListExpr* ExprList() const { return l.get(); } const ListExprPtr& ExprListPtr() const { return l; } @@ -35,8 +37,6 @@ public: protected: ExprListStmt(StmtTag t, ListExprPtr arg_l); - ~ExprListStmt() override; - ValPtr Exec(Frame* f, StmtFlowType& flow) override; virtual ValPtr DoExec(std::vector vals, StmtFlowType& flow) = 0; @@ -220,9 +220,9 @@ protected: // the matching type-based case if it defines one. std::pair FindCaseLabelMatch(const Val* v) const; - case_list* cases; - int default_case_idx; - CompositeHash* comp_hash; + case_list* cases = nullptr; + int default_case_idx = -1; + CompositeHash* comp_hash = nullptr; std::unordered_map case_label_value_map; PDict case_label_hash_map; std::vector> case_label_type_list; diff --git a/src/StmtEnums.h b/src/StmtEnums.h index b5a3030088..81d6e9ea48 100644 --- a/src/StmtEnums.h +++ b/src/StmtEnums.h @@ -2,10 +2,12 @@ #pragma once +#include + namespace zeek::detail { // These are in a separate file to break circular dependences -enum StmtTag { +enum StmtTag : uint8_t { STMT_ALARM, // Does no longer exist but kept to create enums consistent. STMT_PRINT, STMT_EVENT, @@ -33,7 +35,7 @@ enum StmtTag { #define NUM_STMTS (int(STMT_STD_FUNCTION) + 1) }; -enum StmtFlowType { +enum StmtFlowType : uint8_t { FLOW_NEXT, // continue on to next statement FLOW_LOOP, // go to top of loop FLOW_BREAK, // break out of loop diff --git a/src/Timer.h b/src/Timer.h index 509a6bec18..9cc2eadcdb 100644 --- a/src/Timer.h +++ b/src/Timer.h @@ -136,9 +136,9 @@ public: static unsigned int* CurrentTimers() { return current_timers; } // IOSource API methods - virtual double GetNextTimeout() override; - virtual void Process() override; - virtual const char* Tag() override { return "TimerMgr"; } + double GetNextTimeout() override; + void Process() override; + const char* Tag() override { return "TimerMgr"; } /** * Performs some extra initialization on a timer manager. This shouldn't diff --git a/src/TraverseTypes.h b/src/TraverseTypes.h index abe157346a..bb3f071a0c 100644 --- a/src/TraverseTypes.h +++ b/src/TraverseTypes.h @@ -2,16 +2,19 @@ #pragma once +#include + namespace zeek::detail { class TraversalCallback; -enum TraversalCode { +enum TraversalCode : uint8_t { TC_CONTINUE = 0, TC_ABORTALL = 1, TC_ABORTSTMT = 2, }; +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #define HANDLE_TC_STMT_PRE(code) \ { \ switch ( code ) { \ @@ -44,4 +47,6 @@ enum TraversalCode { #define HANDLE_TC_ATTR_PRE(code) HANDLE_TC_STMT_PRE(code) #define HANDLE_TC_ATTR_POST(code) return (code); +// NOLINTEND(cppcoreguidelines-macro-usage) + } // namespace zeek::detail diff --git a/src/Trigger.h b/src/Trigger.h index ad9929f238..9b8c1180f1 100644 --- a/src/Trigger.h +++ b/src/Trigger.h @@ -169,7 +169,7 @@ private: class Manager final : public iosource::IOSource { public: Manager(); - ~Manager(); + ~Manager() override; void InitPostScript(); diff --git a/src/TunnelEncapsulation.h b/src/TunnelEncapsulation.h index 402e6cca0d..5f00900b40 100644 --- a/src/TunnelEncapsulation.h +++ b/src/TunnelEncapsulation.h @@ -145,7 +145,7 @@ protected: */ class EncapsulationStack { public: - EncapsulationStack() : conns(nullptr) {} + EncapsulationStack() = default; EncapsulationStack(const EncapsulationStack& other) { if ( other.conns ) @@ -241,7 +241,7 @@ public: void Pop(); protected: - std::vector* conns; + std::vector* conns = nullptr; }; } // namespace zeek diff --git a/src/Type.h b/src/Type.h index 459ea05472..e17de61cc2 100644 --- a/src/Type.h +++ b/src/Type.h @@ -59,7 +59,7 @@ public: } // namespace detail // Zeek types. -enum TypeTag { +enum TypeTag : uint8_t { TYPE_VOID, // 0 TYPE_BOOL, // 1 TYPE_INT, // 2 @@ -91,9 +91,9 @@ extern const char* type_name(TypeTag t); constexpr bool is_network_order(TypeTag tag) noexcept { return tag == TYPE_PORT; } -enum FunctionFlavor { FUNC_FLAVOR_FUNCTION, FUNC_FLAVOR_EVENT, FUNC_FLAVOR_HOOK }; +enum FunctionFlavor : uint8_t { FUNC_FLAVOR_FUNCTION, FUNC_FLAVOR_EVENT, FUNC_FLAVOR_HOOK }; -enum InternalTypeTag : uint16_t { +enum InternalTypeTag : uint8_t { TYPE_INTERNAL_VOID, TYPE_INTERNAL_INT, TYPE_INTERNAL_UNSIGNED, @@ -356,6 +356,8 @@ protected: class IndexType : public Type { public: + ~IndexType() override = default; + int MatchesIndex(detail::ListExpr* index) const override; const TypeListPtr& GetIndices() const { return indices; } @@ -391,8 +393,6 @@ protected: is_pattern_index = types.size() == 1 && types[0]->Tag() == TYPE_PATTERN; } - ~IndexType() override = default; - void DoDescribe(ODesc* d) const override; TypeListPtr indices; @@ -406,7 +406,7 @@ class TableType : public IndexType { public: TableType(TypeListPtr ind, TypePtr yield); - ~TableType(); + ~TableType() override; /** * Assesses whether an &expire_func attribute's function type is compatible diff --git a/src/UID.h b/src/UID.h index aeccc03684..a951432ebe 100644 --- a/src/UID.h +++ b/src/UID.h @@ -85,6 +85,9 @@ inline UID::UID(const UID& other) { } inline UID& UID::operator=(const UID& other) { + if ( this == &other ) + return *this; + memmove(uid, other.uid, sizeof(uid)); initialized = other.initialized; return *this; diff --git a/src/Val.h b/src/Val.h index cc606d70d5..d50d24e8b5 100644 --- a/src/Val.h +++ b/src/Val.h @@ -18,12 +18,12 @@ // We have four different port name spaces: TCP, UDP, ICMP, and UNKNOWN. // We distinguish between them based on the bits specified in the *_PORT_MASK // entries specified below. -#define NUM_PORT_SPACES 4 -#define PORT_SPACE_MASK 0x30000 +constexpr int NUM_PORT_SPACES = 4; +constexpr uint32_t PORT_SPACE_MASK = 0x30000; -#define TCP_PORT_MASK 0x10000 -#define UDP_PORT_MASK 0x20000 -#define ICMP_PORT_MASK 0x30000 +constexpr uint32_t TCP_PORT_MASK = 0x10000; +constexpr uint32_t UDP_PORT_MASK = 0x20000; +constexpr uint32_t ICMP_PORT_MASK = 0x30000; namespace zeek { @@ -157,6 +157,7 @@ public: return cast_intrusive(type); } +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define UNDERLYING_ACCESSOR_DECL(ztype, ctype, name) ctype name() const; UNDERLYING_ACCESSOR_DECL(detail::IntValImplementation, zeek_int_t, AsInt) @@ -433,12 +434,12 @@ public: // Same as for IntVal: no Get() method needed. }; -#define Microseconds 1e-6 -#define Milliseconds 1e-3 -#define Seconds 1.0 -#define Minutes (60 * Seconds) -#define Hours (60 * Minutes) -#define Days (24 * Hours) +constexpr double Microseconds = 1e-6; +constexpr double Milliseconds = 1e-3; +constexpr double Seconds = 1.0; +constexpr double Minutes = (60 * Seconds); +constexpr double Hours = (60 * Minutes); +constexpr double Days = (24 * Hours); class IntervalVal final : public detail::DoubleValImplementation { public: @@ -1056,7 +1057,7 @@ protected: double CallExpireFunc(ListValPtr idx); // Enum for the different kinds of changes an &on_change handler can see - enum OnChangeType { ELEMENT_NEW, ELEMENT_CHANGED, ELEMENT_REMOVED, ELEMENT_EXPIRED }; + enum OnChangeType : uint8_t { ELEMENT_NEW, ELEMENT_CHANGED, ELEMENT_REMOVED, ELEMENT_EXPIRED }; // Calls &change_func. void CallChangeFunc(const ValPtr& index, const ValPtr& old_value, OnChangeType tpe); @@ -1717,6 +1718,7 @@ private: std::vector* yield_types = nullptr; }; +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define UNDERLYING_ACCESSOR_DEF(ztype, ctype, name) \ inline ctype Val::name() const { return static_cast(this)->Get(); } diff --git a/src/Var.h b/src/Var.h index e611fec3b2..ef44ca24b8 100644 --- a/src/Var.h +++ b/src/Var.h @@ -22,7 +22,7 @@ class Stmt; using StmtPtr = IntrusivePtr; using ScopePtr = IntrusivePtr; -enum DeclType { +enum DeclType : uint8_t { VAR_REGULAR, VAR_CONST, VAR_REDEF, diff --git a/src/ZeekString.h b/src/ZeekString.h index 6c2b68449c..ce3705e323 100644 --- a/src/ZeekString.h +++ b/src/ZeekString.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include #include #include @@ -103,7 +104,7 @@ public: */ std::string_view ToStdStringView() const; - enum render_style { + enum render_style : uint8_t { ESC_NONE = 0, ESC_ESC = (1 << 1), // '\' -> "\\" ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'" diff --git a/src/analyzer/Analyzer.h b/src/analyzer/Analyzer.h index ee35a457e6..9a60ec5545 100644 --- a/src/analyzer/Analyzer.h +++ b/src/analyzer/Analyzer.h @@ -772,6 +772,8 @@ private: static ID id_counter; }; +// NOLINTBEGIN(cppcoreguidelines-macro-usage) + /** * Convenience macro to add a new timer. */ @@ -781,25 +783,28 @@ private: /** * Internal convenience macro to iterate over the list of child analyzers. */ -#define LOOP_OVER_CHILDREN(var) for ( auto var = children.begin(); var != children.end(); ++var ) +#define LOOP_OVER_CHILDREN(var) for ( auto(var) = children.begin(); (var) != children.end(); ++(var) ) /** * Internal convenience macro to iterate over the constant list of child * analyzers. */ -#define LOOP_OVER_CONST_CHILDREN(var) for ( auto var = children.cbegin(); var != children.cend(); ++var ) +#define LOOP_OVER_CONST_CHILDREN(var) for ( auto(var) = children.cbegin(); (var) != children.cend(); ++(var) ) /** * Convenience macro to iterate over a given list of child analyzers. */ -#define LOOP_OVER_GIVEN_CHILDREN(var, the_kids) for ( auto var = the_kids.begin(); var != the_kids.end(); ++var ) +#define LOOP_OVER_GIVEN_CHILDREN(var, the_kids) \ + for ( auto(var) = (the_kids).begin(); (var) != (the_kids).end(); ++(var) ) /** * Convenience macro to iterate over a given constant list of child * analyzers. */ #define LOOP_OVER_GIVEN_CONST_CHILDREN(var, the_kids) \ - for ( auto var = the_kids.cbegin(); var != the_kids.cend(); ++var ) + for ( auto(var) = (the_kids).cbegin(); (var) != (the_kids).cend(); ++(var) ) + +// NOLINTEND(cppcoreguidelines-macro-usage) /** * Support analyzer preprocess input before it reaches an analyzer's main @@ -892,9 +897,21 @@ private: }; // The following need to be consistent with zeek.init. -#define CONTENTS_NONE 0 -#define CONTENTS_ORIG 1 -#define CONTENTS_RESP 2 -#define CONTENTS_BOTH 3 +constexpr int CONTENTS_NONE = 0; +constexpr int CONTENTS_ORIG = 1; +constexpr int CONTENTS_RESP = 2; +constexpr int CONTENTS_BOTH = 3; } // namespace zeek::analyzer + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_NONE = + zeek::analyzer::CONTENTS_NONE; + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_ORIG = + zeek::analyzer::CONTENTS_ORIG; + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_RESP = + zeek::analyzer::CONTENTS_RESP; + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer namespace.")]] constexpr int CONTENTS_BOTH = + zeek::analyzer::CONTENTS_BOTH; diff --git a/src/analyzer/Manager.h b/src/analyzer/Manager.h index 1b6a2ede9c..28f8c5e202 100644 --- a/src/analyzer/Manager.h +++ b/src/analyzer/Manager.h @@ -386,15 +386,18 @@ extern analyzer::Manager* analyzer_mgr; // Macros for analyzer debug logging which include the connection id into the // message. +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #ifdef DEBUG #define DBG_ANALYZER(conn, txt) \ DBG_LOG(zeek::DBG_ANALYZER, "%s " txt, \ - fmt_conn_id(conn->OrigAddr(), ntohs(conn->OrigPort()), conn->RespAddr(), ntohs(conn->RespPort()))); + fmt_conn_id((conn)->OrigAddr(), ntohs((conn)->OrigPort()), (conn)->RespAddr(), \ + ntohs((conn)->RespPort()))); #define DBG_ANALYZER_ARGS(conn, fmt, ...) \ DBG_LOG(zeek::DBG_ANALYZER, "%s " fmt, \ - fmt_conn_id(conn->OrigAddr(), ntohs(conn->OrigPort()), conn->RespAddr(), ntohs(conn->RespPort())), \ + fmt_conn_id((conn)->OrigAddr(), ntohs((conn)->OrigPort()), (conn)->RespAddr(), ntohs((conn)->RespPort())), \ ##__VA_ARGS__); #else #define DBG_ANALYZER(conn, txt) #define DBG_ANALYZER_ARGS(conn, fmt, ...) #endif +// NOLINTEND(cppcoreguidelines-macro-usage) diff --git a/src/analyzer/protocol/bittorrent/BitTorrentTracker.h b/src/analyzer/protocol/bittorrent/BitTorrentTracker.h index 6f8812506a..833a4dabc4 100644 --- a/src/analyzer/protocol/bittorrent/BitTorrentTracker.h +++ b/src/analyzer/protocol/bittorrent/BitTorrentTracker.h @@ -6,7 +6,7 @@ #include "zeek/analyzer/protocol/tcp/TCP.h" -#define BTTRACKER_BUF 2048 +constexpr uint32_t BTTRACKER_BUF = 2048; namespace zeek { @@ -20,7 +20,7 @@ namespace analyzer::bittorrent { namespace detail { -enum BTT_States { +enum BTT_States : uint8_t { BTT_REQ_GET, BTT_REQ_HEADER, BTT_REQ_DONE, @@ -32,9 +32,15 @@ enum BTT_States { }; // "benc" = Bencode ("Bee-Encode"), per http://en.wikipedia.org/wiki/Bencode -enum BTT_BencTypes { BENC_TYPE_INT = 0, BENC_TYPE_STR = 1, BENC_TYPE_DIR = 2, BENC_TYPE_LIST = 3, BENC_TYPE_NONE = 10 }; +enum BTT_BencTypes : uint8_t { + BENC_TYPE_INT = 0, + BENC_TYPE_STR = 1, + BENC_TYPE_DIR = 2, + BENC_TYPE_LIST = 3, + BENC_TYPE_NONE = 10 +}; -enum BTT_BencStates { +enum BTT_BencStates : uint8_t { BENC_STATE_EMPTY, BENC_STATE_INT1, BENC_STATE_INT2, diff --git a/src/analyzer/protocol/bittorrent/bittorrent.pac b/src/analyzer/protocol/bittorrent/bittorrent.pac index 3e9fad78e9..77f52b9649 100644 --- a/src/analyzer/protocol/bittorrent/bittorrent.pac +++ b/src/analyzer/protocol/bittorrent/bittorrent.pac @@ -4,7 +4,7 @@ %include zeek.pac %extern{ -#define MSGLEN_LIMIT 0x40000 +constexpr uint32_t MSGLEN_LIMIT = 0x40000; #include "zeek/analyzer/protocol/bittorrent/events.bif.h" %} diff --git a/src/analyzer/protocol/conn-size/ConnSize.cc b/src/analyzer/protocol/conn-size/ConnSize.cc index f80d16a6d1..eeed6ce531 100644 --- a/src/analyzer/protocol/conn-size/ConnSize.cc +++ b/src/analyzer/protocol/conn-size/ConnSize.cc @@ -11,19 +11,7 @@ namespace zeek::analyzer::conn_size { -ConnSize_Analyzer::ConnSize_Analyzer(Connection* c) - : Analyzer("CONNSIZE", c), - orig_bytes(), - resp_bytes(), - orig_pkts(), - resp_pkts(), - orig_bytes_thresh(), - resp_bytes_thresh(), - orig_pkts_thresh(), - resp_pkts_thresh(), - duration_thresh() { - start_time = c->StartTime(); -} +ConnSize_Analyzer::ConnSize_Analyzer(Connection* c) : Analyzer("CONNSIZE", c) { start_time = c->StartTime(); } void ConnSize_Analyzer::Init() { Analyzer::Init(); diff --git a/src/analyzer/protocol/conn-size/ConnSize.h b/src/analyzer/protocol/conn-size/ConnSize.h index 2ba0aacfbe..268cba8d66 100644 --- a/src/analyzer/protocol/conn-size/ConnSize.h +++ b/src/analyzer/protocol/conn-size/ConnSize.h @@ -32,18 +32,18 @@ protected: void ThresholdEvent(EventHandlerPtr f, uint64_t threshold, bool is_orig); - uint64_t orig_bytes; - uint64_t resp_bytes; - uint64_t orig_pkts; - uint64_t resp_pkts; + uint64_t orig_bytes = 0; + uint64_t resp_bytes = 0; + uint64_t orig_pkts = 0; + uint64_t resp_pkts = 0; - uint64_t orig_bytes_thresh; - uint64_t resp_bytes_thresh; - uint64_t orig_pkts_thresh; - uint64_t resp_pkts_thresh; + uint64_t orig_bytes_thresh = 0; + uint64_t resp_bytes_thresh = 0; + uint64_t orig_pkts_thresh = 0; + uint64_t resp_pkts_thresh = 0; - double start_time; - double duration_thresh; + double start_time = 0.0; + double duration_thresh = 0.0; }; // Exposed to make it available to script optimization. diff --git a/src/analyzer/protocol/dns/DNS.h b/src/analyzer/protocol/dns/DNS.h index 7c6fe57f36..57735470f2 100644 --- a/src/analyzer/protocol/dns/DNS.h +++ b/src/analyzer/protocol/dns/DNS.h @@ -7,7 +7,7 @@ namespace zeek::analyzer::dns { namespace detail { -enum DNS_Opcode { +enum DNS_Opcode : uint8_t { DNS_OP_QUERY = 0, ///< standard query DNS_OP_IQUERY = 1, ///< reverse query @@ -22,16 +22,17 @@ enum DNS_Opcode { NETBIOS_REFRESH = 8, }; -enum DNS_Code { - DNS_CODE_OK = 0, ///< no error - DNS_CODE_FORMAT_ERR = 1, ///< format error - DNS_CODE_SERVER_FAIL = 2, ///< server failure - DNS_CODE_NAME_ERR = 3, ///< no such domain - DNS_CODE_NOT_IMPL = 4, ///< not implemented - DNS_CODE_REFUSED = 5, ///< refused +enum DNS_Code : uint16_t { + DNS_CODE_OK = 0, ///< no error + DNS_CODE_FORMAT_ERR = 1, ///< format error + DNS_CODE_SERVER_FAIL = 2, ///< server failure + DNS_CODE_NAME_ERR = 3, ///< no such domain + DNS_CODE_NOT_IMPL = 4, ///< not implemented + DNS_CODE_REFUSED = 5, ///< refused + DNS_CODE_RESERVED = 65535, ///< Force clang-tidy to accept this enum being 16 bits }; -enum RR_Type { +enum RR_Type : uint16_t { TYPE_A = 1, ///< host address TYPE_NS = 2, ///< authoritative name server TYPE_CNAME = 5, ///< canonical name @@ -80,10 +81,13 @@ enum RR_Type { TYPE_BINDS = 65534, ///< Bind9's Private Type Rec for signaling state of signing process }; -#define DNS_CLASS_IN 1 -#define DNS_CLASS_ANY 255 +enum DNS_Class : uint16_t { + DNS_CLASS_IN = 1, + DNS_CLASS_ANY = 255, + DNS_CLASS_RESERVED = 65535, ///< Force clang-tidy to accept this enum being 16 bits +}; -enum DNS_AnswerType { +enum DNS_AnswerType : uint8_t { DNS_QUESTION, DNS_ANSWER, DNS_AUTHORITY, @@ -92,7 +96,7 @@ enum DNS_AnswerType { // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml // DNS EDNS0 Option Codes (OPT) -enum EDNS_OPT_Type { +enum EDNS_OPT_Type : uint16_t { TYPE_LLQ = 1, ///< https://www.iana.org/go/draft-sekar-dns-llq-06 TYPE_UL = 2, ///< http://files.dns-sd.org/draft-sekar-dns-ul.txt TYPE_NSID = 3, ///< RFC5001 @@ -112,7 +116,7 @@ enum EDNS_OPT_Type { TYPE_DEVICE_ID = 26946 ///< https://docs.umbrella.com/developer/networkdevices-api/identifying-dns-traffic2 }; -enum DNSSEC_Algo { +enum DNSSEC_Algo : uint8_t { reserved0 = 0, RSA_MD5 = 1, ///< [RFC2537] NOT RECOMMENDED Diffie_Hellman = 2, ///< [RFC2539] @@ -134,7 +138,7 @@ enum DNSSEC_Algo { reserved255 = 255, }; -enum DNSSEC_Digest { +enum DNSSEC_Digest : uint8_t { reserved = 0, SHA1 = 1, ///< [RFC3110] MANDATORY SHA256 = 2, @@ -144,7 +148,7 @@ enum DNSSEC_Digest { ///< all keys are defined in RFC draft ///< https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-07#section-14.3.2 -enum SVCPARAM_Key { +enum SVCPARAM_Key : uint8_t { mandatory = 0, alpn = 1, no_default_alpn = 2, @@ -392,7 +396,7 @@ protected: bool is_netbios; }; -enum TCP_DNS_state { +enum TCP_DNS_state : uint8_t { DNS_LEN_HI, ///< looking for the high-order byte of the length DNS_LEN_LO, ///< looking for the low-order byte of the length DNS_MESSAGE_BUFFER, ///< building up the message in the buffer diff --git a/src/analyzer/protocol/ftp/FTP.cc b/src/analyzer/protocol/ftp/FTP.cc index 53be3f0452..d0d48a4f1c 100644 --- a/src/analyzer/protocol/ftp/FTP.cc +++ b/src/analyzer/protocol/ftp/FTP.cc @@ -14,15 +14,13 @@ namespace zeek::analyzer::ftp { FTP_Analyzer::FTP_Analyzer(Connection* conn) : analyzer::tcp::TCP_ApplicationAnalyzer("FTP", conn) { - pending_reply = 0; - nvt_orig = new analyzer::login::NVT_Analyzer(conn, true); nvt_orig->SetIsNULSensitive(true); - nvt_orig->SetCRLFAsEOL(LF_as_EOL); + nvt_orig->SetCRLFAsEOL(tcp::LF_as_EOL); nvt_resp = new analyzer::login::NVT_Analyzer(conn, false); nvt_resp->SetIsNULSensitive(true); - nvt_resp->SetCRLFAsEOL(LF_as_EOL); + nvt_resp->SetCRLFAsEOL(tcp::LF_as_EOL); nvt_resp->SetPeer(nvt_orig); nvt_orig->SetPeer(nvt_resp); diff --git a/src/analyzer/protocol/ftp/FTP.h b/src/analyzer/protocol/ftp/FTP.h index c0bae38dde..00950782f0 100644 --- a/src/analyzer/protocol/ftp/FTP.h +++ b/src/analyzer/protocol/ftp/FTP.h @@ -22,7 +22,7 @@ public: protected: analyzer::login::NVT_Analyzer* nvt_orig; analyzer::login::NVT_Analyzer* nvt_resp; - uint32_t pending_reply; // code associated with multi-line reply, or 0 + uint32_t pending_reply = 0; // code associated with multi-line reply, or 0 std::string auth_requested; // AUTH method requested bool tls_active = false; // starttls active }; @@ -36,8 +36,7 @@ protected: */ class FTP_ADAT_Analyzer final : public analyzer::SupportAnalyzer { public: - FTP_ADAT_Analyzer(Connection* conn, bool arg_orig) - : SupportAnalyzer("FTP_ADAT", conn, arg_orig), first_token(true) {} + FTP_ADAT_Analyzer(Connection* conn, bool arg_orig) : SupportAnalyzer("FTP_ADAT", conn, arg_orig) {} void DeliverStream(int len, const u_char* data, bool orig) override; @@ -45,7 +44,7 @@ protected: // Used by the client-side analyzer to tell if it needs to peek at the // initial context token and do sanity checking (i.e. does it look like // a TLS/SSL handshake token). - bool first_token; + bool first_token = true; }; } // namespace zeek::analyzer::ftp diff --git a/src/analyzer/protocol/http/HTTP.h b/src/analyzer/protocol/http/HTTP.h index b689705a5f..35d264bfeb 100644 --- a/src/analyzer/protocol/http/HTTP.h +++ b/src/analyzer/protocol/http/HTTP.h @@ -15,7 +15,7 @@ namespace zeek::analyzer::http { -enum CHUNKED_TRANSFER_STATE { +enum CHUNKED_TRANSFER_STATE : uint8_t { NON_CHUNKED_TRANSFER, BEFORE_CHUNK, EXPECT_CHUNK_SIZE, @@ -44,7 +44,7 @@ public: bool Undelivered(int64_t len); int64_t BodyLength() const { return body_length; } int64_t HeaderLength() const { return header_length; } - void SkipBody() { deliver_body = 0; } + void SkipBody() { deliver_body = false; } const std::string& FileID() const { return precomputed_file_id; } protected: @@ -59,7 +59,7 @@ protected: int expect_body; int64_t body_length; int64_t header_length; - enum { IDENTITY, GZIP, COMPRESS, DEFLATE } encoding; + enum : uint8_t { IDENTITY, GZIP, COMPRESS, DEFLATE } encoding; analyzer::zip::ZIP_Analyzer* zip; bool deliver_body; bool is_partial_content; @@ -81,7 +81,7 @@ protected: void SubmitAllHeaders() override; }; -enum { +enum : uint8_t { HTTP_BODY_NOT_EXPECTED, HTTP_BODY_EXPECTED, HTTP_BODY_MAYBE, diff --git a/src/analyzer/protocol/irc/IRC.h b/src/analyzer/protocol/irc/IRC.h index fda8ac2d4e..2f76a359cb 100644 --- a/src/analyzer/protocol/irc/IRC.h +++ b/src/analyzer/protocol/irc/IRC.h @@ -16,11 +16,11 @@ namespace irc { * \brief Main class for analyzing IRC traffic. */ class IRC_Analyzer final : public analyzer::tcp::TCP_ApplicationAnalyzer { - enum { + enum : uint8_t { WAIT_FOR_REGISTRATION, REGISTERED, }; - enum { + enum : uint8_t { NO_ZIP, ACCEPT_ZIP, ZIP_LOADED, diff --git a/src/analyzer/protocol/krb/KRB.h b/src/analyzer/protocol/krb/KRB.h index d30490eb82..0fb15f81af 100644 --- a/src/analyzer/protocol/krb/KRB.h +++ b/src/analyzer/protocol/krb/KRB.h @@ -17,10 +17,10 @@ namespace zeek::analyzer::krb { class KRB_Analyzer final : public analyzer::Analyzer { public: explicit KRB_Analyzer(Connection* conn); - virtual ~KRB_Analyzer(); + ~KRB_Analyzer() override; - virtual void Done(); - virtual void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen); + void Done() override; + void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen) override; static analyzer::Analyzer* Instantiate(Connection* conn) { return new KRB_Analyzer(conn); } diff --git a/src/analyzer/protocol/login/Login.cc b/src/analyzer/protocol/login/Login.cc index c3b9f74c9d..00c3a8e4e6 100644 --- a/src/analyzer/protocol/login/Login.cc +++ b/src/analyzer/protocol/login/Login.cc @@ -24,7 +24,7 @@ static RE_Matcher* re_login_timeouts; static RE_Matcher* init_RE(ListVal* l); Login_Analyzer::Login_Analyzer(const char* name, Connection* conn) - : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), user_text() { + : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn) { state = LOGIN_STATE_AUTHENTICATE; num_user_lines_seen = lines_scanned = 0; // Set last_failure_num_user_lines so we will always generate diff --git a/src/analyzer/protocol/login/Login.h b/src/analyzer/protocol/login/Login.h index 04276094f7..f7b3913776 100644 --- a/src/analyzer/protocol/login/Login.h +++ b/src/analyzer/protocol/login/Login.h @@ -6,7 +6,7 @@ namespace zeek::analyzer::login { -enum login_state { +enum login_state : uint8_t { LOGIN_STATE_AUTHENTICATE, // trying to authenticate LOGIN_STATE_LOGGED_IN, // successful authentication LOGIN_STATE_SKIP, // skip any further processing @@ -14,10 +14,14 @@ enum login_state { }; // If no action by this many lines, we're definitely confused. -#define MAX_AUTHENTICATE_LINES 50 +constexpr int MAX_AUTHENTICATE_LINES = 50; // Maximum # lines look after login for failure. -#define MAX_LOGIN_LOOKAHEAD 10 +constexpr int MAX_LOGIN_LOOKAHEAD = 10; + +// If we have more user text than this unprocessed, we complain about +// excessive typeahead. +constexpr int MAX_USER_TEXT = 12; class Login_Analyzer : public analyzer::tcp::TCP_ApplicationAnalyzer { public: @@ -61,10 +65,7 @@ protected: bool HaveTypeahead() const { return num_user_text > 0; } void FlushEmptyTypeahead(); -// If we have more user text than this unprocessed, we complain about -// excessive typeahead. -#define MAX_USER_TEXT 12 - char* user_text[MAX_USER_TEXT]; + char* user_text[MAX_USER_TEXT] = {nullptr}; int user_text_first, user_text_last; // indices into user_text int num_user_text; // number of entries in user_text diff --git a/src/analyzer/protocol/login/NVT.cc b/src/analyzer/protocol/login/NVT.cc index 6de963e323..777f9869f5 100644 --- a/src/analyzer/protocol/login/NVT.cc +++ b/src/analyzer/protocol/login/NVT.cc @@ -316,8 +316,7 @@ void TelnetBinaryOption::InconsistentOption(unsigned int /* type */) { } // namespace detail -NVT_Analyzer::NVT_Analyzer(Connection* conn, bool orig) - : analyzer::tcp::ContentLine_Analyzer("NVT", conn, orig), options() {} +NVT_Analyzer::NVT_Analyzer(Connection* conn, bool orig) : analyzer::tcp::ContentLine_Analyzer("NVT", conn, orig) {} NVT_Analyzer::~NVT_Analyzer() { for ( int i = 0; i < num_options; ++i ) @@ -413,7 +412,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) { switch ( c ) { case '\r': - if ( CRLFAsEOL() & CR_as_EOL ) { + if ( CRLFAsEOL() & tcp::CR_as_EOL ) { buf[offset] = '\0'; ForwardStream(offset, buf, IsOrig()); offset = 0; @@ -424,7 +423,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) { case '\n': if ( last_char == '\r' ) { - if ( CRLFAsEOL() & CR_as_EOL ) + if ( CRLFAsEOL() & tcp::CR_as_EOL ) // we already emitted, skip ; else { @@ -435,7 +434,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) { } } - else if ( CRLFAsEOL() & LF_as_EOL ) { + else if ( CRLFAsEOL() & tcp::LF_as_EOL ) { buf[offset] = '\0'; ForwardStream(offset, buf, IsOrig()); offset = 0; @@ -475,7 +474,7 @@ void NVT_Analyzer::DeliverChunk(int& len, const u_char*& data) { default: buf[offset++] = c; break; } - if ( ! (CRLFAsEOL() & CR_as_EOL) && last_char == '\r' && c != '\n' && c != '\0' ) { + if ( ! (CRLFAsEOL() & tcp::CR_as_EOL) && last_char == '\r' && c != '\n' && c != '\0' ) { if ( Conn()->FlagEvent(SINGULAR_CR) ) Weird("line_terminated_with_single_CR"); } diff --git a/src/analyzer/protocol/login/NVT.h b/src/analyzer/protocol/login/NVT.h index 3f8a99af88..b3e1a5f8c4 100644 --- a/src/analyzer/protocol/login/NVT.h +++ b/src/analyzer/protocol/login/NVT.h @@ -164,7 +164,7 @@ protected: int encrypting_mode = 0; char* auth_name = nullptr; - TelnetOption* options[NUM_TELNET_OPTIONS]; + TelnetOption* options[NUM_TELNET_OPTIONS] = {nullptr}; int num_options = 0; }; diff --git a/src/analyzer/protocol/login/RSH.h b/src/analyzer/protocol/login/RSH.h index 5f5e28cd96..0dd82b4504 100644 --- a/src/analyzer/protocol/login/RSH.h +++ b/src/analyzer/protocol/login/RSH.h @@ -9,7 +9,7 @@ namespace zeek::analyzer::login { class Rsh_Analyzer; -enum rsh_state { +enum rsh_state : uint8_t { RSH_FIRST_NULL, // waiting to see first NUL RSH_CLIENT_USER_NAME, // scanning client user name up to NUL RSH_SERVER_USER_NAME, // scanning server user name up to NUL diff --git a/src/analyzer/protocol/login/Rlogin.h b/src/analyzer/protocol/login/Rlogin.h index fe098cc8ba..7f98c856e1 100644 --- a/src/analyzer/protocol/login/Rlogin.h +++ b/src/analyzer/protocol/login/Rlogin.h @@ -9,7 +9,7 @@ namespace zeek::analyzer::login { class Rlogin_Analyzer; -enum rlogin_state { +enum rlogin_state : uint8_t { RLOGIN_FIRST_NULL, // waiting to see first NUL RLOGIN_CLIENT_USER_NAME, // scanning client user name up to NUL RLOGIN_SERVER_USER_NAME, // scanning server user name up to NUL diff --git a/src/analyzer/protocol/mime/MIME.h b/src/analyzer/protocol/mime/MIME.h index 62c538a511..0a8fdd8b7e 100644 --- a/src/analyzer/protocol/mime/MIME.h +++ b/src/analyzer/protocol/mime/MIME.h @@ -30,19 +30,19 @@ namespace analyzer::mime { // MIME Constants -#define HT '\011' -#define SP '\040' -#define CR '\015' -#define LF '\012' +constexpr char HT = '\011'; +constexpr char SP = '\040'; +constexpr char CR = '\015'; +constexpr char LF = '\012'; -enum MIME_CONTENT_TYPE { +enum MIME_CONTENT_TYPE : uint8_t { CONTENT_TYPE_MULTIPART, CONTENT_TYPE_MESSAGE, CONTENT_TYPE_TEXT, CONTENT_TYPE_OTHER, // image | audio | video | application | }; -enum MIME_EVENT_TYPE { +enum MIME_EVENT_TYPE : uint8_t { MIME_EVENT_ILLEGAL_FORMAT, MIME_EVENT_ILLEGAL_ENCODING, MIME_EVENT_CONTENT_GAP, diff --git a/src/analyzer/protocol/ncp/NCP.h b/src/analyzer/protocol/ncp/NCP.h index 590158c99d..c04d53ff1b 100644 --- a/src/analyzer/protocol/ncp/NCP.h +++ b/src/analyzer/protocol/ncp/NCP.h @@ -69,7 +69,7 @@ protected: size_t buf_len; // size off msg_buf }; -#define NCP_TCPIP_HEADER_LENGTH 8 +constexpr int NCP_TCPIP_HEADER_LENGTH = 8; class NCP_FrameBuffer : public FrameBuffer { public: diff --git a/src/analyzer/protocol/netbios/NetbiosSSN.h b/src/analyzer/protocol/netbios/NetbiosSSN.h index 875ee7e089..750d6e86d8 100644 --- a/src/analyzer/protocol/netbios/NetbiosSSN.h +++ b/src/analyzer/protocol/netbios/NetbiosSSN.h @@ -7,7 +7,7 @@ namespace zeek::analyzer::netbios_ssn { namespace detail { -enum NetbiosSSN_Opcode { +enum NetbiosSSN_Opcode : uint8_t { NETBIOS_SSN_MSG = 0x0, NETBIOS_DGM_DIRECT_UNIQUE = 0x10, NETBIOS_DGM_DIRECT_GROUP = 0x11, @@ -59,7 +59,7 @@ struct NetbiosDGM_RawMsgHdr { uint16_t offset; }; -enum NetbiosSSN_State { +enum NetbiosSSN_State : uint8_t { NETBIOS_SSN_TYPE, // looking for type field NETBIOS_SSN_FLAGS, // looking for flag field NETBIOS_SSN_LEN_HI, // looking for high-order byte of length diff --git a/src/analyzer/protocol/ntp/ntp-analyzer.pac b/src/analyzer/protocol/ntp/ntp-analyzer.pac index d0ce8d964d..6da8c2c2ac 100644 --- a/src/analyzer/protocol/ntp/ntp-analyzer.pac +++ b/src/analyzer/protocol/ntp/ntp-analyzer.pac @@ -1,10 +1,10 @@ %extern{ #include - #define FRAC_16 pow(2,-16) - #define FRAC_32 pow(2,-32) + #define FRAC_16 std::pow(2,-16) + #define FRAC_32 std::pow(2,-32) // NTP defines the epoch from 1900, not 1970 - #define EPOCH_OFFSET -2208988800 + constexpr double EPOCH_OFFSET = -2208988800; %} %header{ diff --git a/src/analyzer/protocol/pia/PIA.cc b/src/analyzer/protocol/pia/PIA.cc index 884b4a67fe..55a1dbe341 100644 --- a/src/analyzer/protocol/pia/PIA.cc +++ b/src/analyzer/protocol/pia/PIA.cc @@ -14,7 +14,7 @@ namespace zeek::analyzer::pia { -PIA::PIA(analyzer::Analyzer* arg_as_analyzer) : state(INIT), as_analyzer(arg_as_analyzer), conn(), current_packet() {} +PIA::PIA(analyzer::Analyzer* arg_as_analyzer) : as_analyzer(arg_as_analyzer), current_packet() {} PIA::~PIA() { ClearBuffer(&pkt_buffer); } diff --git a/src/analyzer/protocol/pia/PIA.h b/src/analyzer/protocol/pia/PIA.h index b471214771..7573b87e54 100644 --- a/src/analyzer/protocol/pia/PIA.h +++ b/src/analyzer/protocol/pia/PIA.h @@ -73,7 +73,8 @@ protected: void PIA_DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen, bool clear_state); - enum State { INIT, BUFFERING, MATCHING_ONLY, SKIPPING } state; + enum State : uint8_t { INIT, BUFFERING, MATCHING_ONLY, SKIPPING }; + State state = INIT; // Buffers one chunk of data. Used both for packet payload (incl. // sequence numbers for TCP) and chunks of a reassembled stream. @@ -114,8 +115,8 @@ private: // Joint backend for the two public FirstPacket() methods. void FirstPacket(bool is_orig, const std::optional& proto, const IP_Hdr* ip); - analyzer::Analyzer* as_analyzer; - Connection* conn; + analyzer::Analyzer* as_analyzer = nullptr; + Connection* conn = nullptr; DataBlock current_packet; }; @@ -166,7 +167,7 @@ protected: } void DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen) override { - Analyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); + TCP_ApplicationAnalyzer::DeliverPacket(len, data, is_orig, seq, ip, caplen); PIA_DeliverPacket(len, data, is_orig, seq, ip, caplen, false); } diff --git a/src/analyzer/protocol/pop3/POP3.h b/src/analyzer/protocol/pop3/POP3.h index d5384a050e..ae5a682c0e 100644 --- a/src/analyzer/protocol/pop3/POP3.h +++ b/src/analyzer/protocol/pop3/POP3.h @@ -19,11 +19,11 @@ namespace zeek::analyzer::pop3 { namespace detail { -enum POP3_Cmd { +enum POP3_Cmd : uint8_t { #include "POP3_cmd.def" }; -enum POP3_MasterState { +enum POP3_MasterState : uint8_t { POP3_START, POP3_AUTHORIZATION, POP3_TRANSACTION, @@ -31,7 +31,7 @@ enum POP3_MasterState { POP3_FINISHED, }; -enum POP3_State { +enum POP3_State : uint8_t { START, USER, PASS, @@ -57,7 +57,7 @@ enum POP3_State { END, }; -enum POP3_SubState { +enum POP3_SubState : uint8_t { POP3_OK, POP3_WOK, }; diff --git a/src/analyzer/protocol/rdp/rdpeudp-analyzer.pac b/src/analyzer/protocol/rdp/rdpeudp-analyzer.pac index 541653e17f..af237e192c 100644 --- a/src/analyzer/protocol/rdp/rdpeudp-analyzer.pac +++ b/src/analyzer/protocol/rdp/rdpeudp-analyzer.pac @@ -1,12 +1,12 @@ refine connection RDPEUDP_Conn += { %member{ - enum RDPEUDP_STATE { + enum RDPEUDP_STATE : uint8_t { NEED_SYN = 0x1, NEED_SYNACK = 0x2, NED_ACK = 0x3, ESTABLISHED = 0x4, }; - enum RDPUDP_VERSION_INFO_FLAG { + enum RDPUDP_VERSION_INFO_FLAG : uint16_t { RDPUDP_PROTOCOL_VERSION_1 = 0x0001, RDPUDP_PROTOCOL_VERSION_2 = 0x0002, RDPUDP_PROTOCOL_VERSION_3 = 0x0101 diff --git a/src/analyzer/protocol/rfb/rfb-analyzer.pac b/src/analyzer/protocol/rfb/rfb-analyzer.pac index a9bf3ce352..1a9e3e540d 100644 --- a/src/analyzer/protocol/rfb/rfb-analyzer.pac +++ b/src/analyzer/protocol/rfb/rfb-analyzer.pac @@ -69,7 +69,7 @@ refine flow RFB_Flow += { refine connection RFB_Conn += { %member{ - enum ServerState { + enum ServerState : uint8_t { SERVER_VERSION = 0, SERVER_AUTH_TYPE = 1, SERVER_AUTH_TYPE37 = 2, @@ -84,7 +84,7 @@ refine connection RFB_Conn += { SERVER_INVALID =100, }; - enum ClientState { + enum ClientState : uint8_t { CLIENT_VERSION = 0, CLIENT_AUTH_SELECTION = 1, CLIENT_AUTH_VNC_RESPONSE = 2, diff --git a/src/analyzer/protocol/rpc/RPC.cc b/src/analyzer/protocol/rpc/RPC.cc index f7a1eb67a1..7ecec676e5 100644 --- a/src/analyzer/protocol/rpc/RPC.cc +++ b/src/analyzer/protocol/rpc/RPC.cc @@ -625,7 +625,7 @@ void Contents_RPC::DeliverStream(int len, const u_char* data, bool orig) { } RPC_Analyzer::RPC_Analyzer(const char* name, Connection* conn, detail::RPC_Interpreter* arg_interp) - : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), interp(arg_interp), orig_rpc(), resp_rpc() { + : analyzer::tcp::TCP_ApplicationAnalyzer(name, conn), interp(arg_interp) { if ( Conn()->ConnTransport() == TRANSPORT_UDP ) ADD_ANALYZER_TIMER(&RPC_Analyzer::ExpireTimer, run_state::network_time + zeek::detail::rpc_timeout, true, zeek::detail::TIMER_RPC_EXPIRE); diff --git a/src/analyzer/protocol/rpc/RPC.h b/src/analyzer/protocol/rpc/RPC.h index 8e198db983..071d011b73 100644 --- a/src/analyzer/protocol/rpc/RPC.h +++ b/src/analyzer/protocol/rpc/RPC.h @@ -7,17 +7,17 @@ namespace zeek::analyzer::rpc { namespace detail { -enum { +enum : uint8_t { RPC_CALL = 0, RPC_REPLY = 1, }; -enum { +enum : uint8_t { RPC_MSG_ACCEPTED = 0, RPC_MSG_DENIED = 1, }; -enum { +enum : uint8_t { RPC_SUCCESS = 0, RPC_PROG_UNAVAIL = 1, RPC_PROG_MISMATCH = 2, @@ -26,12 +26,12 @@ enum { RPC_SYSTEM_ERR = 5, }; -enum { +enum : uint8_t { RPC_MISMATCH = 0, RPC_AUTH_ERROR = 1, }; -enum { +enum : uint8_t { RPC_AUTH_BADCRED = 1, RPC_AUTH_REJECTEDCRED = 2, RPC_AUTH_BADVERF = 3, @@ -39,7 +39,7 @@ enum { RPC_AUTH_TOOWEAK = 5, }; -enum { +enum : uint8_t { RPC_AUTH_NULL = 0, RPC_AUTH_UNIX = 1, RPC_AUTH_SHORT = 2, @@ -196,14 +196,14 @@ public: ~Contents_RPC() override = default; protected: - enum state_t { + enum state_t : uint8_t { WAIT_FOR_MESSAGE, WAIT_FOR_MARKER, WAIT_FOR_DATA, WAIT_FOR_LAST_DATA, }; - enum resync_state_t { + enum resync_state_t : uint8_t { NEED_RESYNC, RESYNC_WAIT_FOR_MSG_START, RESYNC_WAIT_FOR_FULL_MSG, @@ -250,8 +250,8 @@ protected: detail::RPC_Interpreter* interp; - Contents_RPC* orig_rpc; - Contents_RPC* resp_rpc; + Contents_RPC* orig_rpc = nullptr; + Contents_RPC* resp_rpc = nullptr; }; } // namespace zeek::analyzer::rpc diff --git a/src/analyzer/protocol/smtp/BDAT.h b/src/analyzer/protocol/smtp/BDAT.h index a9e7aca197..2368df132d 100644 --- a/src/analyzer/protocol/smtp/BDAT.h +++ b/src/analyzer/protocol/smtp/BDAT.h @@ -42,7 +42,7 @@ struct BDATCmd parse_bdat_arg(int length, const char* arg); * * Helper class to avoid true/false parameters. */ -enum class ChunkType { +enum class ChunkType : uint8_t { None, Intermediate, Last, diff --git a/src/analyzer/protocol/smtp/SMTP.h b/src/analyzer/protocol/smtp/SMTP.h index 1d255bbed3..6dd57ee455 100644 --- a/src/analyzer/protocol/smtp/SMTP.h +++ b/src/analyzer/protocol/smtp/SMTP.h @@ -16,12 +16,12 @@ namespace detail { class SMTP_BDAT_Analyzer; -enum SMTP_Cmd { +enum SMTP_Cmd : uint8_t { #include "SMTP_cmd.def" }; // State is updated on every SMTP reply. -enum SMTP_State { +enum SMTP_State : uint8_t { SMTP_CONNECTED, // 0: before the opening message SMTP_INITIATED, // 1: after opening message 220, EHLO/HELO expected SMTP_NOT_AVAILABLE, // 2: after opening message 554, etc. @@ -50,7 +50,7 @@ public: void ConnectionFinished(bool half_finished) override; void Undelivered(uint64_t seq, int len, bool orig) override; - void SkipData() { skip_data = 1; } // skip delivery of data lines + void SkipData() { skip_data = true; } // skip delivery of data lines static analyzer::Analyzer* Instantiate(Connection* conn) { return new SMTP_Analyzer(conn); } diff --git a/src/analyzer/protocol/snmp/SNMP.h b/src/analyzer/protocol/snmp/SNMP.h index 3800263ac9..d6a46f1696 100644 --- a/src/analyzer/protocol/snmp/SNMP.h +++ b/src/analyzer/protocol/snmp/SNMP.h @@ -10,10 +10,10 @@ namespace zeek::analyzer::snmp { class SNMP_Analyzer final : public analyzer::Analyzer { public: explicit SNMP_Analyzer(Connection* conn); - virtual ~SNMP_Analyzer(); + ~SNMP_Analyzer() override; - virtual void Done(); - virtual void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen); + void Done() override; + void DeliverPacket(int len, const u_char* data, bool orig, uint64_t seq, const IP_Hdr* ip, int caplen) override; static analyzer::Analyzer* InstantiateAnalyzer(Connection* conn) { return new SNMP_Analyzer(conn); } diff --git a/src/analyzer/protocol/tcp/ContentLine.h b/src/analyzer/protocol/tcp/ContentLine.h index 6c6a557ad4..234154b834 100644 --- a/src/analyzer/protocol/tcp/ContentLine.h +++ b/src/analyzer/protocol/tcp/ContentLine.h @@ -8,8 +8,8 @@ namespace zeek::analyzer::tcp { -#define CR_as_EOL 1 -#define LF_as_EOL 2 +constexpr int CR_as_EOL = 1; +constexpr int LF_as_EOL = 2; // Slightly smaller than 16MB so that the buffer is not unnecessarily resized to 32M. constexpr auto DEFAULT_MAX_LINE_LENGTH = 16 * 1024 * 1024 - 100; @@ -122,3 +122,9 @@ protected: }; } // namespace zeek::analyzer::tcp + +// These were previously #defined, so they have to be outside of the namespace. +[[deprecated("Remove in v8.1, use the version in the zeek:::analyzer::tcp namespace")]] constexpr int CR_as_EOL = + zeek::analyzer::tcp::CR_as_EOL; +[[deprecated("Remove in v8.1, use the version in the zeek:::analyzer::tcp namespace")]] constexpr int LF_as_EOL = + zeek::analyzer::tcp::LF_as_EOL; diff --git a/src/analyzer/protocol/tcp/TCP.cc b/src/analyzer/protocol/tcp/TCP.cc index 15275ae8fb..6a5439e371 100644 --- a/src/analyzer/protocol/tcp/TCP.cc +++ b/src/analyzer/protocol/tcp/TCP.cc @@ -195,8 +195,7 @@ RecordVal* TCPStats_Endpoint::BuildStats() { return stats; } -TCPStats_Analyzer::TCPStats_Analyzer(Connection* c) - : TCP_ApplicationAnalyzer("TCPSTATS", c), orig_stats(), resp_stats() {} +TCPStats_Analyzer::TCPStats_Analyzer(Connection* c) : TCP_ApplicationAnalyzer("TCPSTATS", c) {} TCPStats_Analyzer::~TCPStats_Analyzer() { delete orig_stats; diff --git a/src/analyzer/protocol/tcp/TCP.h b/src/analyzer/protocol/tcp/TCP.h index 74d92ceb16..dbec0a55b6 100644 --- a/src/analyzer/protocol/tcp/TCP.h +++ b/src/analyzer/protocol/tcp/TCP.h @@ -117,8 +117,8 @@ public: protected: void DeliverPacket(int len, const u_char* data, bool is_orig, uint64_t seq, const IP_Hdr* ip, int caplen) override; - TCPStats_Endpoint* orig_stats; - TCPStats_Endpoint* resp_stats; + TCPStats_Endpoint* orig_stats = nullptr; + TCPStats_Endpoint* resp_stats = nullptr; }; } // namespace zeek::analyzer::tcp diff --git a/src/analyzer/protocol/tcp/TCP_Endpoint.h b/src/analyzer/protocol/tcp/TCP_Endpoint.h index df8acffdff..d560f6577d 100644 --- a/src/analyzer/protocol/tcp/TCP_Endpoint.h +++ b/src/analyzer/protocol/tcp/TCP_Endpoint.h @@ -18,7 +18,7 @@ namespace analyzer::tcp { class TCP_Reassembler; -enum EndpointState { +enum EndpointState : uint8_t { TCP_ENDPOINT_INACTIVE, // no SYN (or other packets) seen for this side TCP_ENDPOINT_SYN_SENT, // SYN seen, but no ack TCP_ENDPOINT_SYN_ACK_SENT, // SYN ack seen, no initial SYN @@ -193,16 +193,19 @@ public: // Codes used for tracking history. For responders, we shift these // over by 16 bits in order to fit both originator and responder // into a Connection's hist_seen field. -#define HIST_SYN_PKT 0x1 -#define HIST_FIN_PKT 0x2 -#define HIST_RST_PKT 0x4 -#define HIST_FIN_RST_PKT 0x8 -#define HIST_DATA_PKT 0x10 -#define HIST_ACK_PKT 0x20 -#define HIST_MULTI_FLAG_PKT 0x40 -#define HIST_CORRUPT_PKT 0x80 -#define HIST_RXMIT 0x100 -#define HIST_WIN0 0x200 + enum HistoryMasks : uint16_t { + HIST_SYN_PKT = 0x1, + HIST_FIN_PKT = 0x2, + HIST_RST_PKT = 0x4, + HIST_FIN_RST_PKT = 0x8, + HIST_DATA_PKT = 0x10, + HIST_ACK_PKT = 0x20, + HIST_MULTI_FLAG_PKT = 0x40, + HIST_CORRUPT_PKT = 0x80, + HIST_RXMIT = 0x100, + HIST_WIN0 = 0x200, + }; + // #define HIST_UNKNOWN_PKT 0x400 (do not use - used in Session.h) bool CheckHistory(uint32_t mask, char code); void AddHistory(char code); @@ -248,10 +251,50 @@ protected: uint32_t gap_cnt, gap_thresh; }; -#define ENDIAN_UNKNOWN 0 -#define ENDIAN_LITTLE 1 -#define ENDIAN_BIG 2 -#define ENDIAN_CONFUSED 3 +enum EndianTypes : uint8_t { + ENDIAN_UNKNOWN = 0, + ENDIAN_LITTLE = 1, + ENDIAN_BIG = 2, + ENDIAN_CONFUSED = 3, +}; } // namespace analyzer::tcp } // namespace zeek + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_SYN_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_SYN_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_FIN_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_FIN_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_RST_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_RST_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_FIN_RST_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_FIN_RST_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_DATA_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_DATA_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_ACK_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_ACK_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_MULTI_FLAG_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_MULTI_FLAG_PKT; + +[[deprecated( + "Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_CORRUPT_PKT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_CORRUPT_PKT; + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_RXMIT = + zeek::analyzer::tcp::TCP_Endpoint::HIST_RXMIT; + +[[deprecated("Remove in v8.1. Use version in zeek::analyzer::tcp::TCP_Endpoint namespace.")]] constexpr int HIST_WIN0 = + zeek::analyzer::tcp::TCP_Endpoint::HIST_WIN0; diff --git a/src/analyzer/protocol/tcp/TCP_Reassembler.h b/src/analyzer/protocol/tcp/TCP_Reassembler.h index 75292e8941..f45f9337a2 100644 --- a/src/analyzer/protocol/tcp/TCP_Reassembler.h +++ b/src/analyzer/protocol/tcp/TCP_Reassembler.h @@ -22,7 +22,7 @@ namespace tcp { class TCP_Reassembler final : public Reassembler { public: - enum Type { + enum Type : uint8_t { Direct, // deliver to destination analyzer itself Forward, // forward to destination analyzer's children }; diff --git a/src/analyzer/protocol/websocket/WebSocket.h b/src/analyzer/protocol/websocket/WebSocket.h index 394eab194e..81abe5a459 100644 --- a/src/analyzer/protocol/websocket/WebSocket.h +++ b/src/analyzer/protocol/websocket/WebSocket.h @@ -15,7 +15,7 @@ namespace zeek::analyzer::websocket { class WebSocket_Analyzer : public analyzer::tcp::TCP_ApplicationAnalyzer { public: WebSocket_Analyzer(zeek::Connection* conn); - ~WebSocket_Analyzer() = default; + ~WebSocket_Analyzer() override = default; /** * Allows script land to configure the WebSocket analyzer before analysis. diff --git a/src/analyzer/protocol/zip/ZIP.h b/src/analyzer/protocol/zip/ZIP.h index cf161e08ca..9031787c7f 100644 --- a/src/analyzer/protocol/zip/ZIP.h +++ b/src/analyzer/protocol/zip/ZIP.h @@ -10,7 +10,7 @@ namespace zeek::analyzer::zip { class ZIP_Analyzer final : public analyzer::tcp::TCP_SupportAnalyzer { public: - enum Method { GZIP, DEFLATE }; + enum Method : uint8_t { GZIP, DEFLATE }; ZIP_Analyzer(Connection* conn, bool orig, Method method = GZIP); ~ZIP_Analyzer() override; @@ -20,7 +20,7 @@ public: void DeliverStream(int len, const u_char* data, bool orig) override; protected: - enum { NONE, ZIP_OK, ZIP_FAIL }; + enum : uint8_t { NONE, ZIP_OK, ZIP_FAIL }; z_stream* zip; int zip_status; Method method; diff --git a/src/broker/Data.h b/src/broker/Data.h index 4114aac27b..e7bb016195 100644 --- a/src/broker/Data.h +++ b/src/broker/Data.h @@ -323,7 +323,7 @@ public: /** * Converts the value to a Boolean. */ - [[nodiscard]] bool ToBool(bool fallback = 0) const noexcept { + [[nodiscard]] bool ToBool(bool fallback = false) const noexcept { if ( auto val = broker::get_if(value_); val ) { return *val; } diff --git a/src/broker/Manager.h b/src/broker/Manager.h index d9c4a4fa81..6745f57d38 100644 --- a/src/broker/Manager.h +++ b/src/broker/Manager.h @@ -90,7 +90,7 @@ struct Stats { class Manager : public zeek::cluster::Backend, public iosource::IOSource { public: /** Broker protocol to expect on a listening port. */ - enum class BrokerProtocol { + enum class BrokerProtocol : uint8_t { Native, /**< Broker's native binary protocol */ WebSocket /** Broker's WebSocket protocol for external clients. */ }; diff --git a/src/broker/WebSocketShim.h b/src/broker/WebSocketShim.h index c896854d47..c2f1b9a6a8 100644 --- a/src/broker/WebSocketShim.h +++ b/src/broker/WebSocketShim.h @@ -26,7 +26,7 @@ class WebSocketShim : public zeek::cluster::Backend { public: WebSocketShim(std::unique_ptr es, std::unique_ptr ls, std::unique_ptr ehs); - ~WebSocketShim(); + ~WebSocketShim() override; /** * Component factory. diff --git a/src/cluster/Backend.h b/src/cluster/Backend.h index 1c6ba82e2e..91be697441 100644 --- a/src/cluster/Backend.h +++ b/src/cluster/Backend.h @@ -247,7 +247,7 @@ public: /** * Status codes for callbacks. */ - enum class CallbackStatus { + enum class CallbackStatus : uint8_t { Success, Error, NotImplemented, diff --git a/src/cluster/backend/zeromq/ZeroMQ.h b/src/cluster/backend/zeromq/ZeroMQ.h index dae822160b..0af5429a18 100644 --- a/src/cluster/backend/zeromq/ZeroMQ.h +++ b/src/cluster/backend/zeromq/ZeroMQ.h @@ -31,7 +31,7 @@ public: /** * Destructor. */ - ~ZeroMQBackend(); + ~ZeroMQBackend() override; /** * Spawns a thread running zmq_proxy() for the configured XPUB/XSUB listen diff --git a/src/digest.h b/src/digest.h index 07ee1c776b..fb767083b1 100644 --- a/src/digest.h +++ b/src/digest.h @@ -13,32 +13,32 @@ #include "zeek/util.h" // for util::bytetohex // Required buffer size for an MD5 digest. -#define ZEEK_MD5_DIGEST_LENGTH 16 +constexpr size_t ZEEK_MD5_DIGEST_LENGTH = 16; // Required buffer size for an SHA1 digest. -#define ZEEK_SHA_DIGEST_LENGTH 20 +constexpr size_t ZEEK_SHA_DIGEST_LENGTH = 20; // Required buffer size for an SHA224 digest. -#define ZEEK_SHA224_DIGEST_LENGTH 28 +constexpr size_t ZEEK_SHA224_DIGEST_LENGTH = 28; // Required buffer size for an SHA256 digest. -#define ZEEK_SHA256_DIGEST_LENGTH 32 +constexpr size_t ZEEK_SHA256_DIGEST_LENGTH = 32; // Required buffer size for an SHA384 digest. -#define ZEEK_SHA384_DIGEST_LENGTH 48 +constexpr size_t ZEEK_SHA384_DIGEST_LENGTH = 48; // Required buffer size for an SHA512 digest. -#define ZEEK_SHA512_DIGEST_LENGTH 64 +constexpr size_t ZEEK_SHA512_DIGEST_LENGTH = 64; // Buffer size for a digest of any type in hex representation plus size for at // least a null terminator. -#define ZEEK_DIGEST_PRINT_LENGTH (ZEEK_SHA512_DIGEST_LENGTH * 2) + 1 +constexpr size_t ZEEK_DIGEST_PRINT_LENGTH = (ZEEK_SHA512_DIGEST_LENGTH * 2) + 1; namespace zeek::detail { // if you add something here, note that you might have to make sure that the // static_out member in calculate_digest is still long enough. -enum HashAlgorithm { Hash_MD5, Hash_SHA1, Hash_SHA224, Hash_SHA256, Hash_SHA384, Hash_SHA512 }; +enum HashAlgorithm : uint8_t { Hash_MD5, Hash_SHA1, Hash_SHA224, Hash_SHA256, Hash_SHA384, Hash_SHA512 }; inline const char* digest_print(const u_char* digest, size_t n) { static char buf[ZEEK_DIGEST_PRINT_LENGTH]; diff --git a/src/file_analysis/AnalyzerSet.h b/src/file_analysis/AnalyzerSet.h index c446d8f5ed..53827a595f 100644 --- a/src/file_analysis/AnalyzerSet.h +++ b/src/file_analysis/AnalyzerSet.h @@ -187,8 +187,8 @@ private: * @param arg_a an analyzer instance to add to an analyzer set. * @param arg_key hash key representing the analyzer's \c AnalyzerArgs. */ - RemoveMod(const zeek::Tag& arg_tag, std::unique_ptr arg_key) - : Modification(), tag(arg_tag), key(std::move(arg_key)) {} + RemoveMod(zeek::Tag arg_tag, std::unique_ptr arg_key) + : Modification(), tag(std::move(arg_tag)), key(std::move(arg_key)) {} ~RemoveMod() override {} bool Perform(AnalyzerSet* set) override; void Abort() override {} diff --git a/src/file_analysis/File.cc b/src/file_analysis/File.cc index 8b52ddf25b..092d73a8c5 100644 --- a/src/file_analysis/File.cc +++ b/src/file_analysis/File.cc @@ -77,19 +77,7 @@ void File::StaticInit() { } File::File(const std::string& file_id, const std::string& source_name, Connection* conn, zeek::Tag tag, bool is_orig) - : id(file_id), - val(nullptr), - file_reassembler(nullptr), - stream_offset(0), - reassembly_max_buffer(0), - did_metadata_inference(false), - reassembly_enabled(false), - postpone_timeout(false), - done(false), - seen_bytes(0), - missing_bytes(0), - overflow_bytes(0), - analyzers(this) { + : id(file_id), val(nullptr), analyzers(this) { StaticInit(); DBG_LOG(DBG_FILE_ANALYSIS, "[%s] Creating new File object", file_id.c_str()); diff --git a/src/file_analysis/File.h b/src/file_analysis/File.h index 73fb384eb3..a367edd764 100644 --- a/src/file_analysis/File.h +++ b/src/file_analysis/File.h @@ -314,31 +314,31 @@ protected: static void StaticInit(); protected: - std::string id; /**< A pretty hash that likely identifies file */ - RecordValPtr val; /**< \c fa_file from script layer. */ - FileReassembler* file_reassembler; /**< A reassembler for the file if it's needed. */ - uint64_t stream_offset; /**< The offset of the file which has been forwarded. */ - uint64_t reassembly_max_buffer; /**< Maximum allowed buffer for reassembly. */ - bool did_metadata_inference; /**< Whether the metadata inference has already been attempted. */ - bool reassembly_enabled; /**< Whether file stream reassembly is needed. */ - bool postpone_timeout; /**< Whether postponing timeout is requested. */ - bool done; /**< If this object is about to be deleted. */ - uint64_t seen_bytes; /**< Number of bytes processed for this file. */ - uint64_t missing_bytes; /**< Number of bytes missed for this file. */ - uint64_t overflow_bytes; /**< Number of bytes not delivered. */ - detail::AnalyzerSet analyzers; /**< A set of attached file analyzers. */ - std::list done_analyzers; /**< Analyzers we're done with, remembered here until they - can be safely deleted. */ + std::string id; /**< A pretty hash that likely identifies file */ + RecordValPtr val; /**< \c fa_file from script layer. */ + FileReassembler* file_reassembler = nullptr; /**< A reassembler for the file if it's needed. */ + uint64_t stream_offset = 0; /**< The offset of the file which has been forwarded. */ + uint64_t reassembly_max_buffer = 0; /**< Maximum allowed buffer for reassembly. */ + bool did_metadata_inference = false; /**< Whether the metadata inference has already been attempted. */ + bool reassembly_enabled = false; /**< Whether file stream reassembly is needed. */ + bool postpone_timeout = false; /**< Whether postponing timeout is requested. */ + bool done = false; /**< If this object is about to be deleted. */ + uint64_t seen_bytes = 0; /**< Number of bytes processed for this file. */ + uint64_t missing_bytes = 0; /**< Number of bytes missed for this file. */ + uint64_t overflow_bytes = 0; /**< Number of bytes not delivered. */ + detail::AnalyzerSet analyzers; /**< A set of attached file analyzers. */ + std::list done_analyzers; /**< Analyzers we're done with, remembered here until they + can be safely deleted. */ struct BOF_Buffer { - BOF_Buffer() : full(false), size(0) {} + BOF_Buffer() = default; ~BOF_Buffer() { - for ( size_t i = 0; i < chunks.size(); ++i ) - delete chunks[i]; + for ( auto* chunk : chunks ) + delete chunk; } - bool full; - uint64_t size; + bool full = false; + uint64_t size = 0; String::CVec chunks; } bof_buffer; /**< Beginning of file buffer. */ diff --git a/src/file_analysis/Manager.cc b/src/file_analysis/Manager.cc index d67621c201..43c4abf06d 100644 --- a/src/file_analysis/Manager.cc +++ b/src/file_analysis/Manager.cc @@ -16,12 +16,7 @@ using namespace std; namespace zeek::file_analysis { -Manager::Manager() - : plugin::ComponentManager("Files", "Tag", "AllAnalyzers"), - current_file_id(), - magic_state(), - cumulative_files(0), - max_files(0) {} +Manager::Manager() : plugin::ComponentManager("Files", "Tag", "AllAnalyzers") {} Manager::~Manager() { for ( const auto& [_, tag] : mime_types ) diff --git a/src/file_analysis/Manager.h b/src/file_analysis/Manager.h index bdc850b171..c35a5b4f8b 100644 --- a/src/file_analysis/Manager.h +++ b/src/file_analysis/Manager.h @@ -428,17 +428,17 @@ private: TagSet* LookupMIMEType(const std::string& mtype, bool add_if_not_found); - std::map id_map; /**< Map file ID to file_analysis::File records. */ - std::set ignored; /**< Ignored files. Will be finally removed on EOF. */ - std::string current_file_id; /**< Hash of what get_file_handle event sets. */ - zeek::detail::RuleFileMagicState* magic_state; /**< File magic signature match state. */ - MIMEMap mime_types; /**< Mapping of MIME types to analyzers. */ + std::map id_map; /**< Map file ID to file_analysis::File records. */ + std::set ignored; /**< Ignored files. Will be finally removed on EOF. */ + std::string current_file_id; /**< Hash of what get_file_handle event sets. */ + zeek::detail::RuleFileMagicState* magic_state = nullptr; /**< File magic signature match state. */ + MIMEMap mime_types; /**< Mapping of MIME types to analyzers. */ inline static TableVal* disabled = nullptr; /**< Table of disabled analyzers. */ inline static TableType* tag_set_type = nullptr; /**< Type for set[tag]. */ - size_t cumulative_files; - size_t max_files; + size_t cumulative_files = 0; + size_t max_files = 0; zeek::detail::CompositeHash* analyzer_hash = nullptr; }; diff --git a/src/file_analysis/analyzer/extract/Extract.cc b/src/file_analysis/analyzer/extract/Extract.cc index d5eb6263ac..47b13c7036 100644 --- a/src/file_analysis/analyzer/extract/Extract.cc +++ b/src/file_analysis/analyzer/extract/Extract.cc @@ -16,7 +16,6 @@ Extract::Extract(RecordValPtr args, file_analysis::File* file, std::string arg_f : file_analysis::Analyzer(file_mgr->GetComponentTag("EXTRACT"), std::move(args), file), filename(std::move(arg_filename)), limit(arg_limit), - written(0), limit_includes_missing(arg_limit_includes_missing) { char buf[128]; file_stream = fopen(filename.data(), "wb"); diff --git a/src/file_analysis/analyzer/extract/Extract.h b/src/file_analysis/analyzer/extract/Extract.h index 733bb91527..6a94ff178c 100644 --- a/src/file_analysis/analyzer/extract/Extract.h +++ b/src/file_analysis/analyzer/extract/Extract.h @@ -69,10 +69,10 @@ protected: private: std::string filename; - FILE* file_stream; - uint64_t limit; // the file extraction limit - uint64_t written; // how many bytes we have written so far - bool limit_includes_missing; // do count missing bytes against limit if true + FILE* file_stream = nullptr; + uint64_t limit = 0; // the file extraction limit + uint64_t written = 0; // how many bytes we have written so far + bool limit_includes_missing = false; // do count missing bytes against limit if true }; } // namespace zeek::file_analysis::detail diff --git a/src/file_analysis/analyzer/hash/Hash.cc b/src/file_analysis/analyzer/hash/Hash.cc index 5452448d00..ec44eecaf1 100644 --- a/src/file_analysis/analyzer/hash/Hash.cc +++ b/src/file_analysis/analyzer/hash/Hash.cc @@ -16,7 +16,6 @@ Hash::Hash(RecordValPtr args, file_analysis::File* file, HashVal* hv, StringValP : file_analysis::Analyzer(file_mgr->GetComponentTag(util::to_upper(arg_kind->ToStdString())), std::move(args), file), hash(hv), - fed(false), kind(std::move(arg_kind)) { hash->Init(); } diff --git a/src/file_analysis/analyzer/hash/Hash.h b/src/file_analysis/analyzer/hash/Hash.h index b3a30e3d97..be4e5d85c4 100644 --- a/src/file_analysis/analyzer/hash/Hash.h +++ b/src/file_analysis/analyzer/hash/Hash.h @@ -60,8 +60,8 @@ protected: void Finalize(); private: - HashVal* hash; - bool fed; + HashVal* hash = nullptr; + bool fed = false; StringValPtr kind; }; diff --git a/src/file_analysis/analyzer/pe/PE.h b/src/file_analysis/analyzer/pe/PE.h index d2efe24ad7..3949032e31 100644 --- a/src/file_analysis/analyzer/pe/PE.h +++ b/src/file_analysis/analyzer/pe/PE.h @@ -13,15 +13,14 @@ namespace zeek::file_analysis::detail { */ class PE : public file_analysis::Analyzer { public: - ~PE(); + ~PE() override; static file_analysis::Analyzer* Instantiate(RecordValPtr args, file_analysis::File* file) { return new PE(std::move(args), file); } - virtual bool DeliverStream(const u_char* data, uint64_t len); - - virtual bool EndOfFile(); + bool DeliverStream(const u_char* data, uint64_t len) override; + bool EndOfFile() override; protected: PE(RecordValPtr args, file_analysis::File* file); diff --git a/src/input/Manager.h b/src/input/Manager.h index 85cf48d8e1..b6ccafa0b7 100644 --- a/src/input/Manager.h +++ b/src/input/Manager.h @@ -247,7 +247,7 @@ private: void Warning(const Stream* i, const char* fmt, ...) const __attribute__((format(printf, 3, 4))); void Error(const Stream* i, const char* fmt, ...) const __attribute__((format(printf, 3, 4))); - enum class ErrorType { INFO, WARNING, ERROR }; + enum class ErrorType : uint8_t { INFO, WARNING, ERROR }; void ErrorHandler(const Stream* i, ErrorType et, bool reporter_send, const char* fmt, ...) const __attribute__((format(printf, 5, 6))); void ErrorHandler(const Stream* i, ErrorType et, bool reporter_send, const char* fmt, va_list ap) const @@ -256,7 +256,7 @@ private: Stream* FindStream(const std::string& name) const; Stream* FindStream(ReaderFrontend* reader) const; - enum StreamType { TABLE_STREAM, EVENT_STREAM, ANALYSIS_STREAM }; + enum StreamType : uint8_t { TABLE_STREAM, EVENT_STREAM, ANALYSIS_STREAM }; std::map readers; diff --git a/src/input/ReaderBackend.h b/src/input/ReaderBackend.h index 740b0db8ba..29ec4761fb 100644 --- a/src/input/ReaderBackend.h +++ b/src/input/ReaderBackend.h @@ -16,7 +16,7 @@ class ReaderFrontend; /** * The modes a reader can be in. */ -enum ReaderMode { +enum ReaderMode : uint8_t { /** * Manual refresh reader mode. The reader will read the file once, * and send all read data back to the manager. After that, no automatic @@ -118,22 +118,21 @@ public: name = other.name ? util::copy_string(other.name) : nullptr; mode = other.mode; - for ( config_map::const_iterator i = other.config.begin(); i != other.config.end(); i++ ) - config.insert(std::make_pair(util::copy_string(i->first), util::copy_string(i->second))); + for ( const auto& [k, v] : other.config ) + config.insert(std::make_pair(util::copy_string(k), util::copy_string(v))); } ~ReaderInfo() { delete[] source; delete[] name; - for ( config_map::iterator i = config.begin(); i != config.end(); i++ ) { - delete[] i->first; - delete[] i->second; + for ( auto [k, v] : config ) { + delete[] k; + delete[] v; } } - private: - const ReaderInfo& operator=(const ReaderInfo& other); // Disable. + const ReaderInfo& operator=(const ReaderInfo& other) = delete; }; /** diff --git a/src/input/readers/binary/Binary.cc b/src/input/readers/binary/Binary.cc index f1a9236551..eb87f8d0e8 100644 --- a/src/input/readers/binary/Binary.cc +++ b/src/input/readers/binary/Binary.cc @@ -15,7 +15,7 @@ namespace zeek::input::reader::detail { streamsize Binary::chunk_size = 0; -Binary::Binary(ReaderFrontend* frontend) : ReaderBackend(frontend), in(nullptr), mtime(0), ino(0), firstrun(true) { +Binary::Binary(ReaderFrontend* frontend) : ReaderBackend(frontend) { if ( ! chunk_size ) { chunk_size = BifConst::InputBinary::chunk_size; diff --git a/src/input/readers/binary/Binary.h b/src/input/readers/binary/Binary.h index d80d055022..8d240e542e 100644 --- a/src/input/readers/binary/Binary.h +++ b/src/input/readers/binary/Binary.h @@ -32,10 +32,10 @@ private: int UpdateModificationTime(); std::string fname; - std::ifstream* in; - time_t mtime; - ino_t ino; - bool firstrun; + std::ifstream* in = nullptr; + time_t mtime = 0; + ino_t ino = 0; + bool firstrun = true; // options set from the script-level. static std::streamsize chunk_size; diff --git a/src/input/readers/raw/Raw.h b/src/input/readers/raw/Raw.h index 74e694d064..29ba6417cf 100644 --- a/src/input/readers/raw/Raw.h +++ b/src/input/readers/raw/Raw.h @@ -78,7 +78,14 @@ private: int pipes[6] = {-1}; pid_t childpid; - enum IoChannels { stdout_in = 0, stdout_out = 1, stdin_in = 2, stdin_out = 3, stderr_in = 4, stderr_out = 5 }; + enum IoChannels : uint8_t { + stdout_in = 0, + stdout_out = 1, + stdin_in = 2, + stdin_out = 3, + stderr_in = 4, + stderr_out = 5 + }; static const int block_size; }; diff --git a/src/input/readers/sqlite/SQLite.cc b/src/input/readers/sqlite/SQLite.cc index d389168df3..d0ee0e44ca 100644 --- a/src/input/readers/sqlite/SQLite.cc +++ b/src/input/readers/sqlite/SQLite.cc @@ -16,8 +16,7 @@ using zeek::threading::Value; namespace zeek::input::reader::detail { -SQLite::SQLite(ReaderFrontend* frontend) - : ReaderBackend(frontend), fields(), num_fields(), mode(), started(), query(), db(), st() { +SQLite::SQLite(ReaderFrontend* frontend) : ReaderBackend(frontend) { set_separator.assign((const char*)BifConst::LogSQLite::set_separator->Bytes(), BifConst::InputSQLite::set_separator->Len()); diff --git a/src/input/readers/sqlite/SQLite.h b/src/input/readers/sqlite/SQLite.h index 6bd1a3c85a..00b6df89ab 100644 --- a/src/input/readers/sqlite/SQLite.h +++ b/src/input/readers/sqlite/SQLite.h @@ -28,14 +28,14 @@ private: threading::Value* EntryToVal(sqlite3_stmt* st, const threading::Field* field, int pos, int subpos); - const threading::Field* const* fields; // raw mapping - unsigned int num_fields; - int mode; - bool started; + const threading::Field* const* fields = nullptr; // raw mapping + unsigned int num_fields = 0; + int mode = 0; + bool started = false; std::string query; - sqlite3* db; - sqlite3_stmt* st; - threading::formatter::Ascii* io; + sqlite3* db = nullptr; + sqlite3_stmt* st = nullptr; + threading::formatter::Ascii* io = nullptr; std::string set_separator; std::string unset_field; diff --git a/src/iosource/Component.h b/src/iosource/Component.h index 75fad40dc5..5716d16f15 100644 --- a/src/iosource/Component.h +++ b/src/iosource/Component.h @@ -53,7 +53,7 @@ public: /** * Type of input a packet source supports. */ - enum InputType { + enum InputType : uint8_t { LIVE, ///< Live input. TRACE, ///< Offline input from trace file. BOTH ///< Live input as well as offline. diff --git a/src/iosource/IOSource.h b/src/iosource/IOSource.h index 60f2abd896..accb8aa6f2 100644 --- a/src/iosource/IOSource.h +++ b/src/iosource/IOSource.h @@ -2,6 +2,8 @@ #pragma once +#include + namespace zeek::iosource { /** @@ -10,7 +12,7 @@ namespace zeek::iosource { */ class IOSource { public: - enum ProcessFlags { READ = 0x01, WRITE = 0x02 }; + enum ProcessFlags : uint8_t { READ = 0x01, WRITE = 0x02 }; /** * Constructor. diff --git a/src/iosource/Manager.h b/src/iosource/Manager.h index aac2144eb2..5b305f76a5 100644 --- a/src/iosource/Manager.h +++ b/src/iosource/Manager.h @@ -193,7 +193,7 @@ private: class WakeupHandler final : public IOSource { public: WakeupHandler(); - ~WakeupHandler(); + ~WakeupHandler() override; /** * Tells the handler to wake up the loop by firing the flare. diff --git a/src/iosource/Packet.h b/src/iosource/Packet.h index 7b9dce4e1b..770113b3d8 100644 --- a/src/iosource/Packet.h +++ b/src/iosource/Packet.h @@ -38,7 +38,7 @@ using RecordValPtr = IntrusivePtr; * This enum is sized as an int32_t to make the Packet structure align * correctly. */ -enum Layer3Proto : int32_t { +enum Layer3Proto : int8_t { L3_UNKNOWN = -1, /// Layer 3 type could not be determined. L3_IPV4 = 1, /// Layer 3 is IPv4. L3_IPV6 = 2, /// Layer 3 is IPv6. @@ -148,11 +148,6 @@ public: uint32_t cap_len; /// Captured packet length uint32_t link_type; /// pcap link_type (DLT_EN10MB, DLT_RAW, etc) - /** - * Layer 3 protocol identified (if any). - */ - Layer3Proto l3_proto; - /** * If layer 2 is Ethernet, innermost ethertype field. */ @@ -168,6 +163,11 @@ public: */ uint32_t inner_vlan = 0; + /** + * Layer 3 protocol identified (if any). + */ + Layer3Proto l3_proto; + /** * If this packet is related to a connection, this flag denotes whether * this packet is from the originator of the connection. diff --git a/src/iosource/PktSrc.h b/src/iosource/PktSrc.h index dbec7f0584..8ffea4472d 100644 --- a/src/iosource/PktSrc.h +++ b/src/iosource/PktSrc.h @@ -219,7 +219,7 @@ public: * poll should time out in seconds from the current time. Return * -1 if this should not be considered. */ - virtual double GetNextTimeout() override; + double GetNextTimeout() override; protected: friend class Manager; diff --git a/src/logging/Manager.h b/src/logging/Manager.h index e90c545990..8c46af0340 100644 --- a/src/logging/Manager.h +++ b/src/logging/Manager.h @@ -405,7 +405,7 @@ private: /** * Helper enum for CreateWriterForFilter to avoid bool params. */ - enum class WriterOrigin { + enum class WriterOrigin : uint8_t { REMOTE, LOCAL, }; @@ -434,7 +434,7 @@ private: bool CheckFilterWriterConflict(const WriterInfo* winfo, const Filter* filter); // Verdict of a PolicyHook. - enum class PolicyVerdict { + enum class PolicyVerdict : uint8_t { PASS, VETO, }; diff --git a/src/logging/WriterBackend.h b/src/logging/WriterBackend.h index 4b096ca084..49cd8a713b 100644 --- a/src/logging/WriterBackend.h +++ b/src/logging/WriterBackend.h @@ -60,7 +60,7 @@ public: * * Structure takes ownership of string. */ - const char* path; + const char* path = nullptr; /** * The filter this writer is attached to. @@ -79,17 +79,17 @@ public: /** * The rotation interval as configured for this writer. */ - double rotation_interval; + double rotation_interval = 0.0; /** * The parsed value of log_rotate_base_time in seconds. */ - double rotation_base; + double rotation_base = 0.0; /** * The network time when the writer is created. */ - double network_time; + double network_time = 0.0; /** * A map of key/value pairs corresponding to the relevant @@ -97,7 +97,7 @@ public: */ config_map config; - WriterInfo() : path(nullptr), rotation_interval(0.0), rotation_base(0.0), network_time(0.0) {} + WriterInfo() = default; WriterInfo(const WriterInfo& other) { path = other.path ? util::copy_string(other.path) : nullptr; @@ -106,8 +106,8 @@ public: rotation_base = other.rotation_base; network_time = other.network_time; - for ( config_map::const_iterator i = other.config.begin(); i != other.config.end(); i++ ) - config.insert(std::make_pair(util::copy_string(i->first), util::copy_string(i->second))); + for ( const auto& [k, v] : other.config ) + config.insert(std::make_pair(util::copy_string(k), util::copy_string(v))); filter_name = other.filter_name; } @@ -116,9 +116,9 @@ public: delete[] path; delete[] post_proc_func; - for ( config_map::iterator i = config.begin(); i != config.end(); i++ ) { - delete[] i->first; - delete[] i->second; + for ( auto [k, v] : config ) { + delete[] k; + delete[] v; } } @@ -127,8 +127,7 @@ public: broker::data ToBroker() const; bool FromBroker(broker::data d); - private: - const WriterInfo& operator=(const WriterInfo& other); // Disable. + const WriterInfo& operator=(const WriterInfo& other) = delete; }; /** diff --git a/src/logging/writers/sqlite/SQLite.cc b/src/logging/writers/sqlite/SQLite.cc index d397c2d086..8b80d76eef 100644 --- a/src/logging/writers/sqlite/SQLite.cc +++ b/src/logging/writers/sqlite/SQLite.cc @@ -16,7 +16,7 @@ using zeek::threading::Value; namespace zeek::logging::writer::detail { -SQLite::SQLite(WriterFrontend* frontend) : WriterBackend(frontend), fields(), num_fields(), db(), st() { +SQLite::SQLite(WriterFrontend* frontend) : WriterBackend(frontend) { set_separator.assign((const char*)BifConst::LogSQLite::set_separator->Bytes(), BifConst::LogSQLite::set_separator->Len()); diff --git a/src/logging/writers/sqlite/SQLite.h b/src/logging/writers/sqlite/SQLite.h index 619a3f3d9a..86181037a7 100644 --- a/src/logging/writers/sqlite/SQLite.h +++ b/src/logging/writers/sqlite/SQLite.h @@ -32,11 +32,11 @@ private: int AddParams(threading::Value* val, int pos); std::string GetTableType(int, int); - const threading::Field* const* fields; // raw mapping - unsigned int num_fields; + const threading::Field* const* fields = nullptr; // raw mapping + unsigned int num_fields = 0; - sqlite3* db; - sqlite3_stmt* st; + sqlite3* db = nullptr; + sqlite3_stmt* st = nullptr; std::string set_separator; std::string unset_field; diff --git a/src/make_dbg_constants.py b/src/make_dbg_constants.py index 7b2d0b3ba8..53bcda8d47 100644 --- a/src/make_dbg_constants.py +++ b/src/make_dbg_constants.py @@ -39,7 +39,7 @@ enum_str = f""" // This file was automatically generated from {inputfile} // DO NOT EDIT. // -enum DebugCmd {{ +enum DebugCmd : uint8_t {{ """ init_str = f""" diff --git a/src/net_util.h b/src/net_util.h index 008a212795..9591b84142 100644 --- a/src/net_util.h +++ b/src/net_util.h @@ -125,7 +125,7 @@ enum TransportProto : uint8_t { extern const char* transport_proto_string(TransportProto proto); -enum IPFamily { IPv4, IPv6 }; +enum IPFamily : uint8_t { IPv4, IPv6 }; namespace zeek { diff --git a/src/packet_analysis/protocol/gtpv1/GTPv1.cc b/src/packet_analysis/protocol/gtpv1/GTPv1.cc index d724725b54..9dbfccdb80 100644 --- a/src/packet_analysis/protocol/gtpv1/GTPv1.cc +++ b/src/packet_analysis/protocol/gtpv1/GTPv1.cc @@ -55,7 +55,7 @@ bool GTPv1_Analyzer::AnalyzePacket(size_t len, const uint8_t* data, Packet* pack std::shared_ptr inner = nullptr; auto result = packet_analysis::IP::ParsePacket(len, data, next_header, inner); - if ( result == packet_analysis::IP::ParseResult::Ok ) { + if ( result == packet_analysis::IP::ParseResult::OK ) { cm_it->second->set_valid(packet->is_orig, true); if ( (! BifConst::Tunnel::delay_gtp_confirmation) || @@ -67,12 +67,12 @@ bool GTPv1_Analyzer::AnalyzePacket(size_t len, const uint8_t* data, Packet* pack gtp_hdr_val = nullptr; } } - else if ( result == packet_analysis::IP::ParseResult::BadProtocol ) { + else if ( result == packet_analysis::IP::ParseResult::BAD_PROTOCOL ) { AnalyzerViolation("Invalid IP version in wrapped packet", packet->session); gtp_hdr_val = nullptr; return false; } - else if ( result == packet_analysis::IP::ParseResult::CaplenTooSmall ) { + else if ( result == packet_analysis::IP::ParseResult::CAPLEN_TOO_SMALL ) { AnalyzerViolation("Truncated GTPv1", packet->session); gtp_hdr_val = nullptr; return false; diff --git a/src/packet_analysis/protocol/ip/IP.cc b/src/packet_analysis/protocol/ip/IP.cc index e57a04d267..fd84d388d2 100644 --- a/src/packet_analysis/protocol/ip/IP.cc +++ b/src/packet_analysis/protocol/ip/IP.cc @@ -276,29 +276,29 @@ ParseResult zeek::packet_analysis::IP::ParsePacket(int caplen, const u_char* con std::shared_ptr& inner) { if ( proto == IPPROTO_IPV6 ) { if ( caplen < (int)sizeof(struct ip6_hdr) ) - return ParseResult::CaplenTooSmall; + return ParseResult::CAPLEN_TOO_SMALL; const struct ip6_hdr* ip6 = (const struct ip6_hdr*)pkt; inner = std::make_shared(ip6, false, caplen); if ( (ip6->ip6_ctlun.ip6_un2_vfc & 0xF0) != 0x60 ) - return ParseResult::BadProtocol; + return ParseResult::BAD_PROTOCOL; } else if ( proto == IPPROTO_IPV4 ) { if ( caplen < (int)sizeof(struct ip) ) - return ParseResult::BadProtocol; + return ParseResult::BAD_PROTOCOL; const struct ip* ip4 = (const struct ip*)pkt; inner = std::make_shared(ip4, false); if ( ip4->ip_v != 4 ) - return ParseResult::BadProtocol; + return ParseResult::BAD_PROTOCOL; } else { - return ParseResult::BadProtocol; + return ParseResult::BAD_PROTOCOL; } if ( (uint32_t)caplen != inner->TotalLen() ) - return (uint32_t)caplen < inner->TotalLen() ? ParseResult::CaplenTooSmall : ParseResult::CaplenTooLarge; + return (uint32_t)caplen < inner->TotalLen() ? ParseResult::CAPLEN_TOO_SMALL : ParseResult::CAPLEN_TOO_LARGE; - return ParseResult::Ok; + return ParseResult::OK; } diff --git a/src/packet_analysis/protocol/ip/IP.h b/src/packet_analysis/protocol/ip/IP.h index 5c06232c0c..ee2371ae18 100644 --- a/src/packet_analysis/protocol/ip/IP.h +++ b/src/packet_analysis/protocol/ip/IP.h @@ -29,7 +29,16 @@ private: zeek::detail::Discarder* discarder = nullptr; }; -enum class ParseResult { Ok = 0, CaplenTooSmall = -1, BadProtocol = -2, CaplenTooLarge = 1 }; +enum class ParseResult : int8_t { + CAPLEN_TOO_SMALL = -1, + CaplenTooSmall [[deprecated("Remove in v8.1, use ParseResult::CAPLEN_TOO_SMALL.")]] = CAPLEN_TOO_SMALL, + BAD_PROTOCOL = -2, + BadProtocol [[deprecated("Remove in v8.1, use ParseResult::BAD_PROTOCOL.")]] = BAD_PROTOCOL, + OK = 0, + Ok [[deprecated("Remove in v8.1, use ParseResult::OK.")]] = OK, + CAPLEN_TOO_LARGE = 1, + CaplenTooLarge [[deprecated("Remove in v8.1, use ParseResult::CAPLEN_TOO_LARGE.")]] = CAPLEN_TOO_LARGE, +}; /** * Returns a wrapper IP_Hdr object if \a pkt appears to be a valid IPv4 diff --git a/src/packet_analysis/protocol/ip/SessionAdapter.h b/src/packet_analysis/protocol/ip/SessionAdapter.h index 4fca79da85..d3ed0859f8 100644 --- a/src/packet_analysis/protocol/ip/SessionAdapter.h +++ b/src/packet_analysis/protocol/ip/SessionAdapter.h @@ -24,7 +24,7 @@ public: /** * Overridden from parent class. */ - virtual void Done() override; + void Done() override; /** * Sets the parent packet analyzer for this session adapter. This can't be passed to diff --git a/src/packet_analysis/protocol/iptunnel/IPTunnel.cc b/src/packet_analysis/protocol/iptunnel/IPTunnel.cc index a6330fff2d..e933e4ae25 100644 --- a/src/packet_analysis/protocol/iptunnel/IPTunnel.cc +++ b/src/packet_analysis/protocol/iptunnel/IPTunnel.cc @@ -37,14 +37,14 @@ bool IPTunnelAnalyzer::AnalyzePacket(size_t len, const uint8_t* data, Packet* pa if ( gre_version != 0 ) { // Check for a valid inner packet first. auto result = packet_analysis::IP::ParsePacket(len, data, proto, inner); - if ( result == packet_analysis::IP::ParseResult::BadProtocol ) + if ( result == packet_analysis::IP::ParseResult::BAD_PROTOCOL ) Weird("invalid_inner_IP_version", packet); - else if ( result < packet_analysis::IP::ParseResult::CaplenTooSmall ) + else if ( result == packet_analysis::IP::ParseResult::CAPLEN_TOO_SMALL ) Weird("truncated_inner_IP", packet); - else if ( result > packet_analysis::IP::ParseResult::CaplenTooLarge ) + else if ( result == packet_analysis::IP::ParseResult::CAPLEN_TOO_LARGE ) Weird("inner_IP_payload_length_mismatch", packet); - if ( result != packet_analysis::IP::ParseResult::Ok ) + if ( result != packet_analysis::IP::ParseResult::OK ) return false; } diff --git a/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc b/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc index 7722b5198d..b7a73d5da1 100644 --- a/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc +++ b/src/packet_analysis/protocol/tcp/TCPSessionAdapter.cc @@ -192,16 +192,17 @@ static void update_history(analyzer::tcp::TCP_Flags flags, analyzer::tcp::TCP_En int bits_set = (flags.SYN() ? 1 : 0) + (flags.FIN() ? 1 : 0) + (flags.RST() ? 1 : 0); if ( bits_set > 1 ) { if ( flags.FIN() && flags.RST() ) - endpoint->CheckHistory(HIST_FIN_RST_PKT, 'I'); + endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_FIN_RST_PKT, 'I'); else - endpoint->CheckHistory(HIST_MULTI_FLAG_PKT, 'Q'); + endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_MULTI_FLAG_PKT, 'Q'); } else if ( bits_set == 1 ) { if ( flags.SYN() ) { char code = flags.ACK() ? 'H' : 'S'; - if ( endpoint->CheckHistory(HIST_SYN_PKT, code) && rel_seq != endpoint->hist_last_SYN ) + if ( endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_SYN_PKT, code) && + rel_seq != endpoint->hist_last_SYN ) endpoint->AddHistory(code); endpoint->hist_last_SYN = rel_seq; @@ -211,14 +212,16 @@ static void update_history(analyzer::tcp::TCP_Flags flags, analyzer::tcp::TCP_En // For FIN's, the sequence number comes at the // end of (any data in) the packet, not the // beginning as for SYNs and RSTs. - if ( endpoint->CheckHistory(HIST_FIN_PKT, 'F') && rel_seq + len != endpoint->hist_last_FIN ) + if ( endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_FIN_PKT, 'F') && + rel_seq + len != endpoint->hist_last_FIN ) endpoint->AddHistory('F'); endpoint->hist_last_FIN = rel_seq + len; } if ( flags.RST() ) { - if ( endpoint->CheckHistory(HIST_RST_PKT, 'R') && rel_seq != endpoint->hist_last_RST ) + if ( endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_RST_PKT, 'R') && + rel_seq != endpoint->hist_last_RST ) endpoint->AddHistory('R'); endpoint->hist_last_RST = rel_seq; @@ -227,10 +230,10 @@ static void update_history(analyzer::tcp::TCP_Flags flags, analyzer::tcp::TCP_En else { // bits_set == 0 if ( len ) - endpoint->CheckHistory(HIST_DATA_PKT, 'D'); + endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_DATA_PKT, 'D'); else if ( flags.ACK() ) - endpoint->CheckHistory(HIST_ACK_PKT, 'A'); + endpoint->CheckHistory(analyzer::tcp::TCP_Endpoint::HIST_ACK_PKT, 'A'); } } @@ -1142,28 +1145,28 @@ void TCPSessionAdapter::DeleteTimer(double /* t */) { session_mgr->Remove(Conn() void TCPSessionAdapter::ConnDeleteTimer(double t) { Conn()->DeleteTimer(t); } void TCPSessionAdapter::SetContentsFile(unsigned int direction, FilePtr f) { - if ( direction == CONTENTS_NONE ) { + if ( direction == analyzer::CONTENTS_NONE ) { orig->SetContentsFile(nullptr); resp->SetContentsFile(nullptr); } else { - if ( direction == CONTENTS_ORIG || direction == CONTENTS_BOTH ) + if ( direction == analyzer::CONTENTS_ORIG || direction == analyzer::CONTENTS_BOTH ) orig->SetContentsFile(f); - if ( direction == CONTENTS_RESP || direction == CONTENTS_BOTH ) + if ( direction == analyzer::CONTENTS_RESP || direction == analyzer::CONTENTS_BOTH ) resp->SetContentsFile(f); } } FilePtr TCPSessionAdapter::GetContentsFile(unsigned int direction) const { switch ( direction ) { - case CONTENTS_NONE: return nullptr; + case analyzer::CONTENTS_NONE: return nullptr; - case CONTENTS_ORIG: return orig->GetContentsFile(); + case analyzer::CONTENTS_ORIG: return orig->GetContentsFile(); - case CONTENTS_RESP: return resp->GetContentsFile(); + case analyzer::CONTENTS_RESP: return resp->GetContentsFile(); - case CONTENTS_BOTH: + case analyzer::CONTENTS_BOTH: if ( orig->GetContentsFile() != resp->GetContentsFile() ) // This is an "error". return nullptr; diff --git a/src/packet_analysis/protocol/teredo/Teredo.cc b/src/packet_analysis/protocol/teredo/Teredo.cc index b12ff52235..68acf554bf 100644 --- a/src/packet_analysis/protocol/teredo/Teredo.cc +++ b/src/packet_analysis/protocol/teredo/Teredo.cc @@ -168,7 +168,7 @@ bool TeredoAnalyzer::AnalyzePacket(size_t len, const uint8_t* data, Packet* pack // and reused in the IP analyzer somehow? std::shared_ptr inner = nullptr; auto result = packet_analysis::IP::ParsePacket(len, te.InnerIP(), IPPROTO_IPV6, inner); - if ( result == packet_analysis::IP::ParseResult::CaplenTooLarge ) { + if ( result == packet_analysis::IP::ParseResult::CAPLEN_TOO_LARGE ) { if ( inner->NextProto() == IPPROTO_NONE && inner->PayloadLen() == 0 ) // Teredo bubbles having data after IPv6 header isn't strictly a // violation, but a little weird. @@ -179,8 +179,8 @@ bool TeredoAnalyzer::AnalyzePacket(size_t len, const uint8_t* data, Packet* pack } } - if ( result == packet_analysis::IP::ParseResult::CaplenTooSmall || - result == packet_analysis::IP::ParseResult::BadProtocol ) { + if ( result == packet_analysis::IP::ParseResult::CAPLEN_TOO_SMALL || + result == packet_analysis::IP::ParseResult::BAD_PROTOCOL ) { AnalyzerViolation("Truncated Teredo or invalid inner IP version", conn, (const char*)data, len); return false; } diff --git a/src/plugin/Component.h b/src/plugin/Component.h index 6975f77092..3dd07fd03c 100644 --- a/src/plugin/Component.h +++ b/src/plugin/Component.h @@ -23,7 +23,7 @@ namespace component { /** * Component types. */ -enum Type { +enum Type : uint8_t { READER, /// An input reader (not currently used). WRITER, /// A logging writer (not currently used). ANALYZER, /// A protocol analyzer. diff --git a/src/plugin/Manager.h b/src/plugin/Manager.h index 7f80fbed78..a37c0031a5 100644 --- a/src/plugin/Manager.h +++ b/src/plugin/Manager.h @@ -33,6 +33,7 @@ namespace plugin { * * @param method_call The \a Manager method corresponding to the hook. */ +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define PLUGIN_HOOK_VOID(hook, method_call) \ { \ if ( zeek::plugin_mgr->HavePluginForHook(zeek::plugin::hook) ) \ @@ -49,6 +50,7 @@ namespace plugin { * @param default_result: The result to use if there's no plugin implementing * the hook. */ +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define PLUGIN_HOOK_WITH_RESULT(hook, method_call, default_result) \ (zeek::plugin_mgr->HavePluginForHook(zeek::plugin::hook) ? zeek::plugin_mgr->method_call : (default_result)) diff --git a/src/plugin/Plugin.h b/src/plugin/Plugin.h index 7d9c128d89..788cdac4d3 100644 --- a/src/plugin/Plugin.h +++ b/src/plugin/Plugin.h @@ -70,7 +70,7 @@ class Plugin; * Hook types that a plugin may define. Each label maps to the corresponding * virtual method in \a Plugin. */ -enum HookType { +enum HookType : uint8_t { // Note: when changing this table, update hook_name() in Plugin.cc. HOOK_LOAD_FILE, //< Activates Plugin::HookLoadFile(). HOOK_LOAD_FILE_EXT, //< Activates Plugin::HookLoadFileExtended(). @@ -136,12 +136,12 @@ public: #endif } - Configuration(Configuration&& c) { + Configuration(Configuration&& c) noexcept { zeek_version = std::move(c.zeek_version); name = std::move(c.name); description = std::move(c.description); - version = std::move(c.version); + version = c.version; } Configuration(const Configuration& c) { @@ -152,12 +152,12 @@ public: version = c.version; } - Configuration& operator=(Configuration&& c) { + Configuration& operator=(Configuration&& c) noexcept { zeek_version = std::move(c.zeek_version); name = std::move(c.name); description = std::move(c.description); - version = std::move(c.version); + version = c.version; return *this; } @@ -192,7 +192,13 @@ public: /** * Type of the item. */ - enum Type { FUNCTION = 1, EVENT = 2, CONSTANT = 3, GLOBAL = 4, TYPE = 5 }; + enum Type : uint8_t { + FUNCTION = 1, + EVENT = 2, + CONSTANT = 3, + GLOBAL = 4, + TYPE = 5, + }; /** * Constructor. @@ -242,7 +248,7 @@ public: /** * Type of the argument. */ - enum Type { + enum Type : uint8_t { BOOL, DOUBLE, EVENT, @@ -669,7 +675,7 @@ public: /** * The different types of @loads supported by HookLoadFile. */ - enum LoadType { SCRIPT, SIGNATURES, PLUGIN }; + enum LoadType : uint8_t { SCRIPT, SIGNATURES, PLUGIN }; /** * Constructor. diff --git a/src/probabilistic/BloomFilter.h b/src/probabilistic/BloomFilter.h index eed5d4e436..bbeb68b810 100644 --- a/src/probabilistic/BloomFilter.h +++ b/src/probabilistic/BloomFilter.h @@ -20,7 +20,7 @@ class CounterVector; } /** Types of derived BloomFilter classes. */ -enum BloomFilterType { Basic, Counting }; +enum BloomFilterType : uint8_t { Basic, Counting }; /** * The abstract base class for Bloom filters. diff --git a/src/probabilistic/CounterVector.h b/src/probabilistic/CounterVector.h index a63285a7ba..7732a58a93 100644 --- a/src/probabilistic/CounterVector.h +++ b/src/probabilistic/CounterVector.h @@ -47,6 +47,8 @@ public: */ virtual ~CounterVector(); + CounterVector& operator=(const CounterVector&) = delete; + /** * Increments a given cell. * @@ -157,8 +159,6 @@ protected: CounterVector() = default; private: - CounterVector& operator=(const CounterVector&); // Disable. - BitVector* bits = nullptr; size_t width = 0; }; diff --git a/src/probabilistic/Hasher.h b/src/probabilistic/Hasher.h index 53f46e75fa..208510d57c 100644 --- a/src/probabilistic/Hasher.h +++ b/src/probabilistic/Hasher.h @@ -15,7 +15,7 @@ class BrokerDataView; namespace zeek::probabilistic::detail { /** Types of derived Hasher classes. */ -enum HasherType { Default, Double }; +enum HasherType : uint8_t { Default, Double }; /** * Abstract base class for hashers. A hasher creates a family of hash diff --git a/src/scan.l b/src/scan.l index 8a5d796736..339c5e7f95 100644 --- a/src/scan.l +++ b/src/scan.l @@ -653,12 +653,12 @@ F RET_CONST(zeek::val_mgr->False()->Ref()) RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UNKNOWN)->Ref()) } -{FLOAT}{OWS}day(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Days)) -{FLOAT}{OWS}hr(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Hours)) -{FLOAT}{OWS}min(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Minutes)) -{FLOAT}{OWS}sec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Seconds)) -{FLOAT}{OWS}msec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Milliseconds)) -{FLOAT}{OWS}usec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Microseconds)) +{FLOAT}{OWS}day(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Days)) +{FLOAT}{OWS}hr(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Hours)) +{FLOAT}{OWS}min(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Minutes)) +{FLOAT}{OWS}sec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Seconds)) +{FLOAT}{OWS}msec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Milliseconds)) +{FLOAT}{OWS}usec(s?) RET_CONST(new zeek::IntervalVal(atof(yytext), zeek::Microseconds)) "0x"{HEX}+ RET_CONST(zeek::val_mgr->Count(static_cast(strtoull(yytext, 0, 16))).release()) diff --git a/src/script_opt/CPP/AttrExprType.h b/src/script_opt/CPP/AttrExprType.h index 9a8ce8c74b..cabcfa2bc8 100644 --- a/src/script_opt/CPP/AttrExprType.h +++ b/src/script_opt/CPP/AttrExprType.h @@ -4,9 +4,11 @@ #pragma once +#include + namespace zeek::detail { -enum AttrExprType { +enum AttrExprType : uint8_t { AE_NONE, // attribute doesn't have an expression AE_CONST, // easy expression - a constant (ConstExpr) AE_NAME, // easy - a global (NameExpr) diff --git a/src/script_opt/CPP/Exprs.h b/src/script_opt/CPP/Exprs.h index c5830e8ff3..422f00f9a7 100644 --- a/src/script_opt/CPP/Exprs.h +++ b/src/script_opt/CPP/Exprs.h @@ -16,7 +16,10 @@ // values, the end goal is to have the value in (1) native form, (2) instead // in ValPtr form, or (3) whichever is more convenient to generate (sometimes // used when the caller knows that the value is non-native). -enum GenType { + +#include + +enum GenType : uint8_t { GEN_NATIVE, GEN_VAL_PTR, GEN_DONT_CARE, diff --git a/src/script_opt/CPP/RuntimeInits.h b/src/script_opt/CPP/RuntimeInits.h index e582f0f492..c1fa9f87da 100644 --- a/src/script_opt/CPP/RuntimeInits.h +++ b/src/script_opt/CPP/RuntimeInits.h @@ -327,6 +327,8 @@ public: inits_vec.resize(inits.size()); } + virtual ~CPP_AbstractBasicConsts() = default; + void InitializeCohort(InitsManager* im, int cohort) { ASSERT(cohort == 0); auto& offsets_vec = im->Indices(offsets_set); diff --git a/src/script_opt/Expr.h b/src/script_opt/Expr.h index 491b9c59fe..613daa3732 100644 --- a/src/script_opt/Expr.h +++ b/src/script_opt/Expr.h @@ -68,8 +68,8 @@ public: ExprPtr Reduce(Reducer* c, StmtPtr& red_stmt) override; ExprPtr ReduceToSingleton(Reducer* c, StmtPtr& red_stmt) override; - ExprPtr GetOp3() const override final { return op3; } - void SetOp3(ExprPtr _op) override final { op3 = std::move(_op); } + ExprPtr GetOp3() const final { return op3; } + void SetOp3(ExprPtr _op) final { op3 = std::move(_op); } TraversalCode Traverse(TraversalCallback* cb) const override; @@ -234,7 +234,7 @@ protected: class ScriptOptBuiltinExpr : public Expr { public: - enum SOBuiltInTag { + enum SOBuiltInTag : uint8_t { MINIMUM, MAXIMUM, HAS_ELEMENTS, @@ -246,11 +246,11 @@ public: auto Tag() const { return tag; } - ExprPtr GetOp1() const override final { return arg1; } - ExprPtr GetOp2() const override final { return arg2; } + ExprPtr GetOp1() const final { return arg1; } + ExprPtr GetOp2() const final { return arg2; } - void SetOp1(ExprPtr op) override final { arg1 = std::move(op); } - void SetOp2(ExprPtr op) override final { arg2 = std::move(op); } + void SetOp1(ExprPtr op) final { arg1 = std::move(op); } + void SetOp2(ExprPtr op) final { arg2 = std::move(op); } ValPtr Eval(Frame* f) const override; diff --git a/src/script_opt/IDOptInfo.h b/src/script_opt/IDOptInfo.h index 5dd07c85e2..2ac7d037e5 100644 --- a/src/script_opt/IDOptInfo.h +++ b/src/script_opt/IDOptInfo.h @@ -18,7 +18,7 @@ class Stmt; using ExprPtr = IntrusivePtr; -#define NO_DEF -1 +constexpr int NO_DEF = -1; // This class tracks a single region during which an identifier has // a consistent state of definition, meaning either it's (1) defined diff --git a/src/script_opt/ProfileFunc.h b/src/script_opt/ProfileFunc.h index feb78ce786..d3f410cd0d 100644 --- a/src/script_opt/ProfileFunc.h +++ b/src/script_opt/ProfileFunc.h @@ -314,7 +314,7 @@ public: // CONSTRUCTION - relevant for constructing/coercing a record // READ - relevant for reading a table element // WRITE - relevant for modifying a table element - enum AccessType { NONE, CALL, CONSTRUCTION, READ, WRITE }; + enum AccessType : uint8_t { NONE, CALL, CONSTRUCTION, READ, WRITE }; SideEffectsOp(AccessType at = NONE, const Type* t = nullptr) : access(at), type(t) {} diff --git a/src/script_opt/ZAM/BuiltIn.h b/src/script_opt/ZAM/BuiltIn.h index e59b90778b..8274dde7bd 100644 --- a/src/script_opt/ZAM/BuiltIn.h +++ b/src/script_opt/ZAM/BuiltIn.h @@ -132,7 +132,7 @@ public: // values assigned to them reflecting the bit-pattern of the arguments from // left (most significant) to right (least), with a 1-bit encoding Constant, // 0-bit for Variable. -enum BiFArgsType { +enum BiFArgsType : uint8_t { VV = 0x0, VC = 0x1, CV = 0x2, diff --git a/src/script_opt/ZAM/IterInfo.h b/src/script_opt/ZAM/IterInfo.h index 69d6f45ac0..36b63c8c61 100644 --- a/src/script_opt/ZAM/IterInfo.h +++ b/src/script_opt/ZAM/IterInfo.h @@ -96,7 +96,7 @@ public: // For the current iteration, returns the corresponding value. ZVal IterValue() { auto tev = (*tbl_iter)->value; - return ZVal(tev->GetVal(), value_var_type); + return {tev->GetVal(), value_var_type}; } // Called upon finishing the iteration. diff --git a/src/script_opt/ZAM/OPs/calls.op b/src/script_opt/ZAM/OPs/calls.op index 5fcbdda607..b78b7f2a9d 100644 --- a/src/script_opt/ZAM/OPs/calls.op +++ b/src/script_opt/ZAM/OPs/calls.op @@ -144,6 +144,7 @@ macro WhenCall(lhs, func) auto current_assoc = Z_FRAME->GetTriggerAssoc(); auto n = aux->n; std::vector args; + args.reserve(n); for ( auto i = 0; i < n; ++i ) args.push_back(aux->ToVal(frame, i)); Z_FRAME->SetCall(Z_AUX->call_expr.get()); diff --git a/src/script_opt/ZAM/OPs/indexing.op b/src/script_opt/ZAM/OPs/indexing.op index 85f3691150..2a436c7584 100644 --- a/src/script_opt/ZAM/OPs/indexing.op +++ b/src/script_opt/ZAM/OPs/indexing.op @@ -88,7 +88,7 @@ eval EvalIndexAnyVec($$, $1, $2) macro WhenIndexResCheck(vec) if ( vec && IndexExprWhen::evaluating > 0 ) - IndexExprWhen::results.push_back({NewRef{}, vec}); + IndexExprWhen::results.emplace_back(NewRef{}, vec); internal-op When-Index-Vec class VVV diff --git a/src/script_opt/ZAM/OPs/stmts.op b/src/script_opt/ZAM/OPs/stmts.op index b74cbdd1e9..7572d63155 100644 --- a/src/script_opt/ZAM/OPs/stmts.op +++ b/src/script_opt/ZAM/OPs/stmts.op @@ -354,7 +354,7 @@ op1-read classes VC op-types I S eval { - zeek::StringValPtr msg_val = zeek::val_mgr->EmptyString(); + const zeek::StringValPtr& msg_val = zeek::val_mgr->EmptyString(); report_assert($$, $1->ToStdString(), msg_val, Z_LOC->Loc()); } diff --git a/src/script_opt/ZAM/OPs/unary-exprs.op b/src/script_opt/ZAM/OPs/unary-exprs.op index 09d8f9d736..a9a1abf57a 100644 --- a/src/script_opt/ZAM/OPs/unary-exprs.op +++ b/src/script_opt/ZAM/OPs/unary-exprs.op @@ -95,7 +95,7 @@ eval auto vv = $1.AsVector(); vv->Assign(0, $2.ToVal(Z_TYPE)); else { - vv->RawVec().push_back(CopyVal($2)); + vv->RawVec().emplace_back(CopyVal($2)); vv->Modified(); } diff --git a/src/script_opt/ZAM/ZInstAux.h b/src/script_opt/ZAM/ZInstAux.h index 262261df4f..3d1f9bfb36 100644 --- a/src/script_opt/ZAM/ZInstAux.h +++ b/src/script_opt/ZAM/ZInstAux.h @@ -93,7 +93,7 @@ private: bool is_managed = false; }; -enum ControlFlowType { +enum ControlFlowType : uint8_t { CFT_IF, CFT_BLOCK_END, CFT_ELSE, diff --git a/src/script_opt/ZAM/ZOp.h b/src/script_opt/ZAM/ZOp.h index f2fdebd36c..190ed96ab3 100644 --- a/src/script_opt/ZAM/ZOp.h +++ b/src/script_opt/ZAM/ZOp.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include #include @@ -11,7 +12,7 @@ namespace zeek::detail { // Opcodes associated with ZAM instructions. -enum ZOp { +enum ZOp : uint16_t { #include "zeek/ZAM-OpsDefs.h" OP_NOP, }; @@ -25,7 +26,7 @@ enum ZOp { // I1/I2/I3/I4: the instruction's integer value, used directly (not as a slot) // FRAME: a slot in the (interpreter) Frame object // X: no operands -enum ZAMOpType { +enum ZAMOpType : uint8_t { OP_X, OP_C, OP_V, @@ -56,7 +57,7 @@ enum ZAMOpType { }; // Possible "flavors" for an operator's first slot. -enum ZAMOp1Flavor { +enum ZAMOp1Flavor : uint8_t { OP1_READ, // the slot is read, not modified OP1_WRITE, // the slot is modified, not read - the most common OP1_READ_WRITE, // the slot is both read and then modified, e.g. "++" diff --git a/src/session/Session.h b/src/session/Session.h index 747a1c78e4..12e5111c53 100644 --- a/src/session/Session.h +++ b/src/session/Session.h @@ -30,7 +30,7 @@ constexpr uint32_t HIST_UNKNOWN_PKT = 0x400; // Initially for exceeded_tunnel_ma class Session; using timer_func = void (Session::*)(double t); -enum class AnalyzerConfirmationState { UNKNOWN, VIOLATED, CONFIRMED }; +enum class AnalyzerConfirmationState : uint8_t { UNKNOWN, VIOLATED, CONFIRMED }; class Session : public Obj { public: @@ -50,7 +50,7 @@ public: Session(double t, EventHandlerPtr timeout_event, EventHandlerPtr status_update_event = nullptr, double status_update_interval = 0); - virtual ~Session() {} + ~Session() override = default; /** * Invoked when the session is about to be removed. Use Ref(this) @@ -135,7 +135,7 @@ public: return EnqueueEvent(h, analyzer, zeek::Args{std::forward(args)...}); } - virtual void Describe(ODesc* d) const override; + void Describe(ODesc* d) const override; /** * Sets the session to expire after a given amount of time. @@ -326,4 +326,5 @@ protected: } // namespace session } // namespace zeek +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define ADD_TIMER(timer, t, do_expire, type) AddTimer(timer_func(timer), (t), (do_expire), (type)) diff --git a/src/spicy/cookie.h b/src/spicy/cookie.h index 2739f0d026..b27c64c37d 100644 --- a/src/spicy/cookie.h +++ b/src/spicy/cookie.h @@ -171,7 +171,7 @@ struct Cookie { bool confirmed = false; // valid only for protocol analyzers; } cache; - enum Tag { Protocol, File, Packet }; + enum Tag : uint8_t { Protocol, File, Packet }; /** Returns the type of cookie currently stored. */ Tag tag() const { @@ -185,6 +185,9 @@ struct Cookie { throw std::runtime_error("invalid cookie"); } + Cookie(const Cookie& other) = delete; + Cookie& operator=(const Cookie& other) = delete; + private: union Data { cookie::ProtocolAnalyzer protocol; @@ -242,9 +245,6 @@ private: packet = &data.packet; } - Cookie(const Cookie& other) = delete; - Cookie& operator=(const Cookie& other) = delete; - friend inline void swap(Cookie& lhs, Cookie& rhs) noexcept { Cookie tmp = std::move(lhs); lhs = std::move(rhs); diff --git a/src/spicy/file-analyzer.h b/src/spicy/file-analyzer.h index 2bb6506a88..ad4bba6d86 100644 --- a/src/spicy/file-analyzer.h +++ b/src/spicy/file-analyzer.h @@ -25,6 +25,8 @@ public: */ FileState(Cookie cookie) : ParsingState(::spicy::rt::driver::ParsingType::Stream), _cookie(std::move(cookie)) {} + virtual ~FileState() = default; + /** Returns the cookie pointer to use with the runtime library during analysis. */ auto* cookie() { return &_cookie; } @@ -53,7 +55,7 @@ private: class FileAnalyzer : public file_analysis::Analyzer { public: FileAnalyzer(RecordValPtr arg_args, file_analysis::File* arg_file); - virtual ~FileAnalyzer(); + ~FileAnalyzer() override; static file_analysis::Analyzer* InstantiateAnalyzer(RecordValPtr args, file_analysis::File* file); diff --git a/src/spicy/manager.h b/src/spicy/manager.h index 55f47c51fd..9ebc2aceb7 100644 --- a/src/spicy/manager.h +++ b/src/spicy/manager.h @@ -23,6 +23,7 @@ // Macro helper to report Spicy debug messages. This forwards to // to both the Zeek logger and the Spicy runtime logger. +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #define SPICY_DEBUG(msg) ::zeek::spicy::log(msg); namespace hilti::rt { @@ -63,7 +64,7 @@ inline void log(const std::string& msg) { class Manager : public zeek::plugin::Plugin { public: Manager() {} - virtual ~Manager(); + ~Manager() override; /** * Runtime method to begin registration of a Spicy EVT module. All diff --git a/src/spicy/packet-analyzer.h b/src/spicy/packet-analyzer.h index 7d68e322db..351daa4711 100644 --- a/src/spicy/packet-analyzer.h +++ b/src/spicy/packet-analyzer.h @@ -26,6 +26,8 @@ public: */ PacketState(Cookie cookie) : ParsingState(::spicy::rt::driver::ParsingType::Block), _cookie(std::move(cookie)) {} + virtual ~PacketState() = default; + /** Returns the cookie pointer to use with the runtime library during analysis. */ auto* cookie() { return &_cookie; } @@ -54,7 +56,7 @@ private: class PacketAnalyzer : public packet_analysis::Analyzer { public: PacketAnalyzer(std::string name); - virtual ~PacketAnalyzer(); + ~PacketAnalyzer() override; /** Records a debug message. */ void DebugMsg(const std::string& msg) { _state.DebugMsg(msg); } diff --git a/src/spicy/port-range.h b/src/spicy/port-range.h index 7e71d433f8..914165159e 100644 --- a/src/spicy/port-range.h +++ b/src/spicy/port-range.h @@ -32,6 +32,6 @@ inline bool operator==(const PortRange& a, const PortRange& b) { inline bool operator!=(const PortRange& a, const PortRange& b) { return ! (a == b); } -inline PortRange make_port_range(hilti::rt::Port begin, hilti::rt::Port end) { return PortRange(begin, end); } +inline PortRange make_port_range(hilti::rt::Port begin, hilti::rt::Port end) { return {begin, end}; } } // namespace zeek::spicy::rt diff --git a/src/spicy/protocol-analyzer.h b/src/spicy/protocol-analyzer.h index df4115b587..affb091235 100644 --- a/src/spicy/protocol-analyzer.h +++ b/src/spicy/protocol-analyzer.h @@ -17,6 +17,11 @@ namespace zeek::spicy::rt { /** Parsing state for one endpoint of the connection. */ +// FIXME: It's strange that the parent class of this does not have a virtual destructor, +// but fixing it requires also implementing copy constructor/operators, and it turns into +// a rabbit hole. +// +// NOLINTNEXTLINE(cppcoreguidelines-virtual-class-destructor) class EndpointState : public ::spicy::rt::driver::ParsingState { public: /** @@ -123,7 +128,7 @@ private: class TCP_Analyzer : public ProtocolAnalyzer, public analyzer::tcp::TCP_ApplicationAnalyzer { public: TCP_Analyzer(Connection* conn); - virtual ~TCP_Analyzer(); + ~TCP_Analyzer() override; // Overridden from Spicy's Analyzer. void Init() override; @@ -151,7 +156,7 @@ public: class UDP_Analyzer : public ProtocolAnalyzer, public analyzer::Analyzer { public: UDP_Analyzer(Connection* conn); - virtual ~UDP_Analyzer(); + ~UDP_Analyzer() override; // Overridden from Spicy's Analyzer. void Init() override; diff --git a/src/spicy/runtime-support.h b/src/spicy/runtime-support.h index 3766e5b904..fef0957824 100644 --- a/src/spicy/runtime-support.h +++ b/src/spicy/runtime-support.h @@ -141,7 +141,7 @@ void register_spicy_module_end(); /** Identifies a Zeek-side type. */ -enum class ZeekTypeTag : uint64_t { +enum class ZeekTypeTag : uint8_t { Addr, Any, Bool, @@ -549,7 +549,7 @@ inline ::hilti::rt::Address as_address(const ValPtr& v) { /** Converts a Zeek `bool` value to its Spicy equivalent. Throws on error. */ inline ::hilti::rt::Bool as_bool(const ValPtr& v) { detail::check_type(v, TYPE_BOOL, "bool"); - return ::hilti::rt::Bool(v->AsBool()); + return {v->AsBool()}; } /** Converts a Zeek `count` value to its Spicy equivalent. Throws on error. */ @@ -592,7 +592,7 @@ inline ::hilti::rt::Port as_port(const ValPtr& v) { auto p = v->AsPortVal(); // Wrap port number into safe integer to catch any overflows (Zeek returns // an uint32, while HILTI wants an uint16). - return ::hilti::rt::Port(hilti::rt::integer::safe(p->Port()), p->PortType()); + return {hilti::rt::integer::safe(p->Port()), p->PortType()}; } /** Converts a Zeek `record` value to its Spicy equivalent. Throws on error. */ @@ -615,14 +615,14 @@ inline ValSetPtr as_set(const ValPtr& v) { inline hilti::rt::Bytes as_string(const ValPtr& v) { detail::check_type(v, TYPE_STRING, "string"); auto str = v->AsString(); - return hilti::rt::Bytes(reinterpret_cast(str->Bytes()), str->Len()); + return {reinterpret_cast(str->Bytes()), static_cast(str->Len())}; } /** Converts a Zeek `subnet` value to its Spicy equivalent. Throws on error. */ inline ::hilti::rt::Network as_subnet(const ValPtr& v) { detail::check_type(v, TYPE_SUBNET, "subnet"); auto subnet = v->AsSubNet(); - return ::hilti::rt::Network(subnet.Prefix(), subnet.Length()); + return {subnet.Prefix(), subnet.Length()}; } /** Converts a Zeek `table` value to its Spicy equivalent. Throws on error. */ diff --git a/src/spicy/spicyz/config.h.in b/src/spicy/spicyz/config.h.in index 6737049809..80a6c2f31d 100644 --- a/src/spicy/spicyz/config.h.in +++ b/src/spicy/spicyz/config.h.in @@ -29,7 +29,7 @@ static inline void add_path(std::string& old_path, const path& new_path) { static path get_env_path_or(const char* name, const char* default_) { assert(std::strlen(default_) != 0); if ( auto p = hilti::rt::getenv(name); p && ! p->empty() ) - return path(*p); + return {*p}; else return default_; } @@ -56,7 +56,8 @@ inline const auto CxxZeekIncludesDirectories() { return includes; } -// Version of Spicy that we are compiling against. +// Version of Spicy that we are compiling against. Used for codegen changes in glue-compiler.cc. +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) #cmakedefine SPICY_VERSION_NUMBER ${SPICY_VERSION_NUMBER} inline const auto InstallPrefix = path("${CMAKE_INSTALL_PREFIX}"); diff --git a/src/storage/backend/redis/CMakeLists.txt b/src/storage/backend/redis/CMakeLists.txt index c9f5f1b38d..e04d34fbf2 100644 --- a/src/storage/backend/redis/CMakeLists.txt +++ b/src/storage/backend/redis/CMakeLists.txt @@ -15,7 +15,7 @@ if (ENABLE_STORAGE_BACKEND_REDIS) zeek_add_plugin( Zeek Storage_Backend_Redis - INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${HIREDIS_INCLUDE_DIRS} + INCLUDE_DIRS ${HIREDIS_INCLUDE_DIRS} DEPENDENCIES ${HIREDIS_LIBRARIES} SOURCES Plugin.cc Redis.cc) diff --git a/src/strings.bif b/src/strings.bif index b212ec782b..49ba24a650 100644 --- a/src/strings.bif +++ b/src/strings.bif @@ -1146,28 +1146,19 @@ function find_first%(str: string, re: pattern%) : string function hexdump%(data_str: string%) : string %{ -// The width of a line of text in the hex-mode view, consisting -// of offset, hex view and ASCII view: -// -// 32 + 16 characters per 8 bytes, twice -// (2*7) + Single space between bytes, twice -// 4 + Two spaces between 8-byte sets and ASCII -// 1 + For newline -// 17 + For ASCII display, with spacer column -// 6 For 5-digit offset counter, including spacer -// -#define HEX_LINE_WIDTH 74 - -#define HEX_LINE_START 6 -#define HEX_LINE_END 53 -#define HEX_LINE_START_ASCII 56 -#define HEX_LINE_START_RIGHT_ASCII 65 -#define HEX_LINE_LEFT_MIDDLE 28 -#define HEX_LINE_RIGHT_MIDDLE 31 -#define HEX_BLOCK_LEN 23 -#define HEX_LINE_BYTES 16 -#define NULL_CHAR '.' -#define NONPRINT_CHAR '.' + // The width of a line of text in the hex-mode view, consisting + // of offset, hex view and ASCII view: + // + // 32 + 16 characters per 8 bytes, twice + // (2*7) + Single space between bytes, twice + // 4 + Two spaces between 8-byte sets and ASCII + // 1 + For newline + // 17 + For ASCII display, with spacer column + // 6 For 5-digit offset counter, including spacer + // + constexpr int HEX_LINE_WIDTH = 74; + constexpr char NULL_CHAR = '.'; + constexpr char NONPRINT_CHAR = '.'; const u_char* data = data_str->Bytes(); unsigned data_size = data_str->Len(); @@ -1211,7 +1202,7 @@ function hexdump%(data_str: string%) : string // If unprintable, use special characters: if ( val < 0x20 || val >= 0x7f ) { - if ( val == 0 ) + if ( val == 0x00 ) ascii_byte = NULL_CHAR; else ascii_byte = NONPRINT_CHAR; diff --git a/src/supervisor/Supervisor.h b/src/supervisor/Supervisor.h index 64d492fb22..c433c0536a 100644 --- a/src/supervisor/Supervisor.h +++ b/src/supervisor/Supervisor.h @@ -241,7 +241,7 @@ public: /** * Destruction also cleanly shuts down the entire supervised process tree. */ - ~Supervisor(); + ~Supervisor() override; /** * Perform some initialization that needs to happen after scripts are loaded diff --git a/src/telemetry/Manager.h b/src/telemetry/Manager.h index 0d90d9e4ad..a25387a710 100644 --- a/src/telemetry/Manager.h +++ b/src/telemetry/Manager.h @@ -47,7 +47,7 @@ public: Manager(const Manager&) = delete; Manager& operator=(const Manager&) = delete; - ~Manager(); + ~Manager() override; /** * Initialization of the manager. This is called late during Zeek's diff --git a/src/threading/BasicThread.h b/src/threading/BasicThread.h index 8b11e1c2c0..a3e6363c0c 100644 --- a/src/threading/BasicThread.h +++ b/src/threading/BasicThread.h @@ -37,6 +37,13 @@ public: BasicThread(BasicThread const&) = delete; BasicThread& operator=(BasicThread const&) = delete; + /** + * Destructor. This will be called by the manager. + * + * Only Zeek's main thread may delete thread instances. + */ + virtual ~BasicThread(); + /** * Returns a descriptive name for the thread. If not set via * SetName(), a default name is chosen automatically. @@ -168,14 +175,6 @@ protected: */ virtual void OnKill() {} - /** - * Destructor. This will be called by the manager. - * - * Only Zeek's main thread may delete thread instances. - * - */ - virtual ~BasicThread(); - /** * Waits until the thread's Run() method has finished and then joins * it. This is called from the threading::Manager. diff --git a/src/threading/Manager.h b/src/threading/Manager.h index 6eaefe5771..12f30c50d5 100644 --- a/src/threading/Manager.h +++ b/src/threading/Manager.h @@ -26,7 +26,7 @@ namespace detail { class HeartbeatTimer final : public zeek::detail::Timer { public: HeartbeatTimer(double t) : zeek::detail::Timer(t, zeek::detail::TIMER_THREAD_HEARTBEAT) {} - virtual ~HeartbeatTimer() {} + ~HeartbeatTimer() override = default; void Dispatch(double t, bool is_expire) override; diff --git a/src/threading/MsgThread.h b/src/threading/MsgThread.h index 0e486cf592..705888c310 100644 --- a/src/threading/MsgThread.h +++ b/src/threading/MsgThread.h @@ -54,7 +54,7 @@ public: /** * Destructor. */ - virtual ~MsgThread(); + ~MsgThread() override; /** * Sends a message to the child thread. The message will be processed diff --git a/src/threading/Queue.h b/src/threading/Queue.h index 850c5f7bcd..6b2670c028 100644 --- a/src/threading/Queue.h +++ b/src/threading/Queue.h @@ -196,6 +196,7 @@ inline std::vector> Queue::LocksForAllQueues() { std::vector> locks; try { + // NOLINTNEXTLINE(modernize-loop-convert) for ( int i = 0; i < NUM_QUEUES; i++ ) locks.emplace_back(std::unique_lock(mutex[i])); } @@ -216,6 +217,7 @@ inline uint64_t Queue::Size() { uint64_t size = 0; + // NOLINTNEXTLINE(modernize-loop-convert) for ( int i = 0; i < NUM_QUEUES; i++ ) size += messages[i].size(); diff --git a/src/threading/formatters/Ascii.h b/src/threading/formatters/Ascii.h index 800ec3fb98..f64318b580 100644 --- a/src/threading/formatters/Ascii.h +++ b/src/threading/formatters/Ascii.h @@ -46,10 +46,10 @@ public: Ascii(MsgThread* t, const SeparatorInfo& info); ~Ascii() override = default; - virtual bool Describe(ODesc* desc, Value* val, const std::string& name = "") const override; - virtual bool Describe(ODesc* desc, int num_fields, const Field* const* fields, Value** vals) const override; - virtual Value* ParseValue(const std::string& s, const std::string& name, TypeTag type, - TypeTag subtype = TYPE_ERROR) const override; + bool Describe(ODesc* desc, Value* val, const std::string& name = "") const override; + bool Describe(ODesc* desc, int num_fields, const Field* const* fields, Value** vals) const override; + Value* ParseValue(const std::string& s, const std::string& name, TypeTag type, + TypeTag subtype = TYPE_ERROR) const override; private: bool CheckNumberError(const char* start, const char* end, bool nonneg_only = false) const; diff --git a/src/threading/formatters/JSON.h b/src/threading/formatters/JSON.h index b0621012c0..fca567dcdf 100644 --- a/src/threading/formatters/JSON.h +++ b/src/threading/formatters/JSON.h @@ -18,7 +18,7 @@ namespace zeek::threading::formatter { */ class JSON : public Formatter { public: - enum TimeFormat { + enum TimeFormat : uint8_t { TS_EPOCH, // Doubles that represents seconds from the UNIX epoch. TS_ISO8601, // ISO 8601 defined human readable timestamp format. TS_MILLIS, // Signed milliseconds from the UNIX epoch. Some consumers need this (e.g., diff --git a/src/util.cc b/src/util.cc index 2a59ea8a2a..60d502e36c 100644 --- a/src/util.cc +++ b/src/util.cc @@ -1593,7 +1593,7 @@ const char* zeek_plugin_path() { const char* path = getenv("ZEEK_PLUGIN_PATH"); if ( ! path ) - path = BRO_PLUGIN_INSTALL_PATH; + path = ZEEK_PLUGIN_INSTALL_PATH; return path; } diff --git a/src/util.h b/src/util.h index 314f99bf37..429fd11120 100644 --- a/src/util.h +++ b/src/util.h @@ -38,6 +38,7 @@ #include +// NOLINTBEGIN(cppcoreguidelines-macro-usage) #ifdef ASSERT #undef ASSERT #endif @@ -55,6 +56,7 @@ #define DEBUG_fputs(...) #endif +// NOLINTEND(cppcoreguidelines-macro-usage) #ifdef USE_PERFTOOLS_DEBUG #include @@ -101,6 +103,10 @@ extern char* strcasestr(const char* s, const char* find); // This is used by the patricia code and so it remains outside of the namespace. extern "C" void out_of_memory(const char* where); +constexpr int UID_POOL_DEFAULT_INTERNAL = 1; +constexpr int UID_POOL_DEFAULT_SCRIPT = 2; +constexpr int UID_POOL_CUSTOM_SCRIPT = 10; // First available custom script level pool. + namespace zeek { class ODesc; @@ -408,9 +414,6 @@ extern double curr_CPU_time(); // instances. The integer can be drawn from different pools, which is helpful // when the random number generator is seeded to be deterministic. In that // case, the same sequence of integers is generated per pool. -#define UID_POOL_DEFAULT_INTERNAL 1 -#define UID_POOL_DEFAULT_SCRIPT 2 -#define UID_POOL_CUSTOM_SCRIPT 10 // First available custom script level pool. extern uint64_t calculate_unique_id(); extern uint64_t calculate_unique_id(const size_t pool); @@ -425,14 +428,20 @@ constexpr size_t pad_size(size_t size) { if ( size == 0 ) return 0; // glibc allocated 16 bytes anyway. - const int pad = 8; + const size_t pad = 8; if ( size < 12 ) return 2 * pad; return ((size + 3) / pad + 1) * pad; } -#define padded_sizeof(x) (zeek::util::pad_size(sizeof(x))) +template +constexpr size_t padded_size_of() { + return zeek::util::pad_size(sizeof(T)); +} + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define padded_sizeof(x) (zeek::util::padded_size_of()) // Like write() but handles interrupted system calls by restarting. Returns // true if the write was successful, otherwise sets errno. This function is @@ -454,11 +463,11 @@ extern void safe_close(int fd); // Versions of realloc/malloc which abort() on out of memory inline void* safe_realloc(void* ptr, size_t size) { - ptr = realloc(ptr, size); - if ( size && ! ptr ) + void* new_ptr = realloc(ptr, size); + if ( size && ! new_ptr ) out_of_memory("realloc"); - return ptr; + return new_ptr; } inline void* safe_malloc(size_t size) { diff --git a/src/zeekygen/IdentifierInfo.cc b/src/zeekygen/IdentifierInfo.cc index 0bce8a49f5..40ad06bbbe 100644 --- a/src/zeekygen/IdentifierInfo.cc +++ b/src/zeekygen/IdentifierInfo.cc @@ -19,7 +19,6 @@ IdentifierInfo::IdentifierInfo(zeek::detail::IDPtr arg_id, ScriptInfo* script, b initial_val(), redefs(), fields(), - last_field_seen(), declaring_script(script), from_redef(redef) { if ( id->GetVal() && (id->IsOption() || id->IsRedefinable()) ) diff --git a/src/zeekygen/IdentifierInfo.h b/src/zeekygen/IdentifierInfo.h index 22fffa768c..e8dbb65e36 100644 --- a/src/zeekygen/IdentifierInfo.h +++ b/src/zeekygen/IdentifierInfo.h @@ -185,8 +185,8 @@ private: ValPtr initial_val; redef_list redefs; record_field_map fields; - RecordField* last_field_seen; - ScriptInfo* declaring_script; + RecordField* last_field_seen = nullptr; + ScriptInfo* declaring_script = nullptr; bool from_redef = false; }; diff --git a/src/zeekygen/Manager.cc b/src/zeekygen/Manager.cc index 038a183775..ec285eb460 100644 --- a/src/zeekygen/Manager.cc +++ b/src/zeekygen/Manager.cc @@ -51,18 +51,14 @@ static string RemoveLeadingSpace(const string& s) { } Manager::Manager(const string& arg_config, const string& command) - : disabled(), - comment_buffer(), + : comment_buffer(), comment_buffer_map(), packages(), scripts(), identifiers(), all_info(), - last_identifier_seen(), - incomplete_type(), enum_mappings(), - config(arg_config), - mtime() { + config(arg_config) { if ( getenv("ZEEK_DISABLE_ZEEKYGEN") ) disabled = true; diff --git a/src/zeekygen/Manager.h b/src/zeekygen/Manager.h index 796553b2ad..9fc23990bf 100644 --- a/src/zeekygen/Manager.h +++ b/src/zeekygen/Manager.h @@ -226,7 +226,7 @@ private: IdentifierInfo* CreateIdentifierInfo(zeek::detail::IDPtr id, ScriptInfo* script, bool from_redef = false); - bool disabled; + bool disabled = false; comment_buffer_t comment_buffer; // For whatever next identifier comes in. comment_buffer_map_t comment_buffer_map; // For a particular identifier. InfoMap packages; @@ -234,11 +234,11 @@ private: InfoMap identifiers; InfoMap spicy_modules; std::vector all_info; - IdentifierInfo* last_identifier_seen; - IdentifierInfo* incomplete_type; + IdentifierInfo* last_identifier_seen = nullptr; + IdentifierInfo* incomplete_type = nullptr; std::map enum_mappings; // enum id -> enum type id Config config; - time_t mtime; + time_t mtime = 0; }; template diff --git a/src/zeekygen/SpicyModuleInfo.h b/src/zeekygen/SpicyModuleInfo.h index 8f71daf6a6..5db9d638dc 100644 --- a/src/zeekygen/SpicyModuleInfo.h +++ b/src/zeekygen/SpicyModuleInfo.h @@ -21,8 +21,8 @@ public: * @param name name of the Spicy EVT module. * @param description text describing the module further */ - explicit SpicyModuleInfo(const std::string& name, const std::string& description) - : name(name), description(description) {} + explicit SpicyModuleInfo(std::string name, std::string description) + : name(std::move(name)), description(std::move(description)) {} /** @return textual description of the module */ const auto& Description() const { return description; } diff --git a/src/zeekygen/Target.cc b/src/zeekygen/Target.cc index 66ea327823..1f24149bd9 100644 --- a/src/zeekygen/Target.cc +++ b/src/zeekygen/Target.cc @@ -189,7 +189,7 @@ static vector filter_matches(const vector& from, Target* t) { return rval; } -TargetFile::TargetFile(string arg_name) : name(std::move(arg_name)), f() { +TargetFile::TargetFile(string arg_name) : name(std::move(arg_name)) { if ( name.find('/') != string::npos ) { string dir = util::SafeDirname(name).result; diff --git a/src/zeekygen/Target.h b/src/zeekygen/Target.h index 9251c58105..a7a5b346e4 100644 --- a/src/zeekygen/Target.h +++ b/src/zeekygen/Target.h @@ -35,8 +35,8 @@ struct TargetFile { */ ~TargetFile(); - std::string name; /**< File name. */ - FILE* f; /**< File stream. */ + std::string name; /**< File name. */ + FILE* f = nullptr; /**< File stream. */ }; /** @@ -281,8 +281,8 @@ public: ScriptTarget(const std::string& name, const std::string& pattern) : Target(name, pattern), script_deps() {} ~ScriptTarget() override { - for ( size_t i = 0; i < pkg_deps.size(); ++i ) - delete pkg_deps[i]; + for ( auto* pkg : pkg_deps ) + delete pkg; } protected: