diff options
author | sidchat@google.com <sidchat@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-06-15 22:18:40 +0000 |
---|---|---|
committer | sidchat@google.com <sidchat@google.com@0039d316-1c4b-4281-b951-d872f2087c98> | 2009-06-15 22:18:40 +0000 |
commit | 030bdf761f264aa1541a9bf26221fa47e24d5d6e (patch) | |
tree | 9f97599c9a52ef53f35c92e0ae09d31f41ae194c /third_party/cld/base | |
parent | 30b0252c5534d65a19b1b98d2ae72fbbfe5a5952 (diff) | |
download | chromium_src-030bdf761f264aa1541a9bf26221fa47e24d5d6e.zip chromium_src-030bdf761f264aa1541a9bf26221fa47e24d5d6e.tar.gz chromium_src-030bdf761f264aa1541a9bf26221fa47e24d5d6e.tar.bz2 |
Add Compact Language Detection (CLD) library to Chrome. This works in Windows only currently.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/122007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@18445 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'third_party/cld/base')
-rw-r--r-- | third_party/cld/base/callback.h | 308 | ||||
-rw-r--r-- | third_party/cld/base/casts.h | 156 | ||||
-rw-r--r-- | third_party/cld/base/closure.h | 12 | ||||
-rw-r--r-- | third_party/cld/base/commandlineflags.h | 443 | ||||
-rw-r--r-- | third_party/cld/base/crash.h | 41 | ||||
-rw-r--r-- | third_party/cld/base/dynamic_annotations.h | 358 | ||||
-rw-r--r-- | third_party/cld/base/global_strip_options.h | 59 | ||||
-rw-r--r-- | third_party/cld/base/google.h | 212 | ||||
-rw-r--r-- | third_party/cld/base/googleinit.h | 384 | ||||
-rw-r--r-- | third_party/cld/base/log_severity.h | 46 | ||||
-rw-r--r-- | third_party/cld/base/logging.h | 1403 | ||||
-rw-r--r-- | third_party/cld/base/macros.h | 252 | ||||
-rw-r--r-- | third_party/cld/base/scoped_ptr.h | 428 | ||||
-rw-r--r-- | third_party/cld/base/stl_decl.h | 24 | ||||
-rw-r--r-- | third_party/cld/base/stl_decl_msvc.h | 107 | ||||
-rw-r--r-- | third_party/cld/base/strtoint.h | 93 | ||||
-rw-r--r-- | third_party/cld/base/template_util.h | 96 | ||||
-rw-r--r-- | third_party/cld/base/type_traits.h | 198 | ||||
-rw-r--r-- | third_party/cld/base/vlog_is_on.h | 141 |
19 files changed, 4761 insertions, 0 deletions
diff --git a/third_party/cld/base/callback.h b/third_party/cld/base/callback.h new file mode 100644 index 0000000..d4f4644 --- /dev/null +++ b/third_party/cld/base/callback.h @@ -0,0 +1,308 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Callback classes provides a generic interface for classes requiring +// callback from other classes. +// We support callbacks with 0, 1, 2, 3, and 4 arguments. +// Closure -- provides "void Run()" +// Callback1<T1> -- provides "void Run(T1)" +// Callback2<T1,T2> -- provides "void Run(T1, T2)" +// Callback3<T1,T2,T3> -- provides "void Run(T1, T2, T3)" +// Callback4<T1,T2,T3,T4> -- provides "void Run(T1, T2, T3, T4)" +// +// In addition, ResultCallback classes provide a generic interface for +// callbacks that return a value. +// ResultCallback<R> -- provides "R Run()" +// ResultCallback1<R,T1> -- provides "R Run(T1)" +// ResultCallback2<R,T1,T2> -- provides "R Run(T1, T2)" +// ResultCallback3<R,T1,T2,T3> -- provides "R Run(T1, T2, T3)" +// ResultCallback4<R,T1,T2,T3,T4> -- provides "R Run(T1, T2, T3, T4)" + +// We provide a convenient mechanism, NewCallback, for generating one of these +// callbacks given an object pointer, a pointer to a member +// function with the appropriate signature in that object's class, +// and some optional arguments that can be bound into the callback +// object. The mechanism also works with just a function pointer. +// +// Note: there are two types of arguments passed to the callback method: +// * "pre-bound arguments" - supplied when the callback object is created +// * "call-time arguments" - supplied when the callback object is invoked +// +// These two types correspond to "early binding" and "late +// binding". An argument whose value is known when the callback is +// created ("early") can be pre-bound (a.k.a. "Curried"), You can +// combine pre-bound and call-time arguments in different ways. For +// example, invoking a callback with 3 pre-bound arguments and 1 +// call-time argument will have the same effect as invoking a callback +// with 2 pre-bound arguments and 2 call-time arguments, or 4 +// pre-bound arguments and no call-time arguments. This last case is +// often useful; a callback with no call-time arguments is a Closure; +// these are used in many places in the Google libraries, e.g., "done" +// closures. See the examples below. +// +// WARNING: In the current implementation (or perhaps with the current +// compiler) NewCallback() is pickier about the types of pre-bound arguments +// than you might expect. The types must match exactly, rather than merely +// being compatible. +// For example, if you pre-bind an argument with the "const" specifier, +// make sure that the actual parameter passed to NewCallback also has the +// const specifier. If you don't you'll get an error about +// passing a your function "as argument 1 of NewCallback(void (*)())". +// Using a method or function that has reference arguments among its pre-bound +// arguments may not always work. +// +// Examples: +// +// void Call0(Closure* cb) { cb->Run(); } +// void Call1(Callback1<int>* cb, int a) { cb->Run(a); } +// void Call2(Callback2<int, float>* cb, int a, float f) { cb->Run(a, f); } +// float Call3(ResultCallback1<float, int>* cb, int a) { return cb->Run(a); } +// +// class Foo { +// public: +// void A(int a); +// void B(int a, float f); +// void C(const char* label, int a, float f); +// float D(int a); +// }; +// void F0(int a); +// void F1(int a, float f); +// void F2(const char *label, int a, float f); +// float F3(int a); +// float v; +// +// // Run stuff immediately +// // calling a method +// Foo* foo = new Foo; +// +// NewCallback(foo, &Foo::A) ->Run(10); // 0 [pre-bound] + 1 [call-time] +// == NewCallback(foo, &Foo::A, 10) ->Run(); // 1 + 0 +// == foo->A(10); +// +// NewCallback(foo, &Foo::B) ->Run(10, 3.0f); // 0 + 2 +// == NewCallback(foo, &Foo::B, 10) ->Run(3.0f); // 1 + 1 +// == NewCallback(foo, &Foo::B, 10, 3.0f) ->Run(); // 2 + 0 +// == foo->B(10, 3.0f); +// +// NewCallback(foo, &Foo::C) ->Run("Y", 10, 3.0f); // 0 + 3 +// == NewCallback(foo, &Foo::C, "Y") ->Run(10, 3.0f); // 1 + 2 +// == NewCallback(foo, &Foo::C, "Y", 10) ->Run(3.0f); // 2 + 1 +// == NewCallback(foo, &Foo::C, "Y", 10, 3.0f) ->Run(); // 3 + 0 +// == foo->C("Y", 10, 3.0f); +// +// v = NewCallback(foo, &Foo::D) ->Run(10); == v = foo->D(10) +// +// // calling a function +// NewCallback(F0) ->Run(10); // == F0(10) // 0 + 1 +// NewCallback(F0, 10) ->Run(); // == F0(10) // 1 + 0 +// NewCallback(F1) ->Run(10, 3.0f); // == F1(10, 3.0f) +// NewCallback(F2, "X") ->Run(10, 3.0f); // == F2("X", 10, 3.0f) +// NewCallback(F2, "Y") ->Run(10, 3.0f); // == F2("Y", 10, 3.0f) +// v = NewCallback(F3) ->Run(10); // == v = F3(10) +// +// +// // Pass callback object to somebody else, who runs it. +// // Calling a method: +// Call1(NewCallback(foo, &Foo::A), 10); // 0 + 1 +// == Call0(NewCallback(foo, &Foo::A, 10) ); // 1 + 0 +// == foo->A(10) +// +// Call2(NewCallback(foo, &Foo::B), 10, 3.0f); // 0 + 2 +// == Call1(NewCallback(foo, &Foo::B, 10), 3.0f); // 1 + 1 +// == Call0(NewCallback(foo, &Foo::B, 10, 30.f) ); // 2 + 0 +// == foo->B(10, 3.0f) +// +// Call2(NewCallback(foo, &Foo::C, "X"), 10, 3.0f); == foo->C("X", 10, 3.0f) +// Call2(NewCallback(foo, &Foo::C, "Y"), 10, 3.0f); == foo->C("Y", 10, 3.0f) +// +// // Calling a function: +// Call1(NewCallback(F0), 10); // 0 + 1 +// == Call0(NewCallback(F0, 10) ); // 1 + 0 +// == F0(10); +// +// Call2(NewCallback(F1), 10, 3.0f); // == F1(10, 3.0f) +// Call2(NewCallback(F2, "X"), 10, 3.0f); // == F2("X", 10, 3.0f) +// Call2(NewCallback(F2, "Y"), 10, 3.0f); // == F2("Y", 10, 3.0f) +// v = Call3(NewCallback(F3), 10); // == v = F3(10) +// +// Example of a "done" closure: +// +// SelectServer ss; +// Closure* done = NewCallback(&ss, &SelectServer::MakeLoopExit); +// ProcessMyControlFlow(..., done); +// ss.Loop(); +// ... +// +// The following WILL NOT WORK: +// NewCallback(F2, (char *) "Y") ->Run(10, 3.0f); +// It gets the error: +// passing `void (*)(const char *, int, float)' as argument 1 of +// `NewCallback(void (*)())' +// The problem is that "char *" is not an _exact_ match for +// "const char *", even though it's normally a legal implicit +// conversion. +// +// +// The callback objects generated by NewCallback are self-deleting: +// i.e., they call the member function, and then delete themselves. +// If you want a callback that does not delete itself every time +// it runs, use "NewPermanentCallback" instead of "NewCallback". +// +// All the callback/closure classes also provide +// virtual void CheckIsRepeatable() const; +// It crashes if (we know for sure that) the callback's Run method +// can not be called an arbitrary number of times (including 0). +// It crashes for all NewCallback() generated callbacks, +// does not crash for NewPermanentCallback() generated callbacks, +// and although by default it does not crash for all callback-derived classes, +// for these new types of callbacks, the callback writer is encouraged to +// redefine this method appropriately. +// +// CAVEAT: Interfaces that accept callback pointers should clearly document +// if they might call Run methods of those callbacks multiple times +// (and use "c->CheckIsRepeatable();" as an active precondition check), +// or if they call the callbacks exactly once or potentially not at all, +// as well as if they take ownership of the passed callbacks +// (i.e. might manually deallocate them without calling their Run methods). +// The clients can then provide properly allocated and behaving callbacks +// (e.g. choose between NewCallback, NewPermanentCallback, or a custom object). +// Obviously, one should also be careful to ensure that the data a callback +// points to and needs for its Run method is still live when +// the Run method might be called. +// +// MOTIVATION FOR CALLBACK OBJECTS +// ------------------------------- +// It frees service providers from depending on service requestors by +// calling a generic callback other than a callback which depends on +// the service requestor (typically its member function). As a +// result, service provider classes can be developed independently. +// +// Typical usage: Suppose class A wants class B to do something and +// notify A when it is done. As part of the notification, it wants +// to be given a boolean that says what happened. +// +// class A { +// public: +// void RequestService(B* server) { +// ... +// server->StartService(NewCallback(this, &A::ServiceDone), other_args)); +// // the new callback deletes itself after it runs +// } +// void ServiceDone(bool status) {...} +// }; +// +// Class B { +// public: +// void StartService(Callback1<bool>* cb, other_args) : cb_(cb) { ...} +// void FinishService(bool result) { ...; cb_->Run(result); } +// private: +// Callback1<bool>* cb_; +// }; +// +// As can be seen, B is completely independent of A. (Of course, they +// have to agree on callback data type.) +// +// The result of NewCallback() is thread-compatible. The result of +// NewPermanentCallback() is thread-safe if the call its Run() method +// represents is thread-safe and thread-compatible otherwise. +// +// Other modules associated with callbacks may be found in //util/callback +// +// USING CALLBACKS WITH TRACECONTEXT +// --------------------------------- +// Callbacks generated by NewCallback() automatically propagate trace +// context. Callbacks generated by NewPermanentCallback() do not. For +// manually-derived subclasses of Closure and CallbackN, you may decide +// to propagate TraceContext as follows. +// +// struct MyClosure : public Closure { +// MyClosure() +// : Closure(TraceContext::THREAD) { } +// +// void Run() { +// TraceContext *tc = TraceContext::Thread(); +// tc->Swap(&trace_context_); +// DoMyOperation() +// tc->Swap(&trace_context_); +// delete this; +// } +// }; + +#ifndef _CALLBACK_H_ +#define _CALLBACK_H_ + +#include <functional> + +// The actual callback classes and various NewCallback() implementations +// are automatically generated by base/generate-callback-specializations.py. +// We include that output here. +#include "base/callback-specializations.h" + +// A new barrier closure executes another closure after it has been +// invoked N times, and then deletes itself. +// +// If "N" is zero, the supplied closure is executed immediately. +// Barrier closures are thread-safe. They use an atomic operation to +// guarantee a correct count. +// +// REQUIRES N >= 0. +extern Closure* NewBarrierClosure(int N, Closure* done_closure); + +// Function that does nothing; can be used to make new no-op closures: +// NewCallback(&DoNothing) +// NewPermanentCallback(&DoNothing) +// This is a replacement for the formerly available TheNoopClosure() primitive. +extern void DoNothing(); + +// AutoClosureRunner executes a closure upon deletion. This class +// is similar to scoped_ptr: it is typically stack-allocated and can be +// used to perform some type of cleanup upon exiting a block. +// +// Note: use of AutoClosureRunner with Closures that must be executed at +// specific points is discouraged, since the point at which the Closure +// executes is not explicitly marked. For example, consider a Closure +// that should execute after a mutex has been released. The following +// code looks correct, but executes the Closure too early (before release): +// { +// MutexLock l(...); +// AutoClosureRunner r(run_after_unlock); +// ... +// } +// AutoClosureRunner is primarily intended for cleanup operations that +// are relatively independent from other code. +// +// The Reset() method replaces the callback with a new callback. The new +// callback can be supplied as NULL to disable the AutoClosureRunner. This is +// intended as part of a strategy to execute a callback at all exit points of a +// method except where Reset() was called. This method must be used only with +// non-permanent callbacks. The Release() method disables and returns the +// callback, instead of deleting it. +class AutoClosureRunner { + private: + Closure* closure_; + public: + explicit AutoClosureRunner(Closure* c) : closure_(c) {} + ~AutoClosureRunner() { if (closure_) closure_->Run(); } + void Reset(Closure *c) { delete closure_; closure_ = c; } + Closure* Release() { Closure* c = closure_; closure_ = NULL; return c; } + private: + DISALLOW_EVIL_CONSTRUCTORS(AutoClosureRunner); +}; + +// DeletePointerClosure can be used to create a closure that calls delete +// on a pointer. Here is an example: +// +// thread->Add(DeletePointerClosure(expensive_to_delete)); +// +template<typename T> +void DeletePointer(T* p) { + delete p; +} + +template<typename T> +Closure* DeletePointerClosure(T* p) { + return NewCallback(&DeletePointer<T>, p); +} + +#endif /* _CALLBACK_H_ */ diff --git a/third_party/cld/base/casts.h b/third_party/cld/base/casts.h new file mode 100644 index 0000000..1ceb061 --- /dev/null +++ b/third_party/cld/base/casts.h @@ -0,0 +1,156 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_CASTS_H_ +#define BASE_CASTS_H_ + +#include <assert.h> // for use with down_cast<> +#include <string.h> // for memcpy + +#include "third_party/cld/base/macros.h" + + +// Use implicit_cast as a safe version of static_cast or const_cast +// for upcasting in the type hierarchy (i.e. casting a pointer to Foo +// to a pointer to SuperclassOfFoo or casting a pointer to Foo to +// a const pointer to Foo). +// When you use implicit_cast, the compiler checks that the cast is safe. +// Such explicit implicit_casts are necessary in surprisingly many +// situations where C++ demands an exact type match instead of an +// argument type convertable to a target type. +// +// The From type can be inferred, so the preferred syntax for using +// implicit_cast is the same as for static_cast etc.: +// +// implicit_cast<ToType>(expr) +// +// implicit_cast would have been part of the C++ standard library, +// but the proposal was submitted too late. It will probably make +// its way into the language in the future. +template<typename To, typename From> +inline To implicit_cast(From const &f) { + return f; +} + + +// When you upcast (that is, cast a pointer from type Foo to type +// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts +// always succeed. When you downcast (that is, cast a pointer from +// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because +// how do you know the pointer is really of type SubclassOfFoo? It +// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, +// when you downcast, you should use this macro. In debug mode, we +// use dynamic_cast<> to double-check the downcast is legal (we die +// if it's not). In normal mode, we do the efficient static_cast<> +// instead. Thus, it's important to test in debug mode to make sure +// the cast is legal! +// This is the only place in the code we should use dynamic_cast<>. +// In particular, you SHOULDN'T be using dynamic_cast<> in order to +// do RTTI (eg code like this: +// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); +// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); +// You should design the code some other way not to need this. + +template<typename To, typename From> // use like this: down_cast<T*>(foo); +inline To down_cast(From* f) { // so we only accept pointers + // Ensures that To is a sub-type of From *. This test is here only + // for compile-time type checking, and has no overhead in an + // optimized build at run-time, as it will be optimized away + // completely. + if (false) { + implicit_cast<From*, To>(0); + } + + assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only! + return static_cast<To>(f); +} + +// Overload of down_cast for references. Use like this: down_cast<T&>(foo). +// The code is slightly convoluted because we're still using the pointer +// form of dynamic cast. (The reference form throws an exception if it +// fails.) +// +// There's no need for a special const overload either for the pointer +// or the reference form. If you call down_cast with a const T&, the +// compiler will just bind From to const T. +template<typename To, typename From> +inline To down_cast(From& f) { + COMPILE_ASSERT(base::is_reference<To>::value, target_type_not_a_reference); + typedef typename base::remove_reference<To>::type* ToAsPointer; + if (false) { + // Compile-time check that To inherits from From. See above for details. + implicit_cast<From*, ToAsPointer>(0); + } + + assert(dynamic_cast<ToAsPointer>(&f) != NULL); // RTTI: debug mode only + return static_cast<To>(f); +} + +// bit_cast<Dest,Source> is a template function that implements the +// equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in +// very low-level functions like the protobuf library and fast math +// support. +// +// float f = 3.14159265358979; +// int i = bit_cast<int32>(f); +// // i = 0x40490fdb +// +// The classical address-casting method is: +// +// // WRONG +// float f = 3.14159265358979; // WRONG +// int i = * reinterpret_cast<int*>(&f); // WRONG +// +// The address-casting method actually produces undefined behavior +// according to ISO C++ specification section 3.10 -15 -. Roughly, this +// section says: if an object in memory has one type, and a program +// accesses it with a different type, then the result is undefined +// behavior for most values of "different type". +// +// This is true for any cast syntax, either *(int*)&f or +// *reinterpret_cast<int*>(&f). And it is particularly true for +// conversions betweeen integral lvalues and floating-point lvalues. +// +// The purpose of 3.10 -15- is to allow optimizing compilers to assume +// that expressions with different types refer to different memory. gcc +// 4.0.1 has an optimizer that takes advantage of this. So a +// non-conforming program quietly produces wildly incorrect output. +// +// The problem is not the use of reinterpret_cast. The problem is type +// punning: holding an object in memory of one type and reading its bits +// back using a different type. +// +// The C++ standard is more subtle and complex than this, but that +// is the basic idea. +// +// Anyways ... +// +// bit_cast<> calls memcpy() which is blessed by the standard, +// especially by the example in section 3.9 . Also, of course, +// bit_cast<> wraps up the nasty logic in one place. +// +// Fortunately memcpy() is very fast. In optimized mode, with a +// constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline +// code with the minimal amount of data movement. On a 32-bit system, +// memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8) +// compiles to two loads and two stores. +// +// I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1. +// +// WARNING: if Dest or Source is a non-POD type, the result of the memcpy +// is likely to surprise you. +// + +template <class Dest, class Source> +inline Dest bit_cast(const Source& source) { + // Compile time assertion: sizeof(Dest) == sizeof(Source) + // A compile error here means your Dest and Source have different sizes. + typedef char VerifySizesAreEqual [sizeof(Dest) == sizeof(Source) ? 1 : -1]; + + Dest dest; + memcpy(&dest, &source, sizeof(dest)); + return dest; +} + +#endif // BASE_CASTS_H_ diff --git a/third_party/cld/base/closure.h b/third_party/cld/base/closure.h new file mode 100644 index 0000000..d20f065 --- /dev/null +++ b/third_party/cld/base/closure.h @@ -0,0 +1,12 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _CLOSURE_H +#define _CLOSURE_H + +// The Closure class is described in "base/callback.h". + +#include "third_party/cld/base/callback.h" + +#endif /* _CLOSURE_H */ diff --git a/third_party/cld/base/commandlineflags.h b/third_party/cld/base/commandlineflags.h new file mode 100644 index 0000000..fd25767 --- /dev/null +++ b/third_party/cld/base/commandlineflags.h @@ -0,0 +1,443 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This is the file that should be included by any file which declares +// or defines a command line flag or wants to parse command line flags +// or print a program usage message (which will include information about +// flags). Executive summary, in the form of an example foo.cc file: +// +// #include "foo.h" // foo.h has a line "DECLARE_int32(start);" +// +// DEFINE_int32(end, 1000, "The last record to read"); +// DECLARE_bool(verbose); // some other file has a DEFINE_bool(verbose, ...) +// +// void MyFunc() { +// if (FLAGS_verbose) printf("Records %d-%d\n", FLAGS_start, FLAGS_end); +// } +// +// Then, at the command-line: +// ./foo --noverbose --start=5 --end=100 + +#ifndef BASE_COMMANDLINEFLAGS_H_ +#define BASE_COMMANDLINEFLAGS_H_ + +#include <assert.h> +#include <string> +#include <vector> +#include "base/basictypes.h" +#include "base/port.h" +#include "third_party/cld/base/stl_decl.h" +#include "third_party/cld/base/global_strip_options.h" + +// -------------------------------------------------------------------- +// To actually define a flag in a file, use DEFINE_bool, +// DEFINE_string, etc. at the bottom of this file. You may also find +// it useful to register a validator with the flag. This ensures that +// when the flag is parsed from the commandline, or is later set via +// SetCommandLineOption, we call the validation function. +// +// The validation function should return true if the flag value is valid, and +// false otherwise. If the function returns false for the new setting of the +// flag, the flag will retain its current value. If it returns false for the +// default value, InitGoogle will die. +// +// This function is safe to call at global construct time (as in the +// example below). +// +// Example use: +// static bool ValidatePort(const char* flagname, int32 value) { +// if (value > 0 && value < 32768) // value is ok +// return true; +// printf("Invalid value for --%s: %d\n", flagname, (int)value); +// return false; +// } +// DEFINE_int32(port, 0, "What port to listen on"); +// static bool dummy = RegisterFlagValidator(&FLAGS_port, &ValidatePort); + +// Returns true if successfully registered, false if not (because the +// first argument doesn't point to a command-line flag, or because a +// validator is already registered for this flag). +bool RegisterFlagValidator(const bool* flag, + bool (*validate_fn)(const char*, bool)); +bool RegisterFlagValidator(const int32* flag, + bool (*validate_fn)(const char*, int32)); +bool RegisterFlagValidator(const int64* flag, + bool (*validate_fn)(const char*, int64)); +bool RegisterFlagValidator(const uint64* flag, + bool (*validate_fn)(const char*, uint64)); +bool RegisterFlagValidator(const double* flag, + bool (*validate_fn)(const char*, double)); +bool RegisterFlagValidator(const string* flag, + bool (*validate_fn)(const char*, const string&)); + + +// -------------------------------------------------------------------- +// These methods are the best way to get access to info about the +// list of commandline flags. Note that these routines are pretty slow. +// GetAllFlags: mostly-complete info about the list, sorted by file. +// ShowUsageWithFlags: pretty-prints the list to stdout (what --help does) +// ShowUsageWithFlagsRestrict: limit to filenames with restrict as a substr +// +// In addition to accessing flags, you can also access argv[0] (the program +// name) and argv (the entire commandline), which we sock away a copy of. +// These variables are static, so you should only set them once. + +struct CommandLineFlagInfo { + string name; // the name of the flag + string type; // the type of the flag: int32, etc + string description; // the "help text" associated with the flag + string current_value; // the current value, as a string + string default_value; // the default value, as a string + string filename; // 'cleaned' version of filename holding the flag + bool is_default; // true if the flag has default value + bool has_validator_fn; // true if RegisterFlagValidator called on this flag +}; + +extern void GetAllFlags(vector<CommandLineFlagInfo>* OUTPUT); +// These two are actually defined in commandlineflags_reporting.cc. +extern void ShowUsageWithFlags(const char *argv0); // what --help does +extern void ShowUsageWithFlagsRestrict(const char *argv0, const char *restrict); + +// Create a descriptive string for a flag. +// Goes to some trouble to make pretty line breaks. +extern string DescribeOneFlag(const CommandLineFlagInfo& flag); + +// Thread-hostile; meant to be called before any threads are spawned. +extern void SetArgv(int argc, const char** argv); +// The following functions are thread-safe as long as SetArgv() is +// only called before any threads start. +extern const vector<string>& GetArgvs(); // all of argv = vector of strings +extern const char* GetArgv(); // all of argv as a string +extern const char* GetArgv0(); // only argv0 +extern uint32 GetArgvSum(); // simple checksum of argv +extern const char* ProgramInvocationName(); // argv0, or "UNKNOWN" if not set +extern const char* ProgramInvocationShortName(); // basename(argv0) +// ProgramUsage() is thread-safe as long as SetUsageMessage() is only +// called before any threads start. +extern const char* ProgramUsage(); // string set by SetUsageMessage() + + +// -------------------------------------------------------------------- +// Normally you access commandline flags by just saying "if (FLAGS_foo)" +// or whatever, and set them by calling "FLAGS_foo = bar" (or, more +// commonly, via the DEFINE_foo macro). But if you need a bit more +// control, we have programmatic ways to get/set the flags as well. +// These programmatic ways to access flags are thread-safe, but direct +// access is only thread-compatible. + +// Return true iff the flagname was found. +// OUTPUT is set to the flag's value, or unchanged if we return false. +extern bool GetCommandLineOption(const char* name, string* OUTPUT); + +// Return true iff the flagname was found. OUTPUT is set to the flag's +// CommandLineFlagInfo or unchanged if we return false. +extern bool GetCommandLineFlagInfo(const char* name, + CommandLineFlagInfo* OUTPUT); + +// Return the CommandLineFlagInfo of the flagname. exit() if name not found. +// Example usage, to check if a flag's value is currently the default value: +// if (GetCommandLineFlagInfoOrDie("foo").is_default) ... +extern CommandLineFlagInfo GetCommandLineFlagInfoOrDie(const char* name); + +enum FlagSettingMode { + // update the flag's value (can call this multiple times). + SET_FLAGS_VALUE, + // update the flag's value, but *only if* it has not yet been updated + // with SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef". + SET_FLAG_IF_DEFAULT, + // set the flag's default value to this. If the flag has not yet updated + // yet (via SET_FLAGS_VALUE, SET_FLAG_IF_DEFAULT, or "FLAGS_xxx = nondef") + // change the flag's current value to the new default value as well. + SET_FLAGS_DEFAULT +}; + +// Set a particular flag ("command line option"). Returns a string +// describing the new value that the option has been set to. The +// return value API is not well-specified, so basically just depend on +// it to be empty if the setting failed for some reason -- the name is +// not a valid flag name, or the value is not a valid value -- and +// non-empty else. + +// SetCommandLineOption uses set_mode == SET_FLAGS_VALUE (the common case) +extern string SetCommandLineOption(const char* name, const char* value); +extern string SetCommandLineOptionWithMode(const char* name, const char* value, + FlagSettingMode set_mode); + + +// -------------------------------------------------------------------- +// Saves the states (value, default value, whether the user has set +// the flag, registered validators, etc) of all flags, and restores +// them when the FlagSaver is destroyed. This is very useful in +// tests, say, when you want to let your tests change the flags, but +// make sure that they get reverted to the original states when your +// test is complete. +// +// Example usage: +// void TestFoo() { +// FlagSaver s1; +// FLAG_foo = false; +// FLAG_bar = "some value"; +// +// // test happens here. You can return at any time +// // without worrying about restoring the FLAG values. +// } +// +// Note: This class is marked with ATTRIBUTE_UNUSED because all the +// work is done in the constructor and destructor, so in the standard +// usage example above, the compiler would complain that it's an +// unused variable. +// +// This class is thread-safe. +/* +class FlagSaver { + public: + FlagSaver(); + ~FlagSaver(); + + private: + class FlagSaverImpl* impl_; // we use pimpl here to keep API steady + + FlagSaver(const FlagSaver&); // no copying! + void operator=(const FlagSaver&); +} +#ifndef SWIG // swig seems to have trouble with this for some reason +ATTRIBUTE_UNUSED +#endif +; +*/ +// -------------------------------------------------------------------- +// Some deprecated or hopefully-soon-to-be-deprecated functions. + +// This is often used for logging. TODO(csilvers): figure out a better way +extern string CommandlineFlagsIntoString(); +// Usually where this is used, a FlagSaver should be used instead. +extern bool ReadFlagsFromString(const string& flagfilecontents, + const char* prog_name, + bool errors_are_fatal); // uses SET_FLAGS_VALUE + +// These let you manually implement --flagfile functionality. +// DEPRECATED. +extern bool AppendFlagsIntoFile(const string& filename, const char* prog_name); +extern bool SaveCommandFlags(); // actually defined in google.cc ! +extern bool ReadFromFlagsFile(const string& filename, const char* prog_name, + bool errors_are_fatal); // uses SET_FLAGS_VALUE + + +// -------------------------------------------------------------------- +// Useful routines for initializing flags from the environment. +// In each case, if 'varname' does not exist in the environment +// return defval. If 'varname' does exist but is not valid +// (e.g., not a number for an int32 flag), abort with an error. +// Otherwise, return the value. NOTE: for booleans, for true use +// 't' or 'T' or 'true' or '1', for false 'f' or 'F' or 'false' or '0'. + +extern bool BoolFromEnv(const char *varname, bool defval); +extern int32 Int32FromEnv(const char *varname, int32 defval); +extern int64 Int64FromEnv(const char *varname, int64 defval); +extern uint64 Uint64FromEnv(const char *varname, uint64 defval); +extern double DoubleFromEnv(const char *varname, double defval); +extern const char *StringFromEnv(const char *varname, const char *defval); + + +// -------------------------------------------------------------------- +// The next two functions parse commandlineflags from main(): + +// Set the "usage" message for this program. For example: +// string usage("This program does nothing. Sample usage:\n"); +// usage += argv[0] + " <uselessarg1> <uselessarg2>"; +// SetUsageMessage(usage); +// Do not include commandline flags in the usage: we do that for you! +// Thread-hostile; meant to be called before any threads are spawned. +extern void SetUsageMessage(const string& usage); + +// Looks for flags in argv and parses them. Rearranges argv to put +// flags first, or removes them entirely if remove_flags is true. +// If a flag is defined more than once in the command line or flag +// file, the last definition is used. +// See top-of-file for more details on this function. +#ifndef SWIG // In swig, use ParseCommandLineFlagsScript() instead. +extern uint32 ParseCommandLineFlags(int *argc, char*** argv, + bool remove_flags); +#endif + + +// Calls to ParseCommandLineNonHelpFlags and then to +// HandleCommandLineHelpFlags can be used instead of a call to +// ParseCommandLineFlags during initialization, in order to allow for +// changing default values for some FLAGS (via +// e.g. SetCommandLineOptionWithMode calls) between the time of +// command line parsing and the time of dumping help information for +// the flags as a result of command line parsing. +// If a flag is defined more than once in the command line or flag +// file, the last definition is used. +extern uint32 ParseCommandLineNonHelpFlags(int *argc, char*** argv, + bool remove_flags); +// This is actually defined in commandlineflags_reporting.cc. +// This function is misnamed (it also handles --version, etc.), but +// it's too late to change that now. :-( +extern void HandleCommandLineHelpFlags(); // in commandlineflags_reporting.cc + +// Allow command line reparsing. Disables the error normally +// generated when an unknown flag is found, since it may be found in a +// later parse. Thread-hostile; meant to be called before any threads +// are spawned. +extern void AllowCommandLineReparsing(); + +// Reparse the flags that have not yet been recognized. +// Only flags registered since the last parse will be recognized. +// Any flag value must be provided as part of the argument using "=", +// not as a separate command line argument that follows the flag argument. +// Intended for handling flags from dynamically loaded libraries, +// since their flags are not registered until they are loaded. +extern uint32 ReparseCommandLineNonHelpFlags(); + + +// -------------------------------------------------------------------- +// Now come the command line flag declaration/definition macros that +// will actually be used. They're kind of hairy. A major reason +// for this is initialization: we want people to be able to access +// variables in global constructors and have that not crash, even if +// their global constructor runs before the global constructor here. +// (Obviously, we can't guarantee the flags will have the correct +// default value in that case, but at least accessing them is safe.) +// The only way to do that is have flags point to a static buffer. +// So we make one, using a union to ensure proper alignment, and +// then use placement-new to actually set up the flag with the +// correct default value. In the same vein, we have to worry about +// flag access in global destructors, so FlagRegisterer has to be +// careful never to destroy the flag-values it constructs. +// +// Note that when we define a flag variable FLAGS_<name>, we also +// preemptively define a junk variable, FLAGS_no<name>. This is to +// cause a link-time error if someone tries to define 2 flags with +// names like "logging" and "nologging". We do this because a bool +// flag FLAG can be set from the command line to true with a "-FLAG" +// argument, and to false with a "-noFLAG" argument, and so this can +// potentially avert confusion. +// +// We also put flags into their own namespace. It is purposefully +// named in an opaque way that people should have trouble typing +// directly. The idea is that DEFINE puts the flag in the weird +// namespace, and DECLARE imports the flag from there into the current +// namespace. The net result is to force people to use DECLARE to get +// access to a flag, rather than saying "extern bool FLAGS_whatever;" +// or some such instead. We want this so we can put extra +// functionality (like sanity-checking) in DECLARE if we want, and +// make sure it is picked up everywhere. +// +// We also put the type of the variable in the namespace, so that +// people can't DECLARE_int32 something that they DEFINE_bool'd +// elsewhere. + +class FlagRegisterer { + public: + FlagRegisterer(const char* name, const char* type, + const char* help, const char* filename, + void* current_storage, void* defvalue_storage); +}; + +#ifndef SWIG // In swig, ignore the main flag declarations + +// If STRIP_FLAG_HELP is defined and is non-zero, we remove the help +// message from the binary file. This is useful for security reasons +// when shipping a binary outside of Google (if the user cannot see +// the usage message by executing the program, they shouldn't be able +// to see it by running "strings binary_file"). + +extern const char kStrippedFlagHelp[]; + +#if STRIP_FLAG_HELP > 0 +// Need this construct to avoid the 'defined but not used' warning. +#define MAYBE_STRIPPED_HELP(txt) (false ? (txt) : kStrippedFlagHelp) +#else +#define MAYBE_STRIPPED_HELP(txt) txt +#endif + +// Each command-line flag has two variables associated with it: one +// with the current value, and one with the default value. However, +// we have a third variable, which is where value is assigned; it's a +// constant. This guarantees that FLAG_##value is initialized at +// static initialization time (e.g. before program-start) rather than +// than global construction time (which is after program-start but +// before main), at least when 'value' is a compile-time constant. We +// use a small trick for the "default value" variable, and call it +// FLAGS_no<name>. This serves the second purpose of assuring a +// compile error if someone tries to define a flag named no<name> +// which is illegal (--foo and --nofoo both affect the "foo" flag). +#define DEFINE_VARIABLE(type, shorttype, name, value, help) \ + namespace fL##shorttype { \ + static const type FLAGS_nono##name = value; \ + type FLAGS_##name = FLAGS_nono##name; \ + type FLAGS_no##name = FLAGS_nono##name; \ + static FlagRegisterer o_##name( \ + #name, #type, MAYBE_STRIPPED_HELP(help), __FILE__, \ + &FLAGS_##name, &FLAGS_no##name); \ + } \ + using fL##shorttype::FLAGS_##name + +#define DECLARE_VARIABLE(type, shorttype, name) \ + namespace fL##shorttype { \ + extern type FLAGS_##name; \ + } \ + using fL##shorttype::FLAGS_##name + +// For boolean flags, we want to do the extra check that the passed-in +// value is actually a bool, and not a string or something that can be +// coerced to a bool. These declarations (no definition needed!) will +// help us do that, and never evaluate from, which is important. +// We'll use 'sizeof(IsBool(val))' to distinguish. +namespace fLB { +template<typename From> double IsBoolFlag(const From& from); +bool IsBoolFlag(bool from); +} +extern bool FlagsTypeWarn(const char *name); + +#define DECLARE_bool(name) DECLARE_VARIABLE(bool,B, name) +// We have extra code here to make sure 'val' is actually a boolean. +#define DEFINE_bool(name,val,txt) namespace fLB { \ + const bool FLAGS_nonono##name = \ + (sizeof(::fLB::IsBoolFlag(val)) \ + == sizeof(double)) \ + ? FlagsTypeWarn(#name) : true; \ + } \ + DEFINE_VARIABLE(bool,B, name, val, txt) +#define DECLARE_int32(name) DECLARE_VARIABLE(int32,I, name) +#define DEFINE_int32(name,val,txt) DEFINE_VARIABLE(int32,I, name, val, txt) + +#define DECLARE_int64(name) DECLARE_VARIABLE(int64,I64, name) +#define DEFINE_int64(name,val,txt) DEFINE_VARIABLE(int64,I64, name, val, txt) + +#define DECLARE_uint64(name) DECLARE_VARIABLE(uint64,U64, name) +#define DEFINE_uint64(name,val,txt) DEFINE_VARIABLE(uint64,U64, name, val, txt) + +#define DECLARE_double(name) DECLARE_VARIABLE(double,D, name) +#define DEFINE_double(name,val,txt) DEFINE_VARIABLE(double,D, name, val, txt) + +// Strings are trickier, because they're not a POD, so we can't +// construct them at static-initialization time (instead they get +// constructed at global-constructor time, which is much later). To +// try to avoid crashes in that case, we use a char buffer to store +// the string, which we can static-initialize, and then placement-new +// into it later. It's not perfect, but the best we can do. +#define DECLARE_string(name) namespace fLS { extern string& FLAGS_##name; } \ + using fLS::FLAGS_##name + +// We need to define a var named FLAGS_no##name so people don't define +// --string and --nostring. And we need a temporary place to put val +// so we don't have to evaluate it twice. Two great needs that go +// great together! +#define DEFINE_string(name, val, txt) \ + namespace fLS { \ + static union { void* align; char s[sizeof(string)]; } s_##name[2]; \ + const string* const FLAGS_no##name = new (s_##name[0].s) string(val); \ + static FlagRegisterer o_##name( \ + #name, "string", MAYBE_STRIPPED_HELP(txt), __FILE__, \ + s_##name[0].s, new (s_##name[1].s) string(*FLAGS_no##name)); \ + string& FLAGS_##name = *(reinterpret_cast<string*>(s_##name[0].s)); \ + } \ + using fLS::FLAGS_##name + +#endif // SWIG + +#endif // BASE_COMMANDLINEFLAGS_H_ diff --git a/third_party/cld/base/crash.h b/third_party/cld/base/crash.h new file mode 100644 index 0000000..f5c256a --- /dev/null +++ b/third_party/cld/base/crash.h @@ -0,0 +1,41 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Support for collecting useful information when crashing. + +#ifndef BASE_CRASH_H_ +#define BASE_CRASH_H_ + +namespace base { + +struct CrashReason { + CrashReason() : filename(0), line_number(0), message(0), depth(0) {} + + const char* filename; + int line_number; + const char* message; + + // We'll also store a bit of stack trace context at the time of crash as + // it may not be available later on. + void* stack[32]; + int depth; + + // We'll try to store some trace information if it's available - this should + // reflect information from TraceContext::Thread()->tracer()->ToString(). + // This field should probably not be set from within a signal handler or + // low-level code unless absolutely safe to do so. + char trace_info[512]; +}; + +// Stores "reason" as an explanation for why the process is about to +// crash. The reason and its contents must remain live for the life +// of the process. Only the first reason is kept. +void SetCrashReason(const CrashReason* reason); + +// Returns first reason passed to SetCrashReason(), or NULL. +const CrashReason* GetCrashReason(); + +} // namespace base + +#endif // BASE_CRASH_H_ diff --git a/third_party/cld/base/dynamic_annotations.h b/third_party/cld/base/dynamic_annotations.h new file mode 100644 index 0000000..c29c3a2 --- /dev/null +++ b/third_party/cld/base/dynamic_annotations.h @@ -0,0 +1,358 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file defines dynamic annotations for use with dynamic analysis +// tool such as valgrind, PIN, etc. +// +// Dynamic annotation is a source code annotation that affects +// the generated code (that is, the annotation is not a comment). +// Each such annotation is attached to a particular +// instruction and/or to a particular object (address) in the program. +// +// The annotations that should be used by users are macros in all upper-case +// (e.g., ANNOTATE_NEW_MEMORY). +// +// Actual implementation of these macros may differ depending on the +// dynamic analysis tool being used. +// +// This file supports the following dynamic analysis tools: +// - None (NDEBUG is defined). +// Macros are defined empty. +// - Helgrind (NDEBUG is not defined). +// Macros are defined as calls to non-inlinable empty functions +// that are intercepted by helgrind. +// +#ifndef BASE_DYNAMIC_ANNOTATIONS_H_ +#define BASE_DYNAMIC_ANNOTATIONS_H_ + + +// All the annotation macros are in effect only in debug mode. +#ifndef NDEBUG + + // ------------------------------------------------------------- + // Annotations useful when implementing condition variables such as CondVar, + // using conditional critical sections (Await/LockWhen) and when constructing + // user-defined synchronization mechanisms. + // + // The annotations ANNOTATE_HAPPENS_BEFORE() and ANNOTATE_HAPPENS_AFTER() can + // be used to define happens-before arcs in user-defined synchronization + // mechanisms: the race detector will infer an arc from the former to the + // latter when they share the same argument pointer. + // + // Example 1 (reference counting): + // + // void Unref() { + // ANNOTATE_HAPPENS_BEFORE(&refcount_); + // if (AtomicDecrementByOne(&refcount_) == 0) { + // ANNOTATE_HAPPENS_AFTER(&refcount_); + // delete this; + // } + // } + // + // Example 2 (message queue): + // + // void MyQueue::Put(Type *e) { + // MutexLock lock(&mu_); + // ANNOTATE_HAPPENS_BEFORE(e); + // PutElementIntoMyQueue(e); + // } + // + // Type *MyQueue::Get() { + // MutexLock lock(&mu_); + // Type *e = GetElementFromMyQueue(); + // ANNOTATE_HAPPENS_AFTER(e); + // return e; + // } + // + // Note: when possible, please use the existing reference counting and message + // queue implementations instead of inventing new ones. + + // Report that wait on the condition variable at address "cv" has succeeded + // and the lock at address "lock" is held. + #define ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, lock) + + // Report that wait on the condition variable at "cv" has succeeded. Variant + // w/o lock. + #define ANNOTATE_CONDVAR_WAIT(cv) \ + AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL) + + // Report that we are about to signal on the condition variable at address + // "cv". + #define ANNOTATE_CONDVAR_SIGNAL(cv) \ + AnnotateCondVarSignal(__FILE__, __LINE__, cv) + + // Report that we are about to signal_all on the condition variable at "cv". + #define ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ + AnnotateCondVarSignalAll(__FILE__, __LINE__, cv) + + // Annotations for user-defined synchronization mechanisms. + #define ANNOTATE_HAPPENS_BEFORE(obj) ANNOTATE_CONDVAR_SIGNAL(obj) + #define ANNOTATE_HAPPENS_AFTER(obj) ANNOTATE_CONDVAR_WAIT(obj) + + // Report that the bytes in the range [pointer, pointer+size) are about + // to be published safely. The race checker will create a happens-before + // arc from the call ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to + // subsequent accesses to this memory. + #define ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ + AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size) + + // Instruct the tool to create a happens-before arc between mu->Unlock() and + // mu->Lock(). This annotation may slow down the race detector; normally it + // is used only when it would be difficult to annotate each of the mutex's + // critical sections individually using the annotations above. + #define ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) \ + AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu) + + // ------------------------------------------------------------- + // Annotations useful when defining memory allocators, or when memory that + // was protected in one way starts to be protected in another. + + // Report that a new memory at "address" of size "size" has been allocated. + // This might be used when the memory has been retrieved from a free list and + // is about to be reused, or when a the locking discipline for a variable + // changes. + #define ANNOTATE_NEW_MEMORY(address, size) \ + AnnotateNewMemory(__FILE__, __LINE__, address, size) + + // ------------------------------------------------------------- + // Annotations useful when defining FIFO queues that transfer data between + // threads. + + // Report that the producer-consumer queue (such as ProducerConsumerQueue) at + // address "pcq" has been created. The ANNOTATE_PCQ_* annotations + // should be used only for FIFO queues. For non-FIFO queues use + // ANNOTATE_HAPPENS_BEFORE (for put) and ANNOTATE_HAPPENS_AFTER (for get). + #define ANNOTATE_PCQ_CREATE(pcq) \ + AnnotatePCQCreate(__FILE__, __LINE__, pcq) + + // Report that the queue at address "pcq" is about to be destroyed. + #define ANNOTATE_PCQ_DESTROY(pcq) \ + AnnotatePCQDestroy(__FILE__, __LINE__, pcq) + + // Report that we are about to put an element into a FIFO queue at address + // "pcq". + #define ANNOTATE_PCQ_PUT(pcq) \ + AnnotatePCQPut(__FILE__, __LINE__, pcq) + + // Report that we've just got an element from a FIFO queue at address "pcq". + #define ANNOTATE_PCQ_GET(pcq) \ + AnnotatePCQGet(__FILE__, __LINE__, pcq) + + // ------------------------------------------------------------- + // Annotations that suppress errors. It is usually better to express the + // program's synchronization using the other annotations, but these can + // be used when all else fails. + + // Report that we may have a benign race on at "address". + // Insert at the point where "address" has been allocated, preferably close + // to the point where the race happens. + // See also ANNOTATE_BENIGN_RACE_STATIC. + #define ANNOTATE_BENIGN_RACE(address, description) \ + AnnotateBenignRace(__FILE__, __LINE__, address, description) + + // Request the analysis tool to ignore all reads in the current thread + // until ANNOTATE_IGNORE_READS_END is called. + // Useful to ignore intentional racey reads, while still checking + // other reads and all writes. + // See also ANNOTATE_UNPROTECTED_READ. + #define ANNOTATE_IGNORE_READS_BEGIN() \ + AnnotateIgnoreReadsBegin(__FILE__, __LINE__) + + // Stop ignoring reads. + #define ANNOTATE_IGNORE_READS_END() \ + AnnotateIgnoreReadsEnd(__FILE__, __LINE__) + + // Similar to ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. + #define ANNOTATE_IGNORE_WRITES_BEGIN() \ + AnnotateIgnoreWritesBegin(__FILE__, __LINE__) + + // Stop ignoring writes. + #define ANNOTATE_IGNORE_WRITES_END() \ + AnnotateIgnoreWritesEnd(__FILE__, __LINE__) + + // Start ignoring all memory accesses (reads and writes). + #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ + do {\ + ANNOTATE_IGNORE_READS_BEGIN();\ + ANNOTATE_IGNORE_WRITES_BEGIN();\ + }while(0)\ + + // Stop ignoring all memory accesses. + #define ANNOTATE_IGNORE_READS_AND_WRITES_END() \ + do {\ + ANNOTATE_IGNORE_WRITES_END();\ + ANNOTATE_IGNORE_READS_END();\ + }while(0)\ + + // ------------------------------------------------------------- + // Annotations useful for debugging. + + // Request to trace every access to "address". + #define ANNOTATE_TRACE_MEMORY(address) \ + AnnotateTraceMemory(__FILE__, __LINE__, address) + + // Report the current thread name to a race detector. + #define ANNOTATE_THREAD_NAME(name) \ + AnnotateThreadName(__FILE__, __LINE__, name) + + // ------------------------------------------------------------- + // Annotations useful when implementing locks. They are not + // normally needed by modules that merely use locks. + // The "lock" argument is a pointer to the lock object. + + // Report that a lock has been created at address "lock". + #define ANNOTATE_RWLOCK_CREATE(lock) \ + AnnotateRWLockCreate(__FILE__, __LINE__, lock) + + // Report that the lock at address "lock" is about to be destroyed. + #define ANNOTATE_RWLOCK_DESTROY(lock) \ + AnnotateRWLockDestroy(__FILE__, __LINE__, lock) + + // Report that the lock at address "lock" has been acquired. + // is_w=1 for writer lock, is_w=0 for reader lock. + #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ + AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) + + // Report that the lock at address "lock" is about to be released. + #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ + AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) + + // ------------------------------------------------------------- + // Annotations useful for testing race detectors. + + // Report that we expect a race on the variable at "address". + // Use only in unit tests for a race detector. + #define ANNOTATE_EXPECT_RACE(address, description) \ + AnnotateExpectRace(__FILE__, __LINE__, address, description) + + // A no-op. Insert where you like to test the interceptors. + #define ANNOTATE_NO_OP(arg) \ + AnnotateNoOp(__FILE__, __LINE__, arg) + +#else // NDEBUG is defined + + #define ANNOTATE_RWLOCK_CREATE(lock) // empty + #define ANNOTATE_RWLOCK_DESTROY(lock) // empty + #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) // empty + #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) // empty + #define ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) // empty + #define ANNOTATE_CONDVAR_WAIT(cv) // empty + #define ANNOTATE_CONDVAR_SIGNAL(cv) // empty + #define ANNOTATE_CONDVAR_SIGNAL_ALL(cv) // empty + #define ANNOTATE_HAPPENS_BEFORE(obj) // empty + #define ANNOTATE_HAPPENS_AFTER(obj) // empty + #define ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) // empty + #define ANNOTATE_PUBLISH_OBJECT(address) // empty + #define ANNOTATE_PCQ_CREATE(pcq) // empty + #define ANNOTATE_PCQ_DESTROY(pcq) // empty + #define ANNOTATE_PCQ_PUT(pcq) // empty + #define ANNOTATE_PCQ_GET(pcq) // empty + #define ANNOTATE_NEW_MEMORY(address, size) // empty + #define ANNOTATE_EXPECT_RACE(address, description) // empty + #define ANNOTATE_BENIGN_RACE(address, description) // empty + #define ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) // empty + #define ANNOTATE_TRACE_MEMORY(arg) // empty + #define ANNOTATE_THREAD_NAME(name) // empty + #define ANNOTATE_IGNORE_READS_BEGIN() // empty + #define ANNOTATE_IGNORE_READS_END() // empty + #define ANNOTATE_IGNORE_WRITES_BEGIN() // empty + #define ANNOTATE_IGNORE_WRITES_END() // empty + #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() // empty + #define ANNOTATE_IGNORE_READS_AND_WRITES_END() // empty + #define ANNOTATE_NO_OP(arg) // empty + +#endif // NDEBUG + +// Use the macros above rather than using these functions directly. +extern "C" void AnnotateRWLockCreate(const char *file, int line, + const volatile void *lock); +extern "C" void AnnotateRWLockDestroy(const char *file, int line, + const volatile void *lock); +extern "C" void AnnotateRWLockAcquired(const char *file, int line, + const volatile void *lock, long is_w); +extern "C" void AnnotateRWLockReleased(const char *file, int line, + const volatile void *lock, long is_w); +extern "C" void AnnotateCondVarWait(const char *file, int line, + const volatile void *cv, + const volatile void *lock); +extern "C" void AnnotateCondVarSignal(const char *file, int line, + const volatile void *cv); +extern "C" void AnnotateCondVarSignalAll(const char *file, int line, + const volatile void *cv); +extern "C" void AnnotatePublishMemoryRange(const char *file, int line, + const volatile void *address, + long size); +extern "C" void AnnotatePCQCreate(const char *file, int line, + const volatile void *pcq); +extern "C" void AnnotatePCQDestroy(const char *file, int line, + const volatile void *pcq); +extern "C" void AnnotatePCQPut(const char *file, int line, + const volatile void *pcq); +extern "C" void AnnotatePCQGet(const char *file, int line, + const volatile void *pcq); +extern "C" void AnnotateNewMemory(const char *file, int line, + const volatile void *address, + long size); +extern "C" void AnnotateExpectRace(const char *file, int line, + const volatile void *address, + const char *description); +extern "C" void AnnotateBenignRace(const char *file, int line, + const volatile void *address, + const char *description); +extern "C" void AnnotateMutexIsUsedAsCondVar(const char *file, int line, + const volatile void *mu); +extern "C" void AnnotateTraceMemory(const char *file, int line, + const volatile void *arg); +extern "C" void AnnotateThreadName(const char *file, int line, + const char *name); +extern "C" void AnnotateIgnoreReadsBegin(const char *file, int line); +extern "C" void AnnotateIgnoreReadsEnd(const char *file, int line); +extern "C" void AnnotateIgnoreWritesBegin(const char *file, int line); +extern "C" void AnnotateIgnoreWritesEnd(const char *file, int line); +extern "C" void AnnotateNoOp(const char *file, int line, + const volatile void *arg); + +#ifndef NDEBUG + + // ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. + // + // Instead of doing + // ANNOTATE_IGNORE_READS_BEGIN(); + // ... = x; + // ANNOTATE_IGNORE_READS_END(); + // one can use + // ... = ANNOTATE_UNPROTECTED_READ(x); + template <class T> + inline T ANNOTATE_UNPROTECTED_READ(const volatile T &x) { + ANNOTATE_IGNORE_READS_BEGIN(); + T res = x; + ANNOTATE_IGNORE_READS_END(); + return res; + } + + // Apply ANNOTATE_BENIGN_RACE to a static variable. + #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ + namespace { \ + class static_var ## _annotator { \ + public: \ + static_var ## _annotator() { \ + ANNOTATE_BENIGN_RACE(&static_var, \ + # static_var ": " description); \ + } \ + }; \ + static static_var ## _annotator the ## static_var ## _annotator;\ + } +#else // !NDEBUG + + #define ANNOTATE_UNPROTECTED_READ(x) (x) + #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) // empty + +#endif // !NDEBUG + +// Return non-zero value if running under valgrind. +extern "C" int RunningOnValgrind(); + + +#endif // BASE_DYNAMIC_ANNOTATIONS_H_ diff --git a/third_party/cld/base/global_strip_options.h b/third_party/cld/base/global_strip_options.h new file mode 100644 index 0000000..57f955d --- /dev/null +++ b/third_party/cld/base/global_strip_options.h @@ -0,0 +1,59 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Macros for stripping unnecessary string literals from binaries +// (especially for shipping outside of Google). + +#ifndef BASE_GLOBAL_STRIP_OPTIONS_H_ +#define BASE_GLOBAL_STRIP_OPTIONS_H_ + +// The global value of STRIP_LOG. All the messages logged to LOG(XXX) +// with severity less than STRIP_LOG will not be displayed. If it can +// be determined at compile time that the message will not be printed, +// the statement will be compiled out. STRIP_LOG can be set to a value +// between 0 and 4 where 0 logs all messages and 4 logs no messages. +// +// Example: to strip out all INFO and WARNING messages, use the value +// of 2 below. To make an exception for WARNING messages from a single +// file, add "#define STRIP_LOG 1" to that file _before_ including +// base/logging.h +// +// Example: In addition it's possible to remove the dependency on the base +// library if an executable or library currently only depends upon logging. +// +// # A library that only includes "base/basictypes.h" and "base/logging.h". +// cc_library(name = "mylibrary", +// srcs = [ "mymodule_that_logs.cc" ], +// deps = [ "//base" ]) +// +// The build rule for mylibrary can be modified as shown in the following... +// +// # A library with logging disabled. +// cc_library(name = "mylibrary_no_logging", +// srcs = [ "mymodule_that_logs.cc", +// "/base:logging.h" ], +// deps = [ "//third_party/stl" ], +// copts = [ "-DSTRIP_LOG=4" ] ) +// +// Finally if it's desirable to strip all logging from an executable build +// using... +// +// blaze build --copts="-DSTRIP_LOG=4" //mypackage:mylabel + + +#ifndef STRIP_LOG +#define STRIP_LOG 0 +#endif + +// By setting STRIP_FLAG_HELP to 1, we will replace the usage messages +// for command-line flags with "" (thus taking those string literals +// out of the binary). To make an exception for flags DEFINE'd in a +// certain file, add "#define STRIP_FLAG_HELP 0" to that file _before_ +// including base/commandlineflags.h + +#ifndef STRIP_FLAG_HELP +#define STRIP_FLAG_HELP 0 +#endif + +#endif // BASE_GLOBAL_STRIP_OPTIONS_H_ diff --git a/third_party/cld/base/google.h b/third_party/cld/base/google.h new file mode 100644 index 0000000..082058d2 --- /dev/null +++ b/third_party/cld/base/google.h @@ -0,0 +1,212 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file contains a very small number of declarations that should be +// included in most programs. +// +// Sets the usage message to "*usage", parses the command-line flags, +// and initializes various other pieces of global state. If running +// as root, this routine attempts to setuid to FLAGS_uid, which defaults +// to "nobody". +// +// It also logs all the program's command-line flags to the INFO log file. +// +// If the global variable FLAGS_uid is not equal to the empty string, +// then InitGoogle also does an 'su' to the user specified in +// FLAGS_uid, and sets the group equal to FLAGS_gid. +// +// The functions in here are thread-safe unless specified otherwise, +// but they must be called after InitGoogle() (or the +// InitGoogleExceptChangeRootAndUser/ChangeRootAndUser pair). + +#ifndef _GOOGLE_H_ +#define _GOOGLE_H_ + +#include <iosfwd> // to forward declare ostream +#include "base/basictypes.h" +#include "third_party/cld/base/closure.h" +#include "third_party/cld/base/googleinit.h" + +class Closure; + +// A more-convenient way to access gethostname() +const char* Hostname(); +// Return kernel version string in /proc/version +const char* GetKernelVersionString(); +// Return true and set kernel version (x.y.z), patch level and revision (#p.r), +// false, if not known. +struct KernelVersion { + int major; // Major release + int minor; // Minor release + int micro; // Whatever the third no. is called ... + int patch; // Patch level + int revision; // Patch revision +}; +bool GetKernelVersion(KernelVersion* kv); +// A string saying when InitGoogle() was called -- probably program start +const char* GetStartTime(); +// time in ms since InitGoogle() was called -- +int64 GetUptime(); +// the pid for the startup thread +int32 GetMainThreadPid(); + +// the resource limit for core size when InitGoogle() was called. +const struct rlimit* GetSavedCoreLimit(); + +// Restore the core size limit saved in InitGoogle(). This is a no-op if +// FLAGS_allow_kernel_coredumps is true. +int32 RestoreSavedCoreLimit(); + +// Return true if we have determined that all CPUs have the same timing +// (same model, clock rate, stepping). Returns true if there is only one +// CPU. Returns false if we cannot read or parse /proc/cpuinfo. +bool CPUsHaveSameTiming( + const char *cpuinfo = "/proc/cpuinfo", + const char *cpuinfo_max_freq = "/sys/devices/system/cpu/cpu%d/" + "cpufreq/cpuinfo_max_freq"); + +// FlagsParsed is called once for every run VLOG() call site. +// Returns true if command line flags have been parsed +bool FlagsParsed(); + +// A place-holder module initializer to declare initialization ordering +// with respect to it to make chosen initalizers run before command line flag +// parsing (see googleinit.h for more details). +DECLARE_MODULE_INITIALIZER(command_line_flags_parsing); + +// Checks (only in debug mode) if main() has been started and crashes if not +// i.e. makes sure that we are out of the global constructor execution stage. +// Intended to for checking that some code should not be executed during +// global object construction (only specially crafted code might be safe +// to execute at that time). +void AssertMainHasStarted(); + +// Call this from main() if AssertMainHasStarted() is incorrectly failing +// for your code (its current implmentation relies on a call to InitGoogle() +// as the signal that we have reached main(), hence it is not 100% accurate). +void SetMainHasStarted(); + +// Checks (only in debug mode) if InitGoogle() has been fully executed +// and crashes if it has not been. +// Indtended for checking that code that depends on complete execution +// of InitGoogle() for its proper functioning is safe to execute. +void AssertInitGoogleIsDone(); + +// Initializes misc google-related things in the binary. +// In particular it does REQUIRE_MODULE_INITIALIZED(command_line_flags_parsing) +// parses command line flags and does RUN_MODULE_INITIALIZERS() (in that order). +// If a flag is defined more than once in the command line or flag +// file, the last definition is used. +// Typically called early on in main() and must be called before other +// threads start using functions from this file. +// +// 'usage' provides a short usage message passed to SetUsageMessage(). +// 'argc' and 'argv' are the command line flags to parse. +// If 'remove_flags' then parsed flags are removed. +void InitGoogle(const char* usage, int* argc, char*** argv, bool remove_flags); + +// Normally, InitGoogle will chroot (if requested with the --chroot flag) +// and setuid to --uid and --gid (default nobody). +// This version will not, and you will be responsible for calling +// ChangeRootAndUser +// This option is provided for applications that need to read files outside +// the chroot before chrooting. +void InitGoogleExceptChangeRootAndUser(const char* usage, int* argc, + char*** argv, bool remove_flags); +// Thread-hostile. +void ChangeRootAndUser(); + +// if you need to flush InitGoogle's resources from a sighandler +void SigHandlerFlushInitGoogleResources(); + +// Alter behavior of error to not dump core on an error. +// Simply cleanup and exit. Thread-hostile. +void SetNoCoreOnError(); + +// limit the amount of physical memory used by this process to a +// fraction of the available physical memory. The process is killed if +// it tries to go beyond this limit. If randomize is set, we reduce +// the fraction a little in a sort-of-random way. randomize is meant +// to be used for applications which run many copies -- by randomizing +// the limit, we can avoid having all copies of the application hit +// the limit (and die) at the same time. +void LimitPhysicalMemory(double fraction, bool randomize); + +// Return the limit set on physical memory, zero if error or no limit set. +uint64 GetPhysicalMemoryLimit(); + +// Add specified closure to the set of closures which are executed +// when the program dies a horrible death (signal, etc.) +// +// Note: These are not particularly efficient. Use sparingly. +// Note: you can't just use atexit() because functions registered with +// atexit() are supposedly only called on normal program exit, and we +// want to do things like flush logs on failures. +void RunOnFailure(Closure* closure); + +// Remove specified closure references from the set created by RunOnFailure. +void CancelRunOnFailure(Closure* closure); + +// Adds specified Callback2 instances to a set of callbacks that are +// executed when the program crashes. Two values: signo and ucontext_t* +// will be passed into these callback functions. We use void* to avoid the +// use of ucontext_t on non-POSIX systems. +// +// Note: it is recommended that these callbacks are signal-handler +// safe. Also, the calls of these callbacks are not protected by +// a mutex, so they are better to be multithread-safe. +void RunOnFailureCallback2(Callback2<int, void*>* callback); +void CancelRunOnFailureCallback2(Callback2<int, void*>* callback); + +// Return true if the google default signal handler is running, false +// otherwise. Sometimes callbacks specified with +// RunOnFailure{,Callback2} are not called because the process hangs +// or takes too long to symbolize callstacks. Users may want to +// augment the RunOnFailure mechanism with a dedicated thread which +// polls the below function periodically (say, every second) and runs +// their failure closures when it returns true. +bool IsFailureSignalHandlerRunning(); + +// Type of function used for printing in stack trace dumping, etc. +// We avoid closures to keep things simple. +typedef void DebugWriter(const char*, void*); + +// A few useful DebugWriters +DebugWriter DebugWriteToStderr; +DebugWriter DebugWriteToStream; +DebugWriter DebugWriteToFile; +DebugWriter DebugWriteToString; + +// Dump current stack trace omitting the topmost 'skip_count' stack frames. +void DumpStackTrace(int skip_count, DebugWriter *w, void* arg); + +// Dump given pc and stack trace. +void DumpPCAndStackTrace(void *pc, void *stack[], int depth, + DebugWriter *writerfn, void *arg); + +// Returns the program counter from signal context, NULL if unknown. +// vuc is a ucontext_t *. We use void* to avoid the use +// of ucontext_t on non-POSIX systems. +void* GetPC(void* vuc); + +// Dump current address map. +void DumpAddressMap(DebugWriter *w, void* arg); + +// Dump information about currently allocated memory. +void DumpMallocStats(DebugWriter *w, void* arg); + +// Return true if currently executing in the google failure signal +// handler. If this returns true you should: +// +// - avoid allocating anything via malloc/new +// - assume that your stack limit is SIGSTKSZ +// - assume that no other thread can be executing in the failure handler +bool InFailureSignalHandler(); + +// Return the alternate signal stack size (in bytes) needed in order to +// safely run the failure signal handlers. The returned value will +// always be a multiple of the system page size. +int32 GetRequiredAlternateSignalStackSize(); + +#endif // _GOOGLE_H_ diff --git a/third_party/cld/base/googleinit.h b/third_party/cld/base/googleinit.h new file mode 100644 index 0000000..0ccef8b --- /dev/null +++ b/third_party/cld/base/googleinit.h @@ -0,0 +1,384 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_GOOGLEINIT_H_ +#define BASE_GOOGLEINIT_H_ + +//------------------------------------------------------------------------ + +// Initialization sequence in C++ and Google. +// +// This library provides helpers to arrange pieces of initialization code +// for some global objects/state to be executed at well-defined +// moment in time and in a well-defined order. +// +// This library is flexible enough and should be used to do all +// initialization for global/static objects +// except maybe for a few very-low level libraries (mainly inside //base). +// Comments in googleinit.cc discuss the reasons for this. +// +// For the default *MODULE* macros provided below, +// the initialization happens automatically +// during execution of InitGoogle() -- see google.h, +// a call to which should normally be the first statement of main(). +// +// A module can register code to be executed by InitGoogle(). +// For example, one could place the following in common/hostname.cc: +// +// static const char* my_hostname = NULL; +// REGISTER_MODULE_INITIALIZER(hostname, { +// // Code to initialize "my_hostname" +// }); +// +// (Note that, due to preprocessor weirdness, there may be issues with +// the use of commas in your initialization code. If you run into them, +// try using parens around the commas, or use a helper function as follows: +// +// static const char* my_hostname = NULL; +// static void InitMyHostname() { +// // Code to initialize "my_hostname" +// } +// REGISTER_MODULE_INITIALIZER(my_hostname, InitMyHostname()); +// +// This also helps the compiler to accurately attribute compilation errors +// to pieces of your initialization code. +// +// Note that each piece of registered initialized code is tagged +// with an identifier ('my_hostname' in the previous example). This +// is useful to control the order of initialization. For example, +// if we want file initialization to occur after hostname +// initialization, we can place the following in file/base/file.cc: +// +// REGISTER_MODULE_INITIALIZER(file, { +// // File initialization goes here +// }); +// REGISTER_MODULE_INITIALIZER_SEQUENCE(my_hostname, file); +// // requires my_hostname's initializer to run before file's +// +// Alternatively the following *deprecated* method is also supported +// to accomplish the same ordering of initialization: +// +// REGISTER_MODULE_INITIALIZER(file, { +// REQUIRE_MODULE_INITIALIZED(my_hostname); +// // File initialization goes here +// }); +// +// REQUIRE_MODULE_INITIALIZED should really be used only when +// REGISTER_MODULE_INITIALIZER_SEQUENCE can not be e.g. to explicitly make +// a subset of initializers executed from some non-initializer code or +// to define run-time-dependent module dependencies. +// +// For either of the above to compile we should also place the following +// into common/hostname.h and #include that file into file/base/file.cc: +// +// DECLARE_MODULE_INITIALIZER(my_hostname); +// +// Initialization dependencies defined via REGISTER_MODULE_INITIALIZER_SEQUENCE +// are more flexible: unlike with REQUIRE_MODULE_INITIALIZED, one can also +// require that the initialization code defined in the current .cc file +// be executed before some other initializer, e.g.: +// +// In foo_factory.h: +// DECLARE_MODULE_INITIALIZER(foo_factory_init); +// DECLARE_MODULE_INITIALIZER(foo_factory); +// +// In foo_factory.cc: +// static FooFactory* foo_factory = NULL +// REGISTER_MODULE_INITIALIZER(foo_factory_init, { +// foo_factory = new FooFactory(...); +// }); +// REGISTER_MODULE_INITIALIZER(foo_factory, { +// // e.g. code for some final assimilation of all things registered +// // with foo_factory can go here +// }); +// REGISTER_MODULE_INITIALIZER_SEQUENCE(foo_factory_init, foo_factory); +// +// In my_foo_maker.cc: +// REGISTER_MODULE_INITIALIZER(my_registerer, { +// // registration of some my_method with foo_factory goes here +// }); +// REGISTER_MODULE_INITIALIZER_SEQUENCE_3( +// foo_factory_init, my_registerer, foo_factory); +// // my_registerer runs after foo_factory_init, but before foo_factory +// +// In foo_factory_user.cc: +// REGISTER_MODULE_INITIALIZER(foo_user, { +// // use of foo_factory goes here +// }); +// REGISTER_MODULE_INITIALIZER_SEQUENCE(foo_factory, foo_user); +// +// In the above example the initializer execution order will be +// foo_factory_init, my_registerer, foo_factory, foo_user +// even though both foo_factory.cc and foo_factory_user.cc do not have +// explicit dependencies on my_foo_maker.cc (they do not have to know/care +// if it exists). +// +// It is an error to introduce cycles in the initialization +// dependencies. The program will die with an error message +// if the initialization code encounters cyclic dependencies. +// +// Normally all the registered initializers are executed after +// command-line flags have been parsed. +// If you need your initializer to run before parsing of the command-line flags, +// e.g. to adjust the (default) value of certain flags, then include google.h +// and add a directive like this to your .cc file: +// +// REGISTER_MODULE_INITIALIZER_SEQUENCE( +// my_foo_init, command_line_flags_parsing); +// +// Note that you can't instead call +// REQUIRE_MODULE_INITIALIZED(command_line_flags_parsing); +// in the code of your initializer: actual command-line parsing +// is executed by InitGoogle() not in a registered initializer. +// +// A piece of code can declare a dependency on a module using the +// REQUIRE_MODULE macro. This macro creates a link time dependency +// between the .o which the macro is compiled in and the specified +// module. This can be useful in making link time dependencies +// explicit in the code instead of relying on the correctness of the +// BUILD files. For example, foo.cc can declare (see +// file/base/file.h for the REQUIRE_FILE_MODULE definition): +// +// REQUIRE_FILE_MODULE(localfile); +// +// Similarly to other uses, DECLARE_FILE_INITIALIZER(localfile) +// should be #include-d for the above to compile. +// The above will guarantee that the localfile module will be linked into +// an application which foo.cc is linked into. Specifically, a link +// error will occur if the localfile module is not linked in. The +// preferred usage of REQUIRE_*_MODULE is for the module writer to +// provide an external .h which contains the REQUIRE_* macro. In the +// above example, the localfile module writer would provide localfile.h: +// +// #ifndef FILE_LOCALFILE_H_ +// #define FILE_LOCALFILE_H_ +// +// #include "file/base/file.h" +// +// DECLARE_FILE_INITIALIZER(localfile); +// REQUIRE_FILE_MODULE(localfile); +// +// #endif // FILE_LOCALFILE_H_ +// +// Now a user of localfile can declare their dependence on it by +// #including "localfile.h". + +//------------------------------------------------------------------------ + +// The following code is mostly ugly details about how the +// initialization is implemented, and can be safely ignored +// by users of the initialization facility. + +#include <string> + +#include "base/basictypes.h" + +// A static instance of 'GoogleInitializer' is declared for every +// piece of initialization code. The constructor registers the +// code in the initialization table. This class is thread-safe. +class GoogleInitializer { + public: + typedef void (*Initializer)(); + + // Register the specified initialization "function" as the + // initialization code for "name". The "type" parameter controls + // which initializer set this initializer will added to. Note that + // an initializer might end up being run from a different set if it + // is required using the REQUIRE_GOOGLE_INITIALIZED macro. Normally + // the type parameter is "module". Its existence allows the + // specification of other "initializer sets." See file/base/file.h + // and File::Init() for an example of such a set. It's unlikely this + // additional functionality will be used very often. + GoogleInitializer(const char* type, const char* name, Initializer function); + + // Invoke all registered initializers that have not yet been + // executed. The "type" parameter specifies which set of + // initializers to run. The initializers are invoked in + // lexicographically increasing order by name, except as necessary + // to satisfy dependencies. This routine is invoked by InitGoogle(), + // so application code should not call it except in special + // circumstances. + static void RunInitializers(const char* type); + + // If this initialization has not yet been executed, runs it + // right after running all the initializers registered to come before it, + // these initializers are invoked in lexicographically increasing order + // by name, except as necessary to satisfy dependencies. + // It is an error to call this method if the corresponding + // initializer method is currently active (i.e., we do not + // allow cycles in the requirement graph). + void Require(); + + // Helper data-holder struct that is passed into + // DependencyRegisterer's c-tor below. + struct Dependency { + Dependency(const char* n, GoogleInitializer* i) : name(n), initializer(i) {} + const char* const name; + GoogleInitializer* const initializer; + }; + + // A static instance of 'DependencyRegisterer' is declared for every + // piece of initializer ordering definition. The constructor registers the + // ordering relation in the initialization table. This class is thread-safe. + struct DependencyRegisterer { + // Ask to run initializer specified by 'dependency' + // before the 'initializer' with 'name'. + // Both initializers are supposed to be of type 'type'. + DependencyRegisterer(const char* type, + const char* name, + GoogleInitializer* initializer, + const Dependency& dependency); + private: + void SharedConstructorCode(const char* type, + const char* name, + GoogleInitializer* initializer, + const Dependency& dependency); + + DISALLOW_EVIL_CONSTRUCTORS(DependencyRegisterer); + }; + + // Side note: If we happen to decide that connecting all initializers into an + // explicit DAG with one/few sink node(s) that depend on everything else + // is important (to explicitly specify in code all the + // required initializers of a binary) we can provide something like + // static bool DoneAllInitializers(const char *type); + // to check that all registered initializers have been executed. + // Going this route does not seem worth it though: + // it's equivalent to mandating creation of a third complete + // module dependency DAG, the first two being via #include-s and BUILD + // dependencies. + + // Helper structs in .cc; public to declare file-level globals. + struct InitializerData; + struct TypeData; + + private: + void SharedConstructorCode(const char* type, + const char* name, + Initializer function); + + const string type_; // Initializer type + const string name_; // Initializer name + Initializer function_; // The actual initializer + bool done_; // Finished initializing? + bool is_active_; // Is currently running + + // Implementation helper for Require() and RunInitializers: + // Runs initializer *this and all its dependencies + // if that has not happened yet. + // Assumes table_lock is reader-held and TypeData::lock for type_ is held. + void RunIfNecessary_Locked(); + + // Helper to initialize/create and return data for a given initializer type. + static TypeData* InitializerTypeData(const char* type); + + DISALLOW_EVIL_CONSTRUCTORS(GoogleInitializer); +}; + +//------------------------------------------------------------------------ + +// Implementation Internals (most users should ignore) +// +// The *_GOOGLE_* macros are used to make separate initializer +// sets. They should not be used directly by application code, but are +// useful to library writers who want to create a new registration +// mechanism. (See google2file.h and the *_FILE_* macros for an +// example). + +// TODO(maxim): When DECLARE_GOOGLE_INITIALIZER is not used in +// REQUIRE_GOOGLE_INITIALIZED and REQUIRE_GOOGLE_MODULE +// put google_initializer_##type##_##name (and google_init_##type##_##name) +// into a gI##type namespace to force our users to use +// DECLARE_GOOGLE_INITIALIZER not reimplement it +// to manually declare an initializer. + +#define DECLARE_GOOGLE_INITIALIZER(type, name) \ + extern GoogleInitializer google_initializer_##type##_##name + +#define REGISTER_GOOGLE_INITIALIZER(type, name, body) \ + static void google_init_##type##_##name() { body; } \ + GoogleInitializer google_initializer_##type##_##name( \ + #type, #name, google_init_##type##_##name) + +// Require initializer name1 of 'type' to run before initializer +// initializer name2 of same 'type' (i.e. in the order they are written out). +// "Sequence" only means ordering, not direct executions sequence +// without any other initializer executed in between. +// Initializers for both modules must be declared +// with DECLARE_GOOGLE_INITIALIZER at this point. +#define REGISTER_GOOGLE_INITIALIZER_SEQUENCE(type, name1, name2) \ + namespace { \ + static GoogleInitializer::DependencyRegisterer \ + google_initializer_dependency_##type##_##name1##_##name2( \ + #type, #name2, &google_initializer_##type##_##name2, \ + GoogleInitializer::Dependency( \ + #name1, &google_initializer_##type##_##name1)); \ + } +// Require initializers name1, name2, name3 of 'type' to run in the above order. +// Added to support this frequent use case more conveniently. +#define REGISTER_GOOGLE_INITIALIZER_SEQUENCE_3(type, name1, name2, name3) \ + REGISTER_GOOGLE_INITIALIZER_SEQUENCE(type, name1, name2); \ + REGISTER_GOOGLE_INITIALIZER_SEQUENCE(type, name2, name3) + +// Calling REQUIRE_GOOGLE_INITIALIZED(type, foo) means to make sure intializer +// for foo and everything it depends on have executed, and as such +// it can be used to e.g. pre-execute subsets of initializers +// e.g. before everything is executed via RUN_GOGLE_INITIALIZERS(type). +// The initializer must be declared with DECLARE_GOOGLE_INITIALIZER(type, name). +// TODO : remove DECLARE_GOOGLE_INITIALIZER here +// when all old code makes use of DECLARE_GOOGLE_INITIALIZER. +#define REQUIRE_GOOGLE_INITIALIZED(type, name) \ + do { \ + DECLARE_GOOGLE_INITIALIZER(type, name); \ + google_initializer_##type##_##name.Require(); \ + } while (0) + +#define RUN_GOOGLE_INITIALIZERS(type) \ + do { \ + GoogleInitializer::RunInitializers(#type); \ + } while (0) + +// We force the dependant module to be loaded by taking the +// address of an object inside the dependency +// (created by REGISTER_GOOGLE_INITIALIZER). The rest +// is required to avoid warnings about unused variables and +// make sure gcc doesn't optimize it out of existence. +// The initializer must be declared with DECLARE_GOOGLE_INITIALIZER(type, name). +// TODO : remove DECLARE_GOOGLE_INITIALIZER here +// when all old code makes use of DECLARE_GOOGLE_INITIALIZER. +#define REQUIRE_GOOGLE_MODULE(type, name) \ + DECLARE_GOOGLE_INITIALIZER(type, name); \ + static struct GoogleModuleRef_##name { \ + GoogleModuleRef_##name(GoogleInitializer* r) : ref(r) {} \ + GoogleInitializer* ref; \ + } google_module_ref_##name(&google_initializer_##type##_##name) + + +// External Interface (most users should use these macros) + +#define DECLARE_MODULE_INITIALIZER(name) \ + DECLARE_GOOGLE_INITIALIZER(module, name) + +#define REGISTER_MODULE_INITIALIZER(name, body) \ + REGISTER_GOOGLE_INITIALIZER(module, name, body) + +#define REGISTER_MODULE_INITIALIZER_SEQUENCE(name1, name2) \ + REGISTER_GOOGLE_INITIALIZER_SEQUENCE(module, name1, name2) + +#define REGISTER_MODULE_INITIALIZER_SEQUENCE_3(name1, name2, name3) \ + REGISTER_GOOGLE_INITIALIZER_SEQUENCE_3(module, name1, name2, name3) + +#define REQUIRE_MODULE_INITIALIZED(name) \ + REQUIRE_GOOGLE_INITIALIZED(module, name) + +#define RUN_MODULE_INITIALIZERS() \ + RUN_GOOGLE_INITIALIZERS(module) + +// TODO : maybe rename this as REQUIRE_MODULE_LINKED +#define REQUIRE_MODULE(name) \ + REQUIRE_GOOGLE_MODULE(module, name) + +//------------------------------------------------------------------------ + +#endif // BASE_GOOGLEINIT_H_ diff --git a/third_party/cld/base/log_severity.h b/third_party/cld/base/log_severity.h new file mode 100644 index 0000000..05e6f18 --- /dev/null +++ b/third_party/cld/base/log_severity.h @@ -0,0 +1,46 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_LOG_SEVERITY_H_ +#define BASE_LOG_SEVERITY_H_ + +#include "base/port.h" +#include "third_party/cld/base/commandlineflags.h" + +// Variables of type LogSeverity are widely taken to lie in the range +// [0, NUM_SEVERITIES-1]. Be careful to preserve this assumption if +// you ever need to change their values or add a new severity. +typedef int LogSeverity; + +const int INFO = 0, WARNING = 1, ERROR = 2, FATAL = 3, NUM_SEVERITIES = 4; + +// DFATAL is FATAL in debug mode, ERROR in normal mode +#ifdef NDEBUG +#define DFATAL_LEVEL ERROR +#else +#define DFATAL_LEVEL FATAL +#endif + +extern const char* const LogSeverityNames[NUM_SEVERITIES]; + +// Some flags needed for VLOG and RAW_VLOG +DECLARE_int32(v); +DECLARE_bool(silent_init); + +// NDEBUG usage helpers related to (RAW_)DCHECK: +// +// DEBUG_MODE is for small !NDEBUG uses like +// if (DEBUG_MODE) foo.CheckThatFoo(); +// instead of substantially more verbose +// #ifndef NDEBUG +// foo.CheckThatFoo(); +// #endif +// +#ifdef NDEBUG +enum { DEBUG_MODE = 0 }; +#else +enum { DEBUG_MODE = 1 }; +#endif + +#endif // BASE_LOG_SEVERITY_H_ diff --git a/third_party/cld/base/logging.h b/third_party/cld/base/logging.h new file mode 100644 index 0000000..2f75397 --- /dev/null +++ b/third_party/cld/base/logging.h @@ -0,0 +1,1403 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef _LOGGING_H_ +#define _LOGGING_H_ + +#include <errno.h> +#include <string.h> +#include <time.h> +#include <string> +#include <strstream> +#include <vector> + +#ifndef COMPILER_MSVC +#include <unistd.h> // for _exit() +#endif + +#include "base/port.h" +#include "base/basictypes.h" +#include "third_party/cld/base/commandlineflags.h" +#include "third_party/cld/base/crash.h" +#include "third_party/cld/base/dynamic_annotations.h" +#include "third_party/cld/base/macros.h" +#include "third_party/cld/base/scoped_ptr.h" +#include "third_party/cld/base/stl_decl.h" +#include "third_party/cld/base/log_severity.h" +#include "third_party/cld/base/vlog_is_on.h" +#include "third_party/cld/base/global_strip_options.h" + +// Make a bunch of macros for logging. The way to log things is to stream +// things to LOG(<a particular severity level>). E.g., +// +// LOG(INFO) << "Found " << num_cookies << " cookies"; +// +// You can capture log messages in a string, rather than reporting them +// immediately: +// +// vector<string> errors; +// LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num; +// +// This pushes back the new error onto 'errors'; if given a NULL pointer, +// it reports the error via LOG(ERROR). +// +// You can also do conditional logging: +// +// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// You can also do occasional logging (log every n'th occurrence of an +// event): +// +// LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie"; +// +// The above will cause log messages to be output on the 1st, 11th, 21st, ... +// times it is executed. Note that the special COUNTER value is used to +// identify which repetition is happening. +// +// You can also do occasional conditional logging (log every n'th +// occurrence of an event, when condition is satisfied): +// +// LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER +// << "th big cookie"; +// +// You can log messages the first N times your code executes a line. E.g. +// +// LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie"; +// +// Outputs log messages for the first 20 times it is executed. +// +// Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available. +// These log to syslog as well as to the normal logs. If you use these at +// all, you need to be aware that syslog can drastically reduce performance, +// especially if it is configured for remote logging! Don't use these +// unless you fully understand this and have a concrete need to use them. +// Even then, try to minimize your use of them. +// +// There are also "debug mode" logging macros like the ones above: +// +// DLOG(INFO) << "Found cookies"; +// +// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie"; +// +// All "debug mode" logging is compiled away to nothing for non-debug mode +// compiles. +// +// We also have +// +// LOG_ASSERT(assertion); +// DLOG_ASSERT(assertion); +// +// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; +// +// We also override the standard 'assert' to use 'DLOG_ASSERT'. +// +// There are "verbose level" logging macros. They look like +// +// VLOG(1) << "I'm printed when you run the program with --v=1 or more"; +// VLOG(2) << "I'm printed when you run the program with --v=2 or more"; +// +// These always log at the INFO log level (when they log at all). +// The verbose logging can also be turned on module-by-module. For instance, +// --vmodule=recordio=2,file=1,gfs*=3 --v=0 +// will cause: +// a. VLOG(2) and lower messages to be printed from recordio.{h,cc} +// b. VLOG(1) and lower messages to be printed from google2file +// c. VLOG(3) and lower messages to be printed from files prefixed with "gfs" +// d. VLOG(0) and lower messages to be printed from elsewhere +// +// The wildcarding functionality shown by (c) supports both '*' (match +// 0 or more characters) and '?' (match any single character) wildcards. +// +// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as +// +// if (VLOG_IS_ON(2)) { +// // do some logging preparation and logging +// // that can't be accomplished with just VLOG(2) << ...; +// } +// +// There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level" +// condition macros for sample cases, when some extra computation and +// preparation for logs is not needed. +// VLOG_IF(1, (size > 1024)) +// << "I'm printed when size is more than 1024 and when you run the " +// "program with --v=1 or more"; +// VLOG_EVERY_N(1, 10) +// << "I'm printed every 10th occurrence, and when you run the program " +// "with --v=1 or more. Present occurence is " << COUNTER; +// VLOG_IF_EVERY_N(1, (size > 1024), 10) +// << "I'm printed on every 10th occurence of case when size is more " +// " than 1024, when you run the program with --v=1 or more. "; +// "Present occurence is " << COUNTER; +// +// [MLOG is OBSOLETE - use the more convenient VLOG(n) macros] +// There is also an MLOG option that enables module-level logging. MLOG +// is associated with a specific flag by defining a MODULE_FLAG macro. +// Other than this, it behaves like VLOG. Example: +// DEFINE_int32(dnsverbose, 0, "Verbose level for DNS module"); +// #define MODULE_FLAG FLAGS_dnsverbose +// MLOG(1) << "I'm printed when you run with --dnsverbose=1 or more"; +// +// The supported severity levels for macros that allow you to specify one +// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL. +// Note that messages of a given severity are logged not only in the +// logfile for that severity, but also in all logfiles of lower severity. +// E.g., a message of severity FATAL will be logged to the logfiles of +// severity FATAL, ERROR, WARNING, and INFO. +// +// There is also the special severity of DFATAL, which logs FATAL in +// debug mode, ERROR in normal mode. +// +// Very important: logging a message at the FATAL severity level causes +// the program to terminate (after the message is logged). +// +// Unless otherwise specified, logs will be written to the filename +// "<program name>.<hostname>.<user name>.log.<severity level>.", followed +// by the date, time, and pid (you can't prevent the date, time, and pid +// from being in the filename). +// +// The logging code takes two flags: +// --v=# set the verbose level +// --logtostderr log all the messages to stderr instead of to logfiles + +// LOG LINE PREFIX FORMAT +// +// Log lines have this form: +// +// Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... +// +// where the fields are defined as follows: +// +// L A single character, representing the log level +// (eg 'I' for INFO) +// mm The month (zero padded; ie May is '05') +// dd The day (zero padded) +// hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds +// threadid The space-padded thread ID as returned by GetTID() +// (this matches the PID on Linux) +// file The file name +// line The line number +// msg The user-supplied message +// +// Example: +// +// I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog +// I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395 +// +// NOTE: although the microseconds are useful for comparing events on +// a single machine, clocks on different machines may not be well +// synchronized. Hence, use caution when comparing the low bits of +// timestamps from different machines. + +// Set whether log messages go to stderr instead of logfiles +DECLARE_bool(logtostderr); + +// Set whether log messages go to stderr in addition to logfiles. +DECLARE_bool(alsologtostderr); + +// Log messages at a level >= this flag are automatically sent to +// stderr in addition to log files. +DECLARE_int32(stderrthreshold); + +// Set whether the log prefix should be prepended to each line of output. +DECLARE_bool(log_prefix); + +// Log messages at a level <= this flag are buffered. +// Log messages at a higher level are flushed immediately. +DECLARE_int32(logbuflevel); + +// Sets the maximum number of seconds which logs may be buffered for. +DECLARE_int32(logbufsecs); + +// Should Google1 logging be turned on? +DECLARE_bool(logging); + +// Log suppression level: messages logged at a lower level than this +// are suppressed. +DECLARE_int32(minloglevel); + +// If specified, logfiles are written into this directory instead of the +// default logging directory. +DECLARE_string(log_dir); + +// Sets the path of the directory into which to put additional links +// to the log files. +DECLARE_string(log_link); + +// Sets the maximum log file size (in MB). +DECLARE_int32(max_log_size); + +// Should log IO be directed to a background thread? This flag has no +// effect unless //thread/logger:logger is linked into the binary. +DECLARE_bool(threaded_logging); + +// Set to cause StatusMessage() to write status to ./STATUS file. +DECLARE_bool(status_messages_to_status_file); + +// Sets whether to avoid logging to the disk if the disk is full. +DECLARE_bool(stop_logging_if_full_disk); + +// Log messages below the STRIP_LOG level will be compiled away for +// security reasons. See LOG(severtiy) below. STRIP_LOG is defined in +// //base/global_strip_log.h + +// A few definitions of macros that don't generate much code. Since +// LOG(INFO) and its ilk are used all over our code, it's +// better to have compact code for these operations. + +#if STRIP_LOG == 0 +#define COMPACT_GOOGLE_LOG_INFO LogMessage(__FILE__, __LINE__) +#define LOG_TO_STRING_INFO(message) LogMessage(__FILE__, __LINE__, INFO, \ + message) +#else +#define COMPACT_GOOGLE_LOG_INFO NullStream() +#define LOG_TO_STRING_INFO(message) NullStream() +#endif + +#if STRIP_LOG <= 1 +#define COMPACT_GOOGLE_LOG_WARNING LogMessage(__FILE__, __LINE__, WARNING) +#define LOG_TO_STRING_WARNING(message) LogMessage(__FILE__, __LINE__, \ + WARNING, message) +#else +#define COMPACT_GOOGLE_LOG_WARNING NullStream() +#define LOG_TO_STRING_WARNING(message) NullStream() +#endif + +#if STRIP_LOG <= 2 +#define COMPACT_GOOGLE_LOG_ERROR LogMessage(__FILE__, __LINE__, ERROR) +#define LOG_TO_STRING_ERROR(message) LogMessage(__FILE__, __LINE__, ERROR, \ + message) +#else +#define COMPACT_GOOGLE_LOG_ERROR NullStream() +#define LOG_TO_STRING_ERROR(message) NullStream() +#endif + +#if STRIP_LOG <= 3 +#define COMPACT_GOOGLE_LOG_FATAL LogMessageFatal(__FILE__, __LINE__) +#define COMPACT_GOOGLE_LOG_QFATAL LogMessageQuietlyFatal(__FILE__, __LINE__) +#define LOG_TO_STRING_FATAL(message) LogMessage(__FILE__, __LINE__, FATAL, \ + message) +#else +#define COMPACT_GOOGLE_LOG_FATAL NullStreamFatal() +#define COMPACT_GOOGLE_LOG_QFATAL NullStreamFatal() +#define LOG_TO_STRING_FATAL(message) NullStreamFatal() +#endif + +// For DFATAL, we want to use LogMessage (as opposed to +// LogMessageFatal), to be consistent with the original behavior. +#ifdef NDEBUG +#define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR +#elif STRIP_LOG <= 3 +#define COMPACT_GOOGLE_LOG_DFATAL LogMessage(__FILE__, __LINE__, FATAL) +#else +#define COMPACT_GOOGLE_LOG_DFATAL NullStreamFatal() +#endif + +#define GOOGLE_LOG_INFO(counter) \ + LogMessage(__FILE__, __LINE__, INFO, counter, &LogMessage::SendToLog) +#define SYSLOG_INFO(counter) \ + LogMessage(__FILE__, __LINE__, INFO, counter, \ + &LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_WARNING(counter) \ + LogMessage(__FILE__, __LINE__, WARNING, counter, &LogMessage::SendToLog) +#define SYSLOG_WARNING(counter) \ + LogMessage(__FILE__, __LINE__, WARNING, counter, \ + &LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_ERROR(counter) \ + LogMessage(__FILE__, __LINE__, ERROR, counter, &LogMessage::SendToLog) +#define SYSLOG_ERROR(counter) \ + LogMessage(__FILE__, __LINE__, ERROR, counter, \ + &LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_FATAL(counter) \ + LogMessage(__FILE__, __LINE__, FATAL, counter, &LogMessage::SendToLog) +#define SYSLOG_FATAL(counter) \ + LogMessage(__FILE__, __LINE__, FATAL, counter, \ + &LogMessage::SendToSyslogAndLog) +#define GOOGLE_LOG_DFATAL(counter) \ + LogMessage(__FILE__, __LINE__, DFATAL_LEVEL, counter, &LogMessage::SendToLog) +#define SYSLOG_DFATAL(counter) \ + LogMessage(__FILE__, __LINE__, DFATAL_LEVEL, counter, \ + &LogMessage::SendToSyslogAndLog) + +#ifdef OS_WINDOWS +// A very useful logging macro to log windows errors: +#define LOG_SYSRESULT(result) \ + if (FAILED(result)) { \ + LPTSTR message = NULL; \ + LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \ + DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \ + FORMAT_MESSAGE_FROM_SYSTEM, \ + 0, result, 0, msg, 100, NULL); \ + if (message_length > 0) { \ + LogMessage(__FILE__, __LINE__, ERROR, 0, \ + &LogMessage::SendToLog).stream() << message; \ + LocalFree(message); \ + } \ + } +#endif + +// We use the preprocessor's merging operator, "##", so that, e.g., +// LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny +// subtle difference between ostream member streaming functions (e.g., +// ostream::operator<<(int) and ostream non-member streaming functions +// (e.g., ::operator<<(ostream&, string&): it turns out that it's +// impossible to stream something like a string directly to an unnamed +// ostream. We employ a neat hack by calling the stream() member +// function of LogMessage which seems to avoid the problem. +#define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() +#define SYSLOG(severity) SYSLOG_ ## severity(0).stream() + +// A convenient shorthand +#define LG LOG(INFO) + +class LogSink; // defined below + +// If a non-NULL sink pointer is given, we push this message to that sink. +// For LOG_TO_SINK we then do normal LOG(severity) logging as well. +// This is useful for capturing messages and passing/storing them +// somewhere more specific than the global log of the process. +// Argument types: +// LogSink* sink; +// LogSeverity severity; +// The cast is to disambiguate NULL arguments. +#define LOG_TO_SINK(sink, severity) \ + LogMessage(__FILE__, __LINE__, severity, \ + static_cast<LogSink*>(sink), true).stream() +#define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \ + LogMessage(__FILE__, __LINE__, severity, \ + static_cast<LogSink*>(sink), false).stream() + +// If a non-NULL string pointer is given, we write this message to that string. +// We then do normal LOG(severity) logging as well. +// This is useful for capturing messages and storing them somewhere more +// specific than the global log of the process. +// Argument types: +// string* message; +// LogSeverity severity; +// The cast is to disambiguate NULL arguments. +// NOTE: LOG(severity) expands to LogMessage().stream() for the specified +// severity. +#define LOG_TO_STRING(severity, message) \ + LOG_TO_STRING_##severity(static_cast<string*>(message)).stream() + +// If a non-NULL pointer is given, we push the message onto the end +// of a vector of strings; otherwise, we report it with LOG(severity). +// This is handy for capturing messages and perhaps passing them back +// to the caller, rather than reporting them immediately. +// Argument types: +// LogSeverity severity; +// vector<string> *outvec; +// The cast is to disambiguate NULL arguments. +#define LOG_STRING(severity, outvec) \ + LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream() + +#define LOG_IF(severity, condition) \ + !(condition) ? (void) 0 : LogMessageVoidify() & LOG(severity) +#define SYSLOG_IF(severity, condition) \ + !(condition) ? (void) 0 : LogMessageVoidify() & SYSLOG(severity) + +#define LOG_ASSERT(condition) \ + LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition +#define SYSLOG_ASSERT(condition) \ + SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition + +// CHECK dies with a fatal error if condition is not true. It is *not* +// controlled by NDEBUG, so the check will be executed regardless of +// compilation mode. Therefore, it is safe to do things like: +// CHECK(fp->Write(x) == 4) +#define CHECK(condition) \ + LOG_IF(FATAL, PREDICT_FALSE(!(condition))) \ + << "Check failed: " #condition " " + +// QCHECK is a quiet version of CHECK. It has all of the same properties, +// except that when it dies it simply prints out this message and doesn't +// dump a giant stack trace, etc. This is good for tests like sanity-checking +// user inputs, where your own failure message is really the only thing you +// need or want to display. +#define QCHECK(condition) \ + LOG_IF(QFATAL, PREDICT_FALSE(!(condition))) \ + << "Check failed: " #condition " " + +// A container for a string pointer which can be evaluated to a bool - +// true iff the pointer is NULL. +struct CheckOpString { + CheckOpString(string* str) : str_(str) { } + // No destructor: if str_ is non-NULL, we're about to LOG(FATAL), + // so there's no point in cleaning up str_. + operator bool() const { return PREDICT_FALSE(str_ != NULL); } + string* str_; +}; + +// Function is overloaded for integral types to allow static const +// integrals declared in classes and not defined to be used as arguments to +// CHECK* macros. It's not encouraged though. +template <class T> +inline const T& GetReferenceableValue(const T& t) { return t; } +inline char GetReferenceableValue(char t) { return t; } +inline unsigned char GetReferenceableValue(unsigned char t) { return t; } +inline signed char GetReferenceableValue(signed char t) { return t; } +inline short GetReferenceableValue(short t) { return t; } +inline unsigned short GetReferenceableValue(unsigned short t) { return t; } +inline int GetReferenceableValue(int t) { return t; } +inline unsigned int GetReferenceableValue(unsigned int t) { return t; } +inline long GetReferenceableValue(long t) { return t; } +inline unsigned long GetReferenceableValue(unsigned long t) { return t; } +inline long long GetReferenceableValue(long long t) { return t; } +inline unsigned long long GetReferenceableValue(unsigned long long t) { + return t; +} + +// Build the error message string. +template<class t1, class t2> +string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { + strstream ss; + ss << names << " (" << v1 << " vs. " << v2 << ")"; + return new string(ss.str(), ss.pcount()); +} + +// Helper functions for CHECK_OP macro. +// The (int, int) specialization works around the issue that the compiler +// will not instantiate the template version of the function on values of +// unnamed enum type - see comment below. +#define DEFINE_CHECK_OP_IMPL(name, op) \ + template <class t1, class t2> \ + inline string* Check##name##Impl(const t1& v1, const t2& v2, \ + const char* names) { \ + if (v1 op v2) return NULL; \ + else return MakeCheckOpString(v1, v2, names); \ + } \ + inline string* Check##name##Impl(int v1, int v2, const char* names) { \ + return Check##name##Impl<int, int>(v1, v2, names); \ + } + +// Use _EQ, _NE, _LE, etc. in case the file including base/logging.h +// provides its own #defines for the simpler names EQ, NE, LE, etc. +// This happens if, for example, those are used as token names in a +// yacc grammar. +DEFINE_CHECK_OP_IMPL(_EQ, ==) +DEFINE_CHECK_OP_IMPL(_NE, !=) +DEFINE_CHECK_OP_IMPL(_LE, <=) +DEFINE_CHECK_OP_IMPL(_LT, < ) +DEFINE_CHECK_OP_IMPL(_GE, >=) +DEFINE_CHECK_OP_IMPL(_GT, > ) +#undef DEFINE_CHECK_OP_IMPL + +// Helper macro for binary operators. +// Don't use this macro directly in your code, use CHECK_EQ et al below. + +#if defined(STATIC_ANALYSIS) +// Only for static analysis tool to know that it is equivalent to assert +#define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2)) +#elif !defined(NDEBUG) +// In debug mode, avoid constructing CheckOpStrings if possible, +// to reduce the overhead of CHECK statments by 2x. +// Real DCHECK-heavy tests have seen 1.5x speedups. + +// The meaning of "string" might be different between now and +// when this macro gets invoked (e.g., if someone is experimenting +// with other string implementations that get defined after this +// file is included). Save the current meaning now and use it +// in the macro. +typedef string _Check_string; +#define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (_Check_string* _result = \ + Check##name##Impl(GetReferenceableValue(val1), \ + GetReferenceableValue(val2), \ + #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, CheckOpString(_result)).stream() +#else +// In optimized mode, use CheckOpString to hint to compiler that +// the while condition is unlikely. +#define CHECK_OP_LOG(name, op, val1, val2, log) \ + while (CheckOpString _result = \ + Check##name##Impl(GetReferenceableValue(val1), \ + GetReferenceableValue(val2), \ + #val1 " " #op " " #val2)) \ + log(__FILE__, __LINE__, _result).stream() +#endif // STATIC_ANALYSIS, !NDEBUG + +#if STRIP_LOG <= 3 +#define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, LogMessageFatal) +#else +#define CHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, NullStreamFatal) +#endif // STRIP_LOG <= 3 +#define QCHECK_OP(name, op, val1, val2) \ + CHECK_OP_LOG(name, op, val1, val2, LogMessageQuietlyFatal) + +// Equality/Inequality checks - compare two values, and log a FATAL message +// including the two values when the result is not as expected. The values +// must have operator<<(ostream, ...) defined. +// +// You may append to the error message like so: +// CHECK_NE(1, 2) << ": The world must be ending!"; +// +// We are very careful to ensure that each argument is evaluated exactly +// once, and that anything which is legal to pass as a function argument is +// legal here. In particular, the arguments may be temporary expressions +// which will end up being destroyed at the end of the apparent statement, +// for example: +// CHECK_EQ(string("abc")[1], 'b'); +// +// WARNING: These don't compile correctly if one of the arguments is a pointer +// and the other is NULL. To work around this, simply static_cast NULL to the +// type of the desired pointer. + +#define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2) +#define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2) +#define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2) +#define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2) +#define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2) +#define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2) + +#define QCHECK_EQ(val1, val2) QCHECK_OP(_EQ, ==, val1, val2) +#define QCHECK_NE(val1, val2) QCHECK_OP(_NE, !=, val1, val2) +#define QCHECK_LE(val1, val2) QCHECK_OP(_LE, <=, val1, val2) +#define QCHECK_LT(val1, val2) QCHECK_OP(_LT, < , val1, val2) +#define QCHECK_GE(val1, val2) QCHECK_OP(_GE, >=, val1, val2) +#define QCHECK_GT(val1, val2) QCHECK_OP(_GT, > , val1, val2) + + +// Check that the input is non NULL. This very useful in constructor +// initializer lists. + +#define CHECK_NOTNULL(val) \ + CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val)) + +// Helper functions for string comparisons. +// To avoid bloat, the definitions are in logging.cc. +#define DECLARE_CHECK_STROP_IMPL(func, expected) \ + string* Check##func##expected##Impl(const char* s1, const char* s2, \ + const char* names); +DECLARE_CHECK_STROP_IMPL(strcmp, true) +DECLARE_CHECK_STROP_IMPL(strcmp, false) +DECLARE_CHECK_STROP_IMPL(strcasecmp, true) +DECLARE_CHECK_STROP_IMPL(strcasecmp, false) +#undef DECLARE_CHECK_STROP_IMPL + +// Helper macro for string comparisons. +// Don't use this macro directly in your code, use CHECK_STREQ et al below. +#define CHECK_STROP(func, op, expected, s1, s2) \ + while (CheckOpString _result = \ + Check##func##expected##Impl((s1), (s2), \ + #s1 " " #op " " #s2)) \ + LOG(FATAL) << *_result.str_ +#define QCHECK_STROP(func, op, expected, s1, s2) \ + while (CheckOpString _result = \ + Check##func##expected##Impl((s1), (s2), \ + #s1 " " #op " " #s2)) \ + LOG(QFATAL) << *_result.str_ + + +// String (char*) equality/inequality checks. +// CASE versions are case-insensitive. +// +// Note that "s1" and "s2" may be temporary strings which are destroyed +// by the compiler at the end of the current "full expression" +// (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())). + +#define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2) +#define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2) +#define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2) +#define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2) + +#define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0]))) +#define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0]))) + +#define QCHECK_STREQ(s1, s2) QCHECK_STROP(strcmp, ==, true, s1, s2) +#define QCHECK_STRNE(s1, s2) QCHECK_STROP(strcmp, !=, false, s1, s2) +#define QCHECK_STRCASEEQ(s1, s2) QCHECK_STROP(strcasecmp, ==, true, s1, s2) +#define QCHECK_STRCASENE(s1, s2) QCHECK_STROP(strcasecmp, !=, false, s1, s2) + +#define QCHECK_INDEX(I,A) QCHECK(I < (sizeof(A)/sizeof(A[0]))) +#define QCHECK_BOUND(B,A) QCHECK(B <= (sizeof(A)/sizeof(A[0]))) + +// Likely to be deprecated; instead use +// CHECK(MathUtil::NearByMargin(x, y)) +// (or another similar function from util/math/mathutil.h). +#define CHECK_DOUBLE_EQ(val1, val2) \ + do { \ + CHECK_LE((val1), (val2)+0.000000000000001L); \ + CHECK_GE((val1), (val2)-0.000000000000001L); \ + } while (0) + +// Likely to be deprecated; instead use +// CHECK(MathUtil::WithinMargin(x, y, margin)) +// (or another similar function from util/math/mathutil.h). +#define CHECK_NEAR(val1, val2, margin) \ + do { \ + CHECK_LE((val1), (val2)+(margin)); \ + CHECK_GE((val1), (val2)-(margin)); \ + } while (0) + +// perror()..googly style! +// +// PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and +// CHECK equivalents with the addition that they postpend a description +// of the current state of errno to their output lines. + +#define PLOG(severity) GOOGLE_PLOG(severity, 0).stream() + +#define GOOGLE_PLOG(severity, counter) \ + ErrnoLogMessage(__FILE__, __LINE__, severity, counter, \ + &LogMessage::SendToLog) + +#define PLOG_IF(severity, condition) \ + !(condition) ? (void) 0 : LogMessageVoidify() & PLOG(severity) + +// A CHECK() macro that postpends errno if the condition is false. E.g. +// +// if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... } +#define PCHECK(condition) \ + PLOG_IF(FATAL, PREDICT_FALSE(!(condition))) \ + << "Check failed: " #condition " " + +// A CHECK() macro that lets you assert the success of a function that +// returns -1 and sets errno in case of an error. E.g. +// +// CHECK_ERR(mkdir(path, 0700)); +// +// or +// +// int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename; +#define CHECK_ERR(invocation) \ +PLOG_IF(FATAL, PREDICT_FALSE((invocation) == -1)) << #invocation + +// Use macro expansion to create, for each use of LOG_EVERY_N(), static +// variables with the __LINE__ expansion as part of the variable name. +#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line) +#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line + +#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__) +#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__) + +#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + ++LOG_OCCURRENCES; \ + if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \ + ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES_MOD_N, "logging"); \ + ++LOG_OCCURRENCES; \ + if (condition && \ + ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \ + LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \ + ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \ + ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES_MOD_N, "logging"); \ + ++LOG_OCCURRENCES; \ + if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \ + if (LOG_OCCURRENCES_MOD_N == 1) \ + ErrnoLogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \ + static int LOG_OCCURRENCES = 0; \ + ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \ + if (LOG_OCCURRENCES <= n) \ + ++LOG_OCCURRENCES; \ + if (LOG_OCCURRENCES <= n) \ + LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \ + &what_to_do).stream() + +#define LOG_EVERY_N(severity, n) \ + COMPILE_ASSERT(severity < NUM_SEVERITIES, \ + INVALID_REQUESTED_LOG_SEVERITY); \ + SOME_KIND_OF_LOG_EVERY_N(severity, (n), LogMessage::SendToLog) + +#define SYSLOG_EVERY_N(severity, n) \ + SOME_KIND_OF_LOG_EVERY_N(severity, (n), LogMessage::SendToSyslogAndLog) + +#define PLOG_EVERY_N(severity, n) \ + SOME_KIND_OF_PLOG_EVERY_N(severity, (n), LogMessage::SendToLog) + +#define LOG_FIRST_N(severity, n) \ + SOME_KIND_OF_LOG_FIRST_N(severity, (n), LogMessage::SendToLog) + +#define LOG_IF_EVERY_N(severity, condition, n) \ + SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), LogMessage::SendToLog) + +// We want the special COUNTER value available for LOG_EVERY_X()'ed messages +enum PRIVATE_Counter {COUNTER}; + + +// Plus some debug-logging macros that get compiled to nothing for production + +#ifndef NDEBUG + +#define DLOG(severity) LOG(severity) +#define DVLOG(verboselevel) VLOG(verboselevel) +#define DLOG_IF(severity, condition) LOG_IF(severity, condition) +#define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n) +#define DLOG_IF_EVERY_N(severity, condition, n) \ + LOG_IF_EVERY_N(severity, condition, n) +#define DLOG_ASSERT(condition) LOG_ASSERT(condition) + +// debug-only checking. not executed in NDEBUG mode. +#define DCHECK(condition) CHECK(condition) +#define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2) +#define DCHECK_NE(val1, val2) CHECK_NE(val1, val2) +#define DCHECK_LE(val1, val2) CHECK_LE(val1, val2) +#define DCHECK_LT(val1, val2) CHECK_LT(val1, val2) +#define DCHECK_GE(val1, val2) CHECK_GE(val1, val2) +#define DCHECK_GT(val1, val2) CHECK_GT(val1, val2) +#define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2) +#define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2) +#define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2) +#define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2) + +#else // NDEBUG + +#define DLOG(severity) \ + true ? (void) 0 : LogMessageVoidify() & LOG(severity) + +#define DVLOG(verboselevel) \ + (true || !VLOG_IS_ON(verboselevel)) ?\ + (void) 0 : LogMessageVoidify() & LOG(INFO) + +#define DLOG_IF(severity, condition) \ + (true || !(condition)) ? (void) 0 : LogMessageVoidify() & LOG(severity) + +#define DLOG_EVERY_N(severity, n) \ + true ? (void) 0 : LogMessageVoidify() & LOG(severity) + +#define DLOG_IF_EVERY_N(severity, condition, n) \ + (true || !(condition))? (void) 0 : LogMessageVoidify() & LOG(severity) + +#define DLOG_ASSERT(condition) \ + true ? (void) 0 : LOG_ASSERT(condition) + +#define DCHECK(condition) \ + while (false) \ + CHECK(condition) + +#define DCHECK_EQ(val1, val2) \ + while (false) \ + CHECK_EQ(val1, val2) + +#define DCHECK_NE(val1, val2) \ + while (false) \ + CHECK_NE(val1, val2) + +#define DCHECK_LE(val1, val2) \ + while (false) \ + CHECK_LE(val1, val2) + +#define DCHECK_LT(val1, val2) \ + while (false) \ + CHECK_LT(val1, val2) + +#define DCHECK_GE(val1, val2) \ + while (false) \ + CHECK_GE(val1, val2) + +#define DCHECK_GT(val1, val2) \ + while (false) \ + CHECK_GT(val1, val2) + +#define DCHECK_STREQ(str1, str2) \ + while (false) \ + CHECK_STREQ(str1, str2) + +#define DCHECK_STRCASEEQ(str1, str2) \ + while (false) \ + CHECK_STRCASEEQ(str1, str2) + +#define DCHECK_STRNE(str1, str2) \ + while (false) \ + CHECK_STRNE(str1, str2) + +#define DCHECK_STRCASENE(str1, str2) \ + while (false) \ + CHECK_STRCASENE(str1, str2) + + +#endif // NDEBUG + +// Log only in verbose mode. + +#define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel)) + +#define VLOG_IF(verboselevel, condition) \ + LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel)) + +#define VLOG_EVERY_N(verboselevel, n) \ + LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n) + +#define VLOG_IF_EVERY_N(verboselevel, condition, n) \ + LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n) + + +// [MLOG is OBSOLETE - use the more convenient VLOG(n) macros] +// Log only when a module-specific value (MODULE_FLAG) has a specific +// value. MODULE_FLAG must be a macro that evaluates to the name of +// the flag that you wish to use. You should '#define MODULE_FLAG +// <variable name>' before using this macro. (For example: +// #define MODULE_FLAG FLAGS_dnsverbose +#define MLOG(verboselevel) LOG_IF(INFO, MODULE_FLAG >= (verboselevel)) + +// Redefine the standard assert to use our nice log files +#undef assert +#define assert(x) DLOG_ASSERT(x) + +// +// This class more or less represents a particular log message. You +// create an instance of LogMessage and then stream stuff to it. +// When you finish streaming to it, ~LogMessage is called and the +// full message gets streamed to the appropriate destination. +// +// You shouldn't actually use LogMessage's constructor to log things, +// though. You should use the LOG() macro (and variants thereof) +// above. +class LogMessage { +public: + enum { + // Passing kNoLogPrefix for the line number disables the + // log-message prefix. Useful for using the LogMessage + // infrastructure as a printing utility. See also the --log_prefix + // flag for controlling the log-message prefix on an + // application-wide basis. + kNoLogPrefix = -1 + }; + + class LogStream : public ostrstream { + public: + LogStream(char *buf, int len, int ctr) + : ostrstream(buf, len), + ctr_(ctr) { + self_ = this; + } + + int ctr() const { return ctr_; } + void set_ctr(int ctr) { ctr_ = ctr; } + LogStream* self() const { return self_; } + + private: + int ctr_; // Counter hack (for the LOG_EVERY_X() macro) + LogStream *self_; // Consistency check hack + }; + +public: + // icc 8 requires this typedef to avoid an internal compiler error. + typedef void (LogMessage::*SendMethod)(); + + LogMessage(const char* file, int line, LogSeverity severity, int ctr, + SendMethod send_method); + + // Two special constructors that generate reduced amounts of code at + // LOG call sites for common cases. + + // Used for LOG(INFO): Implied are: + // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog. + // + // Using this constructor instead of the more complex constructor above + // saves 19 bytes per call site. + LogMessage(const char* file, int line); + + // Used for LOG(severity) where severity != INFO. Implied + // are: ctr = 0, send_method = &LogMessage::SendToLog + // + // Using this constructor instead of the more complex constructor above + // saves 17 bytes per call site. + LogMessage(const char* file, int line, LogSeverity severity); + + // Constructor to log this message to a specified sink (if not NULL). + // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if + // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise. + LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, + bool also_send_to_log); + + // Constructor where we also give a vector<string> pointer + // for storing the messages (if the pointer is not NULL). + // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog. + LogMessage(const char* file, int line, LogSeverity severity, + vector<string>* outvec); + + // Constructor where we also give a string pointer for storing the + // message (if the pointer is not NULL). Implied are: ctr = 0, + // send_method = &LogMessage::WriteToStringAndLog. + LogMessage(const char* file, int line, LogSeverity severity, + string* message); + + // A special constructor used for check failures + LogMessage(const char* file, int line, const CheckOpString& result); + + ~LogMessage(); + + // Flush a buffered message to the sink set in the constructor. Always + // called by the destructor, it may also be called from elsewhere if + // needed. Only the first call is actioned; any later ones are ignored. + void Flush(); + + // An arbitrary limit on the length of a single log message. This + // is so that streaming can be done more efficiently. + static const size_t kMaxLogMessageLen; + + // Theses should not be called directly outside of logging.*, + // only passed as SendMethod arguments to other LogMessage methods: + void SendToLog(); // Actually dispatch to the logs + void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs + + // Call abort() or similar to perform LOG(FATAL) crash. + // Writes current stack trace to stderr. + static void Fail() ATTRIBUTE_NORETURN; + + // Same as Fail(), but without writing out the stack trace. + // It is assumed that the caller has already generated and + // written the trace as appropriate. + static void FailWithoutStackTrace() ATTRIBUTE_NORETURN; + + // Similar to FailWithoutStackTrace(), but without abort()ing. + // Terminates the process with error exit code. + static void FailQuietly() ATTRIBUTE_NORETURN; + + ostream& stream() { return *(data_->stream_); } + + int preserved_errno() const { return data_->preserved_errno_; } + + // Must be called without the log_mutex held. (L < log_mutex) + static int64 num_messages(int severity); + +private: + // Fully internal SendMethod cases: + void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs + void SendToSink(); // Send to sink if provided, do nothing otherwise. + + // Write to string if provided and dispatch to the logs. + void WriteToStringAndLog(); + + void SaveOrSendToLog(); // Save to stringvec if provided, else to logs + + void Init(const char* file, int line, LogSeverity severity, + void (LogMessage::*send_method)()); + + // Used to fill in crash information during LOG(FATAL) failures. + void RecordCrashReason(base::CrashReason* reason); + + // Counts of messages sent at each priority: + static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex + + // We keep the data in a separate struct so that each instance of + // LogMessage uses less stack space. + struct LogMessageData { + LogMessageData() {}; + + int preserved_errno_; // errno at Init() time + scoped_array<char> buf_; // buffer space for non FATAL messages + char* message_text_; // Complete message text + scoped_ptr<LogStream> stream_alloc_; + LogStream* stream_; + char severity_; // level of LogMessage (ex. I, W, E, F) + int line_; // line number of file that called LOG + void (LogMessage::*send_method_)(); // Call this in destructor to send + union { // At most one of these is used: union to keep the size low. + LogSink* sink_; // NULL or sink to send message to + vector<string>* outvec_; // NULL or vector to push message onto + string* message_; // NULL or string to write message into + }; + time_t timestamp_; // Time of creation of LogMessage + struct tm tm_time_; // Time of creation of LogMessage + size_t num_prefix_chars_; // # of chars of prefix in this message + size_t num_chars_to_log_; // # of chars of msg to send to log + size_t num_chars_to_syslog_; // # of chars of msg to send to syslog + const char* basename_; // basename of file that called LOG + const char* fullname_; // fullname of file that called LOG + bool has_been_flushed_; // false => data has not been flushed + bool first_fatal_; // true => this was first fatal msg + + private: + DISALLOW_EVIL_CONSTRUCTORS(LogMessageData); + }; + + static LogMessageData fatal_msg_data_exclusive_; + static LogMessageData fatal_msg_data_shared_; + + scoped_ptr<LogMessageData> allocated_; + LogMessageData* data_; + + friend class LogDestination; + + DISALLOW_EVIL_CONSTRUCTORS(LogMessage); + +protected: + // Default false; if true, all failures should be as quiet as possible. This + // is stored in LogMessage, rather than LogMessageData, because all FATAL- + // level handlers share the same LogMessageData for signal safety reasons. + bool fail_quietly_; +}; + +// This class happens to be thread-hostile because all instances share +// a single data buffer, but since it can only be created just before +// the process dies, we don't worry so much. +class LogMessageFatal : public LogMessage { + public: + LogMessageFatal(const char* file, int line); + LogMessageFatal(const char* file, int line, const CheckOpString& result); + ~LogMessageFatal() ATTRIBUTE_NORETURN; +}; + +class LogMessageQuietlyFatal : public LogMessage { + public: + LogMessageQuietlyFatal(const char* file, int line); + LogMessageQuietlyFatal(const char* file, int line, + const CheckOpString& result); + ~LogMessageQuietlyFatal() ATTRIBUTE_NORETURN; +}; + +// A non-macro interface to the log facility; (useful +// when the logging level is not a compile-time constant). +inline void LogAtLevel(int const severity, string const &msg) { + LogMessage(__FILE__, __LINE__, severity).stream() << msg; +} + +// A macro alternative of LogAtLevel. New code may want to use this +// version since there are two advantages: 1. this version outputs the +// file name and the line number where this macro is put like other +// LOG macros, 2. this macro can be used as C++ stream. +#define LOG_AT_LEVEL(severity) LogMessage(__FILE__, __LINE__, severity).stream() + +// Helpers for CHECK_NOTNULL(). Two are necessary to support both raw pointers +// and smart pointers. +template <typename T> +T* CheckNotNull(const char *file, int line, const char *names, T* t) { + return CheckNotNullCommon(file, line, names, t); +} + +template <typename T> +T& CheckNotNull(const char *file, int line, const char *names, T& t) { + return CheckNotNullCommon(file, line, names, t); +} + +template <typename T> +T& CheckNotNullCommon(const char *file, int line, const char *names, T& t) { + if (t == NULL) { + LogMessageFatal(file, line, new string(names)); + } + return t; +} + +// Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This +// only works if ostream is a LogStream. If the ostream is not a +// LogStream you'll get an assert saying as much at runtime. +ostream& operator<<(ostream &os, const PRIVATE_Counter&); + + +// We need to be able to stream DocIds. But if DocIds are the same as +// a built-in type, don't try to redefine things that are already +// defined! +#ifndef NDEBUG +inline ostream& operator<<(ostream& o, const DocId& d) { + return (o << DocidForPrintf(d)); +} + +inline ostream& operator<<(ostream& o, const DocId32Bit& d) { + return (o << Docid32BitForPrintf(d)); +} +#endif // NDEBUG + + +// Derived class for PLOG*() above. +class ErrnoLogMessage : public LogMessage { + public: + + ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr, + void (LogMessage::*send_method)()); + + // Postpends ": strerror(errno) [errno]". + ~ErrnoLogMessage(); + + private: + + DISALLOW_EVIL_CONSTRUCTORS(ErrnoLogMessage); +}; + + +// This class is used to explicitly ignore values in the conditional +// logging macros. This avoids compiler warnings like "value computed +// is not used" and "statement has no effect". + +class LogMessageVoidify { + public: + LogMessageVoidify() { } + // This has to be an operator with a precedence lower than << but + // higher than ?: + void operator&(ostream&) { } +}; + + +// Flushes all log files that contains messages that are at least of +// the specified severity level. Thread-safe. +void FlushLogFiles(LogSeverity min_severity); + +// Flushes all log files that contains messages that are at least of +// the specified severity level. Thread-hostile because it ignores +// locking -- used for catastrophic failures. +void FlushLogFilesUnsafe(LogSeverity min_severity); + +// +// Set the destination to which a particular severity level of log +// messages is sent. If base_filename is "", it means "don't log this +// severity". Thread-safe. +// +void SetLogDestination(LogSeverity severity, const char* base_filename); + +// +// Set the basename of the symlink to the latest log file at a given +// severity. If symlink_basename is empty, do not make a symlink. If +// you don't call this function, the symlink basename is the +// invocation name of the program. Thread-safe. +// +void SetLogSymlink(LogSeverity severity, const char* symlink_basename); + +// +// Used to send logs to some other kind of destination +// Users should subclass LogSink and override send to do whatever they want. +// Implementations must be thread-safe because a shared instance will +// be called from whichever thread ran the LOG(XXX) line. +class LogSink { + public: + virtual ~LogSink(); + + // Sink's logging logic (message_len is such as to exclude '\n' at the end). + // This method can't use LOG() or CHECK() as logging system mutex(s) are held + // during this call. + virtual void send(LogSeverity severity, const char* full_filename, + const char* base_filename, int line, + const struct tm* tm_time, + const char* message, size_t message_len) = 0; + + // Redefine this to implement waiting for + // the sink's logging logic to complete. + // It will be called after each send() returns, + // but before that LogMessage exits or crashes. + // By default this function does nothing. + // Using this function one can implement complex logic for send() + // that itself involves logging; and do all this w/o causing deadlocks and + // inconsistent rearrangement of log messages. + // E.g. if a LogSink has thread-specific actions, the send() method + // can simply add the message to a queue and wake up another thread that + // handles real logging while itself making some LOG() calls; + // WaitTillSent() can be implemented to wait for that logic to complete. + // See our unittest for an example. + virtual void WaitTillSent(); + + // Returns the normal text output of the log message. + // Can be useful to implement send(). + static string ToString(LogSeverity severity, const char* file, int line, + const struct tm* tm_time, + const char* message, size_t message_len); +}; + +// Add or remove a LogSink as a consumer of logging data. Thread-safe. +void AddLogSink(LogSink *destination); +void RemoveLogSink(LogSink *destination); + +// +// Specify an "extension" added to the filename specified via +// SetLogDestination. This applies to all severity levels. It's +// often used to append the port we're listening on to the logfile +// name. Thread-safe. +// +void SetLogFilenameExtension(const char* filename_extension); + +// +// Make it so that all log messages of at least a particular severity +// are logged to stderr (in addition to logging to the usual log +// file(s)). Thread-safe. +// +void SetStderrLogging(LogSeverity min_severity); + +// +// Make it so that all log messages go only to stderr. Thread-safe. +// +void LogToStderr(); + +// +// Make it so that all log messages of at least a particular severity are +// logged via email to a list of addresses (in addition to logging to the +// usual log file(s)). The list of addresses is just a string containing +// the email addresses to send to (separated by spaces, say). +// +// Beyond thread-hostile. This function enables email logging, +// which calls popen() if any log messages are actually mailed. +// A multi-thread program which calls this function, even in a single thread, +// will randomly hang if it logs any messages which are mailed. +void SetEmailLogging(LogSeverity min_severity, const char* addresses); + +// +// Generate a special "status" message. This will be useful to +// monitoring scripts that want to know about the progress of +// a long-running program. The two supplied arguments should have +// identical units. The "done" argument says how much work has +// been completed, and the "total" argument says how much total +// work has to be done. Thread-hostile if +// FLAGS_status_messages_to_status_file. Thread-safe otherwise. +// +void StatusMessage(int64 done, int64 total); + +// Like StatusMessage(), only writes the status to the file ./STATUS +// Intended to make life easier for processes running on the global +// work queue, where the standard status message file is ./STATUS. +// Thread-hostile. +void GWQStatusMessage(const char* msg); + +// A simple function that sends email. dest is a comma-separated +// list of addressess. +// +// Beyond thread-hostile. This function calls popen(). +// A multi-thread program which calls this function, even in a single thread, +// will randomly hang. +bool SendEmail(const char*dest, const char *subject, const char*body); + +// Return the set of directories to try generating a log file into. +// Thread-hostile, but expected to only be called from InitGoogle. +const vector<string>& GetLoggingDirectories(); + +// For tests only: Clear the internal [cached] list of logging directories to +// force a refresh the next time GetLoggingDirectories is called. +// Thread-hostile. +void TestOnly_ClearLoggingDirectoriesList(); + +// Returns a set of existing temporary directories, which will be a +// subset of the directories returned by GetLogginDirectories(). +// Thread-safe. +void GetExistingTempDirectories(vector<string>* list); + +// Print any fatal message again -- useful to call from signal handler +// so that the last thing in the output is the fatal message. +// Thread-hostile, but a race is unlikely. +void ReprintFatalMessage(); + +// Truncate a log file that may be the append-only output of multiple +// processes and hence can't simply be renamed/reopened (typically a +// stdout/stderr). If the file "path" is > "limit" bytes, copy the +// last "keep" bytes to offset 0 and truncate the rest. Since we could +// be racing with other writers, this approach has the potential to +// lose very small amounts of data. For security, only follow symlinks +// if the path is /proc/self/fd/* +void TruncateLogFile(const char *path, int64 limit, int64 keep); + +// Truncate stdout and stderr if they are over the value specified by +// --max_log_size; keep the final 1MB. This function has the same +// race condition as TruncateLogFile. +void TruncateStdoutStderr(); + +// Return the string representation of the provided LogSeverity level. +// Thread-safe. +const char* GetLogSeverityName(LogSeverity severity); + +// --------------------------------------------------------------------- +// Implementation details that are not useful to most clients +// --------------------------------------------------------------------- + +// A Logger is the interface used by logging modules (base/logging.cc +// and file/logging/blog.cc) to emit entries to a log. A typical +// implementation will dump formatted data to a sequence of files. We +// also provide interfaces that will forward the data to another +// thread so that the invoker never blocks. Implementations should be +// thread-safe since the logging system will write to them from +// multiple threads. + +namespace base { + +class Logger { + public: + virtual ~Logger(); + + // Writes "message[0,message_len-1]" corresponding to an event that + // occurred at "timestamp". If "force_flush" is true, the log file + // is flushed immediately. + // + // The input message has already been formatted as deemed + // appropriate by the higher level logging facility. For example, + // textual log messages already contain timestamps, and the + // file:linenumber header. + virtual void Write(bool force_flush, + time_t timestamp, + const char* message, + int message_len) = 0; + + // Flush any buffered messages + virtual void Flush() = 0; + + // Get the current LOG file size. + // The returned value is approximate since some + // logged data may not have been flushed to disk yet. + virtual uint32 LogSize() = 0; +}; + +// Get the logger for the specified severity level. The logger +// remains the property of the logging module and should not be +// deleted by the caller. Thread-safe. +extern Logger* GetLogger(LogSeverity level); + +// Set the logger for the specified severity level. The logger +// becomes the property of the logging module and should not +// be deleted by the caller. Thread-safe. +extern void SetLogger(LogSeverity level, Logger* logger); + +} + +// glibc has traditionally implemented two incompatible versions of +// strerror_r(). There is a poorly defined convention for picking the +// version that we want, but it is not clear whether it even works with +// all versions of glibc. +// So, instead, we provide this wrapper that automatically detects the +// version that is in use, and then implements POSIX semantics. +// N.B. In addition to what POSIX says, we also guarantee that "buf" will +// be set to an empty string, if this function failed. This means, in most +// cases, you do not need to check the error code and you can directly +// use the value of "buf". It will never have an undefined value. +int posix_strerror_r(int err, char *buf, size_t len); + + +// A class for which we define operator<<, which does nothing. +class NullStream : public LogMessage::LogStream { + public: + // Initialize the LogStream so the messages can be written somewhere + // (they'll never be actually displayed). This will be needed if a + // NullStream& is implicitly converted to LogStream&, in which case + // the overloaded NullStream::operator<< will not be invoked. + NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { } + NullStream(const char* /*file*/, int /*line*/, + const CheckOpString& /*result*/) : + LogMessage::LogStream(message_buffer_, 1, 0) { } + NullStream &stream() { return *this; } + private: + // A very short buffer for messages (which we discard anyway). This + // will be needed if NullStream& converted to LogStream& (e.g. as a + // result of a conditional expression). + char message_buffer_[2]; +}; + +// Do nothing. This operator is inline, allowing the message to be +// compiled away. The message will not be compiled away if we do +// something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when +// SKIP_LOG=WARNING. In those cases, NullStream will be implicitly +// converted to LogStream and the message will be computed and then +// quietly discarded. +template<class T> +inline NullStream& operator<<(NullStream &str, const T &value) { return str; } + +// Similar to NullStream, but aborts the program (without stack +// trace), like LogMessageFatal. +class NullStreamFatal : public NullStream { + public: + NullStreamFatal() { } + NullStreamFatal(const char* file, int line, const CheckOpString& result) : + NullStream(file, line, result) { } + ~NullStreamFatal() ATTRIBUTE_NORETURN { _exit(1); } +}; + +#endif // _LOGGING_H_ diff --git a/third_party/cld/base/macros.h b/third_party/cld/base/macros.h new file mode 100644 index 0000000..7d0730d --- /dev/null +++ b/third_party/cld/base/macros.h @@ -0,0 +1,252 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Various Google-specific macros. +// +// This code is compiled directly on many platforms, including client +// platforms like Windows, Mac, and embedded systems. Before making +// any changes here, make sure that you're not breaking any platforms. +// + +#ifndef BASE_MACROS_H_ +#define BASE_MACROS_H_ + +#include <stddef.h> // For size_t + +// We use our own local version of type traits while we're waiting +// for TR1 type traits to be standardized. Define some macros so that +// most google3 code doesn't have to work with type traits directly. +#include "third_party/cld/base/type_traits.h" + + +// The COMPILE_ASSERT macro can be used to verify that a compile time +// expression is true. For example, you could use it to verify the +// size of a static array: +// +// COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, +// content_type_names_incorrect_size); +// +// or to make sure a struct is smaller than a certain size: +// +// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); +// +// The second argument to the macro is the name of the variable. If +// the expression is false, most compilers will issue a warning/error +// containing the name of the variable. +/* +template <bool> +struct CompileAssert { +}; + +#define COMPILE_ASSERT(expr, msg) \ + typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] +*/ +// Implementation details of COMPILE_ASSERT: +// +// - COMPILE_ASSERT works by defining an array type that has -1 +// elements (and thus is invalid) when the expression is false. +// +// - The simpler definition +// +// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] +// +// does not work, as gcc supports variable-length arrays whose sizes +// are determined at run-time (this is gcc's extension and not part +// of the C++ standard). As a result, gcc fails to reject the +// following code with the simple definition: +// +// int foo; +// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is +// // not a compile-time constant. +// +// - By using the type CompileAssert<(bool(expr))>, we ensures that +// expr is a compile-time constant. (Template arguments must be +// determined at compile-time.) +// +// - The outter parentheses in CompileAssert<(bool(expr))> are necessary +// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written +// +// CompileAssert<bool(expr)> +// +// instead, these compilers will refuse to compile +// +// COMPILE_ASSERT(5 > 0, some_message); +// +// (They seem to think the ">" in "5 > 0" marks the end of the +// template argument list.) +// +// - The array size is (bool(expr) ? 1 : -1), instead of simply +// +// ((expr) ? 1 : -1). +// +// This is to avoid running into a bug in MS VC 7.1, which +// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. + + +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + void operator=(const TypeName&) + +// An older, politically incorrect name for the above. +// Prefer DISALLOW_COPY_AND_ASSIGN for new code. +#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName) + +// A macro to disallow all the implicit constructors, namely the +// default constructor, copy constructor and operator= functions. +// +// This should be used in the private: declarations for a class +// that wants to prevent anyone from instantiating it. This is +// especially useful for classes containing only static methods. +#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName(); \ + DISALLOW_COPY_AND_ASSIGN(TypeName) + +// The arraysize(arr) macro returns the # of elements in an array arr. +// The expression is a compile-time constant, and therefore can be +// used in defining new arrays, for example. If you use arraysize on +// a pointer by mistake, you will get a compile-time error. +// +// One caveat is that arraysize() doesn't accept any array of an +// anonymous type or a type defined inside a function. In these rare +// cases, you have to use the unsafe ARRAYSIZE() macro below. This is +// due to a limitation in C++'s template system. The limitation might +// eventually be removed, but it hasn't happened yet. + +// This template function declaration is used in defining arraysize. +// Note that the function doesn't need an implementation, as we only +// use its type. +template <typename T, size_t N> +char (&ArraySizeHelper(T (&array)[N]))[N]; + +// That gcc wants both of these prototypes seems mysterious. VC, for +// its part, can't decide which to use (another mystery). Matching of +// template overloads: the final frontier. +#ifndef COMPILER_MSVC +template <typename T, size_t N> +char (&ArraySizeHelper(const T (&array)[N]))[N]; +#endif + +#define arraysize(array) (sizeof(ArraySizeHelper(array))) + +// ARRAYSIZE performs essentially the same calculation as arraysize, +// but can be used on anonymous types or types defined inside +// functions. It's less safe than arraysize as it accepts some +// (although not all) pointers. Therefore, you should use arraysize +// whenever possible. +// +// The expression ARRAYSIZE(a) is a compile-time constant of type +// size_t. +// +// ARRAYSIZE catches a few type errors. If you see a compiler error +// +// "warning: division by zero in ..." +// +// when using ARRAYSIZE, you are (wrongfully) giving it a pointer. +// You should only use ARRAYSIZE on statically allocated arrays. +// +// The following comments are on the implementation details, and can +// be ignored by the users. +// +// ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in +// the array) and sizeof(*(arr)) (the # of bytes in one array +// element). If the former is divisible by the latter, perhaps arr is +// indeed an array, in which case the division result is the # of +// elements in the array. Otherwise, arr cannot possibly be an array, +// and we generate a compiler error to prevent the code from +// compiling. +// +// Since the size of bool is implementation-defined, we need to cast +// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final +// result has type size_t. +// +// This macro is not perfect as it wrongfully accepts certain +// pointers, namely where the pointer size is divisible by the pointee +// size. Since all our code has to go through a 32-bit compiler, +// where a pointer is 4 bytes, this means all pointers to a type whose +// size is 3 or greater than 4 will be (righteously) rejected. +// +// Kudos to Jorg Brown for this simple and elegant implementation. +// +// - wan 2005-11-16 +// +// Starting with Visual C++ 2005, WinNT.h includes ARRAYSIZE. + +#if !defined(COMPILER_MSVC) || (defined(_MSC_VER) && _MSC_VER < 1400) +#define ARRAYSIZE(a) \ + ((sizeof(a) / sizeof(*(a))) / \ + static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) +#endif + + +// A macro to turn a symbol into a string +#define AS_STRING(x) AS_STRING_INTERNAL(x) +#define AS_STRING_INTERNAL(x) #x + + +// One of the type traits, is_pod, makes it possible to query whether +// a type is a POD type. It is impossible for type_traits.h to get +// this right without compiler support, so it fails conservatively. It +// knows that fundamental types and pointers are PODs, but it can't +// tell whether user classes are PODs. The DECLARE_POD macro is used +// to inform the type traits library that a user class is a POD. +// +// Implementation note: the typedef at the end is just to make it legal +// to put a semicolon after DECLARE_POD(foo). +// +// The only reason this matters is that a few parts of the google3 +// code base either require their template arguments to be PODs +// (e.g. compact_vector) or are able to use a more efficient code path +// when their template arguments are PODs (e.g. sparse_hash_map). You +// should use DECLARE_POD if you have written a class that you intend +// to use with one of those components, and if you know that your +// class satisfies all of the conditions to be a POD type. +// +// So what's a POD? The C++ standard (clause 9 paragraph 4) gives a +// full definition, but a good rule of thumb is that a struct is a POD +// ("plain old data") if it doesn't use any of the features that make +// C++ different from C. A POD struct can't have constructors, +// destructors, assignment operators, base classes, private or +// protected members, or virtual functions, and all of its member +// variables must themselves be PODs. + +#define DECLARE_POD(TypeName) \ +namespace base { \ +template<> struct is_pod<TypeName> : true_type { }; \ +} \ +typedef int Dummy_Type_For_DECLARE_POD \ + +// We once needed a different technique to assert that a nested class +// is a POD. This is no longer necessary, and DECLARE_NESTED_POD is +// just a synonym for DECLARE_POD. We continue to provide +// DECLARE_NESTED_POD only so we don't have to change client +// code. Regardless of whether you use DECLARE_POD or +// DECLARE_NESTED_POD: use it after the outer class. Using it within a +// class definition will give a compiler error. +#define DECLARE_NESTED_POD(TypeName) DECLARE_POD(TypeName) + +// Declare that TemplateName<T> is a POD whenever T is +#define PROPAGATE_POD_FROM_TEMPLATE_ARGUMENT(TemplateName) \ +namespace base { \ +template <typename T> struct is_pod<TemplateName<T> > : is_pod<T> { }; \ +} \ +typedef int Dummy_Type_For_PROPAGATE_POD_FROM_TEMPLATE_ARGUMENT + +// Macro that does nothing if TypeName is a POD, and gives a compiler +// error if TypeName is a non-POD. You should put a descriptive +// comment right next to the macro call so that people can tell what +// the compiler error is about. +// +// Implementation note: this works by taking the size of a type that's +// complete when TypeName is a POD and incomplete otherwise. + +template <typename Boolean> struct ERROR_TYPE_MUST_BE_POD; +template <> struct ERROR_TYPE_MUST_BE_POD<base::true_type> { }; +#define ENFORCE_POD(TypeName) \ + enum { dummy_##TypeName \ + = sizeof(ERROR_TYPE_MUST_BE_POD< \ + typename base::is_pod<TypeName>::type>) } + +#endif // BASE_MACROS_H_ diff --git a/third_party/cld/base/scoped_ptr.h b/third_party/cld/base/scoped_ptr.h new file mode 100644 index 0000000..d19ff39 --- /dev/null +++ b/third_party/cld/base/scoped_ptr.h @@ -0,0 +1,428 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef BASE_SCOPED_PTR_H__ +#define BASE_SCOPED_PTR_H__ + +// This is an implementation designed to match the anticipated future TR2 +// implementation of the scoped_ptr class, and its closely-related brethren, +// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. +// +// See http://wiki/Main/ScopedPointerInterface for the spec that drove this +// file. + +#include <assert.h> +#include <stdlib.h> +#include <cstddef> + +#ifdef OS_EMBEDDED_QNX +// NOTE(akirmse): +// The C++ standard says that <stdlib.h> declares both ::foo and std::foo +// But this isn't done in QNX version 6.3.2 200709062316. +using std::free; +using std::malloc; +using std::realloc; +#endif + +template <class C> class scoped_ptr; +template <class C, class Free> class scoped_ptr_malloc; +template <class C> class scoped_array; + +template <class C> +scoped_ptr<C> make_scoped_ptr(C *); + +// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T> +// automatically deletes the pointer it holds (if any). +// That is, scoped_ptr<T> owns the T object that it points to. +// Like a T*, a scoped_ptr<T> may hold either NULL or a pointer to a T object. +// Also like T*, scoped_ptr<T> is thread-compatible, and once you +// dereference it, you get the threadsafety guarantees of T. +// +// The size of a scoped_ptr is small: +// sizeof(scoped_ptr<C>) == sizeof(C*) +template <class C> +class scoped_ptr { + public: + + // The element type + typedef C element_type; + + // Constructor. Defaults to intializing with NULL. + // There is no way to create an uninitialized scoped_ptr. + // The input parameter must be allocated with new. + explicit scoped_ptr(C* p = NULL) : ptr_(p) { } + + // Destructor. If there is a C object, delete it. + // We don't need to test ptr_ == NULL because C++ does that for us. + ~scoped_ptr() { + enum { type_must_be_complete = sizeof(C) }; + delete ptr_; + } + + // Reset. Deletes the current owned object, if any. + // Then takes ownership of a new object, if given. + // this->reset(this->get()) works. + void reset(C* p = NULL) { + if (p != ptr_) { + enum { type_must_be_complete = sizeof(C) }; + delete ptr_; + ptr_ = p; + } + } + + // Accessors to get the owned object. + // operator* and operator-> will assert() if there is no current object. + C& operator*() const { + assert(ptr_ != NULL); + return *ptr_; + } + C* operator->() const { + assert(ptr_ != NULL); + return ptr_; + } + C* get() const { return ptr_; } + + // Comparison operators. + // These return whether a scoped_ptr and a raw pointer refer to + // the same object, not just to two different but equal objects. + bool operator==(const C* p) const { return ptr_ == p; } + bool operator!=(const C* p) const { return ptr_ != p; } + + // Swap two scoped pointers. + void swap(scoped_ptr& p2) { + C* tmp = ptr_; + ptr_ = p2.ptr_; + p2.ptr_ = tmp; + } + + // Release a pointer. + // The return value is the current pointer held by this object. + // If this object holds a NULL pointer, the return value is NULL. + // After this operation, this object will hold a NULL pointer, + // and will not own the object any more. + C* release() { + C* retVal = ptr_; + ptr_ = NULL; + return retVal; + } + + private: + C* ptr_; + + // google3 friend class that can access copy ctor (although if it actually + // calls a copy ctor, there will be a problem) see below + friend scoped_ptr<C> make_scoped_ptr<C>(C *p); + + // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't + // make sense, and if C2 == C, it still doesn't make sense because you should + // never have the same object owned by two different scoped_ptrs. + template <class C2> bool operator==(scoped_ptr<C2> const& p2) const; + template <class C2> bool operator!=(scoped_ptr<C2> const& p2) const; + + // Disallow evil constructors + scoped_ptr(const scoped_ptr&); + void operator=(const scoped_ptr&); +}; + +// Free functions +template <class C> +inline void swap(scoped_ptr<C>& p1, scoped_ptr<C>& p2) { + p1.swap(p2); +} + +template <class C> +inline bool operator==(const C* p1, const scoped_ptr<C>& p2) { + return p1 == p2.get(); +} + +template <class C> +inline bool operator==(const C* p1, const scoped_ptr<const C>& p2) { + return p1 == p2.get(); +} + +template <class C> +inline bool operator!=(const C* p1, const scoped_ptr<C>& p2) { + return p1 != p2.get(); +} + +template <class C> +inline bool operator!=(const C* p1, const scoped_ptr<const C>& p2) { + return p1 != p2.get(); +} + +template <class C> +scoped_ptr<C> make_scoped_ptr(C *p) { + // This does nothing but to return a scoped_ptr of the type that the passed + // pointer is of. (This eliminates the need to specify the name of T when + // making a scoped_ptr that is used anonymously/temporarily.) From an + // access control point of view, we construct an unnamed scoped_ptr here + // which we return and thus copy-construct. Hence, we need to have access + // to scoped_ptr::scoped_ptr(scoped_ptr const &). However, it is guaranteed + // that we never actually call the copy constructor, which is a good thing + // as we would call the temporary's object destructor (and thus delete p) + // if we actually did copy some object, here. + return scoped_ptr<C>(p); +} + +// scoped_array<C> is like scoped_ptr<C>, except that the caller must allocate +// with new [] and the destructor deletes objects with delete []. +// +// As with scoped_ptr<C>, a scoped_array<C> either points to an object +// or is NULL. A scoped_array<C> owns the object that it points to. +// scoped_array<T> is thread-compatible, and once you index into it, +// the returned objects have only the threadsafety guarantees of T. +// +// Size: sizeof(scoped_array<C>) == sizeof(C*) +template <class C> +class scoped_array { + public: + + // The element type + typedef C element_type; + + // Constructor. Defaults to intializing with NULL. + // There is no way to create an uninitialized scoped_array. + // The input parameter must be allocated with new []. + explicit scoped_array(C* p = NULL) : array_(p) { } + + // Destructor. If there is a C object, delete it. + // We don't need to test ptr_ == NULL because C++ does that for us. + ~scoped_array() { + enum { type_must_be_complete = sizeof(C) }; + delete[] array_; + } + + // Reset. Deletes the current owned object, if any. + // Then takes ownership of a new object, if given. + // this->reset(this->get()) works. + void reset(C* p = NULL) { + if (p != array_) { + enum { type_must_be_complete = sizeof(C) }; + delete[] array_; + array_ = p; + } + } + + // Get one element of the current object. + // Will assert() if there is no current object, or index i is negative. + C& operator[](std::ptrdiff_t i) const { + assert(i >= 0); + assert(array_ != NULL); + return array_[i]; + } + + // Get a pointer to the zeroth element of the current object. + // If there is no current object, return NULL. + C* get() const { + return array_; + } + + // Comparison operators. + // These return whether a scoped_array and a raw pointer refer to + // the same array, not just to two different but equal arrays. + bool operator==(const C* p) const { return array_ == p; } + bool operator!=(const C* p) const { return array_ != p; } + + // Swap two scoped arrays. + void swap(scoped_array& p2) { + C* tmp = array_; + array_ = p2.array_; + p2.array_ = tmp; + } + + // Release an array. + // The return value is the current pointer held by this object. + // If this object holds a NULL pointer, the return value is NULL. + // After this operation, this object will hold a NULL pointer, + // and will not own the object any more. + C* release() { + C* retVal = array_; + array_ = NULL; + return retVal; + } + + private: + C* array_; + + // Forbid comparison of different scoped_array types. + template <class C2> bool operator==(scoped_array<C2> const& p2) const; + template <class C2> bool operator!=(scoped_array<C2> const& p2) const; + + // Disallow evil constructors + scoped_array(const scoped_array&); + void operator=(const scoped_array&); +}; + +// Free functions +template <class C> +inline void swap(scoped_array<C>& p1, scoped_array<C>& p2) { + p1.swap(p2); +} + +template <class C> +inline bool operator==(const C* p1, const scoped_array<C>& p2) { + return p1 == p2.get(); +} + +template <class C> +inline bool operator==(const C* p1, const scoped_array<const C>& p2) { + return p1 == p2.get(); +} + +template <class C> +inline bool operator!=(const C* p1, const scoped_array<C>& p2) { + return p1 != p2.get(); +} + +template <class C> +inline bool operator!=(const C* p1, const scoped_array<const C>& p2) { + return p1 != p2.get(); +} + +// This class wraps the c library function free() in a class that can be +// passed as a template argument to scoped_ptr_malloc below. +class ScopedPtrMallocFree { + public: + inline void operator()(void* x) const { + free(x); + } +}; + +// scoped_ptr_malloc<> is similar to scoped_ptr<>, but it accepts a +// second template argument, the functor used to free the object. + +template<class C, class FreeProc = ScopedPtrMallocFree> +class scoped_ptr_malloc { + public: + + // The element type + typedef C element_type; + + // Construction with no arguments sets ptr_ to NULL. + // There is no way to create an uninitialized scoped_ptr. + // The input parameter must be allocated with an allocator that matches the + // Free functor. For the default Free functor, this is malloc, calloc, or + // realloc. + explicit scoped_ptr_malloc(): ptr_(NULL) { } + + // Construct with a C*, and provides an error with a D*. + template<class must_be_C> + explicit scoped_ptr_malloc(must_be_C* p): ptr_(p) { } + + // Construct with a void*, such as you get from malloc. + explicit scoped_ptr_malloc(void *p): ptr_(static_cast<C*>(p)) { } + + // Destructor. If there is a C object, call the Free functor. + ~scoped_ptr_malloc() { + free_(ptr_); + } + + // Reset. Calls the Free functor on the current owned object, if any. + // Then takes ownership of a new object, if given. + // this->reset(this->get()) works. + void reset(C* p = NULL) { + if (ptr_ != p) { + free_(ptr_); + ptr_ = p; + } + } + + // Reallocates the existing pointer, and returns 'true' if + // the reallcation is succesfull. If the reallocation failed, then + // the pointer remains in its previous state. + // + // Note: this calls realloc() directly, even if an alternate 'free' + // functor is provided in the template instantiation. + bool try_realloc(size_t new_size) { + C* new_ptr = static_cast<C*>(realloc(ptr_, new_size)); + if (new_ptr == NULL) { + return false; + } + ptr_ = new_ptr; + return true; + } + + // Get the current object. + // operator* and operator-> will cause an assert() failure if there is + // no current object. + C& operator*() const { + assert(ptr_ != NULL); + return *ptr_; + } + + C* operator->() const { + assert(ptr_ != NULL); + return ptr_; + } + + C* get() const { + return ptr_; + } + + // Comparison operators. + // These return whether a scoped_ptr_malloc and a plain pointer refer + // to the same object, not just to two different but equal objects. + // For compatibility with the boost-derived implementation, these + // take non-const arguments. + bool operator==(C* p) const { + return ptr_ == p; + } + + bool operator!=(C* p) const { + return ptr_ != p; + } + + // Swap two scoped pointers. + void swap(scoped_ptr_malloc & b) { + C* tmp = b.ptr_; + b.ptr_ = ptr_; + ptr_ = tmp; + } + + // Release a pointer. + // The return value is the current pointer held by this object. + // If this object holds a NULL pointer, the return value is NULL. + // After this operation, this object will hold a NULL pointer, + // and will not own the object any more. + C* release() { + C* tmp = ptr_; + ptr_ = NULL; + return tmp; + } + + private: + C* ptr_; + + // no reason to use these: each scoped_ptr_malloc should have its own object + template <class C2, class GP> + bool operator==(scoped_ptr_malloc<C2, GP> const& p) const; + template <class C2, class GP> + bool operator!=(scoped_ptr_malloc<C2, GP> const& p) const; + + static FreeProc const free_; + + // Disallow evil constructors + scoped_ptr_malloc(const scoped_ptr_malloc&); + void operator=(const scoped_ptr_malloc&); +}; + +template<class C, class FP> +FP const scoped_ptr_malloc<C, FP>::free_ = FP(); + +template<class C, class FP> inline +void swap(scoped_ptr_malloc<C, FP>& a, scoped_ptr_malloc<C, FP>& b) { + a.swap(b); +} + +template<class C, class FP> inline +bool operator==(C* p, const scoped_ptr_malloc<C, FP>& b) { + return p == b.get(); +} + +template<class C, class FP> inline +bool operator!=(C* p, const scoped_ptr_malloc<C, FP>& b) { + return p != b.get(); +} + +#endif // BASE_SCOPED_PTR_H__ diff --git a/third_party/cld/base/stl_decl.h b/third_party/cld/base/stl_decl.h new file mode 100644 index 0000000..25671e7 --- /dev/null +++ b/third_party/cld/base/stl_decl.h @@ -0,0 +1,24 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// In most .h files, we would rather include a declaration of an stl +// rather than including the appropriate stl h file (which brings in +// lots of crap). For many STL classes this is ok (eg pair), but for +// some it's really annoying. We define those here, so you can +// just include this file instead of having to deal with the annoyance. +// +// Most of the annoyance, btw, has to do with the default allocator. +// +// DEPRECATED: this file is deprecated. Do not use in new code. +// Be careful about removing from old code, though, because your +// header file might be included by higher-level code that is +// accidentally depending on this. +// -- mec 2007-01-17 + +#ifndef BASE_STL_DECL_H_ +#define BASE_STL_DECL_H_ + +#include "third_party/cld/base/stl_decl_msvc.h" + +#endif // BASE_STL_DECL_H_ diff --git a/third_party/cld/base/stl_decl_msvc.h b/third_party/cld/base/stl_decl_msvc.h new file mode 100644 index 0000000..130b8e1 --- /dev/null +++ b/third_party/cld/base/stl_decl_msvc.h @@ -0,0 +1,107 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// In most .h files, we would rather include a declaration of an stl +// rather than including the appropriate stl h file (which brings in +// lots of noise). For many STL classes this is ok (eg pair), but for +// some it's really annoying. We define those here, so you can +// just include this file instead of having to deal with the annoyance. +// +// Most of the annoyance, btw, has to do with the default allocator. + +#ifndef _STL_DECL_MSVC_H +#define _STL_DECL_MSVC_H + +// VC++ namespace / STL issues; make them explicit +#include <wchar.h> +#include <string> +#include <vector> +#include <functional> +#include <utility> +#include <set> +#include <list> +#define slist list +#include <algorithm> +#include <deque> +#include <iostream> +#include <map> +#include <queue> +#include <stack> + +// copy_n isn't to be found anywhere in MSVC's STL +template <typename InputIterator, typename Size, typename OutputIterator> +std::pair<InputIterator, OutputIterator> +copy_n(InputIterator in, Size count, OutputIterator out) { + for ( ; count > 0; --count) { + *out = *in; + ++out; + ++in; + } + return std::make_pair(in, out); +} + +// Nor are the following selectors +template <typename T> +struct identity { + inline const T& operator()(const T& t) const { return t; } +}; + +// Copied from STLport +template <class _Pair> +struct select1st : public std::unary_function<_Pair, typename _Pair::first_type> { + const typename _Pair::first_type& operator()(const _Pair& __x) const { + return __x.first; + } +}; + +template <class _Pair> +struct select2nd : public std::unary_function<_Pair, typename _Pair::second_type> +{ + const typename _Pair::second_type& operator()(const _Pair& __x) const { + return __x.second; + } +}; + + +#if _MSC_VER >= 1300 + +// If you compile on Windows and get a compile-time error because +// some google3 code specifies a 3rd or 4th parameter to one of +// these template classes, then you have to put in some #ifdefs +// and use the NATIVE_HASH_NAMESPACE::hash_(set|map) implementation. +namespace msvchash { + template <typename Key> + struct hash; + + template <class Key, + class HashFcn = hash<Key> > + class hash_set; + + template <class Key, class Val, + class HashFcn = hash<Key> > + class hash_map; + + template <class Key, + class HashFcn = hash<Key> > + class hash_multiset; + + template <class Key, class Val, + class HashFcn = hash<Key> > + class hash_multimap; +} // end namespace msvchash + +using msvchash::hash_set; +using msvchash::hash_map; +using msvchash::hash; +using msvchash::hash_multimap; +using msvchash::hash_multiset; + +#else +#define hash_map map +#define hash_set set +#endif + +using namespace std; + +#endif /* #ifdef _STL_DECL_MSVC_H */ diff --git a/third_party/cld/base/strtoint.h b/third_party/cld/base/strtoint.h new file mode 100644 index 0000000..13a4bdd --- /dev/null +++ b/third_party/cld/base/strtoint.h @@ -0,0 +1,93 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Architecture-neutral plug compatible replacements for strtol() friends. +// +// Long's have different lengths on ILP-32 and LP-64 platforms, and so overflow +// behavior across the two varies when strtol() and similar are used to parse +// 32-bit integers. Similar problems exist with atoi(), because although it +// has an all-integer interface, it uses strtol() internally, and so suffers +// from the same narrowing problems on assignments to int. +// +// Examples: +// errno = 0; +// i = strtol("3147483647", NULL, 10); +// printf("%d, errno %d\n", i, errno); +// // 32-bit platform: 2147483647, errno 34 +// // 64-bit platform: -1147483649, errno 0 +// +// printf("%d\n", atoi("3147483647")); +// // 32-bit platform: 2147483647 +// // 64-bit platform: -1147483649 +// +// A way round this is to define local replacements for these, and use them +// instead of the standard libc functions. +// +// In most 32-bit cases the replacements can be inlined away to a call to the +// libc function. In a couple of 64-bit cases, however, adapters are required, +// to provide the right overflow and errno behavior. +// + +#ifndef BASE_STRTOINT_H_ +#define BASE_STRTOINT_H_ + +#include <stdlib.h> // For strtol* functions. +#include <string> +#include "base/port.h" +#include "base/basictypes.h" + +// Adapter functions for handling overflow and errno. +int32 strto32_adapter(const char *nptr, char **endptr, int base); +uint32 strtou32_adapter(const char *nptr, char **endptr, int base); + +// Conversions to a 32-bit integer can pass the call to strto[u]l on 32-bit +// platforms, but need a little extra work on 64-bit platforms. +inline int32 strto32(const char *nptr, char **endptr, int base) { + if (sizeof(int32) == sizeof(long)) + return strtol(nptr, endptr, base); + else + return strto32_adapter(nptr, endptr, base); +} + +inline uint32 strtou32(const char *nptr, char **endptr, int base) { + if (sizeof(uint32) == sizeof(unsigned long)) + return strtoul(nptr, endptr, base); + else + return strtou32_adapter(nptr, endptr, base); +} + +// For now, long long is 64-bit on all the platforms we care about, so these +// functions can simply pass the call to strto[u]ll. +inline int64 strto64(const char *nptr, char **endptr, int base) { + COMPILE_ASSERT(sizeof(int64) == sizeof(long long), + sizeof_int64_is_not_sizeof_long_long); + return strtoll(nptr, endptr, base); +} + +inline uint64 strtou64(const char *nptr, char **endptr, int base) { + COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long), + sizeof_uint64_is_not_sizeof_long_long); + return strtoull(nptr, endptr, base); +} + +// Although it returns an int, atoi() is implemented in terms of strtol, and +// so has differing overflow and underflow behavior. atol is the same. +inline int32 atoi32(const char *nptr) { + return strto32(nptr, NULL, 10); +} + +inline int64 atoi64(const char *nptr) { + return strto64(nptr, NULL, 10); +} + +// Convenience versions of the above that take a string argument. +inline int32 atoi32(const string &s) { + return atoi32(s.c_str()); +} + +inline int64 atoi64(const string &s) { + return atoi64(s.c_str()); +} + +#endif // BASE_STRTOINT_H_ diff --git a/third_party/cld/base/template_util.h b/third_party/cld/base/template_util.h new file mode 100644 index 0000000..58c5ca6 --- /dev/null +++ b/third_party/cld/base/template_util.h @@ -0,0 +1,96 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Template metaprogramming utility functions. +// +// This code is compiled directly on many platforms, including client +// platforms like Windows, Mac, and embedded systems. Before making +// any changes here, make sure that you're not breaking any platforms. +// +// The names choosen here reflect those used in tr1 and the boost::mpl +// library, there are similar operations used in the Loki library as +// well. I prefer the boost names for 2 reasons: +// 1. I think that portions of the Boost libraries are more likely to +// be included in the c++ standard. +// 2. It is not impossible that some of the boost libraries will be +// included in our own build in the future. +// Both of these outcomes means that we may be able to directly replace +// some of these with boost equivalents. +// +#ifndef BASE_TEMPLATE_UTIL_H_ +#define BASE_TEMPLATE_UTIL_H_ + +namespace base { + +// Types small_ and big_ are guaranteed such that sizeof(small_) < +// sizeof(big_) +typedef char small_; + +struct big_ { + char dummy[2]; +}; + +// integral_constant, defined in tr1, is a wrapper for an integer +// value. We don't really need this generality; we could get away +// with hardcoding the integer type to bool. We use the fully +// general integer_constant for compatibility with tr1. + +template<class T, T v> +struct integral_constant { + static const T value = v; + typedef T value_type; + typedef integral_constant<T, v> type; +}; + +template <class T, T v> const T integral_constant<T, v>::value; + + +// Abbreviations: true_type and false_type are structs that represent boolean +// true and false values. Also define the boost::mpl versions of those names, +// true_ and false_. +typedef integral_constant<bool, true> true_type; +typedef integral_constant<bool, false> false_type; +typedef true_type true_; +typedef false_type false_; + +// if_ is a templatized conditional statement. +// if_<cond, A, B> is a compile time evaluation of cond. +// if_<>::type contains A if cond is true, B otherwise. +template<bool cond, typename A, typename B> +struct if_{ + typedef A type; +}; + +template<typename A, typename B> +struct if_<false, A, B> { + typedef B type; +}; + + +// type_equals_ is a template type comparator, similar to Loki IsSameType. +// type_equals_<A, B>::value is true iff "A" is the same type as "B". +template<typename A, typename B> +struct type_equals_ : public false_ { +}; + +template<typename A> +struct type_equals_<A, A> : public true_ { +}; + +// and_ is a template && operator. +// and_<A, B>::value evaluates "A::value && B::value". +template<typename A, typename B> +struct and_ : public integral_constant<bool, (A::value && B::value)> { +}; + +// or_ is a template || operator. +// or_<A, B>::value evaluates "A::value || B::value". +template<typename A, typename B> +struct or_ : public integral_constant<bool, (A::value || B::value)> { +}; + + +} // Close namespace base + +#endif // BASE_TEMPLATE_UTIL_H_ diff --git a/third_party/cld/base/type_traits.h b/third_party/cld/base/type_traits.h new file mode 100644 index 0000000..f423140 --- /dev/null +++ b/third_party/cld/base/type_traits.h @@ -0,0 +1,198 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This code is compiled directly on many platforms, including client +// platforms like Windows, Mac, and embedded systems. Before making +// any changes here, make sure that you're not breaking any platforms. +// +// +// Define a small subset of tr1 type traits. The traits we define are: +// is_integral +// is_floating_point +// is_pointer +// is_reference +// is_pod +// has_trivial_constructor +// has_trivial_copy +// has_trivial_assign +// has_trivial_destructor +// remove_const +// remove_volatile +// remove_cv +// remove_reference +// remove_pointer +// is_convertible +// We can add more type traits as required. + +#ifndef BASE_TYPE_TRAITS_H_ +#define BASE_TYPE_TRAITS_H_ + +#include "third_party/cld/base/template_util.h" // For true_type and false_type +#include <utility> // For pair + +namespace base { + +// is_integral is false except for the built-in integer types. +template <class T> struct is_integral : false_type { }; +template<> struct is_integral<bool> : true_type { }; +template<> struct is_integral<char> : true_type { }; +template<> struct is_integral<unsigned char> : true_type { }; +template<> struct is_integral<signed char> : true_type { }; +#if defined(_MSC_VER) +// wchar_t is not by default a distinct type from unsigned short in +// Microsoft C. +// See http://msdn2.microsoft.com/en-us/library/dh8che7s(VS.80).aspx +template<> struct is_integral<__wchar_t> : true_type { }; +#else +template<> struct is_integral<wchar_t> : true_type { }; +#endif +template<> struct is_integral<short> : true_type { }; +template<> struct is_integral<unsigned short> : true_type { }; +template<> struct is_integral<int> : true_type { }; +template<> struct is_integral<unsigned int> : true_type { }; +template<> struct is_integral<long> : true_type { }; +template<> struct is_integral<unsigned long> : true_type { }; +template<> struct is_integral<long long> : true_type { }; +template<> struct is_integral<unsigned long long> : true_type { }; + + +// is_floating_point is false except for the built-in floating-point types. +template <class T> struct is_floating_point : false_type { }; +template<> struct is_floating_point<float> : true_type { }; +template<> struct is_floating_point<double> : true_type { }; +template<> struct is_floating_point<long double> : true_type { }; + + +// is_pointer is false except for pointer types. +template <class T> struct is_pointer : false_type { }; +template <class T> struct is_pointer<T*> : true_type { }; + + +// is_reference is false except for reference types. +template<typename T> struct is_reference : false_type {}; +template<typename T> struct is_reference<T&> : true_type {}; + + +// We can't get is_pod right without compiler help, so fail conservatively. +// We will assume it's false except for arithmetic types and pointers, +// and const versions thereof. Note that std::pair is not a POD. +template <class T> struct is_pod + : integral_constant<bool, (is_integral<T>::value || + is_floating_point<T>::value || + is_pointer<T>::value)> { }; +template <class T> struct is_pod<const T> : is_pod<T> { }; + + +// We can't get has_trivial_constructor right without compiler help, so +// fail conservatively. We will assume it's false except for: (1) types +// for which is_pod is true. (2) std::pair of types with trivial +// constructors. (3) array of a type with a trivial constructor. +// (4) const versions thereof. +template <class T> struct has_trivial_constructor : is_pod<T> { }; +template <class T, class U> struct has_trivial_constructor<std::pair<T, U> > + : integral_constant<bool, + (has_trivial_constructor<T>::value && + has_trivial_constructor<U>::value)> { }; +template <class A, int N> struct has_trivial_constructor<A[N]> + : has_trivial_constructor<A> { }; +template <class T> struct has_trivial_constructor<const T> + : has_trivial_constructor<T> { }; + +// We can't get has_trivial_copy right without compiler help, so fail +// conservatively. We will assume it's false except for: (1) types +// for which is_pod is true. (2) std::pair of types with trivial copy +// constructors. (3) array of a type with a trivial copy constructor. +// (4) const versions thereof. +template <class T> struct has_trivial_copy : is_pod<T> { }; +template <class T, class U> struct has_trivial_copy<std::pair<T, U> > + : integral_constant<bool, + (has_trivial_copy<T>::value && + has_trivial_copy<U>::value)> { }; +template <class A, int N> struct has_trivial_copy<A[N]> + : has_trivial_copy<A> { }; +template <class T> struct has_trivial_copy<const T> : has_trivial_copy<T> { }; + +// We can't get has_trivial_assign right without compiler help, so fail +// conservatively. We will assume it's false except for: (1) types +// for which is_pod is true. (2) std::pair of types with trivial copy +// constructors. (3) array of a type with a trivial assign constructor. +template <class T> struct has_trivial_assign : is_pod<T> { }; +template <class T, class U> struct has_trivial_assign<std::pair<T, U> > + : integral_constant<bool, + (has_trivial_assign<T>::value && + has_trivial_assign<U>::value)> { }; +template <class A, int N> struct has_trivial_assign<A[N]> + : has_trivial_assign<A> { }; + +// We can't get has_trivial_destructor right without compiler help, so +// fail conservatively. We will assume it's false except for: (1) types +// for which is_pod is true. (2) std::pair of types with trivial +// destructors. (3) array of a type with a trivial destructor. +// (4) const versions thereof. +template <class T> struct has_trivial_destructor : is_pod<T> { }; +template <class T, class U> struct has_trivial_destructor<std::pair<T, U> > + : integral_constant<bool, + (has_trivial_destructor<T>::value && + has_trivial_destructor<U>::value)> { }; +template <class A, int N> struct has_trivial_destructor<A[N]> + : has_trivial_destructor<A> { }; +template <class T> struct has_trivial_destructor<const T> + : has_trivial_destructor<T> { }; + +// Specified by TR1 [4.7.1] +template<typename T> struct remove_const { typedef T type; }; +template<typename T> struct remove_const<T const> { typedef T type; }; +template<typename T> struct remove_volatile { typedef T type; }; +template<typename T> struct remove_volatile<T volatile> { typedef T type; }; +template<typename T> struct remove_cv { + typedef typename remove_const<typename remove_volatile<T>::type>::type type; +}; + + +// Specified by TR1 [4.7.2] +template<typename T> struct remove_reference { typedef T type; }; +template<typename T> struct remove_reference<T&> { typedef T type; }; + +// Specified by TR1 [4.7.4] Pointer modifications. +template<typename T> struct remove_pointer { typedef T type; }; +template<typename T> struct remove_pointer<T*> { typedef T type; }; +template<typename T> struct remove_pointer<T* const> { typedef T type; }; +template<typename T> struct remove_pointer<T* volatile> { typedef T type; }; +template<typename T> struct remove_pointer<T* const volatile> { + typedef T type; }; + +// Specified by TR1 [4.6] Relationships between types +#ifndef _MSC_VER +namespace internal { + +// This class is an implementation detail for is_convertible, and you +// don't need to know how it works to use is_convertible. For those +// who care: we declare two different functions, one whose argument is +// of type To and one with a variadic argument list. We give them +// return types of different size, so we can use sizeof to trick the +// compiler into telling us which function it would have chosen if we +// had called it with an argument of type From. See Alexandrescu's +// _Modern C++ Design_ for more details on this sort of trick. + +template <typename From, typename To> +struct ConvertHelper { + static small_ Test(To); + static big_ Test(...); + static From Create(); +}; +} // namespace internal + +// Inherits from true_type if From is convertible to To, false_type otherwise. +template <typename From, typename To> +struct is_convertible + : integral_constant<bool, + sizeof(internal::ConvertHelper<From, To>::Test( + internal::ConvertHelper<From, To>::Create())) + == sizeof(small_)> { +}; +#endif + +} // Close namespace base + +#endif // BASE_TYPE_TRAITS_H_ diff --git a/third_party/cld/base/vlog_is_on.h b/third_party/cld/base/vlog_is_on.h new file mode 100644 index 0000000..57c11ff --- /dev/null +++ b/third_party/cld/base/vlog_is_on.h @@ -0,0 +1,141 @@ +// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Defines the VLOG_IS_ON macro that controls the variable-verbosity +// conditional logging. +// +// It's used by VLOG and VLOG_IF in logging.h +// and by RAW_VLOG in raw_logging.h to trigger the logging. +// +// It can also be used directly e.g. like this: +// if (VLOG_IS_ON(2)) { +// // do some logging preparation and logging +// // that can't be accomplished e.g. via just VLOG(2) << ...; +// } +// +// The truth value that VLOG_IS_ON(level) returns is determined by +// the three verbosity level flags: +// --v=<n> Gives the default maximal active V-logging level; +// 0 is the default. +// Normally positive values are used for V-logging levels. +// --vmodule=<str> Gives the per-module maximal V-logging levels to override +// the value given by --v. +// E.g. "my_module=2,foo*=3" would change the logging level +// for all code in source files "my_module.*" and "foo*.*" +// ("-inl" suffixes are also disregarded for this matching). +// --silent_init When true has the effect of increasing +// the argument of VLOG_IS_ON by 1, +// thus suppressing one more level of verbose logging. +// +// SetVLOGLevel helper function is provided to do limited dynamic control over +// V-logging by overriding the per-module settings given via --vmodule flag. +// +// CAVEAT: --vmodule functionality is not available in non gcc compilers. +// + +#ifndef BASE_VLOG_IS_ON_H_ +#define BASE_VLOG_IS_ON_H_ + +#include "base/atomicops.h" +#include "base/basictypes.h" +#include "base/port.h" +#include "third_party/cld/base/commandlineflags.h" +#include "third_party/cld/base/log_severity.h" + +DECLARE_int32(v); // in vlog_is_on.cc +DECLARE_bool(silent_init); // in google.cc + +#if defined(__GNUC__) +// We pack an int16 verbosity level and an int16 epoch into an +// Atomic32 at every VLOG_IS_ON() call site. The level determines +// whether the site should log, and the epoch determines whether the +// site is stale and should be reinitialized. A verbosity level of +// kUseFlag (-1) indicates that the value of FLAGS_v should be used as +// the verbosity level. When the site is (re)initialized, a verbosity +// level for the current source file is retrieved from an internal +// list. This list is mutated through calls to SetVLOGLevel() and +// mutations to the --vmodule flag. New log sites are initialized +// with a stale epoch and a verbosity level of kUseFlag. +// +// TODO(llansing): Investigate using GCC's __builtin_constant_p() to +// generate less code at call sites where verbositylevel is known to +// be a compile-time constant. +#define VLOG_IS_ON(verboselevel) \ + ({ static Atomic32 site__ = ::base::internal::kDefaultSite; \ + ::base::internal::VLogEnabled(&site__, (verboselevel), __FILE__); }) +#else +// GNU extensions not available, so we do not support --vmodule. +// Dynamic value of FLAGS_v always controls the logging level. +// +// TODO(llansing): Investigate supporting --vmodule on other platforms. +#define VLOG_IS_ON(verboselevel) \ + (FLAGS_v >= (verboselevel) + FLAGS_silent_init) +#endif + +// Set VLOG(_IS_ON) level for module_pattern to log_level. +// This lets us dynamically control what is normally set by the --vmodule flag. +// Returns the level that previously applied to module_pattern. +// NOTE: To change the log level for VLOG(_IS_ON) sites +// that have already executed after/during InitGoogle, +// one needs to supply the exact --vmodule pattern that applied to them. +// (If no --vmodule pattern applied to them +// the value of FLAGS_v will continue to control them.) +int SetVLOGLevel(const char* module_pattern, int log_level); + +// Private implementation details. No user-serviceable parts inside. +namespace base { +namespace internal { + +// Each log site determines whether its log level is up to date by +// comparing its epoch to this global epoch. Whenever the program's +// vmodule configuration changes (ex: SetVLOGLevel is called), the +// global epoch is advanced, invalidating all site epochs. +extern Atomic32 vlog_epoch; + +// A log level of kUseFlag means "read the logging level from FLAGS_v." +const int kUseFlag = -1; + +// Log sites use FLAGS_v by default, and have an initial epoch of 0. +const Atomic32 kDefaultSite = kUseFlag << 16; + +// The global epoch is the least significant half of an Atomic32, and +// may only be accessed through atomic operations. +inline Atomic32 GlobalEpoch() { return Acquire_Load(&vlog_epoch) & 0x0000FFFF; } + +// The least significant half of a site is the epoch. +inline int SiteEpoch(Atomic32 site) { return site & 0x0000FFFF; } + +// The most significant half of a site is the logging level. +inline int SiteLevel(Atomic32 site) { return site >> 16; } + +// Construct a logging site from a logging level and epoch. +inline Atomic32 Site(int level, int epoch) { + return ((level & 0x0000FFFF) << 16) | (epoch & 0x0000FFFF); +} + +// Attempt to initialize or reinitialize a VLOG site. Returns the +// level of the log site, regardless of whether the attempt succeeds +// or fails. +// site: The address of the log site's state. +// fname: The filename of the current source file. +int InitVLOG(Atomic32* site, const char* fname); + +// Determine whether verbose logging should occur at a given log site. +// +// TODO(llansing): Find a way to eliminate FLAGS_silent_init from this +// function while preserving the silent initialization behavior. The +// common-case code path shouldn't pay for silent initialization. +inline bool VLogEnabled(Atomic32* site, int32 level, const char* const file) { + const Atomic32 site_copy = Acquire_Load(site); + const int32 site_level = + PREDICT_TRUE(SiteEpoch(site_copy) == GlobalEpoch()) ? + SiteLevel(site_copy) : InitVLOG(site, file); + return (site_level == kUseFlag ? FLAGS_v : site_level) >= + (level + FLAGS_silent_init); +} + +} // namespace internal +} // namespace base + +#endif // BASE_VLOG_IS_ON_H_ |