Merge remote-tracking branch 'origin/topic/timw/reformat-cpp-code-in-bison-and-flex-files'

* origin/topic/timw/reformat-cpp-code-in-bison-and-flex-files:
  Reformat embedded C++ code in bison/flex files
This commit is contained in:
Tim Wojtulewicz 2025-03-04 09:33:54 -07:00
commit 8f0236448b
8 changed files with 949 additions and 1138 deletions

View file

@ -1,3 +1,7 @@
7.2.0-dev.257 | 2025-03-04 09:33:54 -0700
* Reformat embedded C++ code in bison/flex files (Tim Wojtulewicz, Corelight)
7.2.0-dev.255 | 2025-03-04 08:52:13 -0700
* Fix Coverity findings from recent IPTunnel dumping changes (Tim Wojtulewicz, Corelight)

View file

@ -1 +1 @@
7.2.0-dev.255
7.2.0-dev.257

View file

@ -82,29 +82,28 @@
%type <expr> opt_assert_msg
%{
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <set>
#include <string>
#include "zeek/input.h"
#include "zeek/ZeekList.h"
#include "zeek/Desc.h"
#include "zeek/Expr.h"
#include "zeek/Func.h"
#include "zeek/IntrusivePtr.h"
#include "zeek/RE.h"
#include "zeek/Reporter.h"
#include "zeek/Scope.h"
#include "zeek/ScriptCoverageManager.h"
#include "zeek/ScriptValidation.h"
#include "zeek/Stmt.h"
#include "zeek/Val.h"
#include "zeek/Var.h"
#include "zeek/RE.h"
#include "zeek/Scope.h"
#include "zeek/Reporter.h"
#include "zeek/ScriptCoverageManager.h"
#include "zeek/ScriptValidation.h"
#include "zeek/zeekygen/Manager.h"
#include "zeek/ZeekList.h"
#include "zeek/input.h"
#include "zeek/module_util.h"
#include "zeek/IntrusivePtr.h"
#include "zeek/zeekygen/Manager.h"
extern const char* filename; // Absolute path of file currently being parsed.
extern const char* last_filename; // Absolute path of last file parsed.
@ -120,8 +119,7 @@ extern YYLTYPE GetCurrentLocation();
extern int yyerror(const char[]);
extern int zeeklex();
#define YYLLOC_DEFAULT(Current, Rhs, N) \
(Current) = (Rhs)[(N)];
#define YYLLOC_DEFAULT(Current, Rhs, N) (Current) = (Rhs)[(N)];
using namespace zeek;
using namespace zeek::detail;
@ -162,22 +160,19 @@ static int func_hdr_cond_epoch = 0;
EnumType* cur_enum_type = nullptr;
static ID* cur_decl_type_id = nullptr;
static void parse_new_enum(void)
{
static void parse_new_enum(void) {
// Starting a new enum definition.
assert(cur_enum_type == nullptr);
if ( cur_decl_type_id )
{
if ( cur_decl_type_id ) {
auto name = make_full_var_name(current_module.c_str(), cur_decl_type_id->Name());
cur_enum_type = new EnumType(name);
}
else
reporter->FatalError("incorrect syntax for enum type declaration");
}
}
static void parse_redef_enum(ID* id)
{
static void parse_redef_enum(ID* id) {
// Redef an enum. id points to the enum to be redefined.
// Let cur_enum_type point to it.
assert(cur_enum_type == nullptr);
@ -185,35 +180,29 @@ static void parse_redef_enum(ID* id)
// abort on errors; enums need to be accessible to continue parsing
if ( ! id->GetType() )
reporter->FatalError("unknown enum identifier \"%s\"", id->Name());
else
{
else {
if ( ! id->GetType() || id->GetType()->Tag() != TYPE_ENUM )
reporter->FatalError("identifier \"%s\" is not an enum", id->Name());
cur_enum_type = id->GetType()->AsEnumType();
}
}
}
static void parse_redef_record_field(ID* id, const char* field, InitClass ic,
std::unique_ptr<std::vector<AttrPtr>> attrs)
{
if ( ! id->GetType() )
{
std::unique_ptr<std::vector<AttrPtr>> attrs) {
if ( ! id->GetType() ) {
reporter->FatalError("unknown record identifier \"%s\"", id->Name());
return;
}
auto t = id->GetType();
if ( ! t || t->Tag() != TYPE_RECORD )
{
reporter->FatalError("identifier \"%s\" has type \"%s\", expected \"record\"",
id->Name(), type_name(t->Tag()));
if ( ! t || t->Tag() != TYPE_RECORD ) {
reporter->FatalError("identifier \"%s\" has type \"%s\", expected \"record\"", id->Name(), type_name(t->Tag()));
return;
}
auto rt = t->AsRecordType();
auto idx = rt->FieldOffset(field);
if ( idx < 0 )
{
if ( idx < 0 ) {
reporter->FatalError("field \"%s\" not in record \"%s\"", field, id->Name());
return;
}
@ -221,15 +210,11 @@ static void parse_redef_record_field(ID* id, const char* field, InitClass ic,
auto decl = rt->FieldDecl(idx);
if ( ! decl->attrs )
if ( ic == INIT_EXTRA )
decl->attrs = make_intrusive<detail::Attributes>(decl->type,
true /* in_record */,
false /* is_global */);
decl->attrs = make_intrusive<detail::Attributes>(decl->type, true /* in_record */, false /* is_global */);
for ( const auto& attr : *attrs )
{
for ( const auto& attr : *attrs ) {
// At this point, only support &log redef'ing.
if ( attr->Tag() != ATTR_LOG )
{
if ( attr->Tag() != ATTR_LOG ) {
reporter->FatalError("Can only redef \"&log\" attributes of record fields");
return;
}
@ -241,15 +226,12 @@ static void parse_redef_record_field(ID* id, const char* field, InitClass ic,
if ( decl->attrs )
decl->attrs->RemoveAttr(attr->Tag());
}
}
}
static void extend_record(ID* id, std::unique_ptr<type_decl_list> fields,
std::unique_ptr<std::vector<AttrPtr>> attrs)
{
static void extend_record(ID* id, std::unique_ptr<type_decl_list> fields, std::unique_ptr<std::vector<AttrPtr>> attrs) {
const auto& types = Type::Aliases(id->Name());
if ( types.empty() )
{
if ( types.empty() ) {
id->Error("failed to redef record: no types found in alias map");
return;
}
@ -258,39 +240,31 @@ static void extend_record(ID* id, std::unique_ptr<type_decl_list> fields,
if ( attrs )
for ( const auto& at : *attrs )
if ( at->Tag() == ATTR_LOG )
{
if ( at->Tag() == ATTR_LOG ) {
add_log_attr = true;
break;
}
for ( const auto& t : types )
{
for ( const auto& t : types ) {
auto error = t->AsRecordType()->AddFields(*fields, add_log_attr);
if ( error )
{
if ( error ) {
id->Error(error);
break;
}
}
}
}
static AttributesPtr
make_attributes(std::vector<AttrPtr>* attrs,
TypePtr t, bool in_record, bool is_global)
{
static AttributesPtr make_attributes(std::vector<AttrPtr>* attrs, TypePtr t, bool in_record, bool is_global) {
if ( ! attrs )
return nullptr;
auto rval = make_intrusive<Attributes>(std::move(*attrs), std::move(t),
in_record, is_global);
auto rval = make_intrusive<Attributes>(std::move(*attrs), std::move(t), in_record, is_global);
delete attrs;
return rval;
}
}
static bool expr_is_table_type_name(const Expr* expr)
{
static bool expr_is_table_type_name(const Expr* expr) {
if ( expr->Tag() != EXPR_NAME )
return false;
@ -303,20 +277,17 @@ static bool expr_is_table_type_name(const Expr* expr)
return type->AsTypeType()->GetType()->IsTable();
return false;
}
}
static void check_loop_var(const IDPtr& var)
{
static void check_loop_var(const IDPtr& var) {
if ( var->IsGlobal() )
var->Error("global variable used in 'for' loop");
if ( var->IsConst() )
var->Error("constant used in 'for' loop");
}
}
static void build_global(ID* id, Type* t, InitClass ic, Expr* e,
std::vector<AttrPtr>* attrs, DeclType dt)
{
static void build_global(ID* id, Type* t, InitClass ic, Expr* e, std::vector<AttrPtr>* attrs, DeclType dt) {
IDPtr id_ptr{AdoptRef{}, id};
TypePtr t_ptr{AdoptRef{}, t};
ExprPtr e_ptr{AdoptRef{}, e};
@ -329,32 +300,28 @@ static void build_global(ID* id, Type* t, InitClass ic, Expr* e,
zeekygen_mgr->Redef(id, ::filename, ic, std::move(e_ptr));
else
zeekygen_mgr->Identifier(std::move(id_ptr));
}
}
static StmtPtr build_local(ID* id, Type* t, InitClass ic, Expr* e,
std::vector<AttrPtr>* attrs, DeclType dt,
bool do_coverage)
{
static StmtPtr build_local(ID* id, Type* t, InitClass ic, Expr* e, std::vector<AttrPtr>* attrs, DeclType dt,
bool do_coverage) {
IDPtr id_ptr{AdoptRef{}, id};
TypePtr t_ptr{AdoptRef{}, t};
ExprPtr e_ptr{AdoptRef{}, e};
auto attrs_ptr = attrs ? std::make_unique<std::vector<AttrPtr>>(*attrs) : nullptr;
auto init = add_local(std::move(id_ptr), std::move(t_ptr), ic,
e_ptr, std::move(attrs_ptr), dt);
auto init = add_local(std::move(id_ptr), std::move(t_ptr), ic, e_ptr, std::move(attrs_ptr), dt);
if ( do_coverage )
script_coverage_mgr.AddStmt(init.get());
return init;
}
}
static void refine_location(zeek::detail::ID* id)
{
static void refine_location(zeek::detail::ID* id) {
if ( *id->GetLocationInfo() == zeek::detail::no_location )
id->SetLocationInfo(&detail::start_location, &detail::end_location);
}
}
%}
@ -384,8 +351,7 @@ static void refine_location(zeek::detail::ID* id)
zeek::FuncType::Capture* capture;
zeek::FuncType::CaptureList* captures;
zeek::detail::WhenInfo* when_clause;
struct
{
struct {
bool ignore_case;
bool single_line;
} re_modes;
@ -549,30 +515,25 @@ expr:
set_location(@1, @2);
$$ = new NegExpr({AdoptRef{}, $2});
if ( ! $$->IsError() && $2->IsConst() )
{
if ( ! $$->IsError() && $2->IsConst() ) {
auto v = $2->ExprVal();
auto tag = v->GetType()->Tag();
if ( tag == TYPE_COUNT )
{
if ( tag == TYPE_COUNT ) {
auto c = v->AsCount();
uint64_t int_max = static_cast<uint64_t>(INT64_MAX) + 1;
if ( c <= int_max )
{
if ( c <= int_max ) {
auto ce = new ConstExpr(val_mgr->Int(-c));
Unref($$);
$$ = ce;
}
else
{
else {
$$->Error("literal is outside range of 'int' values");
$$->SetError();
}
}
else
{
else {
auto ce = new ConstExpr($$->Eval(nullptr));
Unref($$);
$$ = ce;
@ -600,8 +561,7 @@ expr:
ExprPtr rhs = {AdoptRef{}, $3};
auto tag1 = $1->GetType()->Tag();
if ( IsArithmetic($1->GetType()->Tag()) )
{
if ( IsArithmetic($1->GetType()->Tag()) ) {
// Script optimization assumes that each AST
// node is distinct, hence the call to
// Duplicate() here.
@ -630,8 +590,7 @@ expr:
ExprPtr rhs = {AdoptRef{}, $3};
auto tag1 = $1->GetType()->Tag();
if ( IsArithmetic(tag1) )
{
if ( IsArithmetic(tag1) ) {
ExprPtr sum = make_intrusive<SubExpr>(lhs, rhs);
if ( sum->GetType()->Tag() != tag1 )
@ -836,10 +795,8 @@ expr:
// used for an initializer. Interpret no expressions
// as an empty record constructor.
for ( int i = 0; i < $2->Exprs().length(); ++i )
{
if ( $2->Exprs()[i]->Tag() != EXPR_FIELD_ASSIGN )
{
for ( int i = 0; i < $2->Exprs().length(); ++i ) {
if ( $2->Exprs()[i]->Tag() != EXPR_FIELD_ASSIGN ) {
is_record_ctor = false;
break;
}
@ -899,12 +856,11 @@ expr:
const auto& ctor_type = $1->AsNameExpr()->Id()->GetType();
switch ( ctor_type->Tag() ) {
case TYPE_RECORD:
{
case TYPE_RECORD: {
auto rt = cast_intrusive<RecordType>(ctor_type);
$$ = new RecordConstructorExpr(rt, ListExprPtr{AdoptRef{}, $4});
}
break;
}
case TYPE_TABLE:
if ( ctor_type->IsTable() )
@ -960,10 +916,8 @@ expr:
set_location(@1);
auto id = lookup_ID($1, current_module.c_str());
if ( ! id )
{
if ( ! in_debug )
{
if ( ! id ) {
if ( ! in_debug ) {
/* // CHECK THAT THIS IS NOT GLOBAL.
id = install_ID($1, current_module.c_str(),
false, is_export);
@ -972,33 +926,26 @@ expr:
yyerror(util::fmt("unknown identifier %s", $1));
YYERROR;
}
else
{
else {
yyerror(util::fmt("unknown identifier %s", $1));
YYERROR;
}
}
else
{
else {
if ( id->IsDeprecated() )
reporter->Deprecation(id->GetDeprecationWarning());
if ( id->IsBlank() )
{
if ( id->IsBlank() ) {
$$ = new NameExpr(std::move(id));
$$->SetError("blank identifier used in expression");
}
else if ( ! id->GetType() )
{
else if ( ! id->GetType() ) {
id->Error("undeclared variable");
id->SetType(error_type());
$$ = new NameExpr(std::move(id));
}
else if ( id->IsEnumConst() )
{
if ( IsErrorType(id->GetType()->Tag()) )
{
else if ( id->IsEnumConst() ) {
if ( IsErrorType(id->GetType()->Tag()) ) {
// The most-relevant error message should already be reported, so
// just bail out.
YYERROR;
@ -1010,8 +957,7 @@ expr:
reporter->InternalError("enum value not found for %s", id->Name());
$$ = new ConstExpr(t->GetEnumVal(intval));
}
else
{
else {
if ( out_of_scope_locals.count(id.get()) > 0 )
id->Error("use of out-of-scope local; move declaration to outer scope");
@ -1324,15 +1270,13 @@ type:
| resolve_id
{
if ( ! $1 || ! ($$ = $1->IsType() ? $1->GetType().get() : nullptr) )
{
if ( ! $1 || ! ($$ = $1->IsType() ? $1->GetType().get() : nullptr) ) {
NullStmt here;
if ( $1 )
$1->Error("not a Zeek type", &here);
$$ = error_type()->Ref();
}
else
{
else {
Ref($$);
if ( $1->IsDeprecated() )
@ -1432,8 +1376,7 @@ decl:
}
| TOK_REDEF global_id {
if ( $2->IsType() )
{
if ( $2->IsType() ) {
auto tag = $2->GetType()->Tag();
auto tstr = type_name(tag);
if ( tag == TYPE_RECORD || tag == TYPE_ENUM )
@ -1582,8 +1525,7 @@ func_body:
set_location(func_hdr_location, @5);
bool free_of_conditionals = true;
if ( current_file_has_conditionals ||
conditional_epoch > func_hdr_cond_epoch )
if ( current_file_has_conditionals || conditional_epoch > func_hdr_cond_epoch )
free_of_conditionals = false;
end_func({AdoptRef{}, $3}, current_module.c_str(), free_of_conditionals);
@ -1652,8 +1594,7 @@ begin_lambda:
std::optional<FuncType::CaptureList> captures;
if ( $1 )
{
if ( $1 ) {
captures = *$1;
delete $1;
}
@ -1692,13 +1633,11 @@ capture:
if ( ! id )
reporter->Error("no such local identifier: %s", $2);
else if ( id->IsType() )
{
else if ( id->IsType() ) {
reporter->Error("cannot specify type in capture: %s", $2);
id = nullptr;
}
else if ( id->IsGlobal() )
{
else if ( id->IsGlobal() ) {
reporter->Error("cannot specify global in capture: %s", $2);
id = nullptr;
}
@ -1836,8 +1775,7 @@ attr:
$$ = new Attr(
ATTR_DEPRECATED,
make_intrusive<ConstExpr>(IntrusivePtr{AdoptRef{}, $3}));
else
{
else {
ODesc d;
$3->Describe(&d);
Unref($3);
@ -2035,10 +1973,8 @@ event:
set_location(@1, @4);
const auto& id = lookup_ID($1, current_module.c_str());
if ( id )
{
if ( ! id->IsGlobal() )
{
if ( id ) {
if ( ! id->IsGlobal() ) {
yyerror(util::fmt("local identifier \"%s\" cannot be used to reference an event", $1));
YYERROR;
}
@ -2048,8 +1984,7 @@ event:
$$ = new EventExpr(id->Name(), {AdoptRef{}, $3});
}
else
{
else {
$$ = new EventExpr($1, {AdoptRef{}, $3});
}
}
@ -2102,8 +2037,7 @@ case_type:
else
case_var = install_ID(name, current_module.c_str(), false, false);
add_local(case_var, std::move(type), INIT_NONE, nullptr, nullptr,
VAR_REGULAR);
add_local(case_var, std::move(type), INIT_NONE, nullptr, nullptr, VAR_REGULAR);
$$ = case_var.release();
}
@ -2120,10 +2054,8 @@ for_head:
if ( loop_var )
check_loop_var(loop_var);
else
{
loop_var = install_ID($3, current_module.c_str(),
false, false);
else {
loop_var = install_ID($3, current_module.c_str(), false, false);
}
auto* loop_vars = new IDPList;
@ -2198,8 +2130,7 @@ local_id:
auto id = lookup_ID($1, current_module.c_str());
$$ = id.release();
if ( $$ )
{
if ( $$ ) {
if ( $$->IsGlobal() && ! $$->IsBlank() )
$$->Error("already a global identifier");
@ -2208,11 +2139,8 @@ local_id:
delete [] $1;
}
else
{
$$ = install_ID($1, current_module.c_str(),
false, false).release();
else {
$$ = install_ID($1, current_module.c_str(), false, false).release();
}
}
;
@ -2240,13 +2168,11 @@ global_or_event_id:
defining_global_ID);
$$ = id.release();
if ( $$ )
{
if ( $$ ) {
if ( ! $$->IsGlobal() )
$$->Error("already a local identifier");
if ( $$->IsDeprecated() )
{
if ( $$->IsDeprecated() ) {
const auto& t = $$->GetType();
if ( t->Tag() != TYPE_FUNC ||
@ -2257,15 +2183,12 @@ global_or_event_id:
refine_location($$);
delete [] $1;
}
else
{
else {
const char* module_name =
resolving_global_ID ?
current_module.c_str() : 0;
current_module.c_str() : nullptr;
$$ = install_ID($1, module_name,
true, is_export).release();
$$ = install_ID($1, module_name, true, is_export).release();
}
}
;
@ -2290,8 +2213,7 @@ lookup_identifier:
|
TOK_GLOBAL_ID
{
if ( is_export )
{
if ( is_export ) {
reporter->Error("cannot use :: prefix in export section: %s", $1);
YYERROR;
}
@ -2328,8 +2250,7 @@ opt_deprecated:
{
if ( IsString($3->GetType()->Tag()) )
$$ = new ConstExpr({AdoptRef{}, $3});
else
{
else {
ODesc d;
$3->Describe(&d);
reporter->Error("'&deprecated=%s' must use a string literal",
@ -2347,29 +2268,24 @@ expr_list_opt_comma: ',' { expr_list_has_opt_comma = 1; }
%%
int yyerror(const char msg[])
{
int yyerror(const char msg[]) {
if ( in_debug )
g_curr_debug_error = util::copy_string(msg);
if ( last_tok[0] == '\n' )
reporter->Error("%s, on previous line", msg);
else if ( last_tok[0] == '\0' )
{
else if ( last_tok[0] == '\0' ) {
if ( last_filename )
reporter->Error("%s, at end of file %s", msg, last_filename);
else
reporter->Error("%s, at end of file", msg);
}
else
{
if ( last_last_tok_filename && last_tok_filename &&
! util::streq(last_last_tok_filename, last_tok_filename) )
reporter->Error("%s, at or near \"%s\" or end of file %s",
msg, last_tok, last_last_tok_filename);
else {
if ( last_last_tok_filename && last_tok_filename && ! util::streq(last_last_tok_filename, last_tok_filename) )
reporter->Error("%s, at or near \"%s\" or end of file %s", msg, last_tok, last_last_tok_filename);
else
reporter->Error("%s, at or near \"%s\"", msg, last_tok);
}
return 0;
}
}

View file

@ -9,7 +9,6 @@
#include "zeek/EquivClass.h"
#include "zeek/Reporter.h"
namespace zeek::detail {
constexpr int csize = 256;
bool re_syntax_error = 0;
@ -69,17 +68,13 @@ singleton : singleton '*'
{
if ( $3 > $5 || $3 < 0 )
zeek::detail::synerr("bad iteration values");
else
{
if ( $3 == 0 )
{
if ( $5 == 0 )
{
else {
if ( $3 == 0 ) {
if ( $5 == 0 ) {
$$ = new zeek::detail::NFA_Machine(new zeek::detail::EpsilonState());
Unref($1);
}
else
{
else {
$1->MakeRepl(1, $5);
$1->MakeOptional();
}
@ -105,8 +100,7 @@ singleton : singleton '*'
{
if ( $3 < 0 )
zeek::detail::synerr("iteration value must be positive");
else if ( $3 == 0 )
{
else if ( $3 == 0 ) {
Unref($1);
$$ = new zeek::detail::NFA_Machine(new zeek::detail::EpsilonState());
}
@ -146,8 +140,7 @@ singleton : singleton '*'
{
auto sym = $1;
if ( sym < 0 || ( sym >= NUM_SYM && sym != SYM_EPSILON ) )
{
if ( sym < 0 || ( sym >= NUM_SYM && sym != SYM_EPSILON ) ) {
zeek::reporter->Error("bad symbol %d (compiling pattern /%s/)", sym,
zeek::detail::RE_parse_input);
return 1;
@ -184,28 +177,22 @@ ccl : ccl TOK_CHAR '-' TOK_CHAR
if ( $2 > $4 )
zeek::detail::synerr("negative range in character class");
else if ( zeek::detail::case_insensitive &&
(isalpha($2) || isalpha($4)) )
{
if ( isalpha($2) && isalpha($4) &&
isupper($2) == isupper($4) )
{ // Compatible range, do both versions
else if ( zeek::detail::case_insensitive && (isalpha($2) || isalpha($4)) ) {
if ( isalpha($2) && isalpha($4) && isupper($2) == isupper($4) ) {
// Compatible range, do both versions
int l2 = tolower($2);
int l4 = tolower($4);
for ( int i = l2; i<= l4; ++i )
{
for ( int i = l2; i<= l4; ++i ) {
$1->Add(i);
$1->Add(toupper(i));
}
}
else
zeek::detail::synerr("ambiguous case-insensitive character class");
}
else
{
else {
for ( int i = $2; i <= $4; ++i )
$1->Add(i);
}
@ -213,8 +200,7 @@ ccl : ccl TOK_CHAR '-' TOK_CHAR
| ccl TOK_CHAR
{
if ( zeek::detail::case_insensitive && isalpha($2) )
{
if ( zeek::detail::case_insensitive && isalpha($2) ) {
$1->Add(zeek::detail::clower($2));
$1->Add(zeek::detail::cupper($2));
}

View file

@ -69,15 +69,13 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
"["({FIRST_CCL_CHAR}|{CCL_EXPR})({CCL_CHAR}|{CCL_EXPR})* {
zeek::detail::curr_ccl = zeek::detail::rem->LookupCCL(yytext);
if ( zeek::detail::curr_ccl )
{
if ( zeek::detail::curr_ccl ) {
if ( yyinput() != ']' )
zeek::detail::synerr("bad character class");
yylval.ccl_val = zeek::detail::curr_ccl;
return TOK_CCL;
}
else
{
else {
zeek::detail::curr_ccl = new zeek::detail::CCL();
zeek::detail::rem->InsertCCL(yytext, zeek::detail::curr_ccl);
@ -99,22 +97,19 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
if ( namedef.empty() )
zeek::detail::synerr("undefined definition");
else
{ // push back name surrounded by ()'s
else {
// push back name surrounded by ()'s
int len = namedef.size();
if ( namedef[0] == '^' ||
(len > 0 && namedef[len - 1] == '$') )
{ // don't use ()'s after all
if ( namedef[0] == '^' || (len > 0 && namedef[len - 1] == '$') ) {
// don't use ()'s after all
for ( int i = len - 1; i >= 0; --i )
unput(namedef[i]);
if ( namedef[0] == '^' )
yy_set_bol(1);
}
else
{
else {
unput(')');
for ( int i = len - 1; i >= 0; --i )
unput(namedef[i]);
@ -127,8 +122,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
"(?s:" zeek::detail::re_single_line = true; return TOK_SINGLE_LINE;
[a-zA-Z] {
if ( zeek::detail::case_insensitive )
{
if ( zeek::detail::case_insensitive ) {
char c = yytext[0]; // unput trashes yytext!
// Push back the character inside a CCL,
// so the parser can then expand it.
@ -136,8 +130,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
unput(c);
unput('[');
}
else
{
else {
yylval.int_val = yytext[0];
return TOK_CHAR;
}
@ -238,13 +231,11 @@ CCL_EXPR ("[:"[[:alpha:]]+":]")
YY_BUFFER_STATE RE_buf;
void RE_set_input(const char* str)
{
void RE_set_input(const char* str) {
zeek::detail::RE_parse_input = str;
RE_buf = yy_scan_string(str);
}
}
void RE_done_with_scan()
{
void RE_done_with_scan() {
yy_delete_buffer(RE_buf);
}
}

View file

@ -19,17 +19,17 @@ extern void end_PS();
zeek::detail::Rule* current_rule = nullptr;
const char* current_rule_file = nullptr;
static uint8_t ip4_mask_to_len(uint32_t mask)
{
static uint8_t ip4_mask_to_len(uint32_t mask) {
if ( mask == 0xffffffff )
return 32;
uint32_t x = ~mask + 1;
uint8_t len;
for ( len = 0; len < 32 && (! (x & (1 << len))); ++len );
for ( len = 0; len < 32 && (! (x & (1 << len))); ++len )
;
return 32 - len;
}
}
%}
%token TOK_COMP
@ -165,8 +165,7 @@ rule_attr:
rules_error("internal_error: unknown protocol");
}
if ( proto )
{
if ( proto ) {
auto* vallist = new zeek::detail::maskedvalue_list;
auto* val = new zeek::detail::MaskedValue();
@ -303,8 +302,7 @@ value_list:
| value_list ',' ranged_value
{
int numVals = $3->length();
for ( int idx = 0; idx < numVals; idx++ )
{
for ( int idx = 0; idx < numVals; idx++ ) {
zeek::detail::MaskedValue* val = (*$3)[idx];
$1->push_back(val);
}
@ -364,8 +362,7 @@ ranged_value:
TOK_INT '-' TOK_INT
{
$$ = new zeek::detail::maskedvalue_list();
for ( int val = $1; val <= $3; val++ )
{
for ( int val = $1; val <= $3; val++ ) {
auto* masked = new zeek::detail::MaskedValue();
masked->val = val;
masked->mask = 0xffffffff;
@ -447,29 +444,20 @@ pattern:
%%
void rules_error(const char* msg)
{
zeek::reporter->Error("Error in signature (%s:%d): %s",
current_rule_file, rules_line_number+1, msg);
void rules_error(const char* msg) {
zeek::reporter->Error("Error in signature (%s:%d): %s", current_rule_file, rules_line_number + 1, msg);
zeek::detail::rule_matcher->SetParseError();
}
}
void rules_error(const char* msg, const char* addl)
{
zeek::reporter->Error("Error in signature (%s:%d): %s (%s)",
current_rule_file, rules_line_number+1, msg, addl);
void rules_error(const char* msg, const char* addl) {
zeek::reporter->Error("Error in signature (%s:%d): %s (%s)", current_rule_file, rules_line_number + 1, msg, addl);
zeek::detail::rule_matcher->SetParseError();
}
}
void rules_error(zeek::detail::Rule* r, const char* msg)
{
void rules_error(zeek::detail::Rule* r, const char* msg) {
const zeek::detail::Location& l = r->GetLocation();
zeek::reporter->Error("Error in signature %s (%s:%d): %s",
r->ID(), l.filename, l.first_line, msg);
zeek::reporter->Error("Error in signature %s (%s:%d): %s", r->ID(), l.filename, l.first_line, msg);
zeek::detail::rule_matcher->SetParseError();
}
}
int rules_wrap(void)
{
return 1;
}
int rules_wrap(void) { return 1; }

View file

@ -204,8 +204,7 @@ finger { rules_lval.val = zeek::detail::Rule::FINGER; return TOK_PATTERN_TYPE; }
{RE} {
auto len = strlen(yytext);
if ( yytext[len - 1] == 'i' )
{
if ( yytext[len - 1] == 'i' ) {
*(yytext + len - 2) = '\0';
const char fmt[] = "(?i:%s)";
int n = len + strlen(fmt);
@ -213,8 +212,7 @@ finger { rules_lval.val = zeek::detail::Rule::FINGER; return TOK_PATTERN_TYPE; }
snprintf(s, n + 5, fmt, yytext + 1);
rules_lval.str = s;
}
else
{
else {
*(yytext + len - 1) = '\0';
rules_lval.str = zeek::util::copy_string(yytext + 1);
}
@ -227,31 +225,26 @@ finger { rules_lval.val = zeek::detail::Rule::FINGER; return TOK_PATTERN_TYPE; }
%%
// We're about to parse a Zeek policy-layer symbol.
void begin_PS()
{
void begin_PS() {
BEGIN(PS);
}
}
void end_PS()
{
void end_PS() {
BEGIN(INITIAL);
}
}
static YY_BUFFER_STATE rules_buffer;
void rules_set_input_from_buffer(const char* data, size_t size)
{
void rules_set_input_from_buffer(const char* data, size_t size) {
rules_buffer = yy_scan_bytes(data, size); // this copies the data
}
}
void rules_set_input_from_file(FILE* f)
{
void rules_set_input_from_file(FILE* f) {
rules_buffer = yy_create_buffer(f, YY_BUF_SIZE);
}
}
void rules_parse_input()
{
void rules_parse_input() {
yy_switch_to_buffer(rules_buffer);
rules_parse();
yy_delete_buffer(rules_buffer);
}
}

View file

@ -101,8 +101,7 @@ char last_tok[128];
if ( ((result = fread(buf, 1, max_size, yyin)) == 0) && ferror(yyin) ) \
zeek::reporter->Error("read failed with \"%s\"", strerror(errno));
static std::string find_relative_file(const std::string& filename, const std::string& ext)
{
static std::string find_relative_file(const std::string& filename, const std::string& ext) {
if ( filename.empty() )
return {};
@ -110,10 +109,9 @@ static std::string find_relative_file(const std::string& filename, const std::st
return zeek::util::find_file(filename, zeek::util::SafeDirname(::filename).result, ext);
else
return zeek::util::find_file(filename, zeek::util::zeek_path(), ext);
}
}
static std::string find_relative_script_file(const std::string& filename)
{
static std::string find_relative_script_file(const std::string& filename) {
if ( filename.empty() )
return {};
@ -121,10 +119,9 @@ static std::string find_relative_script_file(const std::string& filename)
return zeek::util::find_script_file(filename, zeek::util::SafeDirname(::filename).result);
else
return zeek::util::find_script_file(filename, zeek::util::zeek_path());
}
}
static void start_conditional()
{
static void start_conditional() {
++conditional_depth;
++conditional_epoch;
@ -133,11 +130,10 @@ static void start_conditional()
files_with_conditionals.insert(::filename);
current_file_has_conditionals = true;
}
}
static void do_pragma(const std::string& pragma)
{
static std::unordered_set <std::string> known_stack_pragmas = {
static void do_pragma(const std::string& pragma) {
static std::unordered_set<std::string> known_stack_pragmas = {
"ignore-deprecations",
};
@ -145,16 +141,13 @@ static void do_pragma(const std::string& pragma)
auto new_end = std::remove(parts.begin(), parts.end(), "");
parts.erase(new_end, parts.end());
if ( parts.empty() )
{
if ( parts.empty() ) {
zeek::reporter->FatalError("@pragma without value");
return;
}
if ( parts[0] == "push" )
{
if ( parts.size() < 2 )
{
if ( parts[0] == "push" ) {
if ( parts.size() < 2 ) {
zeek::reporter->FatalError("@pragma push without value");
return;
}
@ -164,10 +157,8 @@ static void do_pragma(const std::string& pragma)
pragma_stack.push_back(parts[1]);
}
else if ( parts[0] == "pop" )
{
if ( pragma_stack.empty() || pragma_stack.size() == entry_pragma_stack_depth.back() )
{
else if ( parts[0] == "pop" ) {
if ( pragma_stack.empty() || pragma_stack.size() == entry_pragma_stack_depth.back() ) {
zeek::reporter->FatalError("@pragma pop without active pragma");
return;
}
@ -175,23 +166,21 @@ static void do_pragma(const std::string& pragma)
// Popping with a value: Verify it's popping the right thing. Not providing
// a pop value itself is valid. Don't return, probably blows up below anyway.
if ( parts.size() > 1 && pragma_stack.back() != parts[1] ) {
zeek::reporter->Error("@pragma pop with unexpected '%s', expected '%s'",
parts[1].c_str(), pragma_stack.back().c_str());
zeek::reporter->Error("@pragma pop with unexpected '%s', expected '%s'", parts[1].c_str(),
pragma_stack.back().c_str());
}
// Just pop anything
pragma_stack.pop_back();
}
else
{
zeek::reporter->Warning("Ignoring unknown pragma: '%s'", pragma.c_str());
}
// Cheap: Just walk the pragma_stack now to see if we should ignore deprecations.
bool ignore_deprecations = std::any_of(pragma_stack.cbegin(), pragma_stack.cend(),
[](const auto& s) { return s == "ignore-deprecations"; });
zeek::reporter->SetIgnoreDeprecations(ignore_deprecations);
}
}
class FileInfo {
@ -211,10 +200,10 @@ public:
static zeek::PList<FileInfo> file_stack;
#define RET_CONST(v) \
{ \
{ \
yylval.val = v; \
return TOK_CONSTANT; \
}
}
// Returns true if the file is new, false if it's already been scanned.
static int load_files(const char* file);
@ -260,8 +249,7 @@ ESCSEQ (\\([^\r\n]|[0-7]+|x[[:xdigit:]]+))
}
##<.* {
if ( zeek::detail::current_scope() == zeek::detail::global_scope() )
{
if ( zeek::detail::current_scope() == zeek::detail::global_scope() ) {
std::string hint(cur_enum_type && last_id_tok ?
zeek::detail::make_full_var_name(zeek::detail::current_module.c_str(), last_id_tok) : "");
@ -413,8 +401,7 @@ when return TOK_WHEN;
auto comment = zeek::util::skip_whitespace(yytext + 11);
std::string loaded_from;
if ( num_files > 0 )
{
if ( num_files > 0 ) {
auto lf = file_stack[num_files - 1];
if ( lf->name )
loaded_from = zeek::util::fmt(" from %s:%d", lf->name, lf->line);
@ -423,7 +410,7 @@ when return TOK_WHEN;
}
zeek::reporter->Deprecation(zeek::util::fmt("deprecated script loaded%s %s", loaded_from.c_str(), comment));
}
}
@pragma.* {
do_pragma(zeek::util::skip_whitespace(yytext + 7));
@ -434,8 +421,7 @@ when return TOK_WHEN;
@DIR {
std::string rval = zeek::util::SafeDirname(::filename).result;
if ( ! rval.empty() && rval[0] == '.' )
{
if ( ! rval.empty() && rval[0] == '.' ) {
char path[MAXPATHLEN];
if ( ! getcwd(path, MAXPATHLEN) )
@ -445,11 +431,11 @@ when return TOK_WHEN;
}
RET_CONST(new zeek::StringVal(rval.c_str()));
}
}
@FILENAME {
RET_CONST(new zeek::StringVal(zeek::util::SafeBasename(::filename).result));
}
}
@load{WS}{FILE} {
const char* new_file = zeek::util::skip_whitespace(yytext + 5); // Skip "@load".
@ -457,13 +443,13 @@ when return TOK_WHEN;
std::string loading = find_relative_script_file(new_file);
(void) load_files(new_file);
zeek::detail::zeekygen_mgr->ScriptDependency(loader, loading);
}
}
@load-sigs{WS}{FILE} {
const char* file = zeek::util::skip_whitespace(yytext + 10);
std::string path = find_relative_file(file, ".sig");
sig_files.emplace_back(file, path, GetCurrentLocation());
}
}
@load-plugin{WS}{ID} {
const char* plugin = zeek::util::skip_whitespace(yytext + 12);
@ -564,8 +550,7 @@ when return TOK_WHEN;
const char* file = zeek::util::skip_whitespace(yytext + 7);
std::string path = find_relative_script_file(file);
if ( ! path.empty() && zeek::util::is_dir(path.c_str()) )
{
if ( ! path.empty() && zeek::util::is_dir(path.c_str()) ) {
// open_package() appends __load__.zeek to path and verifies existence
FILE *f = zeek::util::detail::open_package(path);
if (f)
@ -588,8 +573,7 @@ when return TOK_WHEN;
char* pref = zeek::util::skip_whitespace(yytext + 9); // Skip "@prefixes".
int append = 0;
if ( *pref == '+' )
{
if ( *pref == '+' ) {
append = 1;
++pref;
}
@ -600,7 +584,7 @@ when return TOK_WHEN;
zeek::detail::zeek_script_prefixes = { "" }; // don't delete the "" prefix
zeek::util::tokenize_string(pref, ":", &zeek::detail::zeek_script_prefixes);
}
}
@if return TOK_ATIF;
@ifdef return TOK_ATIFDEF;
@ -623,13 +607,13 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
yylval.str = zeek::util::copy_string(yytext);
last_id_tok = yylval.str;
return TOK_ID;
}
}
{GLOBAL_ID} {
yylval.str = zeek::util::copy_string(yytext);
last_id_tok = yylval.str;
return TOK_GLOBAL_ID;
}
}
{D} {
RET_CONST(zeek::val_mgr->Count(static_cast<zeek_uint_t>(strtoull(yytext, (char**) NULL, 10))).release())
@ -638,8 +622,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
{D}"/tcp" {
uint32_t p = atoi(yytext);
if ( p > 65535 )
{
if ( p > 65535 ) {
zeek::reporter->Error("bad port number - %s", yytext);
p = 0;
}
@ -647,8 +630,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
}
{D}"/udp" {
uint32_t p = atoi(yytext);
if ( p > 65535 )
{
if ( p > 65535 ) {
zeek::reporter->Error("bad port number - %s", yytext);
p = 0;
}
@ -656,8 +638,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
}
{D}"/icmp" {
uint32_t p = atoi(yytext);
if ( p > 255 )
{
if ( p > 255 ) {
zeek::reporter->Error("bad port number - %s", yytext);
p = 0;
}
@ -665,8 +646,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
}
{D}"/unknown" {
uint32_t p = atoi(yytext);
if ( p > 255 )
{
if ( p > 255 ) {
zeek::reporter->Error("bad port number - %s", yytext);
p = 0;
}
@ -692,16 +672,13 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
char* s = new char[len];
// Skip leading quote.
for ( ++text; *text; ++text )
{
if ( *text == '\\' )
{
for ( ++text; *text; ++text ) {
if ( *text == '\\' ) {
++text; // skip '\'
s[i++] = zeek::util::detail::expand_escape(text);
--text; // point to end of sequence
}
else
{
else {
s[i++] = *text;
if ( i >= len )
zeek::reporter->InternalError("bad string length computation");
@ -715,30 +692,28 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
s[i-1] = '\0';
RET_CONST(new zeek::StringVal(new zeek::String(1, (zeek::byte_vec) s, i-1)))
}
}
<RE>([^/\\\r\\\n]|{ESCSEQ})+ {
yylval.str = zeek::util::copy_string(yytext);
return TOK_PATTERN_TEXT;
}
}
<RE>"/" {
BEGIN(INITIAL);
yylval.re_modes.ignore_case = false;
yylval.re_modes.single_line = false;
return TOK_PATTERN_END;
}
}
<RE>(\/[is]{0,2}) {
BEGIN(INITIAL);
if ( strlen(yytext) == 2 )
{
if ( strlen(yytext) == 2 ) {
yylval.re_modes.ignore_case = (yytext[1] == 'i');
yylval.re_modes.single_line = (yytext[1] == 's');
}
else
{
else {
if ( yytext[1] == yytext[2] )
zeek::reporter->Error("pattern has duplicate mode %c", yytext[1]);
@ -747,7 +722,7 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
}
return TOK_PATTERN_END;
}
}
<RE>\r?\n {
zeek::reporter->Error("pattern not terminated before end of line");
@ -759,24 +734,21 @@ F RET_CONST(zeek::val_mgr->False()->Ref())
%%
YYLTYPE zeek::detail::GetCurrentLocation()
{
YYLTYPE zeek::detail::GetCurrentLocation() {
static YYLTYPE currloc;
currloc.filename = filename;
currloc.first_line = currloc.last_line = line_number;
return currloc;
}
}
void zeek::detail::SetCurrentLocation(YYLTYPE currloc)
{
void zeek::detail::SetCurrentLocation(YYLTYPE currloc) {
::filename = currloc.filename;
line_number = currloc.first_line;
}
}
static int switch_to(const char* file, YY_BUFFER_STATE buffer)
{
static int switch_to(const char* file, YY_BUFFER_STATE buffer) {
yy_switch_to_buffer(buffer);
yylloc.first_line = yylloc.last_line = line_number = 1;
@ -790,19 +762,19 @@ static int switch_to(const char* file, YY_BUFFER_STATE buffer)
entry_pragma_stack_depth.push_back(pragma_stack.size());
return 1;
}
static int load_files(const char* orig_file)
{
}
static int load_files(const char* orig_file) {
std::string file_path = find_relative_script_file(orig_file);
std::pair<int, std::optional<std::string>> rc = {-1, std::nullopt};
rc.first = PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE, HookLoadFile(zeek::plugin::Plugin::SCRIPT, orig_file, file_path), -1);
rc.first =
PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE, HookLoadFile(zeek::plugin::Plugin::SCRIPT, orig_file, file_path), -1);
if ( rc.first < 0 )
rc = PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE_EXT, HookLoadFileExtended(zeek::plugin::Plugin::SCRIPT, orig_file, file_path), std::make_pair(-1, std::nullopt));
rc = PLUGIN_HOOK_WITH_RESULT(HOOK_LOAD_FILE_EXT,
HookLoadFileExtended(zeek::plugin::Plugin::SCRIPT, orig_file, file_path),
std::make_pair(-1, std::nullopt));
if ( rc.first == 0 )
{
if ( rc.first == 0 ) {
if ( ! zeek::reporter->Errors() )
// This is just in case the plugin failed to report
// the error itself, in which case we want to at
@ -817,22 +789,18 @@ static int load_files(const char* orig_file)
FILE* f = nullptr;
if ( rc.first == -1 )
{
if ( zeek::util::streq(orig_file, "-") )
{
if ( rc.first == -1 ) {
if ( zeek::util::streq(orig_file, "-") ) {
f = stdin;
file_path = zeek::detail::ScannedFile::canonical_stdin_path;
if ( zeek::detail::g_policy_debug )
{
zeek::detail::debug_msg("Warning: can't use debugger while reading policy from stdin; turning off debugging.\n");
if ( zeek::detail::g_policy_debug ) {
zeek::detail::debug_msg(
"Warning: can't use debugger while reading policy from stdin; turning off debugging.\n");
zeek::detail::g_policy_debug = false;
}
}
else
{
else {
if ( file_path.empty() )
zeek::reporter->FatalError("can't find %s", orig_file);
@ -846,8 +814,7 @@ static int load_files(const char* orig_file)
}
zeek::detail::ScannedFile sf(file_stack.length(), file_path);
if ( sf.AlreadyScanned() )
{
if ( sf.AlreadyScanned() ) {
if ( rc.first == -1 && f != stdin )
fclose(f);
@ -857,8 +824,7 @@ static int load_files(const char* orig_file)
zeek::detail::files_scanned.push_back(std::move(sf));
}
if ( zeek::detail::g_policy_debug && ! file_path.empty() )
{
if ( zeek::detail::g_policy_debug && ! file_path.empty() ) {
// Add the filename to the file mapping table (Debug.h).
zeek::detail::Filemap* map = new zeek::detail::Filemap;
zeek::detail::g_dbgfilemaps.emplace(file_path, map);
@ -875,35 +841,32 @@ static int load_files(const char* orig_file)
// and will be zapped after the yy_switch_to_buffer() below.
YY_BUFFER_STATE buffer;
if ( rc.first == 1 )
{
if ( rc.first == 1 ) {
// Parse code provided by plugin.
assert(rc.second);
DBG_LOG(zeek::DBG_SCRIPTS, "Loading %s from code supplied by plugin ", file_path.c_str());
buffer = yy_scan_bytes(rc.second->data(), rc.second->size()); // this copies the data
}
else
{
else {
// Parse from file.
assert(f);
DBG_LOG(zeek::DBG_SCRIPTS, "Loading %s", file_path.c_str());
buffer = yy_create_buffer(f, YY_BUF_SIZE);
}
return switch_to(file_path.c_str(), buffer);
}
yy_switch_to_buffer(buffer);
yylloc.first_line = yylloc.last_line = line_number = 1;
void begin_RE()
{
BEGIN(RE);
}
return switch_to(file_path.c_str(), buffer);
}
void begin_RE() { BEGIN(RE); }
class LocalNameFinder final : public zeek::detail::TraversalCallback {
public:
LocalNameFinder() = default;
zeek::detail::TraversalCode PreExpr(const zeek::detail::Expr* expr) override
{
zeek::detail::TraversalCode PreExpr(const zeek::detail::Expr* expr) override {
if ( expr->Tag() != EXPR_NAME )
return zeek::detail::TC_CONTINUE;
@ -919,20 +882,17 @@ public:
std::vector<const zeek::detail::NameExpr*> local_names;
};
static void begin_ignoring()
{
static void begin_ignoring() {
if_stack.push_back(conditional_depth);
BEGIN(IGNORE);
}
}
static void resume_processing()
{
static void resume_processing() {
if_stack.pop_back();
BEGIN(INITIAL);
}
}
void do_atif(zeek::detail::Expr* expr)
{
void do_atif(zeek::detail::Expr* expr) {
start_conditional();
LocalNameFinder cb;
@ -941,24 +901,21 @@ void do_atif(zeek::detail::Expr* expr)
if ( cb.local_names.empty() )
val = expr->Eval(nullptr);
else
{
else {
for ( size_t i = 0; i < cb.local_names.size(); ++i )
cb.local_names[i]->Error("referencing a local name in @if");
}
if ( ! val )
{
if ( ! val ) {
expr->Error("invalid expression in @if");
return;
}
if ( ! val->AsBool() )
begin_ignoring();
}
}
void do_atifdef(const char* id)
{
void do_atifdef(const char* id) {
start_conditional();
const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str());
@ -970,10 +927,9 @@ void do_atifdef(const char* id)
if ( ! found )
begin_ignoring();
}
}
void do_atifndef(const char *id)
{
void do_atifndef(const char* id) {
start_conditional();
const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str());
@ -985,10 +941,9 @@ void do_atifndef(const char *id)
if ( found )
begin_ignoring();
}
}
void do_atelse()
{
void do_atelse() {
if ( conditional_depth == 0 )
zeek::reporter->Error("@else without @if...");
@ -999,10 +954,9 @@ void do_atelse()
begin_ignoring();
else
resume_processing();
}
}
void do_atendif()
{
void do_atendif() {
if ( conditional_depth <= entry_cond_depth.back() )
zeek::reporter->Error("unbalanced @if... @endif");
@ -1010,53 +964,47 @@ void do_atendif()
resume_processing();
--conditional_depth;
}
}
// If the given Stmt is a directive, trigger an error so that its usage is rejected.
void reject_directive(zeek::detail::Stmt* s)
{
void reject_directive(zeek::detail::Stmt* s) {
if ( s->Tag() == STMT_NULL )
if ( s->AsNullStmt()->IsDirective() )
zeek::reporter->Error("incorrect use of directive");
}
}
void add_essential_input_file(const char* file)
{
void add_essential_input_file(const char* file) {
if ( ! file )
zeek::reporter->InternalError("empty filename");
if ( ! filename )
(void) load_files(file);
(void)load_files(file);
else
essential_input_files.push_back(zeek::util::copy_string(file));
}
}
void add_input_file(const char* file)
{
void add_input_file(const char* file) {
if ( ! file )
zeek::reporter->InternalError("empty filename");
if ( ! filename )
(void) load_files(file);
(void)load_files(file);
else
input_files.push_back(zeek::util::copy_string(file));
}
}
void add_input_file_at_front(const char* file)
{
void add_input_file_at_front(const char* file) {
if ( ! file )
zeek::reporter->InternalError("empty filename");
if ( ! filename )
(void) load_files(file);
(void)load_files(file);
else
input_files.push_front(zeek::util::copy_string(file));
}
}
void add_to_name_list(char* s, char delim, zeek::name_list& nl)
{
while ( s )
{
void add_to_name_list(char* s, char delim, zeek::name_list& nl) {
while ( s ) {
char* s_delim = strchr(s, delim);
if ( s_delim )
*s_delim = 0;
@ -1068,19 +1016,16 @@ void add_to_name_list(char* s, char delim, zeek::name_list& nl)
else
break;
}
}
}
int yywrap()
{
if ( entry_cond_depth.size() > 0 )
{
int yywrap() {
if ( entry_cond_depth.size() > 0 ) {
if ( conditional_depth > entry_cond_depth.back() )
zeek::reporter->FatalError("unbalanced @if... @endif");
entry_cond_depth.pop_back();
}
if ( entry_pragma_stack_depth.size() > 0 )
{
if ( entry_pragma_stack_depth.size() > 0 ) {
if ( pragma_stack.size() > entry_pragma_stack_depth.back() )
zeek::reporter->FatalError("unbalanced @pragma push pop in file");
@ -1097,30 +1042,26 @@ int yywrap()
if ( file_stack.length() > 0 )
delete file_stack.remove_nth(file_stack.length() - 1);
if ( YY_CURRENT_BUFFER )
{
if ( YY_CURRENT_BUFFER ) {
// There's more on the stack to scan.
current_file_has_conditionals = files_with_conditionals.count(::filename) > 0;
return 0;
}
// Stack is now empty.
while ( essential_input_files.length() > 0 || input_files.length() > 0 )
{
zeek::name_list& files = essential_input_files.length() > 0 ?
essential_input_files : input_files;
while ( essential_input_files.length() > 0 || input_files.length() > 0 ) {
zeek::name_list& files = essential_input_files.length() > 0 ? essential_input_files : input_files;
if ( load_files(files[0]) )
{
if ( load_files(files[0]) ) {
// Don't delete the filename - it's pointed to by
// every Obj created when parsing it.
(void) files.remove_nth(0);
(void)files.remove_nth(0);
return 0;
}
// We already scanned the file. Pop it and try the next,
// if any.
(void) files.remove_nth(0);
(void)files.remove_nth(0);
}
// For each file scanned so far, and for each @prefix, look for a
@ -1131,15 +1072,13 @@ int yywrap()
// file name is discarded. If the prefix is non-empty, it gets placed
// in front of the flattened path, separated with another '.'
bool found_prefixed_files = false;
for ( auto& scanned_file : zeek::detail::files_scanned )
{
for ( auto& scanned_file : zeek::detail::files_scanned ) {
if ( scanned_file.skipped || scanned_file.prefixes_checked )
continue;
scanned_file.prefixes_checked = true;
// Prefixes are pushed onto a stack, so iterate backwards.
for ( int i = zeek::detail::zeek_script_prefixes.size() - 1; i >= 0; --i )
{
for ( int i = zeek::detail::zeek_script_prefixes.size() - 1; i >= 0; --i ) {
// Don't look at empty prefixes.
if ( ! zeek::detail::zeek_script_prefixes[i][0] )
continue;
@ -1148,18 +1087,17 @@ int yywrap()
std::string flat = zeek::util::detail::flatten_script_name(canon, zeek::detail::zeek_script_prefixes[i]);
std::string path = find_relative_script_file(flat);
if ( ! path.empty() )
{
if ( ! path.empty() ) {
add_input_file(path.c_str());
found_prefixed_files = true;
}
//printf("====== prefix search ======\n");
//printf("File : %s\n", scanned_file.name.c_str());
//printf("Canon : %s\n", canon.c_str());
//printf("Flat : %s\n", flat.c_str());
//printf("Found : %s\n", path.empty() ? "F" : "T");
//printf("===========================\n");
// printf("====== prefix search ======\n");
// printf("File : %s\n", scanned_file.name.c_str());
// printf("Canon : %s\n", canon.c_str());
// printf("Flat : %s\n", flat.c_str());
// printf("Found : %s\n", path.empty() ? "F" : "T");
// printf("===========================\n");
}
}
@ -1167,15 +1105,14 @@ int yywrap()
return 0;
// Add redef statements for any X=Y command line parameters.
if ( ! zeek::detail::params.empty() )
{
if ( ! zeek::detail::params.empty() ) {
std::string policy;
for ( const auto& pi : zeek::detail::params )
{
for ( const auto& pi : zeek::detail::params ) {
auto p = pi.data();
while ( isalnum(*p) || *p == '_' || *p == ':' ) ++p;
while ( isalnum(*p) || *p == '_' || *p == ':' )
++p;
auto first_non_id_char = p - pi.data();
auto eq_idx = pi.find('=', first_non_id_char);
@ -1185,10 +1122,8 @@ int yywrap()
auto val_str = pi.substr(eq_idx + 1);
const auto& id = zeek::id::find(id_str);
if ( ! id )
{
zeek::reporter->Error("unknown identifier '%s' in command-line options",
id_str.data());
if ( ! id ) {
zeek::reporter->Error("unknown identifier '%s' in command-line options", id_str.data());
continue;
}
@ -1196,23 +1131,24 @@ int yywrap()
// So far, that just means quoting the value for string types.
const auto& type = id->GetType();
if ( ! type )
{
zeek::reporter->Error("can't set value of '%s' in command-line "
"options: unknown type", id_str.data());
if ( ! type ) {
zeek::reporter->Error(
"can't set value of '%s' in command-line "
"options: unknown type",
id_str.data());
continue;
}
if ( val_str.empty() && ! zeek::IsString(type->Tag()) )
{
zeek::reporter->Error("must assign non-empty value to '%s' in "
"command-line options", id_str.data());
if ( val_str.empty() && ! zeek::IsString(type->Tag()) ) {
zeek::reporter->Error(
"must assign non-empty value to '%s' in "
"command-line options",
id_str.data());
continue;
}
auto use_quotes = zeek::IsString(type->Tag());
auto fmt_str = use_quotes ? "redef %s %s= \"%s\";"
: "redef %s %s= %s;";
auto fmt_str = use_quotes ? "redef %s %s= \"%s\";" : "redef %s %s= %s;";
policy += zeek::util::fmt(fmt_str, id_str.data(), op.data(), val_str.data());
}
@ -1228,15 +1164,14 @@ int yywrap()
// Use a synthetic filename, and add an extra semicolon on its own
// line (so that things like @load work), so that a semicolon is
// not strictly necessary.
if ( zeek::detail::command_line_policy )
{
if ( zeek::detail::command_line_policy ) {
int tmp_len = strlen(zeek::detail::command_line_policy) + 32;
char* tmp = new char[tmp_len];
snprintf(tmp, tmp_len, "%s\n;\n", zeek::detail::command_line_policy);
yylloc.filename = filename = "<command line>";
yy_scan_string(tmp);
delete [] tmp;
delete[] tmp;
// Make sure we do not get here again:
zeek::detail::command_line_policy = 0;
@ -1246,18 +1181,16 @@ int yywrap()
// Otherwise, we are done.
return 1;
}
}
FileInfo::FileInfo(std::string arg_restore_module)
{
FileInfo::FileInfo(std::string arg_restore_module) {
buffer_state = YY_CURRENT_BUFFER;
restore_module = arg_restore_module;
name = ::filename;
line = ::line_number;
}
}
FileInfo::~FileInfo()
{
FileInfo::~FileInfo() {
if ( yyin && yyin != stdin )
fclose(yyin);
@ -1267,4 +1200,4 @@ FileInfo::~FileInfo()
if ( restore_module != "" )
zeek::detail::current_module = restore_module;
}
}