Fix clang-tidy modernize-loop-convert findings

This commit is contained in:
Tim Wojtulewicz 2025-05-13 10:06:13 -07:00
parent 49b803c0a8
commit f3588657bf
56 changed files with 452 additions and 542 deletions

View file

@ -136,9 +136,9 @@ void Attr::DescribeReST(ODesc* d, bool shorten) const {
expr->Eval(nullptr)->Describe(&dd); expr->Eval(nullptr)->Describe(&dd);
std::string s = dd.Description(); std::string s = dd.Description();
for ( size_t i = 0; i < s.size(); ++i ) for ( auto& c : s )
if ( s[i] == '\n' ) if ( c == '\n' )
s[i] = ' '; c = ' ';
add_long_expr_string(d, s, shorten); add_long_expr_string(d, s, shorten);
} }

View file

@ -336,19 +336,19 @@ int dbg_cmd_break(DebugCmd cmd, const vector<string>& args) {
if ( string_is_regex(args[0]) ) { if ( string_is_regex(args[0]) ) {
vector<ID*> choices; vector<ID*> choices;
choose_global_symbols_regex(args[0], choices, true); choose_global_symbols_regex(args[0], choices, true);
for ( unsigned int i = 0; i < choices.size(); ++i ) for ( const auto& choice : choices )
locstrings.emplace_back(choices[i]->Name()); locstrings.emplace_back(choice->Name());
} }
else else
locstrings.push_back(args[0]); locstrings.push_back(args[0]);
for ( unsigned int strindex = 0; strindex < locstrings.size(); ++strindex ) { for ( const auto& loc_str : locstrings ) {
debug_msg("Setting breakpoint on %s:\n", locstrings[strindex].c_str()); debug_msg("Setting breakpoint on %s:\n", loc_str.c_str());
vector<ParseLocationRec> plrs = parse_location_string(locstrings[strindex]); vector<ParseLocationRec> plrs = parse_location_string(loc_str);
for ( const auto& plr : plrs ) { for ( const auto& plr : plrs ) {
DbgBreakpoint* bp = new DbgBreakpoint(); DbgBreakpoint* bp = new DbgBreakpoint();
bp->SetID(g_debugger_state.NextBPID()); bp->SetID(g_debugger_state.NextBPID());
if ( ! bp->SetLocation(plr, locstrings[strindex]) ) { if ( ! bp->SetLocation(plr, loc_str) ) {
debug_msg("Breakpoint not set.\n"); debug_msg("Breakpoint not set.\n");
delete bp; delete bp;
} }

View file

@ -90,9 +90,9 @@ void DebugLogger::EnableStreams(const char* s) {
std::string ltok{util::strreplace(util::strtolower(tok), "_", "-")}; std::string ltok{util::strreplace(util::strtolower(tok), "_", "-")};
if ( strcasecmp("all", tok) == 0 ) { if ( strcasecmp("all", tok) == 0 ) {
for ( int i = 0; i < NUM_DBGS; ++i ) { for ( auto& strm : streams ) {
streams[i].enabled = true; strm.enabled = true;
enabled_streams.insert(streams[i].prefix); enabled_streams.insert(strm.prefix);
} }
all = true; all = true;

View file

@ -65,8 +65,8 @@ void EventHandler::Call(Args* vl, bool no_remote, double ts) {
xs.Reserve(vl->size()); xs.Reserve(vl->size());
bool valid_args = true; bool valid_args = true;
for ( size_t index = 0; index < vl->size(); ++index ) { for ( const auto& v : *vl ) {
if ( ! xs.Add((*vl)[index]) ) { if ( ! xs.Add(v) ) {
valid_args = false; valid_args = false;
auto_publish.clear(); auto_publish.clear();
reporter->Error("failed auto-remote event '%s', disabled", Name()); reporter->Error("failed auto-remote event '%s', disabled", Name());

View file

@ -457,8 +457,8 @@ static inline bool isIPv6ExtHeader(uint8_t type) {
} }
IPv6_Hdr_Chain::~IPv6_Hdr_Chain() { IPv6_Hdr_Chain::~IPv6_Hdr_Chain() {
for ( size_t i = 0; i < chain.size(); ++i ) for ( auto& c : chain )
delete chain[i]; delete c;
delete homeAddr; delete homeAddr;
delete finalDst; 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* new_data = (const u_char*)new_hdr;
const u_char* old_data = chain[0]->Data(); const u_char* old_data = chain[0]->Data();
for ( size_t i = 0; i < chain.size(); ++i ) { for ( const auto& c : chain ) {
int off = chain[i]->Data() - old_data; int off = c->Data() - old_data;
rval->chain.push_back(new IPv6_Hdr(chain[i]->Type(), new_data + off)); rval->chain.push_back(new IPv6_Hdr(c->Type(), new_data + off));
} }
return rval; return rval;

View file

@ -205,8 +205,8 @@ bool IPAddr::ConvertString(const char* s, in6_addr* result) {
if ( s[n] != '\0' ) if ( s[n] != '\0' )
return false; return false;
for ( auto i = 0; i < 4; ++i ) for ( int num : a )
if ( a[i] < 0 || a[i] > 255 ) if ( num < 0 || num > 255 )
return false; return false;
uint32_t addr = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]; uint32_t addr = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3];

View file

@ -121,8 +121,8 @@ bool LoadPolicyFileText(const char* policy_filename, const std::optional<std::st
} }
} }
for ( int i = 0; i < int(pf->lines.size()); ++i ) for ( const auto& l : pf->lines )
assert(pf->lines[i][0] != '\n'); assert(l[0] != '\n');
return true; return true;
} }

View file

@ -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) { inline void RE_Match_State::AddMatches(const AcceptingSet& as, MatchPos position) {
using am_idx = std::pair<AcceptIdx, MatchPos>; using am_idx = std::pair<AcceptIdx, MatchPos>;
for ( AcceptingSet::const_iterator it = as.begin(); it != as.end(); ++it ) for ( const auto& entry : as )
accepted_matches.insert(am_idx(*it, position)); accepted_matches.insert(am_idx(entry, position));
} }
bool RE_Match_State::Match(const u_char* bv, int n, bool bol, bool eol, bool clear) { bool RE_Match_State::Match(const u_char* bv, int n, bool bol, bool eol, bool clear) {

View file

@ -17,6 +17,7 @@
#include "zeek/RandTest.h" #include "zeek/RandTest.h"
#include <cmath> #include <cmath>
#include <cstring>
constexpr double log2of10 = 3.32192809488736234787; constexpr double log2of10 = 3.32192809488736234787;
@ -35,9 +36,7 @@ RandTest::RandTest() {
inmont = mcount = 0; inmont = mcount = 0;
cexp = montex = montey = montepi = sccu0 = scclast = scct1 = scct2 = scct3 = 0.0; cexp = montex = montey = montepi = sccu0 = scclast = scct1 = scct2 = scct3 = 0.0;
for ( int i = 0; i < 256; i++ ) { memset(ccount, 0, sizeof(ccount));
ccount[i] = 0;
}
} }
void RandTest::add(const void* buf, int bufl) { void RandTest::add(const void* buf, int bufl) {

View file

@ -106,8 +106,8 @@ RuleHdrTest::RuleHdrTest(RuleHdrTest& h) {
prefix_vals = h.prefix_vals; prefix_vals = h.prefix_vals;
for ( int j = 0; j < Rule::TYPES; ++j ) { for ( const auto& pset : h.psets ) {
for ( PatternSet* orig_set : h.psets[j] ) { for ( PatternSet* orig_set : pset ) {
PatternSet* copied_set = new PatternSet; PatternSet* copied_set = new PatternSet;
copied_set->re = nullptr; copied_set->re = nullptr;
copied_set->ids = orig_set->ids; copied_set->ids = orig_set->ids;
@ -133,8 +133,8 @@ RuleHdrTest::~RuleHdrTest() {
delete val; delete val;
delete vals; delete vals;
for ( int i = 0; i < Rule::TYPES; ++i ) { for ( auto& pset_list : psets ) {
for ( auto pset : psets[i] ) { for ( auto& pset : pset_list ) {
delete pset->re; delete pset->re;
delete pset; 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). // Evaluate a prefix list (matches if at least one value matches).
template<typename FuncT> template<typename FuncT>
static inline bool match_or(const vector<IPPrefix>& prefixes, const IPAddr& a, FuncT comp) { static inline bool match_or(const vector<IPPrefix>& prefixes, const IPAddr& a, FuncT comp) {
for ( size_t i = 0; i < prefixes.size(); ++i ) { for ( const auto& pfx : prefixes ) {
IPAddr masked(a); IPAddr masked(a);
masked.Mask(prefixes[i].LengthIPv6()); masked.Mask(pfx.LengthIPv6());
if ( comp(masked, prefixes[i].Prefix()) ) if ( comp(masked, pfx.Prefix()) )
return true; return true;
} }
return false; 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). // Evaluate a prefix list (doesn't match if any value matches).
template<typename FuncT> template<typename FuncT>
static inline bool match_not_and(const vector<IPPrefix>& prefixes, const IPAddr& a, FuncT comp) { static inline bool match_not_and(const vector<IPPrefix>& prefixes, const IPAddr& a, FuncT comp) {
for ( size_t i = 0; i < prefixes.size(); ++i ) { for ( const auto& pfx : prefixes ) {
IPAddr masked(a); IPAddr masked(a);
masked.Mask(prefixes[i].LengthIPv6()); masked.Mask(pfx.LengthIPv6());
if ( comp(masked, prefixes[i].Prefix()) ) if ( comp(masked, pfx.Prefix()) )
return false; return false;
} }
return true; return true;
@ -1083,12 +1083,12 @@ void RuleMatcher::GetStats(Stats* stats, RuleHdrTest* hdr_test) const {
DFA_State_Cache::Stats cstats; DFA_State_Cache::Stats cstats;
for ( int i = 0; i < Rule::TYPES; ++i ) { for ( const auto& pset_list : hdr_test->psets ) {
for ( const auto& set : hdr_test->psets[i] ) { for ( const auto& pset : pset_list ) {
assert(set->re); assert(pset->re);
++stats->matchers; ++stats->matchers;
set->re->DFA()->Cache()->GetStats(&cstats); pset->re->DFA()->Cache()->GetStats(&cstats);
stats->dfa_states += cstats.dfa_states; stats->dfa_states += cstats.dfa_states;
stats->computed += cstats.computed; stats->computed += cstats.computed;
@ -1183,7 +1183,9 @@ static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, vector<IPPrefi
v->AsSubNet().Prefix().GetBytes(&n); v->AsSubNet().Prefix().GetBytes(&n);
v->AsSubNetVal()->Mask().CopyIPv6(m); 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]); m[i] = ntohl(m[i]);
bool is_v4_mask = m[0] == 0xffffffff && m[1] == m[0] && m[2] == m[0]; bool is_v4_mask = m[0] == 0xffffffff && m[1] == m[0] && m[2] == m[0];

View file

@ -376,8 +376,8 @@ void get_final_stats() {
void delete_run() { void delete_run() {
util::detail::set_processing_status("TERMINATING", "delete_run"); util::detail::set_processing_status("TERMINATING", "delete_run");
for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i ) for ( auto& anon : zeek::detail::ip_anonymizer )
delete zeek::detail::ip_anonymizer[i]; delete anon;
} }
double check_pseudo_time(const Packet* pkt) { double check_pseudo_time(const Packet* pkt) {

View file

@ -194,14 +194,13 @@ void ProfileLogger::Log() {
file->Write(util::fmt("%0.6f Threads: current=%zu\n", run_state::network_time, thread_mgr->NumThreads())); 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(); 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 ) { for ( const auto& [name, s] : thread_stats ) {
threading::MsgThread::Stats s = i->second;
file->Write(util::fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64 file->Write(util::fmt("%0.6f %-25s in=%" PRIu64 " out=%" PRIu64 " pending=%" PRIu64 "/%" PRIu64
" (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")" " (#queue r/w: in=%" PRIu64 "/%" PRIu64 " out=%" PRIu64 "/%" PRIu64 ")"
"\n", "\n",
run_state::network_time, i->first.c_str(), s.sent_in, s.sent_out, s.pending_in, run_state::network_time, name.c_str(), s.sent_in, s.sent_out, s.pending_in, s.pending_out,
s.pending_out, s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, s.queue_in_stats.num_reads, s.queue_in_stats.num_writes, s.queue_out_stats.num_reads,
s.queue_out_stats.num_reads, s.queue_out_stats.num_writes)); s.queue_out_stats.num_writes));
} }
auto cs = broker_mgr->GetStatistics(); auto cs = broker_mgr->GetStatistics();

View file

@ -162,8 +162,8 @@ void Trigger::Terminate() {
Trigger::~Trigger() { Trigger::~Trigger() {
DBG_LOG(DBG_NOTIFIERS, "%s: deleting", Name()); DBG_LOG(DBG_NOTIFIERS, "%s: deleting", Name());
for ( ValCache::iterator i = cache.begin(); i != cache.end(); ++i ) for ( auto& [_, trigger] : cache )
Unref(i->second); Unref(trigger);
Unref(frame); Unref(frame);
UnregisterAll(); UnregisterAll();
@ -457,9 +457,8 @@ void Manager::Process() {
TriggerList tmp; TriggerList tmp;
pending = &tmp; pending = &tmp;
for ( TriggerList::iterator i = orig->begin(); i != orig->end(); ++i ) { for ( auto* t : *orig ) {
Trigger* t = *i; t->Eval();
(*i)->Eval();
Unref(t); Unref(t);
} }

View file

@ -756,9 +756,7 @@ void FuncType::DescribeReST(ODesc* d, bool roles_only) const {
void FuncType::AddPrototype(Prototype p) { prototypes.emplace_back(std::move(p)); } void FuncType::AddPrototype(Prototype p) { prototypes.emplace_back(std::move(p)); }
std::optional<FuncType::Prototype> FuncType::FindPrototype(const RecordType& args) const { std::optional<FuncType::Prototype> FuncType::FindPrototype(const RecordType& args) const {
for ( auto i = 0u; i < prototypes.size(); ++i ) { for ( const auto& p : prototypes ) {
const auto& p = prototypes[i];
if ( args.NumFields() != p.args->NumFields() ) if ( args.NumFields() != p.args->NumFields() )
continue; continue;
@ -1661,8 +1659,8 @@ const char* EnumType::Lookup(zeek_int_t value) const {
EnumType::enum_name_list EnumType::Names() const { EnumType::enum_name_list EnumType::Names() const {
enum_name_list n; enum_name_list n;
for ( auto iter = names.begin(); iter != names.end(); ++iter ) for ( const auto& [name, value] : names )
n.emplace_back(iter->first, iter->second); n.emplace_back(name, value);
return n; return n;
} }

View file

@ -12,8 +12,7 @@ namespace zeek {
void UID::Set(zeek_uint_t bits, const uint64_t* v, size_t n) { void UID::Set(zeek_uint_t bits, const uint64_t* v, size_t n) {
initialized = true; initialized = true;
for ( size_t i = 0; i < UID_LEN; ++i ) memset(uid, 0, sizeof(uid));
uid[i] = 0;
if ( bits > UID_LEN * 64 ) if ( bits > UID_LEN * 64 )
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"); reporter->InternalError("use of uninitialized UID");
char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation char tmp[sizeof(uid) * 8 + 1]; // enough for even binary representation
for ( size_t i = 0; i < UID_LEN; ++i ) for ( const auto& digit : uid )
prefix.append(util::uitoa_n(uid[i], tmp, sizeof(tmp), 62)); prefix.append(util::uitoa_n(digit, tmp, sizeof(tmp), 62));
return prefix; return prefix;
} }

View file

@ -738,8 +738,8 @@ IPAddr SubNetVal::Mask() const {
// We need to special-case a mask width of zero, since // We need to special-case a mask width of zero, since
// the compiler doesn't guarantee that 1 << 32 yields 0. // the compiler doesn't guarantee that 1 << 32 yields 0.
uint32_t m[4]; uint32_t m[4];
for ( unsigned int i = 0; i < 4; ++i ) for ( uint32_t& digit : m )
m[i] = 0; digit = 0;
IPAddr rval(IPv6, m, IPAddr::Host); IPAddr rval(IPv6, m, IPAddr::Host);
return rval; return rval;
} }

View file

@ -438,9 +438,9 @@ static Attr* find_attr(const std::vector<AttrPtr>* al, AttrTag tag) {
if ( ! al ) if ( ! al )
return nullptr; return nullptr;
for ( size_t i = 0; i < al->size(); ++i ) for ( const auto& attr : *al )
if ( (*al)[i]->Tag() == tag ) if ( attr->Tag() == tag )
return (*al)[i].get(); return attr.get();
return nullptr; return nullptr;
} }

View file

@ -352,8 +352,8 @@ String::Vec* String::VecFromPolicy(VectorVal* vec) {
char* String::VecToString(const Vec* vec) { char* String::VecToString(const Vec* vec) {
std::string result("["); std::string result("[");
for ( String::VecCIt it = vec->begin(); it != vec->end(); ++it ) { for ( const auto* str : *vec ) {
result += (*it)->CheckString(); result += str->CheckString();
result += ","; result += ",";
} }
@ -442,10 +442,7 @@ String* concatenate(String::CVec& v) {
String* concatenate(String::Vec& v) { String* concatenate(String::Vec& v) {
String::CVec cv; String::CVec cv;
std::copy(v.begin(), v.end(), std::back_inserter<String::CVec>(cv));
for ( String::VecIt it = v.begin(); it != v.end(); ++it )
cv.push_back(*it);
return concatenate(cv); return concatenate(cv);
} }

View file

@ -388,8 +388,8 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys
tag_set expected = GetScheduled(conn); tag_set expected = GetScheduled(conn);
for ( tag_set::iterator it = expected.begin(); it != expected.end(); ++it ) { for ( const auto& tag : expected ) {
Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(*it, conn); Analyzer* analyzer = analyzer_mgr->InstantiateAnalyzer(tag, conn);
if ( ! analyzer ) if ( ! analyzer )
continue; continue;
@ -397,9 +397,9 @@ bool Manager::ApplyScheduledAnalyzers(Connection* conn, bool init, packet_analys
parent->AddChildAnalyzer(analyzer, init); parent->AddChildAnalyzer(analyzer, init);
if ( scheduled_analyzer_applied ) 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(); return expected.size();

View file

@ -756,12 +756,11 @@ refine flow DHCP_Flow += {
uint16 i = 0; uint16 i = 0;
for ( auto ptrsubopt = ${v.relay_agent_inf}->begin(); for ( const auto& ptrsubopt : *${v.relay_agent_inf} )
ptrsubopt != ${v.relay_agent_inf}->end(); ++ptrsubopt )
{ {
auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::DHCP::SubOpt); auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::DHCP::SubOpt);
r->Assign(0, (*ptrsubopt)->code()); r->Assign(0, ptrsubopt->code());
r->Assign(1, to_stringval((*ptrsubopt)->value())); r->Assign(1, to_stringval(ptrsubopt->value()));
relay_agent_sub_opt->Assign(i, std::move(r)); relay_agent_sub_opt->Assign(i, std::move(r));
++i; ++i;

View file

@ -699,8 +699,8 @@ bool DNS_Interpreter::ParseRR_EDNS(detail::DNS_MsgInfo* msg, const u_char*& data
bits_left -= 8; bits_left -= 8;
} }
for ( uint8_t i = 0; i < 4; i++ ) { for ( uint32_t& a : addr ) {
addr[i] = htonl(addr[i]); a = htonl(a);
} }
opt.ecs_addr = make_intrusive<AddrVal>(addr); opt.ecs_addr = make_intrusive<AddrVal>(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) { bool DNS_Interpreter::ParseRR_AAAA(detail::DNS_MsgInfo* msg, const u_char*& data, int& len, int rdlength) {
uint32_t addr[4]; 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)); addr[i] = htonl(ExtractLong(data, len));
if ( len < 0 ) { if ( len < 0 ) {

View file

@ -20,8 +20,8 @@ static zeek::RecordValPtr parse_port(const std::string& line)
{ {
good = true; good = true;
for ( int i = 0; i < 6; ++i ) for ( int b : bytes )
if ( bytes[i] < 0 || bytes[i] > 255 ) if ( b < 0 || b > 255 )
{ {
good = false; good = false;
break; break;

View file

@ -125,8 +125,7 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) {
pos = myline.length(); pos = myline.length();
command = myline.substr(0, pos); command = myline.substr(0, pos);
for ( size_t i = 0; i < command.size(); ++i ) command = util::to_upper(command);
command[i] = toupper(command[i]);
// Adjust for the no-parameter case // Adjust for the no-parameter case
if ( pos == myline.length() ) if ( pos == myline.length() )
@ -743,9 +742,8 @@ void IRC_Analyzer::DeliverStream(int length, const u_char* line, bool orig) {
string empty_string = ""; string empty_string = "";
for ( unsigned int i = 0; i < users.size(); ++i ) { for ( auto nick : users ) {
auto info = make_intrusive<RecordVal>(irc_join_info); auto info = make_intrusive<RecordVal>(irc_join_info);
string nick = users[i];
string mode = "none"; string mode = "none";
if ( nick[0] == '@' ) { if ( nick[0] == '@' ) {

View file

@ -37,9 +37,8 @@ zeek::RecordValPtr proc_krb_kdc_req_arguments(KRB_KDC_REQ* msg, const ZeekAnalyz
if ( msg->padata()->has_padata() ) if ( msg->padata()->has_padata() )
rv->Assign(2, proc_padata(msg->padata()->padata()->padata(), zeek_analyzer, false)); 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() ) switch ( element->seq_meta()->index() )
{ {
case 0: case 0:
@ -127,35 +126,35 @@ bool proc_error_arguments(zeek::RecordVal* rv, const std::vector<KRB_ERROR_Arg*>
if ( stime_i ) if ( stime_i )
rv->Assign(3, GetTimeFromAsn1((*args)[stime_i]->args()->stime(), stime_usecs)); 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: 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; break;
case 1: 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; break;
// ctime/stime handled above // ctime/stime handled above
case 7: case 7:
rv->Assign(5, to_stringval((*args)[i]->args()->crealm()->encoding()->content())); rv->Assign(5, to_stringval(arg->args()->crealm()->encoding()->content()));
break; break;
case 8: case 8:
rv->Assign(6, GetStringFromPrincipalName((*args)[i]->args()->cname())); rv->Assign(6, GetStringFromPrincipalName(arg->args()->cname()));
break; break;
case 9: case 9:
rv->Assign(7, to_stringval((*args)[i]->args()->realm()->encoding()->content())); rv->Assign(7, to_stringval(arg->args()->realm()->encoding()->content()));
break; break;
case 10: case 10:
rv->Assign(8, GetStringFromPrincipalName((*args)[i]->args()->sname())); rv->Assign(8, GetStringFromPrincipalName(arg->args()->sname()));
break; break;
case 11: 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; break;
case 12: case 12:
if ( error_code == KDC_ERR_PREAUTH_REQUIRED ) 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; break;
default: default:
break; break;
@ -307,27 +306,15 @@ refine connection KRB_Conn += {
{ {
switch ( ${msg.safe_body.args[i].seq_meta.index} ) 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: case 1:
timestamp_i = i; timestamp_i = i;
break; break;
case 2: case 2:
timestamp_usecs = binary_to_int64(${msg.safe_body.args[i].args.usec.encoding.content}); timestamp_usecs = binary_to_int64(${msg.safe_body.args[i].args.usec.encoding.content});
break; 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: case 3:
rv->Assign(5, asn1_integer_to_val(${msg.safe_body.args[i].args.seq_number}, zeek::TYPE_COUNT)); rv->Assign(5, asn1_integer_to_val(${msg.safe_body.args[i].args.seq_number}, zeek::TYPE_COUNT));
break; break;
@ -341,6 +328,10 @@ refine connection KRB_Conn += {
break; 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)); zeek::BifEvent::enqueue_krb_safe(zeek_analyzer(), zeek_analyzer()->Conn(), ${msg.is_orig}, std::move(rv));
} }
return true; return true;

View file

@ -18,9 +18,8 @@ zeek::VectorValPtr proc_padata(const KRB_PA_Data_Sequence* data, const ZeekAnaly
if ( ! data->data()->has_padata() ) if ( ! data->data()->has_padata() )
return vv; 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(); uint64_t data_type = element->data_type();
if ( is_error && ( data_type == PA_PW_AS_REQ || data_type == PA_PW_AS_REP ) ) if ( is_error && ( data_type == PA_PW_AS_REQ || data_type == PA_PW_AS_REP ) )

View file

@ -30,8 +30,8 @@ zeek::ValPtr GetStringFromPrincipalName(const KRB_Principal_Name* pname)
zeek::VectorValPtr proc_cipher_list(const Array* list) zeek::VectorValPtr proc_cipher_list(const Array* list)
{ {
auto ciphers = zeek::make_intrusive<zeek::VectorVal>(zeek::id::index_vec); auto ciphers = zeek::make_intrusive<zeek::VectorVal>(zeek::id::index_vec);
for ( uint i = 0; i < list->data()->size(); ++i ) for ( const auto& data : *(list->data()) )
ciphers->Assign(ciphers->Size(), asn1_integer_to_val((*list->data())[i], zeek::TYPE_COUNT)); ciphers->Assign(ciphers->Size(), asn1_integer_to_val(data, zeek::TYPE_COUNT));
return ciphers; 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::VectorVal>(zeek::id::find_type<zeek::VectorType>("KRB::Host_Address_Vector")); auto addrs = zeek::make_intrusive<zeek::VectorVal>(zeek::id::find_type<zeek::VectorType>("KRB::Host_Address_Vector"));
for ( uint i = 0; i < list->addresses()->size(); ++i ) for ( const auto& addr : *(list->addresses()) )
{ addrs->Assign(addrs->Size(), proc_host_address(a, addr));
addrs->Assign(addrs->Size(), proc_host_address(a, (*list->addresses())[i]));
}
return addrs; return addrs;
} }
@ -98,11 +96,8 @@ zeek::VectorValPtr proc_tickets(const KRB_Ticket_Sequence* list)
{ {
auto tickets = zeek::make_intrusive<zeek::VectorVal>(zeek::id::find_type<zeek::VectorType>("KRB::Ticket_Vector")); auto tickets = zeek::make_intrusive<zeek::VectorVal>(zeek::id::find_type<zeek::VectorType>("KRB::Ticket_Vector"));
for ( uint i = 0; i < list->tickets()->size(); ++i ) for ( KRB_Ticket* element : *(list->tickets()) )
{
KRB_Ticket* element = (*list->tickets())[i];
tickets->Assign(tickets->Size(), proc_ticket(element)); tickets->Assign(tickets->Size(), proc_ticket(element));
}
return tickets; return tickets;
} }

View file

@ -524,14 +524,14 @@ refine flow ModbusTCP_Flow += {
{ {
auto vect = zeek::make_intrusive<zeek::VectorVal>(zeek::BifType::Vector::ModbusFileRecordRequests); auto vect = zeek::make_intrusive<zeek::VectorVal>(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::RecordVal>(zeek::BifType::Record::ModbusFileRecordRequest); auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::ModbusFileRecordRequest);
r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); r->Assign(0, zeek::val_mgr->Count(${ref.ref_type}));
r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); r->Assign(1, zeek::val_mgr->Count(${ref.file_num}));
r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); r->Assign(2, zeek::val_mgr->Count(${ref.record_num}));
r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_len})); r->Assign(3, zeek::val_mgr->Count(${ref.record_len}));
vect->Append(r); vect->Append(r);
} }
@ -551,13 +551,13 @@ refine flow ModbusTCP_Flow += {
{ {
auto vect = zeek::make_intrusive<zeek::VectorVal>(zeek::BifType::Vector::ModbusFileRecordResponses); auto vect = zeek::make_intrusive<zeek::VectorVal>(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::RecordVal>(zeek::BifType::Record::ModbusFileRecordResponse); auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::ModbusFileRecordResponse);
r->Assign(0, zeek::val_mgr->Count(${message.references[i].file_len})); r->Assign(0, zeek::val_mgr->Count(${ref.file_len}));
r->Assign(1, zeek::val_mgr->Count(${message.references[i].ref_type})); r->Assign(1, zeek::val_mgr->Count(${ref.ref_type}));
r->Assign(2, to_stringval(${message.references[i].record_data})); r->Assign(2, to_stringval(${ref.record_data}));
vect->Append(r); vect->Append(r);
} }
@ -577,14 +577,14 @@ refine flow ModbusTCP_Flow += {
{ {
auto vect = zeek::make_intrusive<zeek::VectorVal>(zeek::BifType::Vector::ModbusFileReferences); auto vect = zeek::make_intrusive<zeek::VectorVal>(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::RecordVal>(zeek::BifType::Record::ModbusFileReference); auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::ModbusFileReference);
r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); r->Assign(0, zeek::val_mgr->Count(${ref.ref_type}));
r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); r->Assign(1, zeek::val_mgr->Count(${ref.file_num}));
r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); r->Assign(2, zeek::val_mgr->Count(${ref.record_num}));
r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); r->Assign(3, zeek::val_mgr->Count(${ref.record_length}));
r->Assign(4, to_stringval(${message.references[i].record_data})); r->Assign(4, to_stringval(${ref.record_data}));
vect->Append(r); vect->Append(r);
} }
@ -604,14 +604,14 @@ refine flow ModbusTCP_Flow += {
{ {
auto vect = zeek::make_intrusive<zeek::VectorVal>(zeek::BifType::Vector::ModbusFileReferences); auto vect = zeek::make_intrusive<zeek::VectorVal>(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::RecordVal>(zeek::BifType::Record::ModbusFileReference); auto r = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::ModbusFileReference);
r->Assign(0, zeek::val_mgr->Count(${message.references[i].ref_type})); r->Assign(0, zeek::val_mgr->Count(${ref.ref_type}));
r->Assign(1, zeek::val_mgr->Count(${message.references[i].file_num})); r->Assign(1, zeek::val_mgr->Count(${ref.file_num}));
r->Assign(2, zeek::val_mgr->Count(${message.references[i].record_num})); r->Assign(2, zeek::val_mgr->Count(${ref.record_num}));
r->Assign(3, zeek::val_mgr->Count(${message.references[i].record_length})); r->Assign(3, zeek::val_mgr->Count(${ref.record_length}));
r->Assign(4, to_stringval(${message.references[i].record_data})); r->Assign(4, to_stringval(${ref.record_data}));
vect->Append(r); vect->Append(r);
} }

View file

@ -784,8 +784,7 @@ int POP3_Analyzer::ParseCmd(std::string cmd) {
if ( c == '+' || c == '-' ) if ( c == '+' || c == '-' )
cmd = cmd.substr(1); cmd = cmd.substr(1);
for ( size_t i = 0; i < cmd.size(); ++i ) cmd = util::to_upper(cmd);
cmd[i] = toupper(cmd[i]);
if ( ! cmd.compare(pop3_cmd_word[code]) ) if ( ! cmd.compare(pop3_cmd_word[code]) )
return code; return code;

View file

@ -12,17 +12,17 @@ refine flow RADIUS_Flow += {
result->Assign(1, ${msg.trans_id}); result->Assign(1, ${msg.trans_id});
result->Assign(2, to_stringval(${msg.authenticator})); result->Assign(2, to_stringval(${msg.authenticator}));
if ( ${msg.attributes}->size() ) if ( ! ${msg.attributes}->empty() )
{ {
auto attributes = zeek::make_intrusive<zeek::TableVal>(zeek::BifType::Table::RADIUS::Attributes); auto attributes = zeek::make_intrusive<zeek::TableVal>(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? // Do we already have a vector of attributes for this type?
auto current = attributes->FindOrDefault(index); auto current = attributes->FindOrDefault(index);
zeek::ValPtr val = to_stringval(${msg.attributes[i].value}); zeek::ValPtr val = to_stringval(${attr.value});
if ( current ) if ( current )
{ {

View file

@ -132,28 +132,28 @@ refine flow RDP_Flow += {
if ( ! rdp_client_network_data ) if ( ! rdp_client_network_data )
return false; return false;
if ( ${cnetwork.channel_def_array}->size() ) if ( ! ${cnetwork.channel_def_array}->empty() )
{ {
auto channels = zeek::make_intrusive<zeek::VectorVal>(zeek::BifType::Vector::RDP::ClientChannelList); auto channels = zeek::make_intrusive<zeek::VectorVal>(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::RecordVal>(zeek::BifType::Record::RDP::ClientChannelDef); auto channel_def = zeek::make_intrusive<zeek::RecordVal>(zeek::BifType::Record::RDP::ClientChannelDef);
channel_def->Assign(0, to_stringval(${cnetwork.channel_def_array[i].name})); channel_def->Assign(0, to_stringval(${cdef.name}));
channel_def->Assign(1, ${cnetwork.channel_def_array[i].options}); channel_def->Assign(1, ${cdef.options});
channel_def->Assign(2, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_INITIALIZED}); channel_def->Assign(2, ${cdef.CHANNEL_OPTION_INITIALIZED});
channel_def->Assign(3, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_RDP}); channel_def->Assign(3, ${cdef.CHANNEL_OPTION_ENCRYPT_RDP});
channel_def->Assign(4, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_SC}); channel_def->Assign(4, ${cdef.CHANNEL_OPTION_ENCRYPT_SC});
channel_def->Assign(5, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_ENCRYPT_CS}); channel_def->Assign(5, ${cdef.CHANNEL_OPTION_ENCRYPT_CS});
channel_def->Assign(6, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_HIGH}); channel_def->Assign(6, ${cdef.CHANNEL_OPTION_PRI_HIGH});
channel_def->Assign(7, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_MED}); channel_def->Assign(7, ${cdef.CHANNEL_OPTION_PRI_MED});
channel_def->Assign(8, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_PRI_LOW}); channel_def->Assign(8, ${cdef.CHANNEL_OPTION_PRI_LOW});
channel_def->Assign(9, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS_RDP}); channel_def->Assign(9, ${cdef.CHANNEL_OPTION_COMPRESS_RDP});
channel_def->Assign(10, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_COMPRESS}); channel_def->Assign(10, ${cdef.CHANNEL_OPTION_COMPRESS});
channel_def->Assign(11, ${cnetwork.channel_def_array[i].CHANNEL_OPTION_SHOW_PROTOCOL}); channel_def->Assign(11, ${cdef.CHANNEL_OPTION_SHOW_PROTOCOL});
channel_def->Assign(12, ${cnetwork.channel_def_array[i].REMOTE_CONTROL_PERSISTENT}); channel_def->Assign(12, ${cdef.REMOTE_CONTROL_PERSISTENT});
channels->Assign(channels->Size(), std::move(channel_def)); channels->Assign(channels->Size(), std::move(channel_def));
} }

View file

@ -530,15 +530,15 @@ struct type_checker {
else { else {
indices_to_check.reserve(indices->size()); indices_to_check.reserve(indices->size());
for ( size_t i = 0; i < indices->size(); ++i ) for ( const auto& idx : *indices )
indices_to_check.emplace_back(&(*indices)[i]); indices_to_check.emplace_back(&idx);
} }
} }
else { else {
indices_to_check.reserve(indices->size()); indices_to_check.reserve(indices->size());
for ( size_t i = 0; i < indices->size(); ++i ) for ( const auto& idx : *indices )
indices_to_check.emplace_back(&(*indices)[i]); indices_to_check.emplace_back(&idx);
} }
} }
else else
@ -580,15 +580,15 @@ struct type_checker {
else { else {
indices_to_check.reserve(indices->size()); indices_to_check.reserve(indices->size());
for ( size_t i = 0; i < indices->size(); ++i ) for ( const auto& idx : *indices )
indices_to_check.emplace_back(&(*indices)[i]); indices_to_check.emplace_back(&idx);
} }
} }
else { else {
indices_to_check.reserve(indices->size()); indices_to_check.reserve(indices->size());
for ( size_t i = 0; i < indices->size(); ++i ) for ( const auto& idx : *indices )
indices_to_check.emplace_back(&(*indices)[i]); indices_to_check.emplace_back(&idx);
} }
} }
else else

View file

@ -24,8 +24,8 @@ Manager::Manager()
max_files(0) {} max_files(0) {}
Manager::~Manager() { Manager::~Manager() {
for ( MIMEMap::iterator i = mime_types.begin(); i != mime_types.end(); i++ ) for ( const auto& [_, tag] : mime_types )
delete i->second; delete tag;
// Have to assume that too much of Zeek has been shutdown by this point // Have to assume that too much of Zeek has been shutdown by this point
// to do anything more than reclaim memory. // 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<RecordType>("mime_match"); static auto mime_match = id::find_type<RecordType>("mime_match");
auto rval = make_intrusive<VectorVal>(mime_matches); auto rval = make_intrusive<VectorVal>(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<RecordVal>(mime_match); auto element = make_intrusive<RecordVal>(mime_match);
for ( set<string>::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2 ) { for ( const string& match_str : match ) {
element->Assign(0, it->first); element->Assign(0, index);
element->Assign(1, *it2); element->Assign(1, match_str);
} }
rval->Assign(rval->Size(), std::move(element)); rval->Assign(rval->Size(), std::move(element));

View file

@ -169,9 +169,9 @@ Manager::Manager() : plugin::ComponentManager<input::Component>("Input", "Reader
} }
Manager::~Manager() { Manager::~Manager() {
for ( map<ReaderFrontend*, Stream*>::iterator s = readers.begin(); s != readers.end(); ++s ) { for ( auto& [frontend, stream] : readers ) {
delete s->second; delete stream;
delete s->first; delete frontend;
} }
} }
@ -1439,8 +1439,8 @@ int Manager::SendEventStreamEvent(Stream* i, EnumVal* type, const Value* const*
if ( convert_error ) { if ( convert_error ) {
// we have an error somewhere in our out_vals. Just delete all of them. // we have an error somewhere in our out_vals. Just delete all of them.
for ( list<Val*>::const_iterator it = out_vals.begin(), end = out_vals.end(); it != end; ++it ) for ( auto* val : out_vals )
Unref(*it); Unref(val);
} }
else else
SendEvent(stream->event, out_vals); SendEvent(stream->event, out_vals);
@ -1712,8 +1712,8 @@ void Manager::SendEvent(EventHandlerPtr ev, list<Val*> events) const {
DBG_LOG(DBG_INPUT, "SendEvent with %" PRIuPTR " vals (list)", events.size()); DBG_LOG(DBG_INPUT, "SendEvent with %" PRIuPTR " vals (list)", events.size());
#endif #endif
for ( list<Val*>::iterator i = events.begin(); i != events.end(); i++ ) for ( auto* val : events )
vl.emplace_back(AdoptRef{}, *i); vl.emplace_back(AdoptRef{}, val);
if ( ev ) if ( ev )
event_mgr.Enqueue(ev, std::move(vl), util::detail::SOURCE_LOCAL); 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 { Manager::Stream* Manager::FindStream(const string& name) const {
for ( auto s = readers.begin(); s != readers.end(); ++s ) { for ( const auto& [_, stream] : readers ) {
if ( (*s).second->name == name ) if ( stream->name == name )
return (*s).second; return stream;
} }
return nullptr; return nullptr;
@ -2186,12 +2186,12 @@ Manager::Stream* Manager::FindStream(ReaderFrontend* reader) const {
// Function is called on Zeek shutdown. // Function is called on Zeek shutdown.
// Signal all frontends that they will cease operation. // Signal all frontends that they will cease operation.
void Manager::Terminate() { void Manager::Terminate() {
for ( map<ReaderFrontend*, Stream*>::iterator i = readers.begin(); i != readers.end(); ++i ) { for ( const auto& [_, stream] : readers ) {
if ( i->second->removed ) if ( stream->removed )
continue; continue;
i->second->removed = true; stream->removed = true;
i->second->reader->Stop(); stream->reader->Stop();
} }
} }

View file

@ -23,8 +23,8 @@ PktSrcComponent::PktSrcComponent(const std::string& arg_name, const std::string&
const std::vector<std::string>& PktSrcComponent::Prefixes() const { return prefixes; } const std::vector<std::string>& PktSrcComponent::Prefixes() const { return prefixes; }
bool PktSrcComponent::HandlesPrefix(const std::string& prefix) const { bool PktSrcComponent::HandlesPrefix(const std::string& prefix) const {
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { for ( const auto& pfx : prefixes ) {
if ( *i == prefix ) if ( pfx == prefix )
return true; return true;
} }
@ -42,11 +42,11 @@ void PktSrcComponent::DoDescribe(ODesc* d) const {
std::string prefs; std::string prefs;
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { for ( const auto& pfx : prefixes ) {
if ( prefs.size() ) if ( prefs.size() )
prefs += ", "; prefs += ", ";
prefs += '"' + *i + '"'; prefs += '"' + pfx + '"';
} }
d->Add("interface prefix"); d->Add("interface prefix");
@ -80,8 +80,8 @@ PktDumperComponent::factory_callback PktDumperComponent::Factory() const { retur
const std::vector<std::string>& PktDumperComponent::Prefixes() const { return prefixes; } const std::vector<std::string>& PktDumperComponent::Prefixes() const { return prefixes; }
bool PktDumperComponent::HandlesPrefix(const std::string& prefix) const { bool PktDumperComponent::HandlesPrefix(const std::string& prefix) const {
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { for ( const auto& pfx : prefixes ) {
if ( *i == prefix ) if ( pfx == prefix )
return true; return true;
} }
@ -93,11 +93,11 @@ void PktDumperComponent::DoDescribe(ODesc* d) const {
std::string prefs; std::string prefs;
for ( std::vector<std::string>::const_iterator i = prefixes.begin(); i != prefixes.end(); i++ ) { for ( const auto& pfx : prefixes ) {
if ( prefs.size() ) if ( prefs.size() )
prefs += ", "; prefs += ", ";
prefs += '"' + *i + '"'; prefs += '"' + pfx + '"';
} }
d->Add("dumper prefix"); d->Add("dumper prefix");

View file

@ -64,9 +64,9 @@ Manager::~Manager() {
sources.clear(); sources.clear();
for ( PktDumperList::iterator i = pkt_dumpers.begin(); i != pkt_dumpers.end(); ++i ) { for ( PktDumper* dumper : pkt_dumpers ) {
(*i)->Done(); dumper->Done();
delete *i; delete dumper;
} }
pkt_dumpers.clear(); pkt_dumpers.clear();

View file

@ -351,9 +351,7 @@ Manager::Filter::~Filter() {
Manager::Stream::~Stream() { Manager::Stream::~Stream() {
Unref(columns); Unref(columns);
for ( WriterMap::iterator i = writers.begin(); i != writers.end(); i++ ) { for ( auto& [_, winfo] : writers ) {
WriterInfo* winfo = i->second;
if ( winfo->rotation_timer ) if ( winfo->rotation_timer )
zeek::detail::timer_mgr->Cancel(winfo->rotation_timer); zeek::detail::timer_mgr->Cancel(winfo->rotation_timer);
@ -363,8 +361,8 @@ Manager::Stream::~Stream() {
delete winfo; delete winfo;
} }
for ( list<Filter*>::iterator f = filters.begin(); f != filters.end(); ++f ) for ( Filter* f : filters )
delete *f; delete f;
if ( delay_timer ) if ( delay_timer )
zeek::detail::timer_mgr->Cancel(delay_timer); zeek::detail::timer_mgr->Cancel(delay_timer);
@ -491,8 +489,8 @@ Manager::Manager()
} }
Manager::~Manager() { Manager::~Manager() {
for ( vector<Stream*>::iterator s = streams.begin(); s != streams.end(); ++s ) for ( Stream* s : streams )
delete *s; delete s;
} }
void Manager::InitPostScript() { void Manager::InitPostScript() {
@ -524,13 +522,11 @@ Manager::Stream* Manager::FindStream(EnumVal* id) {
} }
Manager::WriterInfo* Manager::FindWriter(WriterFrontend* writer) { Manager::WriterInfo* Manager::FindWriter(WriterFrontend* writer) {
for ( vector<Stream*>::iterator s = streams.begin(); s != streams.end(); ++s ) { for ( Stream* s : streams ) {
if ( ! *s ) if ( ! s )
continue; continue;
for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) { for ( const auto& [_, winfo] : s->writers ) {
WriterInfo* winfo = i->second;
if ( winfo->writer == writer ) if ( winfo->writer == writer )
return winfo; return winfo;
} }
@ -563,16 +559,16 @@ bool Manager::CheckFilterWriterConflict(const WriterInfo* winfo, const Filter* f
void Manager::RemoveDisabledWriters(Stream* stream) { void Manager::RemoveDisabledWriters(Stream* stream) {
list<Stream::WriterPathPair> disabled; list<Stream::WriterPathPair> disabled;
for ( Stream::WriterMap::iterator j = stream->writers.begin(); j != stream->writers.end(); j++ ) { for ( const auto& [index, winfo] : stream->writers ) {
if ( j->second->writer->Disabled() ) { if ( winfo->writer->Disabled() ) {
j->second->writer->Stop(); winfo->writer->Stop();
delete j->second; delete winfo;
disabled.push_back(j->first); disabled.push_back(index);
} }
} }
for ( list<Stream::WriterPathPair>::iterator j = disabled.begin(); j != disabled.end(); j++ ) for ( const auto& index : disabled )
stream->writers.erase(*j); stream->writers.erase(index);
} }
bool Manager::CreateStream(EnumVal* id, RecordVal* sval) { bool Manager::CreateStream(EnumVal* id, RecordVal* sval) {
@ -681,9 +677,7 @@ bool Manager::RemoveStream(unsigned int idx) {
if ( ! stream ) if ( ! stream )
return false; return false;
for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { for ( const auto& [_, winfo] : stream->writers ) {
WriterInfo* winfo = i->second;
DBG_LOG(DBG_LOGGING, "Removed writer '%s' from stream '%s'", winfo->writer->Name(), stream->name.c_str()); DBG_LOG(DBG_LOGGING, "Removed writer '%s' from stream '%s'", winfo->writer->Name(), stream->name.c_str());
winfo->writer->Stop(); winfo->writer->Stop();
@ -1550,9 +1544,9 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte
// potentially be nested inside other records. // potentially be nested inside other records.
list<int>& indices = filter->indices[i]; list<int>& indices = filter->indices[i];
for ( list<int>::iterator j = indices.begin(); j != indices.end(); ++j ) { for ( int index : indices ) {
auto vr = val->AsRecord(); auto vr = val->AsRecord();
val = vr->RawOptField(*j); val = vr->RawOptField(index);
if ( ! val ) { if ( ! val ) {
// Value, or any of its parents, is not set. // Value, or any of its parents, is not set.
@ -1560,7 +1554,7 @@ detail::LogRecord Manager::RecordToLogRecord(const Stream* stream, Filter* filte
break; break;
} }
vt = cast_intrusive<RecordType>(vr->GetType())->GetFieldType(*j).get(); vt = cast_intrusive<RecordType>(vr->GetType())->GetFieldType(index).get();
} }
if ( val ) if ( val )
@ -1856,21 +1850,19 @@ bool Manager::WriteFromRemote(EnumVal* id, EnumVal* writer, const string& path,
void Manager::SendAllWritersTo(const broker::endpoint_info& ei) { void Manager::SendAllWritersTo(const broker::endpoint_info& ei) {
auto et = id::find_type("Log::Writer")->AsEnumType(); auto et = id::find_type("Log::Writer")->AsEnumType();
for ( vector<Stream*>::iterator s = streams.begin(); s != streams.end(); ++s ) { for ( Stream* stream : streams ) {
Stream* stream = (*s);
if ( ! (stream && stream->enable_remote) ) if ( ! (stream && stream->enable_remote) )
continue; continue;
for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) { for ( const auto& [index, winfo] : stream->writers ) {
WriterFrontend* writer = i->second->writer; WriterFrontend* writer = winfo->writer;
const auto& writer_val = et->GetEnumVal(i->first.first); const auto& writer_val = et->GetEnumVal(index.first);
std::vector<const threading::Field*> fields(writer->GetFields().size()); std::vector<const threading::Field*> fields(writer->GetFields().size());
for ( size_t i = 0; i < writer->GetFields().size(); i++ ) for ( size_t i = 0; i < writer->GetFields().size(); i++ )
fields[i] = &writer->GetFields()[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); ei);
} }
} }
@ -1881,8 +1873,8 @@ bool Manager::SetBuf(EnumVal* id, bool enabled) {
if ( ! stream ) if ( ! stream )
return false; return false;
for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) for ( const auto& [_, winfo] : stream->writers )
i->second->writer->SetBuf(enabled); winfo->writer->SetBuf(enabled);
RemoveDisabledWriters(stream); RemoveDisabledWriters(stream);
@ -1897,8 +1889,8 @@ bool Manager::Flush(EnumVal* id) {
if ( ! stream->enabled ) if ( ! stream->enabled )
return true; return true;
for ( Stream::WriterMap::iterator i = stream->writers.begin(); i != stream->writers.end(); i++ ) for ( const auto& [_, winfo] : stream->writers )
i->second->writer->Flush(run_state::network_time); winfo->writer->Flush(run_state::network_time);
RemoveDisabledWriters(stream); RemoveDisabledWriters(stream);
@ -1906,12 +1898,12 @@ bool Manager::Flush(EnumVal* id) {
} }
void Manager::Terminate() { void Manager::Terminate() {
for ( vector<Stream*>::iterator s = streams.begin(); s != streams.end(); ++s ) { for ( Stream* s : streams ) {
if ( ! *s ) if ( ! s )
continue; continue;
for ( Stream::WriterMap::iterator i = (*s)->writers.begin(); i != (*s)->writers.end(); i++ ) for ( const auto& [_, winfo] : s->writers )
i->second->writer->Stop(); winfo->writer->Stop();
} }
} }

View file

@ -61,8 +61,8 @@ public:
broker::data WriterBackend::WriterInfo::ToBroker() const { broker::data WriterBackend::WriterInfo::ToBroker() const {
auto t = broker::table(); auto t = broker::table();
for ( config_map::const_iterator i = config.begin(); i != config.end(); ++i ) { for ( const auto& [key, value] : config ) {
t.emplace(std::string{i->first}, std::string{i->second}); t.emplace(std::string{key}, std::string{value});
} }
auto bppf = post_proc_func ? post_proc_func : ""; auto bppf = post_proc_func ? post_proc_func : "";
@ -185,12 +185,12 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span<detail::LogRecord> reco
} }
// Double-check all the types match. // 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 ) { 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 #ifdef DEBUG
const char* msg = Fmt("Field #%d type doesn't match in WriterBackend::Write() (%d vs. %d)", i, 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); Debug(DBG_LOGGING, msg);
#endif #endif
DisableFrontend(); DisableFrontend();
@ -212,10 +212,9 @@ bool WriterBackend::Write(int arg_num_fields, zeek::Span<detail::LogRecord> reco
std::vector<Value*> valps; std::vector<Value*> valps;
valps.reserve(num_fields); valps.reserve(num_fields);
for ( size_t j = 0; j < records.size(); j++ ) { for ( auto& record : records ) {
auto& write_vals = records[j];
for ( int f = 0; f < num_fields; f++ ) 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]); success = DoWrite(num_fields, fields, &valps[0]);

View file

@ -255,11 +255,11 @@ bool Ascii::InitFilterOptions() {
const WriterInfo& info = Info(); const WriterInfo& info = Info();
// Set per-filter configuration options. // Set per-filter configuration options.
for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); ++i ) { for ( const auto& [key, value] : info.config ) {
if ( strcmp(i->first, "tsv") == 0 ) { if ( strcmp(key, "tsv") == 0 ) {
if ( strcmp(i->second, "T") == 0 ) if ( strcmp(value, "T") == 0 )
tsv = true; tsv = true;
else if ( strcmp(i->second, "F") == 0 ) else if ( strcmp(value, "F") == 0 )
tsv = false; tsv = false;
else { else {
Error("invalid value for 'tsv', must be a string and either \"T\" or \"F\""); 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 ) { else if ( strcmp(key, "gzip_level") == 0 ) {
gzip_level = atoi(i->second); gzip_level = atoi(value);
if ( gzip_level < 0 || gzip_level > 9 ) { if ( gzip_level < 0 || gzip_level > 9 ) {
Error("invalid value for 'gzip_level', must be a number between 0 and 9."); Error("invalid value for 'gzip_level', must be a number between 0 and 9.");
return false; return false;
} }
} }
else if ( strcmp(i->first, "use_json") == 0 ) { else if ( strcmp(key, "use_json") == 0 ) {
if ( strcmp(i->second, "T") == 0 ) if ( strcmp(value, "T") == 0 )
use_json = true; use_json = true;
else if ( strcmp(i->second, "F") == 0 ) else if ( strcmp(value, "F") == 0 )
use_json = false; use_json = false;
else { else {
Error("invalid value for 'use_json', must be a string and either \"T\" or \"F\""); 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 ) { else if ( strcmp(key, "enable_utf_8") == 0 ) {
if ( strcmp(i->second, "T") == 0 ) if ( strcmp(value, "T") == 0 )
enable_utf_8 = true; enable_utf_8 = true;
else if ( strcmp(i->second, "F") == 0 ) else if ( strcmp(value, "F") == 0 )
enable_utf_8 = false; enable_utf_8 = false;
else { else {
Error("invalid value for 'enable_utf_8', must be a string and either \"T\" or \"F\""); 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 ) { else if ( strcmp(key, "output_to_stdout") == 0 ) {
if ( strcmp(i->second, "T") == 0 ) if ( strcmp(value, "T") == 0 )
output_to_stdout = true; output_to_stdout = true;
else if ( strcmp(i->second, "F") == 0 ) else if ( strcmp(value, "F") == 0 )
output_to_stdout = false; output_to_stdout = false;
else { else {
Error( Error(
@ -310,28 +310,28 @@ bool Ascii::InitFilterOptions() {
} }
} }
else if ( strcmp(i->first, "separator") == 0 ) else if ( strcmp(key, "separator") == 0 )
separator.assign(i->second); separator.assign(value);
else if ( strcmp(i->first, "set_separator") == 0 ) else if ( strcmp(key, "set_separator") == 0 )
set_separator.assign(i->second); set_separator.assign(value);
else if ( strcmp(i->first, "empty_field") == 0 ) else if ( strcmp(key, "empty_field") == 0 )
empty_field.assign(i->second); empty_field.assign(value);
else if ( strcmp(i->first, "unset_field") == 0 ) else if ( strcmp(key, "unset_field") == 0 )
unset_field.assign(i->second); unset_field.assign(value);
else if ( strcmp(i->first, "meta_prefix") == 0 ) else if ( strcmp(key, "meta_prefix") == 0 )
meta_prefix.assign(i->second); meta_prefix.assign(value);
else if ( strcmp(i->first, "json_timestamps") == 0 ) else if ( strcmp(key, "json_timestamps") == 0 )
json_timestamps.assign(i->second); json_timestamps.assign(value);
else if ( strcmp(i->first, "json_include_unset_fields") == 0 ) { else if ( strcmp(key, "json_include_unset_fields") == 0 ) {
if ( strcmp(i->second, "T") == 0 ) if ( strcmp(value, "T") == 0 )
json_include_unset_fields = true; json_include_unset_fields = true;
else if ( strcmp(i->second, "F") == 0 ) else if ( strcmp(value, "F") == 0 )
json_include_unset_fields = false; json_include_unset_fields = false;
else { else {
Error( Error(
@ -341,8 +341,8 @@ bool Ascii::InitFilterOptions() {
} }
} }
else if ( strcmp(i->first, "gzip_file_extension") == 0 ) else if ( strcmp(key, "gzip_file_extension") == 0 )
gzip_file_extension.assign(i->second); gzip_file_extension.assign(value);
} }
if ( ! InitFormatter() ) if ( ! InitFormatter() )

View file

@ -20,13 +20,13 @@ bool None::DoInit(const WriterInfo& info, int num_fields, const threading::Field
std::vector<std::pair<std::string, std::string>> keys; std::vector<std::pair<std::string, std::string>> keys;
for ( WriterInfo::config_map::const_iterator i = info.config.begin(); i != info.config.end(); i++ ) for ( const auto& [key, value] : info.config )
keys.emplace_back(i->first, i->second); keys.emplace_back(key, value);
std::sort(keys.begin(), keys.end()); std::sort(keys.begin(), keys.end());
for ( std::vector<std::pair<std::string, std::string>>::const_iterator i = keys.begin(); i != keys.end(); i++ ) for ( const auto& [key, value] : keys )
std::cout << " config[" << (*i).first << "] = " << (*i).second << "\n"; std::cout << " config[" << key << "] = " << value << "\n";
for ( int i = 0; i < num_fields; i++ ) { for ( int i = 0; i < num_fields; i++ ) {
const threading::Field* field = fields[i]; const threading::Field* field = fields[i];

View file

@ -244,10 +244,8 @@ void CreatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G
bool second_nsapi = false; bool second_nsapi = false;
bool second_gsn_addr = 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_IMSI: case GTPv1::TYPE_IMSI:
rv->Assign(0, BuildIMSI(ie)); 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)); rv->Assign(21, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -342,10 +340,8 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const
bool second_gsn_addr = 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_CAUSE: case GTPv1::TYPE_CAUSE:
rv->Assign(0, BuildCause(ie)); rv->Assign(0, BuildCause(ie));
@ -390,7 +386,7 @@ void CreatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const
rv->Assign(12, BuildPrivateExt(ie)); rv->Assign(12, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }
@ -410,10 +406,8 @@ void UpdatePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const G
bool second_gsn_addr = 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_IMSI: case GTPv1::TYPE_IMSI:
rv->Assign(0, BuildIMSI(ie)); 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)); rv->Assign(15, BuildEndUserAddr(ie));
break; break;
default: 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; break;
} }
} }
@ -487,10 +481,8 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const
bool second_gsn_addr = 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_CAUSE: case GTPv1::TYPE_CAUSE:
rv->Assign(0, BuildCause(ie)); rv->Assign(0, BuildCause(ie));
@ -526,7 +518,7 @@ void UpdatePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const
rv->Assign(9, BuildPrivateExt(ie)); rv->Assign(9, BuildPrivateExt(ie));
break; break;
default: 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; 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) void DeletePDP_Request(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu)
{ {
if ( ! ::gtpv1_delete_pdp_ctx_request ) if ( ! ::gtpv1_delete_pdp_ctx_request )
return; return;
auto rv = zeek::make_intrusive<zeek::RecordVal>( auto rv = zeek::make_intrusive<zeek::RecordVal>(
zeek::BifType::Record::gtp_delete_pdp_ctx_request_elements); zeek::BifType::Record::gtp_delete_pdp_ctx_request_elements);
const vector<InformationElement *> * v = pdu->delete_pdp_ctx_request(); const vector<InformationElement *> * 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_TEARDOWN_IND: case GTPv1::TYPE_TEARDOWN_IND:
rv->Assign(0, BuildTeardownInd(ie)); 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)); rv->Assign(2, BuildPrivateExt(ie));
break; break;
default: 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; 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) void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const GTPv1_Header* pdu)
{ {
if ( ! ::gtpv1_delete_pdp_ctx_response ) if ( ! ::gtpv1_delete_pdp_ctx_response )
return; return;
auto rv = zeek::make_intrusive<zeek::RecordVal>( auto rv = zeek::make_intrusive<zeek::RecordVal>(
zeek::BifType::Record::gtp_delete_pdp_ctx_response_elements); zeek::BifType::Record::gtp_delete_pdp_ctx_response_elements);
const vector<InformationElement *> * v = pdu->delete_pdp_ctx_response(); const vector<InformationElement *> * 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() ) { switch ( ie->type() ) {
case GTPv1::TYPE_CAUSE: case GTPv1::TYPE_CAUSE:
rv->Assign(0, BuildCause(ie)); rv->Assign(0, BuildCause(ie));
@ -589,7 +577,7 @@ void DeletePDP_Response(const ZeekPacketAnalyzer& a, zeek::Connection* c, const
rv->Assign(1, BuildPrivateExt(ie)); rv->Assign(1, BuildPrivateExt(ie));
break; break;
default: 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; break;
} }
} }

View file

@ -7,7 +7,7 @@
namespace zeek::packet_analysis::TCP { namespace zeek::packet_analysis::TCP {
TCPStateStats::TCPStateStats() { 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 ) for ( int j = 0; j < analyzer::tcp::TCP_ENDPOINT_RESET + 1; ++j )
state_cnt[i][j] = 0; state_cnt[i][j] = 0;
} }

View file

@ -440,9 +440,8 @@ void Manager::ExtendZeekPathForPlugins() {
void Manager::InitPreScript() { void Manager::InitPreScript() {
assert(! init); assert(! init);
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) {
i != Manager::ActivePluginsInternal()->end(); i++ ) { plugin->DoConfigure();
(*i)->DoConfigure();
} }
// Sort plugins by name to make sure we have a deterministic order. // Sort plugins by name to make sure we have a deterministic order.
@ -452,10 +451,9 @@ void Manager::InitPreScript() {
// order. // order.
ActivePluginsInternal()->sort(plugin_cmp); ActivePluginsInternal()->sort(plugin_cmp);
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) {
i != Manager::ActivePluginsInternal()->end(); i++ ) { plugin->InitializeComponents();
(*i)->InitializeComponents(); plugin->InitPreScript();
(*i)->InitPreScript();
} }
init = true; init = true;
@ -464,13 +462,12 @@ void Manager::InitPreScript() {
void Manager::InitBifs() { void Manager::InitBifs() {
bif_init_func_map* bifs = BifFilesInternal(); bif_init_func_map* bifs = BifFilesInternal();
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() ) {
i != Manager::ActivePluginsInternal()->end(); i++ ) { bif_init_func_map::const_iterator b = bifs->find(util::strtolower(plugin->Name()));
bif_init_func_map::const_iterator b = bifs->find(util::strtolower((*i)->Name()));
if ( b != bifs->end() ) { if ( b != bifs->end() ) {
for ( bif_init_func_list::const_iterator j = b->second->begin(); j != b->second->end(); ++j ) for ( const auto& func : *(b->second) )
(**j)(*i); func(plugin);
} }
} }
} }
@ -478,25 +475,22 @@ void Manager::InitBifs() {
void Manager::InitPostScript() { void Manager::InitPostScript() {
assert(init); assert(init);
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() )
i != Manager::ActivePluginsInternal()->end(); i++ ) plugin->InitPostScript();
(*i)->InitPostScript();
} }
void Manager::InitPreExecution() { void Manager::InitPreExecution() {
assert(init); assert(init);
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() )
i != Manager::ActivePluginsInternal()->end(); i++ ) plugin->InitPreExecution();
(*i)->InitPreExecution();
} }
void Manager::FinishPlugins() { void Manager::FinishPlugins() {
assert(init); assert(init);
for ( plugin_list::iterator i = Manager::ActivePluginsInternal()->begin(); for ( Plugin* plugin : *Manager::ActivePluginsInternal() )
i != Manager::ActivePluginsInternal()->end(); i++ ) plugin->Done();
(*i)->Done();
Manager::ActivePluginsInternal()->clear(); Manager::ActivePluginsInternal()->clear();
@ -510,18 +504,18 @@ Manager::inactive_plugin_list Manager::InactivePlugins() const {
inactive_plugin_list inactives; 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; bool found = false;
for ( plugin_list::const_iterator j = all->begin(); j != all->end(); j++ ) { for ( Plugin* plugin : *all ) {
if ( (*i).first == util::strtolower((*j)->Name()) ) { if ( index == util::strtolower(plugin->Name()) ) {
found = true; found = true;
break; break;
} }
} }
if ( ! found ) if ( ! found )
inactives.emplace_back(*i); inactives.emplace_back(index, plugin);
} }
return inactives; return inactives;
@ -595,9 +589,9 @@ void Manager::EnableHook(HookType hook, Plugin* plugin, int prio) {
hook_list* l = hooks[hook]; 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. // Already enabled for this plugin.
if ( (*i).second == plugin ) if ( hook_plugin == plugin )
return; return;
} }
@ -646,9 +640,7 @@ int Manager::HookLoadFile(const Plugin::LoadType type, const string& file, const
int rc = -1; int rc = -1;
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
rc = p->HookLoadFile(type, file, resolved); rc = p->HookLoadFile(type, file, resolved);
if ( rc >= 0 ) if ( rc >= 0 )
@ -677,9 +669,7 @@ std::pair<int, std::optional<std::string>> Manager::HookLoadFileExtended(const P
std::pair<int, std::optional<std::string>> rc = {-1, std::nullopt}; std::pair<int, std::optional<std::string>> rc = {-1, std::nullopt};
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
rc = p->HookLoadFileExtended(type, file, resolved); rc = p->HookLoadFileExtended(type, file, resolved);
if ( rc.first >= 0 ) if ( rc.first >= 0 )
@ -713,9 +703,7 @@ std::pair<bool, ValPtr> Manager::HookCallFunction(const Func* func, zeek::detail
std::pair<bool, ValPtr> rval{false, nullptr}; std::pair<bool, ValPtr> rval{false, nullptr};
if ( l ) { if ( l ) {
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
rval = p->HookFunctionCall(func, parent, vecargs); rval = p->HookFunctionCall(func, parent, vecargs);
if ( rval.first ) if ( rval.first )
@ -742,9 +730,7 @@ bool Manager::HookQueueEvent(Event* event) const {
bool result = false; bool result = false;
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
if ( p->HookQueueEvent(event) ) { if ( p->HookQueueEvent(event) ) {
result = true; result = true;
break; break;
@ -766,8 +752,7 @@ void Manager::HookDrainEvents() const {
hook_list* l = hooks[HOOK_DRAIN_EVENTS]; hook_list* l = hooks[HOOK_DRAIN_EVENTS];
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookDrainEvents(); p->HookDrainEvents();
} }
@ -786,8 +771,7 @@ void Manager::HookSetupAnalyzerTree(Connection* conn) const {
hook_list* l = hooks[HOOK_SETUP_ANALYZER_TREE]; hook_list* l = hooks[HOOK_SETUP_ANALYZER_TREE];
if ( l ) { if ( l ) {
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookSetupAnalyzerTree(conn); p->HookSetupAnalyzerTree(conn);
} }
} }
@ -808,8 +792,7 @@ void Manager::HookUpdateNetworkTime(double network_time) const {
hook_list* l = hooks[HOOK_UPDATE_NETWORK_TIME]; hook_list* l = hooks[HOOK_UPDATE_NETWORK_TIME];
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookUpdateNetworkTime(network_time); p->HookUpdateNetworkTime(network_time);
} }
@ -828,8 +811,7 @@ void Manager::HookObjDtor(void* obj) const {
hook_list* l = hooks[HOOK_OBJ_DTOR]; hook_list* l = hooks[HOOK_OBJ_DTOR];
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookObjDtor(obj); 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]; hook_list* l = hooks[HOOK_LOG_INIT];
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookLogInit(writer, instantiating_filter, local, remote, info, num_fields, fields); 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; bool result = true;
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
if ( ! p->HookLogWrite(writer, filter, info, num_fields, fields, vals) ) { if ( ! p->HookLogWrite(writer, filter, info, num_fields, fields, vals) ) {
result = false; result = false;
break; break;
@ -924,9 +903,7 @@ bool Manager::HookReporter(const std::string& prefix, const EventHandlerPtr even
bool result = true; bool result = true;
if ( l ) { if ( l ) {
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
if ( ! p->HookReporter(prefix, event, conn, addl, location, location1, location2, time, message) ) { if ( ! p->HookReporter(prefix, event, conn, addl, location, location1, location2, time, message) ) {
result = false; result = false;
break; break;
@ -951,8 +928,7 @@ void Manager::HookUnprocessedPacket(const Packet* packet) const {
hook_list* l = hooks[HOOK_UNPROCESSED_PACKET]; hook_list* l = hooks[HOOK_UNPROCESSED_PACKET];
if ( l ) if ( l )
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
p->HookUnprocessedPacket(packet); p->HookUnprocessedPacket(packet);
} }
@ -976,9 +952,7 @@ bool Manager::HookPublishEvent(zeek::cluster::Backend& backend, const std::strin
bool result = true; bool result = true;
if ( l ) { if ( l ) {
for ( hook_list::iterator i = l->begin(); i != l->end(); ++i ) { for ( const auto& [_, p] : *l ) {
Plugin* p = (*i).second;
if ( ! p->HookPublishEvent(backend, topic, event) ) { if ( ! p->HookPublishEvent(backend, topic, event) ) {
result = false; result = false;
break; break;

View file

@ -396,17 +396,17 @@ void Plugin::Describe(ODesc* d) const {
if ( d->IsShort() ) if ( d->IsShort() )
return; return;
for ( component_list::const_iterator i = components.begin(); i != components.end(); i++ ) { for ( Component* component : components ) {
(*i)->Describe(d); component->Describe(d);
d->Add("\n"); d->Add("\n");
} }
bif_item_list items = BifItems(); 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; const char* type = nullptr;
switch ( (*i).GetType() ) { switch ( item.GetType() ) {
case BifItem::FUNCTION: type = "Function"; break; case BifItem::FUNCTION: type = "Function"; break;
case BifItem::EVENT: type = "Event"; break; case BifItem::EVENT: type = "Event"; break;
@ -424,16 +424,13 @@ void Plugin::Describe(ODesc* d) const {
d->Add("["); d->Add("[");
d->Add(type); d->Add(type);
d->Add("] "); d->Add("] ");
d->Add((*i).GetID()); d->Add(item.GetID());
d->Add("\n"); d->Add("\n");
} }
hook_list hooks = EnabledHooks(); hook_list hooks = EnabledHooks();
for ( hook_list::iterator i = hooks.begin(); i != hooks.end(); i++ ) { for ( const auto& [hook, prio] : hooks ) {
HookType hook = (*i).first;
int prio = (*i).second;
d->Add(" Implements "); d->Add(" Implements ");
d->Add(hook_name(hook)); d->Add(hook_name(hook));
d->Add(" (priority "); d->Add(" (priority ");

View file

@ -17,15 +17,16 @@ BitVector::block_type BitVector::bits_per_block = std::numeric_limits<BitVector:
namespace { namespace {
uint8_t count_table[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, constexpr uint8_t count_table[] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3,
4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4,
4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4,
5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5,
4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2,
3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5,
5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5,
5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5,
5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
} // namespace } // namespace
@ -380,8 +381,8 @@ BitVector::size_type BitVector::Size() const { return num_bits; }
bool BitVector::Empty() const { return bits.empty(); } bool BitVector::Empty() const { return bits.empty(); }
bool BitVector::AllZero() const { bool BitVector::AllZero() const {
for ( size_t i = 0; i < bits.size(); ++i ) { for ( unsigned long long bit : bits ) {
if ( bits[i] ) if ( bit )
return false; return false;
} }

View file

@ -164,8 +164,8 @@ BasicBloomFilter::~BasicBloomFilter() { delete bits; }
void BasicBloomFilter::Add(const zeek::detail::HashKey* key) { void BasicBloomFilter::Add(const zeek::detail::HashKey* key) {
detail::Hasher::digest_vector h = hasher->Hash(key); detail::Hasher::digest_vector h = hasher->Hash(key);
for ( size_t i = 0; i < h.size(); ++i ) for ( unsigned long long i : h )
bits->Set(h[i] % bits->Size()); bits->Set(i % bits->Size());
} }
bool BasicBloomFilter::Decrement(const zeek::detail::HashKey* key) { 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 { size_t BasicBloomFilter::Count(const zeek::detail::HashKey* key) const {
detail::Hasher::digest_vector h = hasher->Hash(key); detail::Hasher::digest_vector h = hasher->Hash(key);
for ( size_t i = 0; i < h.size(); ++i ) { for ( unsigned long long i : h ) {
if ( ! (*bits)[h[i] % bits->Size()] ) if ( ! (*bits)[i % bits->Size()] )
return 0; return 0;
} }
@ -267,8 +267,8 @@ std::string CountingBloomFilter::InternalState() const { return util::fmt("%" PR
void CountingBloomFilter::Add(const zeek::detail::HashKey* key) { void CountingBloomFilter::Add(const zeek::detail::HashKey* key) {
detail::Hasher::digest_vector h = hasher->Hash(key); detail::Hasher::digest_vector h = hasher->Hash(key);
for ( size_t i = 0; i < h.size(); ++i ) for ( unsigned long long i : h )
cells->Increment(h[i] % cells->Size()); cells->Increment(i % cells->Size());
} }
bool CountingBloomFilter::Decrement(const zeek::detail::HashKey* key) { 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); detail::Hasher::digest_vector h = hasher->Hash(key);
for ( size_t i = 0; i < h.size(); ++i ) for ( unsigned long long i : h )
cells->Decrement(h[i] % cells->Size()); cells->Decrement(i % cells->Size());
return true; return true;
} }
@ -289,8 +289,8 @@ size_t CountingBloomFilter::Count(const zeek::detail::HashKey* key) const {
detail::CounterVector::size_type min = std::numeric_limits<detail::CounterVector::size_type>::max(); detail::CounterVector::size_type min = std::numeric_limits<detail::CounterVector::size_type>::max();
for ( size_t i = 0; i < h.size(); ++i ) { for ( unsigned long long i : h ) {
detail::CounterVector::size_type cnt = cells->Count(h[i] % cells->Size()); detail::CounterVector::size_type cnt = cells->Count(i % cells->Size());
if ( cnt < min ) if ( cnt < min )
min = cnt; min = cnt;
} }

View file

@ -312,8 +312,7 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args)
std::vector<ValPtr> consts; std::vector<ValPtr> consts;
std::vector<int> v; std::vector<int> v;
for ( auto i = 0U; i < args.size(); ++i ) { for ( const auto& a : args ) {
auto a = args[i];
if ( a->Tag() == EXPR_NAME ) if ( a->Tag() == EXPR_NAME )
v.push_back(zam->FrameSlot(a->AsNameExpr())); v.push_back(zam->FrameSlot(a->AsNameExpr()));
else else
@ -402,9 +401,9 @@ bool MultiZBI::Build(ZAMCompiler* zam, const NameExpr* n, const ExprPList& args)
BiFArgsType MultiZBI::ComputeArgsType(const ExprPList& args) const { BiFArgsType MultiZBI::ComputeArgsType(const ExprPList& args) const {
zeek_uint_t mask = 0; zeek_uint_t mask = 0;
for ( auto i = 0U; i < args.size(); ++i ) { for ( const auto& a : args ) {
mask <<= 1; mask <<= 1;
if ( args[i]->Tag() == EXPR_CONST ) if ( a->Tag() == EXPR_CONST )
mask |= 1; mask |= 1;
} }

View file

@ -54,7 +54,7 @@ void Manager::InitPostScript() {
m.second = 0; m.second = 0;
MsgThread::Stats thread_stats; MsgThread::Stats thread_stats;
for ( const auto& t : thread_mgr->msg_threads ) { for ( auto* t : thread_mgr->msg_threads ) {
t->GetStats(&thread_stats); t->GetStats(&thread_stats);
thread_mgr->current_bucketed_messages.pending_in_total += thread_stats.pending_in; thread_mgr->current_bucketed_messages.pending_in_total += thread_stats.pending_in;
@ -140,16 +140,16 @@ void Manager::Terminate() {
// Signal all to stop. // Signal all to stop.
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) for ( auto* t : all_threads )
(*i)->SignalStop(); t->SignalStop();
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) for ( auto* t : all_threads )
(*i)->WaitForStop(); t->WaitForStop();
// Then join them all. // Then join them all.
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { for ( auto* t : all_threads ) {
(*i)->Join(); t->Join();
delete *i; delete t;
} }
all_threads.clear(); all_threads.clear();
@ -183,8 +183,8 @@ void Manager::AddMsgThread(MsgThread* thread) {
void Manager::KillThreads() { void Manager::KillThreads() {
DBG_LOG(DBG_THREADING, "Killing threads ..."); DBG_LOG(DBG_THREADING, "Killing threads ...");
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) for ( auto* t : all_threads )
(*i)->Kill(); t->Kill();
} }
void Manager::KillThread(BasicThread* thread) { 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 // Since this is a regular timer, this is also an ideal place to check whether we have
// and dead threads and to delete them. // and dead threads and to delete them.
all_thread_list to_delete; all_thread_list to_delete;
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { for ( auto* t : all_threads ) {
BasicThread* t = *i;
if ( t->Killed() ) if ( t->Killed() )
to_delete.push_back(t); to_delete.push_back(t);
} }
for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { for ( auto* t : to_delete ) {
BasicThread* t = *i;
t->WaitForStop(); t->WaitForStop();
all_threads.remove(t); all_threads.remove(t);
@ -290,9 +287,7 @@ void Manager::Flush() {
did_process = false; did_process = false;
for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { for ( auto* t : msg_threads ) {
MsgThread* t = *i;
if ( do_beat ) if ( do_beat )
t->Heartbeat(); t->Heartbeat();
@ -316,15 +311,12 @@ void Manager::Flush() {
all_thread_list to_delete; all_thread_list to_delete;
for ( all_thread_list::iterator i = all_threads.begin(); i != all_threads.end(); i++ ) { for ( auto* t : all_threads ) {
BasicThread* t = *i;
if ( t->Killed() ) if ( t->Killed() )
to_delete.push_back(t); to_delete.push_back(t);
} }
for ( all_thread_list::iterator i = to_delete.begin(); i != to_delete.end(); i++ ) { for ( auto* t : to_delete ) {
BasicThread* t = *i;
t->WaitForStop(); t->WaitForStop();
all_threads.remove(t); all_threads.remove(t);
@ -346,9 +338,7 @@ void Manager::Flush() {
const threading::Manager::msg_stats_list& threading::Manager::GetMsgThreadStats() { const threading::Manager::msg_stats_list& threading::Manager::GetMsgThreadStats() {
stats.clear(); stats.clear();
for ( msg_thread_list::iterator i = msg_threads.begin(); i != msg_threads.end(); i++ ) { for ( auto* t : msg_threads ) {
MsgThread* t = *i;
MsgThread::Stats s; MsgThread::Stats s;
t->GetStats(&s); t->GetStats(&s);

View file

@ -664,8 +664,8 @@ string normalize_path(std::string_view path) {
} }
} }
for ( auto it = final_components.begin(); it != final_components.end(); ++it ) { for ( const auto& comp : final_components ) {
new_path.append(*it); new_path.append(comp);
new_path.append("/"); 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]); const auto paths = tokenize_string(zeek_path(), path_list_separator[0]);
for ( size_t i = 0; i < paths.size(); ++i ) { for ( const auto& p : paths ) {
string common = normalize_path(paths[i]); string common = normalize_path(p);
if ( rval.find(common) != 0 ) if ( rval.find(common) != 0 )
continue; continue;
@ -1817,8 +1817,8 @@ string find_file(const string& filename, const string& path_set, const string& o
if ( ! opt_ext.empty() ) if ( ! opt_ext.empty() )
ext.push_back(opt_ext); ext.push_back(opt_ext);
for ( size_t n = 0; n < paths.size(); ++n ) { for ( const auto& p : paths ) {
string f = find_file_in_path(filename, paths[n], ext); string f = find_file_in_path(filename, p, ext);
if ( ! f.empty() ) if ( ! f.empty() )
return f; return f;
@ -1833,8 +1833,8 @@ string find_script_file(const string& filename, const string& path_set) {
vector<string> ext = {".zeek"}; vector<string> ext = {".zeek"};
for ( size_t n = 0; n < paths.size(); ++n ) { for ( const auto& p : paths ) {
string f = find_file_in_path(filename, paths[n], ext); string f = find_file_in_path(filename, p, ext);
if ( ! f.empty() ) if ( ! f.empty() )
return f; return f;

View file

@ -72,18 +72,18 @@ Config::Config(const string& arg_file, const string& delim)
} }
Config::~Config() { Config::~Config() {
for ( size_t i = 0; i < targets.size(); ++i ) for ( auto* t : targets )
delete targets[i]; delete t;
} }
void Config::FindDependencies(const vector<Info*>& infos) { void Config::FindDependencies(const vector<Info*>& infos) {
for ( size_t i = 0; i < targets.size(); ++i ) for ( auto* t : targets )
targets[i]->FindDependencies(infos); t->FindDependencies(infos);
} }
void Config::GenerateDocs() const { void Config::GenerateDocs() const {
for ( size_t i = 0; i < targets.size(); ++i ) for ( auto* t : targets )
targets[i]->Generate(); t->Generate();
} }
time_t Config::GetModificationTime() const { time_t Config::GetModificationTime() const {

View file

@ -81,9 +81,9 @@ vector<string> IdentifierInfo::GetFieldComments(const string& field) const {
list<IdentifierInfo::Redefinition> IdentifierInfo::GetRedefs(const string& from_script) const { list<IdentifierInfo::Redefinition> IdentifierInfo::GetRedefs(const string& from_script) const {
list<Redefinition> rval; list<Redefinition> rval;
for ( redef_list::const_iterator it = redefs.begin(); it != redefs.end(); ++it ) { for ( Redefinition* redef : redefs ) {
if ( from_script == (*it)->from_script ) if ( from_script == redef->from_script )
rval.push_back(*(*it)); rval.push_back(*redef);
} }
return rval; return rval;

View file

@ -93,8 +93,8 @@ Manager::Manager(const string& arg_config, const string& command)
} }
Manager::~Manager() { Manager::~Manager() {
for ( size_t i = 0; i < all_info.size(); ++i ) for ( auto* info : all_info )
delete all_info[i]; delete info;
} }
void Manager::InitPreScript() { void Manager::InitPreScript() {
@ -106,8 +106,8 @@ void Manager::InitPostScript() {
if ( disabled ) if ( disabled )
return; return;
for ( size_t i = 0; i < all_info.size(); ++i ) for ( auto* info : all_info )
all_info[i]->InitPostScript(); info->InitPostScript();
config.FindDependencies(all_info); config.FindDependencies(all_info);
} }
@ -179,8 +179,8 @@ void Manager::ScriptDependency(const string& path, const string& dep) {
script_info->AddDependency(depname); script_info->AddDependency(depname);
DBG_LOG(DBG_ZEEKYGEN, "Added script dependency %s for %s", depname.c_str(), name.c_str()); 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 ) for ( const auto& cmnt : comment_buffer )
DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", comment_buffer[i].c_str())); DbgAndWarn(util::fmt("Discarded extraneous Zeekygen comment: %s", cmnt.c_str()));
} }
void Manager::ModuleUsage(const string& path, const string& module) { void Manager::ModuleUsage(const string& path, const string& module) {

View file

@ -35,8 +35,8 @@ PackageInfo::PackageInfo(const string& arg_name) : Info(), pkg_name(arg_name), r
string PackageInfo::DoReStructuredText(bool roles_only) const { string PackageInfo::DoReStructuredText(bool roles_only) const {
string rval = util::fmt(":doc:`%s </scripts/%s/index>`\n\n", pkg_name.c_str(), pkg_name.c_str()); string rval = util::fmt(":doc:`%s </scripts/%s/index>`\n\n", pkg_name.c_str(), pkg_name.c_str());
for ( size_t i = 0; i < readme.size(); ++i ) for ( const auto& r : readme )
rval += " " + readme[i] + "\n"; rval += " " + r + "\n";
return rval; return rval;
} }

View file

@ -40,16 +40,16 @@ string ReStructuredTextTable::MakeBorder(const vector<size_t>& col_sizes, char b
string ReStructuredTextTable::AsString(char border) const { string ReStructuredTextTable::AsString(char border) const {
string rval = MakeBorder(longest_row_in_column, border); 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 ) { for ( size_t col = 0; col < num_cols; ++col ) {
if ( col > 0 ) { 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 longest = longest_row_in_column[col - 1];
size_t whitespace = longest - last + 1; size_t whitespace = longest - last + 1;
rval += string(whitespace, ' '); rval += string(whitespace, ' ');
} }
rval += rows[row][col]; rval += row[col];
} }
rval += "\n"; rval += "\n";

View file

@ -23,17 +23,17 @@ bool IdInfoComp::operator()(const IdentifierInfo* lhs, const IdentifierInfo* rhs
static vector<string> summary_comment(const vector<string>& cmnts) { static vector<string> summary_comment(const vector<string>& cmnts) {
vector<string> rval; vector<string> rval;
for ( size_t i = 0; i < cmnts.size(); ++i ) { for ( const auto& cmnt : cmnts ) {
size_t end = end_of_first_sentence(cmnts[i]); size_t end = end_of_first_sentence(cmnt);
if ( end == string::npos ) { if ( end == string::npos ) {
if ( is_all_whitespace(cmnts[i]) ) if ( is_all_whitespace(cmnt) )
break; break;
rval.push_back(cmnts[i]); rval.push_back(cmnt);
} }
else { else {
rval.push_back(cmnts[i].substr(0, end + 1)); rval.push_back(cmnt.substr(0, end + 1));
break; break;
} }
} }
@ -68,12 +68,12 @@ static string make_summary(const string& heading, char underline, char border, c
ReStructuredTextTable table(2); ReStructuredTextTable table(2);
for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { for ( IdentifierInfo* info : id_list ) {
auto* id = (*it)->GetID(); auto* id = info->GetID();
ODesc d; ODesc d;
d.SetQuotes(true); d.SetQuotes(true);
id->DescribeReSTShort(&d); 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"; 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); ReStructuredTextTable table(2);
for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { for ( IdentifierInfo* info : id_set ) {
auto* id = (*it)->GetID(); auto* id = info->GetID();
ODesc d; ODesc d;
d.SetQuotes(true); d.SetQuotes(true);
id->DescribeReSTShort(&d); id->DescribeReSTShort(&d);
using redef_list = std::list<IdentifierInfo::Redefinition>; using redef_list = std::list<IdentifierInfo::Redefinition>;
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 ) { for ( redef_list::const_iterator iit = redefs.begin(); iit != redefs.end(); ++iit ) {
add_summary_rows(d, summary_comment(iit->comments), &table); 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); string rval = make_heading(heading, underline);
for ( id_info_list::const_iterator it = id_list.begin(); it != id_list.end(); ++it ) { for ( IdentifierInfo* info : id_list ) {
rval += (*it)->ReStructuredText(); rval += info->ReStructuredText();
rval += "\n\n"; 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); string rval = make_heading(heading, underline);
for ( id_info_set::const_iterator it = id_set.begin(); it != id_set.end(); ++it ) { for ( IdentifierInfo* info : id_set ) {
rval += (*it)->ReStructuredText(true); rval += info->ReStructuredText(true);
rval += "\n\n"; rval += "\n\n";
} }
@ -337,13 +337,13 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const {
rval += ":tocdepth: 3\n\n"; rval += ":tocdepth: 3\n\n";
rval += make_heading(name, '='); rval += make_heading(name, '=');
for ( string_set::const_iterator it = module_usages.begin(); it != module_usages.end(); ++it ) for ( const auto& usage : module_usages )
rval += ".. zeek:namespace:: " + *it + "\n"; rval += ".. zeek:namespace:: " + usage + "\n";
rval += "\n"; rval += "\n";
for ( size_t i = 0; i < comments.size(); ++i ) for ( const auto& cmnt : comments )
rval += comments[i] + "\n"; rval += cmnt + "\n";
rval += "\n"; rval += "\n";
@ -410,15 +410,15 @@ string ScriptInfo::DoReStructuredText(bool roles_only) const {
time_t ScriptInfo::DoGetModificationTime() const { time_t ScriptInfo::DoGetModificationTime() const {
time_t most_recent = get_mtime(path); time_t most_recent = get_mtime(path);
for ( string_set::const_iterator it = dependencies.begin(); it != dependencies.end(); ++it ) { for ( const auto& dep : dependencies ) {
Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(*it); Info* info = zeek::detail::zeekygen_mgr->GetScriptInfo(dep);
if ( ! info ) { if ( ! info ) {
string pkg_name = *it + "/__load__.zeek"; string pkg_name = dep + "/__load__.zeek";
info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name); info = zeek::detail::zeekygen_mgr->GetScriptInfo(pkg_name);
if ( ! info ) 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; continue;
} }

View file

@ -174,8 +174,8 @@ template<class T>
static vector<T*> filter_matches(const vector<Info*>& from, Target* t) { static vector<T*> filter_matches(const vector<Info*>& from, Target* t) {
vector<T*> rval; vector<T*> rval;
for ( size_t i = 0; i < from.size(); ++i ) { for ( Info* f : from ) {
T* d = dynamic_cast<T*>(from[i]); T* d = dynamic_cast<T*>(f);
if ( ! d ) if ( ! d )
continue; continue;
@ -339,19 +339,18 @@ void PackageTarget::DoFindDependencies(const vector<Info*>& infos) {
if ( pkg_deps.empty() ) if ( pkg_deps.empty() )
reporter->FatalError("No match for Zeekygen target '%s' pattern '%s'", Name().c_str(), Pattern().c_str()); 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 ) { for ( Info* info : infos ) {
ScriptInfo* script = dynamic_cast<ScriptInfo*>(infos[i]); ScriptInfo* script = dynamic_cast<ScriptInfo*>(info);
if ( ! script ) if ( ! script )
continue; continue;
for ( size_t j = 0; j < pkg_deps.size(); ++j ) { for ( const auto& dep : pkg_deps ) {
if ( strncmp(script->Name().c_str(), pkg_deps[j]->Name().c_str(), pkg_deps[j]->Name().size()) != 0 ) if ( strncmp(script->Name().c_str(), dep->Name().c_str(), dep->Name().size()) != 0 )
continue; continue;
DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), DBG_LOG(DBG_ZEEKYGEN, "Script %s associated with package %s", script->Name().c_str(), dep->Name().c_str());
pkg_deps[j]->Name().c_str()); pkg_manifest[dep].push_back(script);
pkg_manifest[pkg_deps[j]].push_back(script);
script_deps.push_back(script); script_deps.push_back(script);
} }
} }
@ -366,26 +365,26 @@ void PackageTarget::DoGenerate() const {
fprintf(file.f, ":orphan:\n\n"); fprintf(file.f, ":orphan:\n\n");
for ( manifest_t::const_iterator it = pkg_manifest.begin(); it != pkg_manifest.end(); ++it ) { for ( const auto& [pkg, info_vec] : pkg_manifest ) {
string header = util::fmt("Package: %s", it->first->Name().c_str()); string header = util::fmt("Package: %s", pkg->Name().c_str());
header += "\n" + string(header.size(), '='); header += "\n" + string(header.size(), '=');
fprintf(file.f, "%s\n\n", header.c_str()); fprintf(file.f, "%s\n\n", header.c_str());
vector<string> readme = it->first->GetReadme(); vector<string> readme = pkg->GetReadme();
for ( size_t i = 0; i < readme.size(); ++i ) for ( const auto& r : readme )
fprintf(file.f, "%s\n", readme[i].c_str()); fprintf(file.f, "%s\n", r.c_str());
fprintf(file.f, "\n"); fprintf(file.f, "\n");
for ( size_t i = 0; i < it->second.size(); ++i ) { for ( ScriptInfo* info : info_vec ) {
fprintf(file.f, ":doc:`/scripts/%s`\n\n", it->second[i]->Name().c_str()); fprintf(file.f, ":doc:`/scripts/%s`\n\n", info->Name().c_str());
vector<string> cmnts = it->second[i]->GetComments(); vector<string> cmnts = info->GetComments();
for ( size_t j = 0; j < cmnts.size(); ++j ) for ( const auto& cmnt : cmnts )
fprintf(file.f, " %s\n", cmnts[j].c_str()); fprintf(file.f, " %s\n", cmnt.c_str());
fprintf(file.f, "\n"); fprintf(file.f, "\n");
} }
@ -405,8 +404,8 @@ void PackageIndexTarget::DoGenerate() const {
TargetFile file(Name()); TargetFile file(Name());
for ( size_t i = 0; i < pkg_deps.size(); ++i ) for ( PackageInfo* info : pkg_deps )
fprintf(file.f, "%s\n", pkg_deps[i]->ReStructuredText().c_str()); fprintf(file.f, "%s\n", info->ReStructuredText().c_str());
} }
void ScriptTarget::DoFindDependencies(const vector<Info*>& infos) { void ScriptTarget::DoFindDependencies(const vector<Info*>& infos) {
@ -418,9 +417,9 @@ void ScriptTarget::DoFindDependencies(const vector<Info*>& infos) {
if ( ! IsDir() ) if ( ! IsDir() )
return; return;
for ( size_t i = 0; i < script_deps.size(); ++i ) { for ( ScriptInfo* d : script_deps ) {
if ( util::detail::is_package_loader(script_deps[i]->Name()) ) { if ( util::detail::is_package_loader(d->Name()) ) {
string pkg_dir = util::SafeDirname(script_deps[i]->Name()).result; string pkg_dir = util::SafeDirname(d->Name()).result;
string target_file = Name() + pkg_dir + "/index.rst"; string target_file = Name() + pkg_dir + "/index.rst";
Target* t = new PackageTarget(target_file, pkg_dir); Target* t = new PackageTarget(target_file, pkg_dir);
t->FindDependencies(infos); t->FindDependencies(infos);
@ -472,23 +471,23 @@ void ScriptTarget::DoGenerate() const {
set<string> targets; set<string> targets;
vector<string> dir_contents = dir_contents_recursive(Name()); vector<string> dir_contents = dir_contents_recursive(Name());
for ( size_t i = 0; i < script_deps.size(); ++i ) { for ( ScriptInfo* d : script_deps ) {
string target_filename = Name() + script_deps[i]->Name() + ".rst"; string target_filename = Name() + d->Name() + ".rst";
targets.insert(target_filename); targets.insert(target_filename);
vector<ScriptInfo*> dep; vector<ScriptInfo*> dep;
dep.push_back(script_deps[i]); dep.push_back(d);
if ( zeek::detail::zeekygen_mgr->IsUpToDate(target_filename, dep) ) if ( zeek::detail::zeekygen_mgr->IsUpToDate(target_filename, dep) )
continue; continue;
TargetFile file(target_filename); 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 ) { for ( Target* tgt : pkg_deps ) {
targets.insert(pkg_deps[i]->Name()); targets.insert(tgt->Name());
pkg_deps[i]->Generate(); tgt->Generate();
} }
for ( const auto& f : dir_contents ) { for ( const auto& f : dir_contents ) {
@ -511,8 +510,9 @@ void ScriptTarget::DoGenerate() const {
TargetFile file(Name()); TargetFile file(Name());
for ( size_t i = 0; i < script_deps.size(); ++i ) for ( ScriptInfo* d : script_deps ) {
fprintf(file.f, "%s\n", script_deps[i]->ReStructuredText().c_str()); fprintf(file.f, "%s\n", d->ReStructuredText().c_str());
}
} }
void ScriptSummaryTarget::DoGenerate() const { void ScriptSummaryTarget::DoGenerate() const {
@ -521,9 +521,7 @@ void ScriptSummaryTarget::DoGenerate() const {
TargetFile file(Name()); TargetFile file(Name());
for ( size_t i = 0; i < script_deps.size(); ++i ) { for ( ScriptInfo* d : script_deps ) {
ScriptInfo* d = dynamic_cast<ScriptInfo*>(script_deps[i]);
if ( ! d ) if ( ! d )
continue; continue;
@ -531,8 +529,8 @@ void ScriptSummaryTarget::DoGenerate() const {
vector<string> cmnts = d->GetComments(); vector<string> cmnts = d->GetComments();
for ( size_t i = 0; i < cmnts.size(); ++i ) for ( const string& cmnt : cmnts )
fprintf(file.f, " %s\n", cmnts[i].c_str()); fprintf(file.f, " %s\n", cmnt.c_str());
fprintf(file.f, "\n"); fprintf(file.f, "\n");
} }
@ -547,9 +545,7 @@ void ScriptIndexTarget::DoGenerate() const {
fprintf(file.f, ".. toctree::\n"); fprintf(file.f, ".. toctree::\n");
fprintf(file.f, " :maxdepth: 1\n\n"); fprintf(file.f, " :maxdepth: 1\n\n");
for ( size_t i = 0; i < script_deps.size(); ++i ) { for ( ScriptInfo* d : script_deps ) {
ScriptInfo* d = dynamic_cast<ScriptInfo*>(script_deps[i]);
if ( ! d ) if ( ! d )
continue; continue;
@ -570,8 +566,8 @@ void IdentifierTarget::DoGenerate() const {
TargetFile file(Name()); TargetFile file(Name());
for ( size_t i = 0; i < id_deps.size(); ++i ) for ( IdentifierInfo* info : id_deps )
fprintf(file.f, "%s\n\n", id_deps[i]->ReStructuredText().c_str()); fprintf(file.f, "%s\n\n", info->ReStructuredText().c_str());
} }
} // namespace zeek::zeekygen::detail } // namespace zeek::zeekygen::detail

View file

@ -3,6 +3,7 @@
#include "zeek/zeekygen/utils.h" #include "zeek/zeekygen/utils.h"
#include <sys/stat.h> #include <sys/stat.h>
#include <algorithm>
#include <cerrno> #include <cerrno>
#include "zeek/Func.h" #include "zeek/Func.h"
@ -112,11 +113,8 @@ size_t end_of_first_sentence(const string& s) {
} }
bool is_all_whitespace(const string& s) { bool is_all_whitespace(const string& s) {
for ( size_t i = 0; i < s.size(); ++i ) auto it = std::find_if(s.begin(), s.end(), [](char c) { return ! isspace(c); });
if ( ! isspace(s[i]) ) return it == s.end();
return false;
return true;
} }
string redef_indication(const string& from_script) { string redef_indication(const string& from_script) {