diff --git a/src/parse.y b/src/parse.y index bc90f20dec..c878e9d3b7 100644 --- a/src/parse.y +++ b/src/parse.y @@ -82,31 +82,30 @@ %type opt_assert_msg %{ +#include #include #include -#include - #include #include -#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* filename; // Absolute path of file currently being parsed. extern const char* last_filename; // Absolute path of last file parsed. extern const char* last_tok_filename; extern const char* last_last_tok_filename; @@ -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,199 +160,168 @@ 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) - { - // Starting a new enum definition. - assert(cur_enum_type == nullptr); +static void parse_new_enum(void) { + // Starting a new enum definition. + assert(cur_enum_type == nullptr); - 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"); - } + 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) - { - // Redef an enum. id points to the enum to be redefined. - // Let cur_enum_type point to it. - assert(cur_enum_type == nullptr); +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); - // abort on errors; enums need to be accessible to continue parsing - if ( ! id->GetType() ) - reporter->FatalError("unknown enum identifier \"%s\"", id->Name()); - 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(); - } - } + // abort on errors; enums need to be accessible to continue parsing + if ( ! id->GetType() ) + reporter->FatalError("unknown enum identifier \"%s\"", id->Name()); + 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> attrs) - { - if ( ! id->GetType() ) - { - reporter->FatalError("unknown record identifier \"%s\"", id->Name()); - return; - } + std::unique_ptr> 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())); - 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())); + return; + } - auto rt = t->AsRecordType(); - auto idx = rt->FieldOffset(field); - if ( idx < 0 ) - { - reporter->FatalError("field \"%s\" not in record \"%s\"", field, id->Name()); - return; - } + auto rt = t->AsRecordType(); + auto idx = rt->FieldOffset(field); + if ( idx < 0 ) { + reporter->FatalError("field \"%s\" not in record \"%s\"", field, id->Name()); + return; + } - auto decl = rt->FieldDecl(idx); - if ( ! decl->attrs ) - if ( ic == INIT_EXTRA ) - decl->attrs = make_intrusive(decl->type, - true /* in_record */, - false /* is_global */); + auto decl = rt->FieldDecl(idx); + if ( ! decl->attrs ) + if ( ic == INIT_EXTRA ) + decl->attrs = make_intrusive(decl->type, true /* in_record */, false /* is_global */); - for ( const auto& attr : *attrs ) - { - // At this point, only support &log redef'ing. - if ( attr->Tag() != ATTR_LOG ) - { - reporter->FatalError("Can only redef \"&log\" attributes of record fields"); - return; - } + for ( const auto& attr : *attrs ) { + // At this point, only support &log redef'ing. + if ( attr->Tag() != ATTR_LOG ) { + reporter->FatalError("Can only redef \"&log\" attributes of record fields"); + return; + } - if ( ic == INIT_EXTRA ) - decl->attrs->AddAttr(attr, true /* is_redef */); - else - // Removing attributes is a noop if they don't exist. - if ( decl->attrs ) - decl->attrs->RemoveAttr(attr->Tag()); - } - } + if ( ic == INIT_EXTRA ) + decl->attrs->AddAttr(attr, true /* is_redef */); + else + // Removing attributes is a noop if they don't exist. + if ( decl->attrs ) + decl->attrs->RemoveAttr(attr->Tag()); + } +} -static void extend_record(ID* id, std::unique_ptr fields, - std::unique_ptr> attrs) - { - const auto& types = Type::Aliases(id->Name()); +static void extend_record(ID* id, std::unique_ptr fields, std::unique_ptr> attrs) { + const auto& types = Type::Aliases(id->Name()); - if ( types.empty() ) - { - id->Error("failed to redef record: no types found in alias map"); - return; - } + if ( types.empty() ) { + id->Error("failed to redef record: no types found in alias map"); + return; + } - bool add_log_attr = false; + bool add_log_attr = false; - if ( attrs ) - for ( const auto& at : *attrs ) - if ( at->Tag() == ATTR_LOG ) - { - add_log_attr = true; - break; - } + if ( attrs ) + for ( const auto& at : *attrs ) + if ( at->Tag() == ATTR_LOG ) { + add_log_attr = true; + break; + } - for ( const auto& t : types ) - { - auto error = t->AsRecordType()->AddFields(*fields, add_log_attr); + for ( const auto& t : types ) { + auto error = t->AsRecordType()->AddFields(*fields, add_log_attr); - if ( error ) - { - id->Error(error); - break; - } - } - } + if ( error ) { + id->Error(error); + break; + } + } +} -static AttributesPtr -make_attributes(std::vector* attrs, - TypePtr t, bool in_record, bool is_global) - { - if ( ! attrs ) - return nullptr; +static AttributesPtr make_attributes(std::vector* attrs, TypePtr t, bool in_record, bool is_global) { + if ( ! attrs ) + return nullptr; - auto rval = make_intrusive(std::move(*attrs), std::move(t), - in_record, is_global); - delete attrs; - return rval; - } + auto rval = make_intrusive(std::move(*attrs), std::move(t), in_record, is_global); + delete attrs; + return rval; +} -static bool expr_is_table_type_name(const Expr* expr) - { - if ( expr->Tag() != EXPR_NAME ) - return false; +static bool expr_is_table_type_name(const Expr* expr) { + if ( expr->Tag() != EXPR_NAME ) + return false; - const auto& type = expr->GetType(); + const auto& type = expr->GetType(); - if ( type->IsTable() ) - return true; + if ( type->IsTable() ) + return true; - if ( type->Tag() == TYPE_TYPE ) - return type->AsTypeType()->GetType()->IsTable(); + if ( type->Tag() == TYPE_TYPE ) + return type->AsTypeType()->GetType()->IsTable(); - return false; - } + return false; +} -static void check_loop_var(const IDPtr& var) - { - if ( var->IsGlobal() ) - var->Error("global variable used in 'for' loop"); +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"); - } + if ( var->IsConst() ) + var->Error("constant used in 'for' loop"); +} -static void build_global(ID* id, Type* t, InitClass ic, Expr* e, - std::vector* attrs, DeclType dt) - { - IDPtr id_ptr{AdoptRef{}, id}; - TypePtr t_ptr{AdoptRef{}, t}; - ExprPtr e_ptr{AdoptRef{}, e}; +static void build_global(ID* id, Type* t, InitClass ic, Expr* e, std::vector* attrs, DeclType dt) { + IDPtr id_ptr{AdoptRef{}, id}; + TypePtr t_ptr{AdoptRef{}, t}; + ExprPtr e_ptr{AdoptRef{}, e}; - auto attrs_ptr = attrs ? std::make_unique>(*attrs) : nullptr; + auto attrs_ptr = attrs ? std::make_unique>(*attrs) : nullptr; - add_global(id_ptr, std::move(t_ptr), ic, e_ptr, std::move(attrs_ptr), dt); + add_global(id_ptr, std::move(t_ptr), ic, e_ptr, std::move(attrs_ptr), dt); - if ( dt == VAR_REDEF ) - zeekygen_mgr->Redef(id, ::filename, ic, std::move(e_ptr)); - else - zeekygen_mgr->Identifier(std::move(id_ptr)); - } + if ( dt == VAR_REDEF ) + 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* attrs, DeclType dt, - bool do_coverage) - { - IDPtr id_ptr{AdoptRef{}, id}; - TypePtr t_ptr{AdoptRef{}, t}; - ExprPtr e_ptr{AdoptRef{}, e}; +static StmtPtr build_local(ID* id, Type* t, InitClass ic, Expr* e, std::vector* 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>(*attrs) : nullptr; + auto attrs_ptr = attrs ? std::make_unique>(*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()); + if ( do_coverage ) + script_coverage_mgr.AddStmt(init.get()); - return init; - } + return init; +} -static void refine_location(zeek::detail::ID* id) - { - if ( *id->GetLocationInfo() == zeek::detail::no_location ) - id->SetLocationInfo(&detail::start_location, &detail::end_location); - } +static void refine_location(zeek::detail::ID* id) { + if ( *id->GetLocationInfo() == zeek::detail::no_location ) + id->SetLocationInfo(&detail::start_location, &detail::end_location); +} %} @@ -384,11 +351,10 @@ 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; + } re_modes; } %% @@ -549,36 +515,31 @@ 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(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; - } } } + } | '+' expr %prec '!' { @@ -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. @@ -611,7 +571,7 @@ expr: sum = make_intrusive(sum, tag1); $$ = new AssignExpr(lhs, sum, false); - } + } else $$ = new AddToExpr(lhs, rhs); } @@ -630,15 +590,14 @@ expr: ExprPtr rhs = {AdoptRef{}, $3}; auto tag1 = $1->GetType()->Tag(); - if ( IsArithmetic(tag1) ) - { + if ( IsArithmetic(tag1) ) { ExprPtr sum = make_intrusive(lhs, rhs); if ( sum->GetType()->Tag() != tag1 ) sum = make_intrusive(sum, tag1); $$ = new AssignExpr(lhs, sum, false); - } + } else $$ = new RemoveFromExpr(lhs, rhs); } @@ -773,7 +732,7 @@ expr: { set_location(@2, @4); if ( ! locals_at_this_scope.empty() ) - locals_at_this_scope.back().insert($2); + locals_at_this_scope.back().insert($2); $$ = add_and_assign_local({AdoptRef{}, $2}, {AdoptRef{}, $4}, val_mgr->True()).release(); } @@ -806,7 +765,7 @@ expr: func_hdr_location = @1; $3->SetInferReturnType(true); } - lambda_body + lambda_body { $$ = new FieldAssignExpr($2, IntrusivePtr{AdoptRef{}, $6}); } @@ -836,14 +795,12 @@ 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; - } } + } if ( is_record_ctor ) $$ = new RecordConstructorExpr({AdoptRef{}, $2}); @@ -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(ctor_type); $$ = new RecordConstructorExpr(rt, ListExprPtr{AdoptRef{}, $4}); - } break; + } case TYPE_TABLE: if ( ctor_type->IsTable() ) @@ -922,7 +878,7 @@ expr: $1->Error("constructor type not implemented"); YYERROR; } - } + } else $$ = new CallExpr({AdoptRef{}, $1}, {AdoptRef{}, $4}, in_hook > 0, in_when_cond); @@ -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); @@ -971,54 +925,46 @@ 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; - } + } EnumType* t = id->GetType()->AsEnumType(); auto intval = t->Lookup(id->ModuleName(), id->Name()); if ( intval < 0 ) 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"); $$ = new NameExpr(std::move(id)); - } } } + } | TOK_CONSTANT { @@ -1050,20 +996,20 @@ expr: $$ = new ConstExpr(make_intrusive(re)); } - | '|' expr '|' %prec '(' + | '|' expr '|' %prec '(' { set_location(@1, @3); ExprPtr e{AdoptRef{}, $2}; $$ = new SizeExpr(std::move(e)); } - | expr TOK_AS type + | expr TOK_AS type { set_location(@1, @3); $$ = new CastExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); } - | expr TOK_IS type + | expr TOK_IS type { set_location(@1, @3); $$ = new IsExpr({AdoptRef{}, $1}, {AdoptRef{}, $3}); @@ -1162,182 +1108,180 @@ enum_body_elem: simple_type: TOK_BOOL - { - set_location(@1); - $$ = base_type(TYPE_BOOL)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_BOOL)->Ref(); + } | TOK_INT - { - set_location(@1); - $$ = base_type(TYPE_INT)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_INT)->Ref(); + } | TOK_COUNT - { - set_location(@1); - $$ = base_type(TYPE_COUNT)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_COUNT)->Ref(); + } | TOK_DOUBLE - { - set_location(@1); - $$ = base_type(TYPE_DOUBLE)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_DOUBLE)->Ref(); + } | TOK_TIME - { - set_location(@1); - $$ = base_type(TYPE_TIME)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_TIME)->Ref(); + } | TOK_INTERVAL - { - set_location(@1); - $$ = base_type(TYPE_INTERVAL)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_INTERVAL)->Ref(); + } | TOK_STRING - { - set_location(@1); - $$ = base_type(TYPE_STRING)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_STRING)->Ref(); + } | TOK_PATTERN - { - set_location(@1); - $$ = base_type(TYPE_PATTERN)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_PATTERN)->Ref(); + } | TOK_PORT - { - set_location(@1); - $$ = base_type(TYPE_PORT)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_PORT)->Ref(); + } | TOK_ADDR - { - set_location(@1); - $$ = base_type(TYPE_ADDR)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_ADDR)->Ref(); + } | TOK_SUBNET - { - set_location(@1); - $$ = base_type(TYPE_SUBNET)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_SUBNET)->Ref(); + } | TOK_ANY - { - set_location(@1); - $$ = base_type(TYPE_ANY)->Ref(); - } + { + set_location(@1); + $$ = base_type(TYPE_ANY)->Ref(); + } | TOK_TABLE '[' type_list ']' TOK_OF type - { - set_location(@1, @6); - $$ = new TableType({AdoptRef{}, $3}, {AdoptRef{}, $6}); - } + { + set_location(@1, @6); + $$ = new TableType({AdoptRef{}, $3}, {AdoptRef{}, $6}); + } | TOK_SET '[' type_list ']' - { - set_location(@1, @4); - $$ = new SetType({AdoptRef{}, $3}, nullptr); - } + { + set_location(@1, @4); + $$ = new SetType({AdoptRef{}, $3}, nullptr); + } | TOK_RECORD '{' { ++in_record; } type_decl_list { --in_record; } '}' - { - set_location(@1, @5); - $$ = new RecordType($4); - } + { + set_location(@1, @5); + $$ = new RecordType($4); + } | TOK_ENUM '{' { set_location(@1); parse_new_enum(); } enum_body '}' - { - set_location(@1, @5); - $4->UpdateLocationEndInfo(@5); - $$ = $4; - } + { + set_location(@1, @5); + $4->UpdateLocationEndInfo(@5); + $$ = $4; + } | TOK_LIST - { - set_location(@1); - // $$ = new TypeList(); - reporter->Error("list type not implemented"); - $$ = 0; - } + { + set_location(@1); + // $$ = new TypeList(); + reporter->Error("list type not implemented"); + $$ = 0; + } | TOK_LIST TOK_OF type - { - set_location(@1); - // $$ = new TypeList($3); - reporter->Error("list type not implemented"); - $$ = 0; - } + { + set_location(@1); + // $$ = new TypeList($3); + reporter->Error("list type not implemented"); + $$ = 0; + } | TOK_VECTOR TOK_OF type - { - set_location(@1, @3); - $$ = new VectorType({AdoptRef{}, $3}); - } + { + set_location(@1, @3); + $$ = new VectorType({AdoptRef{}, $3}); + } | TOK_FILE TOK_OF type - { - set_location(@1, @3); - $$ = new FileType({AdoptRef{}, $3}); - } + { + set_location(@1, @3); + $$ = new FileType({AdoptRef{}, $3}); + } | TOK_FILE - { - set_location(@1); - $$ = new FileType(base_type(TYPE_STRING)); - } + { + set_location(@1); + $$ = new FileType(base_type(TYPE_STRING)); + } | TOK_OPAQUE TOK_OF TOK_ID - { - set_location(@1, @3); - $$ = new OpaqueType($3); - } + { + set_location(@1, @3); + $$ = new OpaqueType($3); + } type: simple_type | TOK_FUNCTION func_params - { - set_location(@1, @2); - $$ = $2; - } + { + set_location(@1, @2); + $$ = $2; + } | TOK_HOOK '(' formal_args ')' - { - set_location(@1, @3); - $$ = new FuncType({AdoptRef{}, $3}, base_type(TYPE_BOOL), FUNC_FLAVOR_HOOK); - } + { + set_location(@1, @3); + $$ = new FuncType({AdoptRef{}, $3}, base_type(TYPE_BOOL), FUNC_FLAVOR_HOOK); + } | TOK_EVENT '(' formal_args ')' - { - set_location(@1, @3); - $$ = new FuncType({AdoptRef{}, $3}, nullptr, FUNC_FLAVOR_EVENT); - } + { + set_location(@1, @3); + $$ = new FuncType({AdoptRef{}, $3}, nullptr, FUNC_FLAVOR_EVENT); + } | 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() ) reporter->Deprecation($1->GetDeprecationWarning()); - } + } } ; @@ -1371,7 +1315,7 @@ type_decl: if ( in_record > 0 && cur_decl_type_id ) zeekygen_mgr->RecordField(cur_decl_type_id, $$, ::filename, - in_record_redef != 0); + in_record_redef != 0); } ; @@ -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 ) @@ -1495,7 +1438,7 @@ decl: cur_decl_type_id = 0; IntrusivePtr id{AdoptRef{}, $2}; add_type(id.get(), {AdoptRef{}, $5}, - std::unique_ptr>{$6}); + std::unique_ptr>{$6}); zeekygen_mgr->Identifier(std::move(id)); } @@ -1531,16 +1474,16 @@ func_hdr: { IntrusivePtr id{AdoptRef{}, $2}; begin_func(id, current_module.c_str(), - FUNC_FLAVOR_FUNCTION, false, {NewRef{}, $3}, - std::unique_ptr>{$4}); + FUNC_FLAVOR_FUNCTION, false, {NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; zeekygen_mgr->Identifier(std::move(id)); } | TOK_EVENT event_id func_params opt_attr { begin_func({NewRef{}, $2}, current_module.c_str(), - FUNC_FLAVOR_EVENT, false, {NewRef{}, $3}, - std::unique_ptr>{$4}); + FUNC_FLAVOR_EVENT, false, {NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; } | TOK_HOOK def_global_id func_params opt_attr @@ -1548,15 +1491,15 @@ func_hdr: $3->ClearYieldType(FUNC_FLAVOR_HOOK); $3->SetYieldType(base_type(TYPE_BOOL)); begin_func({NewRef{}, $2}, current_module.c_str(), - FUNC_FLAVOR_HOOK, false, {NewRef{}, $3}, - std::unique_ptr>{$4}); + FUNC_FLAVOR_HOOK, false, {NewRef{}, $3}, + std::unique_ptr>{$4}); $$ = $3; } | TOK_REDEF TOK_EVENT event_id func_params opt_attr { begin_func({NewRef{}, $3}, current_module.c_str(), - FUNC_FLAVOR_EVENT, true, {NewRef{}, $4}, - std::unique_ptr>{$5}); + FUNC_FLAVOR_EVENT, true, {NewRef{}, $4}, + std::unique_ptr>{$5}); $$ = $4; } ; @@ -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,11 +1594,10 @@ begin_lambda: std::optional captures; - if ( $1 ) - { + if ( $1 ) { captures = *$1; delete $1; - } + } $2->SetCaptures(std::move(captures)); $$ = id.release(); @@ -1692,16 +1633,14 @@ 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; - } + } delete [] $2; @@ -1836,13 +1775,12 @@ attr: $$ = new Attr( ATTR_DEPRECATED, make_intrusive(IntrusivePtr{AdoptRef{}, $3})); - else - { + else { ODesc d; $3->Describe(&d); Unref($3); reporter->Error("'&deprecated=%s' must use a string literal", - d.Description()); + d.Description()); $$ = new Attr(ATTR_DEPRECATED); } } @@ -1865,7 +1803,7 @@ stmt: set_location(@1, @5); $$ = $4; if ( $3 ) - script_coverage_mgr.DecIgnoreDepth(); + script_coverage_mgr.DecIgnoreDepth(); } | TOK_ASSERT expr opt_assert_msg ';' @@ -1878,7 +1816,7 @@ stmt: set_location(@1, @3); $$ = new PrintStmt(IntrusivePtr{AdoptRef{}, $2}); if ( ! $4 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_EVENT event ';' opt_no_test @@ -1886,7 +1824,7 @@ stmt: set_location(@1, @3); $$ = new EventStmt({AdoptRef{}, $2}); if ( ! $4 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_IF '(' expr ')' stmt @@ -1932,7 +1870,7 @@ stmt: set_location(@1, @2); $$ = new NextStmt; if ( ! $3 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_BREAK ';' opt_no_test @@ -1940,7 +1878,7 @@ stmt: set_location(@1, @2); $$ = new BreakStmt; if ( ! $3 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_FALLTHROUGH ';' opt_no_test @@ -1956,7 +1894,7 @@ stmt: set_location(@1, @2); $$ = new ReturnStmt(0); if ( ! $3 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_RETURN expr ';' opt_no_test @@ -1964,14 +1902,14 @@ stmt: set_location(@1, @2); $$ = new ReturnStmt({AdoptRef{}, $2}); if ( ! $4 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | TOK_LOCAL local_id opt_type init_class opt_init opt_attr ';' opt_no_test { set_location(@1, @7); if ( ! locals_at_this_scope.empty() ) - locals_at_this_scope.back().insert($2); + locals_at_this_scope.back().insert($2); $$ = build_local($2, $3, $4, $5, $6, VAR_REGULAR, ! $8).release(); } @@ -2004,7 +1942,7 @@ stmt: set_location(@1, @2); $$ = new ExprStmt({AdoptRef{}, $1}); if ( ! $3 ) - script_coverage_mgr.AddStmt($$); + script_coverage_mgr.AddStmt($$); } | ';' @@ -2035,21 +1973,18 @@ 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; - } + } if ( id->IsDeprecated() ) reporter->Deprecation(id->GetDeprecationWarning()); $$ = 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,11 +2054,9 @@ 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; loop_vars->push_back(loop_var.release()); @@ -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"); @@ -2207,12 +2138,9 @@ local_id: $$->Error("already a const identifier"); 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,32 +2168,27 @@ 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 || t->AsFuncType()->Flavor() != FUNC_FLAVOR_FUNCTION ) reporter->Deprecation($$->GetDeprecationWarning()); - } + } 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,11 +2213,10 @@ lookup_identifier: | TOK_GLOBAL_ID { - if ( is_export ) - { + if ( is_export ) { reporter->Error("cannot use :: prefix in export section: %s", $1); YYERROR; - } + } } ; @@ -2328,12 +2250,11 @@ 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", - d.Description()); + d.Description()); $$ = new ConstExpr(make_intrusive("")); } } @@ -2347,29 +2268,24 @@ expr_list_opt_comma: ',' { expr_list_has_opt_comma = 1; } %% -int yyerror(const char msg[]) - { - if ( in_debug ) - g_curr_debug_error = util::copy_string(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' ) - { - 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 - reporter->Error("%s, at or near \"%s\"", msg, last_tok); - } + if ( last_tok[0] == '\n' ) + reporter->Error("%s, on previous line", msg); + 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 + reporter->Error("%s, at or near \"%s\"", msg, last_tok); + } - return 0; - } + return 0; +} diff --git a/src/re-parse.y b/src/re-parse.y index 46ba7f91d1..4dba6717cb 100644 --- a/src/re-parse.y +++ b/src/re-parse.y @@ -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,24 +68,20 @@ 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(); - } } + } else $1->MakeRepl($3, $5); - } + } } | singleton '{' TOK_NUMBER ',' '}' @@ -105,11 +100,10 @@ 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()); - } + } else $1->LinkCopies($3-1); } @@ -117,7 +111,7 @@ singleton : singleton '*' | '.' { $$ = new zeek::detail::NFA_Machine(new zeek::detail::NFA_State( - zeek::detail::rem->AnyCCL(zeek::detail::re_single_line))); + zeek::detail::rem->AnyCCL(zeek::detail::re_single_line))); } | full_ccl @@ -146,12 +140,11 @@ 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; - } + } $$ = new zeek::detail::NFA_Machine(new zeek::detail::NFA_State(sym, zeek::detail::rem->EC())); } @@ -184,40 +177,33 @@ 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); - } + } } | 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)); - } + } else $1->Add($2); } @@ -255,12 +241,12 @@ namespace zeek::detail { int cupper(int sym) { - return (isascii(sym) && islower(sym)) ? toupper(sym) : sym; + return (isascii(sym) && islower(sym)) ? toupper(sym) : sym; } int clower(int sym) { - return (isascii(sym) && isupper(sym)) ? tolower(sym) : sym; + return (isascii(sym) && isupper(sym)) ? tolower(sym) : sym; } void synerr(const char str[]) diff --git a/src/re-scan.l b/src/re-scan.l index 3056762ea7..22d961f7f2 100644 --- a/src/re-scan.l +++ b/src/re-scan.l @@ -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); @@ -87,7 +85,7 @@ CCL_EXPR ("[:"[[:alpha:]]+":]") BEGIN(SC_FIRST_CCL); return '['; - } + } } "{"{NAME}"}" { @@ -99,48 +97,43 @@ 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]); unput('('); - } } } + } "(?i:" zeek::detail::case_insensitive = true; return TOK_CASE_INSENSITIVE; "(?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. unput(']'); unput(c); unput('['); - } - else - { + } + else { yylval.int_val = yytext[0]; return TOK_CHAR; - } + } } [|*+?.(){}] return yytext[0]; @@ -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); - } +} diff --git a/src/rule-parse.y b/src/rule-parse.y index e1294d6af9..bd11a28710 100644 --- a/src/rule-parse.y +++ b/src/rule-parse.y @@ -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) - { - if ( mask == 0xffffffff ) - return 32; +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 ); + uint32_t x = ~mask + 1; + uint8_t len; + for ( len = 0; len < 32 && (! (x & (1 << len))); ++len ) + ; - return 32 - len; - } + return 32 - len; +} %} %token TOK_COMP @@ -153,20 +153,19 @@ rule_attr: { int proto = 0; switch ( $3 ) { - case zeek::detail::RuleHdrTest::ICMP: proto = IPPROTO_ICMP; break; - case zeek::detail::RuleHdrTest::ICMPv6: proto = IPPROTO_ICMPV6; break; - // signature matching against outer packet headers of IP-in-IP - // tunneling not supported, so do a no-op there - case zeek::detail::RuleHdrTest::IP: proto = 0; break; - case zeek::detail::RuleHdrTest::IPv6: proto = 0; break; - case zeek::detail::RuleHdrTest::TCP: proto = IPPROTO_TCP; break; - case zeek::detail::RuleHdrTest::UDP: proto = IPPROTO_UDP; break; - default: - rules_error("internal_error: unknown protocol"); + case zeek::detail::RuleHdrTest::ICMP: proto = IPPROTO_ICMP; break; + case zeek::detail::RuleHdrTest::ICMPv6: proto = IPPROTO_ICMPV6; break; + // signature matching against outer packet headers of IP-in-IP + // tunneling not supported, so do a no-op there + case zeek::detail::RuleHdrTest::IP: proto = 0; break; + case zeek::detail::RuleHdrTest::IPv6: proto = 0; break; + case zeek::detail::RuleHdrTest::TCP: proto = IPPROTO_TCP; break; + case zeek::detail::RuleHdrTest::UDP: proto = IPPROTO_UDP; break; + default: + rules_error("internal_error: unknown protocol"); } - if ( proto ) - { + if ( proto ) { auto* vallist = new zeek::detail::maskedvalue_list; auto* val = new zeek::detail::MaskedValue(); @@ -179,7 +178,7 @@ rule_attr: current_rule->AddHdrTest(new zeek::detail::RuleHdrTest( zeek::detail::RuleHdrTest::NEXT, 0, 0, (zeek::detail::RuleHdrTest::Comp) $2, vallist)); - } + } } | TOK_IP_PROTO TOK_COMP value_list @@ -303,11 +302,10 @@ 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); - } + } $$ = $1; } | value_list ',' TOK_IDENT @@ -364,13 +362,12 @@ 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; $$->push_back(masked); - } + } } ; @@ -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); - zeek::detail::rule_matcher->SetParseError(); - } +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); - 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); + zeek::detail::rule_matcher->SetParseError(); +} -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::detail::rule_matcher->SetParseError(); - } +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::detail::rule_matcher->SetParseError(); +} -int rules_wrap(void) - { - return 1; - } +int rules_wrap(void) { return 1; } diff --git a/src/rule-scan.l b/src/rule-scan.l index 0d023f0f44..04b8a3b1c6 100644 --- a/src/rule-scan.l +++ b/src/rule-scan.l @@ -204,17 +204,15 @@ 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); char* s = new char[n + 5 /* slop */]; 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() - { - BEGIN(PS); - } +void begin_PS() { + BEGIN(PS); +} -void end_PS() - { - BEGIN(INITIAL); - } +void end_PS() { + BEGIN(INITIAL); +} static YY_BUFFER_STATE rules_buffer; -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_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) - { - rules_buffer = yy_create_buffer(f, YY_BUF_SIZE); - } +void rules_set_input_from_file(FILE* f) { + rules_buffer = yy_create_buffer(f, YY_BUF_SIZE); +} -void rules_parse_input() - { - yy_switch_to_buffer(rules_buffer); - rules_parse(); - yy_delete_buffer(rules_buffer); - } +void rules_parse_input() { + yy_switch_to_buffer(rules_buffer); + rules_parse(); + yy_delete_buffer(rules_buffer); +} diff --git a/src/scan.l b/src/scan.l index 44cebc94b1..7c8df307f6 100644 --- a/src/scan.l +++ b/src/scan.l @@ -101,109 +101,98 @@ 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) - { - if ( filename.empty() ) - return {}; +static std::string find_relative_file(const std::string& filename, const std::string& ext) { + if ( filename.empty() ) + return {}; - if ( filename[0] == '.' ) - return zeek::util::find_file(filename, zeek::util::SafeDirname(::filename).result, ext); - else - return zeek::util::find_file(filename, zeek::util::zeek_path(), ext); - } + if ( filename[0] == '.' ) + 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) - { - if ( filename.empty() ) - return {}; +static std::string find_relative_script_file(const std::string& filename) { + if ( filename.empty() ) + return {}; - if ( filename[0] == '.' ) - return zeek::util::find_script_file(filename, zeek::util::SafeDirname(::filename).result); - else - return zeek::util::find_script_file(filename, zeek::util::zeek_path()); - } + if ( filename[0] == '.' ) + 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() - { - ++conditional_depth; - ++conditional_epoch; +static void start_conditional() { + ++conditional_depth; + ++conditional_epoch; - if ( ! current_file_has_conditionals ) - // First time we've observed that this file includes conditionals. - files_with_conditionals.insert(::filename); + if ( ! current_file_has_conditionals ) + // First time we've observed that this file includes conditionals. + files_with_conditionals.insert(::filename); - current_file_has_conditionals = true; - } + current_file_has_conditionals = true; +} -static void do_pragma(const std::string& pragma) - { - static std::unordered_set known_stack_pragmas = { - "ignore-deprecations", - }; +static void do_pragma(const std::string& pragma) { + static std::unordered_set known_stack_pragmas = { + "ignore-deprecations", + }; - auto parts = zeek::util::split(pragma, " "); - auto new_end = std::remove(parts.begin(), parts.end(), ""); - parts.erase(new_end, parts.end()); + auto parts = zeek::util::split(pragma, " "); + auto new_end = std::remove(parts.begin(), parts.end(), ""); + parts.erase(new_end, parts.end()); - if ( parts.empty() ) - { - zeek::reporter->FatalError("@pragma without value"); - return; - } + if ( parts.empty() ) { + zeek::reporter->FatalError("@pragma without value"); + return; + } - if ( parts[0] == "push" ) - { - if ( parts.size() < 2 ) - { - zeek::reporter->FatalError("@pragma push without value"); - return; - } + if ( parts[0] == "push" ) { + if ( parts.size() < 2 ) { + zeek::reporter->FatalError("@pragma push without value"); + return; + } - if ( known_stack_pragmas.count(parts[1]) == 0 ) - zeek::reporter->Warning("pushing unknown @pragma value '%s'", parts[1].c_str()); + if ( known_stack_pragmas.count(parts[1]) == 0 ) + zeek::reporter->Warning("pushing unknown @pragma value '%s'", parts[1].c_str()); - pragma_stack.push_back(parts[1]); - } - 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; - } + pragma_stack.push_back(parts[1]); + } + 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; + } - // 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()); - } + // 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()); + } - // Just pop anything - pragma_stack.pop_back(); - } - else - { - zeek::reporter->Warning("Ignoring unknown pragma: '%s'", pragma.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); - } + // 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 { public: - FileInfo(std::string restore_module = ""); - ~FileInfo(); + FileInfo(std::string restore_module = ""); + ~FileInfo(); - YY_BUFFER_STATE buffer_state; - std::string restore_module; - const char* name = nullptr; - int line = 0; - int level = 0; + YY_BUFFER_STATE buffer_state; + std::string restore_module; + const char* name = nullptr; + int line = 0; + int level = 0; }; // A stack of input buffers we're scanning. file_stack[len-1] is the @@ -211,10 +200,10 @@ public: static zeek::PList 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,13 +249,12 @@ 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) : ""); zeek::detail::zeekygen_mgr->PostComment(yytext + 3, hint); - } + } } ##.* { @@ -406,24 +394,23 @@ when return TOK_WHEN; &broker_store return TOK_ATTR_BROKER_STORE; &broker_allow_complex_type return TOK_ATTR_BROKER_STORE_ALLOW_COMPLEX; &backend return TOK_ATTR_BACKEND; -&ordered return TOK_ATTR_ORDERED; +&ordered return TOK_ATTR_ORDERED; @deprecated.* { auto num_files = file_stack.length(); 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); else loaded_from = " from command line arguments"; - } + } 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,22 +421,21 @@ 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) ) zeek::reporter->InternalError("getcwd failed: %s", strerror(errno)); else rval = std::string(path) + "/" + rval; - } + } 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,15 +550,14 @@ 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) fclose(f); else path = ""; - } + } if ( path.empty() ) zeek::reporter->Error("failed find file associated with @unload %s", file); @@ -588,11 +573,10 @@ when return TOK_WHEN; char* pref = zeek::util::skip_whitespace(yytext + 9); // Skip "@prefixes". int append = 0; - if ( *pref == '+' ) - { + if ( *pref == '+' ) { append = 1; ++pref; - } + } pref = zeek::util::skip_whitespace(pref + 1); // Skip over '='. @@ -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; - } + 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(strtoull(yytext, (char**) NULL, 10))).release()) @@ -638,40 +622,36 @@ 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; - } - RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_TCP)->Ref()) } + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_TCP)->Ref()) + } {D}"/udp" { uint32_t p = atoi(yytext); - if ( p > 65535 ) - { + if ( p > 65535 ) { zeek::reporter->Error("bad port number - %s", yytext); p = 0; - } - RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UDP)->Ref()) } + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UDP)->Ref()) + } {D}"/icmp" { uint32_t p = atoi(yytext); - if ( p > 255 ) - { + if ( p > 255 ) { zeek::reporter->Error("bad port number - %s", yytext); p = 0; - } - RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_ICMP)->Ref()) } + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_ICMP)->Ref()) + } {D}"/unknown" { uint32_t p = atoi(yytext); - if ( p > 255 ) - { + if ( p > 255 ) { zeek::reporter->Error("bad port number - %s", yytext); p = 0; - } - RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UNKNOWN)->Ref()) } + RET_CONST(zeek::val_mgr->Port(p, TRANSPORT_UNKNOWN)->Ref()) + } {FLOAT}{OWS}day(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Days)) {FLOAT}{OWS}hr(s?) RET_CONST(new zeek::IntervalVal(atof(yytext),Hours)) @@ -692,21 +672,18 @@ 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"); - } } + } // Get rid of trailing quote. if ( s[i-1] != '"' ) @@ -715,39 +692,37 @@ 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))) - } +} ([^/\\\r\\\n]|{ESCSEQ})+ { yylval.str = zeek::util::copy_string(yytext); return TOK_PATTERN_TEXT; - } +} "/" { BEGIN(INITIAL); yylval.re_modes.ignore_case = false; yylval.re_modes.single_line = false; return TOK_PATTERN_END; - } +} (\/[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]); yylval.re_modes.ignore_case = (yytext[1] == 'i' || yytext[2] == 'i'); yylval.re_modes.single_line = (yytext[1] == 's' || yytext[2] == 's'); - } + } return TOK_PATTERN_END; - } +} \r?\n { zeek::reporter->Error("pattern not terminated before end of line"); @@ -759,512 +734,470 @@ F RET_CONST(zeek::val_mgr->False()->Ref()) %% -YYLTYPE zeek::detail::GetCurrentLocation() - { - static YYLTYPE currloc; +YYLTYPE zeek::detail::GetCurrentLocation() { + static YYLTYPE currloc; - currloc.filename = filename; - currloc.first_line = currloc.last_line = line_number; + currloc.filename = filename; + currloc.first_line = currloc.last_line = line_number; - return currloc; - } + return currloc; +} -void zeek::detail::SetCurrentLocation(YYLTYPE currloc) - { - ::filename = currloc.filename; - line_number = currloc.first_line; - } +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) - { - yy_switch_to_buffer(buffer); - yylloc.first_line = yylloc.last_line = line_number = 1; +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; - // Don't delete the old filename - it's pointed to by - // every Obj created when parsing it. - yylloc.filename = filename = zeek::util::copy_string(file); + // Don't delete the old filename - it's pointed to by + // every Obj created when parsing it. + yylloc.filename = filename = zeek::util::copy_string(file); - current_file_has_conditionals = files_with_conditionals.count(filename) > 0; + current_file_has_conditionals = files_with_conditionals.count(filename) > 0; - entry_cond_depth.push_back(conditional_depth); - entry_pragma_stack_depth.push_back(pragma_stack.size()); + entry_cond_depth.push_back(conditional_depth); + entry_pragma_stack_depth.push_back(pragma_stack.size()); - return 1; - } + return 1; +} +static int load_files(const char* orig_file) { + std::string file_path = find_relative_script_file(orig_file); -static int load_files(const char* orig_file) - { - std::string file_path = find_relative_script_file(orig_file); + std::pair> rc = {-1, std::nullopt}; + 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)); - std::pair> rc = {-1, std::nullopt}; - 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)); + 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 + // least tell the user that something went wrong. + zeek::reporter->Error("Plugin reported error loading %s", orig_file); - 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 - // least tell the user that something went wrong. - zeek::reporter->Error("Plugin reported error loading %s", orig_file); + exit(1); + } - exit(1); - } + if ( rc.first == 1 && ! rc.second ) + return 0; // A plugin took care of it, just skip. - if ( rc.first == 1 && ! rc.second ) - return 0; // A plugin took care of it, just skip. + FILE* f = nullptr; - FILE* f = nullptr; + if ( rc.first == -1 ) { + if ( zeek::util::streq(orig_file, "-") ) { + f = stdin; + file_path = zeek::detail::ScannedFile::canonical_stdin_path; - 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"); + zeek::detail::g_policy_debug = false; + } + } + else { + if ( file_path.empty() ) + zeek::reporter->FatalError("can't find %s", orig_file); - 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; - } - } + if ( zeek::util::is_dir(file_path.c_str()) ) + f = zeek::util::detail::open_package(file_path); + else + f = zeek::util::open_file(file_path); - else - { - if ( file_path.empty() ) - zeek::reporter->FatalError("can't find %s", orig_file); + if ( ! f ) + zeek::reporter->FatalError("can't open %s", file_path.c_str()); + } - if ( zeek::util::is_dir(file_path.c_str()) ) - f = zeek::util::detail::open_package(file_path); - else - f = zeek::util::open_file(file_path); + zeek::detail::ScannedFile sf(file_stack.length(), file_path); + if ( sf.AlreadyScanned() ) { + if ( rc.first == -1 && f != stdin ) + fclose(f); - if ( ! f ) - zeek::reporter->FatalError("can't open %s", file_path.c_str()); - } + return 0; + } - zeek::detail::ScannedFile sf(file_stack.length(), file_path); - if ( sf.AlreadyScanned() ) - { - if ( rc.first == -1 && f != stdin ) - fclose(f); + zeek::detail::files_scanned.push_back(std::move(sf)); + } - return 0; - } + 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); + LoadPolicyFileText(file_path.c_str(), rc.second); + } - zeek::detail::files_scanned.push_back(std::move(sf)); - } + // Remember where we were to restore the module scope in which + // this @load was done when we're finished processing it. + file_stack.push_back(new FileInfo(zeek::detail::current_module)); - 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); - LoadPolicyFileText(file_path.c_str(), rc.second); - } + zeek::detail::zeekygen_mgr->Script(file_path); - // Remember where we were to restore the module scope in which - // this @load was done when we're finished processing it. - file_stack.push_back(new FileInfo(zeek::detail::current_module)); + // "orig_file" could be an alias for yytext, which is ephemeral + // and will be zapped after the yy_switch_to_buffer() below. + YY_BUFFER_STATE buffer; - zeek::detail::zeekygen_mgr->Script(file_path); + 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 { + // Parse from file. + assert(f); + DBG_LOG(zeek::DBG_SCRIPTS, "Loading %s", file_path.c_str()); + buffer = yy_create_buffer(f, YY_BUF_SIZE); + } - // "orig_file" could be an alias for yytext, which is ephemeral - // and will be zapped after the yy_switch_to_buffer() below. - YY_BUFFER_STATE buffer; - - 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 - { - // Parse from file. - assert(f); - DBG_LOG(zeek::DBG_SCRIPTS, "Loading %s", file_path.c_str()); - buffer = yy_create_buffer(f, YY_BUF_SIZE); - } + yy_switch_to_buffer(buffer); + yylloc.first_line = yylloc.last_line = line_number = 1; return switch_to(file_path.c_str(), buffer); - } +} -void begin_RE() - { - BEGIN(RE); - } +void begin_RE() { BEGIN(RE); } class LocalNameFinder final : public zeek::detail::TraversalCallback { public: - LocalNameFinder() = default; + LocalNameFinder() = default; - zeek::detail::TraversalCode PreExpr(const zeek::detail::Expr* expr) override - { - if ( expr->Tag() != EXPR_NAME ) - return zeek::detail::TC_CONTINUE; + zeek::detail::TraversalCode PreExpr(const zeek::detail::Expr* expr) override { + if ( expr->Tag() != EXPR_NAME ) + return zeek::detail::TC_CONTINUE; - const zeek::detail::NameExpr* name_expr = static_cast(expr); + const zeek::detail::NameExpr* name_expr = static_cast(expr); - if ( name_expr->Id()->IsGlobal() ) - return zeek::detail::TC_CONTINUE; + if ( name_expr->Id()->IsGlobal() ) + return zeek::detail::TC_CONTINUE; - local_names.push_back(name_expr); - return zeek::detail::TC_CONTINUE; - } + local_names.push_back(name_expr); + return zeek::detail::TC_CONTINUE; + } - std::vector local_names; + std::vector local_names; }; -static void begin_ignoring() - { - if_stack.push_back(conditional_depth); - BEGIN(IGNORE); - } +static void begin_ignoring() { + if_stack.push_back(conditional_depth); + BEGIN(IGNORE); +} -static void resume_processing() - { - if_stack.pop_back(); - BEGIN(INITIAL); - } +static void resume_processing() { + if_stack.pop_back(); + BEGIN(INITIAL); +} -void do_atif(zeek::detail::Expr* expr) - { - start_conditional(); +void do_atif(zeek::detail::Expr* expr) { + start_conditional(); - LocalNameFinder cb; - expr->Traverse(&cb); - zeek::ValPtr val; + LocalNameFinder cb; + expr->Traverse(&cb); + zeek::ValPtr val; - if ( cb.local_names.empty() ) - val = expr->Eval(nullptr); - else - { - for ( size_t i = 0; i < cb.local_names.size(); ++i ) - cb.local_names[i]->Error("referencing a local name in @if"); - } + if ( cb.local_names.empty() ) + val = expr->Eval(nullptr); + 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 ) - { - expr->Error("invalid expression in @if"); - return; - } + if ( ! val ) { + expr->Error("invalid expression in @if"); + return; + } - if ( ! val->AsBool() ) - begin_ignoring(); - } + if ( ! val->AsBool() ) + begin_ignoring(); +} -void do_atifdef(const char* id) - { - start_conditional(); +void do_atifdef(const char* id) { + start_conditional(); - const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); + const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); - // If the ID didn't exist, look to see if this is a module name instead. - bool found = (i != nullptr); - if ( ! found ) - found = (zeek::detail::module_names().count(id) != 0); + // If the ID didn't exist, look to see if this is a module name instead. + bool found = (i != nullptr); + if ( ! found ) + found = (zeek::detail::module_names().count(id) != 0); - if ( ! found ) - begin_ignoring(); - } + if ( ! found ) + begin_ignoring(); +} -void do_atifndef(const char *id) - { - start_conditional(); +void do_atifndef(const char* id) { + start_conditional(); - const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); + const auto& i = zeek::detail::lookup_ID(id, zeek::detail::current_module.c_str()); - // If the ID didn't exist, look to see if this is a module name instead. - bool found = (i != nullptr); - if ( ! found ) - found = (zeek::detail::module_names().count(id) != 0); + // If the ID didn't exist, look to see if this is a module name instead. + bool found = (i != nullptr); + if ( ! found ) + found = (zeek::detail::module_names().count(id) != 0); - if ( found ) - begin_ignoring(); - } + if ( found ) + begin_ignoring(); +} -void do_atelse() - { - if ( conditional_depth == 0 ) - zeek::reporter->Error("@else without @if..."); +void do_atelse() { + if ( conditional_depth == 0 ) + zeek::reporter->Error("@else without @if..."); - if ( ! if_stack.empty() && conditional_depth > if_stack.back() ) - return; + if ( ! if_stack.empty() && conditional_depth > if_stack.back() ) + return; - if ( YY_START == INITIAL ) - begin_ignoring(); - else - resume_processing(); - } + if ( YY_START == INITIAL ) + begin_ignoring(); + else + resume_processing(); +} -void do_atendif() - { - if ( conditional_depth <= entry_cond_depth.back() ) - zeek::reporter->Error("unbalanced @if... @endif"); +void do_atendif() { + if ( conditional_depth <= entry_cond_depth.back() ) + zeek::reporter->Error("unbalanced @if... @endif"); - if ( ! if_stack.empty() && conditional_depth == if_stack.back() ) - resume_processing(); + if ( ! if_stack.empty() && conditional_depth == if_stack.back() ) + resume_processing(); - --conditional_depth; - } + --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) - { - if ( s->Tag() == STMT_NULL ) - if ( s->AsNullStmt()->IsDirective() ) - zeek::reporter->Error("incorrect use of directive"); - } +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) - { - if ( ! file ) - zeek::reporter->InternalError("empty filename"); +void add_essential_input_file(const char* file) { + if ( ! file ) + zeek::reporter->InternalError("empty filename"); - if ( ! filename ) - (void) load_files(file); - else - essential_input_files.push_back(zeek::util::copy_string(file)); - } + if ( ! filename ) + (void)load_files(file); + else + essential_input_files.push_back(zeek::util::copy_string(file)); +} -void add_input_file(const char* file) - { - if ( ! file ) - zeek::reporter->InternalError("empty filename"); +void add_input_file(const char* file) { + if ( ! file ) + zeek::reporter->InternalError("empty filename"); - if ( ! filename ) - (void) load_files(file); - else - input_files.push_back(zeek::util::copy_string(file)); - } + if ( ! filename ) + (void)load_files(file); + else + input_files.push_back(zeek::util::copy_string(file)); +} -void add_input_file_at_front(const char* file) - { - if ( ! file ) - zeek::reporter->InternalError("empty filename"); +void add_input_file_at_front(const char* file) { + if ( ! file ) + zeek::reporter->InternalError("empty filename"); - if ( ! filename ) - (void) load_files(file); - else - input_files.push_front(zeek::util::copy_string(file)); - } + if ( ! filename ) + (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 ) - { - char* s_delim = strchr(s, delim); - if ( s_delim ) - *s_delim = 0; +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; - nl.push_back(zeek::util::copy_string(s)); + nl.push_back(zeek::util::copy_string(s)); - if ( s_delim ) - s = s_delim + 1; - else - break; - } - } + if ( s_delim ) + s = s_delim + 1; + else + break; + } +} -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(); - } +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 ( pragma_stack.size() > entry_pragma_stack_depth.back() ) - zeek::reporter->FatalError("unbalanced @pragma push pop in file"); + 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"); - entry_pragma_stack_depth.pop_back(); - } + entry_pragma_stack_depth.pop_back(); + } - last_filename = ::filename; + last_filename = ::filename; - if ( zeek::reporter->Errors() > 0 ) - return 1; + if ( zeek::reporter->Errors() > 0 ) + return 1; - yy_delete_buffer(YY_CURRENT_BUFFER); + yy_delete_buffer(YY_CURRENT_BUFFER); - if ( file_stack.length() > 0 ) - delete file_stack.remove_nth(file_stack.length() - 1); + if ( file_stack.length() > 0 ) + delete file_stack.remove_nth(file_stack.length() - 1); - if ( YY_CURRENT_BUFFER ) - { - // There's more on the stack to scan. - current_file_has_conditionals = files_with_conditionals.count(::filename) > 0; - return 0; - } + 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; + // 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; - 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); - return 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); + return 0; + } - // We already scanned the file. Pop it and try the next, - // if any. - (void) files.remove_nth(0); - } + // We already scanned the file. Pop it and try the next, + // if any. + (void)files.remove_nth(0); + } - // For each file scanned so far, and for each @prefix, look for a - // prefixed and flattened version of the loaded file in ZEEKPATH. The - // flattening involves taking the path in ZEEKPATH in which the - // scanned file lives and replacing '/' path separators with a '.' If - // the scanned file is "__load__.zeek", that part of the flattened - // 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 ) - { - if ( scanned_file.skipped || scanned_file.prefixes_checked ) - continue; + // For each file scanned so far, and for each @prefix, look for a + // prefixed and flattened version of the loaded file in ZEEKPATH. The + // flattening involves taking the path in ZEEKPATH in which the + // scanned file lives and replacing '/' path separators with a '.' If + // the scanned file is "__load__.zeek", that part of the flattened + // 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 ) { + 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 ) - { - // Don't look at empty prefixes. - if ( ! zeek::detail::zeek_script_prefixes[i][0] ) - 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 ) { + // Don't look at empty prefixes. + if ( ! zeek::detail::zeek_script_prefixes[i][0] ) + continue; - std::string canon = zeek::util::detail::without_zeekpath_component(scanned_file.name); - std::string flat = zeek::util::detail::flatten_script_name(canon, zeek::detail::zeek_script_prefixes[i]); - std::string path = find_relative_script_file(flat); + std::string canon = zeek::util::detail::without_zeekpath_component(scanned_file.name); + 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() ) - { - add_input_file(path.c_str()); - found_prefixed_files = true; - } + 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"); + } + } - if ( found_prefixed_files ) - return 0; + if ( found_prefixed_files ) + return 0; - // Add redef statements for any X=Y command line parameters. - if ( ! zeek::detail::params.empty() ) - { - std::string policy; + // Add redef statements for any X=Y command line parameters. + if ( ! zeek::detail::params.empty() ) { + std::string policy; - for ( const auto& pi : zeek::detail::params ) - { - auto p = pi.data(); + 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); - // Omit the '=' from op just to make fmt string below clearer. - auto op = pi.substr(first_non_id_char, eq_idx - first_non_id_char); - auto id_str = pi.substr(0, first_non_id_char); - auto val_str = pi.substr(eq_idx + 1); - const auto& id = zeek::id::find(id_str); + auto first_non_id_char = p - pi.data(); + auto eq_idx = pi.find('=', first_non_id_char); + // Omit the '=' from op just to make fmt string below clearer. + auto op = pi.substr(first_non_id_char, eq_idx - first_non_id_char); + auto id_str = pi.substr(0, first_non_id_char); + 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()); - continue; - } + if ( ! id ) { + zeek::reporter->Error("unknown identifier '%s' in command-line options", id_str.data()); + continue; + } - // Interpret the value based on the identifier's type. - // So far, that just means quoting the value for string types. - const auto& type = id->GetType(); + // Interpret the value based on the identifier's type. + // 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()); - continue; - } + 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()); - 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()); + continue; + } - auto use_quotes = zeek::IsString(type->Tag()); - auto fmt_str = use_quotes ? "redef %s %s= \"%s\";" - : "redef %s %s= %s;"; + auto use_quotes = zeek::IsString(type->Tag()); + 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()); - } + policy += zeek::util::fmt(fmt_str, id_str.data(), op.data(), val_str.data()); + } - zeek::detail::params.clear(); - yylloc.filename = filename = ""; - yy_scan_string(policy.c_str()); - return 0; - } + zeek::detail::params.clear(); + yylloc.filename = filename = ""; + yy_scan_string(policy.c_str()); + return 0; + } - // If we got this far, then we ran out of files. Check if the user - // specified additional code on the command line, if so, parse it. - // 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 ) - { - 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 = ""; + // If we got this far, then we ran out of files. Check if the user + // specified additional code on the command line, if so, parse it. + // 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 ) { + 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 = ""; - yy_scan_string(tmp); - delete [] tmp; + yy_scan_string(tmp); + delete[] tmp; - // Make sure we do not get here again: - zeek::detail::command_line_policy = 0; + // Make sure we do not get here again: + zeek::detail::command_line_policy = 0; - return 0; - } + return 0; + } - // Otherwise, we are done. - return 1; - } + // Otherwise, we are done. + return 1; +} -FileInfo::FileInfo(std::string arg_restore_module) - { - buffer_state = YY_CURRENT_BUFFER; - restore_module = arg_restore_module; - name = ::filename; - line = ::line_number; - } +FileInfo::FileInfo(std::string arg_restore_module) { + buffer_state = YY_CURRENT_BUFFER; + restore_module = arg_restore_module; + name = ::filename; + line = ::line_number; +} -FileInfo::~FileInfo() - { - if ( yyin && yyin != stdin ) - fclose(yyin); +FileInfo::~FileInfo() { + if ( yyin && yyin != stdin ) + fclose(yyin); - yy_switch_to_buffer(buffer_state); - yylloc.filename = filename = name; - yylloc.first_line = yylloc.last_line = line_number = line; + yy_switch_to_buffer(buffer_state); + yylloc.filename = filename = name; + yylloc.first_line = yylloc.last_line = line_number = line; - if ( restore_module != "" ) - zeek::detail::current_module = restore_module; - } + if ( restore_module != "" ) + zeek::detail::current_module = restore_module; +}