diff --git a/src/Attr.cc b/src/Attr.cc index 82605d4da6..038d5ac1fb 100644 --- a/src/Attr.cc +++ b/src/Attr.cc @@ -136,9 +136,9 @@ void Attr::DescribeReST(ODesc* d, bool shorten) const { expr->Eval(nullptr)->Describe(&dd); std::string s = dd.Description(); - for ( size_t i = 0; i < s.size(); ++i ) - if ( s[i] == '\n' ) - s[i] = ' '; + for ( auto& c : s ) + if ( c == '\n' ) + c = ' '; add_long_expr_string(d, s, shorten); } diff --git a/src/DebugCmds.cc b/src/DebugCmds.cc index 47136e299c..ba8a1be162 100644 --- a/src/DebugCmds.cc +++ b/src/DebugCmds.cc @@ -336,19 +336,19 @@ int dbg_cmd_break(DebugCmd cmd, const vector& args) { if ( string_is_regex(args[0]) ) { vector choices; choose_global_symbols_regex(args[0], choices, true); - for ( unsigned int i = 0; i < choices.size(); ++i ) - locstrings.emplace_back(choices[i]->Name()); + for ( const auto& choice : choices ) + locstrings.emplace_back(choice->Name()); } else locstrings.push_back(args[0]); - for ( unsigned int strindex = 0; strindex < locstrings.size(); ++strindex ) { - debug_msg("Setting breakpoint on %s:\n", locstrings[strindex].c_str()); - vector plrs = parse_location_string(locstrings[strindex]); + for ( const auto& loc_str : locstrings ) { + debug_msg("Setting breakpoint on %s:\n", loc_str.c_str()); + vector plrs = parse_location_string(loc_str); for ( const auto& plr : plrs ) { DbgBreakpoint* bp = new DbgBreakpoint(); bp->SetID(g_debugger_state.NextBPID()); - if ( ! bp->SetLocation(plr, locstrings[strindex]) ) { + if ( ! bp->SetLocation(plr, loc_str) ) { debug_msg("Breakpoint not set.\n"); delete bp; } diff --git a/src/DebugLogger.cc b/src/DebugLogger.cc index e3184afa6c..f05e62ece2 100644 --- a/src/DebugLogger.cc +++ b/src/DebugLogger.cc @@ -90,9 +90,9 @@ void DebugLogger::EnableStreams(const char* s) { std::string ltok{util::strreplace(util::strtolower(tok), "_", "-")}; if ( strcasecmp("all", tok) == 0 ) { - for ( int i = 0; i < NUM_DBGS; ++i ) { - streams[i].enabled = true; - enabled_streams.insert(streams[i].prefix); + for ( auto& strm : streams ) { + strm.enabled = true; + enabled_streams.insert(strm.prefix); } all = true; diff --git a/src/EventHandler.cc b/src/EventHandler.cc index 2d60aed663..57cc0703c6 100644 --- a/src/EventHandler.cc +++ b/src/EventHandler.cc @@ -65,8 +65,8 @@ void EventHandler::Call(Args* vl, bool no_remote, double ts) { xs.Reserve(vl->size()); bool valid_args = true; - for ( size_t index = 0; index < vl->size(); ++index ) { - if ( ! xs.Add((*vl)[index]) ) { + for ( const auto& v : *vl ) { + if ( ! xs.Add(v) ) { valid_args = false; auto_publish.clear(); reporter->Error("failed auto-remote event '%s', disabled", Name()); diff --git a/src/IP.cc b/src/IP.cc index c9d7807e76..b8e20ab6cb 100644 --- a/src/IP.cc +++ b/src/IP.cc @@ -457,8 +457,8 @@ static inline bool isIPv6ExtHeader(uint8_t type) { } IPv6_Hdr_Chain::~IPv6_Hdr_Chain() { - for ( size_t i = 0; i < chain.size(); ++i ) - delete chain[i]; + for ( auto& c : chain ) + delete c; delete homeAddr; delete finalDst; } @@ -702,9 +702,9 @@ IPv6_Hdr_Chain* IPv6_Hdr_Chain::Copy(const ip6_hdr* new_hdr) const { const u_char* new_data = (const u_char*)new_hdr; const u_char* old_data = chain[0]->Data(); - for ( size_t i = 0; i < chain.size(); ++i ) { - int off = chain[i]->Data() - old_data; - rval->chain.push_back(new IPv6_Hdr(chain[i]->Type(), new_data + off)); + for ( const auto& c : chain ) { + int off = c->Data() - old_data; + rval->chain.push_back(new IPv6_Hdr(c->Type(), new_data + off)); } return rval; diff --git a/src/IPAddr.cc b/src/IPAddr.cc index a8517daaa9..c22498b22b 100644 --- a/src/IPAddr.cc +++ b/src/IPAddr.cc @@ -205,8 +205,8 @@ bool IPAddr::ConvertString(const char* s, in6_addr* result) { if ( s[n] != '\0' ) return false; - for ( auto i = 0; i < 4; ++i ) - if ( a[i] < 0 || a[i] > 255 ) + for ( int num : a ) + if ( num < 0 || num > 255 ) return false; uint32_t addr = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]; diff --git a/src/PolicyFile.cc b/src/PolicyFile.cc index 323c0fd89f..fb75d8afa3 100644 --- a/src/PolicyFile.cc +++ b/src/PolicyFile.cc @@ -121,8 +121,8 @@ bool LoadPolicyFileText(const char* policy_filename, const std::optionallines.size()); ++i ) - assert(pf->lines[i][0] != '\n'); + for ( const auto& l : pf->lines ) + assert(l[0] != '\n'); return true; } diff --git a/src/RE.cc b/src/RE.cc index 1ece4ebe2b..d30c81d57f 100644 --- a/src/RE.cc +++ b/src/RE.cc @@ -271,8 +271,8 @@ void Specific_RE_Matcher::Dump(FILE* f) { dfa->Dump(f); } inline void RE_Match_State::AddMatches(const AcceptingSet& as, MatchPos position) { using am_idx = std::pair; - for ( AcceptingSet::const_iterator it = as.begin(); it != as.end(); ++it ) - accepted_matches.insert(am_idx(*it, position)); + for ( const auto& entry : as ) + accepted_matches.insert(am_idx(entry, position)); } bool RE_Match_State::Match(const u_char* bv, int n, bool bol, bool eol, bool clear) { diff --git a/src/RandTest.cc b/src/RandTest.cc index 9d53ddefe3..48842ddaab 100644 --- a/src/RandTest.cc +++ b/src/RandTest.cc @@ -17,6 +17,7 @@ #include "zeek/RandTest.h" #include +#include constexpr double log2of10 = 3.32192809488736234787; @@ -35,9 +36,7 @@ RandTest::RandTest() { inmont = mcount = 0; cexp = montex = montey = montepi = sccu0 = scclast = scct1 = scct2 = scct3 = 0.0; - for ( int i = 0; i < 256; i++ ) { - ccount[i] = 0; - } + memset(ccount, 0, sizeof(ccount)); } void RandTest::add(const void* buf, int bufl) { diff --git a/src/RuleMatcher.cc b/src/RuleMatcher.cc index 4ef2211de4..56c077b21e 100644 --- a/src/RuleMatcher.cc +++ b/src/RuleMatcher.cc @@ -106,8 +106,8 @@ RuleHdrTest::RuleHdrTest(RuleHdrTest& h) { prefix_vals = h.prefix_vals; - for ( int j = 0; j < Rule::TYPES; ++j ) { - for ( PatternSet* orig_set : h.psets[j] ) { + for ( const auto& pset : h.psets ) { + for ( PatternSet* orig_set : pset ) { PatternSet* copied_set = new PatternSet; copied_set->re = nullptr; copied_set->ids = orig_set->ids; @@ -133,8 +133,8 @@ RuleHdrTest::~RuleHdrTest() { delete val; delete vals; - for ( int i = 0; i < Rule::TYPES; ++i ) { - for ( auto pset : psets[i] ) { + for ( auto& pset_list : psets ) { + for ( auto& pset : pset_list ) { delete pset->re; delete pset; } @@ -515,10 +515,10 @@ static inline bool match_or(const maskedvalue_list& mvals, uint32_t v, FuncT com // Evaluate a prefix list (matches if at least one value matches). template static inline bool match_or(const vector& prefixes, const IPAddr& a, FuncT comp) { - for ( size_t i = 0; i < prefixes.size(); ++i ) { + for ( const auto& pfx : prefixes ) { IPAddr masked(a); - masked.Mask(prefixes[i].LengthIPv6()); - if ( comp(masked, prefixes[i].Prefix()) ) + masked.Mask(pfx.LengthIPv6()); + if ( comp(masked, pfx.Prefix()) ) return true; } return false; @@ -538,10 +538,10 @@ static inline bool match_not_and(const maskedvalue_list& mvals, uint32_t v, Func // Evaluate a prefix list (doesn't match if any value matches). template static inline bool match_not_and(const vector& prefixes, const IPAddr& a, FuncT comp) { - for ( size_t i = 0; i < prefixes.size(); ++i ) { + for ( const auto& pfx : prefixes ) { IPAddr masked(a); - masked.Mask(prefixes[i].LengthIPv6()); - if ( comp(masked, prefixes[i].Prefix()) ) + masked.Mask(pfx.LengthIPv6()); + if ( comp(masked, pfx.Prefix()) ) return false; } return true; @@ -1083,12 +1083,12 @@ void RuleMatcher::GetStats(Stats* stats, RuleHdrTest* hdr_test) const { DFA_State_Cache::Stats cstats; - for ( int i = 0; i < Rule::TYPES; ++i ) { - for ( const auto& set : hdr_test->psets[i] ) { - assert(set->re); + for ( const auto& pset_list : hdr_test->psets ) { + for ( const auto& pset : pset_list ) { + assert(pset->re); ++stats->matchers; - set->re->DFA()->Cache()->GetStats(&cstats); + pset->re->DFA()->Cache()->GetStats(&cstats); stats->dfa_states += cstats.dfa_states; stats->computed += cstats.computed; @@ -1183,7 +1183,9 @@ static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, vectorAsSubNet().Prefix().GetBytes(&n); v->AsSubNetVal()->Mask().CopyIPv6(m); - for ( unsigned int i = 0; i < 4; ++i ) + // Intentionally leaving this as a normal loop because it's more descriptive. + // NOLINTNEXTLINE(modernize-loop-convert) + for ( unsigned int i = 0; i < 4; i++ ) m[i] = ntohl(m[i]); bool is_v4_mask = m[0] == 0xffffffff && m[1] == m[0] && m[2] == m[0]; diff --git a/src/RunState.cc b/src/RunState.cc index 14af43dba3..e168cdb1fb 100644 --- a/src/RunState.cc +++ b/src/RunState.cc @@ -376,8 +376,8 @@ void get_final_stats() { void delete_run() { util::detail::set_processing_status("TERMINATING", "delete_run"); - for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i ) - delete zeek::detail::ip_anonymizer[i]; + for ( auto& anon : zeek::detail::ip_anonymizer ) + delete anon; } double check_pseudo_time(const Packet* pkt) { diff --git a/src/Stats.cc b/src/Stats.cc index be90c5ae7e..d0e592048b 100644 --- a/src/Stats.cc +++ b/src/Stats.cc @@ -194,14 +194,13 @@ void ProfileLogger::Log() { file->Write(util::fmt("%0.6f Threads: current=%zu\n", run_state::network_time, thread_mgr->NumThreads())); const threading::Manager::msg_stats_list& thread_stats = thread_mgr->GetMsgThreadStats(); - for ( threading::Manager::msg_stats_list::const_iterator i = thread_stats.begin(); i != thread_stats.end(); ++i ) { - threading::MsgThread::Stats s = i->second; + for ( const auto& [name, s] : thread_stats ) { file->Write(util::fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64 " (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")" "\n", - run_state::network_time, i->first.c_str(), s.sent_in, s.sent_out, s.pending_in, - s.pending_out, s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, - s.queue_out_stats.num_reads, s.queue_out_stats.num_writes)); + run_state::network_time, name.c_str(), s.sent_in, s.sent_out, s.pending_in, s.pending_out, + s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, s.queue_out_stats.num_reads, + s.queue_out_stats.num_writes)); } auto cs = broker_mgr->GetStatistics(); diff --git a/src/Trigger.cc b/src/Trigger.cc index eacf631bf9..dafc12e405 100644 --- a/src/Trigger.cc +++ b/src/Trigger.cc @@ -162,8 +162,8 @@ void Trigger::Terminate() { Trigger::~Trigger() { DBG_LOG(DBG_NOTIFIERS, "%s: deleting", Name()); - for ( ValCache::iterator i = cache.begin(); i != cache.end(); ++i ) - Unref(i->second); + for ( auto& [_, trigger] : cache ) + Unref(trigger); Unref(frame); UnregisterAll(); @@ -457,9 +457,8 @@ void Manager::Process() { TriggerList tmp; pending = &tmp; - for ( TriggerList::iterator i = orig->begin(); i != orig->end(); ++i ) { - Trigger* t = *i; - (*i)->Eval(); + for ( auto* t : *orig ) { + t->Eval(); Unref(t); } diff --git a/src/Type.cc b/src/Type.cc index c00f0951af..a5c6f935b5 100644 --- a/src/Type.cc +++ b/src/Type.cc @@ -756,9 +756,7 @@ void FuncType::DescribeReST(ODesc* d, bool roles_only) const { void FuncType::AddPrototype(Prototype p) { prototypes.emplace_back(std::move(p)); } std::optional FuncType::FindPrototype(const RecordType& args) const { - for ( auto i = 0u; i < prototypes.size(); ++i ) { - const auto& p = prototypes[i]; - + for ( const auto& p : prototypes ) { if ( args.NumFields() != p.args->NumFields() ) continue; @@ -1661,8 +1659,8 @@ const char* EnumType::Lookup(zeek_int_t value) const { EnumType::enum_name_list EnumType::Names() const { enum_name_list n; - for ( auto iter = names.begin(); iter != names.end(); ++iter ) - n.emplace_back(iter->first, iter->second); + for ( const auto& [name, value] : names ) + n.emplace_back(name, value); return n; } diff --git a/src/UID.cc b/src/UID.cc index f18ac0208a..d082d01e56 100644 --- a/src/UID.cc +++ b/src/UID.cc @@ -12,8 +12,7 @@ namespace zeek { void UID::Set(zeek_uint_t bits, const uint64_t* v, size_t n) { initialized = true; - for ( size_t i = 0; i < UID_LEN; ++i ) - uid[i] = 0; + memset(uid, 0, sizeof(uid)); if ( bits > UID_LEN * 64 ) bits = UID_LEN * 64; @@ -33,8 +32,8 @@ std::string UID::Base62(std::string prefix) const { reporter->InternalError("use of uninitialized UID"); char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation - for ( size_t i = 0; i < UID_LEN; ++i ) - prefix.append(util::uitoa_n(uid[i], tmp, sizeof(tmp), 62)); + for ( const auto& digit : uid ) + prefix.append(util::uitoa_n(digit, tmp, sizeof(tmp), 62)); return prefix; } diff --git a/src/Val.cc b/src/Val.cc index 19dd67fcd2..6c52fb875a 100644 --- a/src/Val.cc +++ b/src/Val.cc @@ -738,8 +738,8 @@ IPAddr SubNetVal::Mask() const { // We need to special-case a mask width of zero, since // the compiler doesn't guarantee that 1 << 32 yields 0. uint32_t m[4]; - for ( unsigned int i = 0; i < 4; ++i ) - m[i] = 0; + for ( uint32_t& digit : m ) + digit = 0; IPAddr rval(IPv6, m, IPAddr::Host); return rval; } diff --git a/src/Var.cc b/src/Var.cc index 5df4746aa4..6e9a74a754 100644 --- a/src/Var.cc +++ b/src/Var.cc @@ -438,9 +438,9 @@ static Attr* find_attr(const std::vector* al, AttrTag tag) { if ( ! al ) return nullptr; - for ( size_t i = 0; i < al->size(); ++i ) - if ( (*al)[i]->Tag() == tag ) - return (*al)[i].get(); + for ( const auto& attr : *al ) + if ( attr->Tag() == tag ) + return attr.get(); return nullptr; } diff --git a/src/ZeekString.cc b/src/ZeekString.cc index f720e57977..4d63345e3f 100644 --- a/src/ZeekString.cc +++ b/src/ZeekString.cc @@ -352,8 +352,8 @@ String::Vec* String::VecFromPolicy(VectorVal* vec) { char* String::VecToString(const Vec* vec) { std::string result("["); - for ( String::VecCIt it = vec->begin(); it != vec->end(); ++it ) { - result += (*it)->CheckString(); + for ( const auto* str : *vec ) { + result += str->CheckString(); result += ","; } @@ -442,10 +442,7 @@ String* concatenate(String::CVec& v) { String* concatenate(String::Vec& v) { String::CVec cv; - - for ( String::VecIt it = v.begin(); it != v.end(); ++it ) - cv.push_back(*it); - + std::copy(v.begin(), v.end(), std::back_inserter(cv)); return concatenate(cv); } diff --git a/src/analyzer/Manager.cc b/src/analyzer/Manager.cc index 4cd42420a7..980e15d4b3 100644 --- a/src/analyzer/Manager.cc +++ b/src/analyzer/Manager.cc @@ -388,8 +388,8 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys tag_set expected = GetScheduled(conn); - for ( tag_set::iterator it = expected.begin(); it != expected.end(); ++it ) { - Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(*it, conn); + for ( const auto& tag : expected ) { + Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(tag, conn); if ( ! analyzer ) continue; @@ -397,9 +397,9 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys parent->AddChildAnalyzer(analyzer, init); if ( scheduled_analyzer_applied ) - conn->EnqueueEvent(scheduled_analyzer_applied, nullptr, conn->GetVal(), it->AsVal()); + conn->EnqueueEvent(scheduled_analyzer_applied, nullptr, conn->GetVal(), tag.AsVal()); - DBG_ANALYZER_ARGS(conn, "activated %s analyzer as scheduled", analyzer_mgr->GetComponentName(*it).c_str()); + DBG_ANALYZER_ARGS(conn, "activated %s analyzer as scheduled", analyzer_mgr->GetComponentName(tag).c_str()); } return expected.size(); diff --git a/src/analyzer/protocol/dhcp/dhcp-options.pac b/src/analyzer/protocol/dhcp/dhcp-options.pac index 810bb0a6e8..2e14c953a5 100644 --- a/src/analyzer/protocol/dhcp/dhcp-options.pac +++ b/src/analyzer/protocol/dhcp/dhcp-options.pac @@ -756,12 +756,11 @@ refine flow DHCP_Flow += { uint16 i = 0; - for ( auto ptrsubopt = ${v.relay_agent_inf}->begin(); - ptrsubopt != ${v.relay_agent_inf}->end(); ++ptrsubopt ) + for ( const auto& ptrsubopt : *${v.relay_agent_inf} ) { auto r = zeek::make_intrusive(zeek::BifType::Record::DHCP::SubOpt); - r->Assign(0, (*ptrsubopt)->code()); - r->Assign(1, to_stringval((*ptrsubopt)->value())); + r->Assign(0, ptrsubopt->code()); + r->Assign(1, to_stringval(ptrsubopt->value())); relay_agent_sub_opt->Assign(i, std::move(r)); ++i; diff --git a/src/analyzer/protocol/dns/DNS.cc b/src/analyzer/protocol/dns/DNS.cc index dc0132bbfd..98204320f8 100644 --- a/src/analyzer/protocol/dns/DNS.cc +++ b/src/analyzer/protocol/dns/DNS.cc @@ -699,8 +699,8 @@ bool DNS_Interpreter::ParseRR_EDNS(detail::DNS_MsgInfo* msg, const u_char*& data bits_left -= 8; } - for ( uint8_t i = 0; i < 4; i++ ) { - addr[i] = htonl(addr[i]); + for ( uint32_t& a : addr ) { + a = htonl(a); } opt.ecs_addr = make_intrusive(addr); } @@ -1372,7 +1372,9 @@ bool DNS_Interpreter::ParseRR_A(detail::DNS_MsgInfo* msg, const u_char*& data, i bool DNS_Interpreter::ParseRR_AAAA(detail::DNS_MsgInfo* msg, const u_char*& data, int& len, int rdlength) { uint32_t addr[4]; - for ( int i = 0; i < 4; ++i ) { + // Intentionally leaving this as a normal loop because it's more descriptive. + // NOLINTNEXTLINE(modernize-loop-convert) + for ( size_t i = 0; i < 4; i++ ) { addr[i] = htonl(ExtractLong(data, len)); if ( len < 0 ) { diff --git a/src/analyzer/protocol/ftp/functions.bif b/src/analyzer/protocol/ftp/functions.bif index 235cb630ab..1a7dafe901 100644 --- a/src/analyzer/protocol/ftp/functions.bif +++ b/src/analyzer/protocol/ftp/functions.bif @@ -20,8 +20,8 @@ static zeek::RecordValPtr parse_port(const std::string& line) { good = true; - for ( int i = 0; i < 6; ++i ) - if ( bytes[i] < 0 || bytes[i] > 255 ) + for ( int b : bytes ) + if ( b < 0 || b > 255 ) { good = false; break; diff --git a/src/analyzer/protocol/irc/IRC.cc b/src/analyzer/protocol/irc/IRC.cc index 61c33c6683..e5aaca7ac5 100644 --- a/src/analyzer/protocol/irc/IRC.cc +++ b/src/analyzer/protocol/irc/IRC.cc @@ -125,8 +125,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { pos = myline.length(); command = myline.substr(0, pos); - for ( size_t i = 0; i < command.size(); ++i ) - command[i] = toupper(command[i]); + command = util::to_upper(command); // Adjust for the no-parameter case if ( pos == myline.length() ) @@ -743,9 +742,8 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) { string empty_string = ""; - for ( unsigned int i = 0; i < users.size(); ++i ) { + for ( auto nick : users ) { auto info = make_intrusive(irc_join_info); - string nick = users[i]; string mode = "none"; if ( nick[0] == '@' ) { diff --git a/src/analyzer/protocol/krb/krb-analyzer.pac b/src/analyzer/protocol/krb/krb-analyzer.pac index 3df0367a9b..a69b47ce8d 100644 --- a/src/analyzer/protocol/krb/krb-analyzer.pac +++ b/src/analyzer/protocol/krb/krb-analyzer.pac @@ -37,9 +37,8 @@ zeek::RecordValPtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const ZeekAnalyz if ( msg->padata()->has_padata() ) rv->Assign(2, proc_padata(msg->padata()->padata()->padata(), zeek_analyzer, false)); - for ( uint i = 0; i < msg->body_args()->size(); ++i ) + for ( KRB_REQ_Arg* element : *(msg->body_args()) ) { - KRB_REQ_Arg* element = (*msg->body_args())[i]; switch ( element->seq_meta()->index() ) { case 0: @@ -127,35 +126,35 @@ bool proc_error_arguments(zeek::RecordVal* rv, const std::vector if ( stime_i ) rv->Assign(3, GetTimeFromAsn1((*args)[stime_i]->args()->stime(), stime_usecs)); - for ( uint i = 0; i < args->size(); ++i ) + for ( KRB_ERROR_Arg* arg : *args ) { - switch ( (*args)[i]->seq_meta()->index() ) + switch ( arg->seq_meta()->index() ) { case 0: - rv->Assign(0, asn1_integer_to_val((*args)[i]->args()->pvno(), zeek::TYPE_COUNT)); + rv->Assign(0, asn1_integer_to_val(arg->args()->pvno(), zeek::TYPE_COUNT)); break; case 1: - rv->Assign(1, asn1_integer_to_val((*args)[i]->args()->msg_type(), zeek::TYPE_COUNT)); + rv->Assign(1, asn1_integer_to_val(arg->args()->msg_type(), zeek::TYPE_COUNT)); break; // ctime/stime handled above case 7: - rv->Assign(5, to_stringval((*args)[i]->args()->crealm()->encoding()->content())); + rv->Assign(5, to_stringval(arg->args()->crealm()->encoding()->content())); break; case 8: - rv->Assign(6, GetStringFromPrincipalName((*args)[i]->args()->cname())); + rv->Assign(6, GetStringFromPrincipalName(arg->args()->cname())); break; case 9: - rv->Assign(7, to_stringval((*args)[i]->args()->realm()->encoding()->content())); + rv->Assign(7, to_stringval(arg->args()->realm()->encoding()->content())); break; case 10: - rv->Assign(8, GetStringFromPrincipalName((*args)[i]->args()->sname())); + rv->Assign(8, GetStringFromPrincipalName(arg->args()->sname())); break; case 11: - rv->Assign(9, to_stringval((*args)[i]->args()->e_text()->encoding()->content())); + rv->Assign(9, to_stringval(arg->args()->e_text()->encoding()->content())); break; case 12: if ( error_code == KDC_ERR_PREAUTH_REQUIRED ) - rv->Assign(10, proc_padata((*args)[i]->args()->e_data()->padata(), NULL, true)); + rv->Assign(10, proc_padata(arg->args()->e_data()->padata(), NULL, true)); break; default: break; @@ -307,27 +306,15 @@ refine connection KRB_Conn += { { switch ( ${msg.safe_body.args[i].seq_meta.index} ) { + case 0: + rv->Assign(3, to_stringval(${msg.safe_body.args[i].args.user_data.encoding.content})); + break; case 1: timestamp_i = i; break; case 2: timestamp_usecs = binary_to_int64(${msg.safe_body.args[i].args.usec.encoding.content}); break; - default: - break; - } - } - - if ( timestamp_i ) - rv->Assign(4, GetTimeFromAsn1(${msg.safe_body.args[timestamp_i].args.timestamp}, timestamp_usecs)); - - for ( uint i = 0; i < ${msg.safe_body.args}->size(); ++i ) - { - switch ( ${msg.safe_body.args[i].seq_meta.index} ) - { - case 0: - rv->Assign(3, to_stringval(${msg.safe_body.args[i].args.user_data.encoding.content})); - break; case 3: rv->Assign(5, asn1_integer_to_val(${msg.safe_body.args[i].args.seq_number}, zeek::TYPE_COUNT)); break; @@ -341,6 +328,10 @@ refine connection KRB_Conn += { break; } } + + if ( timestamp_i ) + rv->Assign(4, GetTimeFromAsn1(${msg.safe_body.args[timestamp_i].args.timestamp}, timestamp_usecs)); + zeek::BifEvent::enqueue_krb_safe(zeek_analyzer(), zeek_analyzer()->Conn(), ${msg.is_orig}, std::move(rv)); } return true; diff --git a/src/analyzer/protocol/krb/krb-padata.pac b/src/analyzer/protocol/krb/krb-padata.pac index 9266f9ee51..e2ab24d959 100644 --- a/src/analyzer/protocol/krb/krb-padata.pac +++ b/src/analyzer/protocol/krb/krb-padata.pac @@ -18,9 +18,8 @@ zeek::VectorValPtr proc_padata(const KRB_PA_Data_Sequence* data, const ZeekAnaly if ( ! data->data()->has_padata() ) return vv; - for ( uint i = 0; i < data->data()->padata_elems()->size(); ++i) + for ( KRB_PA_Data* element : *(data->data()->padata_elems()) ) { - KRB_PA_Data* element = (*data->data()->padata_elems())[i]; uint64_t data_type = element->data_type(); if ( is_error && ( data_type == PA_PW_AS_REQ || data_type == PA_PW_AS_REP ) ) diff --git a/src/analyzer/protocol/krb/krb-types.pac b/src/analyzer/protocol/krb/krb-types.pac index 64fabec380..71464a7c8d 100644 --- a/src/analyzer/protocol/krb/krb-types.pac +++ b/src/analyzer/protocol/krb/krb-types.pac @@ -30,8 +30,8 @@ zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname) zeek::VectorValPtr proc_cipher_list(const Array* list) { auto ciphers = zeek::make_intrusive(zeek::id::index_vec); - for ( uint i = 0; i < list->data()->size(); ++i ) - ciphers->Assign(ciphers->Size(), asn1_integer_to_val((*list->data())[i], zeek::TYPE_COUNT)); + for ( const auto& data : *(list->data()) ) + ciphers->Assign(ciphers->Size(), asn1_integer_to_val(data, zeek::TYPE_COUNT)); return ciphers; } @@ -39,10 +39,8 @@ zeek::VectorValPtr proc_host_address_list(const ZeekAnalyzer a, const KRB_Host_A { auto addrs = zeek::make_intrusive(zeek::id::find_type("KRB::Host_Address_Vector")); - for ( uint i = 0; i < list->addresses()->size(); ++i ) - { - addrs->Assign(addrs->Size(), proc_host_address(a, (*list->addresses())[i])); - } + for ( const auto& addr : *(list->addresses()) ) + addrs->Assign(addrs->Size(), proc_host_address(a, addr)); return addrs; } @@ -98,11 +96,8 @@ zeek::VectorValPtr proc_tickets(const KRB_Ticket_Sequence* list) { auto tickets = zeek::make_intrusive(zeek::id::find_type("KRB::Ticket_Vector")); - for ( uint i = 0; i < list->tickets()->size(); ++i ) - { - KRB_Ticket* element = (*list->tickets())[i]; + for ( KRB_Ticket* element : *(list->tickets()) ) tickets->Assign(tickets->Size(), proc_ticket(element)); - } return tickets; } diff --git a/src/analyzer/protocol/modbus/modbus-analyzer.pac b/src/analyzer/protocol/modbus/modbus-analyzer.pac index 03a124045f..95cf8c5796 100644 --- a/src/analyzer/protocol/modbus/modbus-analyzer.pac +++ b/src/analyzer/protocol/modbus/modbus-analyzer.pac @@ -524,14 +524,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileRecordRequests); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileRecordRequest); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_len})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_len})); vect->Append(r); } @@ -551,13 +551,13 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileRecordResponses); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileRecordResponse); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].file_len})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(2, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.file_len})); + r->Assign(1, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(2, to_stringval(${ref.record_data})); vect->Append(r); } @@ -577,14 +577,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileReferences); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileReference); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); - r->Assign(4, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_length})); + r->Assign(4, to_stringval(${ref.record_data})); vect->Append(r); } @@ -604,14 +604,14 @@ refine flow ModbusTCP_Flow += { { auto vect = zeek::make_intrusive(zeek::BifType::Vector::ModbusFileReferences); - for ( unsigned int i = 0; i < (${message.references}->size()); ++i ) + for ( const auto& ref : *(${message.references}) ) { auto r = zeek::make_intrusive(zeek::BifType::Record::ModbusFileReference); - r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); - r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); - r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); - r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); - r->Assign(4, to_stringval(${message.references[i].record_data})); + r->Assign(0, zeek::val_mgr->Count(${ref.ref_type})); + r->Assign(1, zeek::val_mgr->Count(${ref.file_num})); + r->Assign(2, zeek::val_mgr->Count(${ref.record_num})); + r->Assign(3, zeek::val_mgr->Count(${ref.record_length})); + r->Assign(4, to_stringval(${ref.record_data})); vect->Append(r); } diff --git a/src/analyzer/protocol/pop3/POP3.cc b/src/analyzer/protocol/pop3/POP3.cc index e1a3e240aa..c4179b354e 100644 --- a/src/analyzer/protocol/pop3/POP3.cc +++ b/src/analyzer/protocol/pop3/POP3.cc @@ -784,8 +784,7 @@ int POP3_Analyzer::ParseCmd(std::string cmd) { if ( c == '+' || c == '-' ) cmd = cmd.substr(1); - for ( size_t i = 0; i < cmd.size(); ++i ) - cmd[i] = toupper(cmd[i]); + cmd = util::to_upper(cmd); if ( ! cmd.compare(pop3_cmd_word[code]) ) return code; diff --git a/src/analyzer/protocol/radius/radius-analyzer.pac b/src/analyzer/protocol/radius/radius-analyzer.pac index a998aafc71..7abf8f243e 100644 --- a/src/analyzer/protocol/radius/radius-analyzer.pac +++ b/src/analyzer/protocol/radius/radius-analyzer.pac @@ -12,17 +12,17 @@ refine flow RADIUS_Flow += { result->Assign(1, ${msg.trans_id}); result->Assign(2, to_stringval(${msg.authenticator})); - if ( ${msg.attributes}->size() ) + if ( ! ${msg.attributes}->empty() ) { auto attributes = zeek::make_intrusive(zeek::BifType::Table::RADIUS::Attributes); - for ( uint i = 0; i < ${msg.attributes}->size(); ++i ) + for ( const auto& attr : *(${msg.attributes}) ) { - auto index = zeek::val_mgr->Count(${msg.attributes[i].code}); + auto index = zeek::val_mgr->Count(${attr.code}); // Do we already have a vector of attributes for this type? auto current = attributes->FindOrDefault(index); - zeek::ValPtr val = to_stringval(${msg.attributes[i].value}); + zeek::ValPtr val = to_stringval(${attr.value}); if ( current ) { diff --git a/src/analyzer/protocol/rdp/rdp-analyzer.pac b/src/analyzer/protocol/rdp/rdp-analyzer.pac index 184fe668c0..56bed9dbe3 100644 --- a/src/analyzer/protocol/rdp/rdp-analyzer.pac +++ b/src/analyzer/protocol/rdp/rdp-analyzer.pac @@ -132,28 +132,28 @@ refine flow RDP_Flow += { if ( ! rdp_client_network_data ) return false; - if ( ${cnetwork.channel_def_array}->size() ) + if ( ! ${cnetwork.channel_def_array}->empty() ) { auto channels = zeek::make_intrusive(zeek::BifType::Vector::RDP::ClientChannelList); - for ( uint i = 0; i < ${cnetwork.channel_def_array}->size(); ++i ) + for ( const auto& cdef : *${cnetwork.channel_def_array} ) { auto channel_def = zeek::make_intrusive(zeek::BifType::Record::RDP::ClientChannelDef); - channel_def->Assign(0, to_stringval(${cnetwork.channel_def_array[i].name})); - channel_def->Assign(1, ${cnetwork.channel_def_array[i].options}); + channel_def->Assign(0, to_stringval(${cdef.name})); + channel_def->Assign(1, ${cdef.options}); - channel_def->Assign(2, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_INITIALIZED}); - channel_def->Assign(3, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_RDP}); - channel_def->Assign(4, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_SC}); - channel_def->Assign(5, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_CS}); - channel_def->Assign(6, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_HIGH}); - channel_def->Assign(7, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_MED}); - channel_def->Assign(8, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_LOW}); - channel_def->Assign(9, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS_RDP}); - channel_def->Assign(10, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS}); - channel_def->Assign(11, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_SHOW_PROTOCOL}); - channel_def->Assign(12, ${cnetwork.channel_def_array[i].REMOTE_CONTROL_PERSISTENT}); + channel_def->Assign(2, ${cdef.CHANNEL_OPTION_INITIALIZED}); + channel_def->Assign(3, ${cdef.CHANNEL_OPTION_ENCRYPT_RDP}); + channel_def->Assign(4, ${cdef.CHANNEL_OPTION_ENCRYPT_SC}); + channel_def->Assign(5, ${cdef.CHANNEL_OPTION_ENCRYPT_CS}); + channel_def->Assign(6, ${cdef.CHANNEL_OPTION_PRI_HIGH}); + channel_def->Assign(7, ${cdef.CHANNEL_OPTION_PRI_MED}); + channel_def->Assign(8, ${cdef.CHANNEL_OPTION_PRI_LOW}); + channel_def->Assign(9, ${cdef.CHANNEL_OPTION_COMPRESS_RDP}); + channel_def->Assign(10, ${cdef.CHANNEL_OPTION_COMPRESS}); + channel_def->Assign(11, ${cdef.CHANNEL_OPTION_SHOW_PROTOCOL}); + channel_def->Assign(12, ${cdef.REMOTE_CONTROL_PERSISTENT}); channels->Assign(channels->Size(), std::move(channel_def)); } diff --git a/src/broker/Data.cc b/src/broker/Data.cc index 1d44e38874..e888c14034 100644 --- a/src/broker/Data.cc +++ b/src/broker/Data.cc @@ -530,15 +530,15 @@ struct type_checker { else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else @@ -580,15 +580,15 @@ struct type_checker { else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else { indices_to_check.reserve(indices->size()); - for ( size_t i = 0; i < indices->size(); ++i ) - indices_to_check.emplace_back(&(*indices)[i]); + for ( const auto& idx : *indices ) + indices_to_check.emplace_back(&idx); } } else diff --git a/src/file_analysis/Manager.cc b/src/file_analysis/Manager.cc index 85a3e83ba4..d67621c201 100644 --- a/src/file_analysis/Manager.cc +++ b/src/file_analysis/Manager.cc @@ -24,8 +24,8 @@ Manager::Manager() max_files(0) {} Manager::~Manager() { - for ( MIMEMap::iterator i = mime_types.begin(); i != mime_types.end(); i++ ) - delete i->second; + for ( const auto& [_, tag] : mime_types ) + delete tag; // Have to assume that too much of Zeek has been shutdown by this point // to do anything more than reclaim memory. @@ -473,12 +473,12 @@ VectorValPtr GenMIMEMatchesVal(const zeek::detail::RuleMatcher::MIME_Matches& m) static auto mime_match = id::find_type("mime_match"); auto rval = make_intrusive(mime_matches); - for ( zeek::detail::RuleMatcher::MIME_Matches::const_iterator it = m.begin(); it != m.end(); ++it ) { + for ( const auto& [index, match] : m ) { auto element = make_intrusive(mime_match); - for ( set::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ) { - element->Assign(0, it->first); - element->Assign(1, *it2); + for ( const string& match_str : match ) { + element->Assign(0, index); + element->Assign(1, match_str); } rval->Assign(rval->Size(), std::move(element)); diff --git a/src/input/Manager.cc b/src/input/Manager.cc index 19e074eeab..03e4b6bde0 100644 --- a/src/input/Manager.cc +++ b/src/input/Manager.cc @@ -169,9 +169,9 @@ Manager::Manager() : plugin::ComponentManager("Input", "Reader } Manager::~Manager() { - for ( map::iterator s = readers.begin(); s != readers.end(); ++s ) { - delete s->second; - delete s->first; + for ( auto& [frontend, stream] : readers ) { + delete stream; + delete frontend; } } @@ -1439,8 +1439,8 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const* if ( convert_error ) { // we have an error somewhere in our out_vals. Just delete all of them. - for ( list::const_iterator it = out_vals.begin(), end = out_vals.end(); it != end; ++it ) - Unref(*it); + for ( auto* val : out_vals ) + Unref(val); } else SendEvent(stream->event, out_vals); @@ -1712,8 +1712,8 @@ void Manager::SendEvent(EventHandlerPtr ev, list events) const { DBG_LOG(DBG_INPUT, "SendEvent with %" PRIuPTR " vals (list)", events.size()); #endif - for ( list::iterator i = events.begin(); i != events.end(); i++ ) - vl.emplace_back(AdoptRef{}, *i); + for ( auto* val : events ) + vl.emplace_back(AdoptRef{}, val); if ( ev ) event_mgr.Enqueue(ev, std::move(vl), util::detail::SOURCE_LOCAL); @@ -2167,9 +2167,9 @@ Val* Manager::ValueToVal(const Stream* i, const Value* val, Type* request_type, } Manager::Stream* Manager::FindStream(const string& name) const { - for ( auto s = readers.begin(); s != readers.end(); ++s ) { - if ( (*s).second->name == name ) - return (*s).second; + for ( const auto& [_, stream] : readers ) { + if ( stream->name == name ) + return stream; } return nullptr; @@ -2186,12 +2186,12 @@ Manager::Stream* Manager::FindStream(ReaderFrontend* reader) const { // Function is called on Zeek shutdown. // Signal all frontends that they will cease operation. void Manager::Terminate() { - for ( map::iterator i = readers.begin(); i != readers.end(); ++i ) { - if ( i->second->removed ) + for ( const auto& [_, stream] : readers ) { + if ( stream->removed ) continue; - i->second->removed = true; - i->second->reader->Stop(); + stream->removed = true; + stream->reader->Stop(); } } diff --git a/src/iosource/Component.cc b/src/iosource/Component.cc index 3aa7610e0b..1fd1815a94 100644 --- a/src/iosource/Component.cc +++ b/src/iosource/Component.cc @@ -23,8 +23,8 @@ PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string& const std::vector& PktSrcComponent::Prefixes() const { return prefixes; } bool PktSrcComponent::HandlesPrefix(const std::string& prefix) const { - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { - if ( *i == prefix ) + for ( const auto& pfx : prefixes ) { + if ( pfx == prefix ) return true; } @@ -42,11 +42,11 @@ void PktSrcComponent::DoDescribe(ODesc* d) const { std::string prefs; - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { + for ( const auto& pfx : prefixes ) { if ( prefs.size() ) prefs += ", "; - prefs += '"' + *i + '"'; + prefs += '"' + pfx + '"'; } d->Add("interface prefix"); @@ -80,8 +80,8 @@ PktDumperComponent::factory_callback PktDumperComponent::Factory() const { retur const std::vector& PktDumperComponent::Prefixes() const { return prefixes; } bool PktDumperComponent::HandlesPrefix(const std::string& prefix) const { - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { - if ( *i == prefix ) + for ( const auto& pfx : prefixes ) { + if ( pfx == prefix ) return true; } @@ -93,11 +93,11 @@ void PktDumperComponent::DoDescribe(ODesc* d) const { std::string prefs; - for ( std::vector::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { + for ( const auto& pfx : prefixes ) { if ( prefs.size() ) prefs += ", "; - prefs += '"' + *i + '"'; + prefs += '"' + pfx + '"'; } d->Add("dumper prefix"); diff --git a/src/iosource/Manager.cc b/src/iosource/Manager.cc index 8e0f4d106d..e31245ffe2 100644 --- a/src/iosource/Manager.cc +++ b/src/iosource/Manager.cc @@ -64,9 +64,9 @@ Manager::~Manager() { sources.clear(); - for ( PktDumperList::iterator i = pkt_dumpers.begin(); i != pkt_dumpers.end(); ++i ) { - (*i)->Done(); - delete *i; + for ( PktDumper* dumper : pkt_dumpers ) { + dumper->Done(); + delete dumper; } pkt_dumpers.clear(); diff --git a/src/logging/Manager.cc b/src/logging/Manager.cc index e4a2b879b4..fb75fb828c 100644 --- a/src/logging/Manager.cc +++ b/src/logging/Manager.cc @@ -351,9 +351,7 @@ Manager::Filter::~Filter() { Manager::Stream::~Stream() { Unref(columns); - for ( WriterMap::iterator i = writers.begin(); i != writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( auto& [_, winfo] : writers ) { if ( winfo->rotation_timer ) zeek::detail::timer_mgr->Cancel(winfo->rotation_timer); @@ -363,8 +361,8 @@ Manager::Stream::~Stream() { delete winfo; } - for ( list::iterator f = filters.begin(); f != filters.end(); ++f ) - delete *f; + for ( Filter* f : filters ) + delete f; if ( delay_timer ) zeek::detail::timer_mgr->Cancel(delay_timer); @@ -491,8 +489,8 @@ Manager::Manager() } Manager::~Manager() { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) - delete *s; + for ( Stream* s : streams ) + delete s; } void Manager::InitPostScript() { @@ -524,13 +522,11 @@ Manager::Stream* Manager::FindStream(EnumVal* id) { } Manager::WriterInfo* Manager::FindWriter(WriterFrontend* writer) { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - if ( ! *s ) + for ( Stream* s : streams ) { + if ( ! s ) continue; - for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( const auto& [_, winfo] : s->writers ) { if ( winfo->writer == writer ) return winfo; } @@ -563,16 +559,16 @@ bool Manager::CheckFilterWriterConflict(const WriterInfo* winfo, const Filter* f void Manager::RemoveDisabledWriters(Stream* stream) { list disabled; - for ( Stream::WriterMap::iterator j = stream->writers.begin(); j != stream->writers.end(); j++ ) { - if ( j->second->writer->Disabled() ) { - j->second->writer->Stop(); - delete j->second; - disabled.push_back(j->first); + for ( const auto& [index, winfo] : stream->writers ) { + if ( winfo->writer->Disabled() ) { + winfo->writer->Stop(); + delete winfo; + disabled.push_back(index); } } - for ( list::iterator j = disabled.begin(); j != disabled.end(); j++ ) - stream->writers.erase(*j); + for ( const auto& index : disabled ) + stream->writers.erase(index); } bool Manager::CreateStream(EnumVal* id, RecordVal* sval) { @@ -681,9 +677,7 @@ bool Manager::RemoveStream(unsigned int idx) { if ( ! stream ) return false; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { - WriterInfo* winfo = i->second; - + for ( const auto& [_, winfo] : stream->writers ) { DBG_LOG(DBG_LOGGING, "Removed writer '%s' from stream '%s'", winfo->writer->Name(), stream->name.c_str()); winfo->writer->Stop(); @@ -1550,9 +1544,9 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte // potentially be nested inside other records. list& indices = filter->indices[i]; - for ( list::iterator j = indices.begin(); j != indices.end(); ++j ) { + for ( int index : indices ) { auto vr = val->AsRecord(); - val = vr->RawOptField(*j); + val = vr->RawOptField(index); if ( ! val ) { // Value, or any of its parents, is not set. @@ -1560,7 +1554,7 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte break; } - vt = cast_intrusive(vr->GetType())->GetFieldType(*j).get(); + vt = cast_intrusive(vr->GetType())->GetFieldType(index).get(); } if ( val ) @@ -1856,21 +1850,19 @@ bool Manager::WriteFromRemote(EnumVal* id, EnumVal* writer, const string& path, void Manager::SendAllWritersTo(const broker::endpoint_info& ei) { auto et = id::find_type("Log::Writer")->AsEnumType(); - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - Stream* stream = (*s); - + for ( Stream* stream : streams ) { if ( ! (stream && stream->enable_remote) ) continue; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { - WriterFrontend* writer = i->second->writer; - const auto& writer_val = et->GetEnumVal(i->first.first); + for ( const auto& [index, winfo] : stream->writers ) { + WriterFrontend* writer = winfo->writer; + const auto& writer_val = et->GetEnumVal(index.first); std::vector fields(writer->GetFields().size()); for ( size_t i = 0; i < writer->GetFields().size(); i++ ) fields[i] = &writer->GetFields()[i]; - broker_mgr->PublishLogCreate((*s)->id, writer_val.get(), *i->second->info, fields.size(), fields.data(), + broker_mgr->PublishLogCreate(stream->id, writer_val.get(), *(winfo->info), fields.size(), fields.data(), ei); } } @@ -1881,8 +1873,8 @@ bool Manager::SetBuf(EnumVal* id, bool enabled) { if ( ! stream ) return false; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) - i->second->writer->SetBuf(enabled); + for ( const auto& [_, winfo] : stream->writers ) + winfo->writer->SetBuf(enabled); RemoveDisabledWriters(stream); @@ -1897,8 +1889,8 @@ bool Manager::Flush(EnumVal* id) { if ( ! stream->enabled ) return true; - for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) - i->second->writer->Flush(run_state::network_time); + for ( const auto& [_, winfo] : stream->writers ) + winfo->writer->Flush(run_state::network_time); RemoveDisabledWriters(stream); @@ -1906,12 +1898,12 @@ bool Manager::Flush(EnumVal* id) { } void Manager::Terminate() { - for ( vector::iterator s = streams.begin(); s != streams.end(); ++s ) { - if ( ! *s ) + for ( Stream* s : streams ) { + if ( ! s ) continue; - for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) - i->second->writer->Stop(); + for ( const auto& [_, winfo] : s->writers ) + winfo->writer->Stop(); } } diff --git a/src/logging/WriterBackend.cc b/src/logging/WriterBackend.cc index 46750cd7a4..70ab8591b4 100644 --- a/src/logging/WriterBackend.cc +++ b/src/logging/WriterBackend.cc @@ -61,8 +61,8 @@ public: broker::data WriterBackend::WriterInfo::ToBroker() const { auto t = broker::table(); - for ( config_map::const_iterator i = config.begin(); i != config.end(); ++i ) { - t.emplace(std::string{i->first}, std::string{i->second}); + for ( const auto& [key, value] : config ) { + t.emplace(std::string{key}, std::string{value}); } auto bppf = post_proc_func ? post_proc_func : ""; @@ -185,12 +185,12 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span reco } // Double-check all the types match. - for ( size_t j = 0; j < records.size(); j++ ) { + for ( const auto& record : records ) { for ( int i = 0; i < num_fields; ++i ) { - if ( records[j][i].type != fields[i]->type ) { + if ( record[i].type != fields[i]->type ) { #ifdef DEBUG const char* msg = Fmt("Field #%d type doesn't match in WriterBackend::Write() (%d vs. %d)", i, - records[j][i].type, fields[i]->type); + record[i].type, fields[i]->type); Debug(DBG_LOGGING, msg); #endif DisableFrontend(); @@ -212,10 +212,9 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span reco std::vector valps; valps.reserve(num_fields); - for ( size_t j = 0; j < records.size(); j++ ) { - auto& write_vals = records[j]; + for ( auto& record : records ) { for ( int f = 0; f < num_fields; f++ ) - valps.emplace_back(&write_vals[f]); + valps.emplace_back(&record[f]); success = DoWrite(num_fields, fields, &valps[0]); diff --git a/src/logging/writers/ascii/Ascii.cc b/src/logging/writers/ascii/Ascii.cc index 5d96786b90..3d43964422 100644 --- a/src/logging/writers/ascii/Ascii.cc +++ b/src/logging/writers/ascii/Ascii.cc @@ -255,11 +255,11 @@ bool Ascii::InitFilterOptions() { const WriterInfo& info = Info(); // Set per-filter configuration options. - for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); ++i ) { - if ( strcmp(i->first, "tsv") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + for ( const auto& [key, value] : info.config ) { + if ( strcmp(key, "tsv") == 0 ) { + if ( strcmp(value, "T") == 0 ) tsv = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) tsv = false; else { Error("invalid value for 'tsv', must be a string and either \"T\" or \"F\""); @@ -267,18 +267,18 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "gzip_level") == 0 ) { - gzip_level = atoi(i->second); + else if ( strcmp(key, "gzip_level") == 0 ) { + gzip_level = atoi(value); if ( gzip_level < 0 || gzip_level > 9 ) { Error("invalid value for 'gzip_level', must be a number between 0 and 9."); return false; } } - else if ( strcmp(i->first, "use_json") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "use_json") == 0 ) { + if ( strcmp(value, "T") == 0 ) use_json = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) use_json = false; else { Error("invalid value for 'use_json', must be a string and either \"T\" or \"F\""); @@ -286,10 +286,10 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "enable_utf_8") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "enable_utf_8") == 0 ) { + if ( strcmp(value, "T") == 0 ) enable_utf_8 = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) enable_utf_8 = false; else { Error("invalid value for 'enable_utf_8', must be a string and either \"T\" or \"F\""); @@ -297,10 +297,10 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "output_to_stdout") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "output_to_stdout") == 0 ) { + if ( strcmp(value, "T") == 0 ) output_to_stdout = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) output_to_stdout = false; else { Error( @@ -310,28 +310,28 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "separator") == 0 ) - separator.assign(i->second); + else if ( strcmp(key, "separator") == 0 ) + separator.assign(value); - else if ( strcmp(i->first, "set_separator") == 0 ) - set_separator.assign(i->second); + else if ( strcmp(key, "set_separator") == 0 ) + set_separator.assign(value); - else if ( strcmp(i->first, "empty_field") == 0 ) - empty_field.assign(i->second); + else if ( strcmp(key, "empty_field") == 0 ) + empty_field.assign(value); - else if ( strcmp(i->first, "unset_field") == 0 ) - unset_field.assign(i->second); + else if ( strcmp(key, "unset_field") == 0 ) + unset_field.assign(value); - else if ( strcmp(i->first, "meta_prefix") == 0 ) - meta_prefix.assign(i->second); + else if ( strcmp(key, "meta_prefix") == 0 ) + meta_prefix.assign(value); - else if ( strcmp(i->first, "json_timestamps") == 0 ) - json_timestamps.assign(i->second); + else if ( strcmp(key, "json_timestamps") == 0 ) + json_timestamps.assign(value); - else if ( strcmp(i->first, "json_include_unset_fields") == 0 ) { - if ( strcmp(i->second, "T") == 0 ) + else if ( strcmp(key, "json_include_unset_fields") == 0 ) { + if ( strcmp(value, "T") == 0 ) json_include_unset_fields = true; - else if ( strcmp(i->second, "F") == 0 ) + else if ( strcmp(value, "F") == 0 ) json_include_unset_fields = false; else { Error( @@ -341,8 +341,8 @@ bool Ascii::InitFilterOptions() { } } - else if ( strcmp(i->first, "gzip_file_extension") == 0 ) - gzip_file_extension.assign(i->second); + else if ( strcmp(key, "gzip_file_extension") == 0 ) + gzip_file_extension.assign(value); } if ( ! InitFormatter() ) diff --git a/src/logging/writers/none/None.cc b/src/logging/writers/none/None.cc index 73affacb9d..e2ba96aae0 100644 --- a/src/logging/writers/none/None.cc +++ b/src/logging/writers/none/None.cc @@ -20,13 +20,13 @@ bool None::DoInit(const WriterInfo& info, int num_fields, const threading::Field std::vector> keys; - for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); i++ ) - keys.emplace_back(i->first, i->second); + for ( const auto& [key, value] : info.config ) + keys.emplace_back(key, value); std::sort(keys.begin(), keys.end()); - for ( std::vector>::const_iterator i = keys.begin(); i != keys.end(); i++ ) - std::cout << " config[" << (*i).first << "] = " << (*i).second << "\n"; + for ( const auto& [key, value] : keys ) + std::cout << " config[" << key << "] = " << value << "\n"; for ( int i = 0; i < num_fields; i++ ) { const threading::Field* field = fields[i]; diff --git a/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac b/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac index eead7bbdc0..c4b4cc8499 100644 --- a/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac +++ b/src/packet_analysis/protocol/gtpv1/gtpv1-analyzer.pac @@ -244,10 +244,8 @@ void CreatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G bool second_nsapi = false; bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_IMSI: rv->Assign(0, BuildIMSI(ie)); @@ -322,7 +320,7 @@ void CreatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(21, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -342,10 +340,8 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -390,7 +386,7 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(12, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -410,10 +406,8 @@ void UpdatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_IMSI: rv->Assign(0, BuildIMSI(ie)); @@ -467,7 +461,7 @@ void UpdatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(15, BuildEndUserAddr(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -487,10 +481,8 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const bool second_gsn_addr = false; - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -526,7 +518,7 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(9, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -537,17 +529,15 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu) { if ( ! ::gtpv1_delete_pdp_ctx_request ) - return; + return; auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_request_elements); const vector * v = pdu->delete_pdp_ctx_request(); - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_TEARDOWN_IND: rv->Assign(0, BuildTeardownInd(ie)); @@ -559,7 +549,7 @@ void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G rv->Assign(2, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } @@ -570,17 +560,15 @@ void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu) { if ( ! ::gtpv1_delete_pdp_ctx_response ) - return; + return; auto rv = zeek::make_intrusive( zeek::BifType::Record::gtp_delete_pdp_ctx_response_elements); const vector * v = pdu->delete_pdp_ctx_response(); - for ( size_t i = 0; i < v->size(); ++i ) + for ( InformationElement* ie : *v ) { - const InformationElement* ie = (*v)[i]; - switch ( ie->type() ) { case GTPv1::TYPE_CAUSE: rv->Assign(0, BuildCause(ie)); @@ -589,7 +577,7 @@ void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const rv->Assign(1, BuildPrivateExt(ie)); break; default: - a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", (*v)[i]->type())); + a->Weird("gtp_invalid_info_element", nullptr, zeek::util::fmt("%d", ie->type())); break; } } diff --git a/src/packet_analysis/protocol/tcp/Stats.cc b/src/packet_analysis/protocol/tcp/Stats.cc index a19d0ca09d..180d79396d 100644 --- a/src/packet_analysis/protocol/tcp/Stats.cc +++ b/src/packet_analysis/protocol/tcp/Stats.cc @@ -7,7 +7,7 @@ namespace zeek::packet_analysis::TCP { TCPStateStats::TCPStateStats() { - for ( int i = 0; i < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++i ) + for ( int i = 0; i < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++i ) // NOLINT for ( int j = 0; j < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++j ) state_cnt[i][j] = 0; } diff --git a/src/plugin/Manager.cc b/src/plugin/Manager.cc index 59328b32a6..b856241436 100644 --- a/src/plugin/Manager.cc +++ b/src/plugin/Manager.cc @@ -440,9 +440,8 @@ void Manager::ExtendZeekPathForPlugins() { void Manager::InitPreScript() { assert(! init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - (*i)->DoConfigure(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + plugin->DoConfigure(); } // Sort plugins by name to make sure we have a deterministic order. @@ -452,10 +451,9 @@ void Manager::InitPreScript() { // order. ActivePluginsInternal()->sort(plugin_cmp); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - (*i)->InitializeComponents(); - (*i)->InitPreScript(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + plugin->InitializeComponents(); + plugin->InitPreScript(); } init = true; @@ -464,13 +462,12 @@ void Manager::InitPreScript() { void Manager::InitBifs() { bif_init_func_map* bifs = BifFilesInternal(); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) { - bif_init_func_map::const_iterator b = bifs->find(util::strtolower((*i)->Name())); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) { + bif_init_func_map::const_iterator b = bifs->find(util::strtolower(plugin->Name())); if ( b != bifs->end() ) { - for ( bif_init_func_list::const_iterator j = b->second->begin(); j != b->second->end(); ++j ) - (**j)(*i); + for ( const auto& func : *(b->second) ) + func(plugin); } } } @@ -478,25 +475,22 @@ void Manager::InitBifs() { void Manager::InitPostScript() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->InitPostScript(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->InitPostScript(); } void Manager::InitPreExecution() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->InitPreExecution(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->InitPreExecution(); } void Manager::FinishPlugins() { assert(init); - for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); - i != Manager::ActivePluginsInternal()->end(); i++ ) - (*i)->Done(); + for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) + plugin->Done(); Manager::ActivePluginsInternal()->clear(); @@ -510,18 +504,18 @@ Manager::inactive_plugin_list Manager::InactivePlugins() const { inactive_plugin_list inactives; - for ( dynamic_plugin_map::const_iterator i = dynamic_plugins.begin(); i != dynamic_plugins.end(); i++ ) { + for ( const auto& [index, plugin] : dynamic_plugins ) { bool found = false; - for ( plugin_list::const_iterator j = all->begin(); j != all->end(); j++ ) { - if ( (*i).first == util::strtolower((*j)->Name()) ) { + for ( Plugin* plugin : *all ) { + if ( index == util::strtolower(plugin->Name()) ) { found = true; break; } } if ( ! found ) - inactives.emplace_back(*i); + inactives.emplace_back(index, plugin); } return inactives; @@ -595,9 +589,9 @@ void Manager::EnableHook(HookType hook, Plugin* plugin, int prio) { hook_list* l = hooks[hook]; - for ( hook_list::iterator i = l->begin(); i != l->end(); i++ ) { + for ( const auto& [_, hook_plugin] : *l ) { // Already enabled for this plugin. - if ( (*i).second == plugin ) + if ( hook_plugin == plugin ) return; } @@ -646,9 +640,7 @@ int Manager::HookLoadFile(const Plugin::LoadType type, const string& file, const int rc = -1; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rc = p->HookLoadFile(type, file, resolved); if ( rc >= 0 ) @@ -677,9 +669,7 @@ std::pair> Manager::HookLoadFileExtended(const P std::pair> rc = {-1, std::nullopt}; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rc = p->HookLoadFileExtended(type, file, resolved); if ( rc.first >= 0 ) @@ -713,9 +703,7 @@ std::pair Manager::HookCallFunction(const Func* func, zeek::detail std::pair rval{false, nullptr}; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { rval = p->HookFunctionCall(func, parent, vecargs); if ( rval.first ) @@ -742,9 +730,7 @@ bool Manager::HookQueueEvent(Event* event) const { bool result = false; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( p->HookQueueEvent(event) ) { result = true; break; @@ -766,8 +752,7 @@ void Manager::HookDrainEvents() const { hook_list* l = hooks[HOOK_DRAIN_EVENTS]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookDrainEvents(); } @@ -786,8 +771,7 @@ void Manager::HookSetupAnalyzerTree(Connection* conn) const { hook_list* l = hooks[HOOK_SETUP_ANALYZER_TREE]; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookSetupAnalyzerTree(conn); } } @@ -808,8 +792,7 @@ void Manager::HookUpdateNetworkTime(double network_time) const { hook_list* l = hooks[HOOK_UPDATE_NETWORK_TIME]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookUpdateNetworkTime(network_time); } @@ -828,8 +811,7 @@ void Manager::HookObjDtor(void* obj) const { hook_list* l = hooks[HOOK_OBJ_DTOR]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookObjDtor(obj); } @@ -856,8 +838,7 @@ void Manager::HookLogInit(const std::string& writer, const std::string& instanti hook_list* l = hooks[HOOK_LOG_INIT]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookLogInit(writer, instantiating_filter, local, remote, info, num_fields, fields); } @@ -885,9 +866,7 @@ bool Manager::HookLogWrite(const std::string& writer, const std::string& filter, bool result = true; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookLogWrite(writer, filter, info, num_fields, fields, vals) ) { result = false; break; @@ -924,9 +903,7 @@ bool Manager::HookReporter(const std::string& prefix, const EventHandlerPtr even bool result = true; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookReporter(prefix, event, conn, addl, location, location1, location2, time, message) ) { result = false; break; @@ -951,8 +928,7 @@ void Manager::HookUnprocessedPacket(const Packet* packet) const { hook_list* l = hooks[HOOK_UNPROCESSED_PACKET]; if ( l ) - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; + for ( const auto& [_, p] : *l ) { p->HookUnprocessedPacket(packet); } @@ -976,9 +952,7 @@ bool Manager::HookPublishEvent(zeek::cluster::Backend& backend, const std::strin bool result = true; if ( l ) { - for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { - Plugin* p = (*i).second; - + for ( const auto& [_, p] : *l ) { if ( ! p->HookPublishEvent(backend, topic, event) ) { result = false; break; diff --git a/src/plugin/Plugin.cc b/src/plugin/Plugin.cc index ad0ea84a0d..e779c4e306 100644 --- a/src/plugin/Plugin.cc +++ b/src/plugin/Plugin.cc @@ -396,17 +396,17 @@ void Plugin::Describe(ODesc* d) const { if ( d->IsShort() ) return; - for ( component_list::const_iterator i = components.begin(); i != components.end(); i++ ) { - (*i)->Describe(d); + for ( Component* component : components ) { + component->Describe(d); d->Add("\n"); } bif_item_list items = BifItems(); - for ( bif_item_list::const_iterator i = items.begin(); i != items.end(); i++ ) { + for ( const auto& item : items ) { const char* type = nullptr; - switch ( (*i).GetType() ) { + switch ( item.GetType() ) { case BifItem::FUNCTION: type = "Function"; break; case BifItem::EVENT: type = "Event"; break; @@ -424,16 +424,13 @@ void Plugin::Describe(ODesc* d) const { d->Add("["); d->Add(type); d->Add("] "); - d->Add((*i).GetID()); + d->Add(item.GetID()); d->Add("\n"); } hook_list hooks = EnabledHooks(); - for ( hook_list::iterator i = hooks.begin(); i != hooks.end(); i++ ) { - HookType hook = (*i).first; - int prio = (*i).second; - + for ( const auto& [hook, prio] : hooks ) { d->Add(" Implements "); d->Add(hook_name(hook)); d->Add(" (priority "); diff --git a/src/probabilistic/BitVector.cc b/src/probabilistic/BitVector.cc index 8b7a9e428e..8bde14a74c 100644 --- a/src/probabilistic/BitVector.cc +++ b/src/probabilistic/BitVector.cc @@ -17,15 +17,16 @@ BitVector::block_type BitVector::bits_per_block = std::numeric_limitsHash(key); - for ( size_t i = 0; i < h.size(); ++i ) - bits->Set(h[i] % bits->Size()); + for ( unsigned long long i : h ) + bits->Set(i % bits->Size()); } bool BasicBloomFilter::Decrement(const zeek::detail::HashKey* key) { @@ -176,8 +176,8 @@ bool BasicBloomFilter::Decrement(const zeek::detail::HashKey* key) { size_t BasicBloomFilter::Count(const zeek::detail::HashKey* key) const { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) { - if ( ! (*bits)[h[i] % bits->Size()] ) + for ( unsigned long long i : h ) { + if ( ! (*bits)[i % bits->Size()] ) return 0; } @@ -267,8 +267,8 @@ std::string CountingBloomFilter::InternalState() const { return util::fmt("%" PR void CountingBloomFilter::Add(const zeek::detail::HashKey* key) { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) - cells->Increment(h[i] % cells->Size()); + for ( unsigned long long i : h ) + cells->Increment(i % cells->Size()); } bool CountingBloomFilter::Decrement(const zeek::detail::HashKey* key) { @@ -278,8 +278,8 @@ bool CountingBloomFilter::Decrement(const zeek::detail::HashKey* key) { detail::Hasher::digest_vector h = hasher->Hash(key); - for ( size_t i = 0; i < h.size(); ++i ) - cells->Decrement(h[i] % cells->Size()); + for ( unsigned long long i : h ) + cells->Decrement(i % cells->Size()); return true; } @@ -289,8 +289,8 @@ size_t CountingBloomFilter::Count(const zeek::detail::HashKey* key) const { detail::CounterVector::size_type min = std::numeric_limits::max(); - for ( size_t i = 0; i < h.size(); ++i ) { - detail::CounterVector::size_type cnt = cells->Count(h[i] % cells->Size()); + for ( unsigned long long i : h ) { + detail::CounterVector::size_type cnt = cells->Count(i % cells->Size()); if ( cnt < min ) min = cnt; } diff --git a/src/script_opt/ZAM/BuiltIn.cc b/src/script_opt/ZAM/BuiltIn.cc index 8238e122e3..c7b07d60ee 100644 --- a/src/script_opt/ZAM/BuiltIn.cc +++ b/src/script_opt/ZAM/BuiltIn.cc @@ -312,8 +312,7 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args) std::vector consts; std::vector v; - for ( auto i = 0U; i < args.size(); ++i ) { - auto a = args[i]; + for ( const auto& a : args ) { if ( a->Tag() == EXPR_NAME ) v.push_back(zam->FrameSlot(a->AsNameExpr())); else @@ -402,9 +401,9 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args) BiFArgsType MultiZBI::ComputeArgsType(const ExprPList& args) const { zeek_uint_t mask = 0; - for ( auto i = 0U; i < args.size(); ++i ) { + for ( const auto& a : args ) { mask <<= 1; - if ( args[i]->Tag() == EXPR_CONST ) + if ( a->Tag() == EXPR_CONST ) mask |= 1; } diff --git a/src/threading/Manager.cc b/src/threading/Manager.cc index 8fcf6605ac..5b16e6b6d2 100644 --- a/src/threading/Manager.cc +++ b/src/threading/Manager.cc @@ -54,7 +54,7 @@ void Manager::InitPostScript() { m.second = 0; MsgThread::Stats thread_stats; - for ( const auto& t : thread_mgr->msg_threads ) { + for ( auto* t : thread_mgr->msg_threads ) { t->GetStats(&thread_stats); thread_mgr->current_bucketed_messages.pending_in_total += thread_stats.pending_in; @@ -140,16 +140,16 @@ void Manager::Terminate() { // Signal all to stop. - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->SignalStop(); + for ( auto* t : all_threads ) + t->SignalStop(); - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->WaitForStop(); + for ( auto* t : all_threads ) + t->WaitForStop(); // Then join them all. - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - (*i)->Join(); - delete *i; + for ( auto* t : all_threads ) { + t->Join(); + delete t; } all_threads.clear(); @@ -183,8 +183,8 @@ void Manager::AddMsgThread(MsgThread* thread) { void Manager::KillThreads() { DBG_LOG(DBG_THREADING, "Killing threads ..."); - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) - (*i)->Kill(); + for ( auto* t : all_threads ) + t->Kill(); } void Manager::KillThread(BasicThread* thread) { @@ -199,15 +199,12 @@ void Manager::SendHeartbeats() { // Since this is a regular timer, this is also an ideal place to check whether we have // and dead threads and to delete them. all_thread_list to_delete; - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - BasicThread* t = *i; - + for ( auto* t : all_threads ) { if ( t->Killed() ) to_delete.push_back(t); } - for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { - BasicThread* t = *i; + for ( auto* t : to_delete ) { t->WaitForStop(); all_threads.remove(t); @@ -290,9 +287,7 @@ void Manager::Flush() { did_process = false; - for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { - MsgThread* t = *i; - + for ( auto* t : msg_threads ) { if ( do_beat ) t->Heartbeat(); @@ -316,15 +311,12 @@ void Manager::Flush() { all_thread_list to_delete; - for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { - BasicThread* t = *i; - + for ( auto* t : all_threads ) { if ( t->Killed() ) to_delete.push_back(t); } - for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { - BasicThread* t = *i; + for ( auto* t : to_delete ) { t->WaitForStop(); all_threads.remove(t); @@ -346,9 +338,7 @@ void Manager::Flush() { const threading::Manager::msg_stats_list& threading::Manager::GetMsgThreadStats() { stats.clear(); - for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { - MsgThread* t = *i; - + for ( auto* t : msg_threads ) { MsgThread::Stats s; t->GetStats(&s); diff --git a/src/util.cc b/src/util.cc index e8b33bf59c..672c22757c 100644 --- a/src/util.cc +++ b/src/util.cc @@ -664,8 +664,8 @@ string normalize_path(std::string_view path) { } } - for ( auto it = final_components.begin(); it != final_components.end(); ++it ) { - new_path.append(*it); + for ( const auto& comp : final_components ) { + new_path.append(comp); new_path.append("/"); } @@ -681,8 +681,8 @@ string without_zeekpath_component(std::string_view path) { const auto paths = tokenize_string(zeek_path(), path_list_separator[0]); - for ( size_t i = 0; i < paths.size(); ++i ) { - string common = normalize_path(paths[i]); + for ( const auto& p : paths ) { + string common = normalize_path(p); if ( rval.find(common) != 0 ) continue; @@ -1817,8 +1817,8 @@ string find_file(const string& filename, const string& path_set, const string& o if ( ! opt_ext.empty() ) ext.push_back(opt_ext); - for ( size_t n = 0; n < paths.size(); ++n ) { - string f = find_file_in_path(filename, paths[n], ext); + for ( const auto& p : paths ) { + string f = find_file_in_path(filename, p, ext); if ( ! f.empty() ) return f; @@ -1833,8 +1833,8 @@ string find_script_file(const string& filename, const string& path_set) { vector ext = {".zeek"}; - for ( size_t n = 0; n < paths.size(); ++n ) { - string f = find_file_in_path(filename, paths[n], ext); + for ( const auto& p : paths ) { + string f = find_file_in_path(filename, p, ext); if ( ! f.empty() ) return f; diff --git a/src/zeekygen/Configuration.cc b/src/zeekygen/Configuration.cc index 021bfd0982..a2639ea71e 100644 --- a/src/zeekygen/Configuration.cc +++ b/src/zeekygen/Configuration.cc @@ -72,18 +72,18 @@ Config::Config(const string& arg_file, const string& delim) } Config::~Config() { - for ( size_t i = 0; i < targets.size(); ++i ) - delete targets[i]; + for ( auto* t : targets ) + delete t; } void Config::FindDependencies(const vector& infos) { - for ( size_t i = 0; i < targets.size(); ++i ) - targets[i]->FindDependencies(infos); + for ( auto* t : targets ) + t->FindDependencies(infos); } void Config::GenerateDocs() const { - for ( size_t i = 0; i < targets.size(); ++i ) - targets[i]->Generate(); + for ( auto* t : targets ) + t->Generate(); } time_t Config::GetModificationTime() const { diff --git a/src/zeekygen/IdentifierInfo.cc b/src/zeekygen/IdentifierInfo.cc index 702f187890..0bce8a49f5 100644 --- a/src/zeekygen/IdentifierInfo.cc +++ b/src/zeekygen/IdentifierInfo.cc @@ -81,9 +81,9 @@ vector IdentifierInfo::GetFieldComments(const string& field) const { list IdentifierInfo::GetRedefs(const string& from_script) const { list rval; - for ( redef_list::const_iterator it = redefs.begin(); it != redefs.end(); ++it ) { - if ( from_script == (*it)->from_script ) - rval.push_back(*(*it)); + for ( Redefinition* redef : redefs ) { + if ( from_script == redef->from_script ) + rval.push_back(*redef); } return rval; diff --git a/src/zeekygen/Manager.cc b/src/zeekygen/Manager.cc index 4afa22354f..038a183775 100644 --- a/src/zeekygen/Manager.cc +++ b/src/zeekygen/Manager.cc @@ -93,8 +93,8 @@ Manager::Manager(const string& arg_config, const string& command) } Manager::~Manager() { - for ( size_t i = 0; i < all_info.size(); ++i ) - delete all_info[i]; + for ( auto* info : all_info ) + delete info; } void Manager::InitPreScript() { @@ -106,8 +106,8 @@ void Manager::InitPostScript() { if ( disabled ) return; - for ( size_t i = 0; i < all_info.size(); ++i ) - all_info[i]->InitPostScript(); + for ( auto* info : all_info ) + info->InitPostScript(); config.FindDependencies(all_info); } @@ -179,8 +179,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) { script_info->AddDependency(depname); DBG_LOG(DBG_ZEEKYGEN, "Added script dependency %s for %s", depname.c_str(), name.c_str()); - for ( size_t i = 0; i < comment_buffer.size(); ++i ) - DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", comment_buffer[i].c_str())); + for ( const auto& cmnt : comment_buffer ) + DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", cmnt.c_str())); } void Manager::ModuleUsage(const string& path, const string& module) { diff --git a/src/zeekygen/PackageInfo.cc b/src/zeekygen/PackageInfo.cc index 6291d5cde3..cfa73c14d6 100644 --- a/src/zeekygen/PackageInfo.cc +++ b/src/zeekygen/PackageInfo.cc @@ -35,8 +35,8 @@ PackageInfo::PackageInfo(const string& arg_name) : Info(), pkg_name(arg_name), r string PackageInfo::DoReStructuredText(bool roles_only) const { string rval = util::fmt(":doc:`%s `\n\n", pkg_name.c_str(), pkg_name.c_str()); - for ( size_t i = 0; i < readme.size(); ++i ) - rval += " " + readme[i] + "\n"; + for ( const auto& r : readme ) + rval += " " + r + "\n"; return rval; } diff --git a/src/zeekygen/ReStructuredTextTable.cc b/src/zeekygen/ReStructuredTextTable.cc index b68dbb86b9..26d5eb5364 100644 --- a/src/zeekygen/ReStructuredTextTable.cc +++ b/src/zeekygen/ReStructuredTextTable.cc @@ -40,16 +40,16 @@ string ReStructuredTextTable::MakeBorder(const vector& col_sizes, char b string ReStructuredTextTable::AsString(char border) const { string rval = MakeBorder(longest_row_in_column, border); - for ( size_t row = 0; row < rows.size(); ++row ) { + for ( const auto& row : rows ) { for ( size_t col = 0; col < num_cols; ++col ) { if ( col > 0 ) { - size_t last = rows[row][col - 1].size(); + size_t last = row[col - 1].size(); size_t longest = longest_row_in_column[col - 1]; size_t whitespace = longest - last + 1; rval += string(whitespace, ' '); } - rval += rows[row][col]; + rval += row[col]; } rval += "\n"; diff --git a/src/zeekygen/ScriptInfo.cc b/src/zeekygen/ScriptInfo.cc index 8495b384f1..365af48a2f 100644 --- a/src/zeekygen/ScriptInfo.cc +++ b/src/zeekygen/ScriptInfo.cc @@ -23,17 +23,17 @@ bool IdInfoComp::operator()(const IdentifierInfo* lhs, const IdentifierInfo* rhs static vector summary_comment(const vector& cmnts) { vector rval; - for ( size_t i = 0; i < cmnts.size(); ++i ) { - size_t end = end_of_first_sentence(cmnts[i]); + for ( const auto& cmnt : cmnts ) { + size_t end = end_of_first_sentence(cmnt); if ( end == string::npos ) { - if ( is_all_whitespace(cmnts[i]) ) + if ( is_all_whitespace(cmnt) ) break; - rval.push_back(cmnts[i]); + rval.push_back(cmnt); } else { - rval.push_back(cmnts[i].substr(0, end + 1)); + rval.push_back(cmnt.substr(0, end + 1)); break; } } @@ -68,12 +68,12 @@ static string make_summary(const string& heading, char underline, char border, c ReStructuredTextTable table(2); - for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { - auto* id = (*it)->GetID(); + for ( IdentifierInfo* info : id_list ) { + auto* id = info->GetID(); ODesc d; d.SetQuotes(true); id->DescribeReSTShort(&d); - add_summary_rows(d, summary_comment((*it)->GetComments()), &table); + add_summary_rows(d, summary_comment(info->GetComments()), &table); } return make_heading(heading, underline) + table.AsString(border) + "\n"; @@ -86,14 +86,14 @@ static string make_redef_summary(const string& heading, char underline, char bor ReStructuredTextTable table(2); - for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { - auto* id = (*it)->GetID(); + for ( IdentifierInfo* info : id_set ) { + auto* id = info->GetID(); ODesc d; d.SetQuotes(true); id->DescribeReSTShort(&d); using redef_list = std::list; - redef_list redefs = (*it)->GetRedefs(from_script); + redef_list redefs = info->GetRedefs(from_script); for ( redef_list::const_iterator iit = redefs.begin(); iit != redefs.end(); ++iit ) { add_summary_rows(d, summary_comment(iit->comments), &table); @@ -199,8 +199,8 @@ static string make_details(const string& heading, char underline, const id_info_ string rval = make_heading(heading, underline); - for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { - rval += (*it)->ReStructuredText(); + for ( IdentifierInfo* info : id_list ) { + rval += info->ReStructuredText(); rval += "\n\n"; } @@ -213,8 +213,8 @@ static string make_redef_details(const string& heading, char underline, const id string rval = make_heading(heading, underline); - for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { - rval += (*it)->ReStructuredText(true); + for ( IdentifierInfo* info : id_set ) { + rval += info->ReStructuredText(true); rval += "\n\n"; } @@ -337,13 +337,13 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const { rval += ":tocdepth: 3\n\n"; rval += make_heading(name, '='); - for ( string_set::const_iterator it = module_usages.begin(); it != module_usages.end(); ++it ) - rval += ".. zeek:namespace:: " + *it + "\n"; + for ( const auto& usage : module_usages ) + rval += ".. zeek:namespace:: " + usage + "\n"; rval += "\n"; - for ( size_t i = 0; i < comments.size(); ++i ) - rval += comments[i] + "\n"; + for ( const auto& cmnt : comments ) + rval += cmnt + "\n"; rval += "\n"; @@ -410,15 +410,15 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const { time_t ScriptInfo::DoGetModificationTime() const { time_t most_recent = get_mtime(path); - for ( string_set::const_iterator it = dependencies.begin(); it != dependencies.end(); ++it ) { - Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(*it); + for ( const auto& dep : dependencies ) { + Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(dep); if ( ! info ) { - string pkg_name = *it + "/__load__.zeek"; + string pkg_name = dep + "/__load__.zeek"; info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name); if ( ! info ) - reporter->InternalWarning("Zeekygen failed to get mtime of %s", it->c_str()); + reporter->InternalWarning("Zeekygen failed to get mtime of %s", dep.c_str()); continue; } diff --git a/src/zeekygen/Target.cc b/src/zeekygen/Target.cc index d9fcbd4b68..d4a133dddf 100644 --- a/src/zeekygen/Target.cc +++ b/src/zeekygen/Target.cc @@ -174,8 +174,8 @@ template static vector filter_matches(const vector& from, Target* t) { vector rval; - for ( size_t i = 0; i < from.size(); ++i ) { - T* d = dynamic_cast(from[i]); + for ( Info* f : from ) { + T* d = dynamic_cast(f); if ( ! d ) continue; @@ -339,19 +339,18 @@ void PackageTarget::DoFindDependencies(const vector& infos) { if ( pkg_deps.empty() ) reporter->FatalError("No match for Zeekygen target '%s' pattern '%s'", Name().c_str(), Pattern().c_str()); - for ( size_t i = 0; i < infos.size(); ++i ) { - ScriptInfo* script = dynamic_cast(infos[i]); + for ( Info* info : infos ) { + ScriptInfo* script = dynamic_cast(info); if ( ! script ) continue; - for ( size_t j = 0; j < pkg_deps.size(); ++j ) { - if ( strncmp(script->Name().c_str(), pkg_deps[j]->Name().c_str(), pkg_deps[j]->Name().size()) != 0 ) + for ( const auto& dep : pkg_deps ) { + if ( strncmp(script->Name().c_str(), dep->Name().c_str(), dep->Name().size()) != 0 ) continue; - DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), - pkg_deps[j]->Name().c_str()); - pkg_manifest[pkg_deps[j]].push_back(script); + DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), dep->Name().c_str()); + pkg_manifest[dep].push_back(script); script_deps.push_back(script); } } @@ -366,26 +365,26 @@ void PackageTarget::DoGenerate() const { fprintf(file.f, ":orphan:\n\n"); - for ( manifest_t::const_iterator it = pkg_manifest.begin(); it != pkg_manifest.end(); ++it ) { - string header = util::fmt("Package: %s", it->first->Name().c_str()); + for ( const auto& [pkg, info_vec] : pkg_manifest ) { + string header = util::fmt("Package: %s", pkg->Name().c_str()); header += "\n" + string(header.size(), '='); fprintf(file.f, "%s\n\n", header.c_str()); - vector readme = it->first->GetReadme(); + vector readme = pkg->GetReadme(); - for ( size_t i = 0; i < readme.size(); ++i ) - fprintf(file.f, "%s\n", readme[i].c_str()); + for ( const auto& r : readme ) + fprintf(file.f, "%s\n", r.c_str()); fprintf(file.f, "\n"); - for ( size_t i = 0; i < it->second.size(); ++i ) { - fprintf(file.f, ":doc:`/scripts/%s`\n\n", it->second[i]->Name().c_str()); + for ( ScriptInfo* info : info_vec ) { + fprintf(file.f, ":doc:`/scripts/%s`\n\n", info->Name().c_str()); - vector cmnts = it->second[i]->GetComments(); + vector cmnts = info->GetComments(); - for ( size_t j = 0; j < cmnts.size(); ++j ) - fprintf(file.f, " %s\n", cmnts[j].c_str()); + for ( const auto& cmnt : cmnts ) + fprintf(file.f, " %s\n", cmnt.c_str()); fprintf(file.f, "\n"); } @@ -405,8 +404,8 @@ void PackageIndexTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < pkg_deps.size(); ++i ) - fprintf(file.f, "%s\n", pkg_deps[i]->ReStructuredText().c_str()); + for ( PackageInfo* info : pkg_deps ) + fprintf(file.f, "%s\n", info->ReStructuredText().c_str()); } void ScriptTarget::DoFindDependencies(const vector& infos) { @@ -418,9 +417,9 @@ void ScriptTarget::DoFindDependencies(const vector& infos) { if ( ! IsDir() ) return; - for ( size_t i = 0; i < script_deps.size(); ++i ) { - if ( util::detail::is_package_loader(script_deps[i]->Name()) ) { - string pkg_dir = util::SafeDirname(script_deps[i]->Name()).result; + for ( ScriptInfo* d : script_deps ) { + if ( util::detail::is_package_loader(d->Name()) ) { + string pkg_dir = util::SafeDirname(d->Name()).result; string target_file = Name() + pkg_dir + "/index.rst"; Target* t = new PackageTarget(target_file, pkg_dir); t->FindDependencies(infos); @@ -472,23 +471,23 @@ void ScriptTarget::DoGenerate() const { set targets; vector dir_contents = dir_contents_recursive(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - string target_filename = Name() + script_deps[i]->Name() + ".rst"; + for ( ScriptInfo* d : script_deps ) { + string target_filename = Name() + d->Name() + ".rst"; targets.insert(target_filename); vector dep; - dep.push_back(script_deps[i]); + dep.push_back(d); if ( zeek::detail::zeekygen_mgr->IsUpToDate(target_filename, dep) ) continue; TargetFile file(target_filename); - fprintf(file.f, "%s\n", script_deps[i]->ReStructuredText().c_str()); + fprintf(file.f, "%s\n", d->ReStructuredText().c_str()); } - for ( size_t i = 0; i < pkg_deps.size(); ++i ) { - targets.insert(pkg_deps[i]->Name()); - pkg_deps[i]->Generate(); + for ( Target* tgt : pkg_deps ) { + targets.insert(tgt->Name()); + tgt->Generate(); } for ( const auto& f : dir_contents ) { @@ -511,8 +510,9 @@ void ScriptTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) - fprintf(file.f, "%s\n", script_deps[i]->ReStructuredText().c_str()); + for ( ScriptInfo* d : script_deps ) { + fprintf(file.f, "%s\n", d->ReStructuredText().c_str()); + } } void ScriptSummaryTarget::DoGenerate() const { @@ -521,9 +521,7 @@ void ScriptSummaryTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - ScriptInfo* d = dynamic_cast(script_deps[i]); - + for ( ScriptInfo* d : script_deps ) { if ( ! d ) continue; @@ -531,8 +529,8 @@ void ScriptSummaryTarget::DoGenerate() const { vector cmnts = d->GetComments(); - for ( size_t i = 0; i < cmnts.size(); ++i ) - fprintf(file.f, " %s\n", cmnts[i].c_str()); + for ( const string& cmnt : cmnts ) + fprintf(file.f, " %s\n", cmnt.c_str()); fprintf(file.f, "\n"); } @@ -547,9 +545,7 @@ void ScriptIndexTarget::DoGenerate() const { fprintf(file.f, ".. toctree::\n"); fprintf(file.f, " :maxdepth: 1\n\n"); - for ( size_t i = 0; i < script_deps.size(); ++i ) { - ScriptInfo* d = dynamic_cast(script_deps[i]); - + for ( ScriptInfo* d : script_deps ) { if ( ! d ) continue; @@ -570,8 +566,8 @@ void IdentifierTarget::DoGenerate() const { TargetFile file(Name()); - for ( size_t i = 0; i < id_deps.size(); ++i ) - fprintf(file.f, "%s\n\n", id_deps[i]->ReStructuredText().c_str()); + for ( IdentifierInfo* info : id_deps ) + fprintf(file.f, "%s\n\n", info->ReStructuredText().c_str()); } } // namespace zeek::zeekygen::detail diff --git a/src/zeekygen/utils.cc b/src/zeekygen/utils.cc index ae1b5b4015..8e4b2fadfa 100644 --- a/src/zeekygen/utils.cc +++ b/src/zeekygen/utils.cc @@ -3,6 +3,7 @@ #include "zeek/zeekygen/utils.h" #include +#include #include #include "zeek/Func.h" @@ -112,11 +113,8 @@ size_t end_of_first_sentence(const string& s) { } bool is_all_whitespace(const string& s) { - for ( size_t i = 0; i < s.size(); ++i ) - if ( ! isspace(s[i]) ) - return false; - - return true; + auto it = std::find_if(s.begin(), s.end(), [](char c) { return ! isspace(c); }); + return it == s.end(); } string redef_indication(const string& from_script) {