Merge remote-tracking branch 'origin/topic/timw/266-namespaces-part2'

* origin/topic/timw/266-namespaces-part2:
  Rename BroString files to ZeekString
  Update NEWS entry with note about class renames
  Rename BroObj to Obj
  Rename BroString to zeek::String
  Move Func up to zeek namespace, rename BroFunc to ScriptFunc
  Mark global val_mgr as deprecated and fix uses of it to use namespaced version
  Minor cleanup items from PR review
  Update binpac and bifcl submodules with review changes
  Move Location to zeek::detail and BroObj to zeek
  Move BroString to zeek namespace
  Move Dictionary/PDict, List/PList, and Queue/PQueue to zeek namespace
  Remove typedef that should have been removed in 3.1
  Move Func and associated classes into zeek::detail namespace
  Move Frame and Scope to zeek::detail namespace
  Move all Val classes to the zeek namespaces
  Use type aliases for IntrusivePtr definitions
  Move deprecation macro to zeek-config.h.in to avoid having to over-include util.h
  Move IntrusivePtr and utility methods to the zeek namespace
This commit is contained in:
Jon Siwek 2020-07-02 19:24:09 -07:00
commit 76e67ff239
340 changed files with 8293 additions and 7822 deletions

34
CHANGES
View file

@ -1,4 +1,38 @@
3.2.0-dev.853 | 2020-07-02 19:24:09 -0700
* Rename BroString files to ZeekString (Tim Wojtulewicz, Corelight)
* Rename BroObj to Obj (Tim Wojtulewicz, Corelight)
* Rename BroString to zeek::String (Tim Wojtulewicz, Corelight)
* Move Func up to zeek namespace, rename BroFunc to ScriptFunc (Tim Wojtulewicz, Corelight)
* Mark global val_mgr as deprecated and fix uses of it to use namespaced version (Tim Wojtulewicz, Corelight)
* Update binpac and bifcl submodules with review changes (Tim Wojtulewicz, Corelight)
* Move Location to zeek::detail and BroObj to zeek (Tim Wojtulewicz, Corelight)
* Move BroString to zeek namespace (Tim Wojtulewicz, Corelight)
* Move Dictionary/PDict, List/PList, and Queue/PQueue to zeek namespace (Tim Wojtulewicz, Corelight)
* Remove typedef that should have been removed in 3.1 (Tim Wojtulewicz, Corelight)
* Move Func and associated classes into zeek::detail namespace (Tim Wojtulewicz, Corelight)
* Move Frame and Scope to zeek::detail namespace (Tim Wojtulewicz)
* Move all Val classes to the zeek namespaces (Tim Wojtulewicz, Corelight)
* Use type aliases for IntrusivePtr definitions (Tim Wojtulewicz, Corelight)
* Move deprecation macro to zeek-config.h.in to avoid having to over-include util.h (Tim Wojtulewicz, Corelight)
* Move IntrusivePtr and utility methods to the zeek namespace (Tim Wojtulewicz, Corelight)
3.2.0-dev.834 | 2020-07-02 15:57:09 -0700 3.2.0-dev.834 | 2020-07-02 15:57:09 -0700
* GH-786: fix Val::As methods casting incomplete types (Jon Siwek, Corelight) * GH-786: fix Val::As methods casting incomplete types (Jon Siwek, Corelight)

6
NEWS
View file

@ -113,6 +113,10 @@ Changed Functionality
but the Deprecated Functionality section below will mention those but the Deprecated Functionality section below will mention those
ones specifically). ones specifically).
This includes a number of renames to classes, removing 'Bro' from their
names. Deprecation warnings should notify plugin developers of these
name changes.
Removed Functionality Removed Functionality
--------------------- ---------------------
@ -249,6 +253,8 @@ Deprecated Functionality
- The ``Val(double, TypeTag)`` constructor is deprecated, use either - The ``Val(double, TypeTag)`` constructor is deprecated, use either
``IntervalVal()``, ``TimeVal()`` or ``DoubleVal()`` constructors. ``IntervalVal()``, ``TimeVal()`` or ``DoubleVal()`` constructors.
- The "BroString.h" file is deprecated, use "ZeekString.h"
Zeek 3.1.0 Zeek 3.1.0
========== ==========

View file

@ -1 +1 @@
3.2.0-dev.834 3.2.0-dev.853

@ -1 +1 @@
Subproject commit 9c10bb74bb62aa7fb10efc079f1b2e5926e9798c Subproject commit 3266a0429b366abd96234911ecf1de284f43a167

@ -1 +1 @@
Subproject commit 9c3211ff121ddc677d0ed8bd3a85783f87921cce Subproject commit 881a5eb49ba1c22623777009b98a667fb183aeca

2
doc

@ -1 +1 @@
Subproject commit e738208f9c4c385b42de7066a71de0a2bcf52ec6 Subproject commit 376907184474f6592ab871b9bd2161140daadb17

View file

@ -358,9 +358,9 @@ AnonymizeIPAddr_A50::Node* AnonymizeIPAddr_A50::find_node(ipaddr32_t a)
return nullptr; return nullptr;
} }
static IntrusivePtr<TableVal> anon_preserve_orig_addr; static zeek::TableValPtr anon_preserve_orig_addr;
static IntrusivePtr<TableVal> anon_preserve_resp_addr; static zeek::TableValPtr anon_preserve_resp_addr;
static IntrusivePtr<TableVal> anon_preserve_other_addr; static zeek::TableValPtr anon_preserve_other_addr;
void zeek::detail::init_ip_addr_anonymizers() void zeek::detail::init_ip_addr_anonymizers()
{ {
@ -373,23 +373,23 @@ void zeek::detail::init_ip_addr_anonymizers()
auto id = global_scope()->Find("preserve_orig_addr"); auto id = global_scope()->Find("preserve_orig_addr");
if ( id ) if ( id )
anon_preserve_orig_addr = cast_intrusive<TableVal>(id->GetVal()); anon_preserve_orig_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal());
id = global_scope()->Find("preserve_resp_addr"); id = global_scope()->Find("preserve_resp_addr");
if ( id ) if ( id )
anon_preserve_resp_addr = cast_intrusive<TableVal>(id->GetVal()); anon_preserve_resp_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal());
id = global_scope()->Find("preserve_other_addr"); id = global_scope()->Find("preserve_other_addr");
if ( id ) if ( id )
anon_preserve_other_addr = cast_intrusive<TableVal>(id->GetVal()); anon_preserve_other_addr = zeek::cast_intrusive<zeek::TableVal>(id->GetVal());
} }
ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl) ipaddr32_t zeek::detail::anonymize_ip(ipaddr32_t ip, enum ip_addr_anonymization_class_t cl)
{ {
TableVal* preserve_addr = nullptr; TableVal* preserve_addr = nullptr;
auto addr = make_intrusive<AddrVal>(ip); auto addr = zeek::make_intrusive<zeek::AddrVal>(ip);
int method = -1; int method = -1;
@ -445,8 +445,8 @@ void zeek::detail::log_anonymization_mapping(ipaddr32_t input, ipaddr32_t output
{ {
if ( anonymization_mapping ) if ( anonymization_mapping )
mgr.Enqueue(anonymization_mapping, mgr.Enqueue(anonymization_mapping,
make_intrusive<AddrVal>(input), zeek::make_intrusive<zeek::AddrVal>(input),
make_intrusive<AddrVal>(output) zeek::make_intrusive<AddrVal>(output)
); );
} }

View file

@ -25,7 +25,7 @@ const char* attr_name(AttrTag t)
return attr_names[int(t)]; return attr_names[int(t)];
} }
Attr::Attr(AttrTag t, IntrusivePtr<Expr> e) Attr::Attr(AttrTag t, ExprPtr e)
: expr(std::move(e)) : expr(std::move(e))
{ {
tag = t; tag = t;
@ -37,7 +37,7 @@ Attr::Attr(AttrTag t)
{ {
} }
void Attr::SetAttrExpr(IntrusivePtr<zeek::detail::Expr> e) void Attr::SetAttrExpr(ExprPtr e)
{ expr = std::move(e); } { expr = std::move(e); }
void Attr::Describe(ODesc* d) const void Attr::Describe(ODesc* d) const
@ -136,7 +136,7 @@ void Attr::AddTag(ODesc* d) const
d->Add(attr_name(Tag())); d->Add(attr_name(Tag()));
} }
Attributes::Attributes(attr_list* a, IntrusivePtr<Type> t, bool arg_in_record, bool is_global) Attributes::Attributes(attr_list* a, TypePtr t, bool arg_in_record, bool is_global)
{ {
attrs_list.resize(a->length()); attrs_list.resize(a->length());
attrs.reserve(a->length()); attrs.reserve(a->length());
@ -150,20 +150,18 @@ Attributes::Attributes(attr_list* a, IntrusivePtr<Type> t, bool arg_in_record, b
// the necessary checking gets done. // the necessary checking gets done.
for ( const auto& attr : *a ) for ( const auto& attr : *a )
AddAttr({NewRef{}, attr}); AddAttr({zeek::NewRef{}, attr});
delete a; delete a;
} }
Attributes::Attributes(IntrusivePtr<Type> t, Attributes::Attributes(TypePtr t, bool arg_in_record, bool is_global)
bool arg_in_record, bool is_global) : Attributes(std::vector<AttrPtr>{}, std::move(t),
: Attributes(std::vector<IntrusivePtr<Attr>>{}, std::move(t),
arg_in_record, is_global) arg_in_record, is_global)
{} {}
Attributes::Attributes(std::vector<IntrusivePtr<Attr>> a, Attributes::Attributes(std::vector<AttrPtr> a,
IntrusivePtr<Type> t, TypePtr t, bool arg_in_record, bool is_global)
bool arg_in_record, bool is_global)
: type(std::move(t)) : type(std::move(t))
{ {
attrs_list.resize(a.size()); attrs_list.resize(a.size());
@ -181,7 +179,7 @@ Attributes::Attributes(std::vector<IntrusivePtr<Attr>> a,
AddAttr(std::move(attr)); AddAttr(std::move(attr));
} }
void Attributes::AddAttr(IntrusivePtr<Attr> attr) void Attributes::AddAttr(AttrPtr attr)
{ {
// We overwrite old attributes by deleting them first. // We overwrite old attributes by deleting them first.
RemoveAttr(attr->Tag()); RemoveAttr(attr->Tag());
@ -197,7 +195,7 @@ void Attributes::AddAttr(IntrusivePtr<Attr> attr)
if ( (attr->Tag() == ATTR_ADD_FUNC || attr->Tag() == ATTR_DEL_FUNC) && if ( (attr->Tag() == ATTR_ADD_FUNC || attr->Tag() == ATTR_DEL_FUNC) &&
! Find(ATTR_REDEF) ) ! Find(ATTR_REDEF) )
{ {
auto a = make_intrusive<Attr>(ATTR_REDEF); auto a = zeek::make_intrusive<Attr>(ATTR_REDEF);
attrs_list.push_back(a.get()); attrs_list.push_back(a.get());
attrs.emplace_back(std::move(a)); attrs.emplace_back(std::move(a));
} }
@ -206,13 +204,13 @@ void Attributes::AddAttr(IntrusivePtr<Attr> attr)
if ( ! global_var && attr->Tag() == ATTR_DEFAULT && if ( ! global_var && attr->Tag() == ATTR_DEFAULT &&
! Find(ATTR_OPTIONAL) ) ! Find(ATTR_OPTIONAL) )
{ {
auto a = make_intrusive<Attr>(ATTR_OPTIONAL); auto a = zeek::make_intrusive<Attr>(ATTR_OPTIONAL);
attrs_list.push_back(a.get()); attrs_list.push_back(a.get());
attrs.emplace_back(std::move(a)); attrs.emplace_back(std::move(a));
} }
} }
void Attributes::AddAttrs(const IntrusivePtr<Attributes>& a) void Attributes::AddAttrs(const AttributesPtr& a)
{ {
for ( const auto& attr : a->GetAttrs() ) for ( const auto& attr : a->GetAttrs() )
AddAttr(attr); AddAttr(attr);
@ -235,7 +233,7 @@ Attr* Attributes::FindAttr(AttrTag t) const
return nullptr; return nullptr;
} }
const IntrusivePtr<Attr>& Attributes::Find(AttrTag t) const const AttrPtr& Attributes::Find(AttrTag t) const
{ {
for ( const auto& a : attrs ) for ( const auto& a : attrs )
if ( a->Tag() == t ) if ( a->Tag() == t )

View file

@ -14,7 +14,15 @@ ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail);
// modify expressions or supply metadata on types, and the kind that // modify expressions or supply metadata on types, and the kind that
// are extra metadata on every variable instance. // are extra metadata on every variable instance.
namespace zeek::detail {
namespace zeek {
class Type;
using TypePtr = IntrusivePtr<Type>;
namespace detail {
using ExprPtr = zeek::IntrusivePtr<zeek::detail::Expr>;
enum AttrTag { enum AttrTag {
ATTR_OPTIONAL, ATTR_OPTIONAL,
@ -38,11 +46,16 @@ enum AttrTag {
NUM_ATTRS // this item should always be last NUM_ATTRS // this item should always be last
}; };
class Attr final : public BroObj { class Attr;
public: using AttrPtr = zeek::IntrusivePtr<Attr>;
static inline const IntrusivePtr<zeek::detail::Attr> nil; class Attributes;
using AttributesPtr = zeek::IntrusivePtr<Attributes>;
Attr(AttrTag t, IntrusivePtr<zeek::detail::Expr> e); class Attr final : public Obj {
public:
static inline const AttrPtr nil;
Attr(AttrTag t, ExprPtr e);
explicit Attr(AttrTag t); explicit Attr(AttrTag t);
~Attr() override = default; ~Attr() override = default;
@ -52,10 +65,10 @@ public:
[[deprecated("Remove in v4.1. Use GetExpr().")]] [[deprecated("Remove in v4.1. Use GetExpr().")]]
zeek::detail::Expr* AttrExpr() const { return expr.get(); } zeek::detail::Expr* AttrExpr() const { return expr.get(); }
const IntrusivePtr<zeek::detail::Expr>& GetExpr() const const ExprPtr& GetExpr() const
{ return expr; } { return expr; }
void SetAttrExpr(IntrusivePtr<zeek::detail::Expr> e); void SetAttrExpr(ExprPtr e);
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
void DescribeReST(ODesc* d, bool shorten = false) const; void DescribeReST(ODesc* d, bool shorten = false) const;
@ -78,24 +91,24 @@ protected:
void AddTag(ODesc* d) const; void AddTag(ODesc* d) const;
AttrTag tag; AttrTag tag;
IntrusivePtr<Expr> expr; ExprPtr expr;
}; };
// Manages a collection of attributes. // Manages a collection of attributes.
class Attributes final : public BroObj { class Attributes final : public Obj {
public: public:
[[deprecated("Remove in v4.1. Construct using IntrusivePtrs instead.")]] [[deprecated("Remove in v4.1. Construct using IntrusivePtrs instead.")]]
Attributes(attr_list* a, IntrusivePtr<Type> t, bool in_record, bool is_global); Attributes(attr_list* a, zeek::TypePtr t, bool in_record, bool is_global);
Attributes(std::vector<IntrusivePtr<Attr>> a, IntrusivePtr<Type> t, Attributes(std::vector<AttrPtr> a, zeek::TypePtr t,
bool in_record, bool is_global); bool in_record, bool is_global);
Attributes(IntrusivePtr<Type> t, bool in_record, bool is_global); Attributes(TypePtr t, bool in_record, bool is_global);
~Attributes() override = default; ~Attributes() override = default;
void AddAttr(IntrusivePtr<Attr> a); void AddAttr(AttrPtr a);
void AddAttrs(const IntrusivePtr<Attributes>& a); void AddAttrs(const AttributesPtr& a);
[[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]]
void AddAttrs(Attributes* a); // Unref's 'a' when done void AddAttrs(Attributes* a); // Unref's 'a' when done
@ -103,7 +116,7 @@ public:
[[deprecated("Remove in v4.1. Use Find().")]] [[deprecated("Remove in v4.1. Use Find().")]]
Attr* FindAttr(AttrTag t) const; Attr* FindAttr(AttrTag t) const;
const IntrusivePtr<Attr>& Find(AttrTag t) const; const AttrPtr& Find(AttrTag t) const;
void RemoveAttr(AttrTag t); void RemoveAttr(AttrTag t);
@ -114,7 +127,7 @@ public:
const attr_list* Attrs() const const attr_list* Attrs() const
{ return &attrs_list; } { return &attrs_list; }
const std::vector<IntrusivePtr<Attr>>& GetAttrs() const const std::vector<AttrPtr>& GetAttrs() const
{ return attrs; } { return attrs; }
bool operator==(const Attributes& other) const; bool operator==(const Attributes& other) const;
@ -122,8 +135,8 @@ public:
protected: protected:
void CheckAttr(Attr* attr); void CheckAttr(Attr* attr);
IntrusivePtr<Type> type; TypePtr type;
std::vector<IntrusivePtr<Attr>> attrs; std::vector<AttrPtr> attrs;
// Remove in v4.1. This is used by Attrs(), which is deprecated. // Remove in v4.1. This is used by Attrs(), which is deprecated.
attr_list attrs_list; attr_list attrs_list;
@ -131,7 +144,8 @@ protected:
bool global_var; bool global_var;
}; };
} } // namespace detail
} // namespace zeek
using Attr [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attr; using Attr [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attr;
using Attributes [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attributes; using Attributes [[deprecated("Remove in v4.1. Use zeek::detail::Attr instead.")]] = zeek::detail::Attributes;

View file

@ -1,6 +1,6 @@
#include "zeek-config.h" #include "zeek-config.h"
#include "Base64.h" #include "Base64.h"
#include "BroString.h" #include "ZeekString.h"
#include "Reporter.h" #include "Reporter.h"
#include "Conn.h" #include "Conn.h"
@ -35,7 +35,7 @@ void Base64Converter::Encode(int len, const unsigned char* data, int* pblen, cha
for ( int i = 0, j = 0; (i < len) && ( j < blen ); ) for ( int i = 0, j = 0; (i < len) && ( j < blen ); )
{ {
uint32_t bit32 = data[i++] << 16; uint32_t bit32 = data[i++] << 16;
bit32 += (i++ < len ? data[i-1] : 0) << 8; bit32 += (i++ < len ? data[i-1] : 0) << 8;
bit32 += i++ < len ? data[i-1] : 0; bit32 += i++ < len ? data[i-1] : 0;
buf[j++] = alphabet[(bit32 >> 18) & 0x3f]; buf[j++] = alphabet[(bit32 >> 18) & 0x3f];
@ -228,7 +228,7 @@ void Base64Converter::IllegalEncoding(const char* msg)
reporter->Error("%s", msg); reporter->Error("%s", msg);
} }
BroString* decode_base64(const BroString* s, const BroString* a, Connection* conn) zeek::String* decode_base64(const zeek::String* s, const zeek::String* a, Connection* conn)
{ {
if ( a && a->Len() != 0 && a->Len() != 64 ) if ( a && a->Len() != 0 && a->Len() != 64 )
{ {
@ -255,14 +255,14 @@ BroString* decode_base64(const BroString* s, const BroString* a, Connection* con
rlen += rlen2; rlen += rlen2;
rbuf[rlen] = '\0'; rbuf[rlen] = '\0';
return new BroString(true, (u_char*) rbuf, rlen); return new zeek::String(true, (u_char*) rbuf, rlen);
err: err:
delete [] rbuf; delete [] rbuf;
return nullptr; return nullptr;
} }
BroString* encode_base64(const BroString* s, const BroString* a, Connection* conn) zeek::String* encode_base64(const zeek::String* s, const zeek::String* a, Connection* conn)
{ {
if ( a && a->Len() != 0 && a->Len() != 64 ) if ( a && a->Len() != 0 && a->Len() != 64 )
{ {
@ -276,5 +276,5 @@ BroString* encode_base64(const BroString* s, const BroString* a, Connection* con
Base64Converter enc(conn, a ? a->CheckString() : ""); Base64Converter enc(conn, a ? a->CheckString() : "");
enc.Encode(s->Len(), (const unsigned char*) s->Bytes(), &outlen, &outbuf); enc.Encode(s->Len(), (const unsigned char*) s->Bytes(), &outlen, &outbuf);
return new BroString(true, (u_char*)outbuf, outlen); return new zeek::String(true, (u_char*)outbuf, outlen);
} }

View file

@ -1,8 +1,11 @@
#pragma once #pragma once
#include "zeek-config.h"
#include <string> #include <string>
class BroString; namespace zeek { class String; }
using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String;
class Connection; class Connection;
// Maybe we should have a base class for generic decoders? // Maybe we should have a base class for generic decoders?
@ -57,5 +60,5 @@ protected:
}; };
BroString* decode_base64(const BroString* s, const BroString* a = nullptr, Connection* conn = nullptr); zeek::String* decode_base64(const zeek::String* s, const zeek::String* a = nullptr, Connection* conn = nullptr);
BroString* encode_base64(const BroString* s, const BroString* a = nullptr, Connection* conn = nullptr); zeek::String* encode_base64(const zeek::String* s, const zeek::String* a = nullptr, Connection* conn = nullptr);

View file

@ -6,6 +6,6 @@
BifReturnVal::BifReturnVal(std::nullptr_t) noexcept BifReturnVal::BifReturnVal(std::nullptr_t) noexcept
{} {}
BifReturnVal::BifReturnVal(Val* v) noexcept BifReturnVal::BifReturnVal(zeek::Val* v) noexcept
: rval(AdoptRef{}, v) : rval(zeek::AdoptRef{}, v)
{} {}

View file

@ -2,9 +2,13 @@
#pragma once #pragma once
#include "zeek-config.h"
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek {
using ValPtr = zeek::IntrusivePtr<zeek::Val>;
}
/** /**
* A simple wrapper class to use for the return value of BIFs so that * A simple wrapper class to use for the return value of BIFs so that
@ -15,14 +19,14 @@ class BifReturnVal {
public: public:
template <typename T> template <typename T>
BifReturnVal(IntrusivePtr<T> v) noexcept BifReturnVal(zeek::IntrusivePtr<T> v) noexcept
: rval(AdoptRef{}, v.release()) : rval(zeek::AdoptRef{}, v.release())
{ } { }
BifReturnVal(std::nullptr_t) noexcept; BifReturnVal(std::nullptr_t) noexcept;
[[deprecated("Remove in v4.1. Return an IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Return an IntrusivePtr instead.")]]
BifReturnVal(Val* v) noexcept; BifReturnVal(zeek::Val* v) noexcept;
IntrusivePtr<Val> rval; zeek::ValPtr rval;
}; };

View file

@ -4,24 +4,24 @@
#include "List.h" #include "List.h"
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
using val_list = PList<Val>; using val_list = zeek::PList<zeek::Val>;
ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail);
using expr_list = PList<zeek::detail::Expr>; using expr_list = zeek::PList<zeek::detail::Expr>;
ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail);
using id_list = PList<zeek::detail::ID>; using id_list = zeek::PList<zeek::detail::ID>;
ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail);
using stmt_list = PList<zeek::detail::Stmt>; using stmt_list = zeek::PList<zeek::detail::Stmt>;
namespace zeek { class Type; } namespace zeek { class Type; }
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
using type_list = PList<zeek::Type>; using type_list = zeek::PList<zeek::Type>;
ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail);
using attr_list = PList<zeek::detail::Attr>; using attr_list = zeek::PList<zeek::detail::Attr>;
class Timer; class Timer;
using timer_list = PList<Timer, ListOrder::UNORDERED>; using timer_list = zeek::PList<Timer, zeek::ListOrder::UNORDERED>;

View file

@ -1,184 +1,2 @@
// See the file "COPYING" in the main distribution directory for copyright. #warning "BroString.h is deprecated and will be removed in v4.1. Use ZeekString.h instead."
#include "ZeekString.h"
#pragma once
#include <vector>
#include <string>
#include <iosfwd>
#include <sys/types.h>
typedef u_char* byte_vec;
// Forward declaration, for helper functions that convert (sub)string vectors
// to and from policy-level representations.
//
class VectorVal;
class BroString {
public:
typedef std::vector<BroString*> Vec;
typedef Vec::iterator VecIt;
typedef Vec::const_iterator VecCIt;
typedef std::vector<const BroString*> CVec;
typedef Vec::iterator CVecIt;
typedef Vec::const_iterator CVecCIt;
// IdxVecs are vectors of indices of characters in a string.
typedef std::vector<int> IdxVec;
typedef IdxVec::iterator IdxVecIt;
typedef IdxVec::const_iterator IdxVecCIt;
// Constructors creating internal copies of the data passed in.
BroString(const u_char* str, int arg_n, bool add_NUL);
explicit BroString(const char* str);
explicit BroString(const std::string& str);
BroString(const BroString& bs);
// Constructor that takes owernship of the vector passed in.
BroString(bool arg_final_NUL, byte_vec str, int arg_n);
BroString();
~BroString() { Reset(); }
const BroString& operator=(const BroString& bs);
bool operator==(const BroString& bs) const;
bool operator<(const BroString& bs) const;
byte_vec Bytes() const { return b; }
int Len() const { return n; }
// Releases the string's current contents, if any, and
// adopts the byte vector of given length. The string will
// manage the memory occupied by the string afterwards.
//
void Adopt(byte_vec bytes, int len);
// Various flavors of methods that release the string's
// current contents, if any, and then set the string's
// contents to a copy of the string given by the arguments.
//
void Set(const u_char* str, int len, bool add_NUL=true);
void Set(const char* str);
void Set(const std::string& str);
void Set(const BroString &str);
void SetUseFreeToDelete(int use_it)
{ use_free_to_delete = use_it; }
const char* CheckString() const;
enum render_style {
ESC_NONE = 0,
ESC_ESC = (1 << 1), // '\' -> "\\"
ESC_QUOT = (1 << 2), // '"' -> "\"", ''' -> "\'"
ESC_HEX = (1 << 3), // Not in [32, 126]? -> "\xXX"
ESC_DOT = (1 << 4), // Not in [32, 126]? -> "."
// For serialization: '<string len> <string>'
ESC_SER = (1 << 7),
};
static const int EXPANDED_STRING = // the original style
ESC_HEX;
static const int BRO_STRING_LITERAL = // as in a Bro string literal
ESC_ESC | ESC_QUOT | ESC_HEX;
// Renders a string into a newly allocated character array that
// you have to delete[]. You can combine the render styles given
// above to achieve the representation you desire. If you pass a
// pointer to an integer as the final argument, you'll receive the
// entire length of the resulting char* in it.
//
// Note that you need to delete[] the resulting string.
//
char* Render(int format = EXPANDED_STRING, int* len = nullptr) const;
// Similar to the above, but useful for output streams.
// Also more useful for debugging purposes since no deallocation
// is required on your part here.
//
std::ostream& Render(std::ostream& os, int format = ESC_SER) const;
// Reads a string from an input stream. Unless you use a render
// style combination that uses ESC_SER, note that the streams
// will consider whitespace as a field delimiter.
//
std::istream& Read(std::istream& is, int format = ESC_SER);
// XXX Fix redundancy: strings.bif implements both to_lower
// XXX and to_upper; the latter doesn't use BroString::ToUpper().
void ToUpper();
unsigned int MemoryAllocation() const;
// Returns new string containing the substring of this string,
// starting at @start >= 0 for going up to @length elements,
// A negative @length means "until end of string". Other invalid
// values result in a return value of 0.
//
BroString* GetSubstring(int start, int length) const;
// Returns the start index of s in this string, counting from 0.
// If s is not found, -1 is returned.
//
int FindSubstring(const BroString* s) const;
// Splits the string into substrings, taking all the indices in
// the given vector as cutting points. The vector does not need
// to be sorted, and can have multiple entries. Out-of-bounds
// indices are ignored. All returned strings are newly allocated.
//
Vec* Split(const IdxVec& indices) const;
// Helper functions for vectors:
static VectorVal* VecToPolicy(Vec* vec);
static Vec* VecFromPolicy(VectorVal* vec);
static char* VecToString(const Vec* vec);
protected:
void Reset();
byte_vec b;
int n;
bool final_NUL; // whether we have added a final NUL
bool use_free_to_delete; // free() vs. operator delete
};
// A comparison class that sorts pointers to BroString's according to
// the length of the pointed-to strings. Sort order can be specified
// through the constructor.
//
class BroStringLenCmp {
public:
explicit BroStringLenCmp(bool increasing = true) { _increasing = increasing; }
bool operator()(BroString*const& bst1, BroString*const& bst2);
private:
unsigned int _increasing;
};
// Default output stream operator, using rendering mode EXPANDED_STRING.
std::ostream& operator<<(std::ostream& os, const BroString& bs);
extern int Bstr_eq(const BroString* s1, const BroString* s2);
extern int Bstr_cmp(const BroString* s1, const BroString* s2);
// A data_chunk_t specifies a length-delimited constant string. It is
// often used for substrings of other BroString's to avoid memory copy,
// which would be necessary if BroString were used. Unlike BroString,
// the string should not be deallocated on destruction.
//
// "BroConstString" might be a better name here.
struct data_chunk_t {
int length;
const char* data;
};
extern BroString* concatenate(std::vector<data_chunk_t>& v);
extern BroString* concatenate(BroString::Vec& v);
extern BroString* concatenate(BroString::CVec& v);
extern void delete_strings(std::vector<const BroString*>& v);

View file

@ -31,7 +31,7 @@ void Brofiler::AddStmt(zeek::detail::Stmt* s)
if ( ignoring != 0 ) if ( ignoring != 0 )
return; return;
::Ref(s); zeek::Ref(s);
stmts.push_back(s); stmts.push_back(s);
} }

View file

@ -220,7 +220,6 @@ set(MAIN_SRCS
Base64.cc Base64.cc
BifReturnVal.cc BifReturnVal.cc
Brofiler.cc Brofiler.cc
BroString.cc
CCL.cc CCL.cc
CompHash.cc CompHash.cc
Conn.cc Conn.cc
@ -290,6 +289,7 @@ set(MAIN_SRCS
Var.cc Var.cc
WeirdState.cc WeirdState.cc
ZeekArgs.cc ZeekArgs.cc
ZeekString.cc
legacy-netvar-init.cc legacy-netvar-init.cc
bsd-getopt-long.c bsd-getopt-long.c
bro_inet_ntop.c bro_inet_ntop.c

View file

@ -7,7 +7,7 @@
#include <map> #include <map>
#include "CompHash.h" #include "CompHash.h"
#include "BroString.h" #include "ZeekString.h"
#include "Dict.h" #include "Dict.h"
#include "Val.h" #include "Val.h"
#include "RE.h" #include "RE.h"
@ -15,7 +15,7 @@
#include "Func.h" #include "Func.h"
#include "IPAddr.h" #include "IPAddr.h"
CompositeHash::CompositeHash(IntrusivePtr<zeek::TypeList> composite_type) CompositeHash::CompositeHash(zeek::TypeListPtr composite_type)
: type(std::move(composite_type)) : type(std::move(composite_type))
{ {
singleton_tag = zeek::TYPE_INTERNAL_ERROR; singleton_tag = zeek::TYPE_INTERNAL_ERROR;
@ -72,7 +72,7 @@ CompositeHash::~CompositeHash()
// Computes the piece of the hash for Val*, returning the new kp. // Computes the piece of the hash for Val*, returning the new kp.
char* CompositeHash::SingleValHash(bool type_check, char* kp0, char* CompositeHash::SingleValHash(bool type_check, char* kp0,
zeek::Type* bt, Val* v, bool optional) const zeek::Type* bt, zeek::Val* v, bool optional) const
{ {
char* kp1 = nullptr; char* kp1 = nullptr;
zeek::InternalTypeTag t = bt->InternalType(); zeek::InternalTypeTag t = bt->InternalType();
@ -176,7 +176,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
case zeek::TYPE_RECORD: case zeek::TYPE_RECORD:
{ {
char* kp = kp0; char* kp = kp0;
RecordVal* rv = v->AsRecordVal(); zeek::RecordVal* rv = v->AsRecordVal();
zeek::RecordType* rt = bt->AsRecordType(); zeek::RecordType* rt = bt->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
@ -203,13 +203,13 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
case zeek::TYPE_TABLE: case zeek::TYPE_TABLE:
{ {
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
TableVal* tv = v->AsTableVal(); zeek::TableVal* tv = v->AsTableVal();
*kp = tv->Size(); *kp = tv->Size();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
auto tbl = tv->AsTable(); auto tbl = tv->AsTable();
auto it = tbl->InitForIteration(); auto it = tbl->InitForIteration();
auto lv = make_intrusive<ListVal>(zeek::TYPE_ANY); auto lv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY);
struct HashKeyComparer { struct HashKeyComparer {
bool operator()(const HashKey* a, const HashKey* b) const bool operator()(const HashKey* a, const HashKey* b) const
@ -262,7 +262,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
case zeek::TYPE_VECTOR: case zeek::TYPE_VECTOR:
{ {
unsigned int* kp = AlignAndPadType<unsigned int>(kp0); unsigned int* kp = AlignAndPadType<unsigned int>(kp0);
VectorVal* vv = v->AsVectorVal(); zeek::VectorVal* vv = v->AsVectorVal();
zeek::VectorType* vt = v->GetType()->AsVectorType(); zeek::VectorType* vt = v->GetType()->AsVectorType();
*kp = vv->Size(); *kp = vv->Size();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
@ -290,12 +290,12 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
case zeek::TYPE_LIST: case zeek::TYPE_LIST:
{ {
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
ListVal* lv = v->AsListVal(); zeek::ListVal* lv = v->AsListVal();
*kp = lv->Length(); *kp = lv->Length();
kp1 = reinterpret_cast<char*>(kp+1); kp1 = reinterpret_cast<char*>(kp+1);
for ( int i = 0; i < lv->Length(); ++i ) for ( int i = 0; i < lv->Length(); ++i )
{ {
Val* v = lv->Idx(i).get(); zeek::Val* v = lv->Idx(i).get();
if ( ! (kp1 = SingleValHash(type_check, kp1, v->GetType().get(), v, if ( ! (kp1 = SingleValHash(type_check, kp1, v->GetType().get(), v,
false)) ) false)) )
return nullptr; return nullptr;
@ -317,7 +317,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
{ {
// Align to int for the length field. // Align to int for the length field.
int* kp = AlignAndPadType<int>(kp0); int* kp = AlignAndPadType<int>(kp0);
const BroString* sval = v->AsString(); const zeek::String* sval = v->AsString();
*kp = sval->Len(); // so we can recover the value *kp = sval->Len(); // so we can recover the value
@ -336,7 +336,7 @@ char* CompositeHash::SingleValHash(bool type_check, char* kp0,
} }
std::unique_ptr<HashKey> CompositeHash::MakeHashKey(const Val& argv, bool type_check) const std::unique_ptr<HashKey> CompositeHash::MakeHashKey(const zeek::Val& argv, bool type_check) const
{ {
auto v = &argv; auto v = &argv;
@ -345,13 +345,13 @@ std::unique_ptr<HashKey> CompositeHash::MakeHashKey(const Val& argv, bool type_c
if ( is_complex_type && v->GetType()->Tag() != zeek::TYPE_LIST ) if ( is_complex_type && v->GetType()->Tag() != zeek::TYPE_LIST )
{ {
ListVal lv(zeek::TYPE_ANY); zeek::ListVal lv(zeek::TYPE_ANY);
// Cast away const to use ListVal - but since we // Cast away const to use ListVal - but since we
// re-introduce const on the recursive call, it should // re-introduce const on the recursive call, it should
// be okay; the only thing is that the ListVal unref's it. // be okay; the only thing is that the ListVal unref's it.
Val* ncv = (Val*) v; zeek::Val* ncv = (zeek::Val*) v;
lv.Append({NewRef{}, ncv}); lv.Append({zeek::NewRef{}, ncv});
return MakeHashKey(lv, type_check); return MakeHashKey(lv, type_check);
} }
@ -388,7 +388,7 @@ std::unique_ptr<HashKey> CompositeHash::MakeHashKey(const Val& argv, bool type_c
return std::make_unique<HashKey>((k == key), (void*) k, kp - k); return std::make_unique<HashKey>((k == key), (void*) k, kp - k);
} }
std::unique_ptr<HashKey> CompositeHash::ComputeSingletonHash(const Val* v, bool type_check) const std::unique_ptr<HashKey> CompositeHash::ComputeSingletonHash(const zeek::Val* v, bool type_check) const
{ {
if ( v->GetType()->Tag() == zeek::TYPE_LIST ) if ( v->GetType()->Tag() == zeek::TYPE_LIST )
{ {
@ -450,9 +450,9 @@ std::unique_ptr<HashKey> CompositeHash::ComputeSingletonHash(const Val* v, bool
} }
} }
int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v, int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const zeek::Val* v,
bool type_check, int sz, bool optional, bool type_check, int sz, bool optional,
bool calc_static_size) const bool calc_static_size) const
{ {
zeek::InternalTypeTag t = bt->InternalType(); zeek::InternalTypeTag t = bt->InternalType();
@ -509,7 +509,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v,
case zeek::TYPE_RECORD: case zeek::TYPE_RECORD:
{ {
const RecordVal* rv = v ? v->AsRecordVal() : nullptr; const zeek::RecordVal* rv = v ? v->AsRecordVal() : nullptr;
zeek::RecordType* rt = bt->AsRecordType(); zeek::RecordType* rt = bt->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
@ -535,7 +535,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v,
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(int)); sz = SizeAlign(sz, sizeof(int));
TableVal* tv = const_cast<TableVal*>(v->AsTableVal()); zeek::TableVal* tv = const_cast<zeek::TableVal*>(v->AsTableVal());
auto lv = tv->ToListVal(); auto lv = tv->ToListVal();
for ( int i = 0; i < tv->Size(); ++i ) for ( int i = 0; i < tv->Size(); ++i )
{ {
@ -564,7 +564,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v,
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(unsigned int)); sz = SizeAlign(sz, sizeof(unsigned int));
VectorVal* vv = const_cast<VectorVal*>(v->AsVectorVal()); zeek::VectorVal* vv = const_cast<zeek::VectorVal*>(v->AsVectorVal());
for ( unsigned int i = 0; i < vv->Size(); ++i ) for ( unsigned int i = 0; i < vv->Size(); ++i )
{ {
const auto& val = vv->At(i); const auto& val = vv->At(i);
@ -586,7 +586,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v,
return (optional && ! calc_static_size) ? sz : 0; return (optional && ! calc_static_size) ? sz : 0;
sz = SizeAlign(sz, sizeof(int)); sz = SizeAlign(sz, sizeof(int));
ListVal* lv = const_cast<ListVal*>(v->AsListVal()); zeek::ListVal* lv = const_cast<zeek::ListVal*>(v->AsListVal());
for ( int i = 0; i < lv->Length(); ++i ) for ( int i = 0; i < lv->Length(); ++i )
{ {
sz = SingleTypeKeySize(lv->Idx(i)->GetType().get(), lv->Idx(i).get(), sz = SingleTypeKeySize(lv->Idx(i)->GetType().get(), lv->Idx(i).get(),
@ -623,7 +623,7 @@ int CompositeHash::SingleTypeKeySize(zeek::Type* bt, const Val* v,
return sz; return sz;
} }
int CompositeHash::ComputeKeySize(const Val* v, bool type_check, bool calc_static_size) const int CompositeHash::ComputeKeySize(const zeek::Val* v, bool type_check, bool calc_static_size) const
{ {
const auto& tl = type->GetTypes(); const auto& tl = type->GetTypes();
@ -709,16 +709,16 @@ int CompositeHash::SizeAlign(int offset, unsigned int size) const
return offset; return offset;
} }
IntrusivePtr<ListVal> CompositeHash::RecoverVals(const HashKey& k) const zeek::ListValPtr CompositeHash::RecoverVals(const HashKey& k) const
{ {
auto l = make_intrusive<ListVal>(zeek::TYPE_ANY); auto l = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY);
const auto& tl = type->GetTypes(); const auto& tl = type->GetTypes();
const char* kp = (const char*) k.Key(); const char* kp = (const char*) k.Key();
const char* const k_end = kp + k.Size(); const char* const k_end = kp + k.Size();
for ( const auto& type : tl ) for ( const auto& type : tl )
{ {
IntrusivePtr<Val> v; zeek::ValPtr v;
kp = RecoverOneVal(k, kp, k_end, type.get(), &v, false); kp = RecoverOneVal(k, kp, k_end, type.get(), &v, false);
ASSERT(v); ASSERT(v);
l->Append(std::move(v)); l->Append(std::move(v));
@ -730,9 +730,10 @@ IntrusivePtr<ListVal> CompositeHash::RecoverVals(const HashKey& k) const
return l; return l;
} }
const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0, const char* CompositeHash::RecoverOneVal(
const char* const k_end, zeek::Type* t, const HashKey& k, const char* kp0,
IntrusivePtr<Val>* pval, bool optional) const const char* const k_end, zeek::Type* t,
zeek::ValPtr* pval, bool optional) const
{ {
// k->Size() == 0 for a single empty string. // k->Size() == 0 for a single empty string.
if ( kp0 >= k_end && k.Size() > 0 ) if ( kp0 >= k_end && k.Size() > 0 )
@ -763,9 +764,9 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
if ( tag == zeek::TYPE_ENUM ) if ( tag == zeek::TYPE_ENUM )
*pval = t->AsEnumType()->GetVal(*kp); *pval = t->AsEnumType()->GetVal(*kp);
else if ( tag == zeek::TYPE_BOOL ) else if ( tag == zeek::TYPE_BOOL )
*pval = val_mgr->Bool(*kp); *pval = zeek::val_mgr->Bool(*kp);
else if ( tag == zeek::TYPE_INT ) else if ( tag == zeek::TYPE_INT )
*pval = val_mgr->Int(*kp); *pval = zeek::val_mgr->Int(*kp);
else else
{ {
reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()"); reporter->InternalError("bad internal unsigned int in CompositeHash::RecoverOneVal()");
@ -782,11 +783,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
switch ( tag ) { switch ( tag ) {
case zeek::TYPE_COUNT: case zeek::TYPE_COUNT:
case zeek::TYPE_COUNTER: case zeek::TYPE_COUNTER:
*pval = val_mgr->Count(*kp); *pval = zeek::val_mgr->Count(*kp);
break; break;
case zeek::TYPE_PORT: case zeek::TYPE_PORT:
*pval = val_mgr->Port(*kp); *pval = zeek::val_mgr->Port(*kp);
break; break;
default: default:
@ -803,11 +804,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
if ( tag == zeek::TYPE_INTERVAL ) if ( tag == zeek::TYPE_INTERVAL )
*pval = make_intrusive<IntervalVal>(*kp, 1.0); *pval = zeek::make_intrusive<zeek::IntervalVal>(*kp, 1.0);
else if ( tag == zeek::TYPE_TIME ) else if ( tag == zeek::TYPE_TIME )
*pval = make_intrusive<TimeVal>(*kp); *pval = zeek::make_intrusive<zeek::TimeVal>(*kp);
else else
*pval = make_intrusive<DoubleVal>(*kp); *pval = zeek::make_intrusive<zeek::DoubleVal>(*kp);
} }
break; break;
@ -820,7 +821,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
switch ( tag ) { switch ( tag ) {
case zeek::TYPE_ADDR: case zeek::TYPE_ADDR:
*pval = make_intrusive<AddrVal>(addr); *pval = zeek::make_intrusive<zeek::AddrVal>(addr);
break; break;
default: default:
@ -835,7 +836,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
{ {
const uint32_t* const kp = AlignType<uint32_t>(kp0); const uint32_t* const kp = AlignType<uint32_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+5); kp1 = reinterpret_cast<const char*>(kp+5);
*pval = make_intrusive<SubNetVal>(kp, kp[4]); *pval = zeek::make_intrusive<zeek::SubNetVal>(kp, kp[4]);
} }
break; break;
@ -848,12 +849,12 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
const uint32_t* const kp = AlignType<uint32_t>(kp0); const uint32_t* const kp = AlignType<uint32_t>(kp0);
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
const auto& f = Func::GetFuncPtrByID(*kp); const auto& f = zeek::Func::GetFuncPtrByID(*kp);
if ( ! f ) if ( ! f )
reporter->InternalError("failed to look up unique function id %" PRIu32 " in CompositeHash::RecoverOneVal()", *kp); reporter->InternalError("failed to look up unique function id %" PRIu32 " in CompositeHash::RecoverOneVal()", *kp);
*pval = make_intrusive<Val>(f); *pval = zeek::make_intrusive<zeek::Val>(f);
const auto& pvt = (*pval)->GetType(); const auto& pvt = (*pval)->GetType();
if ( ! pvt ) if ( ! pvt )
@ -893,7 +894,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
reporter->InternalError("failed compiling table/set key pattern: %s", reporter->InternalError("failed compiling table/set key pattern: %s",
re->PatternText()); re->PatternText());
*pval = make_intrusive<PatternVal>(re); *pval = zeek::make_intrusive<zeek::PatternVal>(re);
} }
break; break;
@ -903,11 +904,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
zeek::RecordType* rt = t->AsRecordType(); zeek::RecordType* rt = t->AsRecordType();
int num_fields = rt->NumFields(); int num_fields = rt->NumFields();
std::vector<IntrusivePtr<Val>> values; std::vector<zeek::ValPtr> values;
int i; int i;
for ( i = 0; i < num_fields; ++i ) for ( i = 0; i < num_fields; ++i )
{ {
IntrusivePtr<Val> v; zeek::ValPtr v;
zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get(); zeek::detail::Attributes* a = rt->FieldDecl(i)->attrs.get();
bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL)); bool optional = (a && a->Find(zeek::detail::ATTR_OPTIONAL));
@ -930,7 +931,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
ASSERT(int(values.size()) == num_fields); ASSERT(int(values.size()) == num_fields);
auto rv = make_intrusive<RecordVal>(IntrusivePtr{NewRef{}, rt}); auto rv = zeek::make_intrusive<zeek::RecordVal>(zeek::IntrusivePtr{zeek::NewRef{}, rt});
for ( int i = 0; i < num_fields; ++i ) for ( int i = 0; i < num_fields; ++i )
rv->Assign(i, std::move(values[i])); rv->Assign(i, std::move(values[i]));
@ -947,18 +948,18 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::TableType* tt = t->AsTableType(); zeek::TableType* tt = t->AsTableType();
auto tv = make_intrusive<TableVal>(IntrusivePtr{NewRef{}, tt}); auto tv = zeek::make_intrusive<zeek::TableVal>(zeek::IntrusivePtr{zeek::NewRef{}, tt});
for ( int i = 0; i < n; ++i ) for ( int i = 0; i < n; ++i )
{ {
IntrusivePtr<Val> key; zeek::ValPtr key;
kp1 = RecoverOneVal(k, kp1, k_end, tt->GetIndices().get(), &key, false); kp1 = RecoverOneVal(k, kp1, k_end, tt->GetIndices().get(), &key, false);
if ( t->IsSet() ) if ( t->IsSet() )
tv->Assign(std::move(key), nullptr); tv->Assign(std::move(key), nullptr);
else else
{ {
IntrusivePtr<Val> value; zeek::ValPtr value;
kp1 = RecoverOneVal(k, kp1, k_end, tt->Yield().get(), &value, kp1 = RecoverOneVal(k, kp1, k_end, tt->Yield().get(), &value,
false); false);
tv->Assign(std::move(key), std::move(value)); tv->Assign(std::move(key), std::move(value));
@ -976,7 +977,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::VectorType* vt = t->AsVectorType(); zeek::VectorType* vt = t->AsVectorType();
auto vv = make_intrusive<VectorVal>(IntrusivePtr{NewRef{}, vt}); auto vv = zeek::make_intrusive<zeek::VectorVal>(zeek::IntrusivePtr{zeek::NewRef{}, vt});
for ( unsigned int i = 0; i < n; ++i ) for ( unsigned int i = 0; i < n; ++i )
{ {
@ -986,7 +987,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
kp = AlignType<unsigned int>(kp1); kp = AlignType<unsigned int>(kp1);
unsigned int have_val = *kp; unsigned int have_val = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
IntrusivePtr<Val> value; zeek::ValPtr value;
if ( have_val ) if ( have_val )
kp1 = RecoverOneVal(k, kp1, k_end, vt->Yield().get(), &value, kp1 = RecoverOneVal(k, kp1, k_end, vt->Yield().get(), &value,
@ -1006,11 +1007,11 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
n = *kp; n = *kp;
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
zeek::TypeList* tl = t->AsTypeList(); zeek::TypeList* tl = t->AsTypeList();
auto lv = make_intrusive<ListVal>(zeek::TYPE_ANY); auto lv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ANY);
for ( int i = 0; i < n; ++i ) for ( int i = 0; i < n; ++i )
{ {
IntrusivePtr<Val> v; zeek::ValPtr v;
zeek::Type* it = tl->GetTypes()[i].get(); zeek::Type* it = tl->GetTypes()[i].get();
kp1 = RecoverOneVal(k, kp1, k_end, it, &v, false); kp1 = RecoverOneVal(k, kp1, k_end, it, &v, false);
lv->Append(std::move(v)); lv->Append(std::move(v));
@ -1046,7 +1047,7 @@ const char* CompositeHash::RecoverOneVal(const HashKey& k, const char* kp0,
kp1 = reinterpret_cast<const char*>(kp+1); kp1 = reinterpret_cast<const char*>(kp+1);
} }
*pval = make_intrusive<StringVal>(new BroString((const byte_vec) kp1, n, true)); *pval = zeek::make_intrusive<zeek::StringVal>(new zeek::String((const zeek::byte_vec) kp1, n, true));
kp1 += n; kp1 += n;
} }
break; break;

View file

@ -7,46 +7,50 @@
#include "Type.h" #include "Type.h"
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
class ListVal; ZEEK_FORWARD_DECLARE_NAMESPACED(ListVal, zeek);
class HashKey; class HashKey;
namespace zeek {
using ListValPtr = zeek::IntrusivePtr<ListVal>;
}
class CompositeHash { class CompositeHash {
public: public:
explicit CompositeHash(IntrusivePtr<zeek::TypeList> composite_type); explicit CompositeHash(zeek::TypeListPtr composite_type);
~CompositeHash(); ~CompositeHash();
// Compute the hash corresponding to the given index val, // Compute the hash corresponding to the given index val,
// or nullptr if it fails to typecheck. // or nullptr if it fails to typecheck.
std::unique_ptr<HashKey> MakeHashKey(const Val& v, bool type_check) const; std::unique_ptr<HashKey> MakeHashKey(const zeek::Val& v, bool type_check) const;
[[deprecated("Remove in v4.1. Use MakeHashKey().")]] [[deprecated("Remove in v4.1. Use MakeHashKey().")]]
HashKey* ComputeHash(const Val* v, bool type_check) const HashKey* ComputeHash(const zeek::Val* v, bool type_check) const
{ return MakeHashKey(*v, type_check).release(); } { return MakeHashKey(*v, type_check).release(); }
// Given a hash key, recover the values used to create it. // Given a hash key, recover the values used to create it.
IntrusivePtr<ListVal> RecoverVals(const HashKey& k) const; zeek::ListValPtr RecoverVals(const HashKey& k) const;
[[deprecated("Remove in v4.1. Pass in HashKey& instead.")]] [[deprecated("Remove in v4.1. Pass in HashKey& instead.")]]
IntrusivePtr<ListVal> RecoverVals(const HashKey* k) const zeek::ListValPtr RecoverVals(const HashKey* k) const
{ return RecoverVals(*k); } { return RecoverVals(*k); }
unsigned int MemoryAllocation() const { return padded_sizeof(*this) + pad_size(size); } unsigned int MemoryAllocation() const { return padded_sizeof(*this) + pad_size(size); }
protected: protected:
std::unique_ptr<HashKey> ComputeSingletonHash(const Val* v, bool type_check) const; std::unique_ptr<HashKey> ComputeSingletonHash(const zeek::Val* v, bool type_check) const;
// Computes the piece of the hash for Val*, returning the new kp. // Computes the piece of the hash for Val*, returning the new kp.
// Used as a helper for ComputeHash in the non-singleton case. // Used as a helper for ComputeHash in the non-singleton case.
char* SingleValHash(bool type_check, char* kp, zeek::Type* bt, Val* v, char* SingleValHash(bool type_check, char* kp, zeek::Type* bt, zeek::Val* v,
bool optional) const; bool optional) const;
// Recovers just one Val of possibly many; called from RecoverVals. // Recovers just one Val of possibly many; called from RecoverVals.
// Upon return, pval will point to the recovered Val of type t. // Upon return, pval will point to the recovered Val of type t.
// Returns and updated kp for the next Val. Calls reporter->InternalError() // Returns and updated kp for the next Val. Calls reporter->InternalError()
// upon errors, so there is no return value for invalid input. // upon errors, so there is no return value for invalid input.
const char* RecoverOneVal(const HashKey& k, const char* RecoverOneVal(
const char* kp, const char* const k_end, const HashKey& k, const char* kp, const char* const k_end,
zeek::Type* t, IntrusivePtr<Val>* pval, bool optional) const; zeek::Type* t, zeek::ValPtr* pval, bool optional) const;
// Rounds the given pointer up to the nearest multiple of the // Rounds the given pointer up to the nearest multiple of the
// given size, if not already a multiple. // given size, if not already a multiple.
@ -82,14 +86,14 @@ protected:
// the value is computed for the particular list of values. // the value is computed for the particular list of values.
// Returns 0 if the key has an indeterminant size (if v not given), // Returns 0 if the key has an indeterminant size (if v not given),
// or if v doesn't match the index type (if given). // or if v doesn't match the index type (if given).
int ComputeKeySize(const Val* v, bool type_check, int ComputeKeySize(const zeek::Val* v, bool type_check,
bool calc_static_size) const; bool calc_static_size) const;
int SingleTypeKeySize(zeek::Type*, const Val*, int SingleTypeKeySize(zeek::Type*, const zeek::Val*,
bool type_check, int sz, bool optional, bool type_check, int sz, bool optional,
bool calc_static_size) const; bool calc_static_size) const;
IntrusivePtr<zeek::TypeList> type; zeek::TypeListPtr type;
char* key; // space for composite key char* key; // space for composite key
int size; int size;
bool is_singleton; // if just one type in index bool is_singleton; // if just one type in index

View file

@ -266,8 +266,8 @@ void Connection::HistoryThresholdEvent(EventHandlerPtr e, bool is_orig,
EnqueueEvent(e, nullptr, EnqueueEvent(e, nullptr,
ConnVal(), ConnVal(),
val_mgr->Bool(is_orig), zeek::val_mgr->Bool(is_orig),
val_mgr->Count(threshold) zeek::val_mgr->Count(threshold)
); );
} }
@ -337,74 +337,74 @@ void Connection::StatusUpdateTimer(double t)
TIMER_CONN_STATUS_UPDATE); TIMER_CONN_STATUS_UPDATE);
} }
RecordVal* Connection::BuildConnVal() zeek::RecordVal* Connection::BuildConnVal()
{ {
return ConnVal()->Ref()->AsRecordVal(); return ConnVal()->Ref()->AsRecordVal();
} }
const IntrusivePtr<RecordVal>& Connection::ConnVal() const zeek::RecordValPtr& Connection::ConnVal()
{ {
if ( ! conn_val ) if ( ! conn_val )
{ {
conn_val = make_intrusive<RecordVal>(zeek::id::connection); conn_val = zeek::make_intrusive<zeek::RecordVal>(zeek::id::connection);
TransportProto prot_type = ConnTransport(); TransportProto prot_type = ConnTransport();
auto id_val = make_intrusive<RecordVal>(zeek::id::conn_id); auto id_val = zeek::make_intrusive<zeek::RecordVal>(zeek::id::conn_id);
id_val->Assign(0, make_intrusive<AddrVal>(orig_addr)); id_val->Assign(0, zeek::make_intrusive<zeek::AddrVal>(orig_addr));
id_val->Assign(1, val_mgr->Port(ntohs(orig_port), prot_type)); id_val->Assign(1, zeek::val_mgr->Port(ntohs(orig_port), prot_type));
id_val->Assign(2, make_intrusive<AddrVal>(resp_addr)); id_val->Assign(2, zeek::make_intrusive<zeek::AddrVal>(resp_addr));
id_val->Assign(3, val_mgr->Port(ntohs(resp_port), prot_type)); id_val->Assign(3, zeek::val_mgr->Port(ntohs(resp_port), prot_type));
auto orig_endp = make_intrusive<RecordVal>(zeek::id::endpoint); auto orig_endp = zeek::make_intrusive<zeek::RecordVal>(zeek::id::endpoint);
orig_endp->Assign(0, val_mgr->Count(0)); orig_endp->Assign(0, zeek::val_mgr->Count(0));
orig_endp->Assign(1, val_mgr->Count(0)); orig_endp->Assign(1, zeek::val_mgr->Count(0));
orig_endp->Assign(4, val_mgr->Count(orig_flow_label)); orig_endp->Assign(4, zeek::val_mgr->Count(orig_flow_label));
const int l2_len = sizeof(orig_l2_addr); const int l2_len = sizeof(orig_l2_addr);
char null[l2_len]{}; char null[l2_len]{};
if ( memcmp(&orig_l2_addr, &null, l2_len) != 0 ) if ( memcmp(&orig_l2_addr, &null, l2_len) != 0 )
orig_endp->Assign(5, make_intrusive<StringVal>(fmt_mac(orig_l2_addr, l2_len))); orig_endp->Assign(5, zeek::make_intrusive<zeek::StringVal>(fmt_mac(orig_l2_addr, l2_len)));
auto resp_endp = make_intrusive<RecordVal>(zeek::id::endpoint); auto resp_endp = zeek::make_intrusive<zeek::RecordVal>(zeek::id::endpoint);
resp_endp->Assign(0, val_mgr->Count(0)); resp_endp->Assign(0, zeek::val_mgr->Count(0));
resp_endp->Assign(1, val_mgr->Count(0)); resp_endp->Assign(1, zeek::val_mgr->Count(0));
resp_endp->Assign(4, val_mgr->Count(resp_flow_label)); resp_endp->Assign(4, zeek::val_mgr->Count(resp_flow_label));
if ( memcmp(&resp_l2_addr, &null, l2_len) != 0 ) if ( memcmp(&resp_l2_addr, &null, l2_len) != 0 )
resp_endp->Assign(5, make_intrusive<StringVal>(fmt_mac(resp_l2_addr, l2_len))); resp_endp->Assign(5, zeek::make_intrusive<zeek::StringVal>(fmt_mac(resp_l2_addr, l2_len)));
conn_val->Assign(0, std::move(id_val)); conn_val->Assign(0, std::move(id_val));
conn_val->Assign(1, std::move(orig_endp)); conn_val->Assign(1, std::move(orig_endp));
conn_val->Assign(2, std::move(resp_endp)); conn_val->Assign(2, std::move(resp_endp));
// 3 and 4 are set below. // 3 and 4 are set below.
conn_val->Assign(5, make_intrusive<TableVal>(zeek::id::string_set)); // service conn_val->Assign(5, zeek::make_intrusive<zeek::TableVal>(zeek::id::string_set)); // service
conn_val->Assign(6, val_mgr->EmptyString()); // history conn_val->Assign(6, zeek::val_mgr->EmptyString()); // history
if ( ! uid ) if ( ! uid )
uid.Set(bits_per_uid); uid.Set(bits_per_uid);
conn_val->Assign(7, make_intrusive<StringVal>(uid.Base62("C").c_str())); conn_val->Assign(7, zeek::make_intrusive<zeek::StringVal>(uid.Base62("C").c_str()));
if ( encapsulation && encapsulation->Depth() > 0 ) if ( encapsulation && encapsulation->Depth() > 0 )
conn_val->Assign(8, encapsulation->ToVal()); conn_val->Assign(8, encapsulation->ToVal());
if ( vlan != 0 ) if ( vlan != 0 )
conn_val->Assign(9, val_mgr->Int(vlan)); conn_val->Assign(9, zeek::val_mgr->Int(vlan));
if ( inner_vlan != 0 ) if ( inner_vlan != 0 )
conn_val->Assign(10, val_mgr->Int(inner_vlan)); conn_val->Assign(10, zeek::val_mgr->Int(inner_vlan));
} }
if ( root_analyzer ) if ( root_analyzer )
root_analyzer->UpdateConnVal(conn_val.get()); root_analyzer->UpdateConnVal(conn_val.get());
conn_val->Assign(3, make_intrusive<TimeVal>(start_time)); // ### conn_val->Assign(3, zeek::make_intrusive<zeek::TimeVal>(start_time)); // ###
conn_val->Assign(4, make_intrusive<IntervalVal>(last_time - start_time)); conn_val->Assign(4, zeek::make_intrusive<zeek::IntervalVal>(last_time - start_time));
conn_val->Assign(6, make_intrusive<StringVal>(history.c_str())); conn_val->Assign(6, zeek::make_intrusive<zeek::StringVal>(history.c_str()));
conn_val->Assign(11, val_mgr->Bool(is_successful)); conn_val->Assign(11, zeek::val_mgr->Bool(is_successful));
conn_val->SetOrigin(this); conn_val->SetOrigin(this);
@ -433,7 +433,7 @@ void Connection::AppendAddl(const char* str)
const char* old = cv->GetField(6)->AsString()->CheckString(); const char* old = cv->GetField(6)->AsString()->CheckString();
const char* format = *old ? "%s %s" : "%s%s"; const char* format = *old ? "%s %s" : "%s%s";
cv->Assign(6, make_intrusive<StringVal>(fmt(format, old, str))); cv->Assign(6, zeek::make_intrusive<zeek::StringVal>(fmt(format, old, str)));
} }
// Returns true if the character at s separates a version number. // Returns true if the character at s separates a version number.
@ -470,12 +470,12 @@ void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, const ch
return; return;
if ( name ) if ( name )
EnqueueEvent(f, analyzer, make_intrusive<StringVal>(name), ConnVal()); EnqueueEvent(f, analyzer, zeek::make_intrusive<zeek::StringVal>(name), ConnVal());
else else
EnqueueEvent(f, analyzer, ConnVal()); EnqueueEvent(f, analyzer, ConnVal());
} }
void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2) void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2)
{ {
if ( ! f ) if ( ! f )
{ {
@ -487,12 +487,12 @@ void Connection::Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1,
if ( v2 ) if ( v2 )
EnqueueEvent(f, analyzer, EnqueueEvent(f, analyzer,
ConnVal(), ConnVal(),
IntrusivePtr{AdoptRef{}, v1}, zeek::IntrusivePtr{zeek::AdoptRef{}, v1},
IntrusivePtr{AdoptRef{}, v2}); zeek::IntrusivePtr{zeek::AdoptRef{}, v2});
else else
EnqueueEvent(f, analyzer, EnqueueEvent(f, analyzer,
ConnVal(), ConnVal(),
IntrusivePtr{AdoptRef{}, v1}); zeek::IntrusivePtr{zeek::AdoptRef{}, v1});
} }
void Connection::ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* a, val_list vl) void Connection::ConnectionEvent(EventHandlerPtr f, analyzer::Analyzer* a, val_list vl)
@ -697,8 +697,8 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label)
{ {
if ( conn_val ) if ( conn_val )
{ {
RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal(); zeek::RecordVal* endp = conn_val->GetField(is_orig ? 1 : 2)->AsRecordVal();
endp->Assign(4, val_mgr->Count(flow_label)); endp->Assign(4, zeek::val_mgr->Count(flow_label));
} }
if ( connection_flow_label_changed && if ( connection_flow_label_changed &&
@ -706,9 +706,9 @@ void Connection::CheckFlowLabel(bool is_orig, uint32_t flow_label)
{ {
EnqueueEvent(connection_flow_label_changed, nullptr, EnqueueEvent(connection_flow_label_changed, nullptr,
ConnVal(), ConnVal(),
val_mgr->Bool(is_orig), zeek::val_mgr->Bool(is_orig),
val_mgr->Count(my_flow_label), zeek::val_mgr->Count(my_flow_label),
val_mgr->Count(flow_label) zeek::val_mgr->Count(flow_label)
); );
} }

View file

@ -29,8 +29,13 @@ class RuleHdrTest;
class Specific_RE_Matcher; class Specific_RE_Matcher;
class RuleEndpointState; class RuleEndpointState;
class EncapsulationStack; class EncapsulationStack;
class Val;
class RecordVal; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek {
using ValPtr = zeek::IntrusivePtr<Val>;
using RecordValPtr = zeek::IntrusivePtr<RecordVal>;
}
namespace analyzer { class TransportLayerAnalyzer; } namespace analyzer { class TransportLayerAnalyzer; }
@ -59,7 +64,7 @@ static inline int addr_port_canon_lt(const IPAddr& addr1, uint32_t p1,
namespace analyzer { class Analyzer; } namespace analyzer { class Analyzer; }
class Connection final : public BroObj { class Connection final : public zeek::Obj {
public: public:
Connection(NetSessions* s, const ConnIDKey& k, double t, const ConnID* id, Connection(NetSessions* s, const ConnIDKey& k, double t, const ConnID* id,
uint32_t flow, const Packet* pkt, const EncapsulationStack* arg_encap); uint32_t flow, const Packet* pkt, const EncapsulationStack* arg_encap);
@ -164,12 +169,12 @@ public:
void EnableStatusUpdateTimer(); void EnableStatusUpdateTimer();
[[deprecated("Remove in v4.1. Use ConnVal() instead.")]] [[deprecated("Remove in v4.1. Use ConnVal() instead.")]]
RecordVal* BuildConnVal(); zeek::RecordVal* BuildConnVal();
/** /**
* Returns the associated "connection" record. * Returns the associated "connection" record.
*/ */
const IntrusivePtr<RecordVal>& ConnVal(); const zeek::RecordValPtr& ConnVal();
void AppendAddl(const char* str); void AppendAddl(const char* str);
@ -194,7 +199,7 @@ public:
// argument is the connection value, second argument is 'v1', and if 'v2' // argument is the connection value, second argument is 'v1', and if 'v2'
// is given that will be it's third argument. // is given that will be it's third argument.
[[deprecated("Remove in v4.1. Use EnqueueEvent() instead (note it doesn't automatically add the connection argument).")]] [[deprecated("Remove in v4.1. Use EnqueueEvent() instead (note it doesn't automatically add the connection argument).")]]
void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, Val* v1, Val* v2 = nullptr); void Event(EventHandlerPtr f, analyzer::Analyzer* analyzer, zeek::Val* v1, zeek::Val* v2 = nullptr);
// If a handler exists for 'f', an event will be generated. In any case, // If a handler exists for 'f', an event will be generated. In any case,
// reference count for each element in the 'vl' list are decremented. The // reference count for each element in the 'vl' list are decremented. The
@ -234,8 +239,8 @@ public:
*/ */
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v< std::is_convertible_v<
std::tuple_element_t<0, std::tuple<Args...>>, IntrusivePtr<Val>>> std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>>
EnqueueEvent(EventHandlerPtr h, analyzer::Analyzer* analyzer, Args&&... args) EnqueueEvent(EventHandlerPtr h, analyzer::Analyzer* analyzer, Args&&... args)
{ return EnqueueEvent(h, analyzer, zeek::Args{std::forward<Args>(args)...}); } { return EnqueueEvent(h, analyzer, zeek::Args{std::forward<Args>(args)...}); }
@ -355,7 +360,7 @@ protected:
u_char resp_l2_addr[Packet::l2_addr_len]; // Link-layer responder address, if available u_char resp_l2_addr[Packet::l2_addr_len]; // Link-layer responder address, if available
double start_time, last_time; double start_time, last_time;
double inactivity_timeout; double inactivity_timeout;
IntrusivePtr<RecordVal> conn_val; zeek::RecordValPtr conn_val;
LoginConn* login_conn; // either nil, or this LoginConn* login_conn; // either nil, or this
const EncapsulationStack* encapsulation; // tunnels const EncapsulationStack* encapsulation; // tunnels
int suppress_event; // suppress certain events to once per conn. int suppress_event; // suppress certain events to once per conn.

View file

@ -49,7 +49,6 @@ private:
int current_level; int current_level;
int suspend_level; int suspend_level;
typedef PList<void> voidp_list; using voidp_list = zeek::PList<void>;
voidp_list states; voidp_list states;
}; };

View file

@ -24,7 +24,7 @@ class DFA_State;
class DFA_Machine; class DFA_Machine;
class DFA_State; class DFA_State;
class DFA_State : public BroObj { class DFA_State : public zeek::Obj {
public: public:
DFA_State(int state_num, const EquivClass* ec, DFA_State(int state_num, const EquivClass* ec,
NFA_state_list* nfa_states, AcceptingSet* accept); NFA_state_list* nfa_states, AcceptingSet* accept);
@ -109,7 +109,7 @@ private:
std::map<DigestStr, DFA_State*> states; std::map<DigestStr, DFA_State*> states;
}; };
class DFA_Machine : public BroObj { class DFA_Machine : public zeek::Obj {
public: public:
DFA_Machine(NFA_Machine* n, EquivClass* ec); DFA_Machine(NFA_Machine* n, EquivClass* ec);
~DFA_Machine() override; ~DFA_Machine() override;

View file

@ -31,7 +31,7 @@
#include <algorithm> #include <algorithm>
#include "BroString.h" #include "ZeekString.h"
#include "Expr.h" #include "Expr.h"
#include "Event.h" #include "Event.h"
#include "Net.h" #include "Net.h"
@ -122,9 +122,9 @@ public:
return req_host ? req_host : req_addr.AsString(); return req_host ? req_host : req_addr.AsString();
} }
IntrusivePtr<ListVal> Addrs(); zeek::ListValPtr Addrs();
IntrusivePtr<TableVal> AddrsSet(); // addresses returned as a set zeek::TableValPtr AddrsSet(); // addresses returned as a set
IntrusivePtr<StringVal> Host(); zeek::StringValPtr Host();
double CreationTime() const { return creation_time; } double CreationTime() const { return creation_time; }
@ -155,11 +155,11 @@ protected:
int num_names; int num_names;
char** names; char** names;
IntrusivePtr<StringVal> host_val; zeek::StringValPtr host_val;
int num_addrs; int num_addrs;
IPAddr* addrs; IPAddr* addrs;
IntrusivePtr<ListVal> addrs_val; zeek::ListValPtr addrs_val;
double creation_time; double creation_time;
int map_type; int map_type;
@ -173,13 +173,13 @@ void DNS_Mgr_mapping_delete_func(void* v)
delete (DNS_Mapping*) v; delete (DNS_Mapping*) v;
} }
static IntrusivePtr<TableVal> empty_addr_set() static zeek::TableValPtr empty_addr_set()
{ {
auto addr_t = zeek::base_type(zeek::TYPE_ADDR); auto addr_t = zeek::base_type(zeek::TYPE_ADDR);
auto set_index = make_intrusive<zeek::TypeList>(addr_t); auto set_index = zeek::make_intrusive<zeek::TypeList>(addr_t);
set_index->Append(std::move(addr_t)); set_index->Append(std::move(addr_t));
auto s = make_intrusive<zeek::SetType>(std::move(set_index), nullptr); auto s = zeek::make_intrusive<zeek::SetType>(std::move(set_index), nullptr);
return make_intrusive<TableVal>(std::move(s)); return zeek::make_intrusive<zeek::TableVal>(std::move(s));
} }
DNS_Mapping::DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl) DNS_Mapping::DNS_Mapping(const char* host, struct hostent* h, uint32_t ttl)
@ -276,23 +276,23 @@ DNS_Mapping::~DNS_Mapping()
delete [] addrs; delete [] addrs;
} }
IntrusivePtr<ListVal> DNS_Mapping::Addrs() zeek::ListValPtr DNS_Mapping::Addrs()
{ {
if ( failed ) if ( failed )
return nullptr; return nullptr;
if ( ! addrs_val ) if ( ! addrs_val )
{ {
addrs_val = make_intrusive<ListVal>(zeek::TYPE_ADDR); addrs_val = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR);
for ( int i = 0; i < num_addrs; ++i ) for ( int i = 0; i < num_addrs; ++i )
addrs_val->Append(make_intrusive<AddrVal>(addrs[i])); addrs_val->Append(zeek::make_intrusive<zeek::AddrVal>(addrs[i]));
} }
return addrs_val; return addrs_val;
} }
IntrusivePtr<TableVal> DNS_Mapping::AddrsSet() { zeek::TableValPtr DNS_Mapping::AddrsSet() {
auto l = Addrs(); auto l = Addrs();
if ( ! l ) if ( ! l )
@ -301,13 +301,13 @@ IntrusivePtr<TableVal> DNS_Mapping::AddrsSet() {
return l->ToSetVal(); return l->ToSetVal();
} }
IntrusivePtr<StringVal> DNS_Mapping::Host() zeek::StringValPtr DNS_Mapping::Host()
{ {
if ( failed || num_names == 0 || ! names[0] ) if ( failed || num_names == 0 || ! names[0] )
return nullptr; return nullptr;
if ( ! host_val ) if ( ! host_val )
host_val = make_intrusive<StringVal>(names[0]); host_val = zeek::make_intrusive<zeek::StringVal>(names[0]);
return host_val; return host_val;
} }
@ -461,12 +461,12 @@ void DNS_Mgr::InitPostScript()
LoadCache(fopen(cache_name, "r")); LoadCache(fopen(cache_name, "r"));
} }
static IntrusivePtr<TableVal> fake_name_lookup_result(const char* name) static zeek::TableValPtr fake_name_lookup_result(const char* name)
{ {
hash128_t hash; hash128_t hash;
KeyedHash::StaticHash128(name, strlen(name), &hash); KeyedHash::StaticHash128(name, strlen(name), &hash);
auto hv = make_intrusive<ListVal>(zeek::TYPE_ADDR); auto hv = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR);
hv->Append(make_intrusive<AddrVal>(reinterpret_cast<const uint32_t*>(&hash))); hv->Append(zeek::make_intrusive<zeek::AddrVal>(reinterpret_cast<const uint32_t*>(&hash)));
return hv->ToSetVal(); return hv->ToSetVal();
} }
@ -485,7 +485,7 @@ static const char* fake_addr_lookup_result(const IPAddr& addr)
return tmp; return tmp;
} }
IntrusivePtr<TableVal> DNS_Mgr::LookupHost(const char* name) zeek::TableValPtr DNS_Mgr::LookupHost(const char* name)
{ {
if ( mode == DNS_FAKE ) if ( mode == DNS_FAKE )
return fake_name_lookup_result(name); return fake_name_lookup_result(name);
@ -542,7 +542,7 @@ IntrusivePtr<TableVal> DNS_Mgr::LookupHost(const char* name)
} }
} }
IntrusivePtr<Val> DNS_Mgr::LookupAddr(const IPAddr& addr) zeek::ValPtr DNS_Mgr::LookupAddr(const IPAddr& addr)
{ {
InitSource(); InitSource();
@ -559,7 +559,7 @@ IntrusivePtr<Val> DNS_Mgr::LookupAddr(const IPAddr& addr)
{ {
string s(addr); string s(addr);
reporter->Warning("can't resolve IP address: %s", s.c_str()); reporter->Warning("can't resolve IP address: %s", s.c_str());
return make_intrusive<StringVal>(s.c_str()); return zeek::make_intrusive<zeek::StringVal>(s.c_str());
} }
} }
} }
@ -568,7 +568,7 @@ IntrusivePtr<Val> DNS_Mgr::LookupAddr(const IPAddr& addr)
switch ( mode ) { switch ( mode ) {
case DNS_PRIME: case DNS_PRIME:
requests.push_back(new DNS_Mgr_Request(addr)); requests.push_back(new DNS_Mgr_Request(addr));
return make_intrusive<StringVal>("<none>"); return zeek::make_intrusive<zeek::StringVal>("<none>");
case DNS_FORCE: case DNS_FORCE:
reporter->FatalError("can't find DNS entry for %s in cache", reporter->FatalError("can't find DNS entry for %s in cache",
@ -698,7 +698,7 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm)
} }
void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm, void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* dm,
IntrusivePtr<ListVal> l1, IntrusivePtr<ListVal> l2) zeek::ListValPtr l1, zeek::ListValPtr l2)
{ {
if ( ! e ) if ( ! e )
return; return;
@ -714,17 +714,17 @@ void DNS_Mgr::Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm)
mgr.Enqueue(e, BuildMappingVal(old_dm), BuildMappingVal(new_dm)); mgr.Enqueue(e, BuildMappingVal(old_dm), BuildMappingVal(new_dm));
} }
IntrusivePtr<Val> DNS_Mgr::BuildMappingVal(DNS_Mapping* dm) zeek::ValPtr DNS_Mgr::BuildMappingVal(DNS_Mapping* dm)
{ {
auto r = make_intrusive<RecordVal>(dm_rec); auto r = zeek::make_intrusive<zeek::RecordVal>(dm_rec);
r->Assign(0, make_intrusive<TimeVal>(dm->CreationTime())); r->Assign(0, zeek::make_intrusive<zeek::TimeVal>(dm->CreationTime()));
r->Assign(1, make_intrusive<StringVal>(dm->ReqHost() ? dm->ReqHost() : "")); r->Assign(1, zeek::make_intrusive<zeek::StringVal>(dm->ReqHost() ? dm->ReqHost() : ""));
r->Assign(2, make_intrusive<AddrVal>(dm->ReqAddr())); r->Assign(2, zeek::make_intrusive<zeek::AddrVal>(dm->ReqAddr()));
r->Assign(3, val_mgr->Bool(dm->Valid())); r->Assign(3, zeek::val_mgr->Bool(dm->Valid()));
auto h = dm->Host(); auto h = dm->Host();
r->Assign(4, h ? std::move(h) : make_intrusive<StringVal>("<none>")); r->Assign(4, h ? std::move(h) : zeek::make_intrusive<zeek::StringVal>("<none>"));
r->Assign(5, dm->AddrsSet()); r->Assign(5, dm->AddrsSet());
return r; return r;
@ -870,9 +870,9 @@ void DNS_Mgr::CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm)
Event(dns_mapping_altered, new_dm, std::move(prev_delta), std::move(new_delta)); Event(dns_mapping_altered, new_dm, std::move(prev_delta), std::move(new_delta));
} }
IntrusivePtr<ListVal> DNS_Mgr::AddrListDelta(ListVal* al1, ListVal* al2) zeek::ListValPtr DNS_Mgr::AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2)
{ {
auto delta = make_intrusive<ListVal>(zeek::TYPE_ADDR); auto delta = zeek::make_intrusive<zeek::ListVal>(zeek::TYPE_ADDR);
for ( int i = 0; i < al1->Length(); ++i ) for ( int i = 0; i < al1->Length(); ++i )
{ {
@ -894,7 +894,7 @@ IntrusivePtr<ListVal> DNS_Mgr::AddrListDelta(ListVal* al1, ListVal* al2)
return delta; return delta;
} }
void DNS_Mgr::DumpAddrList(FILE* f, ListVal* al) void DNS_Mgr::DumpAddrList(FILE* f, zeek::ListVal* al)
{ {
for ( int i = 0; i < al->Length(); ++i ) for ( int i = 0; i < al->Length(); ++i )
{ {
@ -980,7 +980,7 @@ const char* DNS_Mgr::LookupAddrInCache(const IPAddr& addr)
return d->names ? d->names[0] : "<\?\?\?>"; return d->names ? d->names[0] : "<\?\?\?>";
} }
IntrusivePtr<TableVal> DNS_Mgr::LookupNameInCache(const string& name) zeek::TableValPtr DNS_Mgr::LookupNameInCache(const string& name)
{ {
HostMap::iterator it = host_mappings.find(name); HostMap::iterator it = host_mappings.find(name);
if ( it == host_mappings.end() ) if ( it == host_mappings.end() )
@ -1030,7 +1030,7 @@ const char* DNS_Mgr::LookupTextInCache(const string& name)
} }
static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback, static void resolve_lookup_cb(DNS_Mgr::LookupCallback* callback,
IntrusivePtr<TableVal> result) zeek::TableValPtr result)
{ {
callback->Resolved(result.get()); callback->Resolved(result.get());
delete callback; delete callback;

View file

@ -13,17 +13,22 @@
#include "IPAddr.h" #include "IPAddr.h"
#include "util.h" #include "util.h"
template <class T> class IntrusivePtr;
class Val;
class ListVal;
class TableVal;
class Func;
class EventHandler; class EventHandler;
class DNS_Mgr_Request; class DNS_Mgr_Request;
ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(ListVal, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek);
typedef PList<DNS_Mgr_Request> DNS_mgr_request_list; namespace zeek {
template <class T> class IntrusivePtr;
using ValPtr = zeek::IntrusivePtr<Val>;
using ListValPtr = zeek::IntrusivePtr<ListVal>;
using TableValPtr = zeek::IntrusivePtr<TableVal>;
}
using DNS_mgr_request_list = zeek::PList<DNS_Mgr_Request>;
struct nb_dns_info; struct nb_dns_info;
struct nb_dns_result; struct nb_dns_result;
@ -50,9 +55,9 @@ public:
// Looks up the address or addresses of the given host, and returns // Looks up the address or addresses of the given host, and returns
// a set of addr. // a set of addr.
IntrusivePtr<TableVal> LookupHost(const char* host); zeek::TableValPtr LookupHost(const char* host);
IntrusivePtr<Val> LookupAddr(const IPAddr& addr); zeek::ValPtr LookupAddr(const IPAddr& addr);
// Define the directory where to store the data. // Define the directory where to store the data.
void SetDir(const char* arg_dir) { dir = copy_string(arg_dir); } void SetDir(const char* arg_dir) { dir = copy_string(arg_dir); }
@ -62,7 +67,7 @@ public:
bool Save(); bool Save();
const char* LookupAddrInCache(const IPAddr& addr); const char* LookupAddrInCache(const IPAddr& addr);
IntrusivePtr<TableVal> LookupNameInCache(const std::string& name); zeek::TableValPtr LookupNameInCache(const std::string& name);
const char* LookupTextInCache(const std::string& name); const char* LookupTextInCache(const std::string& name);
// Support for async lookups. // Support for async lookups.
@ -72,7 +77,7 @@ public:
virtual ~LookupCallback() { } virtual ~LookupCallback() { }
virtual void Resolved(const char* name) { }; virtual void Resolved(const char* name) { };
virtual void Resolved(TableVal* addrs) { }; virtual void Resolved(zeek::TableVal* addrs) { };
virtual void Timeout() = 0; virtual void Timeout() = 0;
}; };
@ -100,15 +105,15 @@ protected:
void Event(EventHandlerPtr e, DNS_Mapping* dm); void Event(EventHandlerPtr e, DNS_Mapping* dm);
void Event(EventHandlerPtr e, DNS_Mapping* dm, void Event(EventHandlerPtr e, DNS_Mapping* dm,
IntrusivePtr<ListVal> l1, IntrusivePtr<ListVal> l2); zeek::ListValPtr l1, zeek::ListValPtr l2);
void Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm); void Event(EventHandlerPtr e, DNS_Mapping* old_dm, DNS_Mapping* new_dm);
IntrusivePtr<Val> BuildMappingVal(DNS_Mapping* dm); zeek::ValPtr BuildMappingVal(DNS_Mapping* dm);
void AddResult(DNS_Mgr_Request* dr, struct nb_dns_result* r); void AddResult(DNS_Mgr_Request* dr, struct nb_dns_result* r);
void CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm); void CompareMappings(DNS_Mapping* prev_dm, DNS_Mapping* new_dm);
IntrusivePtr<ListVal> AddrListDelta(ListVal* al1, ListVal* al2); zeek::ListValPtr AddrListDelta(zeek::ListVal* al1, zeek::ListVal* al2);
void DumpAddrList(FILE* f, ListVal* al); void DumpAddrList(FILE* f, zeek::ListVal* al);
typedef std::map<std::string, std::pair<DNS_Mapping*, DNS_Mapping*> > HostMap; typedef std::map<std::string, std::pair<DNS_Mapping*, DNS_Mapping*> > HostMap;
typedef std::map<IPAddr, DNS_Mapping*> AddrMap; typedef std::map<IPAddr, DNS_Mapping*> AddrMap;
@ -151,7 +156,7 @@ protected:
bool did_init; bool did_init;
IntrusivePtr<zeek::RecordType> dm_rec; zeek::RecordTypePtr dm_rec;
typedef std::list<LookupCallback*> CallbackList; typedef std::list<LookupCallback*> CallbackList;
@ -179,7 +184,7 @@ protected:
processed = true; processed = true;
} }
void Resolved(TableVal* addrs) void Resolved(zeek::TableVal* addrs)
{ {
for ( CallbackList::iterator i = callbacks.begin(); for ( CallbackList::iterator i = callbacks.begin();
i != callbacks.end(); ++i ) i != callbacks.end(); ++i )

View file

@ -13,7 +13,6 @@
#include "Scope.h" #include "Scope.h"
#include "Frame.h" #include "Frame.h"
#include "Func.h" #include "Func.h"
#include "IntrusivePtr.h"
#include "Val.h" #include "Val.h"
#include "Stmt.h" #include "Stmt.h"
#include "Timer.h" #include "Timer.h"
@ -142,7 +141,7 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str)
at_stmt = plr.stmt; at_stmt = plr.stmt;
snprintf(description, sizeof(description), "%s:%d", snprintf(description, sizeof(description), "%s:%d",
source_filename, source_line); source_filename, source_line);
debug_msg("Breakpoint %d set at %s\n", GetID(), Description()); debug_msg("Breakpoint %d set at %s\n", GetID(), Description());
} }
@ -151,12 +150,12 @@ bool DbgBreakpoint::SetLocation(ParseLocationRec plr, std::string_view loc_str)
{ {
std::string loc_s(loc_str); std::string loc_s(loc_str);
kind = BP_FUNC; kind = BP_FUNC;
function_name = make_full_var_name(current_module.c_str(), function_name = make_full_var_name(zeek::detail::current_module.c_str(),
loc_s.c_str()); loc_s.c_str());
at_stmt = plr.stmt; at_stmt = plr.stmt;
const Location* loc = at_stmt->GetLocationInfo(); const zeek::detail::Location* loc = at_stmt->GetLocationInfo();
snprintf(description, sizeof(description), "%s at %s:%d", snprintf(description, sizeof(description), "%s at %s:%d",
function_name.c_str(), loc->filename, loc->last_line); function_name.c_str(), loc->filename, loc->last_line);
debug_msg("Breakpoint %d set at %s\n", GetID(), Description()); debug_msg("Breakpoint %d set at %s\n", GetID(), Description());
} }
@ -177,7 +176,7 @@ bool DbgBreakpoint::SetLocation(zeek::detail::Stmt* stmt)
SetEnable(true); SetEnable(true);
AddToGlobalMap(); AddToGlobalMap();
const Location* loc = stmt->GetLocationInfo(); const zeek::detail::Location* loc = stmt->GetLocationInfo();
snprintf(description, sizeof(description), "%s:%d", snprintf(description, sizeof(description), "%s:%d",
loc->filename, loc->last_line); loc->filename, loc->last_line);
@ -351,13 +350,13 @@ void DbgBreakpoint::PrintHitMsg()
case BP_LINE: case BP_LINE:
{ {
ODesc d; ODesc d;
Frame* f = g_frame_stack.back(); zeek::detail::Frame* f = g_frame_stack.back();
const BroFunc* func = f->GetFunction(); const zeek::detail::ScriptFunc* func = f->GetFunction();
if ( func ) if ( func )
func->DescribeDebug (&d, f->GetFuncArgs()); func->DescribeDebug (&d, f->GetFuncArgs());
const Location* loc = at_stmt->GetLocationInfo(); const zeek::detail::Location* loc = at_stmt->GetLocationInfo();
debug_msg("Breakpoint %d, %s at %s:%d\n", debug_msg("Breakpoint %d, %s at %s:%d\n",
GetID(), d.Description(), GetID(), d.Description(),

View file

@ -7,7 +7,7 @@
#include "Reporter.h" #include "Reporter.h"
// Support classes // Support classes
DbgWatch::DbgWatch(BroObj* var_to_watch) DbgWatch::DbgWatch(zeek::Obj* var_to_watch)
{ {
reporter->InternalError("DbgWatch unimplemented"); reporter->InternalError("DbgWatch unimplemented");
} }

View file

@ -4,17 +4,17 @@
#include "util.h" #include "util.h"
class BroObj;
ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail);
namespace zeek { class Obj; }
using BroObj [[deprecated("Remove in v4.1. Use zeek:Obj instead.")]] = zeek::Obj;
class DbgWatch { class DbgWatch {
public: public:
explicit DbgWatch(BroObj* var_to_watch); explicit DbgWatch(zeek::Obj* var_to_watch);
explicit DbgWatch(zeek::detail::Expr* expr_to_watch); explicit DbgWatch(zeek::detail::Expr* expr_to_watch);
~DbgWatch(); ~DbgWatch();
protected: protected:
BroObj* var; zeek::Obj* var;
zeek::detail::Expr* expr; zeek::detail::Expr* expr;
}; };

View file

@ -44,7 +44,7 @@ std::map<string, Filemap*> g_dbgfilemaps;
// current context; you don't want to do it after a step or next // current context; you don't want to do it after a step or next
// command unless you've exited a function. // command unless you've exited a function.
static bool step_or_next_pending = false; static bool step_or_next_pending = false;
static Frame* last_frame; static zeek::detail::Frame* last_frame;
DebuggerState::DebuggerState() DebuggerState::DebuggerState()
{ {
@ -55,7 +55,7 @@ DebuggerState::DebuggerState()
BreakFromSignal(false); BreakFromSignal(false);
// ### Don't choose this arbitrary size! Extend Frame. // ### Don't choose this arbitrary size! Extend Frame.
dbg_locals = new Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr); dbg_locals = new zeek::detail::Frame(1024, /* func = */ nullptr, /* fn_args = */ nullptr);
} }
DebuggerState::~DebuggerState() DebuggerState::~DebuggerState()
@ -136,7 +136,7 @@ int TraceState::LogTrace(const char* fmt, ...)
fprintf(trace_file, "%.6f ", network_time); fprintf(trace_file, "%.6f ", network_time);
const zeek::detail::Stmt* stmt; const zeek::detail::Stmt* stmt;
Location loc; zeek::detail::Location loc;
loc.filename = nullptr; loc.filename = nullptr;
if ( g_frame_stack.size() > 0 && g_frame_stack.back() ) if ( g_frame_stack.size() > 0 && g_frame_stack.back() )
@ -146,7 +146,7 @@ int TraceState::LogTrace(const char* fmt, ...)
loc = *stmt->GetLocationInfo(); loc = *stmt->GetLocationInfo();
else else
{ {
const BroFunc* f = g_frame_stack.back()->GetFunction(); const zeek::detail::ScriptFunc* f = g_frame_stack.back()->GetFunction();
if ( f ) if ( f )
loc = *f->GetLocationInfo(); loc = *f->GetLocationInfo();
} }
@ -174,7 +174,7 @@ int TraceState::LogTrace(const char* fmt, ...)
// Helper functions. // Helper functions.
void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, Location& loc) void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, zeek::detail::Location& loc)
{ {
if ( ! list ) if ( ! list )
{ {
@ -197,11 +197,11 @@ void get_first_statement(zeek::detail::Stmt* list, zeek::detail::Stmt*& first, L
static void parse_function_name(vector<ParseLocationRec>& result, static void parse_function_name(vector<ParseLocationRec>& result,
ParseLocationRec& plr, const string& s) ParseLocationRec& plr, const string& s)
{ // function name { // function name
const auto& id = lookup_ID(s.c_str(), current_module.c_str()); const auto& id = zeek::detail::lookup_ID(s.c_str(), zeek::detail::current_module.c_str());
if ( ! id ) if ( ! id )
{ {
string fullname = make_full_var_name(current_module.c_str(), s.c_str()); string fullname = make_full_var_name(zeek::detail::current_module.c_str(), s.c_str());
debug_msg("Function %s not defined.\n", fullname.c_str()); debug_msg("Function %s not defined.\n", fullname.c_str());
plr.type = plrUnknown; plr.type = plrUnknown;
return; return;
@ -221,8 +221,8 @@ static void parse_function_name(vector<ParseLocationRec>& result,
return; return;
} }
const Func* func = id->GetVal()->AsFunc(); const zeek::Func* func = id->GetVal()->AsFunc();
const vector<Func::Body>& bodies = func->GetBodies(); const vector<zeek::Func::Body>& bodies = func->GetBodies();
if ( bodies.size() == 0 ) if ( bodies.size() == 0 )
{ {
@ -244,7 +244,7 @@ static void parse_function_name(vector<ParseLocationRec>& result,
for ( unsigned int i = 0; i < bodies.size(); ++i ) for ( unsigned int i = 0; i < bodies.size(); ++i )
{ {
zeek::detail::Stmt* first; zeek::detail::Stmt* first;
Location stmt_loc; zeek::detail::Location stmt_loc;
get_first_statement(bodies[i].stmts.get(), first, stmt_loc); get_first_statement(bodies[i].stmts.get(), first, stmt_loc);
debug_msg("[%d] %s:%d\n", i+1, stmt_loc.filename, stmt_loc.first_line); debug_msg("[%d] %s:%d\n", i+1, stmt_loc.filename, stmt_loc.first_line);
} }
@ -287,7 +287,7 @@ static void parse_function_name(vector<ParseLocationRec>& result,
// Find first atomic (non-STMT_LIST) statement // Find first atomic (non-STMT_LIST) statement
zeek::detail::Stmt* first; zeek::detail::Stmt* first;
Location stmt_loc; zeek::detail::Location stmt_loc;
if ( body ) if ( body )
{ {
@ -728,17 +728,17 @@ static char* get_prompt(bool reset_counter = false)
return prompt; return prompt;
} }
string get_context_description(const zeek::detail::Stmt* stmt, const Frame* frame) string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame)
{ {
ODesc d; ODesc d;
const BroFunc* func = frame ? frame->GetFunction() : nullptr; const zeek::detail::ScriptFunc* func = frame ? frame->GetFunction() : nullptr;
if ( func ) if ( func )
func->DescribeDebug(&d, frame->GetFuncArgs()); func->DescribeDebug(&d, frame->GetFuncArgs());
else else
d.Add("<unknown function>", 0); d.Add("<unknown function>", 0);
Location loc; zeek::detail::Location loc;
if ( stmt ) if ( stmt )
loc = *stmt->GetLocationInfo(); loc = *stmt->GetLocationInfo();
else else
@ -769,18 +769,18 @@ int dbg_handle_debug_input()
g_debugger_state.BreakFromSignal(false); g_debugger_state.BreakFromSignal(false);
} }
Frame* curr_frame = g_frame_stack.back(); zeek::detail::Frame* curr_frame = g_frame_stack.back();
const BroFunc* func = curr_frame->GetFunction(); const zeek::detail::ScriptFunc* func = curr_frame->GetFunction();
if ( func ) if ( func )
current_module = extract_module_name(func->Name()); zeek::detail::current_module = extract_module_name(func->Name());
else else
current_module = GLOBAL_MODULE_NAME; zeek::detail::current_module = GLOBAL_MODULE_NAME;
const zeek::detail::Stmt* stmt = curr_frame->GetNextStmt(); const zeek::detail::Stmt* stmt = curr_frame->GetNextStmt();
if ( ! stmt ) if ( ! stmt )
reporter->InternalError("Assertion failed: stmt != 0"); reporter->InternalError("Assertion failed: stmt != 0");
const Location loc = *stmt->GetLocationInfo(); const zeek::detail::Location loc = *stmt->GetLocationInfo();
if ( ! step_or_next_pending || g_frame_stack.back() != last_frame ) if ( ! step_or_next_pending || g_frame_stack.back() != last_frame )
{ {
@ -840,7 +840,7 @@ int dbg_handle_debug_input()
// Return true to continue execution, false to abort. // Return true to continue execution, false to abort.
bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f) bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f)
{ {
if ( ! g_policy_debug || if ( ! g_policy_debug ||
stmt->Tag() == STMT_LIST || stmt->Tag() == STMT_NULL ) stmt->Tag() == STMT_LIST || stmt->Tag() == STMT_NULL )
@ -905,7 +905,7 @@ bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f)
return true; return true;
} }
bool post_execute_stmt(zeek::detail::Stmt* stmt, Frame* f, Val* result, stmt_flow_type* flow) bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, stmt_flow_type* flow)
{ {
// Handle the case where someone issues a "next" debugger command, // Handle the case where someone issues a "next" debugger command,
// but we're at a return statement, so the next statement is in // but we're at a return statement, so the next statement is in
@ -948,7 +948,7 @@ extern YYLTYPE yylloc; // holds start line and column of token
extern int line_number; extern int line_number;
extern const char* filename; extern const char* filename;
IntrusivePtr<Val> dbg_eval_expr(const char* expr) zeek::ValPtr dbg_eval_expr(const char* expr)
{ {
// Push the current frame's associated scope. // Push the current frame's associated scope.
// Note: g_debugger_state.curr_frame_idx is the user-visible number, // Note: g_debugger_state.curr_frame_idx is the user-visible number,
@ -959,15 +959,15 @@ IntrusivePtr<Val> dbg_eval_expr(const char* expr)
if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) ) if ( ! (frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()) )
reporter->InternalError("Assertion failed: frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()"); reporter->InternalError("Assertion failed: frame_idx >= 0 && (unsigned) frame_idx < g_frame_stack.size()");
Frame* frame = g_frame_stack[frame_idx]; zeek::detail::Frame* frame = g_frame_stack[frame_idx];
if ( ! (frame) ) if ( ! (frame) )
reporter->InternalError("Assertion failed: frame"); reporter->InternalError("Assertion failed: frame");
const BroFunc* func = frame->GetFunction(); const zeek::detail::ScriptFunc* func = frame->GetFunction();
if ( func ) if ( func )
{ {
Ref(func->GetScope()); Ref(func->GetScope());
push_existing_scope(func->GetScope()); zeek::detail::push_existing_scope(func->GetScope());
} }
// ### Possibly push a debugger-local scope? // ### Possibly push a debugger-local scope?
@ -983,7 +983,7 @@ IntrusivePtr<Val> dbg_eval_expr(const char* expr)
yylloc.first_line = yylloc.last_line = line_number = 1; yylloc.first_line = yylloc.last_line = line_number = 1;
// Parse the thing into an expr. // Parse the thing into an expr.
IntrusivePtr<Val> result; zeek::ValPtr result;
if ( yyparse() ) if ( yyparse() )
{ {
if ( g_curr_debug_error ) if ( g_curr_debug_error )
@ -1001,7 +1001,7 @@ IntrusivePtr<Val> dbg_eval_expr(const char* expr)
result = g_curr_debug_expr->Eval(frame); result = g_curr_debug_expr->Eval(frame);
if ( func ) if ( func )
pop_scope(); zeek::detail::pop_scope();
delete g_curr_debug_expr; delete g_curr_debug_expr;
g_curr_debug_expr = nullptr; g_curr_debug_expr = nullptr;

View file

@ -11,10 +11,14 @@
#include <map> #include <map>
#include <string> #include <string>
template <class T> class IntrusivePtr; ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
class Val;
ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek {
template <class T> class IntrusivePtr;
using ValPtr = zeek::IntrusivePtr<Val>;
}
// This needs to be defined before we do the includes that come after it. // This needs to be defined before we do the includes that come after it.
enum ParseLocationRecType { plrUnknown, plrFileAndLine, plrFunction }; enum ParseLocationRecType { plrUnknown, plrFileAndLine, plrFunction };
@ -26,9 +30,8 @@ struct ParseLocationRec {
}; };
class StmtLocMapping; class StmtLocMapping;
typedef PQueue<StmtLocMapping> Filemap; // mapping for a single file typedef zeek::PQueue<StmtLocMapping> Filemap; // mapping for a single file
class Frame;
class DbgBreakpoint; class DbgBreakpoint;
class DbgWatch; class DbgWatch;
class DbgDisplay; class DbgDisplay;
@ -37,7 +40,9 @@ class StmtHashFn;
typedef std::map<int, DbgBreakpoint*> BPIDMapType; typedef std::map<int, DbgBreakpoint*> BPIDMapType;
typedef std::multimap<const zeek::detail::Stmt*, DbgBreakpoint*> BPMapType; typedef std::multimap<const zeek::detail::Stmt*, DbgBreakpoint*> BPMapType;
namespace zeek {
extern std::string current_module; extern std::string current_module;
}
class TraceState { class TraceState {
public: public:
@ -84,7 +89,7 @@ public:
bool already_did_list; // did we already do a 'list' command? bool already_did_list; // did we already do a 'list' command?
Location last_loc; // used by 'list'; the last location listed zeek::detail::Location last_loc; // used by 'list'; the last location listed
BPIDMapType breakpoints; // BPID -> Breakpoint BPIDMapType breakpoints; // BPID -> Breakpoint
std::vector<DbgWatch*> watches; std::vector<DbgWatch*> watches;
@ -98,7 +103,7 @@ protected:
int next_bp_id, next_watch_id, next_display_id; int next_bp_id, next_watch_id, next_display_id;
private: private:
Frame* dbg_locals; // unused zeek::detail::Frame* dbg_locals; // unused
}; };
// Source line -> statement mapping. // Source line -> statement mapping.
@ -106,14 +111,14 @@ private:
class StmtLocMapping { class StmtLocMapping {
public: public:
StmtLocMapping() { } StmtLocMapping() { }
StmtLocMapping(const Location* l, zeek::detail::Stmt* s) { loc = *l; stmt = s; } StmtLocMapping(const zeek::detail::Location* l, zeek::detail::Stmt* s) { loc = *l; stmt = s; }
bool StartsAfter(const StmtLocMapping* m2); bool StartsAfter(const StmtLocMapping* m2);
const Location& Loc() const { return loc; } const zeek::detail::Location& Loc() const { return loc; }
zeek::detail::Stmt* Statement() const { return stmt; } zeek::detail::Stmt* Statement() const { return stmt; }
protected: protected:
Location loc; zeek::detail::Location loc;
zeek::detail::Stmt* stmt; zeek::detail::Stmt* stmt;
}; };
@ -145,8 +150,8 @@ std::vector<ParseLocationRec> parse_location_string(const std::string& s);
// Debugging hooks. // Debugging hooks.
// Return true to continue execution, false to abort. // Return true to continue execution, false to abort.
bool pre_execute_stmt(zeek::detail::Stmt* stmt, Frame* f); bool pre_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f);
bool post_execute_stmt(zeek::detail::Stmt* stmt, Frame* f, Val* result, stmt_flow_type* flow); bool post_execute_stmt(zeek::detail::Stmt* stmt, zeek::detail::Frame* f, zeek::Val* result, stmt_flow_type* flow);
// Returns 1 if successful, 0 otherwise. // Returns 1 if successful, 0 otherwise.
// If cmdfile is non-nil, it contains the location of a file of commands // If cmdfile is non-nil, it contains the location of a file of commands
@ -162,7 +167,7 @@ int dbg_handle_debug_input(); // read a line and then have it executed
int dbg_execute_command(const char* cmd); int dbg_execute_command(const char* cmd);
// Interactive expression evaluation. // Interactive expression evaluation.
IntrusivePtr<Val> dbg_eval_expr(const char* expr); zeek::ValPtr dbg_eval_expr(const char* expr);
// Extra debugging facilities. // Extra debugging facilities.
// TODO: current connections, memory allocated, other internal data structures. // TODO: current connections, memory allocated, other internal data structures.
@ -170,9 +175,9 @@ IntrusivePtr<Val> dbg_eval_expr(const char* expr);
int dbg_read_internal_state(); int dbg_read_internal_state();
// Get line that looks like "In FnFoo(arg = val) at File:Line". // Get line that looks like "In FnFoo(arg = val) at File:Line".
std::string get_context_description(const zeek::detail::Stmt* stmt, const Frame* frame); std::string get_context_description(const zeek::detail::Stmt* stmt, const zeek::detail::Frame* frame);
extern Frame* g_dbg_locals; // variables created within debugger context extern zeek::detail::Frame* g_dbg_locals; // variables created within debugger context
extern std::map<std::string, Filemap*> g_dbgfilemaps; // filename => filemap extern std::map<std::string, Filemap*> g_dbgfilemaps; // filename => filemap

View file

@ -15,7 +15,6 @@
#include "Desc.h" #include "Desc.h"
#include "DbgBreakpoint.h" #include "DbgBreakpoint.h"
#include "ID.h" #include "ID.h"
#include "IntrusivePtr.h"
#include "Frame.h" #include "Frame.h"
#include "Func.h" #include "Func.h"
#include "Stmt.h" #include "Stmt.h"
@ -58,7 +57,7 @@ static void lookup_global_symbols_regex(const string& orig_regex, vector<zeek::d
return; return;
} }
Scope* global = global_scope(); zeek::detail::Scope* global = zeek::detail::global_scope();
const auto& syms = global->Vars(); const auto& syms = global->Vars();
zeek::detail::ID* nextid; zeek::detail::ID* nextid;
@ -124,7 +123,7 @@ static void choose_global_symbols_regex(const string& regex, vector<zeek::detail
// DebugCmdInfo implementation // DebugCmdInfo implementation
// //
PQueue<DebugCmdInfo> g_DebugCmdInfos; zeek::PQueue<DebugCmdInfo> g_DebugCmdInfos;
DebugCmdInfo::DebugCmdInfo(const DebugCmdInfo& info) DebugCmdInfo::DebugCmdInfo(const DebugCmdInfo& info)
: cmd(info.cmd), helpstring(nullptr) : cmd(info.cmd), helpstring(nullptr)
@ -215,7 +214,7 @@ static int dbg_backtrace_internal(int start, int end)
for ( int i = start; i >= end; --i ) for ( int i = start; i >= end; --i )
{ {
const Frame* f = g_frame_stack[i]; const zeek::detail::Frame* f = g_frame_stack[i];
const zeek::detail::Stmt* stmt = f ? f->GetNextStmt() : nullptr; const zeek::detail::Stmt* stmt = f ? f->GetNextStmt() : nullptr;
string context = get_context_description(stmt, f); string context = get_context_description(stmt, f);
@ -337,7 +336,7 @@ int dbg_cmd_frame(DebugCmd cmd, const vector<string>& args)
if ( ! stmt ) if ( ! stmt )
reporter->InternalError("Assertion failed: %s", "stmt != 0"); reporter->InternalError("Assertion failed: %s", "stmt != 0");
const Location loc = *stmt->GetLocationInfo(); const zeek::detail::Location loc = *stmt->GetLocationInfo();
g_debugger_state.last_loc = loc; g_debugger_state.last_loc = loc;
g_debugger_state.already_did_list = false; g_debugger_state.already_did_list = false;

View file

@ -41,7 +41,7 @@ protected:
bool repeatable; bool repeatable;
}; };
extern PQueue<DebugCmdInfo> g_DebugCmdInfos; extern zeek::PQueue<DebugCmdInfo> g_DebugCmdInfos;
void init_global_dbg_constants (); void init_global_dbg_constants ();

View file

@ -197,7 +197,7 @@ void ODesc::AddCS(const char* s)
Add(s); Add(s);
} }
void ODesc::AddBytes(const BroString* s) void ODesc::AddBytes(const zeek::String* s)
{ {
if ( IsReadable() ) if ( IsReadable() )
{ {
@ -205,7 +205,7 @@ void ODesc::AddBytes(const BroString* s)
AddBytes(reinterpret_cast<const char*>(s->Bytes()), s->Len()); AddBytes(reinterpret_cast<const char*>(s->Bytes()), s->Len());
else else
{ {
const char* str = s->Render(BroString::EXPANDED_STRING); const char* str = s->Render(zeek::String::EXPANDED_STRING);
Add(str); Add(str);
delete [] str; delete [] str;
} }

View file

@ -2,7 +2,7 @@
#pragma once #pragma once
#include "BroString.h" // for byte_vec #include "ZeekString.h" // for byte_vec
#include "util.h" // for bro_int_t #include "util.h" // for bro_int_t
#include <set> #include <set>
@ -93,7 +93,7 @@ public:
// Add s as a counted string. // Add s as a counted string.
void AddCS(const char* s); void AddCS(const char* s);
void AddBytes(const BroString* s); void AddBytes(const zeek::String* s);
void Add(const char* s1, const char* s2) void Add(const char* s1, const char* s2)
{ Add(s1); Add(s2); } { Add(s1); Add(s2); }
@ -130,7 +130,7 @@ public:
const char* Description() const { return (const char*) base; } const char* Description() const { return (const char*) base; }
const u_char* Bytes() const { return (const u_char *) base; } const u_char* Bytes() const { return (const u_char *) base; }
byte_vec TakeBytes() zeek::byte_vec TakeBytes()
{ {
const void* t = base; const void* t = base;
base = nullptr; base = nullptr;
@ -139,7 +139,7 @@ public:
// Don't clear offset, as we want to still support // Don't clear offset, as we want to still support
// subsequent calls to Len(). // subsequent calls to Len().
return byte_vec(t); return zeek::byte_vec(t);
} }
int Len() const { return offset; } int Len() const { return offset; }

View file

@ -13,17 +13,18 @@
// If the mean bucket length exceeds the following then Insert() will // If the mean bucket length exceeds the following then Insert() will
// increase the size of the hash table. // increase the size of the hash table.
#define DEFAULT_DENSITY_THRESH 3.0 constexpr double DEFAULT_DENSITY_THRESH = 3.0;
// Threshold above which we do not try to ensure that the hash size // Threshold above which we do not try to ensure that the hash size
// is prime. // is prime.
#define PRIME_THRESH 1000 constexpr int PRIME_THRESH = 1000;
// Default number of hash buckets in dictionary. The dictionary will // Default number of hash buckets in dictionary. The dictionary will
// increase the size of the hash table as needed. // increase the size of the hash table as needed.
#define DEFAULT_DICT_SIZE 16 constexpr int DEFAULT_DICT_SIZE = 16;
TEST_SUITE_BEGIN("Dict"); namespace zeek {
namespace detail {
class DictEntry { class DictEntry {
public: public:
@ -40,6 +41,8 @@ public:
void* value; void* value;
}; };
} //namespace detail
// The value of an iteration cookie is the bucket and offset within the // The value of an iteration cookie is the bucket and offset within the
// bucket at which to start looking for the next value to return. // bucket at which to start looking for the next value to return.
class IterCookie { class IterCookie {
@ -47,25 +50,29 @@ public:
IterCookie(int b, int o) : bucket(b), offset(o) {} IterCookie(int b, int o) : bucket(b), offset(o) {}
int bucket, offset; int bucket, offset;
PList<DictEntry>** ttbl = nullptr; zeek::PList<detail::DictEntry>** ttbl = nullptr;
const int* num_buckets_p = nullptr; const int* num_buckets_p = nullptr;
PList<DictEntry> inserted; // inserted while iterating zeek::PList<detail::DictEntry> inserted; // inserted while iterating
}; };
} // namespace zeek
TEST_SUITE_BEGIN("Dict");
TEST_CASE("dict construction") TEST_CASE("dict construction")
{ {
PDict<int> dict; zeek::PDict<int> dict;
CHECK(dict.IsOrdered() == false); CHECK(dict.IsOrdered() == false);
CHECK(dict.Length() == 0); CHECK(dict.Length() == 0);
PDict<int> dict2(ORDERED); zeek::PDict<int> dict2(zeek::ORDERED);
CHECK(dict2.IsOrdered() == true); CHECK(dict2.IsOrdered() == true);
CHECK(dict2.Length() == 0); CHECK(dict2.Length() == 0);
} }
TEST_CASE("dict operation") TEST_CASE("dict operation")
{ {
PDict<uint32_t> dict; zeek::PDict<uint32_t> dict;
uint32_t val = 10; uint32_t val = 10;
uint32_t key_val = 5; uint32_t key_val = 5;
@ -111,8 +118,8 @@ TEST_CASE("dict operation")
TEST_CASE("dict nthentry") TEST_CASE("dict nthentry")
{ {
PDict<uint32_t> unordered(UNORDERED); zeek::PDict<uint32_t> unordered(zeek::UNORDERED);
PDict<uint32_t> ordered(ORDERED); zeek::PDict<uint32_t> ordered(zeek::ORDERED);
uint32_t val = 15; uint32_t val = 15;
uint32_t key_val = 5; uint32_t key_val = 5;
@ -147,7 +154,7 @@ TEST_CASE("dict nthentry")
TEST_CASE("dict iteration") TEST_CASE("dict iteration")
{ {
PDict<uint32_t> dict; zeek::PDict<uint32_t> dict;
uint32_t val = 15; uint32_t val = 15;
uint32_t key_val = 5; uint32_t key_val = 5;
@ -161,7 +168,7 @@ TEST_CASE("dict iteration")
dict.Insert(key2, &val2); dict.Insert(key2, &val2);
HashKey* it_key; HashKey* it_key;
IterCookie* it = dict.InitForIteration(); zeek::IterCookie* it = dict.InitForIteration();
CHECK(it != nullptr); CHECK(it != nullptr);
int count = 0; int count = 0;
@ -186,10 +193,14 @@ TEST_CASE("dict iteration")
delete key2; delete key2;
} }
Dictionary::Dictionary(dict_order ordering, int initial_size) TEST_SUITE_END();
namespace zeek {
Dictionary::Dictionary(DictOrder ordering, int initial_size)
{ {
if ( ordering == ORDERED ) if ( ordering == ORDERED )
order = new PList<DictEntry>; order = new zeek::PList<detail::DictEntry>;
if ( initial_size > 0 ) if ( initial_size > 0 )
Init(initial_size); Init(initial_size);
@ -218,7 +229,7 @@ void Dictionary::DeInit()
for ( int i = 0; i < num_buckets; ++i ) for ( int i = 0; i < num_buckets; ++i )
if ( tbl[i] ) if ( tbl[i] )
{ {
PList<DictEntry>* chain = tbl[i]; zeek::PList<detail::DictEntry>* chain = tbl[i];
for ( const auto& e : *chain ) for ( const auto& e : *chain )
{ {
if ( delete_func ) if ( delete_func )
@ -238,7 +249,7 @@ void Dictionary::DeInit()
for ( int i = 0; i < num_buckets2; ++i ) for ( int i = 0; i < num_buckets2; ++i )
if ( tbl2[i] ) if ( tbl2[i] )
{ {
PList<DictEntry>* chain = tbl2[i]; zeek::PList<detail::DictEntry>* chain = tbl2[i];
for ( const auto& e : *chain ) for ( const auto& e : *chain )
{ {
if ( delete_func ) if ( delete_func )
@ -259,7 +270,7 @@ void* Dictionary::Lookup(const void* key, int key_size, hash_t hash) const
return nullptr; return nullptr;
hash_t h; hash_t h;
PList<DictEntry>* chain; zeek::PList<detail::DictEntry>* chain;
// Figure out which hash table to look in. // Figure out which hash table to look in.
h = hash % num_buckets; h = hash % num_buckets;
@ -287,12 +298,12 @@ void* Dictionary::Insert(void* key, int key_size, hash_t hash, void* val,
if ( ! tbl ) if ( ! tbl )
Init(DEFAULT_DICT_SIZE); Init(DEFAULT_DICT_SIZE);
DictEntry* new_entry = new DictEntry(key, key_size, hash, val); detail::DictEntry* new_entry = new detail::DictEntry(key, key_size, hash, val);
void* old_val = Insert(new_entry, copy_key); void* old_val = Insert(new_entry, copy_key);
if ( old_val ) if ( old_val )
{ {
// We didn't need the new DictEntry, the key was already // We didn't need the new detail::DictEntry, the key was already
// present. // present.
delete new_entry; delete new_entry;
} }
@ -315,7 +326,7 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash,
return nullptr; return nullptr;
hash_t h; hash_t h;
PList<DictEntry>* chain; zeek::PList<detail::DictEntry>* chain;
int* num_entries_ptr; int* num_entries_ptr;
// Figure out which hash table to look in // Figure out which hash table to look in
@ -338,7 +349,7 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash,
for ( auto i = 0u; i < chain_length; ++i ) for ( auto i = 0u; i < chain_length; ++i )
{ {
DictEntry* entry = (*chain)[i]; detail::DictEntry* entry = (*chain)[i];
if ( entry->hash == hash && entry->len == key_size && if ( entry->hash == hash && entry->len == key_size &&
! memcmp(key, entry->key, key_size) ) ! memcmp(key, entry->key, key_size) )
@ -357,8 +368,8 @@ void* Dictionary::Remove(const void* key, int key_size, hash_t hash,
return nullptr; return nullptr;
} }
void* Dictionary::DoRemove(DictEntry* entry, hash_t h, void* Dictionary::DoRemove(detail::DictEntry* entry, hash_t h,
PList<DictEntry>* chain, int chain_offset) zeek::PList<detail::DictEntry>* chain, int chain_offset)
{ {
void* entry_value = entry->value; void* entry_value = entry->value;
@ -397,7 +408,7 @@ void* Dictionary::NthEntry(int n, const void*& key, int& key_len) const
if ( ! order || n < 0 || n >= Length() ) if ( ! order || n < 0 || n >= Length() )
return nullptr; return nullptr;
DictEntry* entry = (*order)[n]; detail::DictEntry* entry = (*order)[n];
key = entry->key; key = entry->key;
key_len = entry->len; key_len = entry->len;
return entry->value; return entry->value;
@ -417,7 +428,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c
{ {
if ( ! tbl && ! tbl2 ) if ( ! tbl && ! tbl2 )
{ {
const_cast<PList<IterCookie>*>(&cookies)->remove(cookie); const_cast<zeek::PList<IterCookie>*>(&cookies)->remove(cookie);
delete cookie; delete cookie;
cookie = nullptr; cookie = nullptr;
return nullptr; return nullptr;
@ -427,7 +438,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c
// That keeps the list small and helps avoiding searching // That keeps the list small and helps avoiding searching
// a large list when deleting an entry. // a large list when deleting an entry.
DictEntry* entry; detail::DictEntry* entry;
if ( cookie->inserted.length() ) if ( cookie->inserted.length() )
{ {
@ -442,7 +453,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c
int b = cookie->bucket; int b = cookie->bucket;
int o = cookie->offset; int o = cookie->offset;
PList<DictEntry>** ttbl; zeek::PList<detail::DictEntry>** ttbl;
const int* num_buckets_p; const int* num_buckets_p;
if ( ! cookie->ttbl ) if ( ! cookie->ttbl )
@ -484,7 +495,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c
// FIXME: I don't like removing the const here. But is there // FIXME: I don't like removing the const here. But is there
// a better way? // a better way?
const_cast<PList<IterCookie>*>(&cookies)->remove(cookie); const_cast<zeek::PList<IterCookie>*>(&cookies)->remove(cookie);
delete cookie; delete cookie;
cookie = nullptr; cookie = nullptr;
return nullptr; return nullptr;
@ -503,7 +514,7 @@ void* Dictionary::NextEntry(HashKey*& h, IterCookie*& cookie, int return_hash) c
void Dictionary::Init(int size) void Dictionary::Init(int size)
{ {
num_buckets = NextPrime(size); num_buckets = NextPrime(size);
tbl = new PList<DictEntry>*[num_buckets]; tbl = new zeek::PList<detail::DictEntry>*[num_buckets];
for ( int i = 0; i < num_buckets; ++i ) for ( int i = 0; i < num_buckets; ++i )
tbl[i] = nullptr; tbl[i] = nullptr;
@ -515,7 +526,7 @@ void Dictionary::Init(int size)
void Dictionary::Init2(int size) void Dictionary::Init2(int size)
{ {
num_buckets2 = NextPrime(size); num_buckets2 = NextPrime(size);
tbl2 = new PList<DictEntry>*[num_buckets2]; tbl2 = new zeek::PList<detail::DictEntry>*[num_buckets2];
for ( int i = 0; i < num_buckets2; ++i ) for ( int i = 0; i < num_buckets2; ++i )
tbl2[i] = nullptr; tbl2[i] = nullptr;
@ -524,12 +535,12 @@ void Dictionary::Init2(int size)
} }
// private // private
void* Dictionary::Insert(DictEntry* new_entry, bool copy_key) void* Dictionary::Insert(detail::DictEntry* new_entry, bool copy_key)
{ {
if ( ! tbl ) if ( ! tbl )
Init(DEFAULT_DICT_SIZE); Init(DEFAULT_DICT_SIZE);
PList<DictEntry>** ttbl; zeek::PList<detail::DictEntry>** ttbl;
int* num_entries_ptr; int* num_entries_ptr;
int* max_num_entries_ptr; int* max_num_entries_ptr;
hash_t h = new_entry->hash % num_buckets; hash_t h = new_entry->hash % num_buckets;
@ -554,7 +565,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key)
max_num_entries_ptr = &max_num_entries2; max_num_entries_ptr = &max_num_entries2;
} }
PList<DictEntry>* chain = ttbl[h]; zeek::PList<detail::DictEntry>* chain = ttbl[h];
int n = new_entry->len; int n = new_entry->len;
@ -562,7 +573,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key)
{ {
for ( int i = 0; i < chain->length(); ++i ) for ( int i = 0; i < chain->length(); ++i )
{ {
DictEntry* entry = (*chain)[i]; detail::DictEntry* entry = (*chain)[i];
if ( entry->hash == new_entry->hash && if ( entry->hash == new_entry->hash &&
entry->len == n && entry->len == n &&
@ -576,7 +587,7 @@ void* Dictionary::Insert(DictEntry* new_entry, bool copy_key)
} }
else else
// Create new chain. // Create new chain.
chain = ttbl[h] = new PList<DictEntry>; chain = ttbl[h] = new zeek::PList<detail::DictEntry>;
// If we got this far, then we couldn't use an existing copy // If we got this far, then we couldn't use an existing copy
// of the key, so make a new one if necessary. // of the key, so make a new one if necessary.
@ -660,7 +671,7 @@ void Dictionary::MoveChains()
do do
{ {
PList<DictEntry>* chain = tbl[tbl_next_ind++]; zeek::PList<detail::DictEntry>* chain = tbl[tbl_next_ind++];
if ( ! chain ) if ( ! chain )
continue; continue;
@ -720,13 +731,13 @@ unsigned int Dictionary::MemoryAllocation() const
for ( int i = 0; i < num_buckets; ++i ) for ( int i = 0; i < num_buckets; ++i )
if ( tbl[i] ) if ( tbl[i] )
{ {
PList<DictEntry>* chain = tbl[i]; zeek::PList<detail::DictEntry>* chain = tbl[i];
for ( const auto& c : *chain ) for ( const auto& c : *chain )
size += padded_sizeof(DictEntry) + pad_size(c->len); size += padded_sizeof(detail::DictEntry) + pad_size(c->len);
size += chain->MemoryAllocation(); size += chain->MemoryAllocation();
} }
size += pad_size(num_buckets * sizeof(PList<DictEntry>*)); size += pad_size(num_buckets * sizeof(zeek::PList<detail::DictEntry>*));
if ( order ) if ( order )
size += order->MemoryAllocation(); size += order->MemoryAllocation();
@ -736,13 +747,13 @@ unsigned int Dictionary::MemoryAllocation() const
for ( int i = 0; i < num_buckets2; ++i ) for ( int i = 0; i < num_buckets2; ++i )
if ( tbl2[i] ) if ( tbl2[i] )
{ {
PList<DictEntry>* chain = tbl2[i]; zeek::PList<detail::DictEntry>* chain = tbl2[i];
for ( const auto& c : *chain ) for ( const auto& c : *chain )
size += padded_sizeof(DictEntry) + pad_size(c->len); size += padded_sizeof(detail::DictEntry) + pad_size(c->len);
size += chain->MemoryAllocation(); size += chain->MemoryAllocation();
} }
size += pad_size(num_buckets2 * sizeof(PList<DictEntry>*)); size += pad_size(num_buckets2 * sizeof(zeek::PList<detail::DictEntry>*));
} }
return size; return size;
@ -753,4 +764,4 @@ void generic_delete_func(void* v)
free(v); free(v);
} }
TEST_SUITE_END(); } // namespace zeek

View file

@ -2,27 +2,31 @@
#pragma once #pragma once
#include "zeek-config.h"
#include "List.h" #include "List.h"
#include "Hash.h" #include "Hash.h"
class Dictionary; ZEEK_FORWARD_DECLARE_NAMESPACED(DictEntry, zeek::detail);
class DictEntry; ZEEK_FORWARD_DECLARE_NAMESPACED(IterCookie, zeek);
class IterCookie;
// Type indicating whether the dictionary should keep track of the order
// of insertions.
enum dict_order { ORDERED, UNORDERED };
// Type for function to be called when deleting elements. // Type for function to be called when deleting elements.
typedef void (*dict_delete_func)(void*); typedef void (*dict_delete_func)(void*);
namespace zeek {
// Type indicating whether the dictionary should keep track of the order
// of insertions.
enum DictOrder { ORDERED, UNORDERED };
// A dict_delete_func that just calls delete. // A dict_delete_func that just calls delete.
extern void generic_delete_func(void*); extern void generic_delete_func(void*);
class Dictionary { class Dictionary {
public: public:
explicit Dictionary(dict_order ordering = UNORDERED, explicit Dictionary(DictOrder ordering = UNORDERED,
int initial_size = 0); int initial_size = 0);
~Dictionary(); ~Dictionary();
// Member functions for looking up a key, inserting/changing its // Member functions for looking up a key, inserting/changing its
@ -125,10 +129,10 @@ private:
void DeInit(); void DeInit();
// Internal version of Insert(). // Internal version of Insert().
void* Insert(DictEntry* entry, bool copy_key); void* Insert(zeek::detail::DictEntry* entry, bool copy_key);
void* DoRemove(DictEntry* entry, hash_t h, void* DoRemove(zeek::detail::DictEntry* entry, hash_t h,
PList<DictEntry>* chain, int chain_offset); zeek::PList<zeek::detail::DictEntry>* chain, int chain_offset);
int NextPrime(int n) const; int NextPrime(int n) const;
bool IsPrime(int n) const; bool IsPrime(int n) const;
@ -158,7 +162,7 @@ private:
// When we're resizing, we'll have tbl (old) and tbl2 (new) // When we're resizing, we'll have tbl (old) and tbl2 (new)
// tbl_next_ind keeps track of how much we've moved to tbl2 // tbl_next_ind keeps track of how much we've moved to tbl2
// (it's the next index we're going to move). // (it's the next index we're going to move).
PList<DictEntry>** tbl = nullptr; zeek::PList<zeek::detail::DictEntry>** tbl = nullptr;
int num_buckets = 0; int num_buckets = 0;
int num_entries = 0; int num_entries = 0;
int max_num_entries = 0; int max_num_entries = 0;
@ -167,7 +171,7 @@ private:
double den_thresh = 0.0; double den_thresh = 0.0;
// Resizing table (replicates tbl above). // Resizing table (replicates tbl above).
PList<DictEntry>** tbl2 = nullptr; zeek::PList<zeek::detail::DictEntry>** tbl2 = nullptr;
int num_buckets2 = 0; int num_buckets2 = 0;
int num_entries2 = 0; int num_entries2 = 0;
int max_num_entries2 = 0; int max_num_entries2 = 0;
@ -177,16 +181,16 @@ private:
hash_t tbl_next_ind = 0; hash_t tbl_next_ind = 0;
PList<DictEntry>* order = nullptr; zeek::PList<zeek::detail::DictEntry>* order = nullptr;
dict_delete_func delete_func = nullptr; dict_delete_func delete_func = nullptr;
PList<IterCookie> cookies; zeek::PList<IterCookie> cookies;
}; };
template<typename T> template<typename T>
class PDict : public Dictionary { class PDict : public Dictionary {
public: public:
explicit PDict(dict_order ordering = UNORDERED, int initial_size = 0) : explicit PDict(DictOrder ordering = UNORDERED, int initial_size = 0) :
Dictionary(ordering, initial_size) {} Dictionary(ordering, initial_size) {}
T* Lookup(const char* key) const T* Lookup(const char* key) const
{ {
@ -221,3 +225,8 @@ public:
T* RemoveEntry(const HashKey& key) T* RemoveEntry(const HashKey& key)
{ return (T*) Remove(key.Key(), key.Size(), key.Hash()); } { return (T*) Remove(key.Key(), key.Size(), key.Hash()); }
}; };
} //namespace zeek
using Dictionary [[deprecated("Remove in v4.1. Use zeek::Dictionary instead.")]] = zeek::Dictionary;
template<typename T> using PDict [[deprecated("Remove in v4.1. Use zeek::PDict instead.")]] = zeek::PDict<T>;

View file

@ -6,7 +6,7 @@
#include <algorithm> #include <algorithm>
#include "BroString.h" #include "ZeekString.h"
#include "Net.h" #include "Net.h"
#include "Func.h" #include "Func.h"
#include "Var.h" #include "Var.h"
@ -93,7 +93,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen)
zeek::Args args{ zeek::Args args{
ip->ToPktHdrVal(), ip->ToPktHdrVal(),
{AdoptRef{}, BuildData(data, th_len, len, caplen)}, {zeek::AdoptRef{}, BuildData(data, th_len, len, caplen)},
}; };
try try
@ -117,7 +117,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen)
zeek::Args args{ zeek::Args args{
ip->ToPktHdrVal(), ip->ToPktHdrVal(),
{AdoptRef{}, BuildData(data, uh_len, len, caplen)}, {zeek::AdoptRef{}, BuildData(data, uh_len, len, caplen)},
}; };
try try
@ -155,7 +155,7 @@ bool Discarder::NextPacket(const IP_Hdr* ip, int len, int caplen)
return discard_packet; return discard_packet;
} }
Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen) zeek::Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen)
{ {
len -= hdrlen; len -= hdrlen;
caplen -= hdrlen; caplen -= hdrlen;
@ -163,5 +163,5 @@ Val* Discarder::BuildData(const u_char* data, int hdrlen, int len, int caplen)
len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0); len = std::max(std::min(std::min(len, caplen), discarder_maxlen), 0);
return new StringVal(new BroString(data, len, true)); return new zeek::StringVal(new zeek::String(data, len, true));
} }

View file

@ -7,8 +7,13 @@
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
class IP_Hdr; class IP_Hdr;
class Val;
class Func; ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek {
using FuncPtr = zeek::IntrusivePtr<Func>;
}
class Discarder { class Discarder {
public: public:
@ -20,12 +25,12 @@ public:
bool NextPacket(const IP_Hdr* ip, int len, int caplen); bool NextPacket(const IP_Hdr* ip, int len, int caplen);
protected: protected:
Val* BuildData(const u_char* data, int hdrlen, int len, int caplen); zeek::Val* BuildData(const u_char* data, int hdrlen, int len, int caplen);
IntrusivePtr<Func> check_ip; zeek::FuncPtr check_ip;
IntrusivePtr<Func> check_tcp; zeek::FuncPtr check_tcp;
IntrusivePtr<Func> check_udp; zeek::FuncPtr check_udp;
IntrusivePtr<Func> check_icmp; zeek::FuncPtr check_icmp;
// Maximum amount of application data passed to filtering functions. // Maximum amount of application data passed to filtering functions.
int discarder_maxlen; int discarder_maxlen;

View file

@ -19,7 +19,7 @@ uint64_t num_events_queued = 0;
uint64_t num_events_dispatched = 0; uint64_t num_events_dispatched = 0;
Event::Event(EventHandlerPtr arg_handler, zeek::Args arg_args, Event::Event(EventHandlerPtr arg_handler, zeek::Args arg_args,
SourceID arg_src, analyzer::ID arg_aid, BroObj* arg_obj) SourceID arg_src, analyzer::ID arg_aid, Obj* arg_obj)
: handler(arg_handler), : handler(arg_handler),
args(std::move(arg_args)), args(std::move(arg_args)),
src(arg_src), src(arg_src),
@ -95,14 +95,14 @@ EventMgr::~EventMgr()
void EventMgr::QueueEventFast(const EventHandlerPtr &h, val_list vl, void EventMgr::QueueEventFast(const EventHandlerPtr &h, val_list vl,
SourceID src, analyzer::ID aid, TimerMgr* mgr, SourceID src, analyzer::ID aid, TimerMgr* mgr,
BroObj* obj) Obj* obj)
{ {
QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj)); QueueEvent(new Event(h, zeek::val_list_to_args(vl), src, aid, obj));
} }
void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl,
SourceID src, analyzer::ID aid, SourceID src, analyzer::ID aid,
TimerMgr* mgr, BroObj* obj) TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(vl); auto args = zeek::val_list_to_args(vl);
@ -112,7 +112,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list vl,
void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl, void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl,
SourceID src, analyzer::ID aid, SourceID src, analyzer::ID aid,
TimerMgr* mgr, BroObj* obj) TimerMgr* mgr, Obj* obj)
{ {
auto args = zeek::val_list_to_args(*vl); auto args = zeek::val_list_to_args(*vl);
delete vl; delete vl;
@ -122,7 +122,7 @@ void EventMgr::QueueEvent(const EventHandlerPtr &h, val_list* vl,
} }
void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args vl, void EventMgr::Enqueue(const EventHandlerPtr& h, zeek::Args vl,
SourceID src, analyzer::ID aid, BroObj* obj) SourceID src, analyzer::ID aid, Obj* obj)
{ {
QueueEvent(new Event(h, std::move(vl), src, aid, obj)); QueueEvent(new Event(h, std::move(vl), src, aid, obj));
} }

View file

@ -14,11 +14,11 @@
class EventMgr; class EventMgr;
class Event final : public BroObj { class Event final : public zeek::Obj {
public: public:
Event(EventHandlerPtr handler, zeek::Args args, Event(EventHandlerPtr handler, zeek::Args args,
SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0,
BroObj* obj = nullptr); zeek::Obj* obj = nullptr);
void SetNext(Event* n) { next_event = n; } void SetNext(Event* n) { next_event = n; }
Event* NextEvent() const { return next_event; } Event* NextEvent() const { return next_event; }
@ -41,14 +41,14 @@ protected:
zeek::Args args; zeek::Args args;
SourceID src; SourceID src;
analyzer::ID aid; analyzer::ID aid;
BroObj* obj; zeek::Obj* obj;
Event* next_event; Event* next_event;
}; };
extern uint64_t num_events_queued; extern uint64_t num_events_queued;
extern uint64_t num_events_dispatched; extern uint64_t num_events_dispatched;
class EventMgr final : public BroObj, public iosource::IOSource { class EventMgr final : public zeek::Obj, public iosource::IOSource {
public: public:
EventMgr(); EventMgr();
~EventMgr() override; ~EventMgr() override;
@ -64,7 +64,7 @@ public:
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEventFast(const EventHandlerPtr &h, val_list vl, void QueueEventFast(const EventHandlerPtr &h, val_list vl,
SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0,
TimerMgr* mgr = nullptr, BroObj* obj = nullptr); TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
// Queues an event if there's an event handler (or remote consumer). This // Queues an event if there's an event handler (or remote consumer). This
// function always takes ownership of decrementing the reference count of // function always takes ownership of decrementing the reference count of
@ -75,7 +75,7 @@ public:
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEvent(const EventHandlerPtr &h, val_list vl, void QueueEvent(const EventHandlerPtr &h, val_list vl,
SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0,
TimerMgr* mgr = nullptr, BroObj* obj = nullptr); TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
// Same as QueueEvent, except taking the event's argument list via a // Same as QueueEvent, except taking the event's argument list via a
// pointer instead of by value. This function takes ownership of the // pointer instead of by value. This function takes ownership of the
@ -84,7 +84,7 @@ public:
[[deprecated("Remove in v4.1. Use Enqueue() instead.")]] [[deprecated("Remove in v4.1. Use Enqueue() instead.")]]
void QueueEvent(const EventHandlerPtr &h, val_list* vl, void QueueEvent(const EventHandlerPtr &h, val_list* vl,
SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0,
TimerMgr* mgr = nullptr, BroObj* obj = nullptr); TimerMgr* mgr = nullptr, zeek::Obj* obj = nullptr);
/** /**
* Adds an event to the queue. If no handler is found for the event * Adds an event to the queue. If no handler is found for the event
@ -100,15 +100,15 @@ public:
*/ */
void Enqueue(const EventHandlerPtr& h, zeek::Args vl, void Enqueue(const EventHandlerPtr& h, zeek::Args vl,
SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0, SourceID src = SOURCE_LOCAL, analyzer::ID aid = 0,
BroObj* obj = nullptr); zeek::Obj* obj = nullptr);
/** /**
* A version of Enqueue() taking a variable number of arguments. * A version of Enqueue() taking a variable number of arguments.
*/ */
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v< std::is_convertible_v<
std::tuple_element_t<0, std::tuple<Args...>>, IntrusivePtr<Val>>> std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>>
Enqueue(const EventHandlerPtr& h, Args&&... args) Enqueue(const EventHandlerPtr& h, Args&&... args)
{ return Enqueue(h, zeek::Args{std::forward<Args>(args)...}); } { return Enqueue(h, zeek::Args{std::forward<Args>(args)...}); }
@ -143,7 +143,7 @@ protected:
Event* tail; Event* tail;
SourceID current_src; SourceID current_src;
analyzer::ID current_aid; analyzer::ID current_aid;
RecordVal* src_val; zeek::RecordVal* src_val;
bool draining; bool draining;
zeek::detail::Flare queue_flare; zeek::detail::Flare queue_flare;
}; };

View file

@ -26,13 +26,13 @@ EventHandler::operator bool() const
|| ! auto_publish.empty()); || ! auto_publish.empty());
} }
const IntrusivePtr<zeek::FuncType>& EventHandler::GetType(bool check_export) const zeek::FuncTypePtr& EventHandler::GetType(bool check_export)
{ {
if ( type ) if ( type )
return type; return type;
const auto& id = lookup_ID(name.data(), current_module.c_str(), false, false, const auto& id = zeek::detail::lookup_ID(name.data(), zeek::detail::current_module.c_str(),
check_export); false, false, check_export);
if ( ! id ) if ( ! id )
return zeek::FuncType::nil; return zeek::FuncType::nil;
@ -44,11 +44,11 @@ const IntrusivePtr<zeek::FuncType>& EventHandler::GetType(bool check_export)
return type; return type;
} }
void EventHandler::SetFunc(IntrusivePtr<Func> f) void EventHandler::SetFunc(zeek::FuncPtr f)
{ local = std::move(f); } { local = std::move(f); }
void EventHandler::SetLocalHandler(Func* f) void EventHandler::SetLocalHandler(zeek::Func* f)
{ SetFunc({NewRef{}, f}); } { SetFunc({zeek::NewRef{}, f}); }
void EventHandler::Call(zeek::Args* vl, bool no_remote) void EventHandler::Call(zeek::Args* vl, bool no_remote)
{ {
@ -118,7 +118,7 @@ void EventHandler::NewEvent(zeek::Args* vl)
const auto& args = GetType()->Params(); const auto& args = GetType()->Params();
static auto call_argument_vector = zeek::id::find_type<zeek::VectorType>("call_argument_vector"); static auto call_argument_vector = zeek::id::find_type<zeek::VectorType>("call_argument_vector");
auto vargs = make_intrusive<VectorVal>(call_argument_vector); auto vargs = zeek::make_intrusive<zeek::VectorVal>(call_argument_vector);
for ( int i = 0; i < args->NumFields(); i++ ) for ( int i = 0; i < args->NumFields(); i++ )
{ {
@ -127,13 +127,13 @@ void EventHandler::NewEvent(zeek::Args* vl)
auto fdefault = args->FieldDefault(i); auto fdefault = args->FieldDefault(i);
static auto call_argument = zeek::id::find_type<zeek::RecordType>("call_argument"); static auto call_argument = zeek::id::find_type<zeek::RecordType>("call_argument");
auto rec = make_intrusive<RecordVal>(call_argument); auto rec = zeek::make_intrusive<zeek::RecordVal>(call_argument);
rec->Assign(0, make_intrusive<StringVal>(fname)); rec->Assign(0, zeek::make_intrusive<zeek::StringVal>(fname));
ODesc d; ODesc d;
d.SetShort(); d.SetShort();
ftype->Describe(&d); ftype->Describe(&d);
rec->Assign(1, make_intrusive<StringVal>(d.Description())); rec->Assign(1, zeek::make_intrusive<zeek::StringVal>(d.Description()));
if ( fdefault ) if ( fdefault )
rec->Assign(2, std::move(fdefault)); rec->Assign(2, std::move(fdefault));
@ -145,8 +145,8 @@ void EventHandler::NewEvent(zeek::Args* vl)
} }
Event* ev = new Event(new_event, { Event* ev = new Event(new_event, {
make_intrusive<StringVal>(name), zeek::make_intrusive<zeek::StringVal>(name),
std::move(vargs), std::move(vargs),
}); });
mgr.Dispatch(ev); mgr.Dispatch(ev);
} }

View file

@ -9,7 +9,10 @@
#include <unordered_set> #include <unordered_set>
#include <string> #include <string>
class Func; ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
namespace zeek {
using FuncPtr = zeek::IntrusivePtr<zeek::Func>;
}
class EventHandler { class EventHandler {
public: public:
@ -17,22 +20,22 @@ public:
const char* Name() { return name.data(); } const char* Name() { return name.data(); }
const IntrusivePtr<Func>& GetFunc() const zeek::FuncPtr& GetFunc()
{ return local; } { return local; }
[[deprecated("Remove in v4.1. Use GetFunc().")]] [[deprecated("Remove in v4.1. Use GetFunc().")]]
Func* LocalHandler() { return local.get(); } zeek::Func* LocalHandler() { return local.get(); }
const IntrusivePtr<zeek::FuncType>& GetType(bool check_export = true); const zeek::FuncTypePtr& GetType(bool check_export = true);
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::FuncType* FType(bool check_export = true) zeek::FuncType* FType(bool check_export = true)
{ return GetType().get(); } { return GetType().get(); }
void SetFunc(IntrusivePtr<Func> f); void SetFunc(zeek::FuncPtr f);
[[deprecated("Remove in v4.1. Use SetFunc().")]] [[deprecated("Remove in v4.1. Use SetFunc().")]]
void SetLocalHandler(Func* f); void SetLocalHandler(zeek::Func* f);
void AutoPublish(std::string topic) void AutoPublish(std::string topic)
{ {
@ -68,8 +71,8 @@ private:
void NewEvent(zeek::Args* vl); // Raise new_event() meta event. void NewEvent(zeek::Args* vl); // Raise new_event() meta event.
std::string name; std::string name;
IntrusivePtr<Func> local; zeek::FuncPtr local;
IntrusivePtr<zeek::FuncType> type; zeek::FuncTypePtr type;
bool used; // this handler is indeed used somewhere bool used; // this handler is indeed used somewhere
bool enabled; bool enabled;
bool error_handler; // this handler reports error messages. bool error_handler; // this handler reports error messages.

File diff suppressed because it is too large Load diff

View file

@ -17,12 +17,18 @@
#include "Val.h" #include "Val.h"
#include "ZeekArgs.h" #include "ZeekArgs.h"
template <class T> class IntrusivePtr; ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
class Frame; ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail);
class Scope;
struct function_ingredients;
namespace zeek::detail { namespace zeek::detail { struct function_ingredients; }
using function_ingredients [[deprecated("Remove in v4.1. Use zeek::detail::function_ingredients.")]] = zeek::detail::function_ingredients;
namespace zeek {
template <class T> class IntrusivePtr;
namespace detail {
using IDPtr = zeek::IntrusivePtr<ID>;
enum BroExprTag : int { enum BroExprTag : int {
EXPR_ANY = -1, EXPR_ANY = -1,
@ -73,39 +79,43 @@ class CallExpr;
class EventExpr; class EventExpr;
class Stmt; class Stmt;
class Expr : public BroObj { class Expr;
using ExprPtr = zeek::IntrusivePtr<Expr>;
using EventExprPtr = zeek::IntrusivePtr<EventExpr>;
using ListExprPtr = zeek::IntrusivePtr<ListExpr>;
class Expr : public Obj {
public: public:
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::Type* Type() const { return type.get(); } zeek::Type* Type() const { return type.get(); }
const IntrusivePtr<zeek::Type>& GetType() const const zeek::TypePtr& GetType() const
{ return type; } { return type; }
template <class T> template <class T>
IntrusivePtr<T> GetType() const zeek::IntrusivePtr<T> GetType() const
{ return cast_intrusive<T>(type); } { return zeek::cast_intrusive<T>(type); }
BroExprTag Tag() const { return tag; } BroExprTag Tag() const { return tag; }
Expr* Ref() { ::Ref(this); return this; } Expr* Ref() { zeek::Ref(this); return this; }
// Evaluates the expression and returns a corresponding Val*, // Evaluates the expression and returns a corresponding Val*,
// or nil if the expression's value isn't fixed. // or nil if the expression's value isn't fixed.
virtual IntrusivePtr<Val> Eval(Frame* f) const = 0; virtual ValPtr Eval(Frame* f) const = 0;
// Same, but the context is that we are adding an element // Same, but the context is that we are adding an element
// into the given aggregate of the given type. Note that // into the given aggregate of the given type. Note that
// return type is void since it's updating an existing // return type is void since it's updating an existing
// value, rather than creating a new one. // value, rather than creating a new one.
virtual void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) virtual void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const;
const;
// Assign to the given value, if appropriate. // Assign to the given value, if appropriate.
virtual void Assign(Frame* f, IntrusivePtr<Val> v); virtual void Assign(Frame* f, ValPtr v);
// Returns the type corresponding to this expression interpreted // Returns the type corresponding to this expression interpreted
// as an initialization. Returns nil if the initialization is illegal. // as an initialization. Returns nil if the initialization is illegal.
virtual IntrusivePtr<zeek::Type> InitType() const; virtual zeek::TypePtr InitType() const;
// Returns true if this expression, interpreted as an initialization, // Returns true if this expression, interpreted as an initialization,
// constitutes a record element, false otherwise. If the TypeDecl* // constitutes a record element, false otherwise. If the TypeDecl*
@ -118,7 +128,7 @@ public:
// with the given type. If "aggr" is non-nil, then this expression // with the given type. If "aggr" is non-nil, then this expression
// is an element of the given aggregate, and it is added to it // is an element of the given aggregate, and it is added to it
// accordingly. // accordingly.
virtual IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const; virtual ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const;
// True if the expression has no side effects, false otherwise. // True if the expression has no side effects, false otherwise.
virtual bool IsPure() const; virtual bool IsPure() const;
@ -154,7 +164,7 @@ public:
// Return the expression converted to L-value form. If expr // Return the expression converted to L-value form. If expr
// cannot be used as an L-value, reports an error and returns // cannot be used as an L-value, reports an error and returns
// the current value of expr (this is the default method). // the current value of expr (this is the default method).
virtual IntrusivePtr<Expr> MakeLvalue(); virtual ExprPtr MakeLvalue();
// Marks the expression as one requiring (or at least appearing // Marks the expression as one requiring (or at least appearing
// with) parentheses. Used for pretty-printing. // with) parentheses. Used for pretty-printing.
@ -187,7 +197,7 @@ protected:
// Puts the expression in canonical form. // Puts the expression in canonical form.
virtual void Canonicize(); virtual void Canonicize();
void SetType(IntrusivePtr<zeek::Type> t); void SetType(zeek::TypePtr t);
// Reports the given error and sets the expression's type to // Reports the given error and sets the expression's type to
// TYPE_ERROR. // TYPE_ERROR.
@ -199,19 +209,19 @@ protected:
[[noreturn]] void RuntimeErrorWithCallStack(const std::string& msg) const; [[noreturn]] void RuntimeErrorWithCallStack(const std::string& msg) const;
BroExprTag tag; BroExprTag tag;
IntrusivePtr<zeek::Type> type; zeek::TypePtr type;
bool paren; bool paren;
}; };
class NameExpr final : public Expr { class NameExpr final : public Expr {
public: public:
explicit NameExpr(IntrusivePtr<ID> id, bool const_init = false); explicit NameExpr(zeek::detail::IDPtr id, bool const_init = false);
ID* Id() const { return id.get(); } ID* Id() const { return id.get(); }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
void Assign(Frame* f, IntrusivePtr<Val> v) override; void Assign(Frame* f, ValPtr v) override;
IntrusivePtr<Expr> MakeLvalue() override; ExprPtr MakeLvalue() override;
bool IsPure() const override; bool IsPure() const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
@ -219,23 +229,23 @@ public:
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<ID> id; zeek::detail::IDPtr id;
bool in_const_init; bool in_const_init;
}; };
class ConstExpr final : public Expr { class ConstExpr final : public Expr {
public: public:
explicit ConstExpr(IntrusivePtr<Val> val); explicit ConstExpr(ValPtr val);
Val* Value() const { return val.get(); } Val* Value() const { return val.get(); }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Val> val; ValPtr val;
}; };
class UnaryExpr : public Expr { class UnaryExpr : public Expr {
@ -245,21 +255,21 @@ public:
// UnaryExpr::Eval correctly handles vector types. Any child // UnaryExpr::Eval correctly handles vector types. Any child
// class that overrides Eval() should be modified to handle // class that overrides Eval() should be modified to handle
// vectors correctly as necessary. // vectors correctly as necessary.
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
bool IsPure() const override; bool IsPure() const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
UnaryExpr(BroExprTag arg_tag, IntrusivePtr<Expr> arg_op); UnaryExpr(BroExprTag arg_tag, ExprPtr arg_op);
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
// Returns the expression folded using the given constant. // Returns the expression folded using the given constant.
virtual IntrusivePtr<Val> Fold(Val* v) const; virtual ValPtr Fold(Val* v) const;
IntrusivePtr<Expr> op; ExprPtr op;
}; };
class BinaryExpr : public Expr { class BinaryExpr : public Expr {
@ -272,13 +282,13 @@ public:
// BinaryExpr::Eval correctly handles vector types. Any child // BinaryExpr::Eval correctly handles vector types. Any child
// class that overrides Eval() should be modified to handle // class that overrides Eval() should be modified to handle
// vectors correctly as necessary. // vectors correctly as necessary.
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
BinaryExpr(BroExprTag arg_tag, BinaryExpr(BroExprTag arg_tag,
IntrusivePtr<Expr> arg_op1, IntrusivePtr<Expr> arg_op2) ExprPtr arg_op1, ExprPtr arg_op2)
: Expr(arg_tag), op1(std::move(arg_op1)), op2(std::move(arg_op2)) : Expr(arg_tag), op1(std::move(arg_op1)), op2(std::move(arg_op2))
{ {
if ( ! (op1 && op2) ) if ( ! (op1 && op2) )
@ -288,20 +298,20 @@ protected:
} }
// Returns the expression folded using the given constants. // Returns the expression folded using the given constants.
virtual IntrusivePtr<Val> Fold(Val* v1, Val* v2) const; virtual ValPtr Fold(Val* v1, Val* v2) const;
// Same for when the constants are strings. // Same for when the constants are strings.
virtual IntrusivePtr<Val> StringFold(Val* v1, Val* v2) const; virtual ValPtr StringFold(Val* v1, Val* v2) const;
// Same for when the constants are patterns. // Same for when the constants are patterns.
virtual IntrusivePtr<Val> PatternFold(Val* v1, Val* v2) const; virtual ValPtr PatternFold(Val* v1, Val* v2) const;
// Same for when the constants are sets. // Same for when the constants are sets.
virtual IntrusivePtr<Val> SetFold(Val* v1, Val* v2) const; virtual ValPtr SetFold(Val* v1, Val* v2) const;
// Same for when the constants are addresses or subnets. // Same for when the constants are addresses or subnets.
virtual IntrusivePtr<Val> AddrFold(Val* v1, Val* v2) const; virtual ValPtr AddrFold(Val* v1, Val* v2) const;
virtual IntrusivePtr<Val> SubNetFold(Val* v1, Val* v2) const; virtual ValPtr SubNetFold(Val* v1, Val* v2) const;
bool BothConst() const { return op1->IsConst() && op2->IsConst(); } bool BothConst() const { return op1->IsConst() && op2->IsConst(); }
@ -317,148 +327,148 @@ protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Expr> op1; ExprPtr op1;
IntrusivePtr<Expr> op2; ExprPtr op2;
}; };
class CloneExpr final : public UnaryExpr { class CloneExpr final : public UnaryExpr {
public: public:
explicit CloneExpr(IntrusivePtr<Expr> op); explicit CloneExpr(ExprPtr op);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class IncrExpr final : public UnaryExpr { class IncrExpr final : public UnaryExpr {
public: public:
IncrExpr(BroExprTag tag, IntrusivePtr<Expr> op); IncrExpr(BroExprTag tag, ExprPtr op);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
IntrusivePtr<Val> DoSingleEval(Frame* f, Val* v) const; ValPtr DoSingleEval(Frame* f, Val* v) const;
bool IsPure() const override; bool IsPure() const override;
}; };
class ComplementExpr final : public UnaryExpr { class ComplementExpr final : public UnaryExpr {
public: public:
explicit ComplementExpr(IntrusivePtr<Expr> op); explicit ComplementExpr(ExprPtr op);
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class NotExpr final : public UnaryExpr { class NotExpr final : public UnaryExpr {
public: public:
explicit NotExpr(IntrusivePtr<Expr> op); explicit NotExpr(ExprPtr op);
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class PosExpr final : public UnaryExpr { class PosExpr final : public UnaryExpr {
public: public:
explicit PosExpr(IntrusivePtr<Expr> op); explicit PosExpr(ExprPtr op);
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class NegExpr final : public UnaryExpr { class NegExpr final : public UnaryExpr {
public: public:
explicit NegExpr(IntrusivePtr<Expr> op); explicit NegExpr(ExprPtr op);
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class SizeExpr final : public UnaryExpr { class SizeExpr final : public UnaryExpr {
public: public:
explicit SizeExpr(IntrusivePtr<Expr> op); explicit SizeExpr(ExprPtr op);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class AddExpr final : public BinaryExpr { class AddExpr final : public BinaryExpr {
public: public:
AddExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); AddExpr(ExprPtr op1, ExprPtr op2);
void Canonicize() override; void Canonicize() override;
}; };
class AddToExpr final : public BinaryExpr { class AddToExpr final : public BinaryExpr {
public: public:
AddToExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); AddToExpr(ExprPtr op1, ExprPtr op2);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
}; };
class RemoveFromExpr final : public BinaryExpr { class RemoveFromExpr final : public BinaryExpr {
public: public:
RemoveFromExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); RemoveFromExpr(ExprPtr op1, ExprPtr op2);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
}; };
class SubExpr final : public BinaryExpr { class SubExpr final : public BinaryExpr {
public: public:
SubExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); SubExpr(ExprPtr op1, ExprPtr op2);
}; };
class TimesExpr final : public BinaryExpr { class TimesExpr final : public BinaryExpr {
public: public:
TimesExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); TimesExpr(ExprPtr op1, ExprPtr op2);
void Canonicize() override; void Canonicize() override;
}; };
class DivideExpr final : public BinaryExpr { class DivideExpr final : public BinaryExpr {
public: public:
DivideExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); DivideExpr(ExprPtr op1, ExprPtr op2);
protected: protected:
IntrusivePtr<Val> AddrFold(Val* v1, Val* v2) const override; ValPtr AddrFold(Val* v1, Val* v2) const override;
}; };
class ModExpr final : public BinaryExpr { class ModExpr final : public BinaryExpr {
public: public:
ModExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); ModExpr(ExprPtr op1, ExprPtr op2);
}; };
class BoolExpr final : public BinaryExpr { class BoolExpr final : public BinaryExpr {
public: public:
BoolExpr(BroExprTag tag, IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); BoolExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
IntrusivePtr<Val> DoSingleEval(Frame* f, IntrusivePtr<Val> v1, Expr* op2) const; ValPtr DoSingleEval(Frame* f, ValPtr v1, Expr* op2) const;
}; };
class BitExpr final : public BinaryExpr { class BitExpr final : public BinaryExpr {
public: public:
BitExpr(BroExprTag tag, IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); BitExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2);
}; };
class EqExpr final : public BinaryExpr { class EqExpr final : public BinaryExpr {
public: public:
EqExpr(BroExprTag tag, IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); EqExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2);
void Canonicize() override; void Canonicize() override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v1, Val* v2) const override; ValPtr Fold(Val* v1, Val* v2) const override;
}; };
class RelExpr final : public BinaryExpr { class RelExpr final : public BinaryExpr {
public: public:
RelExpr(BroExprTag tag, IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); RelExpr(BroExprTag tag, ExprPtr op1, ExprPtr op2);
void Canonicize() override; void Canonicize() override;
}; };
class CondExpr final : public Expr { class CondExpr final : public Expr {
public: public:
CondExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2, IntrusivePtr<Expr> op3); CondExpr(ExprPtr op1, ExprPtr op2, ExprPtr op3);
const Expr* Op1() const { return op1.get(); } const Expr* Op1() const { return op1.get(); }
const Expr* Op2() const { return op2.get(); } const Expr* Op2() const { return op2.get(); }
const Expr* Op3() const { return op3.get(); } const Expr* Op3() const { return op3.get(); }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
bool IsPure() const override; bool IsPure() const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
@ -466,53 +476,53 @@ public:
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Expr> op1; ExprPtr op1;
IntrusivePtr<Expr> op2; ExprPtr op2;
IntrusivePtr<Expr> op3; ExprPtr op3;
}; };
class RefExpr final : public UnaryExpr { class RefExpr final : public UnaryExpr {
public: public:
explicit RefExpr(IntrusivePtr<Expr> op); explicit RefExpr(ExprPtr op);
void Assign(Frame* f, IntrusivePtr<Val> v) override; void Assign(Frame* f, ValPtr v) override;
IntrusivePtr<Expr> MakeLvalue() override; ExprPtr MakeLvalue() override;
}; };
class AssignExpr : public BinaryExpr { class AssignExpr : public BinaryExpr {
public: public:
// If val is given, evaluating this expression will always yield the val // If val is given, evaluating this expression will always yield the val
// yet still perform the assignment. Used for triggers. // yet still perform the assignment. Used for triggers.
AssignExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2, bool is_init, AssignExpr(ExprPtr op1, ExprPtr op2, bool is_init,
IntrusivePtr<Val> val = nullptr, ValPtr val = nullptr,
const IntrusivePtr<Attributes>& attrs = nullptr); const AttributesPtr& attrs = nullptr);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const override; void EvalIntoAggregate(const zeek::Type* t, Val* aggr, Frame* f) const override;
IntrusivePtr<zeek::Type> InitType() const override; zeek::TypePtr InitType() const override;
bool IsRecordElement(TypeDecl* td) const override; bool IsRecordElement(TypeDecl* td) const override;
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
bool IsPure() const override; bool IsPure() const override;
protected: protected:
bool TypeCheck(const IntrusivePtr<Attributes>& attrs = nullptr); bool TypeCheck(const AttributesPtr& attrs = nullptr);
bool TypeCheckArithmetics(TypeTag bt1, TypeTag bt2); bool TypeCheckArithmetics(TypeTag bt1, TypeTag bt2);
bool is_init; bool is_init;
IntrusivePtr<Val> val; // optional ValPtr val; // optional
}; };
class IndexSliceAssignExpr final : public AssignExpr { class IndexSliceAssignExpr final : public AssignExpr {
public: public:
IndexSliceAssignExpr(IntrusivePtr<Expr> op1, IndexSliceAssignExpr(ExprPtr op1,
IntrusivePtr<Expr> op2, bool is_init); ExprPtr op2, bool is_init);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
}; };
class IndexExpr final : public BinaryExpr { class IndexExpr final : public BinaryExpr {
public: public:
IndexExpr(IntrusivePtr<Expr> op1, IndexExpr(ExprPtr op1,
IntrusivePtr<ListExpr> op2, bool is_slice = false); ListExprPtr op2, bool is_slice = false);
bool CanAdd() const override; bool CanAdd() const override;
bool CanDel() const override; bool CanDel() const override;
@ -520,19 +530,19 @@ public:
void Add(Frame* f) override; void Add(Frame* f) override;
void Delete(Frame* f) override; void Delete(Frame* f) override;
void Assign(Frame* f, IntrusivePtr<Val> v) override; void Assign(Frame* f, ValPtr v) override;
IntrusivePtr<Expr> MakeLvalue() override; ExprPtr MakeLvalue() override;
// Need to override Eval since it can take a vector arg but does // Need to override Eval since it can take a vector arg but does
// not necessarily return a vector. // not necessarily return a vector.
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
bool IsSlice() const { return is_slice; } bool IsSlice() const { return is_slice; }
protected: protected:
IntrusivePtr<Val> Fold(Val* v1, Val* v2) const override; ValPtr Fold(Val* v1, Val* v2) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -541,7 +551,7 @@ protected:
class FieldExpr final : public UnaryExpr { class FieldExpr final : public UnaryExpr {
public: public:
FieldExpr(IntrusivePtr<Expr> op, const char* field_name); FieldExpr(ExprPtr op, const char* field_name);
~FieldExpr() override; ~FieldExpr() override;
int Field() const { return field; } int Field() const { return field; }
@ -549,13 +559,13 @@ public:
bool CanDel() const override; bool CanDel() const override;
void Assign(Frame* f, IntrusivePtr<Val> v) override; void Assign(Frame* f, ValPtr v) override;
void Delete(Frame* f) override; void Delete(Frame* f) override;
IntrusivePtr<Expr> MakeLvalue() override; ExprPtr MakeLvalue() override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -568,13 +578,13 @@ protected:
// "rec?$$attrname" is true if the attribute attrname is not nil. // "rec?$$attrname" is true if the attribute attrname is not nil.
class HasFieldExpr final : public UnaryExpr { class HasFieldExpr final : public UnaryExpr {
public: public:
HasFieldExpr(IntrusivePtr<Expr> op, const char* field_name); HasFieldExpr(ExprPtr op, const char* field_name);
~HasFieldExpr() override; ~HasFieldExpr() override;
const char* FieldName() const { return field_name; } const char* FieldName() const { return field_name; }
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -584,76 +594,76 @@ protected:
class RecordConstructorExpr final : public UnaryExpr { class RecordConstructorExpr final : public UnaryExpr {
public: public:
explicit RecordConstructorExpr(IntrusivePtr<ListExpr> constructor_list); explicit RecordConstructorExpr(ListExprPtr constructor_list);
~RecordConstructorExpr() override; ~RecordConstructorExpr() override;
protected: protected:
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
}; };
class TableConstructorExpr final : public UnaryExpr { class TableConstructorExpr final : public UnaryExpr {
public: public:
TableConstructorExpr(IntrusivePtr<ListExpr> constructor_list, TableConstructorExpr(ListExprPtr constructor_list,
std::unique_ptr<std::vector<IntrusivePtr<Attr>>> attrs, std::unique_ptr<std::vector<AttrPtr>> attrs,
IntrusivePtr<zeek::Type> arg_type = nullptr); zeek::TypePtr arg_type = nullptr);
[[deprecated("Remove in v4.1. Use GetAttrs().")]] [[deprecated("Remove in v4.1. Use GetAttrs().")]]
Attributes* Attrs() { return attrs.get(); } Attributes* Attrs() { return attrs.get(); }
const IntrusivePtr<Attributes>& GetAttrs() const const AttributesPtr& GetAttrs() const
{ return attrs; } { return attrs; }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
protected: protected:
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Attributes> attrs; AttributesPtr attrs;
}; };
class SetConstructorExpr final : public UnaryExpr { class SetConstructorExpr final : public UnaryExpr {
public: public:
SetConstructorExpr(IntrusivePtr<ListExpr> constructor_list, SetConstructorExpr(ListExprPtr constructor_list,
std::unique_ptr<std::vector<IntrusivePtr<Attr>>> attrs, std::unique_ptr<std::vector<AttrPtr>> attrs,
IntrusivePtr<zeek::Type> arg_type = nullptr); zeek::TypePtr arg_type = nullptr);
[[deprecated("Remove in v4.1. Use GetAttrs().")]] [[deprecated("Remove in v4.1. Use GetAttrs().")]]
Attributes* Attrs() { return attrs.get(); } Attributes* Attrs() { return attrs.get(); }
const IntrusivePtr<Attributes>& GetAttrs() const const AttributesPtr& GetAttrs() const
{ return attrs; } { return attrs; }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
protected: protected:
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Attributes> attrs; AttributesPtr attrs;
}; };
class VectorConstructorExpr final : public UnaryExpr { class VectorConstructorExpr final : public UnaryExpr {
public: public:
explicit VectorConstructorExpr(IntrusivePtr<ListExpr> constructor_list, explicit VectorConstructorExpr(ListExprPtr constructor_list,
IntrusivePtr<zeek::Type> arg_type = nullptr); zeek::TypePtr arg_type = nullptr);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
protected: protected:
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
}; };
class FieldAssignExpr final : public UnaryExpr { class FieldAssignExpr final : public UnaryExpr {
public: public:
FieldAssignExpr(const char* field_name, IntrusivePtr<Expr> value); FieldAssignExpr(const char* field_name, ExprPtr value);
const char* FieldName() const { return field_name.c_str(); } const char* FieldName() const { return field_name.c_str(); }
@ -668,21 +678,21 @@ protected:
class ArithCoerceExpr final : public UnaryExpr { class ArithCoerceExpr final : public UnaryExpr {
public: public:
ArithCoerceExpr(IntrusivePtr<Expr> op, zeek::TypeTag t); ArithCoerceExpr(ExprPtr op, zeek::TypeTag t);
protected: protected:
IntrusivePtr<Val> FoldSingleVal(Val* v, InternalTypeTag t) const; ValPtr FoldSingleVal(Val* v, InternalTypeTag t) const;
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class RecordCoerceExpr final : public UnaryExpr { class RecordCoerceExpr final : public UnaryExpr {
public: public:
RecordCoerceExpr(IntrusivePtr<Expr> op, IntrusivePtr<RecordType> r); RecordCoerceExpr(ExprPtr op, RecordTypePtr r);
~RecordCoerceExpr() override; ~RecordCoerceExpr() override;
protected: protected:
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
// For each super-record slot, gives subrecord slot with which to // For each super-record slot, gives subrecord slot with which to
// fill it. // fill it.
@ -692,20 +702,20 @@ protected:
class TableCoerceExpr final : public UnaryExpr { class TableCoerceExpr final : public UnaryExpr {
public: public:
TableCoerceExpr(IntrusivePtr<Expr> op, IntrusivePtr<TableType> r); TableCoerceExpr(ExprPtr op, TableTypePtr r);
~TableCoerceExpr() override; ~TableCoerceExpr() override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class VectorCoerceExpr final : public UnaryExpr { class VectorCoerceExpr final : public UnaryExpr {
public: public:
VectorCoerceExpr(IntrusivePtr<Expr> op, IntrusivePtr<VectorType> v); VectorCoerceExpr(ExprPtr op, VectorTypePtr v);
~VectorCoerceExpr() override; ~VectorCoerceExpr() override;
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
}; };
class ScheduleTimer final : public Timer { class ScheduleTimer final : public Timer {
@ -722,11 +732,11 @@ protected:
class ScheduleExpr final : public Expr { class ScheduleExpr final : public Expr {
public: public:
ScheduleExpr(IntrusivePtr<Expr> when, IntrusivePtr<EventExpr> event); ScheduleExpr(ExprPtr when, EventExprPtr event);
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
Expr* When() const { return when.get(); } Expr* When() const { return when.get(); }
EventExpr* Event() const { return event.get(); } EventExpr* Event() const { return event.get(); }
@ -736,22 +746,22 @@ public:
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Expr> when; ExprPtr when;
IntrusivePtr<EventExpr> event; EventExprPtr event;
}; };
class InExpr final : public BinaryExpr { class InExpr final : public BinaryExpr {
public: public:
InExpr(IntrusivePtr<Expr> op1, IntrusivePtr<Expr> op2); InExpr(ExprPtr op1, ExprPtr op2);
protected: protected:
IntrusivePtr<Val> Fold(Val* v1, Val* v2) const override; ValPtr Fold(Val* v1, Val* v2) const override;
}; };
class CallExpr final : public Expr { class CallExpr final : public Expr {
public: public:
CallExpr(IntrusivePtr<Expr> func, IntrusivePtr<ListExpr> args, CallExpr(ExprPtr func, ListExprPtr args,
bool in_hook = false); bool in_hook = false);
Expr* Func() const { return func.get(); } Expr* Func() const { return func.get(); }
@ -759,15 +769,15 @@ public:
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
IntrusivePtr<Expr> func; ExprPtr func;
IntrusivePtr<ListExpr> args; ListExprPtr args;
}; };
@ -781,7 +791,7 @@ public:
LambdaExpr(std::unique_ptr<function_ingredients> ingredients, LambdaExpr(std::unique_ptr<function_ingredients> ingredients,
id_list outer_ids); id_list outer_ids);
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
Scope* GetScope() const; Scope* GetScope() const;
@ -798,13 +808,13 @@ private:
class EventExpr final : public Expr { class EventExpr final : public Expr {
public: public:
EventExpr(const char* name, IntrusivePtr<ListExpr> args); EventExpr(const char* name, ListExprPtr args);
const char* Name() const { return name.c_str(); } const char* Name() const { return name.c_str(); }
ListExpr* Args() const { return args.get(); } ListExpr* Args() const { return args.get(); }
EventHandlerPtr Handler() const { return handler; } EventHandlerPtr Handler() const { return handler; }
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
@ -813,16 +823,16 @@ protected:
std::string name; std::string name;
EventHandlerPtr handler; EventHandlerPtr handler;
IntrusivePtr<ListExpr> args; ListExprPtr args;
}; };
class ListExpr : public Expr { class ListExpr : public Expr {
public: public:
ListExpr(); ListExpr();
explicit ListExpr(IntrusivePtr<Expr> e); explicit ListExpr(ExprPtr e);
~ListExpr() override; ~ListExpr() override;
void Append(IntrusivePtr<Expr> e); void Append(ExprPtr e);
const expr_list& Exprs() const { return exprs; } const expr_list& Exprs() const { return exprs; }
expr_list& Exprs() { return exprs; } expr_list& Exprs() { return exprs; }
@ -830,17 +840,17 @@ public:
// True if the entire list represents pure values. // True if the entire list represents pure values.
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
IntrusivePtr<zeek::Type> InitType() const override; zeek::TypePtr InitType() const override;
IntrusivePtr<Val> InitVal(const zeek::Type* t, IntrusivePtr<Val> aggr) const override; ValPtr InitVal(const zeek::Type* t, ValPtr aggr) const override;
IntrusivePtr<Expr> MakeLvalue() override; ExprPtr MakeLvalue() override;
void Assign(Frame* f, IntrusivePtr<Val> v) override; void Assign(Frame* f, ValPtr v) override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Val> AddSetInit(const zeek::Type* t, IntrusivePtr<Val> aggr) const; ValPtr AddSetInit(const zeek::Type* t, ValPtr aggr) const;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
@ -850,28 +860,28 @@ protected:
class RecordAssignExpr final : public ListExpr { class RecordAssignExpr final : public ListExpr {
public: public:
RecordAssignExpr(const IntrusivePtr<Expr>& record, const IntrusivePtr<Expr>& init_list, bool is_init); RecordAssignExpr(const ExprPtr& record, const ExprPtr& init_list, bool is_init);
}; };
class CastExpr final : public UnaryExpr { class CastExpr final : public UnaryExpr {
public: public:
CastExpr(IntrusivePtr<Expr> op, IntrusivePtr<zeek::Type> t); CastExpr(ExprPtr op, zeek::TypePtr t);
protected: protected:
IntrusivePtr<Val> Eval(Frame* f) const override; ValPtr Eval(Frame* f) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
}; };
class IsExpr final : public UnaryExpr { class IsExpr final : public UnaryExpr {
public: public:
IsExpr(IntrusivePtr<Expr> op, IntrusivePtr<zeek::Type> t); IsExpr(ExprPtr op, zeek::TypePtr t);
protected: protected:
IntrusivePtr<Val> Fold(Val* v) const override; ValPtr Fold(Val* v) const override;
void ExprDescribe(ODesc* d) const override; void ExprDescribe(ODesc* d) const override;
private: private:
IntrusivePtr<zeek::Type> t; zeek::TypePtr t;
}; };
inline Val* Expr::ExprVal() const inline Val* Expr::ExprVal() const
@ -882,8 +892,9 @@ inline Val* Expr::ExprVal() const
} }
// Decides whether to return an AssignExpr or a RecordAssignExpr. // Decides whether to return an AssignExpr or a RecordAssignExpr.
IntrusivePtr<Expr> get_assign_expr(IntrusivePtr<Expr> op1, ExprPtr get_assign_expr(
IntrusivePtr<Expr> op2, bool is_init); ExprPtr op1,
ExprPtr op2, bool is_init);
// Type-check the given expression(s) against the given type(s). Complain // Type-check the given expression(s) against the given type(s). Complain
// if the expression cannot match the given type, returning 0. If it can // if the expression cannot match the given type, returning 0. If it can
@ -900,7 +911,7 @@ IntrusivePtr<Expr> get_assign_expr(IntrusivePtr<Expr> op1,
* Returns nullptr if the expression cannot match or a promoted * Returns nullptr if the expression cannot match or a promoted
* expression. * expression.
*/ */
extern IntrusivePtr<Expr> check_and_promote_expr(Expr* e, Type* t); extern ExprPtr check_and_promote_expr(Expr* e, Type* t);
extern bool check_and_promote_exprs(ListExpr* elements, TypeList* types); extern bool check_and_promote_exprs(ListExpr* elements, TypeList* types);
extern bool check_and_promote_args(ListExpr* args, RecordType* types); extern bool check_and_promote_args(ListExpr* args, RecordType* types);
@ -908,7 +919,7 @@ extern bool check_and_promote_exprs_to_type(ListExpr* elements, Type* type);
// Returns a ListExpr simplified down to a list a values, or nil // Returns a ListExpr simplified down to a list a values, or nil
// if they couldn't all be reduced. // if they couldn't all be reduced.
std::optional<std::vector<IntrusivePtr<Val>>> eval_list(Frame* f, const ListExpr* l); std::optional<std::vector<ValPtr>> eval_list(Frame* f, const ListExpr* l);
// Returns true if e1 is "greater" than e2 - here "greater" is just // Returns true if e1 is "greater" than e2 - here "greater" is just
// a heuristic, used with commutative operators to put them into // a heuristic, used with commutative operators to put them into
@ -917,9 +928,10 @@ extern bool expr_greater(const Expr* e1, const Expr* e2);
// True if the given Expr* has a vector type // True if the given Expr* has a vector type
inline bool is_vector(Expr* e) { return e->GetType()->Tag() == TYPE_VECTOR; } inline bool is_vector(Expr* e) { return e->GetType()->Tag() == TYPE_VECTOR; }
inline bool is_vector(const IntrusivePtr<Expr>& e) { return is_vector(e.get()); } inline bool is_vector(const ExprPtr& e) { return is_vector(e.get()); }
} } // namespace detail
} // namespace zeek
using Expr [[deprecated("Remove in v4.1. Use zeek::detail::Expr instead.")]] = zeek::detail::Expr; using Expr [[deprecated("Remove in v4.1. Use zeek::detail::Expr instead.")]] = zeek::detail::Expr;
using NameExpr [[deprecated("Remove in v4.1. Use zeek::detail::NameExpr instead.")]] = zeek::detail::NameExpr; using NameExpr [[deprecated("Remove in v4.1. Use zeek::detail::NameExpr instead.")]] = zeek::detail::NameExpr;

View file

@ -269,7 +269,7 @@ void BroFile::SetAttrs(zeek::detail::Attributes* arg_attrs)
EnableRawOutput(); EnableRawOutput();
} }
RecordVal* BroFile::Rotate() zeek::RecordVal* BroFile::Rotate()
{ {
if ( ! is_open ) if ( ! is_open )
return nullptr; return nullptr;
@ -279,7 +279,7 @@ RecordVal* BroFile::Rotate()
return nullptr; return nullptr;
static auto rotate_info = zeek::id::find_type<zeek::RecordType>("rotate_info"); static auto rotate_info = zeek::id::find_type<zeek::RecordType>("rotate_info");
RecordVal* info = new RecordVal(rotate_info); auto* info = new zeek::RecordVal(rotate_info);
FILE* newf = rotate_file(name, info); FILE* newf = rotate_file(name, info);
if ( ! newf ) if ( ! newf )
@ -288,7 +288,7 @@ RecordVal* BroFile::Rotate()
return nullptr; return nullptr;
} }
info->Assign<TimeVal>(2, open_time); info->Assign<zeek::TimeVal>(2, open_time);
Unlink(); Unlink();
@ -328,8 +328,8 @@ void BroFile::RaiseOpenEvent()
if ( ! ::file_opened ) if ( ! ::file_opened )
return; return;
IntrusivePtr<BroFile> bf{NewRef{}, this}; BroFilePtr bf{zeek::NewRef{}, this};
Event* event = new ::Event(::file_opened, {make_intrusive<Val>(std::move(bf))}); Event* event = new ::Event(::file_opened, {zeek::make_intrusive<zeek::Val>(std::move(bf))});
mgr.Dispatch(event, true); mgr.Dispatch(event, true);
} }
@ -346,11 +346,11 @@ double BroFile::Size()
return s.st_size; return s.st_size;
} }
IntrusivePtr<BroFile> BroFile::Get(const char* name) BroFilePtr BroFile::Get(const char* name)
{ {
for ( const auto &el : open_files ) for ( const auto &el : open_files )
if ( el.first == name ) if ( el.first == name )
return {NewRef{}, el.second}; return {zeek::NewRef{}, el.second};
return make_intrusive<BroFile>(name, "w"); return zeek::make_intrusive<BroFile>(name, "w");
} }

View file

@ -16,15 +16,20 @@
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
#include "util.h" #include "util.h"
class RecordVal; namespace zeek {
class Type;
namespace zeek { class Type; } using TypePtr = zeek::IntrusivePtr<zeek::Type>;
}
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
ZEEK_FORWARD_DECLARE_NAMESPACED(PrintStmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(PrintStmt, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Attributes, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Attributes, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek);
class BroFile final : public BroObj { class BroFile;
using BroFilePtr = zeek::IntrusivePtr<BroFile>;
class BroFile final : public zeek::Obj {
public: public:
explicit BroFile(FILE* arg_f); explicit BroFile(FILE* arg_f);
BroFile(FILE* arg_f, const char* filename, const char* access); BroFile(FILE* arg_f, const char* filename, const char* access);
@ -45,7 +50,7 @@ public:
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::Type* FType() const { return t.get(); } zeek::Type* FType() const { return t.get(); }
const IntrusivePtr<zeek::Type>& GetType() const const zeek::TypePtr& GetType() const
{ return t; } { return t; }
// Whether the file is open in a general sense; it might // Whether the file is open in a general sense; it might
@ -60,7 +65,7 @@ public:
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
// Rotates the logfile. Returns rotate_info. // Rotates the logfile. Returns rotate_info.
RecordVal* Rotate(); zeek::RecordVal* Rotate();
// Set &raw_output attribute. // Set &raw_output attribute.
void SetAttrs(zeek::detail::Attributes* attrs); void SetAttrs(zeek::detail::Attributes* attrs);
@ -72,7 +77,7 @@ public:
static void CloseOpenFiles(); static void CloseOpenFiles();
// Get the file with the given name, opening it if it doesn't yet exist. // Get the file with the given name, opening it if it doesn't yet exist.
static IntrusivePtr<BroFile> Get(const char* name); static BroFilePtr Get(const char* name);
[[deprecated("Remove in v4.1. Use BroFile::Get().")]] [[deprecated("Remove in v4.1. Use BroFile::Get().")]]
static BroFile* GetFile(const char* name) static BroFile* GetFile(const char* name)
{ return Get(name).release(); } { return Get(name).release(); }
@ -106,7 +111,7 @@ protected:
void RaiseOpenEvent(); void RaiseOpenEvent();
FILE* f; FILE* f;
IntrusivePtr<zeek::Type> t; zeek::TypePtr t;
char* name; char* name;
char* access; char* access;
zeek::detail::Attributes* attrs; zeek::detail::Attributes* attrs;

View file

@ -7,14 +7,15 @@
#include "Func.h" #include "Func.h"
#include "Desc.h" #include "Desc.h"
#include "IntrusivePtr.h"
#include "Trigger.h" #include "Trigger.h"
#include "Val.h" #include "Val.h"
#include "ID.h" #include "ID.h"
std::vector<Frame*> g_frame_stack; std::vector<zeek::detail::Frame*> g_frame_stack;
Frame::Frame(int arg_size, const BroFunc* func, const zeek::Args* fn_args) namespace zeek::detail {
Frame::Frame(int arg_size, const ScriptFunc* func, const zeek::Args* fn_args)
{ {
size = arg_size; size = arg_size;
frame = std::make_unique<Element[]>(size); frame = std::make_unique<Element[]>(size);
@ -52,32 +53,32 @@ Frame::~Frame()
ClearElement(i); ClearElement(i);
} }
void Frame::AddFunctionWithClosureRef(BroFunc* func) void Frame::AddFunctionWithClosureRef(ScriptFunc* func)
{ {
::Ref(func); zeek::Ref(func);
if ( ! functions_with_closure_frame_reference ) if ( ! functions_with_closure_frame_reference )
functions_with_closure_frame_reference = std::make_unique<std::vector<BroFunc*>>(); functions_with_closure_frame_reference = std::make_unique<std::vector<ScriptFunc*>>();
functions_with_closure_frame_reference->emplace_back(func); functions_with_closure_frame_reference->emplace_back(func);
} }
void Frame::SetElement(int n, Val* v) void Frame::SetElement(int n, zeek::Val* v)
{ SetElement(n, {AdoptRef{}, v}); } { SetElement(n, {zeek::AdoptRef{}, v}); }
void Frame::SetElement(int n, IntrusivePtr<Val> v) void Frame::SetElement(int n, zeek::ValPtr v)
{ {
ClearElement(n); ClearElement(n);
frame[n] = {std::move(v), false}; frame[n] = {std::move(v), false};
} }
void Frame::SetElementWeak(int n, Val* v) void Frame::SetElementWeak(int n, zeek::Val* v)
{ {
ClearElement(n); ClearElement(n);
frame[n] = {{AdoptRef{}, v}, true}; frame[n] = {{zeek::AdoptRef{}, v}, true};
} }
void Frame::SetElement(const zeek::detail::ID* id, IntrusivePtr<Val> v) void Frame::SetElement(const zeek::detail::ID* id, zeek::ValPtr v)
{ {
if ( closure ) if ( closure )
{ {
@ -106,7 +107,7 @@ void Frame::SetElement(const zeek::detail::ID* id, IntrusivePtr<Val> v)
SetElement(id->Offset(), std::move(v)); SetElement(id->Offset(), std::move(v));
} }
const IntrusivePtr<Val>& Frame::GetElementByID(const zeek::detail::ID* id) const const zeek::ValPtr& Frame::GetElementByID(const zeek::detail::ID* id) const
{ {
if ( closure ) if ( closure )
{ {
@ -173,7 +174,7 @@ Frame* Frame::Clone() const
return other; return other;
} }
static bool val_is_func(const IntrusivePtr<Val>& v, BroFunc* func) static bool val_is_func(const zeek::ValPtr& v, ScriptFunc* func)
{ {
if ( v->GetType()->Tag() != zeek::TYPE_FUNC ) if ( v->GetType()->Tag() != zeek::TYPE_FUNC )
return false; return false;
@ -181,7 +182,7 @@ static bool val_is_func(const IntrusivePtr<Val>& v, BroFunc* func)
return v->AsFunc() == func; return v->AsFunc() == func;
} }
void Frame::CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const void Frame::CloneNonFuncElement(int offset, ScriptFunc* func, Frame* other) const
{ {
const auto& v = frame[offset].val; const auto& v = frame[offset].val;
@ -198,7 +199,7 @@ void Frame::CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const
other->SetElement(offset, std::move(rval)); other->SetElement(offset, std::move(rval));
} }
Frame* Frame::SelectiveClone(const id_list& selection, BroFunc* func) const Frame* Frame::SelectiveClone(const id_list& selection, ScriptFunc* func) const
{ {
if ( selection.length() == 0 ) if ( selection.length() == 0 )
return nullptr; return nullptr;
@ -348,14 +349,14 @@ broker::expected<broker::data> Frame::Serialize(const Frame* target, const id_li
return {std::move(rval)}; return {std::move(rval)};
} }
std::pair<bool, IntrusivePtr<Frame>> Frame::Unserialize(const broker::vector& data) std::pair<bool, FramePtr> Frame::Unserialize(const broker::vector& data)
{ {
if ( data.size() == 0 ) if ( data.size() == 0 )
return std::make_pair(true, nullptr); return std::make_pair(true, nullptr);
id_list outer_ids; id_list outer_ids;
OffsetMap offset_map; OffsetMap offset_map;
IntrusivePtr<Frame> closure; FramePtr closure;
auto where = data.begin(); auto where = data.begin();
@ -437,7 +438,7 @@ std::pair<bool, IntrusivePtr<Frame>> Frame::Unserialize(const broker::vector& da
int frame_size = body.size(); int frame_size = body.size();
// We'll associate this frame with a function later. // We'll associate this frame with a function later.
auto rf = make_intrusive<Frame>(frame_size, nullptr, nullptr); auto rf = zeek::make_intrusive<Frame>(frame_size, nullptr, nullptr);
rf->offset_map = std::make_unique<OffsetMap>(std::move(offset_map)); rf->offset_map = std::make_unique<OffsetMap>(std::move(offset_map));
// Frame takes ownership of unref'ing elements in outer_ids // Frame takes ownership of unref'ing elements in outer_ids
@ -492,7 +493,7 @@ void Frame::CaptureClosure(Frame* c, id_list arg_outer_ids)
outer_ids = std::move(arg_outer_ids); outer_ids = std::move(arg_outer_ids);
for ( auto& i : outer_ids ) for ( auto& i : outer_ids )
::Ref(i); zeek::Ref(i);
closure = c; closure = c;
if ( closure ) if ( closure )
@ -505,7 +506,7 @@ void Frame::CaptureClosure(Frame* c, id_list arg_outer_ids)
// if (c) closure = c->SelectiveClone(outer_ids); // if (c) closure = c->SelectiveClone(outer_ids);
} }
void Frame::SetTrigger(IntrusivePtr<zeek::detail::trigger::Trigger> arg_trigger) void Frame::SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger)
{ {
trigger = std::move(arg_trigger); trigger = std::move(arg_trigger);
} }
@ -617,3 +618,5 @@ Frame::UnserializeOffsetMap(const broker::vector& data)
return std::make_pair(true, std::move(rval)); return std::make_pair(true, std::move(rval));
} }
}

View file

@ -16,12 +16,26 @@
#include <broker/data.hh> #include <broker/data.hh>
#include <broker/expected.hh> #include <broker/expected.hh>
class BroFunc;
ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Trigger, zeek::detail::trigger); ZEEK_FORWARD_DECLARE_NAMESPACED(Trigger, zeek::detail::trigger);
class Frame : public BroObj { namespace zeek::detail { class ScriptFunc; }
using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc instead.")]] = zeek::detail::ScriptFunc;
namespace zeek {
using ValPtr = zeek::IntrusivePtr<Val>;
namespace detail {
using IDPtr = zeek::IntrusivePtr<ID>;
namespace trigger {
using TriggerPtr = zeek::IntrusivePtr<Trigger>;
}
class Frame;
using FramePtr = zeek::IntrusivePtr<Frame>;
class Frame : public Obj {
public: public:
/** /**
* Constructs a new frame belonging to *func* with *fn_args* * Constructs a new frame belonging to *func* with *fn_args*
@ -31,7 +45,7 @@ public:
* @param func the function that is creating this frame * @param func the function that is creating this frame
* @param fn_args the arguments being passed to that function. * @param fn_args the arguments being passed to that function.
*/ */
Frame(int size, const BroFunc* func, const zeek::Args* fn_args); Frame(int size, const ScriptFunc* func, const zeek::Args* fn_args);
/** /**
* Deletes the frame. Unrefs its trigger, the values that it * Deletes the frame. Unrefs its trigger, the values that it
@ -43,21 +57,21 @@ public:
* @param n the index to get. * @param n the index to get.
* @return the value at index *n* of the underlying array. * @return the value at index *n* of the underlying array.
*/ */
const IntrusivePtr<Val>& GetElement(int n) const const zeek::ValPtr& GetElement(int n) const
{ return frame[n].val; } { return frame[n].val; }
[[deprecated("Remove in v4.1. Use GetElement(int).")]] [[deprecated("Remove in v4.1. Use GetElement(int).")]]
Val* NthElement(int n) const { return frame[n].val.get(); } zeek::Val* NthElement(int n) const { return frame[n].val.get(); }
/** /**
* Sets the element at index *n* of the underlying array to *v*. * Sets the element at index *n* of the underlying array to *v*.
* @param n the index to set * @param n the index to set
* @param v the value to set it to * @param v the value to set it to
*/ */
void SetElement(int n, IntrusivePtr<Val> v); void SetElement(int n, zeek::ValPtr v);
[[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Pass IntrusivePtr instead.")]]
void SetElement(int n, Val* v); void SetElement(int n, zeek::Val* v);
/** /**
* Associates *id* and *v* in the frame. Future lookups of * Associates *id* and *v* in the frame. Future lookups of
@ -66,8 +80,8 @@ public:
* @param id the ID to associate * @param id the ID to associate
* @param v the value to associate it with * @param v the value to associate it with
*/ */
void SetElement(const zeek::detail::ID* id, IntrusivePtr<Val> v); void SetElement(const zeek::detail::ID* id, zeek::ValPtr v);
void SetElement(const IntrusivePtr<zeek::detail::ID>& id, IntrusivePtr<Val> v) void SetElement(const zeek::detail::IDPtr& id, zeek::ValPtr v)
{ SetElement(id.get(), std::move(v)); } { SetElement(id.get(), std::move(v)); }
/** /**
@ -77,11 +91,11 @@ public:
* @param id the id who's value to retreive * @param id the id who's value to retreive
* @return the value associated with *id* * @return the value associated with *id*
*/ */
const IntrusivePtr<Val>& GetElementByID(const IntrusivePtr<zeek::detail::ID>& id) const const zeek::ValPtr& GetElementByID(const zeek::detail::IDPtr& id) const
{ return GetElementByID(id.get()); } { return GetElementByID(id.get()); }
[[deprecated("Remove in v4.1. Use GetElementByID().")]] [[deprecated("Remove in v4.1. Use GetElementByID().")]]
Val* GetElement(const zeek::detail::ID* id) const zeek::Val* GetElement(const zeek::detail::ID* id) const
{ return GetElementByID(id).get(); } { return GetElementByID(id).get(); }
/** /**
@ -99,7 +113,7 @@ public:
/** /**
* @return the function that the frame is associated with. * @return the function that the frame is associated with.
*/ */
const BroFunc* GetFunction() const { return function; } const ScriptFunc* GetFunction() const { return function; }
/** /**
* @return the arguments passed to the function that this frame * @return the arguments passed to the function that this frame
@ -112,7 +126,7 @@ public:
* *
* @param func the function for the frame to be associated with. * @param func the function for the frame to be associated with.
*/ */
void SetFunction(BroFunc* func) { function = func; } void SetFunction(ScriptFunc* func) { function = func; }
/** /**
* Sets the next statement to be executed in the context of the frame. * Sets the next statement to be executed in the context of the frame.
@ -161,7 +175,7 @@ public:
* *selection* have been cloned. All other values are made to be * *selection* have been cloned. All other values are made to be
* null. * null.
*/ */
Frame* SelectiveClone(const id_list& selection, BroFunc* func) const; Frame* SelectiveClone(const id_list& selection, ScriptFunc* func) const;
/** /**
* Serializes the Frame into a Broker representation. * Serializes the Frame into a Broker representation.
@ -195,7 +209,7 @@ public:
* and the second is the unserialized frame with reference count +1, or * and the second is the unserialized frame with reference count +1, or
* null if the serialization wasn't successful. * null if the serialization wasn't successful.
*/ */
static std::pair<bool, IntrusivePtr<Frame>> Unserialize(const broker::vector& data); static std::pair<bool, FramePtr> Unserialize(const broker::vector& data);
/** /**
* Sets the IDs that the frame knows offsets for. These offsets will * Sets the IDs that the frame knows offsets for. These offsets will
@ -216,7 +230,7 @@ public:
// If the frame is run in the context of a trigger condition evaluation, // If the frame is run in the context of a trigger condition evaluation,
// the trigger needs to be registered. // the trigger needs to be registered.
void SetTrigger(IntrusivePtr<zeek::detail::trigger::Trigger> arg_trigger); void SetTrigger(zeek::detail::trigger::TriggerPtr arg_trigger);
void ClearTrigger(); void ClearTrigger();
zeek::detail::trigger::Trigger* GetTrigger() const { return trigger.get(); } zeek::detail::trigger::Trigger* GetTrigger() const { return trigger.get(); }
@ -234,20 +248,20 @@ public:
* weak references prevents unbreakable circular references that * weak references prevents unbreakable circular references that
* otherwise cause memory leaks. * otherwise cause memory leaks.
*/ */
void AddFunctionWithClosureRef(BroFunc* func); void AddFunctionWithClosureRef(ScriptFunc* func);
private: private:
using OffsetMap = std::unordered_map<std::string, int>; using OffsetMap = std::unordered_map<std::string, int>;
struct Element { struct Element {
IntrusivePtr<Val> val; zeek::ValPtr val;
// Weak reference is used to prevent circular reference memory leaks // Weak reference is used to prevent circular reference memory leaks
// in lambdas/closures. // in lambdas/closures.
bool weak_ref; bool weak_ref;
}; };
const IntrusivePtr<Val>& GetElementByID(const zeek::detail::ID* id) const; const zeek::ValPtr& GetElementByID(const zeek::detail::ID* id) const;
/** /**
* Sets the element at index *n* of the underlying array to *v*, but does * Sets the element at index *n* of the underlying array to *v*, but does
@ -257,14 +271,14 @@ private:
* @param v the value to set it to (caller has not Ref'd and Frame will * @param v the value to set it to (caller has not Ref'd and Frame will
* not Unref it) * not Unref it)
*/ */
void SetElementWeak(int n, Val* v); void SetElementWeak(int n, zeek::Val* v);
/** /**
* Clone an element at an offset into other frame if not equal to a given * Clone an element at an offset into other frame if not equal to a given
* function (in that case just assigna weak reference). Used to break * function (in that case just assigna weak reference). Used to break
* circular references between lambda functions and closure frames. * circular references between lambda functions and closure frames.
*/ */
void CloneNonFuncElement(int offset, BroFunc* func, Frame* other) const; void CloneNonFuncElement(int offset, ScriptFunc* func, Frame* other) const;
/** /**
* Resets the value at offset 'n' frame (by decrementing reference * Resets the value at offset 'n' frame (by decrementing reference
@ -315,19 +329,24 @@ private:
std::unique_ptr<OffsetMap> offset_map; std::unique_ptr<OffsetMap> offset_map;
/** The function this frame is associated with. */ /** The function this frame is associated with. */
const BroFunc* function; const ScriptFunc* function;
/** The arguments to the function that this Frame is associated with. */ /** The arguments to the function that this Frame is associated with. */
const zeek::Args* func_args; const zeek::Args* func_args;
/** The next statement to be evaluted in the context of this frame. */ /** The next statement to be evaluted in the context of this frame. */
zeek::detail::Stmt* next_stmt; zeek::detail::Stmt* next_stmt;
IntrusivePtr<zeek::detail::trigger::Trigger> trigger; zeek::detail::trigger::TriggerPtr trigger;
const zeek::detail::CallExpr* call; const zeek::detail::CallExpr* call;
std::unique_ptr<std::vector<BroFunc*>> functions_with_closure_frame_reference; std::unique_ptr<std::vector<ScriptFunc*>> functions_with_closure_frame_reference;
}; };
} // namespace detail
} // namespace zeek
using Frame [[deprecated("Remove in v4.1. Use zeek::detail::Frame instead.")]] = zeek::detail::Frame;
/** /**
* If we stopped using this and instead just made a struct of the information * If we stopped using this and instead just made a struct of the information
* that the debugger actually uses we could make the Frame a class a template. * that the debugger actually uses we could make the Frame a class a template.
@ -338,4 +357,4 @@ private:
* DebugFrame which provides the information that the debugger uses. See: * DebugFrame which provides the information that the debugger uses. See:
* https://stackoverflow.com/a/16211097 * https://stackoverflow.com/a/16211097
*/ */
extern std::vector<Frame*> g_frame_stack; extern std::vector<zeek::detail::Frame*> g_frame_stack;

View file

@ -1,3 +1,4 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
#include "zeek-config.h" #include "zeek-config.h"
@ -54,22 +55,39 @@
#include "iosource/PktSrc.h" #include "iosource/PktSrc.h"
#include "iosource/PktDumper.h" #include "iosource/PktDumper.h"
#include "zeek.bif.func_h"
#include "stats.bif.func_h"
#include "reporter.bif.func_h"
#include "strings.bif.func_h"
#include "option.bif.func_h"
#include "supervisor.bif.func_h"
#include "zeek.bif.func_def"
#include "stats.bif.func_def"
#include "reporter.bif.func_def"
#include "strings.bif.func_def"
#include "option.bif.func_def"
#include "supervisor.bif.func_def"
extern RETSIGTYPE sig_handler(int signo); extern RETSIGTYPE sig_handler(int signo);
namespace zeek::detail {
std::vector<CallInfo> call_stack; std::vector<CallInfo> call_stack;
bool did_builtin_init = false; bool did_builtin_init = false;
static const std::pair<bool, zeek::ValPtr> empty_hook_result(false, nullptr);
} // namespace zeek::detail
static const std::pair<bool, IntrusivePtr<Val>> empty_hook_result(false, nullptr); namespace zeek {
std::string render_call_stack() std::string render_call_stack()
{ {
std::string rval; std::string rval;
int lvl = 0; int lvl = 0;
if ( ! call_stack.empty() ) if ( ! detail::call_stack.empty() )
rval += "| "; rval += "| ";
for ( auto it = call_stack.rbegin(); it != call_stack.rend(); ++it ) for ( auto it = detail::call_stack.rbegin(); it != detail::call_stack.rend(); ++it )
{ {
if ( lvl > 0 ) if ( lvl > 0 )
rval += " | "; rval += " | ";
@ -101,7 +119,7 @@ std::string render_call_stack()
++lvl; ++lvl;
} }
if ( ! call_stack.empty() ) if ( ! detail::call_stack.empty() )
rval += " |"; rval += " |";
return rval; return rval;
@ -110,34 +128,34 @@ std::string render_call_stack()
Func::Func() Func::Func()
{ {
unique_id = unique_ids.size(); unique_id = unique_ids.size();
unique_ids.push_back({NewRef{}, this}); unique_ids.push_back({zeek::NewRef{}, this});
} }
Func::Func(Kind arg_kind) : kind(arg_kind) Func::Func(Kind arg_kind) : kind(arg_kind)
{ {
unique_id = unique_ids.size(); unique_id = unique_ids.size();
unique_ids.push_back({NewRef{}, this}); unique_ids.push_back({zeek::NewRef{}, this});
} }
Func::~Func() = default; Func::~Func() = default;
void Func::AddBody(IntrusivePtr<zeek::detail::Stmt> /* new_body */, void Func::AddBody(zeek::detail::StmtPtr /* new_body */,
const std::vector<IntrusivePtr<zeek::detail::ID>>& /* new_inits */, const std::vector<zeek::detail::IDPtr>& /* new_inits */,
size_t /* new_frame_size */, int /* priority */) size_t /* new_frame_size */, int /* priority */)
{ {
Internal("Func::AddBody called"); Internal("Func::AddBody called");
} }
void Func::SetScope(IntrusivePtr<Scope> newscope) void Func::SetScope(zeek::detail::ScopePtr newscope)
{ {
scope = std::move(newscope); scope = std::move(newscope);
} }
IntrusivePtr<Func> Func::DoClone() zeek::FuncPtr Func::DoClone()
{ {
// By default, ok just to return a reference. Func does not have any state // By default, ok just to return a reference. Func does not have any state
// that is different across instances. // that is different across instances.
return {NewRef{}, this}; return {zeek::NewRef{}, this};
} }
void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const
@ -178,14 +196,14 @@ void Func::DescribeDebug(ODesc* d, const zeek::Args* args) const
TraversalCode Func::Traverse(TraversalCallback* cb) const TraversalCode Func::Traverse(TraversalCallback* cb) const
{ {
// FIXME: Make a fake scope for builtins? // FIXME: Make a fake scope for builtins?
Scope* old_scope = cb->current_scope; zeek::detail::Scope* old_scope = cb->current_scope;
cb->current_scope = scope.get(); cb->current_scope = scope.get();
TraversalCode tc = cb->PreFunction(this); TraversalCode tc = cb->PreFunction(this);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
// FIXME: Traverse arguments to builtin functions, too. // FIXME: Traverse arguments to builtin functions, too.
if ( kind == BRO_FUNC && scope ) if ( kind == SCRIPT_FUNC && scope )
{ {
tc = scope->Traverse(cb); tc = scope->Traverse(cb);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
@ -215,10 +233,10 @@ void Func::CopyStateInto(Func* other) const
other->unique_id = unique_id; other->unique_id = unique_id;
} }
void Func::CheckPluginResult(bool handled, const IntrusivePtr<Val>& hook_result, void Func::CheckPluginResult(bool handled, const zeek::ValPtr& hook_result,
zeek::FunctionFlavor flavor) const zeek::FunctionFlavor flavor) const
{ {
// Helper function factoring out this code from BroFunc:Call() for // Helper function factoring out this code from ScriptFunc:Call() for
// better readability. // better readability.
if ( ! handled ) if ( ! handled )
@ -268,10 +286,18 @@ void Func::CheckPluginResult(bool handled, const IntrusivePtr<Val>& hook_result,
} }
} }
BroFunc::BroFunc(const IntrusivePtr<zeek::detail::ID>& arg_id, IntrusivePtr<zeek::detail::Stmt> arg_body, zeek::Val* Func::Call(val_list* args, zeek::detail::Frame* parent) const
const std::vector<IntrusivePtr<zeek::detail::ID>>& aggr_inits, {
size_t arg_frame_size, int priority) auto zargs = zeek::val_list_to_args(*args);
: Func(BRO_FUNC) return Invoke(&zargs, parent).release();
};
namespace detail {
ScriptFunc::ScriptFunc(const zeek::detail::IDPtr& arg_id, zeek::detail::StmtPtr arg_body,
const std::vector<zeek::detail::IDPtr>& aggr_inits,
size_t arg_frame_size, int priority)
: Func(SCRIPT_FUNC)
{ {
name = arg_id->Name(); name = arg_id->Name();
type = arg_id->GetType<zeek::FuncType>(); type = arg_id->GetType<zeek::FuncType>();
@ -286,25 +312,19 @@ BroFunc::BroFunc(const IntrusivePtr<zeek::detail::ID>& arg_id, IntrusivePtr<zeek
} }
} }
BroFunc::~BroFunc() ScriptFunc::~ScriptFunc()
{ {
if ( ! weak_closure_ref ) if ( ! weak_closure_ref )
Unref(closure); Unref(closure);
} }
bool BroFunc::IsPure() const bool ScriptFunc::IsPure() const
{ {
return std::all_of(bodies.begin(), bodies.end(), return std::all_of(bodies.begin(), bodies.end(),
[](const Body& b) { return b.stmts->IsPure(); }); [](const Body& b) { return b.stmts->IsPure(); });
} }
Val* Func::Call(val_list* args, Frame* parent) const zeek::ValPtr ScriptFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const
{
auto zargs = zeek::val_list_to_args(*args);
return Invoke(&zargs, parent).release();
};
IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
{ {
#ifdef PROFILE_BRO_FUNCTIONS #ifdef PROFILE_BRO_FUNCTIONS
DEBUG_MSG("Function: %s\n", Name()); DEBUG_MSG("Function: %s\n", Name());
@ -327,10 +347,10 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
{ {
// Can only happen for events and hooks. // Can only happen for events and hooks.
assert(Flavor() == zeek::FUNC_FLAVOR_EVENT || Flavor() == zeek::FUNC_FLAVOR_HOOK); assert(Flavor() == zeek::FUNC_FLAVOR_EVENT || Flavor() == zeek::FUNC_FLAVOR_HOOK);
return Flavor() == zeek::FUNC_FLAVOR_HOOK ? val_mgr->True() : nullptr; return Flavor() == zeek::FUNC_FLAVOR_HOOK ? zeek::val_mgr->True() : nullptr;
} }
auto f = make_intrusive<Frame>(frame_size, this, args); auto f = zeek::make_intrusive<zeek::detail::Frame>(frame_size, this, args);
if ( closure ) if ( closure )
f->CaptureClosure(closure, outer_ids); f->CaptureClosure(closure, outer_ids);
@ -338,7 +358,7 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
// Hand down any trigger. // Hand down any trigger.
if ( parent ) if ( parent )
{ {
f->SetTrigger({NewRef{}, parent->GetTrigger()}); f->SetTrigger({zeek::NewRef{}, parent->GetTrigger()});
f->SetCall(parent->GetCall()); f->SetCall(parent->GetCall());
} }
@ -356,7 +376,7 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
} }
stmt_flow_type flow = FLOW_NEXT; stmt_flow_type flow = FLOW_NEXT;
IntrusivePtr<Val> result; zeek::ValPtr result;
for ( const auto& body : bodies ) for ( const auto& body : bodies )
{ {
@ -413,7 +433,7 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
if ( flow == FLOW_BREAK ) if ( flow == FLOW_BREAK )
{ {
// Short-circuit execution of remaining hook handler bodies. // Short-circuit execution of remaining hook handler bodies.
result = val_mgr->False(); result = zeek::val_mgr->False();
break; break;
} }
} }
@ -424,7 +444,7 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
if ( Flavor() == zeek::FUNC_FLAVOR_HOOK ) if ( Flavor() == zeek::FUNC_FLAVOR_HOOK )
{ {
if ( ! result ) if ( ! result )
result = val_mgr->True(); result = zeek::val_mgr->True();
} }
// Warn if the function returns something, but we returned from // Warn if the function returns something, but we returned from
@ -449,9 +469,9 @@ IntrusivePtr<Val> BroFunc::Invoke(zeek::Args* args, Frame* parent) const
return result; return result;
} }
void BroFunc::AddBody(IntrusivePtr<zeek::detail::Stmt> new_body, void ScriptFunc::AddBody(zeek::detail::StmtPtr new_body,
const std::vector<IntrusivePtr<zeek::detail::ID>>& new_inits, const std::vector<zeek::detail::IDPtr>& new_inits,
size_t new_frame_size, int priority) size_t new_frame_size, int priority)
{ {
if ( new_frame_size > frame_size ) if ( new_frame_size > frame_size )
frame_size = new_frame_size; frame_size = new_frame_size;
@ -478,7 +498,7 @@ void BroFunc::AddBody(IntrusivePtr<zeek::detail::Stmt> new_body,
sort(bodies.begin(), bodies.end()); sort(bodies.begin(), bodies.end());
} }
void BroFunc::AddClosure(id_list ids, Frame* f) void ScriptFunc::AddClosure(id_list ids, zeek::detail::Frame* f)
{ {
if ( ! f ) if ( ! f )
return; return;
@ -487,7 +507,7 @@ void BroFunc::AddClosure(id_list ids, Frame* f)
SetClosureFrame(f); SetClosureFrame(f);
} }
bool BroFunc::StrengthenClosureReference(Frame* f) bool ScriptFunc::StrengthenClosureReference(zeek::detail::Frame* f)
{ {
if ( closure != f ) if ( closure != f )
return false; return false;
@ -500,10 +520,10 @@ bool BroFunc::StrengthenClosureReference(Frame* f)
return true; return true;
} }
void BroFunc::SetClosureFrame(Frame* f) void ScriptFunc::SetClosureFrame(zeek::detail::Frame* f)
{ {
if ( closure ) if ( closure )
reporter->InternalError("Tried to override closure for BroFunc %s.", reporter->InternalError("Tried to override closure for ScriptFunc %s.",
Name()); Name());
// Have to use weak references initially because otherwise Ref'ing the // Have to use weak references initially because otherwise Ref'ing the
@ -518,9 +538,9 @@ void BroFunc::SetClosureFrame(Frame* f)
f->AddFunctionWithClosureRef(this); f->AddFunctionWithClosureRef(this);
} }
bool BroFunc::UpdateClosure(const broker::vector& data) bool ScriptFunc::UpdateClosure(const broker::vector& data)
{ {
auto result = Frame::Unserialize(data); auto result = zeek::detail::Frame::Unserialize(data);
if ( ! result.first ) if ( ! result.first )
return false; return false;
@ -540,11 +560,11 @@ bool BroFunc::UpdateClosure(const broker::vector& data)
} }
IntrusivePtr<Func> BroFunc::DoClone() zeek::FuncPtr ScriptFunc::DoClone()
{ {
// BroFunc could hold a closure. In this case a clone of it must // ScriptFunc could hold a closure. In this case a clone of it must
// store a copy of this closure. // store a copy of this closure.
auto other = IntrusivePtr{AdoptRef{}, new BroFunc()}; auto other = zeek::IntrusivePtr{zeek::AdoptRef{}, new ScriptFunc()};
CopyStateInto(other.get()); CopyStateInto(other.get());
@ -556,12 +576,12 @@ IntrusivePtr<Func> BroFunc::DoClone()
return other; return other;
} }
broker::expected<broker::data> BroFunc::SerializeClosure() const broker::expected<broker::data> ScriptFunc::SerializeClosure() const
{ {
return Frame::Serialize(closure, outer_ids); return zeek::detail::Frame::Serialize(closure, outer_ids);
} }
void BroFunc::Describe(ODesc* d) const void ScriptFunc::Describe(ODesc* d) const
{ {
d->Add(Name()); d->Add(Name());
@ -574,13 +594,14 @@ void BroFunc::Describe(ODesc* d) const
} }
} }
IntrusivePtr<zeek::detail::Stmt> BroFunc::AddInits(IntrusivePtr<zeek::detail::Stmt> body, zeek::detail::StmtPtr ScriptFunc::AddInits(
const std::vector<IntrusivePtr<zeek::detail::ID>>& inits) zeek::detail::StmtPtr body,
const std::vector<zeek::detail::IDPtr>& inits)
{ {
if ( inits.empty() ) if ( inits.empty() )
return body; return body;
auto stmt_series = make_intrusive<zeek::detail::StmtList>(); auto stmt_series = zeek::make_intrusive<zeek::detail::StmtList>();
stmt_series->Stmts().push_back(new zeek::detail::InitStmt(inits)); stmt_series->Stmts().push_back(new zeek::detail::InitStmt(inits));
stmt_series->Stmts().push_back(body.release()); stmt_series->Stmts().push_back(body.release());
@ -588,21 +609,21 @@ IntrusivePtr<zeek::detail::Stmt> BroFunc::AddInits(IntrusivePtr<zeek::detail::St
} }
BuiltinFunc::BuiltinFunc(built_in_func arg_func, const char* arg_name, BuiltinFunc::BuiltinFunc(built_in_func arg_func, const char* arg_name,
bool arg_is_pure) bool arg_is_pure)
: Func(BUILTIN_FUNC) : Func(BUILTIN_FUNC)
{ {
func = arg_func; func = arg_func;
name = make_full_var_name(GLOBAL_MODULE_NAME, arg_name); name = make_full_var_name(GLOBAL_MODULE_NAME, arg_name);
is_pure = arg_is_pure; is_pure = arg_is_pure;
const auto& id = lookup_ID(Name(), GLOBAL_MODULE_NAME, false); const auto& id = zeek::detail::lookup_ID(Name(), GLOBAL_MODULE_NAME, false);
if ( ! id ) if ( ! id )
reporter->InternalError("built-in function %s missing", Name()); reporter->InternalError("built-in function %s missing", Name());
if ( id->HasVal() ) if ( id->HasVal() )
reporter->InternalError("built-in function %s multiply defined", Name()); reporter->InternalError("built-in function %s multiply defined", Name());
type = id->GetType<zeek::FuncType>(); type = id->GetType<zeek::FuncType>();
id->SetVal(make_intrusive<Val>(IntrusivePtr{NewRef{}, this})); id->SetVal(zeek::make_intrusive<zeek::Val>(zeek::IntrusivePtr{zeek::NewRef{}, this}));
} }
BuiltinFunc::~BuiltinFunc() BuiltinFunc::~BuiltinFunc()
@ -614,7 +635,7 @@ bool BuiltinFunc::IsPure() const
return is_pure; return is_pure;
} }
IntrusivePtr<Val> BuiltinFunc::Invoke(zeek::Args* args, Frame* parent) const zeek::ValPtr BuiltinFunc::Invoke(zeek::Args* args, zeek::detail::Frame* parent) const
{ {
#ifdef PROFILE_BRO_FUNCTIONS #ifdef PROFILE_BRO_FUNCTIONS
DEBUG_MSG("Function: %s\n", Name()); DEBUG_MSG("Function: %s\n", Name());
@ -663,132 +684,6 @@ void BuiltinFunc::Describe(ODesc* d) const
d->AddCount(is_pure); d->AddCount(is_pure);
} }
void builtin_error(const char* msg)
{
builtin_error(msg, IntrusivePtr<Val>{});
}
void builtin_error(const char* msg, IntrusivePtr<Val> arg)
{
builtin_error(msg, arg.get());
}
void builtin_error(const char* msg, BroObj* arg)
{
auto emit = [=](const zeek::detail::CallExpr* ce)
{
if ( ce )
ce->Error(msg, arg);
else
reporter->Error(msg, arg);
};
if ( call_stack.empty() )
{
emit(nullptr);
return;
}
auto last_call = call_stack.back();
if ( call_stack.size() < 2 )
{
// Don't need to check for wrapper function like "<module>::__<func>"
emit(last_call.call);
return;
}
auto starts_with_double_underscore = [](const std::string& name) -> bool
{ return name.size() > 2 && name[0] == '_' && name[1] == '_'; };
std::string last_func = last_call.func->Name();
auto pos = last_func.find_first_of("::");
std::string wrapper_func;
if ( pos == std::string::npos )
{
if ( ! starts_with_double_underscore(last_func) )
{
emit(last_call.call);
return;
}
wrapper_func = last_func.substr(2);
}
else
{
auto module_name = last_func.substr(0, pos);
auto func_name = last_func.substr(pos + 2);
if ( ! starts_with_double_underscore(func_name) )
{
emit(last_call.call);
return;
}
wrapper_func = module_name + "::" + func_name.substr(2);
}
auto parent_call = call_stack[call_stack.size() - 2];
auto parent_func = parent_call.func->Name();
if ( wrapper_func == parent_func )
emit(parent_call.call);
else
emit(last_call.call);
}
#include "zeek.bif.func_h"
#include "stats.bif.func_h"
#include "reporter.bif.func_h"
#include "strings.bif.func_h"
#include "option.bif.func_h"
#include "supervisor.bif.func_h"
#include "zeek.bif.func_def"
#include "stats.bif.func_def"
#include "reporter.bif.func_def"
#include "strings.bif.func_def"
#include "option.bif.func_def"
#include "supervisor.bif.func_def"
#include "__all__.bif.cc" // Autogenerated for compiling in the bif_target() code.
#include "__all__.bif.register.cc" // Autogenerated for compiling in the bif_target() code.
void init_builtin_funcs()
{
ProcStats = zeek::id::find_type<zeek::RecordType>("ProcStats");
NetStats = zeek::id::find_type<zeek::RecordType>("NetStats");
MatcherStats = zeek::id::find_type<zeek::RecordType>("MatcherStats");
ConnStats = zeek::id::find_type<zeek::RecordType>("ConnStats");
ReassemblerStats = zeek::id::find_type<zeek::RecordType>("ReassemblerStats");
DNSStats = zeek::id::find_type<zeek::RecordType>("DNSStats");
GapStats = zeek::id::find_type<zeek::RecordType>("GapStats");
EventStats = zeek::id::find_type<zeek::RecordType>("EventStats");
TimerStats = zeek::id::find_type<zeek::RecordType>("TimerStats");
FileAnalysisStats = zeek::id::find_type<zeek::RecordType>("FileAnalysisStats");
ThreadStats = zeek::id::find_type<zeek::RecordType>("ThreadStats");
BrokerStats = zeek::id::find_type<zeek::RecordType>("BrokerStats");
ReporterStats = zeek::id::find_type<zeek::RecordType>("ReporterStats");
var_sizes = zeek::id::find_type("var_sizes")->AsTableType();
#include "zeek.bif.func_init"
#include "stats.bif.func_init"
#include "reporter.bif.func_init"
#include "strings.bif.func_init"
#include "option.bif.func_init"
#include "supervisor.bif.func_init"
did_builtin_init = true;
}
void init_builtin_funcs_subdirs()
{
#include "__all__.bif.init.cc" // Autogenerated for compiling in the bif_target() code.
}
bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call) bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call)
{ {
if ( f->TheFunc() != zeek::BifFunc::fmt_bif) if ( f->TheFunc() != zeek::BifFunc::fmt_bif)
@ -844,7 +739,7 @@ bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call)
// Gets a function's priority from its Scope's attributes. Errors if it sees any // Gets a function's priority from its Scope's attributes. Errors if it sees any
// problems. // problems.
static int get_func_priority(const std::vector<IntrusivePtr<zeek::detail::Attr>>& attrs) static int get_func_priority(const std::vector<zeek::detail::AttrPtr>& attrs)
{ {
int priority = 0; int priority = 0;
@ -879,7 +774,7 @@ static int get_func_priority(const std::vector<IntrusivePtr<zeek::detail::Attr>>
return priority; return priority;
} }
function_ingredients::function_ingredients(IntrusivePtr<Scope> scope, IntrusivePtr<zeek::detail::Stmt> body) function_ingredients::function_ingredients(zeek::detail::ScopePtr scope, zeek::detail::StmtPtr body)
{ {
frame_size = scope->Length(); frame_size = scope->Length();
inits = scope->GetInits(); inits = scope->GetInits();
@ -892,3 +787,134 @@ function_ingredients::function_ingredients(IntrusivePtr<Scope> scope, IntrusiveP
priority = (attrs ? get_func_priority(*attrs) : 0); priority = (attrs ? get_func_priority(*attrs) : 0);
this->body = std::move(body); this->body = std::move(body);
} }
} // namespace detail
void emit_builtin_error(const char* msg)
{
emit_builtin_error(msg, zeek::ValPtr{});
}
void emit_builtin_error(const char* msg, zeek::ValPtr arg)
{
emit_builtin_error(msg, arg.get());
}
void emit_builtin_error(const char* msg, Obj* arg)
{
auto emit = [=](const zeek::detail::CallExpr* ce)
{
if ( ce )
ce->Error(msg, arg);
else
reporter->Error(msg, arg);
};
if ( zeek::detail::call_stack.empty() )
{
emit(nullptr);
return;
}
auto last_call = zeek::detail::call_stack.back();
if ( zeek::detail::call_stack.size() < 2 )
{
// Don't need to check for wrapper function like "<module>::__<func>"
emit(last_call.call);
return;
}
auto starts_with_double_underscore = [](const std::string& name) -> bool
{ return name.size() > 2 && name[0] == '_' && name[1] == '_'; };
std::string last_func = last_call.func->Name();
auto pos = last_func.find_first_of("::");
std::string wrapper_func;
if ( pos == std::string::npos )
{
if ( ! starts_with_double_underscore(last_func) )
{
emit(last_call.call);
return;
}
wrapper_func = last_func.substr(2);
}
else
{
auto module_name = last_func.substr(0, pos);
auto func_name = last_func.substr(pos + 2);
if ( ! starts_with_double_underscore(func_name) )
{
emit(last_call.call);
return;
}
wrapper_func = module_name + "::" + func_name.substr(2);
}
auto parent_call = zeek::detail::call_stack[zeek::detail::call_stack.size() - 2];
auto parent_func = parent_call.func->Name();
if ( wrapper_func == parent_func )
emit(parent_call.call);
else
emit(last_call.call);
}
} // namespace zeek
void builtin_error(const char* msg)
{
zeek::emit_builtin_error(msg);
}
void builtin_error(const char* msg, zeek::ValPtr arg)
{
zeek::emit_builtin_error(msg, arg);
}
void builtin_error(const char* msg, zeek::Obj* arg)
{
zeek::emit_builtin_error(msg, arg);
}
#include "__all__.bif.cc" // Autogenerated for compiling in the bif_target() code.
#include "__all__.bif.register.cc" // Autogenerated for compiling in the bif_target() code.
void init_builtin_funcs()
{
ProcStats = zeek::id::find_type<zeek::RecordType>("ProcStats");
NetStats = zeek::id::find_type<zeek::RecordType>("NetStats");
MatcherStats = zeek::id::find_type<zeek::RecordType>("MatcherStats");
ConnStats = zeek::id::find_type<zeek::RecordType>("ConnStats");
ReassemblerStats = zeek::id::find_type<zeek::RecordType>("ReassemblerStats");
DNSStats = zeek::id::find_type<zeek::RecordType>("DNSStats");
GapStats = zeek::id::find_type<zeek::RecordType>("GapStats");
EventStats = zeek::id::find_type<zeek::RecordType>("EventStats");
TimerStats = zeek::id::find_type<zeek::RecordType>("TimerStats");
FileAnalysisStats = zeek::id::find_type<zeek::RecordType>("FileAnalysisStats");
ThreadStats = zeek::id::find_type<zeek::RecordType>("ThreadStats");
BrokerStats = zeek::id::find_type<zeek::RecordType>("BrokerStats");
ReporterStats = zeek::id::find_type<zeek::RecordType>("ReporterStats");
var_sizes = zeek::id::find_type("var_sizes")->AsTableType();
#include "zeek.bif.func_init"
#include "stats.bif.func_init"
#include "reporter.bif.func_init"
#include "strings.bif.func_init"
#include "option.bif.func_init"
#include "supervisor.bif.func_init"
zeek::detail::did_builtin_init = true;
}
void init_builtin_funcs_subdirs()
{
#include "__all__.bif.init.cc" // Autogenerated for compiling in the bif_target() code.
}

View file

@ -17,14 +17,19 @@
#include "ZeekArgs.h" #include "ZeekArgs.h"
#include "BifReturnVal.h" #include "BifReturnVal.h"
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail);
class Frame; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
class Scope;
ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(CallExpr, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(FuncType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
namespace zeek::detail {
using ScopePtr = zeek::IntrusivePtr<detail::Scope>;
using IDPtr = zeek::IntrusivePtr<ID>;
using StmtPtr = zeek::IntrusivePtr<Stmt>;
}
namespace caf { namespace caf {
template <class> class expected; template <class> class expected;
@ -36,11 +41,18 @@ using vector = std::vector<data>;
using caf::expected; using caf::expected;
} }
class Func : public BroObj { namespace zeek {
public:
static inline const IntrusivePtr<Func> nil;
enum Kind { BRO_FUNC, BUILTIN_FUNC }; class Func;
using FuncPtr = zeek::IntrusivePtr<Func>;
class Func : public Obj {
public:
static inline const FuncPtr nil;
enum Kind { SCRIPT_FUNC, BUILTIN_FUNC };
static constexpr auto BRO_FUNC [[deprecated("Remove in v4.1. Use Func::SCRIPT_FUNC instead.")]] = SCRIPT_FUNC;
explicit Func(Kind arg_kind); explicit Func(Kind arg_kind);
@ -50,7 +62,7 @@ public:
zeek::FunctionFlavor Flavor() const { return GetType()->Flavor(); } zeek::FunctionFlavor Flavor() const { return GetType()->Flavor(); }
struct Body { struct Body {
IntrusivePtr<zeek::detail::Stmt> stmts; zeek::detail::StmtPtr stmts;
int priority; int priority;
bool operator<(const Body& other) const bool operator<(const Body& other) const
{ return priority > other.priority; } // reverse sort { return priority > other.priority; } // reverse sort
@ -60,7 +72,7 @@ public:
bool HasBodies() const { return bodies.size(); } bool HasBodies() const { return bodies.size(); }
[[deprecated("Remove in v4.1. Use Invoke() instead.")]] [[deprecated("Remove in v4.1. Use Invoke() instead.")]]
Val* Call(val_list* args, Frame* parent = nullptr) const; zeek::Val* Call(val_list* args, zeek::detail::Frame* parent = nullptr) const;
/** /**
* Calls a Zeek function. * Calls a Zeek function.
@ -68,17 +80,16 @@ public:
* @param parent the frame from which the function is being called. * @param parent the frame from which the function is being called.
* @return the return value of the function call. * @return the return value of the function call.
*/ */
virtual IntrusivePtr<Val> Invoke(zeek::Args* args, virtual zeek::ValPtr Invoke(
Frame* parent = nullptr) const = 0; zeek::Args* args, zeek::detail::Frame* parent = nullptr) const = 0;
/** /**
* A version of Invoke() taking a variable number of individual arguments. * A version of Invoke() taking a variable number of individual arguments.
*/ */
template <class... Args> template <class... Args>
std::enable_if_t< std::enable_if_t<
std::is_convertible_v<std::tuple_element_t<0, std::tuple<Args...>>, std::is_convertible_v<std::tuple_element_t<0, std::tuple<Args...>>, zeek::ValPtr>,
IntrusivePtr<Val>>, zeek::ValPtr>
IntrusivePtr<Val>>
Invoke(Args&&... args) const Invoke(Args&&... args) const
{ {
auto zargs = zeek::Args{std::forward<Args>(args)...}; auto zargs = zeek::Args{std::forward<Args>(args)...};
@ -86,17 +97,17 @@ public:
} }
// Add a new event handler to an existing function (event). // Add a new event handler to an existing function (event).
virtual void AddBody(IntrusivePtr<zeek::detail::Stmt> new_body, virtual void AddBody(zeek::detail::StmtPtr new_body,
const std::vector<IntrusivePtr<zeek::detail::ID>>& new_inits, const std::vector<zeek::detail::IDPtr>& new_inits,
size_t new_frame_size, int priority = 0); size_t new_frame_size, int priority = 0);
virtual void SetScope(IntrusivePtr<Scope> newscope); virtual void SetScope(zeek::detail::ScopePtr newscope);
virtual Scope* GetScope() const { return scope.get(); } virtual zeek::detail::Scope* GetScope() const { return scope.get(); }
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
virtual zeek::FuncType* FType() const { return type.get(); } virtual zeek::FuncType* FType() const { return type.get(); }
const IntrusivePtr<zeek::FuncType>& GetType() const const zeek::FuncTypePtr& GetType() const
{ return type; } { return type; }
Kind GetKind() const { return kind; } Kind GetKind() const { return kind; }
@ -107,12 +118,12 @@ public:
void Describe(ODesc* d) const override = 0; void Describe(ODesc* d) const override = 0;
virtual void DescribeDebug(ODesc* d, const zeek::Args* args) const; virtual void DescribeDebug(ODesc* d, const zeek::Args* args) const;
virtual IntrusivePtr<Func> DoClone(); virtual FuncPtr DoClone();
virtual TraversalCode Traverse(TraversalCallback* cb) const; virtual TraversalCode Traverse(TraversalCallback* cb) const;
uint32_t GetUniqueFuncID() const { return unique_id; } uint32_t GetUniqueFuncID() const { return unique_id; }
static const IntrusivePtr<Func>& GetFuncPtrByID(uint32_t id) static const FuncPtr& GetFuncPtrByID(uint32_t id)
{ return id >= unique_ids.size() ? Func::nil : unique_ids[id]; } { return id >= unique_ids.size() ? Func::nil : unique_ids[id]; }
protected: protected:
@ -122,38 +133,39 @@ protected:
void CopyStateInto(Func* other) const; void CopyStateInto(Func* other) const;
// Helper function for checking result of plugin hook. // Helper function for checking result of plugin hook.
void CheckPluginResult(bool handled, const IntrusivePtr<Val>& hook_result, void CheckPluginResult(bool handled, const zeek::ValPtr& hook_result,
zeek::FunctionFlavor flavor) const; zeek::FunctionFlavor flavor) const;
std::vector<Body> bodies; std::vector<Body> bodies;
IntrusivePtr<Scope> scope; zeek::detail::ScopePtr scope;
Kind kind; Kind kind;
uint32_t unique_id; uint32_t unique_id;
IntrusivePtr<zeek::FuncType> type; zeek::FuncTypePtr type;
std::string name; std::string name;
static inline std::vector<IntrusivePtr<Func>> unique_ids; static inline std::vector<FuncPtr> unique_ids;
}; };
namespace detail {
class BroFunc final : public Func { class ScriptFunc final : public zeek::Func {
public: public:
BroFunc(const IntrusivePtr<zeek::detail::ID>& id, IntrusivePtr<zeek::detail::Stmt> body, ScriptFunc(const zeek::detail::IDPtr& id, zeek::detail::StmtPtr body,
const std::vector<IntrusivePtr<zeek::detail::ID>>& inits, const std::vector<zeek::detail::IDPtr>& inits,
size_t frame_size, int priority); size_t frame_size, int priority);
~BroFunc() override; ~ScriptFunc() override;
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Invoke(zeek::Args* args, Frame* parent) const override; zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override;
/** /**
* Adds adds a closure to the function. Closures are cloned and * Adds adds a closure to the function. Closures are cloned and
* future calls to BroFunc methods will not modify *f*. * future calls to ScriptFunc methods will not modify *f*.
* *
* @param ids IDs that are captured by the closure. * @param ids IDs that are captured by the closure.
* @param f the closure to be captured. * @param f the closure to be captured.
*/ */
void AddClosure(id_list ids, Frame* f); void AddClosure(id_list ids, zeek::detail::Frame* f);
/** /**
* Replaces the current closure with one built from *data* * Replaces the current closure with one built from *data*
@ -166,7 +178,7 @@ public:
* If the function's closure is a weak reference to the given frame, * If the function's closure is a weak reference to the given frame,
* upgrade to a strong reference of a shallow clone of that frame. * upgrade to a strong reference of a shallow clone of that frame.
*/ */
bool StrengthenClosureReference(Frame* f); bool StrengthenClosureReference(zeek::detail::Frame* f);
/** /**
* Serializes this function's closure. * Serializes this function's closure.
@ -175,8 +187,8 @@ public:
*/ */
broker::expected<broker::data> SerializeClosure() const; broker::expected<broker::data> SerializeClosure() const;
void AddBody(IntrusivePtr<zeek::detail::Stmt> new_body, void AddBody(zeek::detail::StmtPtr new_body,
const std::vector<IntrusivePtr<zeek::detail::ID>>& new_inits, const std::vector<zeek::detail::IDPtr>& new_inits,
size_t new_frame_size, int priority) override; size_t new_frame_size, int priority) override;
/** Sets this function's outer_id list. */ /** Sets this function's outer_id list. */
@ -186,15 +198,15 @@ public:
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
protected: protected:
BroFunc() : Func(BRO_FUNC) {} ScriptFunc() : zeek::Func(SCRIPT_FUNC) {}
IntrusivePtr<zeek::detail::Stmt> AddInits( zeek::detail::StmtPtr AddInits(
IntrusivePtr<zeek::detail::Stmt> body, zeek::detail::StmtPtr body,
const std::vector<IntrusivePtr<zeek::detail::ID>>& inits); const std::vector<zeek::detail::IDPtr>& inits);
/** /**
* Clones this function along with its closures. * Clones this function along with its closures.
*/ */
IntrusivePtr<Func> DoClone() override; zeek::FuncPtr DoClone() override;
/** /**
* Performs a selective clone of *f* using the IDs that were * Performs a selective clone of *f* using the IDs that were
@ -202,27 +214,27 @@ protected:
* *
* @param f the frame to be cloned. * @param f the frame to be cloned.
*/ */
void SetClosureFrame(Frame* f); void SetClosureFrame(zeek::detail::Frame* f);
private: private:
size_t frame_size; size_t frame_size;
// List of the outer IDs used in the function. // List of the outer IDs used in the function.
id_list outer_ids; id_list outer_ids;
// The frame the BroFunc was initialized in. // The frame the ScriptFunc was initialized in.
Frame* closure = nullptr; zeek::detail::Frame* closure = nullptr;
bool weak_closure_ref = false; bool weak_closure_ref = false;
}; };
using built_in_func = BifReturnVal (*)(Frame* frame, const zeek::Args* args); using built_in_func = BifReturnVal (*)(zeek::detail::Frame* frame, const zeek::Args* args);
class BuiltinFunc final : public Func { class BuiltinFunc final : public zeek::Func {
public: public:
BuiltinFunc(built_in_func func, const char* name, bool is_pure); BuiltinFunc(built_in_func func, const char* name, bool is_pure);
~BuiltinFunc() override; ~BuiltinFunc() override;
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Invoke(zeek::Args* args, Frame* parent) const override; zeek::ValPtr Invoke(zeek::Args* args, zeek::detail::Frame* parent) const override;
built_in_func TheFunc() const { return func; } built_in_func TheFunc() const { return func; }
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -234,13 +246,6 @@ protected:
bool is_pure; bool is_pure;
}; };
extern void builtin_error(const char* msg);
extern void builtin_error(const char* msg, IntrusivePtr<Val>);
extern void builtin_error(const char* msg, BroObj* arg);
extern void init_builtin_funcs();
extern void init_builtin_funcs_subdirs();
extern bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call); extern bool check_built_in_call(BuiltinFunc* f, zeek::detail::CallExpr* call);
struct CallInfo { struct CallInfo {
@ -249,25 +254,59 @@ struct CallInfo {
const zeek::Args& args; const zeek::Args& args;
}; };
// Struct that collects all the specifics defining a Func. Used for BroFuncs // Struct that collects all the specifics defining a Func. Used for ScriptFuncs
// with closures. // with closures.
struct function_ingredients { struct function_ingredients {
// Gathers all of the information from a scope and a function body needed // Gathers all of the information from a scope and a function body needed
// to build a function. // to build a function.
function_ingredients(IntrusivePtr<Scope> scope, IntrusivePtr<zeek::detail::Stmt> body); function_ingredients(ScopePtr scope, StmtPtr body);
IntrusivePtr<zeek::detail::ID> id; IDPtr id;
IntrusivePtr<zeek::detail::Stmt> body; StmtPtr body;
std::vector<IntrusivePtr<zeek::detail::ID>> inits; std::vector<IDPtr> inits;
int frame_size; int frame_size;
int priority; int priority;
IntrusivePtr<Scope> scope; ScopePtr scope;
}; };
extern std::vector<CallInfo> call_stack; extern std::vector<CallInfo> call_stack;
extern std::string render_call_stack();
// This is set to true after the built-in functions have been initialized. // This is set to true after the built-in functions have been initialized.
extern bool did_builtin_init; extern bool did_builtin_init;
} // namespace detail
extern std::string render_call_stack();
// These methods are used by BIFs, so they're in the public namespace.
extern void emit_builtin_error(const char* msg);
extern void emit_builtin_error(const char* msg, zeek::ValPtr);
extern void emit_builtin_error(const char* msg, Obj* arg);
} // namespace zeek
using Func [[deprecated("Remove in v4.1. Use zeek::Func.")]] = zeek::Func;
using BroFunc [[deprecated("Remove in v4.1. Use zeek::detail::ScriptFunc.")]] = zeek::detail::ScriptFunc;
using BuiltinFunc [[deprecated("Remove in v4.1. Use zeek::detail::BuiltinFunc.")]] = zeek::detail::BuiltinFunc;
using CallInfo [[deprecated("Remove in v4.1. Use zeek::detail::CallInfo.")]] = zeek::detail::CallInfo;
using function_ingredients [[deprecated("Remove in v4.1. Use zeek::detail::function_ingredients.")]] = zeek::detail::function_ingredients;
constexpr auto check_built_in_call [[deprecated("Remove in v4.1. Use zeek::detail::check_built_in_call.")]] = zeek::detail::check_built_in_call;
constexpr auto render_call_stack [[deprecated("Remove in v4.1. Use zeek::render_call_stack.")]] = zeek::render_call_stack;
// TODO: these are still here because of how all of the bif code gets included in Func.c. There could be a
// renamed version inside the namespace, but the way that the code gets included complicates the matter. It
// might need to be revisited after everything is namespaced everywhere else.
void init_builtin_funcs();
void init_builtin_funcs_subdirs();
// TODO: do call_stack and did_builtin_init need to be aliased?
// These have to be implemented as actual methods due to function overloading breaking the use of aliases.
[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]]
extern void builtin_error(const char* msg);
[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]]
extern void builtin_error(const char* msg, zeek::ValPtr);
[[deprecated("Remove in v4.1. Use zeek::emit_builtin_error.")]]
extern void builtin_error(const char* msg, zeek::Obj* arg);

View file

@ -5,7 +5,7 @@
#include "Hash.h" #include "Hash.h"
#include "digest.h" #include "digest.h"
#include "Reporter.h" #include "Reporter.h"
#include "BroString.h" #include "ZeekString.h"
#include "Val.h" // needed for const.bif #include "Val.h" // needed for const.bif
#include "const.bif.netvar_h" #include "const.bif.netvar_h"
@ -145,7 +145,7 @@ HashKey::HashKey(const char* s)
hash = HashBytes(key, size); hash = HashBytes(key, size);
} }
HashKey::HashKey(const BroString* s) HashKey::HashKey(const zeek::String* s)
{ {
size = s->Len(); size = s->Len();
key = (void*) s->Bytes(); key = (void*) s->Bytes();

View file

@ -23,15 +23,17 @@
#include <stdlib.h> #include <stdlib.h>
class BroString;
// to allow bro_md5_hmac access to the hmac seed // to allow bro_md5_hmac access to the hmac seed
#include "ZeekArgs.h" #include "ZeekArgs.h"
class Val;
class Frame; ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
namespace zeek { class String; }
using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String;
class BifReturnVal; class BifReturnVal;
namespace zeek::BifFunc { namespace zeek::BifFunc {
extern BifReturnVal md5_hmac_bif(Frame* frame, const zeek::Args*); extern BifReturnVal md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*);
} }
typedef uint64_t hash_t; typedef uint64_t hash_t;
@ -196,7 +198,7 @@ private:
inline static bool seeds_initialized = false; inline static bool seeds_initialized = false;
friend void hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]); friend void hmac_md5(size_t size, const unsigned char* bytes, unsigned char digest[16]);
friend BifReturnVal zeek::BifFunc::md5_hmac_bif(Frame* frame, const zeek::Args*); friend BifReturnVal zeek::BifFunc::md5_hmac_bif(zeek::detail::Frame* frame, const zeek::Args*);
}; };
typedef enum { typedef enum {
@ -215,7 +217,7 @@ public:
explicit HashKey(double d); explicit HashKey(double d);
explicit HashKey(const void* p); explicit HashKey(const void* p);
explicit HashKey(const char* s); explicit HashKey(const char* s);
explicit HashKey(const BroString* s); explicit HashKey(const zeek::String* s);
~HashKey() ~HashKey()
{ {
if ( is_our_dynamic ) if ( is_our_dynamic )

View file

@ -1,3 +1,4 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
#include "zeek-config.h" #include "zeek-config.h"
@ -19,26 +20,26 @@
#include "zeekygen/ScriptInfo.h" #include "zeekygen/ScriptInfo.h"
#include "module_util.h" #include "module_util.h"
IntrusivePtr<zeek::RecordType> zeek::id::conn_id; zeek::RecordTypePtr zeek::id::conn_id;
IntrusivePtr<zeek::RecordType> zeek::id::endpoint; zeek::RecordTypePtr zeek::id::endpoint;
IntrusivePtr<zeek::RecordType> zeek::id::connection; zeek::RecordTypePtr zeek::id::connection;
IntrusivePtr<zeek::RecordType> zeek::id::fa_file; zeek::RecordTypePtr zeek::id::fa_file;
IntrusivePtr<zeek::RecordType> zeek::id::fa_metadata; zeek::RecordTypePtr zeek::id::fa_metadata;
IntrusivePtr<zeek::EnumType> zeek::id::transport_proto; zeek::EnumTypePtr zeek::id::transport_proto;
IntrusivePtr<zeek::TableType> zeek::id::string_set; zeek::TableTypePtr zeek::id::string_set;
IntrusivePtr<zeek::TableType> zeek::id::string_array; zeek::TableTypePtr zeek::id::string_array;
IntrusivePtr<zeek::TableType> zeek::id::count_set; zeek::TableTypePtr zeek::id::count_set;
IntrusivePtr<zeek::VectorType> zeek::id::string_vec; zeek::VectorTypePtr zeek::id::string_vec;
IntrusivePtr<zeek::VectorType> zeek::id::index_vec; zeek::VectorTypePtr zeek::id::index_vec;
const IntrusivePtr<zeek::detail::ID>& zeek::id::find(std::string_view name) const zeek::detail::IDPtr& zeek::id::find(std::string_view name)
{ {
return global_scope()->Find(name); return zeek::detail::global_scope()->Find(name);
} }
const IntrusivePtr<zeek::Type>& zeek::id::find_type(std::string_view name) const zeek::TypePtr& zeek::id::find_type(std::string_view name)
{ {
auto id = global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
reporter->InternalError("Failed to find type named: %s", reporter->InternalError("Failed to find type named: %s",
@ -47,9 +48,9 @@ const IntrusivePtr<zeek::Type>& zeek::id::find_type(std::string_view name)
return id->GetType(); return id->GetType();
} }
const IntrusivePtr<Val>& zeek::id::find_val(std::string_view name) const zeek::ValPtr& zeek::id::find_val(std::string_view name)
{ {
auto id = global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
reporter->InternalError("Failed to find variable named: %s", reporter->InternalError("Failed to find variable named: %s",
@ -58,9 +59,9 @@ const IntrusivePtr<Val>& zeek::id::find_val(std::string_view name)
return id->GetVal(); return id->GetVal();
} }
const IntrusivePtr<Val>& zeek::id::find_const(std::string_view name) const zeek::ValPtr& zeek::id::find_const(std::string_view name)
{ {
auto id = global_scope()->Find(name); auto id = zeek::detail::global_scope()->Find(name);
if ( ! id ) if ( ! id )
reporter->InternalError("Failed to find variable named: %s", reporter->InternalError("Failed to find variable named: %s",
@ -73,7 +74,7 @@ const IntrusivePtr<Val>& zeek::id::find_const(std::string_view name)
return id->GetVal(); return id->GetVal();
} }
IntrusivePtr<Func> zeek::id::find_func(std::string_view name) zeek::FuncPtr zeek::id::find_func(std::string_view name)
{ {
const auto& v = zeek::id::find_val(name); const auto& v = zeek::id::find_val(name);
@ -130,7 +131,7 @@ std::string ID::ModuleName() const
return extract_module_name(name); return extract_module_name(name);
} }
void ID::SetType(IntrusivePtr<zeek::Type> t) void ID::SetType(zeek::TypePtr t)
{ {
type = std::move(t); type = std::move(t);
} }
@ -140,7 +141,7 @@ void ID::ClearVal()
val = nullptr; val = nullptr;
} }
void ID::SetVal(IntrusivePtr<Val> v) void ID::SetVal(zeek::ValPtr v)
{ {
val = std::move(v); val = std::move(v);
Modified(); Modified();
@ -169,7 +170,7 @@ void ID::SetVal(IntrusivePtr<Val> v)
} }
} }
void ID::SetVal(IntrusivePtr<Val> v, InitClass c) void ID::SetVal(zeek::ValPtr v, InitClass c)
{ {
if ( c == INIT_NONE || c == INIT_FULL ) if ( c == INIT_NONE || c == INIT_FULL )
{ {
@ -207,7 +208,7 @@ void ID::SetVal(IntrusivePtr<Val> v, InitClass c)
} }
} }
void ID::SetVal(IntrusivePtr<Expr> ev, InitClass c) void ID::SetVal(ExprPtr ev, InitClass c)
{ {
const auto& a = attrs->Find(c == INIT_EXTRA ? ATTR_ADD_FUNC : ATTR_DEL_FUNC); const auto& a = attrs->Find(c == INIT_EXTRA ? ATTR_ADD_FUNC : ATTR_DEL_FUNC);
@ -222,7 +223,7 @@ bool ID::IsRedefinable() const
return GetAttr(ATTR_REDEF) != nullptr; return GetAttr(ATTR_REDEF) != nullptr;
} }
void ID::SetAttrs(IntrusivePtr<Attributes> a) void ID::SetAttrs(AttributesPtr a)
{ {
attrs = nullptr; attrs = nullptr;
AddAttrs(std::move(a)); AddAttrs(std::move(a));
@ -260,15 +261,15 @@ void ID::UpdateValAttrs()
TypeDecl* fd = rt->FieldDecl(i); TypeDecl* fd = rt->FieldDecl(i);
if ( ! fd->attrs ) if ( ! fd->attrs )
fd->attrs = make_intrusive<Attributes>(rt->GetFieldType(i), true, IsGlobal()); fd->attrs = zeek::make_intrusive<Attributes>(rt->GetFieldType(i), true, IsGlobal());
fd->attrs->AddAttr(make_intrusive<Attr>(ATTR_LOG)); fd->attrs->AddAttr(zeek::make_intrusive<Attr>(ATTR_LOG));
} }
} }
} }
} }
const IntrusivePtr<Attr>& ID::GetAttr(AttrTag t) const const AttrPtr& ID::GetAttr(AttrTag t) const
{ {
return attrs ? attrs->Find(t) : Attr::nil; return attrs ? attrs->Find(t) : Attr::nil;
} }
@ -278,13 +279,13 @@ bool ID::IsDeprecated() const
return GetAttr(ATTR_DEPRECATED) != nullptr; return GetAttr(ATTR_DEPRECATED) != nullptr;
} }
void ID::MakeDeprecated(IntrusivePtr<Expr> deprecation) void ID::MakeDeprecated(ExprPtr deprecation)
{ {
if ( IsDeprecated() ) if ( IsDeprecated() )
return; return;
std::vector<IntrusivePtr<Attr>> attrv{make_intrusive<Attr>(ATTR_DEPRECATED, std::move(deprecation))}; std::vector<AttrPtr> attrv{zeek::make_intrusive<Attr>(ATTR_DEPRECATED, std::move(deprecation))};
AddAttrs(make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal())); AddAttrs(zeek::make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal()));
} }
std::string ID::GetDeprecationWarning() const std::string ID::GetDeprecationWarning() const
@ -308,7 +309,7 @@ std::string ID::GetDeprecationWarning() const
return fmt("deprecated (%s): %s", Name(), result.c_str()); return fmt("deprecated (%s): %s", Name(), result.c_str());
} }
void ID::AddAttrs(IntrusivePtr<Attributes> a) void ID::AddAttrs(AttributesPtr a)
{ {
if ( attrs ) if ( attrs )
attrs->AddAttrs(a); attrs->AddAttrs(a);
@ -334,18 +335,18 @@ void ID::SetOption()
// option implied redefinable // option implied redefinable
if ( ! IsRedefinable() ) if ( ! IsRedefinable() )
{ {
std::vector<IntrusivePtr<Attr>> attrv{make_intrusive<Attr>(ATTR_REDEF)}; std::vector<AttrPtr> attrv{zeek::make_intrusive<Attr>(ATTR_REDEF)};
AddAttrs(make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal())); AddAttrs(zeek::make_intrusive<Attributes>(std::move(attrv), GetType(), false, IsGlobal()));
} }
} }
void ID::EvalFunc(IntrusivePtr<Expr> ef, IntrusivePtr<Expr> ev) void ID::EvalFunc(ExprPtr ef, ExprPtr ev)
{ {
auto arg1 = make_intrusive<zeek::detail::ConstExpr>(val); auto arg1 = zeek::make_intrusive<zeek::detail::ConstExpr>(val);
auto args = make_intrusive<zeek::detail::ListExpr>(); auto args = zeek::make_intrusive<zeek::detail::ListExpr>();
args->Append(std::move(arg1)); args->Append(std::move(arg1));
args->Append(std::move(ev)); args->Append(std::move(ev));
auto ce = make_intrusive<CallExpr>(std::move(ef), std::move(args)); auto ce = zeek::make_intrusive<CallExpr>(std::move(ef), std::move(args));
SetVal(ce->Eval(nullptr)); SetVal(ce->Eval(nullptr));
} }
@ -365,7 +366,7 @@ TraversalCode ID::Traverse(TraversalCallback* cb) const
// FIXME: Perhaps we should be checking at other than global scope. // FIXME: Perhaps we should be checking at other than global scope.
else if ( val && IsFunc(val->GetType()->Tag()) && else if ( val && IsFunc(val->GetType()->Tag()) &&
cb->current_scope == global_scope() ) cb->current_scope == zeek::detail::global_scope() )
{ {
tc = val->AsFunc()->Traverse(cb); tc = val->AsFunc()->Traverse(cb);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
@ -384,9 +385,9 @@ TraversalCode ID::Traverse(TraversalCallback* cb) const
HANDLE_TC_EXPR_POST(tc); HANDLE_TC_EXPR_POST(tc);
} }
void ID::Error(const char* msg, const BroObj* o2) void ID::Error(const char* msg, const Obj* o2)
{ {
BroObj::Error(msg, o2, true); Obj::Error(msg, o2, true);
SetType(error_type()); SetType(error_type());
} }
@ -642,7 +643,7 @@ void ID::UpdateValID()
} }
#endif #endif
void ID::AddOptionHandler(IntrusivePtr<Func> callback, int priority) void ID::AddOptionHandler(zeek::FuncPtr callback, int priority)
{ {
option_handlers.emplace(priority, std::move(callback)); option_handlers.emplace(priority, std::move(callback));
} }

117
src/ID.h
View file

@ -13,28 +13,41 @@
#include <string_view> #include <string_view>
#include <vector> #include <vector>
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
class Func; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace zeek { class Type; }
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(RecordType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(TableType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(TableType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(VectorType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(VectorType, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek);
namespace zeek {
class Type;
using TypePtr = zeek::IntrusivePtr<zeek::Type>;
using RecordTypePtr = zeek::IntrusivePtr<zeek::RecordType>;
using TableTypePtr = zeek::IntrusivePtr<zeek::TableType>;
using VectorTypePtr = zeek::IntrusivePtr<zeek::VectorType>;
using EnumTypePtr = zeek::IntrusivePtr<zeek::EnumType>;
using ValPtr = zeek::IntrusivePtr<zeek::Val>;
using FuncPtr = zeek::IntrusivePtr<zeek::Func>;
}
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
namespace zeek::detail { namespace zeek::detail {
class Attributes; class Attributes;
class Expr; class Expr;
using ExprPtr = zeek::IntrusivePtr<Expr>;
enum InitClass { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, }; enum InitClass { INIT_NONE, INIT_FULL, INIT_EXTRA, INIT_REMOVE, };
enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL }; enum IDScope { SCOPE_FUNCTION, SCOPE_MODULE, SCOPE_GLOBAL };
class ID final : public BroObj, public notifier::Modifiable { class ID;
using IDPtr = zeek::IntrusivePtr<ID>;
class ID final : public Obj, public notifier::Modifiable {
public: public:
static inline const IntrusivePtr<ID> nil; static inline const IDPtr nil;
ID(const char* name, IDScope arg_scope, bool arg_is_export); ID(const char* name, IDScope arg_scope, bool arg_is_export);
@ -50,19 +63,19 @@ public:
std::string ModuleName() const; std::string ModuleName() const;
void SetType(IntrusivePtr<Type> t); void SetType(TypePtr t);
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
zeek::Type* Type() { return type.get(); } zeek::Type* Type() { return type.get(); }
[[deprecated("Remove in v4.1. Use GetType().")]] [[deprecated("Remove in v4.1. Use GetType().")]]
const zeek::Type* Type() const { return type.get(); } const zeek::Type* Type() const { return type.get(); }
const IntrusivePtr<zeek::Type>& GetType() const const TypePtr& GetType() const
{ return type; } { return type; }
template <class T> template <class T>
IntrusivePtr<T> GetType() const zeek::IntrusivePtr<T> GetType() const
{ return cast_intrusive<T>(type); } { return zeek::cast_intrusive<T>(type); }
[[deprecated("Remove in v4.1. Use IsType() and GetType().")]] [[deprecated("Remove in v4.1. Use IsType() and GetType().")]]
zeek::Type* AsType() { return is_type ? GetType().get() : nullptr; } zeek::Type* AsType() { return is_type ? GetType().get() : nullptr; }
@ -74,10 +87,10 @@ public:
void MakeType() { is_type = true; } void MakeType() { is_type = true; }
void SetVal(IntrusivePtr<Val> v); void SetVal(ValPtr v);
void SetVal(IntrusivePtr<Val> v, InitClass c); void SetVal(ValPtr v, InitClass c);
void SetVal(IntrusivePtr<Expr> ev, InitClass c); void SetVal(ExprPtr ev, InitClass c);
bool HasVal() const { return val != nullptr; } bool HasVal() const { return val != nullptr; }
@ -86,7 +99,7 @@ public:
[[deprecated("Remove in v4.1. Use GetVal().")]] [[deprecated("Remove in v4.1. Use GetVal().")]]
const Val* ID_Val() const { return val.get(); } const Val* ID_Val() const { return val.get(); }
const IntrusivePtr<Val>& GetVal() const const ValPtr& GetVal() const
{ return val; } { return val; }
void ClearVal(); void ClearVal();
@ -105,26 +118,26 @@ public:
bool IsRedefinable() const; bool IsRedefinable() const;
void SetAttrs(IntrusivePtr<Attributes> attr); void SetAttrs(AttributesPtr attr);
void AddAttrs(IntrusivePtr<Attributes> attr); void AddAttrs(AttributesPtr attr);
void RemoveAttr(zeek::detail::AttrTag a); void RemoveAttr(AttrTag a);
void UpdateValAttrs(); void UpdateValAttrs();
const IntrusivePtr<Attributes>& GetAttrs() const const AttributesPtr& GetAttrs() const
{ return attrs; } { return attrs; }
[[deprecated("Remove in 4.1. Use GetAttrs().")]] [[deprecated("Remove in 4.1. Use GetAttrs().")]]
Attributes* Attrs() const { return attrs.get(); } Attributes* Attrs() const { return attrs.get(); }
const IntrusivePtr<zeek::detail::Attr>& GetAttr(zeek::detail::AttrTag t) const; const AttrPtr& GetAttr(zeek::detail::AttrTag t) const;
bool IsDeprecated() const; bool IsDeprecated() const;
void MakeDeprecated(IntrusivePtr<Expr> deprecation); void MakeDeprecated(ExprPtr deprecation);
std::string GetDeprecationWarning() const; std::string GetDeprecationWarning() const;
void Error(const char* msg, const BroObj* o2 = nullptr); void Error(const char* msg, const Obj* o2 = nullptr);
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
// Adds type and value to description. // Adds type and value to description.
@ -143,11 +156,11 @@ public:
bool HasOptionHandlers() const bool HasOptionHandlers() const
{ return !option_handlers.empty(); } { return !option_handlers.empty(); }
void AddOptionHandler(IntrusivePtr<Func> callback, int priority); void AddOptionHandler(zeek::FuncPtr callback, int priority);
std::vector<Func*> GetOptionHandlers() const; std::vector<Func*> GetOptionHandlers() const;
protected: protected:
void EvalFunc(IntrusivePtr<Expr> ef, IntrusivePtr<Expr> ev); void EvalFunc(ExprPtr ef, ExprPtr ev);
#ifdef DEBUG #ifdef DEBUG
void UpdateValID(); void UpdateValID();
@ -157,13 +170,13 @@ protected:
IDScope scope; IDScope scope;
bool is_export; bool is_export;
bool infer_return_type; bool infer_return_type;
IntrusivePtr<zeek::Type> type; TypePtr type;
bool is_const, is_enum_const, is_type, is_option; bool is_const, is_enum_const, is_type, is_option;
int offset; int offset;
IntrusivePtr<Val> val; ValPtr val;
IntrusivePtr<Attributes> attrs; AttributesPtr attrs;
// contains list of functions that are called when an option changes // contains list of functions that are called when an option changes
std::multimap<int, IntrusivePtr<Func>> option_handlers; std::multimap<int, zeek::FuncPtr> option_handlers;
}; };
@ -179,7 +192,7 @@ namespace zeek::id {
* @return The identifier, which may reference a nil object if no such * @return The identifier, which may reference a nil object if no such
* name exists. * name exists.
*/ */
const IntrusivePtr<zeek::detail::ID>& find(std::string_view name); const detail::IDPtr& find(std::string_view name);
/** /**
* Lookup an ID by its name and return its type. A fatal occurs if the ID * Lookup an ID by its name and return its type. A fatal occurs if the ID
@ -187,7 +200,7 @@ const IntrusivePtr<zeek::detail::ID>& find(std::string_view name);
* @param name The identifier name to lookup * @param name The identifier name to lookup
* @return The type of the identifier. * @return The type of the identifier.
*/ */
const IntrusivePtr<zeek::Type>& find_type(std::string_view name); const TypePtr& find_type(std::string_view name);
/** /**
* Lookup an ID by its name and return its type (as cast to @c T). * Lookup an ID by its name and return its type (as cast to @c T).
@ -196,8 +209,8 @@ const IntrusivePtr<zeek::Type>& find_type(std::string_view name);
* @return The type of the identifier. * @return The type of the identifier.
*/ */
template<class T> template<class T>
IntrusivePtr<T> find_type(std::string_view name) zeek::IntrusivePtr<T> find_type(std::string_view name)
{ return cast_intrusive<T>(find_type(name)); } { return zeek::cast_intrusive<T>(find_type(name)); }
/** /**
* Lookup an ID by its name and return its value. A fatal occurs if the ID * Lookup an ID by its name and return its value. A fatal occurs if the ID
@ -205,7 +218,7 @@ IntrusivePtr<T> find_type(std::string_view name)
* @param name The identifier name to lookup * @param name The identifier name to lookup
* @return The current value of the identifier * @return The current value of the identifier
*/ */
const IntrusivePtr<Val>& find_val(std::string_view name); const ValPtr& find_val(std::string_view name);
/** /**
* Lookup an ID by its name and return its value (as cast to @c T). * Lookup an ID by its name and return its value (as cast to @c T).
@ -214,8 +227,8 @@ const IntrusivePtr<Val>& find_val(std::string_view name);
* @return The current value of the identifier. * @return The current value of the identifier.
*/ */
template<class T> template<class T>
IntrusivePtr<T> find_val(std::string_view name) zeek::IntrusivePtr<T> find_val(std::string_view name)
{ return cast_intrusive<T>(find_val(name)); } { return zeek::cast_intrusive<T>(find_val(name)); }
/** /**
* Lookup an ID by its name and return its value. A fatal occurs if the ID * Lookup an ID by its name and return its value. A fatal occurs if the ID
@ -223,7 +236,7 @@ IntrusivePtr<T> find_val(std::string_view name)
* @param name The identifier name to lookup * @param name The identifier name to lookup
* @return The current value of the identifier * @return The current value of the identifier
*/ */
const IntrusivePtr<Val>& find_const(std::string_view name); const ValPtr& find_const(std::string_view name);
/** /**
* Lookup an ID by its name and return its value (as cast to @c T). * Lookup an ID by its name and return its value (as cast to @c T).
@ -232,8 +245,8 @@ const IntrusivePtr<Val>& find_const(std::string_view name);
* @return The current value of the identifier. * @return The current value of the identifier.
*/ */
template<class T> template<class T>
IntrusivePtr<T> find_const(std::string_view name) zeek::IntrusivePtr<T> find_const(std::string_view name)
{ return cast_intrusive<T>(find_const(name)); } { return zeek::cast_intrusive<T>(find_const(name)); }
/** /**
* Lookup an ID by its name and return the function it references. * Lookup an ID by its name and return the function it references.
@ -241,19 +254,19 @@ IntrusivePtr<T> find_const(std::string_view name)
* @param name The identifier name to lookup * @param name The identifier name to lookup
* @return The current function value the identifier references. * @return The current function value the identifier references.
*/ */
IntrusivePtr<Func> find_func(std::string_view name); zeek::FuncPtr find_func(std::string_view name);
extern IntrusivePtr<zeek::RecordType> conn_id; extern RecordTypePtr conn_id;
extern IntrusivePtr<zeek::RecordType> endpoint; extern RecordTypePtr endpoint;
extern IntrusivePtr<zeek::RecordType> connection; extern RecordTypePtr connection;
extern IntrusivePtr<zeek::RecordType> fa_file; extern RecordTypePtr fa_file;
extern IntrusivePtr<zeek::RecordType> fa_metadata; extern RecordTypePtr fa_metadata;
extern IntrusivePtr<zeek::EnumType> transport_proto; extern EnumTypePtr transport_proto;
extern IntrusivePtr<zeek::TableType> string_set; extern TableTypePtr string_set;
extern IntrusivePtr<zeek::TableType> string_array; extern TableTypePtr string_array;
extern IntrusivePtr<zeek::TableType> count_set; extern TableTypePtr count_set;
extern IntrusivePtr<zeek::VectorType> string_vec; extern VectorTypePtr string_vec;
extern IntrusivePtr<zeek::VectorType> index_vec; extern VectorTypePtr index_vec;
namespace detail { namespace detail {
@ -263,6 +276,8 @@ void init();
} // namespace zeek::id } // namespace zeek::id
using ID [[deprecated("Remove in v4.1 Use zeek::detail::ID instead.")]] = zeek::detail::ID;
using init_class [[deprecated("Remove in v4.1. Use zeek::detail::InitClass instead.")]] = zeek::detail::InitClass; using init_class [[deprecated("Remove in v4.1. Use zeek::detail::InitClass instead.")]] = zeek::detail::InitClass;
[[deprecated("Remove in v4.1. Use zeek::detail::INIT_NONE instead.")]] [[deprecated("Remove in v4.1. Use zeek::detail::INIT_NONE instead.")]]
constexpr auto INIT_NONE = zeek::detail::INIT_NONE; constexpr auto INIT_NONE = zeek::detail::INIT_NONE;

266
src/IP.cc
View file

@ -10,25 +10,25 @@
#include "Type.h" #include "Type.h"
#include "Val.h" #include "Val.h"
#include "Var.h" #include "Var.h"
#include "BroString.h" #include "ZeekString.h"
#include "Reporter.h" #include "Reporter.h"
static IntrusivePtr<VectorVal> BuildOptionsVal(const u_char* data, int len) static zeek::VectorValPtr BuildOptionsVal(const u_char* data, int len)
{ {
auto vv = make_intrusive<VectorVal>(zeek::id::find_type<zeek::VectorType>("ip6_options")); auto vv = zeek::make_intrusive<zeek::VectorVal>(zeek::id::find_type<zeek::VectorType>("ip6_options"));
while ( len > 0 ) while ( len > 0 )
{ {
static auto ip6_option_type = zeek::id::find_type<zeek::RecordType>("ip6_option"); static auto ip6_option_type = zeek::id::find_type<zeek::RecordType>("ip6_option");
const struct ip6_opt* opt = (const struct ip6_opt*) data; const struct ip6_opt* opt = (const struct ip6_opt*) data;
auto rv = make_intrusive<RecordVal>(ip6_option_type); auto rv = zeek::make_intrusive<zeek::RecordVal>(ip6_option_type);
rv->Assign(0, val_mgr->Count(opt->ip6o_type)); rv->Assign(0, zeek::val_mgr->Count(opt->ip6o_type));
if ( opt->ip6o_type == 0 ) if ( opt->ip6o_type == 0 )
{ {
// Pad1 option // Pad1 option
rv->Assign(1, val_mgr->Count(0)); rv->Assign(1, zeek::val_mgr->Count(0));
rv->Assign(2, val_mgr->EmptyString()); rv->Assign(2, zeek::val_mgr->EmptyString());
data += sizeof(uint8_t); data += sizeof(uint8_t);
len -= sizeof(uint8_t); len -= sizeof(uint8_t);
} }
@ -36,9 +36,9 @@ static IntrusivePtr<VectorVal> BuildOptionsVal(const u_char* data, int len)
{ {
// PadN or other option // PadN or other option
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(1, val_mgr->Count(opt->ip6o_len)); rv->Assign(1, zeek::val_mgr->Count(opt->ip6o_len));
rv->Assign(2, make_intrusive<StringVal>( rv->Assign(2, zeek::make_intrusive<zeek::StringVal>(
new BroString(data + off, opt->ip6o_len, true))); new zeek::String(data + off, opt->ip6o_len, true)));
data += opt->ip6o_len + off; data += opt->ip6o_len + off;
len -= opt->ip6o_len + off; len -= opt->ip6o_len + off;
} }
@ -49,25 +49,25 @@ static IntrusivePtr<VectorVal> BuildOptionsVal(const u_char* data, int len)
return vv; return vv;
} }
IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const zeek::RecordValPtr IPv6_Hdr::ToVal(zeek::VectorValPtr chain) const
{ {
IntrusivePtr<RecordVal> rv; zeek::RecordValPtr rv;
switch ( type ) { switch ( type ) {
case IPPROTO_IPV6: case IPPROTO_IPV6:
{ {
static auto ip6_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_hdr"); static auto ip6_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_hdr");
rv = make_intrusive<RecordVal>(ip6_hdr_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_hdr_type);
const struct ip6_hdr* ip6 = (const struct ip6_hdr*)data; const struct ip6_hdr* ip6 = (const struct ip6_hdr*)data;
rv->Assign(0, val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20)); rv->Assign(0, zeek::val_mgr->Count((ntohl(ip6->ip6_flow) & 0x0ff00000)>>20));
rv->Assign(1, val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff)); rv->Assign(1, zeek::val_mgr->Count(ntohl(ip6->ip6_flow) & 0x000fffff));
rv->Assign(2, val_mgr->Count(ntohs(ip6->ip6_plen))); rv->Assign(2, zeek::val_mgr->Count(ntohs(ip6->ip6_plen)));
rv->Assign(3, val_mgr->Count(ip6->ip6_nxt)); rv->Assign(3, zeek::val_mgr->Count(ip6->ip6_nxt));
rv->Assign(4, val_mgr->Count(ip6->ip6_hlim)); rv->Assign(4, zeek::val_mgr->Count(ip6->ip6_hlim));
rv->Assign(5, make_intrusive<AddrVal>(IPAddr(ip6->ip6_src))); rv->Assign(5, zeek::make_intrusive<zeek::AddrVal>(IPAddr(ip6->ip6_src)));
rv->Assign(6, make_intrusive<AddrVal>(IPAddr(ip6->ip6_dst))); rv->Assign(6, zeek::make_intrusive<zeek::AddrVal>(IPAddr(ip6->ip6_dst)));
if ( ! chain ) if ( ! chain )
chain = make_intrusive<VectorVal>( chain = zeek::make_intrusive<zeek::VectorVal>(
zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain")); zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain"));
rv->Assign(7, std::move(chain)); rv->Assign(7, std::move(chain));
} }
@ -76,10 +76,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case IPPROTO_HOPOPTS: case IPPROTO_HOPOPTS:
{ {
static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts"); static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts");
rv = make_intrusive<RecordVal>(ip6_hopopts_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_hopopts_type);
const struct ip6_hbh* hbh = (const struct ip6_hbh*)data; const struct ip6_hbh* hbh = (const struct ip6_hbh*)data;
rv->Assign(0, val_mgr->Count(hbh->ip6h_nxt)); rv->Assign(0, zeek::val_mgr->Count(hbh->ip6h_nxt));
rv->Assign(1, val_mgr->Count(hbh->ip6h_len)); rv->Assign(1, zeek::val_mgr->Count(hbh->ip6h_len));
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); rv->Assign(2, BuildOptionsVal(data + off, Length() - off));
@ -89,10 +89,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case IPPROTO_DSTOPTS: case IPPROTO_DSTOPTS:
{ {
static auto ip6_dstopts_type = zeek::id::find_type<zeek::RecordType>("ip6_dstopts"); static auto ip6_dstopts_type = zeek::id::find_type<zeek::RecordType>("ip6_dstopts");
rv = make_intrusive<RecordVal>(ip6_dstopts_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_dstopts_type);
const struct ip6_dest* dst = (const struct ip6_dest*)data; const struct ip6_dest* dst = (const struct ip6_dest*)data;
rv->Assign(0, val_mgr->Count(dst->ip6d_nxt)); rv->Assign(0, zeek::val_mgr->Count(dst->ip6d_nxt));
rv->Assign(1, val_mgr->Count(dst->ip6d_len)); rv->Assign(1, zeek::val_mgr->Count(dst->ip6d_len));
uint16_t off = 2 * sizeof(uint8_t); uint16_t off = 2 * sizeof(uint8_t);
rv->Assign(2, BuildOptionsVal(data + off, Length() - off)); rv->Assign(2, BuildOptionsVal(data + off, Length() - off));
} }
@ -101,47 +101,47 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case IPPROTO_ROUTING: case IPPROTO_ROUTING:
{ {
static auto ip6_routing_type = zeek::id::find_type<zeek::RecordType>("ip6_routing"); static auto ip6_routing_type = zeek::id::find_type<zeek::RecordType>("ip6_routing");
rv = make_intrusive<RecordVal>(ip6_routing_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_routing_type);
const struct ip6_rthdr* rt = (const struct ip6_rthdr*)data; const struct ip6_rthdr* rt = (const struct ip6_rthdr*)data;
rv->Assign(0, val_mgr->Count(rt->ip6r_nxt)); rv->Assign(0, zeek::val_mgr->Count(rt->ip6r_nxt));
rv->Assign(1, val_mgr->Count(rt->ip6r_len)); rv->Assign(1, zeek::val_mgr->Count(rt->ip6r_len));
rv->Assign(2, val_mgr->Count(rt->ip6r_type)); rv->Assign(2, zeek::val_mgr->Count(rt->ip6r_type));
rv->Assign(3, val_mgr->Count(rt->ip6r_segleft)); rv->Assign(3, zeek::val_mgr->Count(rt->ip6r_segleft));
uint16_t off = 4 * sizeof(uint8_t); uint16_t off = 4 * sizeof(uint8_t);
rv->Assign(4, make_intrusive<StringVal>(new BroString(data + off, Length() - off, true))); rv->Assign(4, zeek::make_intrusive<zeek::StringVal>(new zeek::String(data + off, Length() - off, true)));
} }
break; break;
case IPPROTO_FRAGMENT: case IPPROTO_FRAGMENT:
{ {
static auto ip6_fragment_type = zeek::id::find_type<zeek::RecordType>("ip6_fragment"); static auto ip6_fragment_type = zeek::id::find_type<zeek::RecordType>("ip6_fragment");
rv = make_intrusive<RecordVal>(ip6_fragment_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_fragment_type);
const struct ip6_frag* frag = (const struct ip6_frag*)data; const struct ip6_frag* frag = (const struct ip6_frag*)data;
rv->Assign(0, val_mgr->Count(frag->ip6f_nxt)); rv->Assign(0, zeek::val_mgr->Count(frag->ip6f_nxt));
rv->Assign(1, val_mgr->Count(frag->ip6f_reserved)); rv->Assign(1, zeek::val_mgr->Count(frag->ip6f_reserved));
rv->Assign(2, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3)); rv->Assign(2, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0xfff8)>>3));
rv->Assign(3, val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1)); rv->Assign(3, zeek::val_mgr->Count((ntohs(frag->ip6f_offlg) & 0x0006)>>1));
rv->Assign(4, val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001)); rv->Assign(4, zeek::val_mgr->Bool(ntohs(frag->ip6f_offlg) & 0x0001));
rv->Assign(5, val_mgr->Count(ntohl(frag->ip6f_ident))); rv->Assign(5, zeek::val_mgr->Count(ntohl(frag->ip6f_ident)));
} }
break; break;
case IPPROTO_AH: case IPPROTO_AH:
{ {
static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah"); static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah");
rv = make_intrusive<RecordVal>(ip6_ah_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_ah_type);
rv->Assign(0, val_mgr->Count(((ip6_ext*)data)->ip6e_nxt)); rv->Assign(0, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_nxt));
rv->Assign(1, val_mgr->Count(((ip6_ext*)data)->ip6e_len)); rv->Assign(1, zeek::val_mgr->Count(((ip6_ext*)data)->ip6e_len));
rv->Assign(2, val_mgr->Count(ntohs(((uint16_t*)data)[1]))); rv->Assign(2, zeek::val_mgr->Count(ntohs(((uint16_t*)data)[1])));
rv->Assign(3, val_mgr->Count(ntohl(((uint32_t*)data)[1]))); rv->Assign(3, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[1])));
if ( Length() >= 12 ) if ( Length() >= 12 )
{ {
// Sequence Number and ICV fields can only be extracted if // Sequence Number and ICV fields can only be extracted if
// Payload Len was non-zero for this header. // Payload Len was non-zero for this header.
rv->Assign(4, val_mgr->Count(ntohl(((uint32_t*)data)[2]))); rv->Assign(4, zeek::val_mgr->Count(ntohl(((uint32_t*)data)[2])));
uint16_t off = 3 * sizeof(uint32_t); uint16_t off = 3 * sizeof(uint32_t);
rv->Assign(5, make_intrusive<StringVal>(new BroString(data + off, Length() - off, true))); rv->Assign(5, zeek::make_intrusive<zeek::StringVal>(new zeek::String(data + off, Length() - off, true)));
} }
} }
break; break;
@ -149,10 +149,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case IPPROTO_ESP: case IPPROTO_ESP:
{ {
static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp"); static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp");
rv = make_intrusive<RecordVal>(ip6_esp_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_esp_type);
const uint32_t* esp = (const uint32_t*)data; const uint32_t* esp = (const uint32_t*)data;
rv->Assign(0, val_mgr->Count(ntohl(esp[0]))); rv->Assign(0, zeek::val_mgr->Count(ntohl(esp[0])));
rv->Assign(1, val_mgr->Count(ntohl(esp[1]))); rv->Assign(1, zeek::val_mgr->Count(ntohl(esp[1])));
} }
break; break;
@ -160,17 +160,17 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case IPPROTO_MOBILITY: case IPPROTO_MOBILITY:
{ {
static auto ip6_mob_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_hdr"); static auto ip6_mob_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_hdr");
rv = make_intrusive<RecordVal>(ip6_mob_type); rv = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_type);
const struct ip6_mobility* mob = (const struct ip6_mobility*) data; const struct ip6_mobility* mob = (const struct ip6_mobility*) data;
rv->Assign(0, val_mgr->Count(mob->ip6mob_payload)); rv->Assign(0, zeek::val_mgr->Count(mob->ip6mob_payload));
rv->Assign(1, val_mgr->Count(mob->ip6mob_len)); rv->Assign(1, zeek::val_mgr->Count(mob->ip6mob_len));
rv->Assign(2, val_mgr->Count(mob->ip6mob_type)); rv->Assign(2, zeek::val_mgr->Count(mob->ip6mob_type));
rv->Assign(3, val_mgr->Count(mob->ip6mob_rsv)); rv->Assign(3, zeek::val_mgr->Count(mob->ip6mob_rsv));
rv->Assign(4, val_mgr->Count(ntohs(mob->ip6mob_chksum))); rv->Assign(4, zeek::val_mgr->Count(ntohs(mob->ip6mob_chksum)));
static auto ip6_mob_msg_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_msg"); static auto ip6_mob_msg_type = zeek::id::find_type<zeek::RecordType>("ip6_mobility_msg");
auto msg = make_intrusive<RecordVal>(ip6_mob_msg_type); auto msg = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_msg_type);
msg->Assign(0, val_mgr->Count(mob->ip6mob_type)); msg->Assign(0, zeek::val_mgr->Count(mob->ip6mob_type));
uint16_t off = sizeof(ip6_mobility); uint16_t off = sizeof(ip6_mobility);
const u_char* msg_data = data + off; const u_char* msg_data = data + off;
@ -187,8 +187,8 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
switch ( mob->ip6mob_type ) { switch ( mob->ip6mob_type ) {
case 0: case 0:
{ {
auto m = make_intrusive<RecordVal>(ip6_mob_brr_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mob_brr_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
off += sizeof(uint16_t); off += sizeof(uint16_t);
m->Assign(1, BuildOptionsVal(data + off, Length() - off)); m->Assign(1, BuildOptionsVal(data + off, Length() - off));
msg->Assign(1, std::move(m)); msg->Assign(1, std::move(m));
@ -197,9 +197,9 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 1: case 1:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_hoti_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_hoti_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
off += sizeof(uint16_t) + sizeof(uint64_t); off += sizeof(uint16_t) + sizeof(uint64_t);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(2, std::move(m)); msg->Assign(2, std::move(m));
@ -208,9 +208,9 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 2: case 2:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_coti_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_coti_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
off += sizeof(uint16_t) + sizeof(uint64_t); off += sizeof(uint16_t) + sizeof(uint64_t);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(3, std::move(m)); msg->Assign(3, std::move(m));
@ -219,10 +219,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 3: case 3:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_hot_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_hot_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); m->Assign(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t))))));
off += sizeof(uint16_t) + 2 * sizeof(uint64_t); off += sizeof(uint16_t) + 2 * sizeof(uint64_t);
m->Assign(3, BuildOptionsVal(data + off, Length() - off)); m->Assign(3, BuildOptionsVal(data + off, Length() - off));
msg->Assign(4, std::move(m)); msg->Assign(4, std::move(m));
@ -231,10 +231,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 4: case 4:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_cot_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_cot_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(1, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(2, val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t)))))); m->Assign(2, zeek::val_mgr->Count(ntohll(*((uint64_t*)(msg_data + sizeof(uint16_t) + sizeof(uint64_t))))));
off += sizeof(uint16_t) + 2 * sizeof(uint64_t); off += sizeof(uint16_t) + 2 * sizeof(uint64_t);
m->Assign(3, BuildOptionsVal(data + off, Length() - off)); m->Assign(3, BuildOptionsVal(data + off, Length() - off));
msg->Assign(5, std::move(m)); msg->Assign(5, std::move(m));
@ -243,13 +243,13 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 5: case 5:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_bu_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_bu_type);
m->Assign(0, val_mgr->Count(ntohs(*((uint16_t*)msg_data)))); m->Assign(0, zeek::val_mgr->Count(ntohs(*((uint16_t*)msg_data))));
m->Assign(1, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x8000)); m->Assign(1, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x8000));
m->Assign(2, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x4000)); m->Assign(2, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x4000));
m->Assign(3, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x2000)); m->Assign(3, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x2000));
m->Assign(4, val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x1000)); m->Assign(4, zeek::val_mgr->Bool(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))) & 0x1000));
m->Assign(5, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); m->Assign(5, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t))))));
off += 3 * sizeof(uint16_t); off += 3 * sizeof(uint16_t);
m->Assign(6, BuildOptionsVal(data + off, Length() - off)); m->Assign(6, BuildOptionsVal(data + off, Length() - off));
msg->Assign(6, std::move(m)); msg->Assign(6, std::move(m));
@ -258,11 +258,11 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 6: case 6:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_back_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_back_type);
m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data))); m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data)));
m->Assign(1, val_mgr->Bool(*((uint8_t*)(msg_data + sizeof(uint8_t))) & 0x80)); m->Assign(1, zeek::val_mgr->Bool(*((uint8_t*)(msg_data + sizeof(uint8_t))) & 0x80));
m->Assign(2, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t)))))); m->Assign(2, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + sizeof(uint16_t))))));
m->Assign(3, val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t)))))); m->Assign(3, zeek::val_mgr->Count(ntohs(*((uint16_t*)(msg_data + 2*sizeof(uint16_t))))));
off += 3 * sizeof(uint16_t); off += 3 * sizeof(uint16_t);
m->Assign(4, BuildOptionsVal(data + off, Length() - off)); m->Assign(4, BuildOptionsVal(data + off, Length() - off));
msg->Assign(7, std::move(m)); msg->Assign(7, std::move(m));
@ -271,10 +271,10 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
case 7: case 7:
{ {
auto m = make_intrusive<RecordVal>(ip6_mobility_be_type); auto m = zeek::make_intrusive<zeek::RecordVal>(ip6_mobility_be_type);
m->Assign(0, val_mgr->Count(*((uint8_t*)msg_data))); m->Assign(0, zeek::val_mgr->Count(*((uint8_t*)msg_data)));
const in6_addr* hoa = (const in6_addr*)(msg_data + sizeof(uint16_t)); const in6_addr* hoa = (const in6_addr*)(msg_data + sizeof(uint16_t));
m->Assign(1, make_intrusive<AddrVal>(IPAddr(*hoa))); m->Assign(1, zeek::make_intrusive<zeek::AddrVal>(IPAddr(*hoa)));
off += sizeof(uint16_t) + sizeof(in6_addr); off += sizeof(uint16_t) + sizeof(in6_addr);
m->Assign(2, BuildOptionsVal(data + off, Length() - off)); m->Assign(2, BuildOptionsVal(data + off, Length() - off));
msg->Assign(8, std::move(m)); msg->Assign(8, std::move(m));
@ -298,12 +298,12 @@ IntrusivePtr<RecordVal> IPv6_Hdr::ToVal(IntrusivePtr<VectorVal> chain) const
return rv; return rv;
} }
IntrusivePtr<RecordVal> IPv6_Hdr::ToVal() const zeek::RecordValPtr IPv6_Hdr::ToVal() const
{ return ToVal(nullptr); } { return ToVal(nullptr); }
RecordVal* IPv6_Hdr::BuildRecordVal(VectorVal* chain) const zeek::RecordVal* IPv6_Hdr::BuildRecordVal(zeek::VectorVal* chain) const
{ {
return ToVal({AdoptRef{}, chain}).release(); return ToVal({zeek::AdoptRef{}, chain}).release();
} }
IPAddr IP_Hdr::IPHeaderSrcAddr() const IPAddr IP_Hdr::IPHeaderSrcAddr() const
@ -326,22 +326,22 @@ IPAddr IP_Hdr::DstAddr() const
return ip4 ? IPAddr(ip4->ip_dst) : ip6_hdrs->DstAddr(); return ip4 ? IPAddr(ip4->ip_dst) : ip6_hdrs->DstAddr();
} }
IntrusivePtr<RecordVal> IP_Hdr::ToIPHdrVal() const zeek::RecordValPtr IP_Hdr::ToIPHdrVal() const
{ {
IntrusivePtr<RecordVal> rval; zeek::RecordValPtr rval;
if ( ip4 ) if ( ip4 )
{ {
static auto ip4_hdr_type = zeek::id::find_type<zeek::RecordType>("ip4_hdr"); static auto ip4_hdr_type = zeek::id::find_type<zeek::RecordType>("ip4_hdr");
rval = make_intrusive<RecordVal>(ip4_hdr_type); rval = zeek::make_intrusive<zeek::RecordVal>(ip4_hdr_type);
rval->Assign(0, val_mgr->Count(ip4->ip_hl * 4)); rval->Assign(0, zeek::val_mgr->Count(ip4->ip_hl * 4));
rval->Assign(1, val_mgr->Count(ip4->ip_tos)); rval->Assign(1, zeek::val_mgr->Count(ip4->ip_tos));
rval->Assign(2, val_mgr->Count(ntohs(ip4->ip_len))); rval->Assign(2, zeek::val_mgr->Count(ntohs(ip4->ip_len)));
rval->Assign(3, val_mgr->Count(ntohs(ip4->ip_id))); rval->Assign(3, zeek::val_mgr->Count(ntohs(ip4->ip_id)));
rval->Assign(4, val_mgr->Count(ip4->ip_ttl)); rval->Assign(4, zeek::val_mgr->Count(ip4->ip_ttl));
rval->Assign(5, val_mgr->Count(ip4->ip_p)); rval->Assign(5, zeek::val_mgr->Count(ip4->ip_p));
rval->Assign(6, make_intrusive<AddrVal>(ip4->ip_src.s_addr)); rval->Assign(6, zeek::make_intrusive<zeek::AddrVal>(ip4->ip_src.s_addr));
rval->Assign(7, make_intrusive<AddrVal>(ip4->ip_dst.s_addr)); rval->Assign(7, zeek::make_intrusive<zeek::AddrVal>(ip4->ip_dst.s_addr));
} }
else else
{ {
@ -351,23 +351,23 @@ IntrusivePtr<RecordVal> IP_Hdr::ToIPHdrVal() const
return rval; return rval;
} }
RecordVal* IP_Hdr::BuildIPHdrVal() const zeek::RecordVal* IP_Hdr::BuildIPHdrVal() const
{ {
return ToIPHdrVal().release(); return ToIPHdrVal().release();
} }
IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal() const zeek::RecordValPtr IP_Hdr::ToPktHdrVal() const
{ {
static auto pkt_hdr_type = zeek::id::find_type<zeek::RecordType>("pkt_hdr"); static auto pkt_hdr_type = zeek::id::find_type<zeek::RecordType>("pkt_hdr");
return ToPktHdrVal(make_intrusive<RecordVal>(pkt_hdr_type), 0); return ToPktHdrVal(zeek::make_intrusive<zeek::RecordVal>(pkt_hdr_type), 0);
} }
RecordVal* IP_Hdr::BuildPktHdrVal() const zeek::RecordVal* IP_Hdr::BuildPktHdrVal() const
{ {
return ToPktHdrVal().release(); return ToPktHdrVal().release();
} }
IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int sindex) const zeek::RecordValPtr IP_Hdr::ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const
{ {
static auto tcp_hdr_type = zeek::id::find_type<zeek::RecordType>("tcp_hdr"); static auto tcp_hdr_type = zeek::id::find_type<zeek::RecordType>("tcp_hdr");
static auto udp_hdr_type = zeek::id::find_type<zeek::RecordType>("udp_hdr"); static auto udp_hdr_type = zeek::id::find_type<zeek::RecordType>("udp_hdr");
@ -386,20 +386,20 @@ IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int
case IPPROTO_TCP: case IPPROTO_TCP:
{ {
const struct tcphdr* tp = (const struct tcphdr*) data; const struct tcphdr* tp = (const struct tcphdr*) data;
auto tcp_hdr = make_intrusive<RecordVal>(tcp_hdr_type); auto tcp_hdr = zeek::make_intrusive<zeek::RecordVal>(tcp_hdr_type);
int tcp_hdr_len = tp->th_off * 4; int tcp_hdr_len = tp->th_off * 4;
int data_len = PayloadLen() - tcp_hdr_len; int data_len = PayloadLen() - tcp_hdr_len;
tcp_hdr->Assign(0, val_mgr->Port(ntohs(tp->th_sport), TRANSPORT_TCP)); tcp_hdr->Assign(0, zeek::val_mgr->Port(ntohs(tp->th_sport), TRANSPORT_TCP));
tcp_hdr->Assign(1, val_mgr->Port(ntohs(tp->th_dport), TRANSPORT_TCP)); tcp_hdr->Assign(1, zeek::val_mgr->Port(ntohs(tp->th_dport), TRANSPORT_TCP));
tcp_hdr->Assign(2, val_mgr->Count(uint32_t(ntohl(tp->th_seq)))); tcp_hdr->Assign(2, zeek::val_mgr->Count(uint32_t(ntohl(tp->th_seq))));
tcp_hdr->Assign(3, val_mgr->Count(uint32_t(ntohl(tp->th_ack)))); tcp_hdr->Assign(3, zeek::val_mgr->Count(uint32_t(ntohl(tp->th_ack))));
tcp_hdr->Assign(4, val_mgr->Count(tcp_hdr_len)); tcp_hdr->Assign(4, zeek::val_mgr->Count(tcp_hdr_len));
tcp_hdr->Assign(5, val_mgr->Count(data_len)); tcp_hdr->Assign(5, zeek::val_mgr->Count(data_len));
tcp_hdr->Assign(6, val_mgr->Count(tp->th_x2)); tcp_hdr->Assign(6, zeek::val_mgr->Count(tp->th_x2));
tcp_hdr->Assign(7, val_mgr->Count(tp->th_flags)); tcp_hdr->Assign(7, zeek::val_mgr->Count(tp->th_flags));
tcp_hdr->Assign(8, val_mgr->Count(ntohs(tp->th_win))); tcp_hdr->Assign(8, zeek::val_mgr->Count(ntohs(tp->th_win)));
pkt_hdr->Assign(sindex + 2, std::move(tcp_hdr)); pkt_hdr->Assign(sindex + 2, std::move(tcp_hdr));
break; break;
@ -408,11 +408,11 @@ IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int
case IPPROTO_UDP: case IPPROTO_UDP:
{ {
const struct udphdr* up = (const struct udphdr*) data; const struct udphdr* up = (const struct udphdr*) data;
auto udp_hdr = make_intrusive<RecordVal>(udp_hdr_type); auto udp_hdr = zeek::make_intrusive<zeek::RecordVal>(udp_hdr_type);
udp_hdr->Assign(0, val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP)); udp_hdr->Assign(0, zeek::val_mgr->Port(ntohs(up->uh_sport), TRANSPORT_UDP));
udp_hdr->Assign(1, val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP)); udp_hdr->Assign(1, zeek::val_mgr->Port(ntohs(up->uh_dport), TRANSPORT_UDP));
udp_hdr->Assign(2, val_mgr->Count(ntohs(up->uh_ulen))); udp_hdr->Assign(2, zeek::val_mgr->Count(ntohs(up->uh_ulen)));
pkt_hdr->Assign(sindex + 3, std::move(udp_hdr)); pkt_hdr->Assign(sindex + 3, std::move(udp_hdr));
break; break;
@ -421,9 +421,9 @@ IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int
case IPPROTO_ICMP: case IPPROTO_ICMP:
{ {
const struct icmp* icmpp = (const struct icmp *) data; const struct icmp* icmpp = (const struct icmp *) data;
auto icmp_hdr = make_intrusive<RecordVal>(icmp_hdr_type); auto icmp_hdr = zeek::make_intrusive<zeek::RecordVal>(icmp_hdr_type);
icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp_type)); icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp_type));
pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr));
break; break;
@ -432,9 +432,9 @@ IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int
case IPPROTO_ICMPV6: case IPPROTO_ICMPV6:
{ {
const struct icmp6_hdr* icmpp = (const struct icmp6_hdr*) data; const struct icmp6_hdr* icmpp = (const struct icmp6_hdr*) data;
auto icmp_hdr = make_intrusive<RecordVal>(icmp_hdr_type); auto icmp_hdr = zeek::make_intrusive<zeek::RecordVal>(icmp_hdr_type);
icmp_hdr->Assign(0, val_mgr->Count(icmpp->icmp6_type)); icmp_hdr->Assign(0, zeek::val_mgr->Count(icmpp->icmp6_type));
pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr)); pkt_hdr->Assign(sindex + 4, std::move(icmp_hdr));
break; break;
@ -450,9 +450,9 @@ IntrusivePtr<RecordVal> IP_Hdr::ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int
return pkt_hdr; return pkt_hdr;
} }
RecordVal* IP_Hdr::BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const zeek::RecordVal* IP_Hdr::BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const
{ {
return ToPktHdrVal({AdoptRef{}, pkt_hdr}, sindex).release(); return ToPktHdrVal({zeek::AdoptRef{}, pkt_hdr}, sindex).release();
} }
static inline bool isIPv6ExtHeader(uint8_t type) static inline bool isIPv6ExtHeader(uint8_t type)
@ -676,7 +676,7 @@ void IPv6_Hdr_Chain::ProcessDstOpts(const struct ip6_dest* d, uint16_t len)
} }
#endif #endif
IntrusivePtr<VectorVal> IPv6_Hdr_Chain::ToVal() const zeek::VectorValPtr IPv6_Hdr_Chain::ToVal() const
{ {
static auto ip6_ext_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_ext_hdr"); static auto ip6_ext_hdr_type = zeek::id::find_type<zeek::RecordType>("ip6_ext_hdr");
static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts"); static auto ip6_hopopts_type = zeek::id::find_type<zeek::RecordType>("ip6_hopopts");
@ -686,14 +686,14 @@ IntrusivePtr<VectorVal> IPv6_Hdr_Chain::ToVal() const
static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah"); static auto ip6_ah_type = zeek::id::find_type<zeek::RecordType>("ip6_ah");
static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp"); static auto ip6_esp_type = zeek::id::find_type<zeek::RecordType>("ip6_esp");
static auto ip6_ext_hdr_chain_type = zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain"); static auto ip6_ext_hdr_chain_type = zeek::id::find_type<zeek::VectorType>("ip6_ext_hdr_chain");
auto rval = make_intrusive<VectorVal>(ip6_ext_hdr_chain_type); auto rval = zeek::make_intrusive<zeek::VectorVal>(ip6_ext_hdr_chain_type);
for ( size_t i = 1; i < chain.size(); ++i ) for ( size_t i = 1; i < chain.size(); ++i )
{ {
auto v = chain[i]->ToVal(); auto v = chain[i]->ToVal();
auto ext_hdr = make_intrusive<RecordVal>(ip6_ext_hdr_type); auto ext_hdr = zeek::make_intrusive<zeek::RecordVal>(ip6_ext_hdr_type);
uint8_t type = chain[i]->Type(); uint8_t type = chain[i]->Type();
ext_hdr->Assign(0, val_mgr->Count(type)); ext_hdr->Assign(0, zeek::val_mgr->Count(type));
switch (type) { switch (type) {
case IPPROTO_HOPOPTS: case IPPROTO_HOPOPTS:
@ -730,7 +730,7 @@ IntrusivePtr<VectorVal> IPv6_Hdr_Chain::ToVal() const
return rval; return rval;
} }
VectorVal* IPv6_Hdr_Chain::BuildVal() const zeek::VectorVal* IPv6_Hdr_Chain::BuildVal() const
{ {
return ToVal().release(); return ToVal().release();
} }

View file

@ -17,8 +17,14 @@
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
class IPAddr; class IPAddr;
class RecordVal;
class VectorVal; ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(VectorVal, zeek);
namespace zeek {
using RecordValPtr = zeek::IntrusivePtr<RecordVal>;
using VectorValPtr = zeek::IntrusivePtr<VectorVal>;
}
#ifdef ENABLE_MOBILE_IPV6 #ifdef ENABLE_MOBILE_IPV6
@ -136,11 +142,11 @@ public:
/** /**
* Returns the script-layer record representation of the header. * Returns the script-layer record representation of the header.
*/ */
IntrusivePtr<RecordVal> ToVal(IntrusivePtr<VectorVal> chain) const; zeek::RecordValPtr ToVal(zeek::VectorValPtr chain) const;
IntrusivePtr<RecordVal> ToVal() const; zeek::RecordValPtr ToVal() const;
[[deprecated("Remove in v4.1. Use ToVal() instead.")]] [[deprecated("Remove in v4.1. Use ToVal() instead.")]]
RecordVal* BuildRecordVal(VectorVal* chain = nullptr) const; zeek::RecordVal* BuildRecordVal(zeek::VectorVal* chain = nullptr) const;
protected: protected:
uint8_t type; uint8_t type;
@ -229,10 +235,10 @@ public:
* Returns a vector of ip6_ext_hdr RecordVals that includes script-layer * Returns a vector of ip6_ext_hdr RecordVals that includes script-layer
* representation of all extension headers in the chain. * representation of all extension headers in the chain.
*/ */
IntrusivePtr<VectorVal> ToVal() const; zeek::VectorValPtr ToVal() const;
[[deprecated("Remove in v4.1. Use ToVal() instead.")]] [[deprecated("Remove in v4.1. Use ToVal() instead.")]]
VectorVal* BuildVal() const; zeek::VectorVal* BuildVal() const;
protected: protected:
// for access to protected ctor that changes next header values that // for access to protected ctor that changes next header values that
@ -526,28 +532,28 @@ public:
/** /**
* Returns an ip_hdr or ip6_hdr_chain RecordVal. * Returns an ip_hdr or ip6_hdr_chain RecordVal.
*/ */
IntrusivePtr<RecordVal> ToIPHdrVal() const; zeek::RecordValPtr ToIPHdrVal() const;
[[deprecated("Remove in v4.1. Use ToIPHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToIPHdrVal() instead.")]]
RecordVal* BuildIPHdrVal() const; zeek::RecordVal* BuildIPHdrVal() const;
/** /**
* Returns a pkt_hdr RecordVal, which includes not only the IP header, but * Returns a pkt_hdr RecordVal, which includes not only the IP header, but
* also upper-layer (tcp/udp/icmp) headers. * also upper-layer (tcp/udp/icmp) headers.
*/ */
IntrusivePtr<RecordVal> ToPktHdrVal() const; zeek::RecordValPtr ToPktHdrVal() const;
[[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]]
RecordVal* BuildPktHdrVal() const; zeek::RecordVal* BuildPktHdrVal() const;
/** /**
* Same as above, but simply add our values into the record at the * Same as above, but simply add our values into the record at the
* specified starting index. * specified starting index.
*/ */
IntrusivePtr<RecordVal> ToPktHdrVal(IntrusivePtr<RecordVal> pkt_hdr, int sindex) const; zeek::RecordValPtr ToPktHdrVal(zeek::RecordValPtr pkt_hdr, int sindex) const;
[[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]] [[deprecated("Remove in v4.1. Use ToPktHdrVal() instead.")]]
RecordVal* BuildPktHdrVal(RecordVal* pkt_hdr, int sindex) const; zeek::RecordVal* BuildPktHdrVal(zeek::RecordVal* pkt_hdr, int sindex) const;
private: private:
const struct ip* ip4 = nullptr; const struct ip* ip4 = nullptr;

View file

@ -5,7 +5,7 @@
#include <vector> #include <vector>
#include "IPAddr.h" #include "IPAddr.h"
#include "Reporter.h" #include "Reporter.h"
#include "BroString.h" #include "ZeekString.h"
#include "Conn.h" #include "Conn.h"
#include "Hash.h" #include "Hash.h"
#include "bro_inet_ntop.h" #include "bro_inet_ntop.h"
@ -47,7 +47,7 @@ ConnIDKey BuildConnIDKey(const ConnID& id)
return key; return key;
} }
IPAddr::IPAddr(const BroString& s) IPAddr::IPAddr(const zeek::String& s)
{ {
Init(s.CheckString()); Init(s.CheckString());
} }

View file

@ -10,15 +10,16 @@
#include "threading/SerialTypes.h" #include "threading/SerialTypes.h"
namespace zeek { class String; }
using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String;
struct ConnID; struct ConnID;
class BroString;
class HashKey; class HashKey;
namespace analyzer { class ExpectedConn; } namespace analyzer { class ExpectedConn; }
typedef in_addr in4_addr; typedef in_addr in4_addr;
struct ConnIDKey struct ConnIDKey {
{
in6_addr ip1; in6_addr ip1;
in6_addr ip2; in6_addr ip2;
uint16_t port1; uint16_t port1;
@ -40,13 +41,12 @@ struct ConnIDKey
return *this; return *this;
} }
}; };
/** /**
* Class storing both IPv4 and IPv6 addresses. * Class storing both IPv4 and IPv6 addresses.
*/ */
class IPAddr class IPAddr {
{
public: public:
/** /**
* Address family. * Address family.
@ -112,7 +112,7 @@ public:
* @param s String containing an IP address as either a dotted IPv4 * @param s String containing an IP address as either a dotted IPv4
* address or a hex IPv6 address. * address or a hex IPv6 address.
*/ */
explicit IPAddr(const BroString& s); explicit IPAddr(const zeek::String& s);
/** /**
* Constructs an address instance from a raw byte representation. * Constructs an address instance from a raw byte representation.

View file

@ -5,6 +5,8 @@
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
namespace zeek {
/** /**
* A tag class for the #IntrusivePtr constructor which means: adopt * A tag class for the #IntrusivePtr constructor which means: adopt
* the reference from the caller. * the reference from the caller.
@ -31,7 +33,7 @@ struct NewRef {};
* for destroying the shared object. * for destroying the shared object.
* *
* The @c IntrusivePtr works with any type that offers the two free functions, * The @c IntrusivePtr works with any type that offers the two free functions,
* but most notably is designed to work with @c BroObj and its subtypes. * but most notably is designed to work with @c Obj and its subtypes.
* *
* The same object may get managed via @c IntrusivePtr in one part of the * The same object may get managed via @c IntrusivePtr in one part of the
* code base while another part of the program manages it manually by passing * code base while another part of the program manages it manually by passing
@ -97,7 +99,7 @@ public:
} }
IntrusivePtr(const IntrusivePtr& other) noexcept IntrusivePtr(const IntrusivePtr& other) noexcept
: IntrusivePtr(NewRef{}, other.get()) : IntrusivePtr(zeek::NewRef{}, other.get())
{ {
} }
@ -181,7 +183,7 @@ template <class T, class... Ts>
IntrusivePtr<T> make_intrusive(Ts&&... args) IntrusivePtr<T> make_intrusive(Ts&&... args)
{ {
// Assumes that objects start with a reference count of 1! // Assumes that objects start with a reference count of 1!
return {AdoptRef{}, new T(std::forward<Ts>(args)...)}; return {zeek::AdoptRef{}, new T(std::forward<Ts>(args)...)};
} }
/** /**
@ -193,16 +195,18 @@ IntrusivePtr<T> make_intrusive(Ts&&... args)
template <class T, class U> template <class T, class U>
IntrusivePtr<T> cast_intrusive(IntrusivePtr<U> p) noexcept IntrusivePtr<T> cast_intrusive(IntrusivePtr<U> p) noexcept
{ {
return {AdoptRef{}, static_cast<T*>(p.release())}; return {zeek::AdoptRef{}, static_cast<T*>(p.release())};
} }
}
// -- comparison to nullptr ---------------------------------------------------- // -- comparison to nullptr ----------------------------------------------------
/** /**
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator==(const IntrusivePtr<T>& x, std::nullptr_t) { bool operator==(const zeek::IntrusivePtr<T>& x, std::nullptr_t) {
return !x; return !x;
} }
@ -210,7 +214,7 @@ bool operator==(const IntrusivePtr<T>& x, std::nullptr_t) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator==(std::nullptr_t, const IntrusivePtr<T>& x) { bool operator==(std::nullptr_t, const zeek::IntrusivePtr<T>& x) {
return !x; return !x;
} }
@ -218,7 +222,7 @@ bool operator==(std::nullptr_t, const IntrusivePtr<T>& x) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator!=(const IntrusivePtr<T>& x, std::nullptr_t) { bool operator!=(const zeek::IntrusivePtr<T>& x, std::nullptr_t) {
return static_cast<bool>(x); return static_cast<bool>(x);
} }
@ -226,7 +230,7 @@ bool operator!=(const IntrusivePtr<T>& x, std::nullptr_t) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator!=(std::nullptr_t, const IntrusivePtr<T>& x) { bool operator!=(std::nullptr_t, const zeek::IntrusivePtr<T>& x) {
return static_cast<bool>(x); return static_cast<bool>(x);
} }
@ -236,7 +240,7 @@ bool operator!=(std::nullptr_t, const IntrusivePtr<T>& x) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator==(const IntrusivePtr<T>& x, const T* y) { bool operator==(const zeek::IntrusivePtr<T>& x, const T* y) {
return x.get() == y; return x.get() == y;
} }
@ -244,7 +248,7 @@ bool operator==(const IntrusivePtr<T>& x, const T* y) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator==(const T* x, const IntrusivePtr<T>& y) { bool operator==(const T* x, const zeek::IntrusivePtr<T>& y) {
return x == y.get(); return x == y.get();
} }
@ -252,7 +256,7 @@ bool operator==(const T* x, const IntrusivePtr<T>& y) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator!=(const IntrusivePtr<T>& x, const T* y) { bool operator!=(const zeek::IntrusivePtr<T>& x, const T* y) {
return x.get() != y; return x.get() != y;
} }
@ -260,7 +264,7 @@ bool operator!=(const IntrusivePtr<T>& x, const T* y) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T> template <class T>
bool operator!=(const T* x, const IntrusivePtr<T>& y) { bool operator!=(const T* x, const zeek::IntrusivePtr<T>& y) {
return x != y.get(); return x != y.get();
} }
@ -273,7 +277,7 @@ bool operator!=(const T* x, const IntrusivePtr<T>& y) {
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T, class U> template <class T, class U>
auto operator==(const IntrusivePtr<T>& x, const IntrusivePtr<U>& y) auto operator==(const zeek::IntrusivePtr<T>& x, const zeek::IntrusivePtr<U>& y)
-> decltype(x.get() == y.get()) -> decltype(x.get() == y.get())
{ {
return x.get() == y.get(); return x.get() == y.get();
@ -283,9 +287,8 @@ auto operator==(const IntrusivePtr<T>& x, const IntrusivePtr<U>& y)
* @relates IntrusivePtr * @relates IntrusivePtr
*/ */
template <class T, class U> template <class T, class U>
auto operator!=(const IntrusivePtr<T>& x, const IntrusivePtr<U>& y) auto operator!=(const zeek::IntrusivePtr<T>& x, const zeek::IntrusivePtr<U>& y)
-> decltype(x.get() != y.get()) -> decltype(x.get() != y.get())
{ {
return x.get() != y.get(); return x.get() != y.get();
} }

View file

@ -3,17 +3,17 @@
TEST_CASE("list construction") TEST_CASE("list construction")
{ {
List<int> list; zeek::List<int> list;
CHECK(list.empty()); CHECK(list.empty());
List<int> list2(10); zeek::List<int> list2(10);
CHECK(list2.empty()); CHECK(list2.empty());
CHECK(list2.max() == 10); CHECK(list2.max() == 10);
} }
TEST_CASE("list operation") TEST_CASE("list operation")
{ {
List<int> list({ 1, 2, 3 }); zeek::List<int> list({ 1, 2, 3 });
CHECK(list.size() == 3); CHECK(list.size() == 3);
CHECK(list.max() == 3); CHECK(list.max() == 3);
CHECK(list[0] == 1); CHECK(list[0] == 1);
@ -85,7 +85,7 @@ TEST_CASE("list operation")
TEST_CASE("list iteration") TEST_CASE("list iteration")
{ {
List<int> list({ 1, 2, 3, 4}); zeek::List<int> list({ 1, 2, 3, 4});
int index = 1; int index = 1;
for ( int v : list ) for ( int v : list )
@ -98,7 +98,7 @@ TEST_CASE("list iteration")
TEST_CASE("plists") TEST_CASE("plists")
{ {
PList<int> list; zeek::PList<int> list;
list.push_back(new int(1)); list.push_back(new int(1));
list.push_back(new int(2)); list.push_back(new int(2));
list.push_back(new int(3)); list.push_back(new int(3));
@ -117,7 +117,7 @@ TEST_CASE("plists")
TEST_CASE("unordered list operation") TEST_CASE("unordered list operation")
{ {
List<int, ListOrder::UNORDERED> list({1, 2, 3, 4}); zeek::List<int, zeek::ListOrder::UNORDERED> list({1, 2, 3, 4});
CHECK(list.size() == 4); CHECK(list.size() == 4);
// An unordered list doesn't maintain the ordering of the elements when // An unordered list doesn't maintain the ordering of the elements when

View file

@ -26,8 +26,7 @@
#include <cassert> #include <cassert>
#include "util.h" #include "util.h"
// TODO: this can be removed in v3.1 when List::sort() is removed namespace zeek {
typedef int (*list_cmp_func)(const void* v1, const void* v2);
enum class ListOrder : int { ORDERED, UNORDERED }; enum class ListOrder : int { ORDERED, UNORDERED };
@ -334,7 +333,11 @@ template<typename T, ListOrder Order = ListOrder::ORDERED>
using PList = List<T*, Order>; using PList = List<T*, Order>;
// Popular type of list: list of strings. // Popular type of list: list of strings.
typedef PList<char> name_list; using name_list = PList<char>;
} // namespace zeek
using ListOrder [[deprecated("Remove in v4.1. Use zeek::ListOrder instead.")]] = zeek::ListOrder;
// Macro to visit each list element in turn. // Macro to visit each list element in turn.
#define loop_over_list(list, iterator) \ #define loop_over_list(list, iterator) \

View file

@ -6,11 +6,12 @@
#include "List.h" #include "List.h"
class CCL; class CCL;
class Func;
class NFA_State; class NFA_State;
class EquivClass; class EquivClass;
typedef PList<NFA_State> NFA_state_list; ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
using NFA_state_list = zeek::PList<NFA_State>;
#define NO_ACCEPT 0 #define NO_ACCEPT 0
@ -21,10 +22,10 @@ typedef PList<NFA_State> NFA_state_list;
#define NUM_SYM 258 #define NUM_SYM 258
#define SYM_EPSILON 259 #define SYM_EPSILON 259
#define SYM_CCL 260 #define SYM_CCL 260
class NFA_State : public BroObj { class NFA_State : public zeek::Obj {
public: public:
NFA_State(int sym, EquivClass* ec); NFA_State(int sym, EquivClass* ec);
explicit NFA_State(CCL* ccl); explicit NFA_State(CCL* ccl);
@ -81,7 +82,7 @@ public:
EpsilonState() : NFA_State(SYM_EPSILON, nullptr) { } EpsilonState() : NFA_State(SYM_EPSILON, nullptr) { }
}; };
class NFA_Machine : public BroObj { class NFA_Machine : public zeek::Obj {
public: public:
explicit NFA_Machine(NFA_State* first, NFA_State* final = nullptr); explicit NFA_Machine(NFA_State* first, NFA_State* final = nullptr);
~NFA_Machine() override; ~NFA_Machine() override;

View file

@ -193,8 +193,8 @@ void net_init(const std::optional<std::string>& interface,
reporter->FatalError("problem opening dump file %s (%s)", reporter->FatalError("problem opening dump file %s (%s)",
writefile, pkt_dumper->ErrorMsg()); writefile, pkt_dumper->ErrorMsg());
if ( const auto& id = global_scope()->Find("trace_output_file") ) if ( const auto& id = zeek::detail::global_scope()->Find("trace_output_file") )
id->SetVal(make_intrusive<StringVal>(writefile)); id->SetVal(zeek::make_intrusive<zeek::StringVal>(writefile));
else else
reporter->Error("trace_output_file not defined in bro.init"); reporter->Error("trace_output_file not defined in bro.init");
} }

View file

@ -66,17 +66,17 @@ double icmp_inactivity_timeout;
int tcp_storm_thresh; int tcp_storm_thresh;
double tcp_storm_interarrival_thresh; double tcp_storm_interarrival_thresh;
TableVal* tcp_reassembler_ports_orig; zeek::TableVal* tcp_reassembler_ports_orig;
TableVal* tcp_reassembler_ports_resp; zeek::TableVal* tcp_reassembler_ports_resp;
TableVal* tcp_content_delivery_ports_orig; zeek::TableVal* tcp_content_delivery_ports_orig;
TableVal* tcp_content_delivery_ports_resp; zeek::TableVal* tcp_content_delivery_ports_resp;
bool tcp_content_deliver_all_orig; bool tcp_content_deliver_all_orig;
bool tcp_content_deliver_all_resp; bool tcp_content_deliver_all_resp;
TableVal* udp_content_delivery_ports_orig; zeek::TableVal* udp_content_delivery_ports_orig;
TableVal* udp_content_delivery_ports_resp; zeek::TableVal* udp_content_delivery_ports_resp;
TableVal* udp_content_ports; zeek::TableVal* udp_content_ports;
bool udp_content_deliver_all_orig; bool udp_content_deliver_all_orig;
bool udp_content_deliver_all_resp; bool udp_content_deliver_all_resp;
bool udp_content_delivery_ports_use_resp; bool udp_content_delivery_ports_use_resp;
@ -112,15 +112,15 @@ zeek::RecordType* dns_rrsig_rr;
zeek::RecordType* dns_dnskey_rr; zeek::RecordType* dns_dnskey_rr;
zeek::RecordType* dns_nsec3_rr; zeek::RecordType* dns_nsec3_rr;
zeek::RecordType* dns_ds_rr; zeek::RecordType* dns_ds_rr;
TableVal* dns_skip_auth; zeek::TableVal* dns_skip_auth;
TableVal* dns_skip_addl; zeek::TableVal* dns_skip_addl;
int dns_skip_all_auth; int dns_skip_all_auth;
int dns_skip_all_addl; int dns_skip_all_addl;
int dns_max_queries; int dns_max_queries;
double stp_delta; double stp_delta;
double stp_idle_min; double stp_idle_min;
TableVal* stp_skip_src; zeek::TableVal* stp_skip_src;
double table_expire_interval; double table_expire_interval;
double table_expire_delay; double table_expire_delay;
@ -130,22 +130,22 @@ double connection_status_update_interval;
int orig_addr_anonymization, resp_addr_anonymization; int orig_addr_anonymization, resp_addr_anonymization;
int other_addr_anonymization; int other_addr_anonymization;
TableVal* preserve_orig_addr; zeek::TableVal* preserve_orig_addr;
TableVal* preserve_resp_addr; zeek::TableVal* preserve_resp_addr;
TableVal* preserve_other_addr; zeek::TableVal* preserve_other_addr;
zeek::RecordType* rotate_info; zeek::RecordType* rotate_info;
StringVal* log_rotate_base_time; zeek::StringVal* log_rotate_base_time;
StringVal* peer_description; zeek::StringVal* peer_description;
Val* profiling_file; zeek::Val* profiling_file;
double profiling_interval; double profiling_interval;
int expensive_profiling_multiple; int expensive_profiling_multiple;
int segment_profiling; int segment_profiling;
int pkt_profile_mode; int pkt_profile_mode;
double pkt_profile_freq; double pkt_profile_freq;
Val* pkt_profile_file; zeek::Val* pkt_profile_file;
int load_sample_freq; int load_sample_freq;
@ -162,13 +162,13 @@ int dpd_match_only_beginning;
int dpd_late_match_stop; int dpd_late_match_stop;
int dpd_ignore_ports; int dpd_ignore_ports;
TableVal* likely_server_ports; zeek::TableVal* likely_server_ports;
int check_for_unused_event_handlers; int check_for_unused_event_handlers;
double timer_mgr_inactivity_timeout; double timer_mgr_inactivity_timeout;
StringVal* trace_output_file; zeek::StringVal* trace_output_file;
int record_all_packets; int record_all_packets;
@ -179,9 +179,9 @@ zeek::TableType* record_field_table;
zeek::RecordType* call_argument; zeek::RecordType* call_argument;
zeek::VectorType* call_argument_vector; zeek::VectorType* call_argument_vector;
StringVal* cmd_line_bpf_filter; zeek::StringVal* cmd_line_bpf_filter;
StringVal* global_hash_seed; zeek::StringVal* global_hash_seed;
bro_uint_t bits_per_uid; bro_uint_t bits_per_uid;

View file

@ -87,23 +87,23 @@ extern int tcp_storm_thresh;
extern double tcp_storm_interarrival_thresh; extern double tcp_storm_interarrival_thresh;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* tcp_reassembler_ports_orig; extern zeek::TableVal* tcp_reassembler_ports_orig;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* tcp_reassembler_ports_resp; extern zeek::TableVal* tcp_reassembler_ports_resp;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* tcp_content_delivery_ports_orig; extern zeek::TableVal* tcp_content_delivery_ports_orig;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* tcp_content_delivery_ports_resp; extern zeek::TableVal* tcp_content_delivery_ports_resp;
extern bool tcp_content_deliver_all_orig; extern bool tcp_content_deliver_all_orig;
extern bool tcp_content_deliver_all_resp; extern bool tcp_content_deliver_all_resp;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* udp_content_delivery_ports_orig; extern zeek::TableVal* udp_content_delivery_ports_orig;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* udp_content_delivery_ports_resp; extern zeek::TableVal* udp_content_delivery_ports_resp;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* udp_content_ports; extern zeek::TableVal* udp_content_ports;
extern bool udp_content_deliver_all_orig; extern bool udp_content_deliver_all_orig;
extern bool udp_content_deliver_all_resp; extern bool udp_content_deliver_all_resp;
extern bool udp_content_delivery_ports_use_resp; extern bool udp_content_delivery_ports_use_resp;
@ -159,9 +159,9 @@ extern zeek::RecordType* dns_nsec3_rr;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern zeek::RecordType* dns_ds_rr; extern zeek::RecordType* dns_ds_rr;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* dns_skip_auth; extern zeek::TableVal* dns_skip_auth;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* dns_skip_addl; extern zeek::TableVal* dns_skip_addl;
extern int dns_skip_all_auth; extern int dns_skip_all_auth;
extern int dns_skip_all_addl; extern int dns_skip_all_addl;
extern int dns_max_queries; extern int dns_max_queries;
@ -169,7 +169,7 @@ extern int dns_max_queries;
extern double stp_delta; extern double stp_delta;
extern double stp_idle_min; extern double stp_idle_min;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* stp_skip_src; extern zeek::TableVal* stp_skip_src;
extern double table_expire_interval; extern double table_expire_interval;
extern double table_expire_delay; extern double table_expire_delay;
@ -178,24 +178,24 @@ extern int table_incremental_step;
extern int orig_addr_anonymization, resp_addr_anonymization; extern int orig_addr_anonymization, resp_addr_anonymization;
extern int other_addr_anonymization; extern int other_addr_anonymization;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* preserve_orig_addr; extern zeek::TableVal* preserve_orig_addr;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* preserve_resp_addr; extern zeek::TableVal* preserve_resp_addr;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* preserve_other_addr; extern zeek::TableVal* preserve_other_addr;
extern double connection_status_update_interval; extern double connection_status_update_interval;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern zeek::RecordType* rotate_info; extern zeek::RecordType* rotate_info;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern StringVal* log_rotate_base_time; extern zeek::StringVal* log_rotate_base_time;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern StringVal* peer_description; extern zeek::StringVal* peer_description;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern Val* profiling_file; extern zeek::Val* profiling_file;
extern double profiling_interval; extern double profiling_interval;
extern int expensive_profiling_multiple; extern int expensive_profiling_multiple;
@ -203,7 +203,7 @@ extern int segment_profiling;
extern int pkt_profile_mode; extern int pkt_profile_mode;
extern double pkt_profile_freq; extern double pkt_profile_freq;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern Val* pkt_profile_file; extern zeek::Val* pkt_profile_file;
extern int load_sample_freq; extern int load_sample_freq;
@ -223,14 +223,14 @@ extern int dpd_late_match_stop;
extern int dpd_ignore_ports; extern int dpd_ignore_ports;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern TableVal* likely_server_ports; extern zeek::TableVal* likely_server_ports;
extern int check_for_unused_event_handlers; extern int check_for_unused_event_handlers;
extern double timer_mgr_inactivity_timeout; extern double timer_mgr_inactivity_timeout;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern StringVal* trace_output_file; extern zeek::StringVal* trace_output_file;
extern int record_all_packets; extern int record_all_packets;
@ -248,10 +248,10 @@ extern zeek::RecordType* call_argument;
extern zeek::VectorType* call_argument_vector; extern zeek::VectorType* call_argument_vector;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern StringVal* cmd_line_bpf_filter; extern zeek::StringVal* cmd_line_bpf_filter;
[[deprecated("Remove in v4.1. Perform your own lookup.")]] [[deprecated("Remove in v4.1. Perform your own lookup.")]]
extern StringVal* global_hash_seed; extern zeek::StringVal* global_hash_seed;
extern bro_uint_t bits_per_uid; extern bro_uint_t bits_per_uid;

View file

@ -10,6 +10,9 @@
#include "File.h" #include "File.h"
#include "plugin/Manager.h" #include "plugin/Manager.h"
namespace zeek {
namespace detail {
Location start_location("<start uninitialized>", 0, 0, 0, 0); Location start_location("<start uninitialized>", 0, 0, 0, 0);
Location end_location("<end uninitialized>", 0, 0, 0, 0); Location end_location("<end uninitialized>", 0, 0, 0, 0);
@ -48,9 +51,11 @@ bool Location::operator==(const Location& l) const
return false; return false;
} }
int BroObj::suppress_errors = 0; } // namespace detail
BroObj::~BroObj() int Obj::suppress_errors = 0;
Obj::~Obj()
{ {
if ( notify_plugins ) if ( notify_plugins )
PLUGIN_HOOK_VOID(HOOK_BRO_OBJ_DTOR, HookBroObjDtor(this)); PLUGIN_HOOK_VOID(HOOK_BRO_OBJ_DTOR, HookBroObjDtor(this));
@ -58,7 +63,7 @@ BroObj::~BroObj()
delete location; delete location;
} }
void BroObj::Warn(const char* msg, const BroObj* obj2, bool pinpoint_only, const Location* expr_location) const void Obj::Warn(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const
{ {
ODesc d; ODesc d;
DoMsg(&d, msg, obj2, pinpoint_only, expr_location); DoMsg(&d, msg, obj2, pinpoint_only, expr_location);
@ -66,7 +71,7 @@ void BroObj::Warn(const char* msg, const BroObj* obj2, bool pinpoint_only, const
reporter->PopLocation(); reporter->PopLocation();
} }
void BroObj::Error(const char* msg, const BroObj* obj2, bool pinpoint_only, const Location* expr_location) const void Obj::Error(const char* msg, const Obj* obj2, bool pinpoint_only, const detail::Location* expr_location) const
{ {
if ( suppress_errors ) if ( suppress_errors )
return; return;
@ -77,7 +82,7 @@ void BroObj::Error(const char* msg, const BroObj* obj2, bool pinpoint_only, cons
reporter->PopLocation(); reporter->PopLocation();
} }
void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const void Obj::BadTag(const char* msg, const char* t1, const char* t2) const
{ {
char out[512]; char out[512];
@ -94,11 +99,11 @@ void BroObj::BadTag(const char* msg, const char* t1, const char* t2) const
reporter->PopLocation(); reporter->PopLocation();
} }
void BroObj::Internal(const char* msg) const void Obj::Internal(const char* msg) const
{ {
ODesc d; ODesc d;
DoMsg(&d, msg); DoMsg(&d, msg);
auto rcs = render_call_stack(); auto rcs = zeek::render_call_stack();
if ( rcs.empty() ) if ( rcs.empty() )
reporter->InternalError("%s", d.Description()); reporter->InternalError("%s", d.Description());
@ -108,7 +113,7 @@ void BroObj::Internal(const char* msg) const
reporter->PopLocation(); reporter->PopLocation();
} }
void BroObj::InternalWarning(const char* msg) const void Obj::InternalWarning(const char* msg) const
{ {
ODesc d; ODesc d;
DoMsg(&d, msg); DoMsg(&d, msg);
@ -116,7 +121,7 @@ void BroObj::InternalWarning(const char* msg) const
reporter->PopLocation(); reporter->PopLocation();
} }
void BroObj::AddLocation(ODesc* d) const void Obj::AddLocation(ODesc* d) const
{ {
if ( ! location ) if ( ! location )
{ {
@ -127,7 +132,7 @@ void BroObj::AddLocation(ODesc* d) const
location->Describe(d); location->Describe(d);
} }
bool BroObj::SetLocationInfo(const Location* start, const Location* end) bool Obj::SetLocationInfo(const detail::Location* start, const detail::Location* end)
{ {
if ( ! start || ! end ) if ( ! start || ! end )
return false; return false;
@ -135,20 +140,20 @@ bool BroObj::SetLocationInfo(const Location* start, const Location* end)
if ( end->filename && ! streq(start->filename, end->filename) ) if ( end->filename && ! streq(start->filename, end->filename) )
return false; return false;
if ( location && (start == &no_location || end == &no_location) ) if ( location && (start == &zeek::detail::no_location || end == &zeek::detail::no_location) )
// We already have a better location, so don't use this one. // We already have a better location, so don't use this one.
return true; return true;
delete location; delete location;
location = new Location(start->filename, location = new detail::Location(start->filename,
start->first_line, end->last_line, start->first_line, end->last_line,
start->first_column, end->last_column); start->first_column, end->last_column);
return true; return true;
} }
void BroObj::UpdateLocationEndInfo(const Location& end) void Obj::UpdateLocationEndInfo(const detail::Location& end)
{ {
if ( ! location ) if ( ! location )
SetLocationInfo(&end, &end); SetLocationInfo(&end, &end);
@ -157,16 +162,16 @@ void BroObj::UpdateLocationEndInfo(const Location& end)
location->last_column = end.last_column; location->last_column = end.last_column;
} }
void BroObj::DoMsg(ODesc* d, const char s1[], const BroObj* obj2, void Obj::DoMsg(ODesc* d, const char s1[], const Obj* obj2,
bool pinpoint_only, const Location* expr_location) const bool pinpoint_only, const detail::Location* expr_location) const
{ {
d->SetShort(); d->SetShort();
d->Add(s1); d->Add(s1);
PinPoint(d, obj2, pinpoint_only); PinPoint(d, obj2, pinpoint_only);
const Location* loc2 = nullptr; const detail::Location* loc2 = nullptr;
if ( obj2 && obj2->GetLocationInfo() != &no_location && if ( obj2 && obj2->GetLocationInfo() != &zeek::detail::no_location &&
*obj2->GetLocationInfo() != *GetLocationInfo() ) *obj2->GetLocationInfo() != *GetLocationInfo() )
loc2 = obj2->GetLocationInfo(); loc2 = obj2->GetLocationInfo();
else if ( expr_location ) else if ( expr_location )
@ -175,7 +180,7 @@ void BroObj::DoMsg(ODesc* d, const char s1[], const BroObj* obj2,
reporter->PushLocation(GetLocationInfo(), loc2); reporter->PushLocation(GetLocationInfo(), loc2);
} }
void BroObj::PinPoint(ODesc* d, const BroObj* obj2, bool pinpoint_only) const void Obj::PinPoint(ODesc* d, const Obj* obj2, bool pinpoint_only) const
{ {
d->Add(" ("); d->Add(" (");
Describe(d); Describe(d);
@ -188,11 +193,11 @@ void BroObj::PinPoint(ODesc* d, const BroObj* obj2, bool pinpoint_only) const
d->Add(")"); d->Add(")");
} }
void print(const BroObj* obj) void Obj::Print() const
{ {
static BroFile fstderr(stderr); static BroFile fstderr(stderr);
ODesc d(DESC_READABLE, &fstderr); ODesc d(DESC_READABLE, &fstderr);
obj->Describe(&d); Describe(&d);
d.Add("\n"); d.Add("\n");
} }
@ -202,7 +207,14 @@ void bad_ref(int type)
abort(); abort();
} }
void bro_obj_delete_func(void* v) void obj_delete_func(void* v)
{ {
Unref((BroObj*) v); Unref((Obj*) v);
}
} // namespace zeek
void print(const zeek::Obj* obj)
{
obj->Print();
} }

View file

@ -6,8 +6,12 @@
class ODesc; class ODesc;
namespace zeek {
namespace detail {
class Location final { class Location final {
public: public:
constexpr Location(const char* fname, int line_f, int line_l, constexpr Location(const char* fname, int line_f, int line_l,
int col_f, int col_l) noexcept int col_f, int col_l) noexcept
:filename(fname), first_line(line_f), last_line(line_l), :filename(fname), first_line(line_f), last_line(line_l),
@ -26,7 +30,7 @@ public:
int first_column = 0, last_column = 0; int first_column = 0, last_column = 0;
}; };
#define YYLTYPE yyltype #define YYLTYPE zeek::detail::yyltype
typedef Location yyltype; typedef Location yyltype;
YYLTYPE GetCurrentLocation(); YYLTYPE GetCurrentLocation();
@ -49,9 +53,11 @@ inline void set_location(const Location start, const Location end)
end_location = end; end_location = end;
} }
class BroObj { } // namespace detail
class Obj {
public: public:
BroObj() Obj()
{ {
// A bit of a hack. We'd like to associate location // A bit of a hack. We'd like to associate location
// information with every object created when parsing, // information with every object created when parsing,
@ -67,23 +73,23 @@ public:
// of 0, which should only happen if it's been assigned // of 0, which should only happen if it's been assigned
// to no_location (or hasn't been initialized at all). // to no_location (or hasn't been initialized at all).
location = nullptr; location = nullptr;
if ( start_location.first_line != 0 ) if ( detail::start_location.first_line != 0 )
SetLocationInfo(&start_location, &end_location); SetLocationInfo(&detail::start_location, &detail::end_location);
} }
virtual ~BroObj(); virtual ~Obj();
/* disallow copying */ /* disallow copying */
BroObj(const BroObj &) = delete; Obj(const Obj &) = delete;
BroObj &operator=(const BroObj &) = delete; Obj &operator=(const Obj &) = delete;
// Report user warnings/errors. If obj2 is given, then it's // Report user warnings/errors. If obj2 is given, then it's
// included in the message, though if pinpoint_only is non-zero, // included in the message, though if pinpoint_only is non-zero,
// then obj2 is only used to pinpoint the location. // then obj2 is only used to pinpoint the location.
void Warn(const char* msg, const BroObj* obj2 = nullptr, void Warn(const char* msg, const Obj* obj2 = nullptr,
bool pinpoint_only = false, const Location* expr_location = nullptr) const; bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const;
void Error(const char* msg, const BroObj* obj2 = nullptr, void Error(const char* msg, const Obj* obj2 = nullptr,
bool pinpoint_only = false, const Location* expr_location = nullptr) const; bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const;
// Report internal errors. // Report internal errors.
void BadTag(const char* msg, const char* t1 = nullptr, void BadTag(const char* msg, const char* t1 = nullptr,
@ -102,18 +108,18 @@ public:
void AddLocation(ODesc* d) const; void AddLocation(ODesc* d) const;
// Get location info for debugging. // Get location info for debugging.
const Location* GetLocationInfo() const const detail::Location* GetLocationInfo() const
{ return location ? location : &no_location; } { return location ? location : &detail::no_location; }
virtual bool SetLocationInfo(const Location* loc) virtual bool SetLocationInfo(const detail::Location* loc)
{ return SetLocationInfo(loc, loc); } { return SetLocationInfo(loc, loc); }
// Location = range from start to end. // Location = range from start to end.
virtual bool SetLocationInfo(const Location* start, const Location* end); virtual bool SetLocationInfo(const detail::Location* start, const detail::Location* end);
// Set new end-of-location information. This is used to // Set new end-of-location information. This is used to
// extend compound objects such as statement lists. // extend compound objects such as statement lists.
virtual void UpdateLocationEndInfo(const Location& end); virtual void UpdateLocationEndInfo(const detail::Location& end);
// Enable notification of plugins when this objects gets destroyed. // Enable notification of plugins when this objects gets destroyed.
void NotifyPluginsOnDtor() { notify_plugins = true; } void NotifyPluginsOnDtor() { notify_plugins = true; }
@ -124,23 +130,25 @@ public:
// as long as there exist any instances. // as long as there exist any instances.
class SuppressErrors { class SuppressErrors {
public: public:
SuppressErrors() { ++BroObj::suppress_errors; } SuppressErrors() { ++Obj::suppress_errors; }
~SuppressErrors() { --BroObj::suppress_errors; } ~SuppressErrors() { --Obj::suppress_errors; }
}; };
void Print() const;
protected: protected:
Location* location; // all that matters in real estate detail::Location* location; // all that matters in real estate
private: private:
friend class SuppressErrors; friend class SuppressErrors;
void DoMsg(ODesc* d, const char s1[], const BroObj* obj2 = nullptr, void DoMsg(ODesc* d, const char s1[], const Obj* obj2 = nullptr,
bool pinpoint_only = false, const Location* expr_location = nullptr) const; bool pinpoint_only = false, const detail::Location* expr_location = nullptr) const;
void PinPoint(ODesc* d, const BroObj* obj2 = nullptr, void PinPoint(ODesc* d, const Obj* obj2 = nullptr,
bool pinpoint_only = false) const; bool pinpoint_only = false) const;
friend inline void Ref(BroObj* o); friend inline void Ref(Obj* o);
friend inline void Unref(BroObj* o); friend inline void Unref(Obj* o);
bool notify_plugins = false; bool notify_plugins = false;
int ref_cnt = 1; int ref_cnt = 1;
@ -150,19 +158,16 @@ private:
static int suppress_errors; static int suppress_errors;
}; };
// Prints obj to stderr, primarily for debugging. // Sometimes useful when dealing with Obj subclasses that have their
extern void print(const BroObj* obj);
[[noreturn]] extern void bad_ref(int type);
// Sometimes useful when dealing with BroObj subclasses that have their
// own (protected) versions of Error. // own (protected) versions of Error.
inline void Error(const BroObj* o, const char* msg) inline void Error(const Obj* o, const char* msg)
{ {
o->Error(msg); o->Error(msg);
} }
inline void Ref(BroObj* o) [[noreturn]] extern void bad_ref(int type);
inline void Ref(Obj* o)
{ {
if ( ++(o->ref_cnt) <= 1 ) if ( ++(o->ref_cnt) <= 1 )
bad_ref(0); bad_ref(0);
@ -170,7 +175,7 @@ inline void Ref(BroObj* o)
bad_ref(1); bad_ref(1);
} }
inline void Unref(BroObj* o) inline void Unref(Obj* o)
{ {
if ( o && --o->ref_cnt <= 0 ) if ( o && --o->ref_cnt <= 0 )
{ {
@ -179,9 +184,18 @@ inline void Unref(BroObj* o)
delete o; delete o;
// We could do the following if o were passed by reference. // We could do the following if o were passed by reference.
// o = (BroObj*) 0xcd; // o = (Obj*) 0xcd;
} }
} }
// A dict_delete_func that knows to Unref() dictionary entries. // A dict_delete_func that knows to Unref() dictionary entries.
extern void bro_obj_delete_func(void* v); extern void obj_delete_func(void* v);
} // namespace zeek
using Location [[deprecated("Remove in v4.1. Use zeek::detail::Location instead.")]] = zeek::detail::Location;
using yyltype [[deprecated("Remove in v4.1. Use zeek::detail::yyltype instead.")]] = zeek::detail::yyltype;
using BroObj [[deprecated("Remove in v4.1. Use zeek::Obj instead.")]] = zeek::Obj;
[[deprecated("Remove in v4.1. Use zeek::Obj::Print instead.")]]
extern void print(const zeek::Obj* obj);

View file

@ -15,6 +15,8 @@
#include <broker/data.hh> #include <broker/data.hh>
#include <broker/error.hh> #include <broker/error.hh>
namespace zeek {
// Helper to retrieve a broker value out of a broker::vector at a specified // Helper to retrieve a broker value out of a broker::vector at a specified
// index, and casted to the expected destination type. // index, and casted to the expected destination type.
template<typename S, typename V, typename D> template<typename S, typename V, typename D>
@ -37,10 +39,10 @@ OpaqueMgr* OpaqueMgr::mgr()
return &mgr; return &mgr;
} }
OpaqueVal::OpaqueVal(zeek::OpaqueType* t) : OpaqueVal({NewRef{}, t}) OpaqueVal::OpaqueVal(zeek::OpaqueType* t) : OpaqueVal({zeek::NewRef{}, t})
{} {}
OpaqueVal::OpaqueVal(IntrusivePtr<zeek::OpaqueType> t) : Val(std::move(t)) OpaqueVal::OpaqueVal(zeek::OpaqueTypePtr t) : Val(std::move(t))
{} {}
OpaqueVal::~OpaqueVal() OpaqueVal::~OpaqueVal()
@ -58,7 +60,7 @@ const std::string& OpaqueMgr::TypeID(const OpaqueVal* v) const
return x->first; return x->first;
} }
IntrusivePtr<OpaqueVal> OpaqueMgr::Instantiate(const std::string& id) const OpaqueValPtr OpaqueMgr::Instantiate(const std::string& id) const
{ {
auto x = _types.find(id); auto x = _types.find(id);
return x != _types.end() ? (*x->second)() : nullptr; return x != _types.end() ? (*x->second)() : nullptr;
@ -75,7 +77,7 @@ broker::expected<broker::data> OpaqueVal::Serialize() const
return {broker::vector{std::move(type), std::move(*d)}}; return {broker::vector{std::move(type), std::move(*d)}};
} }
IntrusivePtr<OpaqueVal> OpaqueVal::Unserialize(const broker::data& data) OpaqueValPtr OpaqueVal::Unserialize(const broker::data& data)
{ {
auto v = caf::get_if<broker::vector>(&data); auto v = caf::get_if<broker::vector>(&data);
@ -96,7 +98,7 @@ IntrusivePtr<OpaqueVal> OpaqueVal::Unserialize(const broker::data& data)
return val; return val;
} }
broker::expected<broker::data> OpaqueVal::SerializeType(const IntrusivePtr<zeek::Type>& t) broker::expected<broker::data> OpaqueVal::SerializeType(const zeek::TypePtr& t)
{ {
if ( t->InternalType() == zeek::TYPE_INTERNAL_ERROR ) if ( t->InternalType() == zeek::TYPE_INTERNAL_ERROR )
return broker::ec::invalid_data; return broker::ec::invalid_data;
@ -112,7 +114,7 @@ broker::expected<broker::data> OpaqueVal::SerializeType(const IntrusivePtr<zeek:
return {broker::vector{false, static_cast<uint64_t>(t->Tag())}}; return {broker::vector{false, static_cast<uint64_t>(t->Tag())}};
} }
IntrusivePtr<zeek::Type> OpaqueVal::UnserializeType(const broker::data& data) zeek::TypePtr OpaqueVal::UnserializeType(const broker::data& data)
{ {
auto v = caf::get_if<broker::vector>(&data); auto v = caf::get_if<broker::vector>(&data);
if ( ! (v && v->size() == 2) ) if ( ! (v && v->size() == 2) )
@ -128,7 +130,7 @@ IntrusivePtr<zeek::Type> OpaqueVal::UnserializeType(const broker::data& data)
if ( ! name ) if ( ! name )
return nullptr; return nullptr;
const auto& id = global_scope()->Find(*name); const auto& id = zeek::detail::global_scope()->Find(*name);
if ( ! id ) if ( ! id )
return nullptr; return nullptr;
@ -145,7 +147,7 @@ IntrusivePtr<zeek::Type> OpaqueVal::UnserializeType(const broker::data& data)
return zeek::base_type(static_cast<zeek::TypeTag>(*tag)); return zeek::base_type(static_cast<zeek::TypeTag>(*tag));
} }
IntrusivePtr<Val> OpaqueVal::DoClone(CloneState* state) ValPtr OpaqueVal::DoClone(CloneState* state)
{ {
auto d = OpaqueVal::Serialize(); auto d = OpaqueVal::Serialize();
if ( ! d ) if ( ! d )
@ -169,10 +171,10 @@ bool HashVal::Init()
return valid; return valid;
} }
IntrusivePtr<StringVal> HashVal::Get() StringValPtr HashVal::Get()
{ {
if ( ! valid ) if ( ! valid )
return val_mgr->EmptyString(); return zeek::val_mgr->EmptyString();
auto result = DoGet(); auto result = DoGet();
valid = false; valid = false;
@ -200,18 +202,18 @@ bool HashVal::DoFeed(const void*, size_t)
return false; return false;
} }
IntrusivePtr<StringVal> HashVal::DoGet() StringValPtr HashVal::DoGet()
{ {
assert(! "missing implementation of DoGet()"); assert(! "missing implementation of DoGet()");
return val_mgr->EmptyString(); return zeek::val_mgr->EmptyString();
} }
HashVal::HashVal(IntrusivePtr<zeek::OpaqueType> t) : OpaqueVal(std::move(t)) HashVal::HashVal(zeek::OpaqueTypePtr t) : OpaqueVal(std::move(t))
{ {
valid = false; valid = false;
} }
HashVal::HashVal(zeek::OpaqueType* t) : HashVal({NewRef{}, t}) HashVal::HashVal(zeek::OpaqueType* t) : HashVal({zeek::NewRef{}, t})
{} {}
MD5Val::MD5Val() : HashVal(md5_type) MD5Val::MD5Val() : HashVal(md5_type)
@ -228,7 +230,7 @@ void HashVal::digest_one(EVP_MD_CTX* h, const Val* v)
{ {
if ( v->GetType()->Tag() == zeek::TYPE_STRING ) if ( v->GetType()->Tag() == zeek::TYPE_STRING )
{ {
const BroString* str = v->AsString(); const String* str = v->AsString();
hash_update(h, str->Bytes(), str->Len()); hash_update(h, str->Bytes(), str->Len());
} }
else else
@ -239,14 +241,14 @@ void HashVal::digest_one(EVP_MD_CTX* h, const Val* v)
} }
} }
void HashVal::digest_one(EVP_MD_CTX* h, const IntrusivePtr<Val>& v) void HashVal::digest_one(EVP_MD_CTX* h, const ValPtr& v)
{ {
digest_one(h, v.get()); digest_one(h, v.get());
} }
IntrusivePtr<Val> MD5Val::DoClone(CloneState* state) ValPtr MD5Val::DoClone(CloneState* state)
{ {
auto out = make_intrusive<MD5Val>(); auto out = zeek::make_intrusive<MD5Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -275,14 +277,14 @@ bool MD5Val::DoFeed(const void* data, size_t size)
return true; return true;
} }
IntrusivePtr<StringVal> MD5Val::DoGet() StringValPtr MD5Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return val_mgr->EmptyString(); return zeek::val_mgr->EmptyString();
u_char digest[MD5_DIGEST_LENGTH]; u_char digest[MD5_DIGEST_LENGTH];
hash_final(ctx, digest); hash_final(ctx, digest);
return make_intrusive<StringVal>(md5_digest_print(digest)); return zeek::make_intrusive<StringVal>(md5_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(MD5Val) IMPLEMENT_OPAQUE_VALUE(MD5Val)
@ -364,9 +366,9 @@ SHA1Val::~SHA1Val()
EVP_MD_CTX_free(ctx); EVP_MD_CTX_free(ctx);
} }
IntrusivePtr<Val> SHA1Val::DoClone(CloneState* state) ValPtr SHA1Val::DoClone(CloneState* state)
{ {
auto out = make_intrusive<SHA1Val>(); auto out = zeek::make_intrusive<SHA1Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -395,14 +397,14 @@ bool SHA1Val::DoFeed(const void* data, size_t size)
return true; return true;
} }
IntrusivePtr<StringVal> SHA1Val::DoGet() StringValPtr SHA1Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return val_mgr->EmptyString(); return zeek::val_mgr->EmptyString();
u_char digest[SHA_DIGEST_LENGTH]; u_char digest[SHA_DIGEST_LENGTH];
hash_final(ctx, digest); hash_final(ctx, digest);
return make_intrusive<StringVal>(sha1_digest_print(digest)); return zeek::make_intrusive<StringVal>(sha1_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(SHA1Val) IMPLEMENT_OPAQUE_VALUE(SHA1Val)
@ -487,9 +489,9 @@ SHA256Val::~SHA256Val()
EVP_MD_CTX_free(ctx); EVP_MD_CTX_free(ctx);
} }
IntrusivePtr<Val> SHA256Val::DoClone(CloneState* state) ValPtr SHA256Val::DoClone(CloneState* state)
{ {
auto out = make_intrusive<SHA256Val>(); auto out = zeek::make_intrusive<SHA256Val>();
if ( IsValid() ) if ( IsValid() )
{ {
@ -518,14 +520,14 @@ bool SHA256Val::DoFeed(const void* data, size_t size)
return true; return true;
} }
IntrusivePtr<StringVal> SHA256Val::DoGet() StringValPtr SHA256Val::DoGet()
{ {
if ( ! IsValid() ) if ( ! IsValid() )
return val_mgr->EmptyString(); return zeek::val_mgr->EmptyString();
u_char digest[SHA256_DIGEST_LENGTH]; u_char digest[SHA256_DIGEST_LENGTH];
hash_final(ctx, digest); hash_final(ctx, digest);
return make_intrusive<StringVal>(sha256_digest_print(digest)); return zeek::make_intrusive<StringVal>(sha256_digest_print(digest));
} }
IMPLEMENT_OPAQUE_VALUE(SHA256Val) IMPLEMENT_OPAQUE_VALUE(SHA256Val)
@ -711,26 +713,26 @@ BloomFilterVal::BloomFilterVal(probabilistic::BloomFilter* bf)
bloom_filter = bf; bloom_filter = bf;
} }
IntrusivePtr<Val> BloomFilterVal::DoClone(CloneState* state) ValPtr BloomFilterVal::DoClone(CloneState* state)
{ {
if ( bloom_filter ) if ( bloom_filter )
{ {
auto bf = make_intrusive<BloomFilterVal>(bloom_filter->Clone()); auto bf = zeek::make_intrusive<BloomFilterVal>(bloom_filter->Clone());
bf->Typify(type); bf->Typify(type);
return state->NewClone(this, std::move(bf)); return state->NewClone(this, std::move(bf));
} }
return state->NewClone(this, make_intrusive<BloomFilterVal>()); return state->NewClone(this, zeek::make_intrusive<BloomFilterVal>());
} }
bool BloomFilterVal::Typify(IntrusivePtr<zeek::Type> arg_type) bool BloomFilterVal::Typify(zeek::TypePtr arg_type)
{ {
if ( type ) if ( type )
return false; return false;
type = std::move(arg_type); type = std::move(arg_type);
auto tl = make_intrusive<zeek::TypeList>(type); auto tl = zeek::make_intrusive<zeek::TypeList>(type);
tl->Append(type); tl->Append(type);
hash = new CompositeHash(std::move(tl)); hash = new CompositeHash(std::move(tl));
@ -765,8 +767,8 @@ std::string BloomFilterVal::InternalState() const
return bloom_filter->InternalState(); return bloom_filter->InternalState();
} }
IntrusivePtr<BloomFilterVal> BloomFilterVal::Merge(const BloomFilterVal* x, BloomFilterValPtr BloomFilterVal::Merge(const BloomFilterVal* x,
const BloomFilterVal* y) const BloomFilterVal* y)
{ {
if ( x->Type() && // any one 0 is ok here if ( x->Type() && // any one 0 is ok here
y->Type() && y->Type() &&
@ -791,7 +793,7 @@ IntrusivePtr<BloomFilterVal> BloomFilterVal::Merge(const BloomFilterVal* x,
return nullptr; return nullptr;
} }
auto merged = make_intrusive<BloomFilterVal>(copy); auto merged = zeek::make_intrusive<BloomFilterVal>(copy);
if ( x->Type() && ! merged->Typify(x->Type()) ) if ( x->Type() && ! merged->Typify(x->Type()) )
{ {
@ -876,20 +878,20 @@ CardinalityVal::~CardinalityVal()
delete hash; delete hash;
} }
IntrusivePtr<Val> CardinalityVal::DoClone(CloneState* state) ValPtr CardinalityVal::DoClone(CloneState* state)
{ {
return state->NewClone(this, return state->NewClone(this,
make_intrusive<CardinalityVal>(new probabilistic::CardinalityCounter(*c))); zeek::make_intrusive<CardinalityVal>(new probabilistic::CardinalityCounter(*c)));
} }
bool CardinalityVal::Typify(IntrusivePtr<zeek::Type> arg_type) bool CardinalityVal::Typify(zeek::TypePtr arg_type)
{ {
if ( type ) if ( type )
return false; return false;
type = std::move(arg_type); type = std::move(arg_type);
auto tl = make_intrusive<zeek::TypeList>(type); auto tl = zeek::make_intrusive<zeek::TypeList>(type);
tl->Append(type); tl->Append(type);
hash = new CompositeHash(std::move(tl)); hash = new CompositeHash(std::move(tl));
@ -957,14 +959,14 @@ ParaglobVal::ParaglobVal(std::unique_ptr<paraglob::Paraglob> p)
this->internal_paraglob = std::move(p); this->internal_paraglob = std::move(p);
} }
IntrusivePtr<VectorVal> ParaglobVal::Get(StringVal* &pattern) VectorValPtr ParaglobVal::Get(StringVal* &pattern)
{ {
auto rval = make_intrusive<VectorVal>(zeek::id::string_vec); auto rval = zeek::make_intrusive<VectorVal>(zeek::id::string_vec);
std::string string_pattern (reinterpret_cast<const char*>(pattern->Bytes()), pattern->Len()); std::string string_pattern (reinterpret_cast<const char*>(pattern->Bytes()), pattern->Len());
std::vector<std::string> matches = this->internal_paraglob->get(string_pattern); std::vector<std::string> matches = this->internal_paraglob->get(string_pattern);
for (unsigned int i = 0; i < matches.size(); i++) for (unsigned int i = 0; i < matches.size(); i++)
rval->Assign(i, make_intrusive<StringVal>(matches.at(i))); rval->Assign(i, zeek::make_intrusive<StringVal>(matches.at(i)));
return rval; return rval;
} }
@ -1018,10 +1020,10 @@ bool ParaglobVal::DoUnserialize(const broker::data& data)
return true; return true;
} }
IntrusivePtr<Val> ParaglobVal::DoClone(CloneState* state) ValPtr ParaglobVal::DoClone(CloneState* state)
{ {
try { try {
return make_intrusive<ParaglobVal> return zeek::make_intrusive<ParaglobVal>
(std::make_unique<paraglob::Paraglob>(this->internal_paraglob->serialize())); (std::make_unique<paraglob::Paraglob>(this->internal_paraglob->serialize()));
} }
catch (const paraglob::underflow_error& e) catch (const paraglob::underflow_error& e)
@ -1035,3 +1037,5 @@ IntrusivePtr<Val> ParaglobVal::DoClone(CloneState* state)
return nullptr; return nullptr;
} }
} }
}

View file

@ -13,7 +13,19 @@
#include <sys/types.h> // for u_char #include <sys/types.h> // for u_char
namespace broker { class data; } namespace broker { class data; }
namespace probabilistic {
class BloomFilter;
class CardinalityCounter;
}
namespace zeek {
class OpaqueVal; class OpaqueVal;
using OpaqueValPtr = zeek::IntrusivePtr<OpaqueVal>;
class BloomFilterVal;
using BloomFilterValPtr = zeek::IntrusivePtr<BloomFilterVal>;
/** /**
* Singleton that registers all available all available types of opaque * Singleton that registers all available all available types of opaque
@ -21,7 +33,7 @@ class OpaqueVal;
*/ */
class OpaqueMgr { class OpaqueMgr {
public: public:
using Factory = IntrusivePtr<OpaqueVal> (); using Factory = OpaqueValPtr ();
/** /**
* Return's a unique ID for the type of an opaque value. * Return's a unique ID for the type of an opaque value.
@ -45,7 +57,7 @@ public:
* is unknown, this will return null. * is unknown, this will return null.
* *
*/ */
IntrusivePtr<OpaqueVal> Instantiate(const std::string& id) const; OpaqueValPtr Instantiate(const std::string& id) const;
/** Returns the global manager singleton object. */ /** Returns the global manager singleton object. */
static OpaqueMgr* mgr(); static OpaqueMgr* mgr();
@ -67,18 +79,18 @@ private:
/** Macro to insert into an OpaqueVal-derived class's declaration. */ /** Macro to insert into an OpaqueVal-derived class's declaration. */
#define DECLARE_OPAQUE_VALUE(T) \ #define DECLARE_OPAQUE_VALUE(T) \
friend class OpaqueMgr::Register<T>; \ friend class zeek::OpaqueMgr::Register<T>; \
friend IntrusivePtr<T> make_intrusive<T>(); \ friend zeek::IntrusivePtr<T> zeek::make_intrusive<T>(); \
broker::expected<broker::data> DoSerialize() const override; \ broker::expected<broker::data> DoSerialize() const override; \
bool DoUnserialize(const broker::data& data) override; \ bool DoUnserialize(const broker::data& data) override; \
const char* OpaqueName() const override { return #T; } \ const char* OpaqueName() const override { return #T; } \
static IntrusivePtr<OpaqueVal> OpaqueInstantiate() { return make_intrusive<T>(); } static zeek::OpaqueValPtr OpaqueInstantiate() { return zeek::make_intrusive<T>(); }
#define __OPAQUE_MERGE(a, b) a ## b #define __OPAQUE_MERGE(a, b) a ## b
#define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x) #define __OPAQUE_ID(x) __OPAQUE_MERGE(_opaque, x)
/** Macro to insert into an OpaqueVal-derived class's implementation file. */ /** Macro to insert into an OpaqueVal-derived class's implementation file. */
#define IMPLEMENT_OPAQUE_VALUE(T) static OpaqueMgr::Register<T> __OPAQUE_ID(__LINE__)(#T); #define IMPLEMENT_OPAQUE_VALUE(T) static zeek::OpaqueMgr::Register<T> __OPAQUE_ID(__LINE__)(#T);
/** /**
* Base class for all opaque values. Opaque values are types that are managed * Base class for all opaque values. Opaque values are types that are managed
@ -89,7 +101,7 @@ class OpaqueVal : public Val {
public: public:
[[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]]
explicit OpaqueVal(zeek::OpaqueType* t); explicit OpaqueVal(zeek::OpaqueType* t);
explicit OpaqueVal(IntrusivePtr<zeek::OpaqueType> t); explicit OpaqueVal(zeek::OpaqueTypePtr t);
~OpaqueVal() override; ~OpaqueVal() override;
/** /**
@ -106,7 +118,7 @@ public:
* @param data Broker representation as returned by *Serialize()*. * @param data Broker representation as returned by *Serialize()*.
* @return unserialized instances with reference count at +1 * @return unserialized instances with reference count at +1
*/ */
static IntrusivePtr<OpaqueVal> Unserialize(const broker::data& data); static OpaqueValPtr Unserialize(const broker::data& data);
protected: protected:
friend class Val; friend class Val;
@ -142,26 +154,21 @@ protected:
* may also override this with a more efficient custom clone * may also override this with a more efficient custom clone
* implementation of their own. * implementation of their own.
*/ */
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
/** /**
* Helper function for derived class that need to record a type * Helper function for derived class that need to record a type
* during serialization. * during serialization.
*/ */
static broker::expected<broker::data> SerializeType(const IntrusivePtr<zeek::Type>& t); static broker::expected<broker::data> SerializeType(const zeek::TypePtr& t);
/** /**
* Helper function for derived class that need to restore a type * Helper function for derived class that need to restore a type
* during unserialization. Returns the type at reference count +1. * during unserialization. Returns the type at reference count +1.
*/ */
static IntrusivePtr<zeek::Type> UnserializeType(const broker::data& data); static zeek::TypePtr UnserializeType(const broker::data& data);
}; };
namespace probabilistic {
class BloomFilter;
class CardinalityCounter;
}
class HashVal : public OpaqueVal { class HashVal : public OpaqueVal {
public: public:
template <class T> template <class T>
@ -178,21 +185,21 @@ public:
bool IsValid() const; bool IsValid() const;
bool Init(); bool Init();
bool Feed(const void* data, size_t size); bool Feed(const void* data, size_t size);
IntrusivePtr<StringVal> Get(); StringValPtr Get();
protected: protected:
static void digest_one(EVP_MD_CTX* h, const Val* v); static void digest_one(EVP_MD_CTX* h, const Val* v);
static void digest_one(EVP_MD_CTX* h, const IntrusivePtr<Val>& v); static void digest_one(EVP_MD_CTX* h, const ValPtr& v);
HashVal() { valid = false; } HashVal() { valid = false; }
[[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]]
explicit HashVal(zeek::OpaqueType* t); explicit HashVal(zeek::OpaqueType* t);
explicit HashVal(IntrusivePtr<zeek::OpaqueType> t); explicit HashVal(zeek::OpaqueTypePtr t);
virtual bool DoInit(); virtual bool DoInit();
virtual bool DoFeed(const void* data, size_t size); virtual bool DoFeed(const void* data, size_t size);
virtual IntrusivePtr<StringVal> DoGet(); virtual StringValPtr DoGet();
private: private:
// This flag exists because Get() can only be called once. // This flag exists because Get() can only be called once.
@ -221,14 +228,14 @@ public:
MD5Val(); MD5Val();
~MD5Val(); ~MD5Val();
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
protected: protected:
friend class Val; friend class Val;
bool DoInit() override; bool DoInit() override;
bool DoFeed(const void* data, size_t size) override; bool DoFeed(const void* data, size_t size) override;
IntrusivePtr<StringVal> DoGet() override; StringValPtr DoGet() override;
DECLARE_OPAQUE_VALUE(MD5Val) DECLARE_OPAQUE_VALUE(MD5Val)
private: private:
@ -244,14 +251,14 @@ public:
SHA1Val(); SHA1Val();
~SHA1Val(); ~SHA1Val();
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
protected: protected:
friend class Val; friend class Val;
bool DoInit() override; bool DoInit() override;
bool DoFeed(const void* data, size_t size) override; bool DoFeed(const void* data, size_t size) override;
IntrusivePtr<StringVal> DoGet() override; StringValPtr DoGet() override;
DECLARE_OPAQUE_VALUE(SHA1Val) DECLARE_OPAQUE_VALUE(SHA1Val)
private: private:
@ -267,14 +274,14 @@ public:
SHA256Val(); SHA256Val();
~SHA256Val(); ~SHA256Val();
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
protected: protected:
friend class Val; friend class Val;
bool DoInit() override; bool DoInit() override;
bool DoFeed(const void* data, size_t size) override; bool DoFeed(const void* data, size_t size) override;
IntrusivePtr<StringVal> DoGet() override; StringValPtr DoGet() override;
DECLARE_OPAQUE_VALUE(SHA256Val) DECLARE_OPAQUE_VALUE(SHA256Val)
private: private:
@ -302,12 +309,12 @@ public:
explicit BloomFilterVal(probabilistic::BloomFilter* bf); explicit BloomFilterVal(probabilistic::BloomFilter* bf);
~BloomFilterVal() override; ~BloomFilterVal() override;
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
const IntrusivePtr<zeek::Type>& Type() const const zeek::TypePtr& Type() const
{ return type; } { return type; }
bool Typify(IntrusivePtr<zeek::Type> type); bool Typify(zeek::TypePtr type);
void Add(const Val* val); void Add(const Val* val);
size_t Count(const Val* val) const; size_t Count(const Val* val) const;
@ -315,8 +322,8 @@ public:
bool Empty() const; bool Empty() const;
std::string InternalState() const; std::string InternalState() const;
static IntrusivePtr<BloomFilterVal> Merge(const BloomFilterVal* x, static BloomFilterValPtr Merge(const BloomFilterVal* x,
const BloomFilterVal* y); const BloomFilterVal* y);
protected: protected:
friend class Val; friend class Val;
@ -328,25 +335,25 @@ private:
BloomFilterVal(const BloomFilterVal&); BloomFilterVal(const BloomFilterVal&);
BloomFilterVal& operator=(const BloomFilterVal&); BloomFilterVal& operator=(const BloomFilterVal&);
IntrusivePtr<zeek::Type> type; zeek::TypePtr type;
CompositeHash* hash; CompositeHash* hash;
probabilistic::BloomFilter* bloom_filter; probabilistic::BloomFilter* bloom_filter;
}; };
class CardinalityVal: public OpaqueVal { class CardinalityVal : public OpaqueVal {
public: public:
explicit CardinalityVal(probabilistic::CardinalityCounter*); explicit CardinalityVal(probabilistic::CardinalityCounter*);
~CardinalityVal() override; ~CardinalityVal() override;
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
void Add(const Val* val); void Add(const Val* val);
const IntrusivePtr<zeek::Type>& Type() const const zeek::TypePtr& Type() const
{ return type; } { return type; }
bool Typify(IntrusivePtr<zeek::Type> type); bool Typify(zeek::TypePtr type);
probabilistic::CardinalityCounter* Get() { return c; }; probabilistic::CardinalityCounter* Get() { return c; };
@ -355,7 +362,7 @@ protected:
DECLARE_OPAQUE_VALUE(CardinalityVal) DECLARE_OPAQUE_VALUE(CardinalityVal)
private: private:
IntrusivePtr<zeek::Type> type; zeek::TypePtr type;
CompositeHash* hash; CompositeHash* hash;
probabilistic::CardinalityCounter* c; probabilistic::CardinalityCounter* c;
}; };
@ -363,8 +370,8 @@ private:
class ParaglobVal : public OpaqueVal { class ParaglobVal : public OpaqueVal {
public: public:
explicit ParaglobVal(std::unique_ptr<paraglob::Paraglob> p); explicit ParaglobVal(std::unique_ptr<paraglob::Paraglob> p);
IntrusivePtr<VectorVal> Get(StringVal* &pattern); VectorValPtr Get(StringVal* &pattern);
IntrusivePtr<Val> DoClone(CloneState* state) override; ValPtr DoClone(CloneState* state) override;
bool operator==(const ParaglobVal& other) const; bool operator==(const ParaglobVal& other) const;
protected: protected:
@ -375,3 +382,16 @@ protected:
private: private:
std::unique_ptr<paraglob::Paraglob> internal_paraglob; std::unique_ptr<paraglob::Paraglob> internal_paraglob;
}; };
}
using OpaqueMgr [[deprecated("Remove in v4.1. Use zeek::OpaqueMgr instead.")]] = zeek::OpaqueMgr;
using OpaqueVal [[deprecated("Remove in v4.1. Use zeek::OpaqueVal instead.")]] = zeek::OpaqueVal;
using HashVal [[deprecated("Remove in v4.1. Use zeek::HashVal instead.")]] = zeek::HashVal;
using MD5Val [[deprecated("Remove in v4.1. Use zeek::MD5Val instead.")]] = zeek::MD5Val;
using SHA1Val [[deprecated("Remove in v4.1. Use zeek::SHA1Val instead.")]] = zeek::SHA1Val;
using SHA256Val [[deprecated("Remove in v4.1. Use zeek::SHA256Val instead.")]] = zeek::SHA256Val;
using EntropyVal [[deprecated("Remove in v4.1. Use zeek::EntropyVal instead.")]] = zeek::EntropyVal;
using BloomFilterVal [[deprecated("Remove in v4.1. Use zeek::BloomFilterVal instead.")]] = zeek::BloomFilterVal;
using CardinalityVal [[deprecated("Remove in v4.1. Use zeek::CardinalityVal instead.")]] = zeek::CardinalityVal;
using ParaglobVal [[deprecated("Remove in v4.1. Use zeek::ParaglobVal instead.")]] = zeek::ParaglobVal;

View file

@ -23,7 +23,7 @@ void PacketFilter::AddSrc(const IPAddr& src, uint32_t tcp_flags, double probabil
delete prev; delete prev;
} }
void PacketFilter::AddSrc(Val* src, uint32_t tcp_flags, double probability) void PacketFilter::AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability)
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
@ -41,7 +41,7 @@ void PacketFilter::AddDst(const IPAddr& dst, uint32_t tcp_flags, double probabil
delete prev; delete prev;
} }
void PacketFilter::AddDst(Val* dst, uint32_t tcp_flags, double probability) void PacketFilter::AddDst(zeek::Val* dst, uint32_t tcp_flags, double probability)
{ {
Filter* f = new Filter; Filter* f = new Filter;
f->tcp_flags = tcp_flags; f->tcp_flags = tcp_flags;
@ -57,7 +57,7 @@ bool PacketFilter::RemoveSrc(const IPAddr& src)
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::RemoveSrc(Val* src) bool PacketFilter::RemoveSrc(zeek::Val* src)
{ {
auto f = static_cast<Filter*>(src_filter.Remove(src)); auto f = static_cast<Filter*>(src_filter.Remove(src));
delete f; delete f;
@ -71,7 +71,7 @@ bool PacketFilter::RemoveDst(const IPAddr& dst)
return f != nullptr; return f != nullptr;
} }
bool PacketFilter::RemoveDst(Val* dst) bool PacketFilter::RemoveDst(zeek::Val* dst)
{ {
auto f = static_cast<Filter*>(dst_filter.Remove(dst)); auto f = static_cast<Filter*>(dst_filter.Remove(dst));
delete f; delete f;

View file

@ -6,7 +6,7 @@
#include "PrefixTable.h" #include "PrefixTable.h"
class IP_Hdr; class IP_Hdr;
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
class PacketFilter { class PacketFilter {
public: public:
@ -17,16 +17,16 @@ public:
// as an AddrVal or a SubnetVal) which hasn't any of TCP flags set // as an AddrVal or a SubnetVal) which hasn't any of TCP flags set
// (TH_*) with the given probability (from 0..MAX_PROB). // (TH_*) with the given probability (from 0..MAX_PROB).
void AddSrc(const IPAddr& src, uint32_t tcp_flags, double probability); void AddSrc(const IPAddr& src, uint32_t tcp_flags, double probability);
void AddSrc(Val* src, uint32_t tcp_flags, double probability); void AddSrc(zeek::Val* src, uint32_t tcp_flags, double probability);
void AddDst(const IPAddr& src, uint32_t tcp_flags, double probability); void AddDst(const IPAddr& src, uint32_t tcp_flags, double probability);
void AddDst(Val* src, uint32_t tcp_flags, double probability); void AddDst(zeek::Val* src, uint32_t tcp_flags, double probability);
// Removes the filter entry for the given src/dst // Removes the filter entry for the given src/dst
// Returns false if filter doesn not exist. // Returns false if filter doesn not exist.
bool RemoveSrc(const IPAddr& src); bool RemoveSrc(const IPAddr& src);
bool RemoveSrc(Val* dst); bool RemoveSrc(zeek::Val* dst);
bool RemoveDst(const IPAddr& dst); bool RemoveDst(const IPAddr& dst);
bool RemoveDst(Val* dst); bool RemoveDst(zeek::Val* dst);
// Returns true if packet matches a drop filter // Returns true if packet matches a drop filter
bool Match(const IP_Hdr* ip, int len, int caplen); bool Match(const IP_Hdr* ip, int len, int caplen);

View file

@ -40,7 +40,7 @@ void* PrefixTable::Insert(const IPAddr& addr, int width, void* data)
return old; return old;
} }
void* PrefixTable::Insert(const Val* value, void* data) void* PrefixTable::Insert(const zeek::Val* value, void* data)
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == zeek::TYPE_LIST &&
@ -81,7 +81,7 @@ std::list<std::tuple<IPPrefix,void*>> PrefixTable::FindAll(const IPAddr& addr, i
return out; return out;
} }
std::list<std::tuple<IPPrefix,void*>> PrefixTable::FindAll(const SubNetVal* value) const std::list<std::tuple<IPPrefix,void*>> PrefixTable::FindAll(const zeek::SubNetVal* value) const
{ {
return FindAll(value->AsSubNet().Prefix(), value->AsSubNet().LengthIPv6()); return FindAll(value->AsSubNet().Prefix(), value->AsSubNet().LengthIPv6());
} }
@ -100,7 +100,7 @@ void* PrefixTable::Lookup(const IPAddr& addr, int width, bool exact) const
return node ? node->data : nullptr; return node ? node->data : nullptr;
} }
void* PrefixTable::Lookup(const Val* value, bool exact) const void* PrefixTable::Lookup(const zeek::Val* value, bool exact) const
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == zeek::TYPE_LIST &&
@ -139,7 +139,7 @@ void* PrefixTable::Remove(const IPAddr& addr, int width)
return old; return old;
} }
void* PrefixTable::Remove(const Val* value) void* PrefixTable::Remove(const zeek::Val* value)
{ {
// [elem] -> elem // [elem] -> elem
if ( value->GetType()->Tag() == zeek::TYPE_LIST && if ( value->GetType()->Tag() == zeek::TYPE_LIST &&

View file

@ -8,8 +8,8 @@ extern "C" {
#include "IPAddr.h" #include "IPAddr.h"
class Val; ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
class SubNetVal; ZEEK_FORWARD_DECLARE_NAMESPACED(SubNetVal, zeek);
class PrefixTable { class PrefixTable {
private: private:
@ -30,21 +30,21 @@ public:
void* Insert(const IPAddr& addr, int width, void* data = nullptr); void* Insert(const IPAddr& addr, int width, void* data = nullptr);
// Value may be addr or subnet. // Value may be addr or subnet.
void* Insert(const Val* value, void* data = nullptr); void* Insert(const zeek::Val* value, void* data = nullptr);
// Returns nil if not found, pointer to data otherwise. // Returns nil if not found, pointer to data otherwise.
// For items without data, returns non-nil if found. // For items without data, returns non-nil if found.
// If exact is false, performs exact rather than longest-prefix match. // If exact is false, performs exact rather than longest-prefix match.
void* Lookup(const IPAddr& addr, int width, bool exact = false) const; void* Lookup(const IPAddr& addr, int width, bool exact = false) const;
void* Lookup(const Val* value, bool exact = false) const; void* Lookup(const zeek::Val* value, bool exact = false) const;
// Returns list of all found matches or empty list otherwise. // Returns list of all found matches or empty list otherwise.
std::list<std::tuple<IPPrefix,void*>> FindAll(const IPAddr& addr, int width) const; std::list<std::tuple<IPPrefix,void*>> FindAll(const IPAddr& addr, int width) const;
std::list<std::tuple<IPPrefix,void*>> FindAll(const SubNetVal* value) const; std::list<std::tuple<IPPrefix,void*>> FindAll(const zeek::SubNetVal* value) const;
// Returns pointer to data or nil if not found. // Returns pointer to data or nil if not found.
void* Remove(const IPAddr& addr, int width); void* Remove(const IPAddr& addr, int width);
void* Remove(const Val* value); void* Remove(const zeek::Val* value);
void Clear() { Clear_Patricia(tree, delete_function); } void Clear() { Clear_Patricia(tree, delete_function); }

View file

@ -2,6 +2,7 @@
#pragma once #pragma once
#include <string.h>
#include <iterator> #include <iterator>
// Queue.h -- // Queue.h --
@ -22,6 +23,7 @@
// Entries must be either a pointer to the data or nonzero data with // Entries must be either a pointer to the data or nonzero data with
// sizeof(data) <= sizeof(void*). // sizeof(data) <= sizeof(void*).
namespace zeek {
template<typename T> template<typename T>
class Queue { class Queue {
@ -196,3 +198,8 @@ protected:
template<typename T> template<typename T>
using PQueue = Queue<T*>; using PQueue = Queue<T*>;
} // namespace zeek
template<typename T> using Queue [[deprecated("Remove in v4.1. Use zeek::Queue instead.")]] = zeek::Queue<T>;
template<typename T> using PQueue [[deprecated("Remove in v4.1. Use zeek::Queue instead.")]] = zeek::PQueue<T>;

View file

@ -10,7 +10,7 @@
#include "CCL.h" #include "CCL.h"
#include "EquivClass.h" #include "EquivClass.h"
#include "Reporter.h" #include "Reporter.h"
#include "BroString.h" #include "ZeekString.h"
CCL* curr_ccl = nullptr; CCL* curr_ccl = nullptr;
@ -209,7 +209,7 @@ bool Specific_RE_Matcher::MatchAll(const char* s)
return MatchAll((const u_char*)(s), strlen(s)); return MatchAll((const u_char*)(s), strlen(s));
} }
bool Specific_RE_Matcher::MatchAll(const BroString* s) bool Specific_RE_Matcher::MatchAll(const zeek::String* s)
{ {
// s->Len() does not include '\0'. // s->Len() does not include '\0'.
return MatchAll(s->Bytes(), s->Len()); return MatchAll(s->Bytes(), s->Len());
@ -220,7 +220,7 @@ int Specific_RE_Matcher::Match(const char* s)
return Match((const u_char*)(s), strlen(s)); return Match((const u_char*)(s), strlen(s));
} }
int Specific_RE_Matcher::Match(const BroString* s) int Specific_RE_Matcher::Match(const zeek::String* s)
{ {
return Match(s->Bytes(), s->Len()); return Match(s->Bytes(), s->Len());
} }
@ -230,7 +230,7 @@ int Specific_RE_Matcher::LongestMatch(const char* s)
return LongestMatch((const u_char*)(s), strlen(s)); return LongestMatch((const u_char*)(s), strlen(s));
} }
int Specific_RE_Matcher::LongestMatch(const BroString* s) int Specific_RE_Matcher::LongestMatch(const zeek::String* s)
{ {
return LongestMatch(s->Bytes(), s->Len()); return LongestMatch(s->Bytes(), s->Len());
} }

View file

@ -14,13 +14,15 @@
#include <ctype.h> #include <ctype.h>
typedef int (*cce_func)(int); typedef int (*cce_func)(int);
namespace zeek { class String; }
using BroString [[deprecated("Remove in v4.1. Use zeek::String instead.")]] = zeek::String;
class CCL; class CCL;
class NFA_Machine; class NFA_Machine;
class DFA_Machine; class DFA_Machine;
class Specific_RE_Matcher; class Specific_RE_Matcher;
class RE_Matcher; class RE_Matcher;
class DFA_State; class DFA_State;
class BroString;
extern int case_insensitive; extern int case_insensitive;
extern CCL* curr_ccl; extern CCL* curr_ccl;
@ -36,7 +38,7 @@ typedef int AcceptIdx;
typedef std::set<AcceptIdx> AcceptingSet; typedef std::set<AcceptIdx> AcceptingSet;
typedef uint64_t MatchPos; typedef uint64_t MatchPos;
typedef std::map<AcceptIdx, MatchPos> AcceptingMatchSet; typedef std::map<AcceptIdx, MatchPos> AcceptingMatchSet;
typedef name_list string_list; typedef zeek::name_list string_list;
typedef enum { MATCH_ANYWHERE, MATCH_EXACTLY, } match_type; typedef enum { MATCH_ANYWHERE, MATCH_EXACTLY, } match_type;
@ -81,7 +83,7 @@ public:
void ConvertCCLs(); void ConvertCCLs();
bool MatchAll(const char* s); bool MatchAll(const char* s);
bool MatchAll(const BroString* s); bool MatchAll(const zeek::String* s);
// Compiles a set of regular expressions simultaniously. // Compiles a set of regular expressions simultaniously.
// 'idx' contains indizes associated with the expressions. // 'idx' contains indizes associated with the expressions.
@ -94,10 +96,10 @@ public:
// if the pattern matches empty strings, matching continues // if the pattern matches empty strings, matching continues
// in an attempt to match at least one character. // in an attempt to match at least one character.
int Match(const char* s); int Match(const char* s);
int Match(const BroString* s); int Match(const zeek::String* s);
int LongestMatch(const char* s); int LongestMatch(const char* s);
int LongestMatch(const BroString* s); int LongestMatch(const zeek::String* s);
int LongestMatch(const u_char* bv, int n); int LongestMatch(const u_char* bv, int n);
EquivClass* EC() { return &equiv_class; } EquivClass* EC() { return &equiv_class; }
@ -128,7 +130,7 @@ protected:
std::map<std::string, std::string> defs; std::map<std::string, std::string> defs;
std::map<std::string, CCL*> ccl_dict; std::map<std::string, CCL*> ccl_dict;
PList<CCL> ccl_list; zeek::PList<CCL> ccl_list;
EquivClass equiv_class; EquivClass equiv_class;
int* ecs; int* ecs;
DFA_Machine* dfa; DFA_Machine* dfa;
@ -191,7 +193,7 @@ public:
// Returns true if s exactly matches the pattern, false otherwise. // Returns true if s exactly matches the pattern, false otherwise.
bool MatchExactly(const char* s) bool MatchExactly(const char* s)
{ return re_exact->MatchAll(s); } { return re_exact->MatchAll(s); }
bool MatchExactly(const BroString* s) bool MatchExactly(const zeek::String* s)
{ return re_exact->MatchAll(s); } { return re_exact->MatchAll(s); }
// Returns the position in s just beyond where the first match // Returns the position in s just beyond where the first match
@ -200,14 +202,14 @@ public:
// in an attempt to match at least one character. // in an attempt to match at least one character.
int MatchAnywhere(const char* s) int MatchAnywhere(const char* s)
{ return re_anywhere->Match(s); } { return re_anywhere->Match(s); }
int MatchAnywhere(const BroString* s) int MatchAnywhere(const zeek::String* s)
{ return re_anywhere->Match(s); } { return re_anywhere->Match(s); }
// Note: it matches the *longest* prefix and returns the // Note: it matches the *longest* prefix and returns the
// length of matched prefix. It returns -1 on mismatch. // length of matched prefix. It returns -1 on mismatch.
int MatchPrefix(const char* s) int MatchPrefix(const char* s)
{ return re_exact->LongestMatch(s); } { return re_exact->LongestMatch(s); }
int MatchPrefix(const BroString* s) int MatchPrefix(const zeek::String* s)
{ return re_exact->LongestMatch(s); } { return re_exact->LongestMatch(s); }
int MatchPrefix(const u_char* s, int n) int MatchPrefix(const u_char* s, int n)
{ return re_exact->LongestMatch(s, n); } { return re_exact->LongestMatch(s, n); }

View file

@ -1,30 +1,31 @@
#pragma once #pragma once
#include "zeek-config.h"
#include <stdint.h> #include <stdint.h>
#define RT_MONTEN 6 /* Bytes used as Monte Carlo #define RT_MONTEN 6 /* Bytes used as Monte Carlo
co-ordinates. This should be no more co-ordinates. This should be no more
bits than the mantissa of your "double" bits than the mantissa of your "double"
floating point type. */ floating point type. */
class EntropyVal;
ZEEK_FORWARD_DECLARE_NAMESPACED(EntropyVal, zeek);
class RandTest { class RandTest {
public: public:
RandTest(); RandTest();
void add(const void* buf, int bufl); void add(const void* buf, int bufl);
void end(double* r_ent, double* r_chisq, double* r_mean, void end(double* r_ent, double* r_chisq, double* r_mean,
double* r_montepicalc, double* r_scc); double* r_montepicalc, double* r_scc);
private: private:
friend class EntropyVal; friend class zeek::EntropyVal;
int64_t ccount[256]; /* Bins to count occurrences of values */ int64_t ccount[256]; /* Bins to count occurrences of values */
int64_t totalc; /* Total bytes counted */ int64_t totalc; /* Total bytes counted */
int mp; int mp;
int sccfirst; int sccfirst;
unsigned int monte[RT_MONTEN]; unsigned int monte[RT_MONTEN];
int64_t inmont, mcount; int64_t inmont, mcount;
double cexp, montex, montey, montepi, double cexp, montex, montey, montepi,
sccu0, scclast, scct1, scct2, scct3; sccu0, scclast, scct1, scct2, scct3;
}; };

View file

@ -251,7 +251,7 @@ private:
DataBlockMap block_map; DataBlockMap block_map;
}; };
class Reassembler : public BroObj { class Reassembler : public zeek::Obj {
public: public:
Reassembler(uint64_t init_seq, ReassemblerType reassem_type = REASSEM_UNKNOWN); Reassembler(uint64_t init_seq, ReassemblerType reassem_type = REASSEM_UNKNOWN);
~Reassembler() override {} ~Reassembler() override {}

View file

@ -73,8 +73,8 @@ void Reporter::InitOptions()
auto wl_table = wl_val->AsTable(); auto wl_table = wl_val->AsTable();
HashKey* k; HashKey* k;
IterCookie* c = wl_table->InitForIteration(); zeek::IterCookie* c = wl_table->InitForIteration();
TableEntryVal* v; zeek::TableEntryVal* v;
while ( (v = wl_table->NextEntry(k, c)) ) while ( (v = wl_table->NextEntry(k, c)) )
{ {
@ -165,7 +165,7 @@ void Reporter::ExprRuntimeError(const zeek::detail::Expr* expr, const char* fmt,
throw InterpreterException(); throw InterpreterException();
} }
void Reporter::RuntimeError(const Location* location, const char* fmt, ...) void Reporter::RuntimeError(const zeek::detail::Location* location, const char* fmt, ...)
{ {
++errors; ++errors;
PushLocation(location); PushLocation(location);
@ -345,7 +345,7 @@ bool Reporter::PermitFlowWeird(const char* name,
return false; return false;
} }
bool Reporter::PermitExpiredConnWeird(const char* name, const RecordVal& conn_id) bool Reporter::PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id)
{ {
auto conn_tuple = std::make_tuple(conn_id.GetField("orig_h")->AsAddr(), auto conn_tuple = std::make_tuple(conn_id.GetField("orig_h")->AsAddr(),
conn_id.GetField("resp_h")->AsAddr(), conn_id.GetField("resp_h")->AsAddr(),
@ -384,7 +384,7 @@ void Reporter::Weird(const char* name, const char* addl)
return; return;
} }
WeirdHelper(net_weird, {new StringVal(addl)}, "%s", name); WeirdHelper(net_weird, {new zeek::StringVal(addl)}, "%s", name);
} }
void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl) void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl)
@ -398,7 +398,7 @@ void Reporter::Weird(file_analysis::File* f, const char* name, const char* addl)
return; return;
} }
WeirdHelper(file_weird, {f->ToVal()->Ref(), new StringVal(addl)}, WeirdHelper(file_weird, {f->ToVal()->Ref(), new zeek::StringVal(addl)},
"%s", name); "%s", name);
} }
@ -413,11 +413,11 @@ void Reporter::Weird(Connection* conn, const char* name, const char* addl)
return; return;
} }
WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new StringVal(addl)}, WeirdHelper(conn_weird, {conn->ConnVal()->Ref(), new zeek::StringVal(addl)},
"%s", name); "%s", name);
} }
void Reporter::Weird(IntrusivePtr<RecordVal> conn_id, IntrusivePtr<StringVal> uid, void Reporter::Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid,
const char* name, const char* addl) const char* name, const char* addl)
{ {
UpdateWeirdStats(name); UpdateWeirdStats(name);
@ -429,7 +429,7 @@ void Reporter::Weird(IntrusivePtr<RecordVal> conn_id, IntrusivePtr<StringVal> ui
} }
WeirdHelper(expired_conn_weird, WeirdHelper(expired_conn_weird,
{conn_id.release(), uid.release(), new StringVal(addl)}, {conn_id.release(), uid.release(), new zeek::StringVal(addl)},
"%s", name); "%s", name);
} }
@ -444,7 +444,7 @@ void Reporter::Weird(const IPAddr& orig, const IPAddr& resp, const char* name, c
} }
WeirdHelper(flow_weird, WeirdHelper(flow_weird,
{new AddrVal(orig), new AddrVal(resp), new StringVal(addl)}, {new zeek::AddrVal(orig), new zeek::AddrVal(resp), new zeek::StringVal(addl)},
"%s", name); "%s", name);
} }
@ -469,11 +469,11 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
{ {
ODesc d; ODesc d;
std::pair<const Location*, const Location*> locs = locations.back(); std::pair<const zeek::detail::Location*, const zeek::detail::Location*> locs = locations.back();
if ( locs.first ) if ( locs.first )
{ {
if ( locs.first != &no_location ) if ( locs.first != &zeek::detail::no_location )
locs.first->Describe(&d); locs.first->Describe(&d);
else else
@ -483,7 +483,7 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
{ {
d.Add(" and "); d.Add(" and ");
if ( locs.second != &no_location ) if ( locs.second != &zeek::detail::no_location )
locs.second->Describe(&d); locs.second->Describe(&d);
else else
@ -558,19 +558,19 @@ void Reporter::DoLog(const char* prefix, EventHandlerPtr event, FILE* out,
vl.reserve(vl_size); vl.reserve(vl_size);
if ( time ) if ( time )
vl.emplace_back(make_intrusive<TimeVal>(network_time ? network_time : current_time())); vl.emplace_back(zeek::make_intrusive<zeek::TimeVal>(network_time ? network_time : current_time()));
vl.emplace_back(make_intrusive<StringVal>(buffer)); vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(buffer));
if ( location ) if ( location )
vl.emplace_back(make_intrusive<StringVal>(loc_str.c_str())); vl.emplace_back(zeek::make_intrusive<zeek::StringVal>(loc_str.c_str()));
if ( conn ) if ( conn )
vl.emplace_back(conn->ConnVal()); vl.emplace_back(conn->ConnVal());
if ( addl ) if ( addl )
for ( auto v : *addl ) for ( auto v : *addl )
vl.emplace_back(AdoptRef{}, v); vl.emplace_back(zeek::AdoptRef{}, v);
if ( conn ) if ( conn )
conn->EnqueueEvent(event, nullptr, std::move(vl)); conn->EnqueueEvent(event, nullptr, std::move(vl));

View file

@ -18,13 +18,18 @@
namespace analyzer { class Analyzer; } namespace analyzer { class Analyzer; }
namespace file_analysis { class File; } namespace file_analysis { class File; }
class Connection; class Connection;
class Location;
class Reporter; class Reporter;
class EventHandlerPtr; class EventHandlerPtr;
class RecordVal; ZEEK_FORWARD_DECLARE_NAMESPACED(RecordVal, zeek);
class StringVal; ZEEK_FORWARD_DECLARE_NAMESPACED(StringVal, zeek);
namespace zeek {
template <class T> class IntrusivePtr; template <class T> class IntrusivePtr;
using RecordValPtr = zeek::IntrusivePtr<RecordVal>;
using StringValPtr = zeek::IntrusivePtr<StringVal>;
}
ZEEK_FORWARD_DECLARE_NAMESPACED(Location, zeek::detail);
// One cannot raise this exception directly, go through the // One cannot raise this exception directly, go through the
// Reporter's methods instead. // Reporter's methods instead.
@ -90,14 +95,14 @@ public:
// Report a runtime error in evaluating a Bro script expression. This // Report a runtime error in evaluating a Bro script expression. This
// function will not return but raise an InterpreterException. // function will not return but raise an InterpreterException.
[[noreturn]] void RuntimeError(const Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4))); [[noreturn]] void RuntimeError(const zeek::detail::Location* location, const char* fmt, ...) __attribute__((format(printf, 3, 4)));
// Report a traffic weirdness, i.e., an unexpected protocol situation // Report a traffic weirdness, i.e., an unexpected protocol situation
// that may lead to incorrectly processing a connnection. // that may lead to incorrectly processing a connnection.
void Weird(const char* name, const char* addl = ""); // Raises net_weird(). void Weird(const char* name, const char* addl = ""); // Raises net_weird().
void Weird(file_analysis::File* f, const char* name, const char* addl = ""); // Raises file_weird(). void Weird(file_analysis::File* f, const char* name, const char* addl = ""); // Raises file_weird().
void Weird(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird(). void Weird(Connection* conn, const char* name, const char* addl = ""); // Raises conn_weird().
void Weird(IntrusivePtr<RecordVal> conn_id, IntrusivePtr<StringVal> uid, void Weird(zeek::RecordValPtr conn_id, zeek::StringValPtr uid,
const char* name, const char* addl = ""); // Raises expired_conn_weird(). const char* name, const char* addl = ""); // Raises expired_conn_weird().
void Weird(const IPAddr& orig, const IPAddr& resp, const char* name, const char* addl = ""); // Raises flow_weird(). void Weird(const IPAddr& orig, const IPAddr& resp, const char* name, const char* addl = ""); // Raises flow_weird().
@ -126,11 +131,11 @@ public:
// stack of location so that the most recent is always the one that // stack of location so that the most recent is always the one that
// will be assumed to be the current one. The pointer must remain // will be assumed to be the current one. The pointer must remain
// valid until the location is popped. // valid until the location is popped.
void PushLocation(const Location* location) void PushLocation(const zeek::detail::Location* location)
{ locations.push_back(std::pair<const Location*, const Location*>(location, 0)); } { locations.push_back(std::pair<const zeek::detail::Location*, const zeek::detail::Location*>(location, 0)); }
void PushLocation(const Location* loc1, const Location* loc2) void PushLocation(const zeek::detail::Location* loc1, const zeek::detail::Location* loc2)
{ locations.push_back(std::pair<const Location*, const Location*>(loc1, loc2)); } { locations.push_back(std::pair<const zeek::detail::Location*, const zeek::detail::Location*>(loc1, loc2)); }
// Removes the top-most location information from stack. // Removes the top-most location information from stack.
void PopLocation() void PopLocation()
@ -270,7 +275,7 @@ private:
{ return weird_sampling_whitelist.find(name) != weird_sampling_whitelist.end(); } { return weird_sampling_whitelist.find(name) != weird_sampling_whitelist.end(); }
bool PermitNetWeird(const char* name); bool PermitNetWeird(const char* name);
bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r); bool PermitFlowWeird(const char* name, const IPAddr& o, const IPAddr& r);
bool PermitExpiredConnWeird(const char* name, const RecordVal& conn_id); bool PermitExpiredConnWeird(const char* name, const zeek::RecordVal& conn_id);
bool EmitToStderr(bool flag) bool EmitToStderr(bool flag)
{ return flag || ! after_zeek_init; } { return flag || ! after_zeek_init; }
@ -284,7 +289,7 @@ private:
bool after_zeek_init; bool after_zeek_init;
bool abort_on_scripting_errors = false; bool abort_on_scripting_errors = false;
std::list<std::pair<const Location*, const Location*> > locations; std::list<std::pair<const zeek::detail::Location*, const zeek::detail::Location*> > locations;
uint64_t weird_count; uint64_t weird_count;
WeirdCountMap weird_count_by_type; WeirdCountMap weird_count_by_type;

View file

@ -14,12 +14,12 @@ class RuleAction;
class RuleHdrTest; class RuleHdrTest;
class Rule; class Rule;
typedef PList<Rule> rule_list; using rule_list = zeek::PList<Rule>;
typedef std::map<std::string, Rule*> rule_dict; using rule_dict = std::map<std::string, Rule*>;
class Rule { class Rule {
public: public:
Rule(const char* arg_id, const Location& arg_location) Rule(const char* arg_id, const zeek::detail::Location& arg_location)
{ {
id = copy_string(arg_id); id = copy_string(arg_id);
idx = rule_counter++; idx = rule_counter++;
@ -47,7 +47,7 @@ public:
uint32_t offset = 0, uint32_t depth = INT_MAX); uint32_t offset = 0, uint32_t depth = INT_MAX);
void AddRequires(const char* id, bool opposite_direction, bool negate); void AddRequires(const char* id, bool opposite_direction, bool negate);
const Location& GetLocation() const { return location; } const zeek::detail::Location& GetLocation() const { return location; }
void PrintDebug(); void PrintDebug();
@ -58,9 +58,9 @@ private:
void SortHdrTests(); void SortHdrTests();
typedef PList<RuleAction> rule_action_list; using rule_action_list = zeek::PList<RuleAction>;
typedef PList<RuleCondition> rule_condition_list; using rule_condition_list = zeek::PList<RuleCondition>;
typedef PList<RuleHdrTest> rule_hdr_test_list; using rule_hdr_test_list = zeek::PList<RuleHdrTest>;
rule_hdr_test_list hdr_tests; rule_hdr_test_list hdr_tests;
rule_condition_list conditions; rule_condition_list conditions;
@ -74,7 +74,7 @@ private:
bool negate; // negate test bool negate; // negate test
}; };
typedef PList<Precond> precond_list; using precond_list = zeek::PList<Precond>;
precond_list preconds; precond_list preconds;
rule_list dependents; // rules w/ us as a precondition rule_list dependents; // rules w/ us as a precondition
@ -92,13 +92,13 @@ private:
uint32_t depth; uint32_t depth;
}; };
typedef PList<Pattern> pattern_list; using pattern_list = zeek::PList<Pattern>;
pattern_list patterns; pattern_list patterns;
Rule* next; // Linkage within RuleHdrTest tree: Rule* next; // Linkage within RuleHdrTest tree:
// Ptr to next rule using the same RuleHdrTests // Ptr to next rule using the same RuleHdrTests
Location location; zeek::detail::Location location;
// Rules and payloads are numbered individually. // Rules and payloads are numbered individually.
static unsigned int rule_counter; static unsigned int rule_counter;

View file

@ -22,9 +22,9 @@ void RuleActionEvent::DoAction(const Rule* parent, RuleEndpointState* state,
{ {
if ( signature_match ) if ( signature_match )
mgr.Enqueue(signature_match, mgr.Enqueue(signature_match,
IntrusivePtr{AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)}, zeek::IntrusivePtr{zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(parent, state)},
make_intrusive<StringVal>(msg), zeek::make_intrusive<zeek::StringVal>(msg),
data ? make_intrusive<StringVal>(len, (const char*)data) : val_mgr->EmptyString() data ? zeek::make_intrusive<zeek::StringVal>(len, (const char*)data) : zeek::val_mgr->EmptyString()
); );
} }

View file

@ -129,7 +129,7 @@ bool RuleConditionPayloadSize::DoMatch(Rule* rule, RuleEndpointState* state,
RuleConditionEval::RuleConditionEval(const char* func) RuleConditionEval::RuleConditionEval(const char* func)
{ {
id = global_scope()->Find(func).get(); id = zeek::detail::global_scope()->Find(func).get();
if ( ! id ) if ( ! id )
{ {
rules_error("unknown identifier", func); rules_error("unknown identifier", func);
@ -170,12 +170,12 @@ bool RuleConditionEval::DoMatch(Rule* rule, RuleEndpointState* state,
// Call function with a signature_state value as argument. // Call function with a signature_state value as argument.
zeek::Args args; zeek::Args args;
args.reserve(2); args.reserve(2);
args.emplace_back(AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state)); args.emplace_back(zeek::AdoptRef{}, rule_matcher->BuildRuleStateValue(rule, state));
if ( data ) if ( data )
args.emplace_back(make_intrusive<StringVal>(len, (const char*) data)); args.emplace_back(zeek::make_intrusive<zeek::StringVal>(len, (const char*) data));
else else
args.emplace_back(val_mgr->EmptyString()); args.emplace_back(zeek::val_mgr->EmptyString());
bool result = false; bool result = false;

View file

@ -7,7 +7,7 @@
#include "RuleAction.h" #include "RuleAction.h"
#include "RuleCondition.h" #include "RuleCondition.h"
#include "BroString.h" #include "ZeekString.h"
#include "ID.h" #include "ID.h"
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
#include "IntSet.h" #include "IntSet.h"
@ -78,15 +78,15 @@ RuleHdrTest::RuleHdrTest(Prot arg_prot, Comp arg_comp, vector<IPPrefix> arg_v)
level = 0; level = 0;
} }
Val* RuleMatcher::BuildRuleStateValue(const Rule* rule, zeek::Val* RuleMatcher::BuildRuleStateValue(const Rule* rule,
const RuleEndpointState* state) const const RuleEndpointState* state) const
{ {
static auto signature_state = zeek::id::find_type<zeek::RecordType>("signature_state"); static auto signature_state = zeek::id::find_type<zeek::RecordType>("signature_state");
RecordVal* val = new RecordVal(signature_state); auto* val = new zeek::RecordVal(signature_state);
val->Assign(0, make_intrusive<StringVal>(rule->ID())); val->Assign(0, zeek::make_intrusive<zeek::StringVal>(rule->ID()));
val->Assign(1, state->GetAnalyzer()->ConnVal()); val->Assign(1, state->GetAnalyzer()->ConnVal());
val->Assign(2, val_mgr->Bool(state->is_orig)); val->Assign(2, zeek::val_mgr->Bool(state->is_orig));
val->Assign(3, val_mgr->Count(state->payload_size)); val->Assign(3, zeek::val_mgr->Count(state->payload_size));
return val; return val;
} }
@ -958,7 +958,7 @@ void RuleMatcher::Match(RuleEndpointState* state, Rule::PatternType type,
if ( ! state->matched_by_patterns.is_member(r) ) if ( ! state->matched_by_patterns.is_member(r) )
{ {
state->matched_by_patterns.push_back(r); state->matched_by_patterns.push_back(r);
BroString* s = new BroString(data, data_len, false); zeek::String* s = new zeek::String(data, data_len, false);
state->matched_text.push_back(s); state->matched_text.push_back(s);
} }
@ -998,7 +998,7 @@ void RuleMatcher::ExecPureRules(RuleEndpointState* state, bool eos)
} }
} }
bool RuleMatcher::ExecRulePurely(Rule* r, BroString* s, bool RuleMatcher::ExecRulePurely(Rule* r, zeek::String* s,
RuleEndpointState* state, bool eos) RuleEndpointState* state, bool eos)
{ {
if ( is_member_of(state->matched_rules, r->Index()) ) if ( is_member_of(state->matched_rules, r->Index()) )
@ -1272,9 +1272,9 @@ void RuleMatcher::DumpStateStats(BroFile* f, RuleHdrTest* hdr_test)
DumpStateStats(f, h); DumpStateStats(f, h);
} }
static Val* get_bro_val(const char* label) static zeek::Val* get_bro_val(const char* label)
{ {
auto id = lookup_ID(label, GLOBAL_MODULE_NAME, false); auto id = zeek::detail::lookup_ID(label, GLOBAL_MODULE_NAME, false);
if ( ! id ) if ( ! id )
{ {
rules_error("unknown script-level identifier", label); rules_error("unknown script-level identifier", label);
@ -1288,7 +1288,7 @@ static Val* get_bro_val(const char* label)
// Converts an atomic Val and appends it to the list. For subnet types, // Converts an atomic Val and appends it to the list. For subnet types,
// if the prefix_vector param isn't null, appending to that is preferred // if the prefix_vector param isn't null, appending to that is preferred
// over appending to the masked val list. // over appending to the masked val list.
static bool val_to_maskedval(Val* v, maskedvalue_list* append_to, static bool val_to_maskedval(zeek::Val* v, maskedvalue_list* append_to,
vector<IPPrefix>* prefix_vector) vector<IPPrefix>* prefix_vector)
{ {
MaskedValue* mval = new MaskedValue; MaskedValue* mval = new MaskedValue;
@ -1358,7 +1358,7 @@ static bool val_to_maskedval(Val* v, maskedvalue_list* append_to,
void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
vector<IPPrefix>* prefix_vector) vector<IPPrefix>* prefix_vector)
{ {
Val* v = get_bro_val(id); zeek::Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
return; return;
@ -1377,10 +1377,10 @@ void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
char* id_to_str(const char* id) char* id_to_str(const char* id)
{ {
const BroString* src; const zeek::String* src;
char* dst; char* dst;
Val* v = get_bro_val(id); zeek::Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
goto error; goto error;
@ -1403,7 +1403,7 @@ error:
uint32_t id_to_uint(const char* id) uint32_t id_to_uint(const char* id)
{ {
Val* v = get_bro_val(id); zeek::Val* v = get_bro_val(id);
if ( ! v ) if ( ! v )
return 0; return 0;

View file

@ -27,7 +27,6 @@ extern FILE* rules_in;
extern int rules_line_number; extern int rules_line_number;
extern const char* current_rule_file; extern const char* current_rule_file;
class Val;
class BroFile; class BroFile;
class IntSet; class IntSet;
class IP_Hdr; class IP_Hdr;
@ -37,6 +36,8 @@ class Specific_RE_Matcher;
class RuleMatcher; class RuleMatcher;
extern RuleMatcher* rule_matcher; extern RuleMatcher* rule_matcher;
ZEEK_FORWARD_DECLARE_NAMESPACED(Val, zeek);
namespace analyzer { namespace analyzer {
namespace pia { class PIA; } namespace pia { class PIA; }
class Analyzer; class Analyzer;
@ -56,9 +57,9 @@ struct MaskedValue {
uint32_t mask; uint32_t mask;
}; };
typedef PList<MaskedValue> maskedvalue_list; using maskedvalue_list = zeek::PList<MaskedValue>;
typedef PList<char> string_list; using string_list = zeek::PList<char>;
typedef PList<BroString> bstr_list; using bstr_list = zeek::PList<zeek::String>;
// Get values from Bro's script-level variables. // Get values from Bro's script-level variables.
extern void id_to_maskedvallist(const char* id, maskedvalue_list* append_to, extern void id_to_maskedvallist(const char* id, maskedvalue_list* append_to,
@ -116,7 +117,7 @@ private:
int_list ids; // (only needed for debugging) int_list ids; // (only needed for debugging)
}; };
typedef PList<PatternSet> pattern_set_list; using pattern_set_list = zeek::PList<PatternSet>;
pattern_set_list psets[Rule::TYPES]; pattern_set_list psets[Rule::TYPES];
// List of rules belonging to this node. // List of rules belonging to this node.
@ -130,7 +131,7 @@ private:
RuleHdrTest* child; RuleHdrTest* child;
}; };
typedef PList<RuleHdrTest> rule_hdr_test_list; using rule_hdr_test_list = zeek::PList<RuleHdrTest>;
// RuleEndpointState keeps the per-stream matching state of one // RuleEndpointState keeps the per-stream matching state of one
// connection endpoint. // connection endpoint.
@ -165,7 +166,7 @@ private:
Rule::PatternType type; Rule::PatternType type;
}; };
typedef PList<Matcher> matcher_list; using matcher_list = zeek::PList<Matcher>;
analyzer::Analyzer* analyzer; analyzer::Analyzer* analyzer;
RuleEndpointState* opposite; RuleEndpointState* opposite;
@ -204,8 +205,7 @@ private:
RE_Match_State* state; RE_Match_State* state;
}; };
typedef PList<Matcher> matcher_list; using matcher_list = zeek::PList<Matcher>;
matcher_list matchers; matcher_list matchers;
}; };
@ -304,8 +304,8 @@ public:
unsigned int misses; // # cache misses unsigned int misses; // # cache misses
}; };
Val* BuildRuleStateValue(const Rule* rule, zeek::Val* BuildRuleStateValue(const Rule* rule,
const RuleEndpointState* state) const; const RuleEndpointState* state) const;
void GetStats(Stats* stats, RuleHdrTest* hdr_test = nullptr); void GetStats(Stats* stats, RuleHdrTest* hdr_test = nullptr);
void DumpStats(BroFile* f); void DumpStats(BroFile* f);
@ -338,7 +338,7 @@ private:
// Eval a rule under the assumption that all its patterns // Eval a rule under the assumption that all its patterns
// have already matched. s holds the text the rule matched, // have already matched. s holds the text the rule matched,
// or nil if N/A. // or nil if N/A.
bool ExecRulePurely(Rule* r, BroString* s, bool ExecRulePurely(Rule* r, zeek::String* s,
RuleEndpointState* state, bool eos); RuleEndpointState* state, bool eos);
// Execute the actions associated with a rule. // Execute the actions associated with a rule.

View file

@ -10,13 +10,15 @@
#include "Reporter.h" #include "Reporter.h"
#include "module_util.h" #include "module_util.h"
typedef PList<Scope> scope_list; namespace zeek::detail {
using scope_list = zeek::PList<Scope>;
static scope_list scopes; static scope_list scopes;
static Scope* top_scope; static Scope* top_scope;
Scope::Scope(IntrusivePtr<zeek::detail::ID> id, Scope::Scope(zeek::detail::IDPtr id,
std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>> al) std::unique_ptr<std::vector<zeek::detail::AttrPtr>> al)
: scope_id(std::move(id)), attrs(std::move(al)) : scope_id(std::move(id)), attrs(std::move(al))
{ {
return_type = nullptr; return_type = nullptr;
@ -35,7 +37,7 @@ Scope::Scope(IntrusivePtr<zeek::detail::ID> id,
} }
} }
const IntrusivePtr<zeek::detail::ID>& Scope::Find(std::string_view name) const const zeek::detail::IDPtr& Scope::Find(std::string_view name) const
{ {
auto entry = local.find(name); auto entry = local.find(name);
@ -45,7 +47,7 @@ const IntrusivePtr<zeek::detail::ID>& Scope::Find(std::string_view name) const
return zeek::detail::ID::nil; return zeek::detail::ID::nil;
} }
IntrusivePtr<zeek::detail::ID> Scope::Remove(std::string_view name) zeek::detail::IDPtr Scope::Remove(std::string_view name)
{ {
auto entry = local.find(name); auto entry = local.find(name);
@ -59,12 +61,12 @@ IntrusivePtr<zeek::detail::ID> Scope::Remove(std::string_view name)
return nullptr; return nullptr;
} }
IntrusivePtr<zeek::detail::ID> Scope::GenerateTemporary(const char* name) zeek::detail::IDPtr Scope::GenerateTemporary(const char* name)
{ {
return make_intrusive<zeek::detail::ID>(name, zeek::detail::SCOPE_FUNCTION, false); return zeek::make_intrusive<zeek::detail::ID>(name, zeek::detail::SCOPE_FUNCTION, false);
} }
std::vector<IntrusivePtr<zeek::detail::ID>> Scope::GetInits() std::vector<zeek::detail::IDPtr> Scope::GetInits()
{ {
auto rval = std::move(inits); auto rval = std::move(inits);
inits = {}; inits = {};
@ -119,9 +121,9 @@ TraversalCode Scope::Traverse(TraversalCallback* cb) const
} }
const IntrusivePtr<zeek::detail::ID>& lookup_ID(const char* name, const char* curr_module, const zeek::detail::IDPtr& lookup_ID(const char* name, const char* curr_module,
bool no_global, bool same_module_only, bool no_global, bool same_module_only,
bool check_export) bool check_export)
{ {
std::string fullname = make_full_var_name(curr_module, name); std::string fullname = make_full_var_name(curr_module, name);
@ -137,14 +139,14 @@ const IntrusivePtr<zeek::detail::ID>& lookup_ID(const char* name, const char* cu
{ {
if ( need_export && ! id->IsExport() && ! in_debug ) if ( need_export && ! id->IsExport() && ! in_debug )
reporter->Error("identifier is not exported: %s", reporter->Error("identifier is not exported: %s",
fullname.c_str()); fullname.c_str());
return id; return id;
} }
} }
if ( ! no_global && (strcmp(GLOBAL_MODULE_NAME, curr_module) == 0 || if ( ! no_global && (strcmp(GLOBAL_MODULE_NAME, curr_module) == 0 ||
! same_module_only) ) ! same_module_only) )
{ {
std::string globalname = make_full_var_name(GLOBAL_MODULE_NAME, name); std::string globalname = make_full_var_name(GLOBAL_MODULE_NAME, name);
return global_scope()->Find(globalname); return global_scope()->Find(globalname);
@ -153,8 +155,8 @@ const IntrusivePtr<zeek::detail::ID>& lookup_ID(const char* name, const char* cu
return zeek::detail::ID::nil; return zeek::detail::ID::nil;
} }
IntrusivePtr<zeek::detail::ID> install_ID(const char* name, const char* module_name, zeek::detail::IDPtr install_ID(const char* name, const char* module_name,
bool is_global, bool is_export) bool is_global, bool is_export)
{ {
if ( scopes.empty() && ! is_global ) if ( scopes.empty() && ! is_global )
reporter->InternalError("local identifier in global scope"); reporter->InternalError("local identifier in global scope");
@ -171,7 +173,7 @@ IntrusivePtr<zeek::detail::ID> install_ID(const char* name, const char* module_n
std::string full_name = make_full_var_name(module_name, name); std::string full_name = make_full_var_name(module_name, name);
auto id = make_intrusive<zeek::detail::ID>(full_name.data(), scope, is_export); auto id = zeek::make_intrusive<zeek::detail::ID>(full_name.data(), scope, is_export);
if ( zeek::detail::SCOPE_FUNCTION != scope ) if ( zeek::detail::SCOPE_FUNCTION != scope )
global_scope()->Insert(std::move(full_name), id); global_scope()->Insert(std::move(full_name), id);
@ -189,14 +191,14 @@ void push_existing_scope(Scope* scope)
scopes.push_back(scope); scopes.push_back(scope);
} }
void push_scope(IntrusivePtr<zeek::detail::ID> id, void push_scope(zeek::detail::IDPtr id,
std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>> attrs) std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs)
{ {
top_scope = new Scope(std::move(id), std::move(attrs)); top_scope = new Scope(std::move(id), std::move(attrs));
scopes.push_back(top_scope); scopes.push_back(top_scope);
} }
IntrusivePtr<Scope> pop_scope() ScopePtr pop_scope()
{ {
if ( scopes.empty() ) if ( scopes.empty() )
reporter->InternalError("scope underflow"); reporter->InternalError("scope underflow");
@ -206,7 +208,7 @@ IntrusivePtr<Scope> pop_scope()
top_scope = scopes.empty() ? nullptr : scopes.back(); top_scope = scopes.empty() ? nullptr : scopes.back();
return {AdoptRef{}, old_top}; return {zeek::AdoptRef{}, old_top};
} }
Scope* current_scope() Scope* current_scope()
@ -218,3 +220,14 @@ Scope* global_scope()
{ {
return scopes.empty() ? 0 : scopes.front(); return scopes.empty() ? 0 : scopes.front();
} }
}
const zeek::detail::ID* lookup_ID(
const char* name, const char* module,
bool no_global,
bool same_module_only,
bool check_export)
{
return zeek::detail::lookup_ID(name, module, no_global, same_module_only, check_export).get();
}

View file

@ -12,19 +12,31 @@
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
#include "TraverseTypes.h" #include "TraverseTypes.h"
template <class T> class IntrusivePtr; ZEEK_FORWARD_DECLARE_NAMESPACED(Type, zeek);
class ListVal;
namespace zeek { class Type; }
using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type; using BroType [[deprecated("Remove in v4.1. Use zeek::Type instead.")]] = zeek::Type;
ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Attr, zeek::detail);
class Scope : public BroObj { namespace zeek {
template <class T> class IntrusivePtr;
using TypePtr = zeek::IntrusivePtr<Type>;
namespace detail {
using AttrPtr = zeek::IntrusivePtr<Attr>;
using IDPtr = zeek::IntrusivePtr<ID>;
class Scope;
using ScopePtr = zeek::IntrusivePtr<Scope>;
class Scope : public Obj {
public: public:
explicit Scope(IntrusivePtr<zeek::detail::ID> id, explicit Scope(zeek::detail::IDPtr id,
std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>> al); std::unique_ptr<std::vector<zeek::detail::AttrPtr>> al);
const IntrusivePtr<zeek::detail::ID>& Find(std::string_view name) const; const zeek::detail::IDPtr& Find(std::string_view name) const;
template<typename N> template<typename N>
[[deprecated("Remove in v4.1. Use Find().")]] [[deprecated("Remove in v4.1. Use Find().")]]
@ -34,34 +46,34 @@ public:
template<typename N, typename I> template<typename N, typename I>
void Insert(N&& name, I&& id) { local[std::forward<N>(name)] = std::forward<I>(id); } void Insert(N&& name, I&& id) { local[std::forward<N>(name)] = std::forward<I>(id); }
IntrusivePtr<zeek::detail::ID> Remove(std::string_view name); zeek::detail::IDPtr Remove(std::string_view name);
[[deprecated("Remove in v4.1. Use GetID().")]] [[deprecated("Remove in v4.1. Use GetID().")]]
zeek::detail::ID* ScopeID() const { return scope_id.get(); } zeek::detail::ID* ScopeID() const { return scope_id.get(); }
const IntrusivePtr<zeek::detail::ID>& GetID() const const zeek::detail::IDPtr& GetID() const
{ return scope_id; } { return scope_id; }
const std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>>& Attrs() const const std::unique_ptr<std::vector<zeek::detail::AttrPtr>>& Attrs() const
{ return attrs; } { return attrs; }
[[deprecated("Remove in v4.1. Use GetReturnTrype().")]] [[deprecated("Remove in v4.1. Use GetReturnTrype().")]]
zeek::Type* ReturnType() const { return return_type.get(); } zeek::Type* ReturnType() const { return return_type.get(); }
const IntrusivePtr<zeek::Type>& GetReturnType() const const zeek::TypePtr& GetReturnType() const
{ return return_type; } { return return_type; }
size_t Length() const { return local.size(); } size_t Length() const { return local.size(); }
const auto& Vars() { return local; } const auto& Vars() { return local; }
IntrusivePtr<zeek::detail::ID> GenerateTemporary(const char* name); zeek::detail::IDPtr GenerateTemporary(const char* name);
// Returns the list of variables needing initialization, and // Returns the list of variables needing initialization, and
// removes it from this Scope. // removes it from this Scope.
std::vector<IntrusivePtr<zeek::detail::ID>> GetInits(); std::vector<zeek::detail::IDPtr> GetInits();
// Adds a variable to the list. // Adds a variable to the list.
void AddInit(IntrusivePtr<zeek::detail::ID> id) void AddInit(zeek::detail::IDPtr id)
{ inits.emplace_back(std::move(id)); } { inits.emplace_back(std::move(id)); }
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -69,33 +81,55 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const; TraversalCode Traverse(TraversalCallback* cb) const;
protected: protected:
IntrusivePtr<zeek::detail::ID> scope_id; zeek::detail::IDPtr scope_id;
std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>> attrs; std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs;
IntrusivePtr<zeek::Type> return_type; zeek::TypePtr return_type;
std::map<std::string, IntrusivePtr<zeek::detail::ID>, std::less<>> local; std::map<std::string, zeek::detail::IDPtr, std::less<>> local;
std::vector<IntrusivePtr<zeek::detail::ID>> inits; std::vector<zeek::detail::IDPtr> inits;
}; };
extern bool in_debug;
// If no_global is true, don't search in the default "global" namespace. // If no_global is true, don't search in the default "global" namespace.
extern const IntrusivePtr<zeek::detail::ID>& lookup_ID(const char* name, const char* module, extern const zeek::detail::IDPtr& lookup_ID(
bool no_global = false, const char* name, const char* module,
bool same_module_only = false, bool no_global = false,
bool check_export = true); bool same_module_only = false,
bool check_export = true);
extern IntrusivePtr<zeek::detail::ID> install_ID(const char* name, const char* module_name, extern zeek::detail::IDPtr install_ID(
bool is_global, bool is_export); const char* name, const char* module_name,
bool is_global, bool is_export);
extern void push_scope(IntrusivePtr<zeek::detail::ID> id, extern void push_scope(zeek::detail::IDPtr id,
std::unique_ptr<std::vector<IntrusivePtr<zeek::detail::Attr>>> attrs); std::unique_ptr<std::vector<zeek::detail::AttrPtr>> attrs);
extern void push_existing_scope(Scope* scope); extern void push_existing_scope(Scope* scope);
// Returns the one popped off. // Returns the one popped off.
extern IntrusivePtr<Scope> pop_scope(); extern ScopePtr pop_scope();
extern Scope* current_scope(); extern Scope* current_scope();
extern Scope* global_scope(); extern Scope* global_scope();
// Current module (identified by its name). // Current module (identified by its name).
extern std::string current_module; extern std::string current_module;
} // namespace detail
} // namespace zeek
extern bool in_debug;
using Scope [[deprecated("Remove in v4.1. Use zeek::detail::Scope instead.")]] = zeek::detail::Scope;
extern std::string& current_module [[deprecated("Remove in v4.1. Use zeek::detail::current_module.")]];
constexpr auto install_ID [[deprecated("Remove in v4.1 Use zeek::detail::install_ID instead.")]] = zeek::detail::install_ID;
constexpr auto push_scope [[deprecated("Remove in v4.1 Use zeek::detail::push_scope instead.")]] = zeek::detail::push_scope;
constexpr auto push_existing_scope[[deprecated("Remove in v4.1 Use zeek::detail::push_existing_scope instead.")]] = zeek::detail::push_existing_scope;
constexpr auto pop_scope [[deprecated("Remove in v4.1 Use zeek::detail::pop_scope instead.")]] = zeek::detail::pop_scope;
constexpr auto current_scope [[deprecated("Remove in v4.1 Use zeek::detail::current_scope instead.")]] = zeek::detail::current_scope;
constexpr auto global_scope [[deprecated("Remove in v4.1 Use zeek::detail::global_scope instead.")]] = zeek::detail::global_scope;
// Because of the use of default arguments, this function can't be aliased like the rest.
[[deprecated("Remove in v4.1 Use zeek::detail::lookup_ID instead.")]]
extern const zeek::detail::ID* lookup_ID(
const char* name, const char* module,
bool no_global = false,
bool same_module_only = false,
bool check_export = true);

View file

@ -703,7 +703,7 @@ void NetSessions::DoNextPacket(double t, const Packet* pkt, const IP_Hdr* ip_hdr
conn->CheckFlowLabel(is_orig, ip_hdr->FlowLabel()); conn->CheckFlowLabel(is_orig, ip_hdr->FlowLabel());
IntrusivePtr<Val> pkt_hdr_val; zeek::ValPtr pkt_hdr_val;
if ( ipv6_ext_headers && ip_hdr->NumHeaders() > 1 ) if ( ipv6_ext_headers && ip_hdr->NumHeaders() > 1 )
{ {
@ -920,7 +920,7 @@ FragReassembler* NetSessions::NextFragment(double t, const IP_Hdr* ip,
return f; return f;
} }
Connection* NetSessions::FindConnection(Val* v) Connection* NetSessions::FindConnection(zeek::Val* v)
{ {
const auto& vt = v->GetType(); const auto& vt = v->GetType();
if ( ! zeek::IsRecord(vt->Tag()) ) if ( ! zeek::IsRecord(vt->Tag()) )
@ -958,8 +958,8 @@ Connection* NetSessions::FindConnection(Val* v)
const IPAddr& orig_addr = (*vl)[orig_h]->AsAddr(); const IPAddr& orig_addr = (*vl)[orig_h]->AsAddr();
const IPAddr& resp_addr = (*vl)[resp_h]->AsAddr(); const IPAddr& resp_addr = (*vl)[resp_h]->AsAddr();
PortVal* orig_portv = (*vl)[orig_p]->AsPortVal(); zeek::PortVal* orig_portv = (*vl)[orig_p]->AsPortVal();
PortVal* resp_portv = (*vl)[resp_p]->AsPortVal(); zeek::PortVal* resp_portv = (*vl)[resp_p]->AsPortVal();
ConnID id; ConnID id;
@ -1236,7 +1236,7 @@ bool NetSessions::IsLikelyServerPort(uint32_t port, TransportProto proto) const
if ( ! have_cache ) if ( ! have_cache )
{ {
auto likely_server_ports = zeek::id::find_val<TableVal>("likely_server_ports"); auto likely_server_ports = zeek::id::find_val<zeek::TableVal>("likely_server_ports");
auto lv = likely_server_ports->ToPureListVal(); auto lv = likely_server_ports->ToPureListVal();
for ( int i = 0; i < lv->Length(); i++ ) for ( int i = 0; i < lv->Length(); i++ )
port_cache.insert(lv->Idx(i)->InternalUnsigned()); port_cache.insert(lv->Idx(i)->InternalUnsigned());

View file

@ -61,7 +61,7 @@ public:
// Looks up the connection referred to by the given Val, // Looks up the connection referred to by the given Val,
// which should be a conn_id record. Returns nil if there's // which should be a conn_id record. Returns nil if there's
// no such connection or the Val is ill-formed. // no such connection or the Val is ill-formed.
Connection* FindConnection(Val* v); Connection* FindConnection(zeek::Val* v);
void Remove(Connection* c); void Remove(Connection* c);
void Remove(FragReassembler* f); void Remove(FragReassembler* f);

View file

@ -12,7 +12,7 @@
#include "Val.h" #include "Val.h"
BroSubstring::BroSubstring(const BroSubstring& bst) BroSubstring::BroSubstring(const BroSubstring& bst)
: BroString((const BroString&) bst), _num(), _new(bst._new) : zeek::String((const zeek::String&) bst), _num(), _new(bst._new)
{ {
for ( BSSAlignVecCIt it = bst._aligns.begin(); it != bst._aligns.end(); ++it ) for ( BSSAlignVecCIt it = bst._aligns.begin(); it != bst._aligns.end(); ++it )
_aligns.push_back(*it); _aligns.push_back(*it);
@ -20,7 +20,7 @@ BroSubstring::BroSubstring(const BroSubstring& bst)
const BroSubstring& BroSubstring::operator=(const BroSubstring& bst) const BroSubstring& BroSubstring::operator=(const BroSubstring& bst)
{ {
BroString::operator=(bst); zeek::String::operator=(bst);
_aligns.clear(); _aligns.clear();
@ -32,7 +32,7 @@ const BroSubstring& BroSubstring::operator=(const BroSubstring& bst)
return *this; return *this;
} }
void BroSubstring::AddAlignment(const BroString* str, int index) void BroSubstring::AddAlignment(const zeek::String* str, int index)
{ {
_aligns.push_back(BSSAlign(str, index)); _aligns.push_back(BSSAlign(str, index));
} }
@ -56,14 +56,14 @@ bool BroSubstring::DoesCover(const BroSubstring* bst) const
return true; return true;
} }
VectorVal* BroSubstring::VecToPolicy(Vec* vec) zeek::VectorVal* BroSubstring::VecToPolicy(Vec* vec)
{ {
static auto sw_substring_type = zeek::id::find_type<zeek::RecordType>("sw_substring"); static auto sw_substring_type = zeek::id::find_type<zeek::RecordType>("sw_substring");
static auto sw_align_type = zeek::id::find_type<zeek::RecordType>("sw_align"); static auto sw_align_type = zeek::id::find_type<zeek::RecordType>("sw_align");
static auto sw_align_vec_type = zeek::id::find_type<zeek::VectorType>("sw_align_vec"); static auto sw_align_vec_type = zeek::id::find_type<zeek::VectorType>("sw_align_vec");
static auto sw_substring_vec_type = zeek::id::find_type<zeek::VectorType>("sw_substring_vec"); static auto sw_substring_vec_type = zeek::id::find_type<zeek::VectorType>("sw_substring_vec");
auto result = make_intrusive<VectorVal>(sw_substring_vec_type); auto result = zeek::make_intrusive<zeek::VectorVal>(sw_substring_vec_type);
if ( vec ) if ( vec )
{ {
@ -71,24 +71,24 @@ VectorVal* BroSubstring::VecToPolicy(Vec* vec)
{ {
BroSubstring* bst = (*vec)[i]; BroSubstring* bst = (*vec)[i];
auto st_val = make_intrusive<RecordVal>(sw_substring_type); auto st_val = zeek::make_intrusive<zeek::RecordVal>(sw_substring_type);
st_val->Assign(0, make_intrusive<StringVal>(new BroString(*bst))); st_val->Assign(0, zeek::make_intrusive<zeek::StringVal>(new zeek::String(*bst)));
auto aligns = make_intrusive<VectorVal>(sw_align_vec_type); auto aligns = zeek::make_intrusive<zeek::VectorVal>(sw_align_vec_type);
for ( unsigned int j = 0; j < bst->GetNumAlignments(); ++j ) for ( unsigned int j = 0; j < bst->GetNumAlignments(); ++j )
{ {
const BSSAlign& align = (bst->GetAlignments())[j]; const BSSAlign& align = (bst->GetAlignments())[j];
auto align_val = make_intrusive<RecordVal>(sw_align_type); auto align_val = zeek::make_intrusive<zeek::RecordVal>(sw_align_type);
align_val->Assign(0, make_intrusive<StringVal>(new BroString(*align.string))); align_val->Assign(0, zeek::make_intrusive<zeek::StringVal>(new zeek::String(*align.string)));
align_val->Assign(1, val_mgr->Count(align.index)); align_val->Assign(1, zeek::val_mgr->Count(align.index));
aligns->Assign(j + 1, std::move(align_val)); aligns->Assign(j + 1, std::move(align_val));
} }
st_val->Assign(1, std::move(aligns)); st_val->Assign(1, std::move(aligns));
st_val->Assign(2, val_mgr->Bool(bst->IsNewAlignment())); st_val->Assign(2, zeek::val_mgr->Bool(bst->IsNewAlignment()));
result->Assign(i + 1, std::move(st_val)); result->Assign(i + 1, std::move(st_val));
} }
} }
@ -96,7 +96,7 @@ VectorVal* BroSubstring::VecToPolicy(Vec* vec)
return result.release(); return result.release();
} }
BroSubstring::Vec* BroSubstring::VecFromPolicy(VectorVal* vec) BroSubstring::Vec* BroSubstring::VecFromPolicy(zeek::VectorVal* vec)
{ {
Vec* result = new Vec(); Vec* result = new Vec();
@ -107,14 +107,14 @@ BroSubstring::Vec* BroSubstring::VecFromPolicy(VectorVal* vec)
if ( ! v ) if ( ! v )
continue; continue;
const BroString* str = v->AsRecordVal()->GetField(0)->AsString(); const zeek::String* str = v->AsRecordVal()->GetField(0)->AsString();
BroSubstring* substr = new BroSubstring(*str); BroSubstring* substr = new BroSubstring(*str);
const VectorVal* aligns = v->AsRecordVal()->GetField(1)->AsVectorVal(); const zeek::VectorVal* aligns = v->AsRecordVal()->GetField(1)->AsVectorVal();
for ( unsigned int j = 1; j <= aligns->Size(); ++j ) for ( unsigned int j = 1; j <= aligns->Size(); ++j )
{ {
const RecordVal* align = aligns->AsVectorVal()->At(j)->AsRecordVal(); const zeek::RecordVal* align = aligns->AsVectorVal()->At(j)->AsRecordVal();
const BroString* str = align->GetField(0)->AsString(); const zeek::String* str = align->GetField(0)->AsString();
int index = align->GetField(1)->AsCount(); int index = align->GetField(1)->AsCount();
substr->AddAlignment(str, index); substr->AddAlignment(str, index);
} }
@ -142,9 +142,9 @@ char* BroSubstring::VecToString(Vec* vec)
return strdup(result.c_str()); return strdup(result.c_str());
} }
BroString::IdxVec* BroSubstring::GetOffsetsVec(const Vec* vec, unsigned int index) zeek::String::IdxVec* BroSubstring::GetOffsetsVec(const Vec* vec, unsigned int index)
{ {
BroString::IdxVec* result = new BroString::IdxVec(); zeek::String::IdxVec* result = new zeek::String::IdxVec();
for ( VecCIt it = vec->begin(); it != vec->end(); ++it ) for ( VecCIt it = vec->begin(); it != vec->end(); ++it )
{ {
@ -209,7 +209,7 @@ struct SWNode {
// //
class SWNodeMatrix { class SWNodeMatrix {
public: public:
SWNodeMatrix(const BroString* s1, const BroString* s2) SWNodeMatrix(const zeek::String* s1, const zeek::String* s2)
: _s1(s1), _s2(s2), _rows(s1->Len() + 1), _cols(s2->Len() + 1) : _s1(s1), _s2(s2), _rows(s1->Len() + 1), _cols(s2->Len() + 1)
{ {
_nodes = new SWNode[_cols * _rows]; _nodes = new SWNode[_cols * _rows];
@ -229,8 +229,8 @@ public:
return &(_nodes[row * _cols + col]); return &(_nodes[row * _cols + col]);
} }
const BroString* GetRowsString() const { return _s1; } const zeek::String* GetRowsString() const { return _s1; }
const BroString* GetColsString() const { return _s2; } const zeek::String* GetColsString() const { return _s2; }
int GetHeight() const { return _rows; } int GetHeight() const { return _rows; }
int GetWidth() const { return _cols; } int GetWidth() const { return _cols; }
@ -247,8 +247,8 @@ public:
} }
private: private:
const BroString* _s1; const zeek::String* _s1;
const BroString* _s2; const zeek::String* _s2;
int _rows, _cols; int _rows, _cols;
SWNode* _nodes; SWNode* _nodes;
@ -398,7 +398,7 @@ end_loop:
// The main Smith-Waterman algorithm. // The main Smith-Waterman algorithm.
// //
BroSubstring::Vec* smith_waterman(const BroString* s1, const BroString* s2, BroSubstring::Vec* smith_waterman(const zeek::String* s1, const zeek::String* s2,
SWParams& params) SWParams& params)
{ {
BroSubstring::Vec* result = new BroSubstring::Vec(); BroSubstring::Vec* result = new BroSubstring::Vec();
@ -415,8 +415,8 @@ BroSubstring::Vec* smith_waterman(const BroString* s1, const BroString* s2,
int row = 0, col = 0; int row = 0, col = 0;
byte_vec string1 = s1->Bytes(); zeek::byte_vec string1 = s1->Bytes();
byte_vec string2 = s2->Bytes(); zeek::byte_vec string2 = s2->Bytes();
SWNodeMatrix matrix(s1, s2); // dynamic programming matrix. SWNodeMatrix matrix(s1, s2); // dynamic programming matrix.
SWNode* node_max = nullptr; // pointer to the best score's node SWNode* node_max = nullptr; // pointer to the best score's node

View file

@ -2,7 +2,7 @@
#pragma once #pragma once
#include "BroString.h" #include "ZeekString.h"
#include <map> #include <map>
// BroSubstrings are essentially BroStrings, augmented with indexing // BroSubstrings are essentially BroStrings, augmented with indexing
@ -11,7 +11,7 @@
// for each of which we store where the substring starts. // for each of which we store where the substring starts.
// //
// //
class BroSubstring : public BroString { class BroSubstring : public zeek::String {
public: public:
typedef std::vector<BroSubstring*> Vec; typedef std::vector<BroSubstring*> Vec;
@ -22,12 +22,12 @@ public:
// //
struct BSSAlign { struct BSSAlign {
BSSAlign(const BroString* string, int index) BSSAlign(const zeek::String* string, int index)
{ this->string = string; this->index = index; } { this->string = string; this->index = index; }
// The other string // The other string
// //
const BroString* string; const zeek::String* string;
// Offset in the string that substring // Offset in the string that substring
// starts at, counting from 0. // starts at, counting from 0.
@ -40,10 +40,10 @@ public:
typedef BSSAlignVec::const_iterator BSSAlignVecCIt; typedef BSSAlignVec::const_iterator BSSAlignVecCIt;
explicit BroSubstring(const std::string& string) explicit BroSubstring(const std::string& string)
: BroString(string), _num(), _new(false) { } : zeek::String(string), _num(), _new(false) { }
explicit BroSubstring(const BroString& string) explicit BroSubstring(const zeek::String& string)
: BroString(string), _num(), _new(false) { } : zeek::String(string), _num(), _new(false) { }
BroSubstring(const BroSubstring& bst); BroSubstring(const BroSubstring& bst);
@ -56,7 +56,7 @@ public:
// //
bool DoesCover(const BroSubstring* bst) const; bool DoesCover(const BroSubstring* bst) const;
void AddAlignment(const BroString* string, int index); void AddAlignment(const zeek::String* string, int index);
const BSSAlignVec& GetAlignments() const { return _aligns; } const BSSAlignVec& GetAlignments() const { return _aligns; }
unsigned int GetNumAlignments() const { return _aligns.size(); } unsigned int GetNumAlignments() const { return _aligns.size(); }
@ -68,11 +68,11 @@ public:
// Helper methods for vectors: // Helper methods for vectors:
// //
static VectorVal* VecToPolicy(Vec* vec); static zeek::VectorVal* VecToPolicy(Vec* vec);
static Vec* VecFromPolicy(VectorVal* vec); static Vec* VecFromPolicy(zeek::VectorVal* vec);
static char* VecToString(Vec* vec); static char* VecToString(Vec* vec);
static BroString::IdxVec* GetOffsetsVec(const Vec* vec, static zeek::String::IdxVec* GetOffsetsVec(const Vec* vec,
unsigned int index); unsigned int index);
private: private:
typedef std::map<std::string, void*> DataMap; typedef std::map<std::string, void*> DataMap;
@ -148,6 +148,6 @@ struct SWParams {
// input strings where the string occurs. On error, or if no common // input strings where the string occurs. On error, or if no common
// subsequence exists, an empty vector is returned. // subsequence exists, an empty vector is returned.
// //
extern BroSubstring::Vec* smith_waterman(const BroString* s1, extern BroSubstring::Vec* smith_waterman(const zeek::String* s1,
const BroString* s2, const zeek::String* s2,
SWParams& params); SWParams& params);

View file

@ -240,7 +240,7 @@ void ProfileLogger::Log()
// Script-level state. // Script-level state.
unsigned int size, mem = 0; unsigned int size, mem = 0;
const auto& globals = global_scope()->Vars(); const auto& globals = zeek::detail::global_scope()->Vars();
if ( expensive ) if ( expensive )
{ {
@ -313,14 +313,14 @@ void ProfileLogger::Log()
if ( profiling_update ) if ( profiling_update )
{ {
mgr.Dispatch(new Event(profiling_update, { mgr.Dispatch(new Event(profiling_update, {
make_intrusive<Val>(IntrusivePtr{NewRef{}, file}), zeek::make_intrusive<zeek::Val>(zeek::IntrusivePtr{zeek::NewRef{}, file}),
val_mgr->Bool(expensive), zeek::val_mgr->Bool(expensive),
})); }));
} }
} }
void ProfileLogger::SegmentProfile(const char* name, const Location* loc, void ProfileLogger::SegmentProfile(const char* name, const zeek::detail::Location* loc,
double dtime, int dmem) double dtime, int dmem)
{ {
if ( name ) if ( name )
file->Write(fmt("%.06f segment-%s dt=%.06f dmem=%d\n", file->Write(fmt("%.06f segment-%s dt=%.06f dmem=%d\n",
@ -344,7 +344,7 @@ SampleLogger::SampleLogger()
if ( ! load_sample_info ) if ( ! load_sample_info )
load_sample_info = zeek::id::find_type("load_sample_info")->AsTableType(); load_sample_info = zeek::id::find_type("load_sample_info")->AsTableType();
load_samples = new TableVal({NewRef{}, load_sample_info}); load_samples = new zeek::TableVal({zeek::NewRef{}, load_sample_info});
} }
SampleLogger::~SampleLogger() SampleLogger::~SampleLogger()
@ -352,27 +352,27 @@ SampleLogger::~SampleLogger()
Unref(load_samples); Unref(load_samples);
} }
void SampleLogger::FunctionSeen(const Func* func) void SampleLogger::FunctionSeen(const zeek::Func* func)
{ {
auto idx = make_intrusive<StringVal>(func->Name()); auto idx = zeek::make_intrusive<zeek::StringVal>(func->Name());
load_samples->Assign(std::move(idx), nullptr); load_samples->Assign(std::move(idx), nullptr);
} }
void SampleLogger::LocationSeen(const Location* loc) void SampleLogger::LocationSeen(const zeek::detail::Location* loc)
{ {
auto idx = make_intrusive<StringVal>(loc->filename); auto idx = zeek::make_intrusive<zeek::StringVal>(loc->filename);
load_samples->Assign(std::move(idx), nullptr); load_samples->Assign(std::move(idx), nullptr);
} }
void SampleLogger::SegmentProfile(const char* /* name */, void SampleLogger::SegmentProfile(const char* /* name */,
const Location* /* loc */, const zeek::detail::Location* /* loc */,
double dtime, int dmem) double dtime, int dmem)
{ {
if ( load_sample ) if ( load_sample )
mgr.Enqueue(load_sample, mgr.Enqueue(load_sample,
IntrusivePtr{NewRef{}, load_samples}, zeek::IntrusivePtr{zeek::NewRef{}, load_samples},
make_intrusive<IntervalVal>(dtime, Seconds), zeek::make_intrusive<zeek::IntervalVal>(dtime, Seconds),
val_mgr->Int(dmem) zeek::val_mgr->Int(dmem)
); );
} }

View file

@ -2,16 +2,19 @@
#pragma once #pragma once
#include "zeek-config.h"
#include <sys/types.h> #include <sys/types.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/resource.h> #include <sys/resource.h>
#include <stdint.h> #include <stdint.h>
class Func;
class TableVal;
class Location;
class BroFile; class BroFile;
ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(TableVal, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(Location, zeek::detail);
// Object called by SegmentProfiler when it is done and reports its // Object called by SegmentProfiler when it is done and reports its
// cumulative CPU/memory statistics. // cumulative CPU/memory statistics.
class SegmentStatsReporter { class SegmentStatsReporter {
@ -19,7 +22,7 @@ public:
SegmentStatsReporter() { } SegmentStatsReporter() { }
virtual ~SegmentStatsReporter() { } virtual ~SegmentStatsReporter() { }
virtual void SegmentProfile(const char* name, const Location* loc, virtual void SegmentProfile(const char* name, const zeek::detail::Location* loc,
double dtime, int dmem) = 0; double dtime, int dmem) = 0;
}; };
@ -41,7 +44,7 @@ public:
} }
SegmentProfiler(SegmentStatsReporter* arg_reporter, SegmentProfiler(SegmentStatsReporter* arg_reporter,
const Location* arg_loc) const zeek::detail::Location* arg_loc)
: reporter(arg_reporter), name(), loc(arg_loc), initial_rusage() : reporter(arg_reporter), name(), loc(arg_loc), initial_rusage()
{ {
if ( reporter ) if ( reporter )
@ -60,7 +63,7 @@ protected:
SegmentStatsReporter* reporter; SegmentStatsReporter* reporter;
const char* name; const char* name;
const Location* loc; const zeek::detail::Location* loc;
struct rusage initial_rusage; struct rusage initial_rusage;
}; };
@ -74,8 +77,8 @@ public:
BroFile* File() { return file; } BroFile* File() { return file; }
protected: protected:
void SegmentProfile(const char* name, const Location* loc, void SegmentProfile(const char* name, const zeek::detail::Location* loc,
double dtime, int dmem) override; double dtime, int dmem) override;
private: private:
BroFile* file; BroFile* file;
@ -91,14 +94,14 @@ public:
// These are called to report that a given function or location // These are called to report that a given function or location
// has been seen during the sampling. // has been seen during the sampling.
void FunctionSeen(const Func* func); void FunctionSeen(const zeek::Func* func);
void LocationSeen(const Location* loc); void LocationSeen(const zeek::detail::Location* loc);
protected: protected:
void SegmentProfile(const char* name, const Location* loc, void SegmentProfile(const char* name, const zeek::detail::Location* loc,
double dtime, int dmem) override; double dtime, int dmem) override;
TableVal* load_samples; zeek::TableVal* load_samples;
}; };

View file

@ -71,7 +71,7 @@ ForStmt* Stmt::AsForStmt()
bool Stmt::SetLocationInfo(const Location* start, const Location* end) bool Stmt::SetLocationInfo(const Location* start, const Location* end)
{ {
if ( ! BroObj::SetLocationInfo(start, end) ) if ( ! Obj::SetLocationInfo(start, end) )
return false; return false;
// Update the Filemap of line number -> statement mapping for // Update the Filemap of line number -> statement mapping for
@ -151,7 +151,7 @@ void Stmt::AccessStats(ODesc* d) const
} }
} }
ExprListStmt::ExprListStmt(BroStmtTag t, IntrusivePtr<ListExpr> arg_l) ExprListStmt::ExprListStmt(BroStmtTag t, ListExprPtr arg_l)
: Stmt(t), l(std::move(arg_l)) : Stmt(t), l(std::move(arg_l))
{ {
const expr_list& e = l->Exprs(); const expr_list& e = l->Exprs();
@ -167,7 +167,7 @@ ExprListStmt::ExprListStmt(BroStmtTag t, IntrusivePtr<ListExpr> arg_l)
ExprListStmt::~ExprListStmt() = default; ExprListStmt::~ExprListStmt() = default;
IntrusivePtr<Val> ExprListStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr ExprListStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
last_access = network_time; last_access = network_time;
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -205,7 +205,7 @@ TraversalCode ExprListStmt::Traverse(TraversalCallback* cb) const
static BroFile* print_stdout = nullptr; static BroFile* print_stdout = nullptr;
static IntrusivePtr<EnumVal> lookup_enum_val(const char* module_name, const char* name) static EnumValPtr lookup_enum_val(const char* module_name, const char* name)
{ {
const auto& id = lookup_ID(name, module_name); const auto& id = lookup_ID(name, module_name);
assert(id); assert(id);
@ -219,27 +219,27 @@ static IntrusivePtr<EnumVal> lookup_enum_val(const char* module_name, const char
return et->GetVal(index); return et->GetVal(index);
} }
static void print_log(const std::vector<IntrusivePtr<Val>>& vals) static void print_log(const std::vector<ValPtr>& vals)
{ {
static auto plval = lookup_enum_val("Log", "PRINTLOG"); static auto plval = lookup_enum_val("Log", "PRINTLOG");
static auto lpli = zeek::id::find_type<RecordType>("Log::PrintLogInfo"); static auto lpli = zeek::id::find_type<RecordType>("Log::PrintLogInfo");
auto record = make_intrusive<RecordVal>(lpli); auto record = zeek::make_intrusive<zeek::RecordVal>(lpli);
auto vec = make_intrusive<VectorVal>(zeek::id::string_vec); auto vec = zeek::make_intrusive<zeek::VectorVal>(zeek::id::string_vec);
for ( const auto& val : vals ) for ( const auto& val : vals )
{ {
ODesc d(DESC_READABLE); ODesc d(DESC_READABLE);
val->Describe(&d); val->Describe(&d);
vec->Assign(vec->Size(), make_intrusive<StringVal>(d.Description())); vec->Assign(vec->Size(), zeek::make_intrusive<zeek::StringVal>(d.Description()));
} }
record->Assign(0, make_intrusive<TimeVal>(network_time)); record->Assign(0, zeek::make_intrusive<zeek::TimeVal>(network_time));
record->Assign(1, std::move(vec)); record->Assign(1, std::move(vec));
log_mgr->Write(plval.get(), record.get()); log_mgr->Write(plval.get(), record.get());
} }
IntrusivePtr<Val> PrintStmt::DoExec(std::vector<IntrusivePtr<Val>> vals, ValPtr PrintStmt::DoExec(std::vector<ValPtr> vals,
stmt_flow_type& /* flow */) const stmt_flow_type& /* flow */) const
{ {
RegisterAccess(); RegisterAccess();
@ -308,7 +308,7 @@ IntrusivePtr<Val> PrintStmt::DoExec(std::vector<IntrusivePtr<Val>> vals,
return nullptr; return nullptr;
} }
ExprStmt::ExprStmt(IntrusivePtr<Expr> arg_e) : Stmt(STMT_EXPR), e(std::move(arg_e)) ExprStmt::ExprStmt(ExprPtr arg_e) : Stmt(STMT_EXPR), e(std::move(arg_e))
{ {
if ( e && e->IsPure() ) if ( e && e->IsPure() )
Warn("expression value ignored"); Warn("expression value ignored");
@ -316,7 +316,7 @@ ExprStmt::ExprStmt(IntrusivePtr<Expr> arg_e) : Stmt(STMT_EXPR), e(std::move(arg_
SetLocationInfo(e->GetLocationInfo()); SetLocationInfo(e->GetLocationInfo());
} }
ExprStmt::ExprStmt(BroStmtTag t, IntrusivePtr<Expr> arg_e) : Stmt(t), e(std::move(arg_e)) ExprStmt::ExprStmt(BroStmtTag t, ExprPtr arg_e) : Stmt(t), e(std::move(arg_e))
{ {
if ( e ) if ( e )
SetLocationInfo(e->GetLocationInfo()); SetLocationInfo(e->GetLocationInfo());
@ -324,7 +324,7 @@ ExprStmt::ExprStmt(BroStmtTag t, IntrusivePtr<Expr> arg_e) : Stmt(t), e(std::mov
ExprStmt::~ExprStmt() = default; ExprStmt::~ExprStmt() = default;
IntrusivePtr<Val> ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -337,7 +337,7 @@ IntrusivePtr<Val> ExprStmt::Exec(Frame* f, stmt_flow_type& flow) const
return nullptr; return nullptr;
} }
IntrusivePtr<Val> ExprStmt::DoExec(Frame* /* f */, Val* /* v */, stmt_flow_type& /* flow */) const ValPtr ExprStmt::DoExec(Frame* /* f */, Val* /* v */, stmt_flow_type& /* flow */) const
{ {
return nullptr; return nullptr;
} }
@ -383,8 +383,9 @@ TraversalCode ExprStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IfStmt::IfStmt(IntrusivePtr<Expr> test, IfStmt::IfStmt(ExprPtr test,
IntrusivePtr<Stmt> arg_s1, IntrusivePtr<Stmt> arg_s2) StmtPtr arg_s1,
StmtPtr arg_s2)
: ExprStmt(STMT_IF, std::move(test)), : ExprStmt(STMT_IF, std::move(test)),
s1(std::move(arg_s1)), s2(std::move(arg_s2)) s1(std::move(arg_s1)), s2(std::move(arg_s2))
{ {
@ -398,7 +399,7 @@ IfStmt::IfStmt(IntrusivePtr<Expr> test,
IfStmt::~IfStmt() = default; IfStmt::~IfStmt() = default;
IntrusivePtr<Val> IfStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const ValPtr IfStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const
{ {
// Treat 0 as false, but don't require 1 for true. // Treat 0 as false, but don't require 1 for true.
Stmt* do_stmt = v->IsZero() ? s2.get() : s1.get(); Stmt* do_stmt = v->IsZero() ? s2.get() : s1.get();
@ -483,8 +484,8 @@ static BroStmtTag get_last_stmt_tag(const Stmt* stmt)
return get_last_stmt_tag(stmts->Stmts()[len - 1]); return get_last_stmt_tag(stmts->Stmts()[len - 1]);
} }
Case::Case(IntrusivePtr<ListExpr> arg_expr_cases, id_list* arg_type_cases, Case::Case(ListExprPtr arg_expr_cases, id_list* arg_type_cases,
IntrusivePtr<Stmt> arg_s) StmtPtr arg_s)
: expr_cases(std::move(arg_expr_cases)), type_cases(arg_type_cases), : expr_cases(std::move(arg_expr_cases)), type_cases(arg_type_cases),
s(std::move(arg_s)) s(std::move(arg_s))
{ {
@ -601,14 +602,14 @@ static void int_del_func(void* v)
void SwitchStmt::Init() void SwitchStmt::Init()
{ {
auto t = make_intrusive<TypeList>(); auto t = zeek::make_intrusive<TypeList>();
t->Append(e->GetType()); t->Append(e->GetType());
comp_hash = new CompositeHash(std::move(t)); comp_hash = new CompositeHash(std::move(t));
case_label_value_map.SetDeleteFunc(int_del_func); case_label_value_map.SetDeleteFunc(int_del_func);
} }
SwitchStmt::SwitchStmt(IntrusivePtr<Expr> index, case_list* arg_cases) SwitchStmt::SwitchStmt(ExprPtr index, case_list* arg_cases)
: ExprStmt(STMT_SWITCH, std::move(index)), : ExprStmt(STMT_SWITCH, std::move(index)),
cases(arg_cases), default_case_idx(-1) cases(arg_cases), default_case_idx(-1)
{ {
@ -814,9 +815,9 @@ std::pair<int, ID*> SwitchStmt::FindCaseLabelMatch(const Val* v) const
return std::make_pair(label_idx, label_id); return std::make_pair(label_idx, label_id);
} }
IntrusivePtr<Val> SwitchStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const ValPtr SwitchStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const
{ {
IntrusivePtr<Val> rval; ValPtr rval;
auto m = FindCaseLabelMatch(v); auto m = FindCaseLabelMatch(v);
int matching_label_idx = m.first; int matching_label_idx = m.first;
@ -899,7 +900,7 @@ TraversalCode SwitchStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
AddStmt::AddStmt(IntrusivePtr<Expr> arg_e) : ExprStmt(STMT_ADD, std::move(arg_e)) AddStmt::AddStmt(ExprPtr arg_e) : ExprStmt(STMT_ADD, std::move(arg_e))
{ {
if ( ! e->CanAdd() ) if ( ! e->CanAdd() )
Error("illegal add statement"); Error("illegal add statement");
@ -910,7 +911,7 @@ bool AddStmt::IsPure() const
return false; return false;
} }
IntrusivePtr<Val> AddStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr AddStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -932,7 +933,7 @@ TraversalCode AddStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
DelStmt::DelStmt(IntrusivePtr<Expr> arg_e) : ExprStmt(STMT_DELETE, std::move(arg_e)) DelStmt::DelStmt(ExprPtr arg_e) : ExprStmt(STMT_DELETE, std::move(arg_e))
{ {
if ( e->IsError() ) if ( e->IsError() )
return; return;
@ -946,7 +947,7 @@ bool DelStmt::IsPure() const
return false; return false;
} }
IntrusivePtr<Val> DelStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr DelStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -967,12 +968,12 @@ TraversalCode DelStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
EventStmt::EventStmt(IntrusivePtr<EventExpr> arg_e) EventStmt::EventStmt(EventExprPtr arg_e)
: ExprStmt(STMT_EVENT, arg_e), event_expr(std::move(arg_e)) : ExprStmt(STMT_EVENT, arg_e), event_expr(std::move(arg_e))
{ {
} }
IntrusivePtr<Val> EventStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr EventStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
auto args = eval_list(f, event_expr->Args()); auto args = eval_list(f, event_expr->Args());
@ -998,8 +999,8 @@ TraversalCode EventStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
WhileStmt::WhileStmt(IntrusivePtr<Expr> arg_loop_condition, WhileStmt::WhileStmt(ExprPtr arg_loop_condition,
IntrusivePtr<Stmt> arg_body) StmtPtr arg_body)
: loop_condition(std::move(arg_loop_condition)), body(std::move(arg_body)) : loop_condition(std::move(arg_loop_condition)), body(std::move(arg_body))
{ {
if ( ! loop_condition->IsError() && if ( ! loop_condition->IsError() &&
@ -1048,11 +1049,11 @@ TraversalCode WhileStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
IntrusivePtr<Val> rval; ValPtr rval;
for ( ; ; ) for ( ; ; )
{ {
@ -1077,7 +1078,7 @@ IntrusivePtr<Val> WhileStmt::Exec(Frame* f, stmt_flow_type& flow) const
return rval; return rval;
} }
ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr<Expr> loop_expr) ForStmt::ForStmt(id_list* arg_loop_vars, ExprPtr loop_expr)
: ExprStmt(STMT_FOR, std::move(loop_expr)) : ExprStmt(STMT_FOR, std::move(loop_expr))
{ {
loop_vars = arg_loop_vars; loop_vars = arg_loop_vars;
@ -1107,7 +1108,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr<Expr> loop_expr)
else else
{ {
add_local({NewRef{}, lv}, ind_type, INIT_NONE, add_local({zeek::NewRef{}, lv}, ind_type, INIT_NONE,
nullptr, nullptr, VAR_REGULAR); nullptr, nullptr, VAR_REGULAR);
} }
} }
@ -1124,7 +1125,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr<Expr> loop_expr)
const auto& t = (*loop_vars)[0]->GetType(); const auto& t = (*loop_vars)[0]->GetType();
if ( ! t ) if ( ! t )
add_local({NewRef{}, (*loop_vars)[0]}, base_type(TYPE_COUNT), add_local({zeek::NewRef{}, (*loop_vars)[0]}, base_type(TYPE_COUNT),
INIT_NONE, nullptr, nullptr, VAR_REGULAR); INIT_NONE, nullptr, nullptr, VAR_REGULAR);
else if ( ! IsIntegral(t->Tag()) ) else if ( ! IsIntegral(t->Tag()) )
@ -1145,7 +1146,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr<Expr> loop_expr)
const auto& t = (*loop_vars)[0]->GetType(); const auto& t = (*loop_vars)[0]->GetType();
if ( ! t ) if ( ! t )
add_local({NewRef{}, (*loop_vars)[0]}, add_local({zeek::NewRef{}, (*loop_vars)[0]},
base_type(TYPE_STRING), base_type(TYPE_STRING),
INIT_NONE, nullptr, nullptr, VAR_REGULAR); INIT_NONE, nullptr, nullptr, VAR_REGULAR);
@ -1160,7 +1161,7 @@ ForStmt::ForStmt(id_list* arg_loop_vars, IntrusivePtr<Expr> loop_expr)
} }
ForStmt::ForStmt(id_list* arg_loop_vars, ForStmt::ForStmt(id_list* arg_loop_vars,
IntrusivePtr<Expr> loop_expr, IntrusivePtr<ID> val_var) ExprPtr loop_expr, IDPtr val_var)
: ForStmt(arg_loop_vars, std::move(loop_expr)) : ForStmt(arg_loop_vars, std::move(loop_expr))
{ {
value_var = std::move(val_var); value_var = std::move(val_var);
@ -1191,14 +1192,14 @@ ForStmt::~ForStmt()
delete loop_vars; delete loop_vars;
} }
IntrusivePtr<Val> ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const ValPtr ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const
{ {
IntrusivePtr<Val> ret; ValPtr ret;
if ( v->GetType()->Tag() == TYPE_TABLE ) if ( v->GetType()->Tag() == TYPE_TABLE )
{ {
TableVal* tv = v->AsTableVal(); TableVal* tv = v->AsTableVal();
const PDict<TableEntryVal>* loop_vals = tv->AsTable(); const PDict<zeek::TableEntryVal>* loop_vals = tv->AsTable();
if ( ! loop_vals->Length() ) if ( ! loop_vals->Length() )
return nullptr; return nullptr;
@ -1251,7 +1252,7 @@ IntrusivePtr<Val> ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const
// Set the loop variable to the current index, and make // Set the loop variable to the current index, and make
// another pass over the loop body. // another pass over the loop body.
f->SetElement((*loop_vars)[0], val_mgr->Count(i)); f->SetElement((*loop_vars)[0], zeek::val_mgr->Count(i));
flow = FLOW_NEXT; flow = FLOW_NEXT;
ret = body->Exec(f, flow); ret = body->Exec(f, flow);
@ -1265,7 +1266,7 @@ IntrusivePtr<Val> ForStmt::DoExec(Frame* f, Val* v, stmt_flow_type& flow) const
for ( int i = 0; i < sval->Len(); ++i ) for ( int i = 0; i < sval->Len(); ++i )
{ {
auto sv = make_intrusive<StringVal>(1, (const char*) sval->Bytes() + i); auto sv = zeek::make_intrusive<zeek::StringVal>(1, (const char*) sval->Bytes() + i);
f->SetElement((*loop_vars)[0], std::move(sv)); f->SetElement((*loop_vars)[0], std::move(sv));
flow = FLOW_NEXT; flow = FLOW_NEXT;
ret = body->Exec(f, flow); ret = body->Exec(f, flow);
@ -1349,7 +1350,7 @@ TraversalCode ForStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> NextStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const ValPtr NextStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_LOOP; flow = FLOW_LOOP;
@ -1376,7 +1377,7 @@ TraversalCode NextStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> BreakStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const ValPtr BreakStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_BREAK; flow = FLOW_BREAK;
@ -1403,7 +1404,7 @@ TraversalCode BreakStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> FallthroughStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const ValPtr FallthroughStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_FALLTHROUGH; flow = FLOW_FALLTHROUGH;
@ -1430,7 +1431,7 @@ TraversalCode FallthroughStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
ReturnStmt::ReturnStmt(IntrusivePtr<Expr> arg_e) ReturnStmt::ReturnStmt(ExprPtr arg_e)
: ExprStmt(STMT_RETURN, std::move(arg_e)) : ExprStmt(STMT_RETURN, std::move(arg_e))
{ {
Scope* s = current_scope(); Scope* s = current_scope();
@ -1474,7 +1475,7 @@ ReturnStmt::ReturnStmt(IntrusivePtr<Expr> arg_e)
} }
} }
IntrusivePtr<Val> ReturnStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr ReturnStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_RETURN; flow = FLOW_RETURN;
@ -1513,7 +1514,7 @@ StmtList::~StmtList()
Unref(stmt); Unref(stmt);
} }
IntrusivePtr<Val> StmtList::Exec(Frame* f, stmt_flow_type& flow) const ValPtr StmtList::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -1592,7 +1593,7 @@ TraversalCode StmtList::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> EventBodyList::Exec(Frame* f, stmt_flow_type& flow) const ValPtr EventBodyList::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -1650,7 +1651,7 @@ void EventBodyList::Describe(ODesc* d) const
StmtList::Describe(d); StmtList::Describe(d);
} }
InitStmt::InitStmt(std::vector<IntrusivePtr<ID>> arg_inits) : Stmt(STMT_INIT) InitStmt::InitStmt(std::vector<IDPtr> arg_inits) : Stmt(STMT_INIT)
{ {
inits = std::move(arg_inits); inits = std::move(arg_inits);
@ -1658,7 +1659,7 @@ InitStmt::InitStmt(std::vector<IntrusivePtr<ID>> arg_inits) : Stmt(STMT_INIT)
SetLocationInfo(inits[0]->GetLocationInfo()); SetLocationInfo(inits[0]->GetLocationInfo());
} }
IntrusivePtr<Val> InitStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr InitStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -1667,18 +1668,18 @@ IntrusivePtr<Val> InitStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
const auto& t = aggr->GetType(); const auto& t = aggr->GetType();
IntrusivePtr<Val> v; ValPtr v;
switch ( t->Tag() ) { switch ( t->Tag() ) {
case TYPE_RECORD: case TYPE_RECORD:
v = make_intrusive<RecordVal>(cast_intrusive<RecordType>(t)); v = zeek::make_intrusive<zeek::RecordVal>(zeek::cast_intrusive<RecordType>(t));
break; break;
case TYPE_VECTOR: case TYPE_VECTOR:
v = make_intrusive<VectorVal>(cast_intrusive<VectorType>(t)); v = zeek::make_intrusive<zeek::VectorVal>(zeek::cast_intrusive<VectorType>(t));
break; break;
case TYPE_TABLE: case TYPE_TABLE:
v = make_intrusive<TableVal>(cast_intrusive<TableType>(t), v = zeek::make_intrusive<zeek::TableVal>(zeek::cast_intrusive<TableType>(t),
aggr->GetAttrs()); aggr->GetAttrs());
break; break;
default: default:
break; break;
@ -1723,7 +1724,7 @@ TraversalCode InitStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
IntrusivePtr<Val> NullStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const ValPtr NullStmt::Exec(Frame* /* f */, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;
@ -1752,9 +1753,9 @@ TraversalCode NullStmt::Traverse(TraversalCallback* cb) const
HANDLE_TC_STMT_POST(tc); HANDLE_TC_STMT_POST(tc);
} }
WhenStmt::WhenStmt(IntrusivePtr<Expr> arg_cond, WhenStmt::WhenStmt(ExprPtr arg_cond,
IntrusivePtr<Stmt> arg_s1, IntrusivePtr<Stmt> arg_s2, StmtPtr arg_s1, StmtPtr arg_s2,
IntrusivePtr<Expr> arg_timeout, bool arg_is_return) ExprPtr arg_timeout, bool arg_is_return)
: Stmt(STMT_WHEN), : Stmt(STMT_WHEN),
cond(std::move(arg_cond)), s1(std::move(arg_s1)), s2(std::move(arg_s2)), cond(std::move(arg_cond)), s1(std::move(arg_s1)), s2(std::move(arg_s2)),
timeout(std::move(arg_timeout)), is_return(arg_is_return) timeout(std::move(arg_timeout)), is_return(arg_is_return)
@ -1778,7 +1779,7 @@ WhenStmt::WhenStmt(IntrusivePtr<Expr> arg_cond,
WhenStmt::~WhenStmt() = default; WhenStmt::~WhenStmt() = default;
IntrusivePtr<Val> WhenStmt::Exec(Frame* f, stmt_flow_type& flow) const ValPtr WhenStmt::Exec(Frame* f, stmt_flow_type& flow) const
{ {
RegisterAccess(); RegisterAccess();
flow = FLOW_NEXT; flow = FLOW_NEXT;

View file

@ -14,7 +14,8 @@
#include "TraverseTypes.h" #include "TraverseTypes.h"
class CompositeHash; class CompositeHash;
class Frame;
ZEEK_FORWARD_DECLARE_NAMESPACED(Frame, zeek::detail);
namespace zeek::detail { namespace zeek::detail {
@ -23,15 +24,21 @@ class ForStmt;
class EventExpr; class EventExpr;
class ListExpr; class ListExpr;
class Stmt : public BroObj { using EventExprPtr = zeek::IntrusivePtr<EventExpr>;
using ListExprPtr = zeek::IntrusivePtr<ListExpr>;
class Stmt;
using StmtPtr = zeek::IntrusivePtr<Stmt>;
class Stmt : public Obj {
public: public:
BroStmtTag Tag() const { return tag; } BroStmtTag Tag() const { return tag; }
~Stmt() override; ~Stmt() override;
virtual IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const = 0; virtual ValPtr Exec(Frame* f, stmt_flow_type& flow) const = 0;
Stmt* Ref() { ::Ref(this); return this; } Stmt* Ref() { zeek::Ref(this); return this; }
bool SetLocationInfo(const Location* loc) override bool SetLocationInfo(const Location* loc) override
{ return Stmt::SetLocationInfo(loc, loc); } { return Stmt::SetLocationInfo(loc, loc); }
@ -80,17 +87,17 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
ExprListStmt(BroStmtTag t, IntrusivePtr<ListExpr> arg_l); ExprListStmt(BroStmtTag t, ListExprPtr arg_l);
~ExprListStmt() override; ~ExprListStmt() override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
virtual IntrusivePtr<Val> DoExec(std::vector<IntrusivePtr<Val>> vals, virtual ValPtr DoExec(std::vector<ValPtr> vals,
stmt_flow_type& flow) const = 0; stmt_flow_type& flow) const = 0;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
IntrusivePtr<ListExpr> l; ListExprPtr l;
}; };
class PrintStmt final : public ExprListStmt { class PrintStmt final : public ExprListStmt {
@ -99,16 +106,16 @@ public:
explicit PrintStmt(L&& l) : ExprListStmt(STMT_PRINT, std::forward<L>(l)) { } explicit PrintStmt(L&& l) : ExprListStmt(STMT_PRINT, std::forward<L>(l)) { }
protected: protected:
IntrusivePtr<Val> DoExec(std::vector<IntrusivePtr<Val>> vals, ValPtr DoExec(std::vector<ValPtr> vals,
stmt_flow_type& flow) const override; stmt_flow_type& flow) const override;
}; };
class ExprStmt : public Stmt { class ExprStmt : public Stmt {
public: public:
explicit ExprStmt(IntrusivePtr<Expr> e); explicit ExprStmt(ExprPtr e);
~ExprStmt() override; ~ExprStmt() override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
const Expr* StmtExpr() const { return e.get(); } const Expr* StmtExpr() const { return e.get(); }
@ -117,18 +124,18 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
ExprStmt(BroStmtTag t, IntrusivePtr<Expr> e); ExprStmt(BroStmtTag t, ExprPtr e);
virtual IntrusivePtr<Val> DoExec(Frame* f, Val* v, stmt_flow_type& flow) const; virtual ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const;
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Expr> e; ExprPtr e;
}; };
class IfStmt final : public ExprStmt { class IfStmt final : public ExprStmt {
public: public:
IfStmt(IntrusivePtr<Expr> test, IntrusivePtr<Stmt> s1, IntrusivePtr<Stmt> s2); IfStmt(ExprPtr test, StmtPtr s1, StmtPtr s2);
~IfStmt() override; ~IfStmt() override;
const Stmt* TrueBranch() const { return s1.get(); } const Stmt* TrueBranch() const { return s1.get(); }
@ -139,16 +146,16 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Val> DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Stmt> s1; StmtPtr s1;
IntrusivePtr<Stmt> s2; StmtPtr s2;
}; };
class Case final : public BroObj { class Case final : public Obj {
public: public:
Case(IntrusivePtr<ListExpr> c, id_list* types, IntrusivePtr<Stmt> arg_s); Case(ListExprPtr c, id_list* types, StmtPtr arg_s);
~Case() override; ~Case() override;
const ListExpr* ExprCases() const { return expr_cases.get(); } const ListExpr* ExprCases() const { return expr_cases.get(); }
@ -165,16 +172,16 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const; TraversalCode Traverse(TraversalCallback* cb) const;
protected: protected:
IntrusivePtr<ListExpr> expr_cases; ListExprPtr expr_cases;
id_list* type_cases; id_list* type_cases;
IntrusivePtr<Stmt> s; StmtPtr s;
}; };
using case_list = PList<Case>; using case_list = zeek::PList<Case>;
class SwitchStmt final : public ExprStmt { class SwitchStmt final : public ExprStmt {
public: public:
SwitchStmt(IntrusivePtr<Expr> index, case_list* cases); SwitchStmt(ExprPtr index, case_list* cases);
~SwitchStmt() override; ~SwitchStmt() override;
const case_list* Cases() const { return cases; } const case_list* Cases() const { return cases; }
@ -184,7 +191,7 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Val> DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
// Initialize composite hash and case label map. // Initialize composite hash and case label map.
@ -209,46 +216,46 @@ protected:
case_list* cases; case_list* cases;
int default_case_idx; int default_case_idx;
CompositeHash* comp_hash; CompositeHash* comp_hash;
PDict<int> case_label_value_map; zeek::PDict<int> case_label_value_map;
std::vector<std::pair<ID*, int>> case_label_type_list; std::vector<std::pair<ID*, int>> case_label_type_list;
}; };
class AddStmt final : public ExprStmt { class AddStmt final : public ExprStmt {
public: public:
explicit AddStmt(IntrusivePtr<Expr> e); explicit AddStmt(ExprPtr e);
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
}; };
class DelStmt final : public ExprStmt { class DelStmt final : public ExprStmt {
public: public:
explicit DelStmt(IntrusivePtr<Expr> e); explicit DelStmt(ExprPtr e);
bool IsPure() const override; bool IsPure() const override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
}; };
class EventStmt final : public ExprStmt { class EventStmt final : public ExprStmt {
public: public:
explicit EventStmt(IntrusivePtr<EventExpr> e); explicit EventStmt(EventExprPtr e);
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<EventExpr> event_expr; EventExprPtr event_expr;
}; };
class WhileStmt final : public Stmt { class WhileStmt final : public Stmt {
public: public:
WhileStmt(IntrusivePtr<Expr> loop_condition, IntrusivePtr<Stmt> body); WhileStmt(ExprPtr loop_condition, StmtPtr body);
~WhileStmt() override; ~WhileStmt() override;
bool IsPure() const override; bool IsPure() const override;
@ -258,20 +265,20 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
IntrusivePtr<Expr> loop_condition; ExprPtr loop_condition;
IntrusivePtr<Stmt> body; StmtPtr body;
}; };
class ForStmt final : public ExprStmt { class ForStmt final : public ExprStmt {
public: public:
ForStmt(id_list* loop_vars, IntrusivePtr<Expr> loop_expr); ForStmt(id_list* loop_vars, ExprPtr loop_expr);
// Special constructor for key value for loop. // Special constructor for key value for loop.
ForStmt(id_list* loop_vars, IntrusivePtr<Expr> loop_expr, IntrusivePtr<ID> val_var); ForStmt(id_list* loop_vars, ExprPtr loop_expr, IDPtr val_var);
~ForStmt() override; ~ForStmt() override;
void AddBody(IntrusivePtr<Stmt> arg_body) { body = std::move(arg_body); } void AddBody(StmtPtr arg_body) { body = std::move(arg_body); }
const id_list* LoopVar() const { return loop_vars; } const id_list* LoopVar() const { return loop_vars; }
const Expr* LoopExpr() const { return e.get(); } const Expr* LoopExpr() const { return e.get(); }
@ -284,20 +291,20 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Val> DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override; ValPtr DoExec(Frame* f, Val* v, stmt_flow_type& flow) const override;
id_list* loop_vars; id_list* loop_vars;
IntrusivePtr<Stmt> body; StmtPtr body;
// Stores the value variable being used for a key value for loop. // Stores the value variable being used for a key value for loop.
// Always set to nullptr unless special constructor is called. // Always set to nullptr unless special constructor is called.
IntrusivePtr<ID> value_var; IDPtr value_var;
}; };
class NextStmt final : public Stmt { class NextStmt final : public Stmt {
public: public:
NextStmt() : Stmt(STMT_NEXT) { } NextStmt() : Stmt(STMT_NEXT) { }
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -311,7 +318,7 @@ class BreakStmt final : public Stmt {
public: public:
BreakStmt() : Stmt(STMT_BREAK) { } BreakStmt() : Stmt(STMT_BREAK) { }
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -325,7 +332,7 @@ class FallthroughStmt final : public Stmt {
public: public:
FallthroughStmt() : Stmt(STMT_FALLTHROUGH) { } FallthroughStmt() : Stmt(STMT_FALLTHROUGH) { }
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -337,9 +344,9 @@ protected:
class ReturnStmt final : public ExprStmt { class ReturnStmt final : public ExprStmt {
public: public:
explicit ReturnStmt(IntrusivePtr<Expr> e); explicit ReturnStmt(ExprPtr e);
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
}; };
@ -349,7 +356,7 @@ public:
StmtList(); StmtList();
~StmtList() override; ~StmtList() override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
const stmt_list& Stmts() const { return stmts; } const stmt_list& Stmts() const { return stmts; }
stmt_list& Stmts() { return stmts; } stmt_list& Stmts() { return stmts; }
@ -369,7 +376,7 @@ public:
EventBodyList() : StmtList() EventBodyList() : StmtList()
{ topmost = false; tag = STMT_EVENT_BODY_LIST; } { topmost = false; tag = STMT_EVENT_BODY_LIST; }
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -383,11 +390,11 @@ protected:
class InitStmt final : public Stmt { class InitStmt final : public Stmt {
public: public:
explicit InitStmt(std::vector<IntrusivePtr<ID>> arg_inits); explicit InitStmt(std::vector<IDPtr> arg_inits);
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
const std::vector<IntrusivePtr<ID>>& Inits() const const std::vector<IDPtr>& Inits() const
{ return inits; } { return inits; }
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -395,14 +402,14 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
std::vector<IntrusivePtr<ID>> inits; std::vector<IDPtr> inits;
}; };
class NullStmt final : public Stmt { class NullStmt final : public Stmt {
public: public:
NullStmt() : Stmt(STMT_NULL) { } NullStmt() : Stmt(STMT_NULL) { }
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
void Describe(ODesc* d) const override; void Describe(ODesc* d) const override;
@ -413,12 +420,12 @@ public:
class WhenStmt final : public Stmt { class WhenStmt final : public Stmt {
public: public:
// s2 is null if no timeout block given. // s2 is null if no timeout block given.
WhenStmt(IntrusivePtr<Expr> cond, WhenStmt(ExprPtr cond,
IntrusivePtr<Stmt> s1, IntrusivePtr<Stmt> s2, StmtPtr s1, StmtPtr s2,
IntrusivePtr<Expr> timeout, bool is_return); ExprPtr timeout, bool is_return);
~WhenStmt() override; ~WhenStmt() override;
IntrusivePtr<Val> Exec(Frame* f, stmt_flow_type& flow) const override; ValPtr Exec(Frame* f, stmt_flow_type& flow) const override;
bool IsPure() const override; bool IsPure() const override;
const Expr* Cond() const { return cond.get(); } const Expr* Cond() const { return cond.get(); }
@ -431,10 +438,10 @@ public:
TraversalCode Traverse(TraversalCallback* cb) const override; TraversalCode Traverse(TraversalCallback* cb) const override;
protected: protected:
IntrusivePtr<Expr> cond; ExprPtr cond;
IntrusivePtr<Stmt> s1; StmtPtr s1;
IntrusivePtr<Stmt> s2; StmtPtr s2;
IntrusivePtr<Expr> timeout; ExprPtr timeout;
bool is_return; bool is_return;
}; };

View file

@ -2,9 +2,8 @@
#include "Tag.h" #include "Tag.h"
#include "Val.h" #include "Val.h"
#include "IntrusivePtr.h"
Tag::Tag(const IntrusivePtr<zeek::EnumType>& etype, type_t arg_type, subtype_t arg_subtype) Tag::Tag(const zeek::EnumTypePtr& etype, type_t arg_type, subtype_t arg_subtype)
{ {
assert(arg_type > 0); assert(arg_type > 0);
@ -15,10 +14,10 @@ Tag::Tag(const IntrusivePtr<zeek::EnumType>& etype, type_t arg_type, subtype_t a
} }
Tag::Tag(zeek::EnumType* etype, type_t arg_type, subtype_t arg_subtype) Tag::Tag(zeek::EnumType* etype, type_t arg_type, subtype_t arg_subtype)
: Tag({NewRef{}, etype}, arg_type, arg_subtype) : Tag({zeek::NewRef{}, etype}, arg_type, arg_subtype)
{ } { }
Tag::Tag(IntrusivePtr<EnumVal> arg_val) Tag::Tag(zeek::EnumValPtr arg_val)
{ {
assert(arg_val); assert(arg_val);
@ -29,8 +28,8 @@ Tag::Tag(IntrusivePtr<EnumVal> arg_val)
subtype = (i >> 31) & 0xffffffff; subtype = (i >> 31) & 0xffffffff;
} }
Tag::Tag(EnumVal* arg_val) Tag::Tag(zeek::EnumVal* arg_val)
: Tag({NewRef{}, arg_val}) : Tag({zeek::NewRef{}, arg_val})
{ } { }
Tag::Tag(const Tag& other) Tag::Tag(const Tag& other)
@ -73,7 +72,7 @@ Tag& Tag::operator=(const Tag&& other) noexcept
return *this; return *this;
} }
const IntrusivePtr<EnumVal>& Tag::AsVal(const IntrusivePtr<zeek::EnumType>& etype) const const zeek::EnumValPtr& Tag::AsVal(const zeek::EnumTypePtr& etype) const
{ {
if ( ! val ) if ( ! val )
{ {
@ -84,9 +83,9 @@ const IntrusivePtr<EnumVal>& Tag::AsVal(const IntrusivePtr<zeek::EnumType>& etyp
return val; return val;
} }
EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const zeek::EnumVal* Tag::AsEnumVal(zeek::EnumType* etype) const
{ {
return AsVal({NewRef{}, etype}).get(); return AsVal({zeek::NewRef{}, etype}).get();
} }
std::string Tag::AsString() const std::string Tag::AsString() const

View file

@ -10,9 +10,14 @@
#include "IntrusivePtr.h" #include "IntrusivePtr.h"
#include "util.h" #include "util.h"
class EnumVal; ZEEK_FORWARD_DECLARE_NAMESPACED(EnumVal, zeek);
ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek); ZEEK_FORWARD_DECLARE_NAMESPACED(EnumType, zeek);
namespace zeek {
using EnumTypePtr = zeek::IntrusivePtr<zeek::EnumType>;
using EnumValPtr = zeek::IntrusivePtr<zeek::EnumVal>;
}
/** /**
* Class to identify an analyzer type. * Class to identify an analyzer type.
* *
@ -116,10 +121,10 @@ protected:
* *
* @param etype the script-layer enum type associated with the tag. * @param etype the script-layer enum type associated with the tag.
*/ */
const IntrusivePtr<EnumVal>& AsVal(const IntrusivePtr<zeek::EnumType>& etype) const; const zeek::EnumValPtr& AsVal(const zeek::EnumTypePtr& etype) const;
[[deprecated("Remove in v4.1. Use AsVal() instead.")]] [[deprecated("Remove in v4.1. Use AsVal() instead.")]]
EnumVal* AsEnumVal(zeek::EnumType* etype) const; zeek::EnumVal* AsEnumVal(zeek::EnumType* etype) const;
/** /**
* Constructor. * Constructor.
@ -132,9 +137,9 @@ protected:
* @param subtype The sub type, which is left to an analyzer for * @param subtype The sub type, which is left to an analyzer for
* interpretation. By default it's set to zero. * interpretation. By default it's set to zero.
*/ */
Tag(const IntrusivePtr<zeek::EnumType>& etype, type_t type, subtype_t subtype = 0); Tag(const zeek::EnumTypePtr& etype, type_t type, subtype_t subtype = 0);
[[deprecated("Remove in v4.1. Construct from IntrusivePtr& instead.")]] [[deprecated("Remove in v4.1. Construct from zeek::IntrusivePtr& instead.")]]
Tag(zeek::EnumType* etype, type_t type, subtype_t subtype = 0); Tag(zeek::EnumType* etype, type_t type, subtype_t subtype = 0);
/** /**
@ -142,13 +147,13 @@ protected:
* *
* @param val An enum value of script type \c Analyzer::Tag. * @param val An enum value of script type \c Analyzer::Tag.
*/ */
explicit Tag(IntrusivePtr<EnumVal> val); explicit Tag(zeek::EnumValPtr val);
[[deprecated("Remove in v4.1. Construct from IntrusivePtr instead.")]] [[deprecated("Remove in v4.1. Construct from zeek::IntrusivePtr instead.")]]
explicit Tag(EnumVal* val); explicit Tag(zeek::EnumVal* val);
private: private:
type_t type; // Main type. type_t type; // Main type.
subtype_t subtype; // Subtype. subtype_t subtype; // Subtype.
mutable IntrusivePtr<EnumVal> val; // Script-layer value. mutable zeek::EnumValPtr val; // Script-layer value.
}; };

View file

@ -7,16 +7,16 @@
TraversalCode traverse_all(TraversalCallback* cb) TraversalCode traverse_all(TraversalCallback* cb)
{ {
if ( ! global_scope() ) if ( ! zeek::detail::global_scope() )
return TC_CONTINUE; return TC_CONTINUE;
if ( ! stmts ) if ( ! stmts )
// May be null when parsing fails. // May be null when parsing fails.
return TC_CONTINUE; return TC_CONTINUE;
cb->current_scope = global_scope(); cb->current_scope = zeek::detail::global_scope();
TraversalCode tc = global_scope()->Traverse(cb); TraversalCode tc = zeek::detail::global_scope()->Traverse(cb);
HANDLE_TC_STMT_PRE(tc); HANDLE_TC_STMT_PRE(tc);
tc = stmts->Traverse(cb); tc = stmts->Traverse(cb);

View file

@ -4,9 +4,8 @@
#include "TraverseTypes.h" #include "TraverseTypes.h"
class Func; ZEEK_FORWARD_DECLARE_NAMESPACED(Func, zeek);
class Scope; ZEEK_FORWARD_DECLARE_NAMESPACED(Scope, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Stmt, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(Expr, zeek::detail);
ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail); ZEEK_FORWARD_DECLARE_NAMESPACED(ID, zeek::detail);
@ -16,8 +15,8 @@ public:
TraversalCallback() { current_scope = nullptr; } TraversalCallback() { current_scope = nullptr; }
virtual ~TraversalCallback() {} virtual ~TraversalCallback() {}
virtual TraversalCode PreFunction(const Func*) { return TC_CONTINUE; } virtual TraversalCode PreFunction(const zeek::Func*) { return TC_CONTINUE; }
virtual TraversalCode PostFunction(const Func*) { return TC_CONTINUE; } virtual TraversalCode PostFunction(const zeek::Func*) { return TC_CONTINUE; }
virtual TraversalCode PreStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; } virtual TraversalCode PreStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; }
virtual TraversalCode PostStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; } virtual TraversalCode PostStmt(const zeek::detail::Stmt*) { return TC_CONTINUE; }
@ -34,7 +33,7 @@ public:
virtual TraversalCode PreDecl(const zeek::detail::ID*) { return TC_CONTINUE; } virtual TraversalCode PreDecl(const zeek::detail::ID*) { return TC_CONTINUE; }
virtual TraversalCode PostDecl(const zeek::detail::ID*) { return TC_CONTINUE; } virtual TraversalCode PostDecl(const zeek::detail::ID*) { return TC_CONTINUE; }
Scope* current_scope; zeek::detail::Scope* current_scope;
}; };
TraversalCode traverse_all(TraversalCallback* cb); TraversalCode traverse_all(TraversalCallback* cb);

View file

@ -59,7 +59,7 @@ TraversalCode zeek::detail::trigger::TriggerTraversalCallback::PreExpr(const zee
case EXPR_INDEX: case EXPR_INDEX:
{ {
const auto* e = static_cast<const zeek::detail::IndexExpr*>(expr); const auto* e = static_cast<const zeek::detail::IndexExpr*>(expr);
BroObj::SuppressErrors no_errors; Obj::SuppressErrors no_errors;
try try
{ {
@ -151,7 +151,7 @@ Trigger::Trigger(zeek::detail::Expr* arg_cond, zeek::detail::Stmt* arg_body,
arg_frame->SetDelayed(); arg_frame->SetDelayed();
} }
IntrusivePtr<Val> timeout_val; ValPtr timeout_val;
if ( arg_timeout ) if ( arg_timeout )
{ {
@ -262,9 +262,9 @@ bool Trigger::Eval()
return false; return false;
} }
f->SetTrigger({NewRef{}, this}); f->SetTrigger({zeek::NewRef{}, this});
IntrusivePtr<Val> v; ValPtr v;
try try
{ {
@ -348,8 +348,8 @@ void Trigger::Timeout()
if ( timeout_stmts ) if ( timeout_stmts )
{ {
stmt_flow_type flow; stmt_flow_type flow;
IntrusivePtr<Frame> f{AdoptRef{}, frame->Clone()}; FramePtr f{zeek::AdoptRef{}, frame->Clone()};
IntrusivePtr<Val> v; ValPtr v;
try try
{ {

Some files were not shown because too many files have changed in this diff Show more