summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorerg@google.com <erg@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2011-01-11 00:50:59 +0000
committererg@google.com <erg@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2011-01-11 00:50:59 +0000
commiteae9c0623d1800201739b4be146649103a45cd93 (patch)
tree2ce42f83e18d8a0a618ffd6dbe69b1acade5bda4
parent26f0821d0a34a79e551213d56054366aab6c70f7 (diff)
downloadchromium_src-eae9c0623d1800201739b4be146649103a45cd93.zip
chromium_src-eae9c0623d1800201739b4be146649103a45cd93.tar.gz
chromium_src-eae9c0623d1800201739b4be146649103a45cd93.tar.bz2
Order function definitions in base/ according to the header.
BUG=68682 TEST=compiles Review URL: http://codereview.chromium.org/6085015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70975 0039d316-1c4b-4281-b951-d872f2087c98
-rw-r--r--base/at_exit.cc10
-rw-r--r--base/crypto/rsa_private_key.cc266
-rw-r--r--base/crypto/rsa_private_key_nss.cc135
-rw-r--r--base/crypto/signature_creator_nss.cc22
-rw-r--r--base/crypto/symmetric_key_nss.cc8
-rw-r--r--base/debug/trace_event.cc132
-rw-r--r--base/file_util.cc20
-rw-r--r--base/file_util_posix.cc40
-rw-r--r--base/file_util_proxy.cc82
-rw-r--r--base/file_util_proxy.h28
-rw-r--r--base/global_descriptors_posix.cc28
-rw-r--r--base/global_descriptors_posix.h4
-rw-r--r--base/hmac_nss.cc6
-rw-r--r--base/json/json_reader.cc50
-rw-r--r--base/json/json_reader.h10
-rw-r--r--base/logging.cc106
-rw-r--r--base/message_loop_proxy_impl.cc56
-rw-r--r--base/message_pump_glib.cc38
-rw-r--r--base/message_pump_glib_x.cc107
-rw-r--r--base/message_pump_libevent.cc150
-rw-r--r--base/metrics/field_trial.cc30
-rw-r--r--base/metrics/stats_table.cc254
-rw-r--r--base/ref_counted.cc10
-rw-r--r--base/shared_memory_posix.cc125
-rw-r--r--base/synchronization/waitable_event_posix.cc11
-rw-r--r--base/threading/simple_thread.cc32
-rw-r--r--base/threading/thread.cc46
-rw-r--r--base/time.h8
-rw-r--r--base/time_posix.cc74
-rw-r--r--base/tracked_objects.cc9
-rw-r--r--base/vlog.cc30
-rw-r--r--base/vlog.h17
32 files changed, 973 insertions, 971 deletions
diff --git a/base/at_exit.cc b/base/at_exit.cc
index 9fdfd77..e6618a0 100644
--- a/base/at_exit.cc
+++ b/base/at_exit.cc
@@ -18,11 +18,6 @@ AtExitManager::AtExitManager() : next_manager_(NULL) {
g_top_manager = this;
}
-AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
- DCHECK(shadow || !g_top_manager);
- g_top_manager = this;
-}
-
AtExitManager::~AtExitManager() {
if (!g_top_manager) {
NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
@@ -64,4 +59,9 @@ void AtExitManager::ProcessCallbacksNow() {
}
}
+AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
+ DCHECK(shadow || !g_top_manager);
+ g_top_manager = this;
+}
+
} // namespace base
diff --git a/base/crypto/rsa_private_key.cc b/base/crypto/rsa_private_key.cc
index 75da7e4..4048ed1 100644
--- a/base/crypto/rsa_private_key.cc
+++ b/base/crypto/rsa_private_key.cc
@@ -48,118 +48,6 @@ const uint8 PrivateKeyInfoCodec::kRsaAlgorithmIdentifier[] = {
0x05, 0x00
};
-void PrivateKeyInfoCodec::PrependBytes(uint8* val,
- int start,
- int num_bytes,
- std::list<uint8>* data) {
- while (num_bytes > 0) {
- --num_bytes;
- data->push_front(val[start + num_bytes]);
- }
-}
-
-void PrivateKeyInfoCodec::PrependLength(size_t size, std::list<uint8>* data) {
- // The high bit is used to indicate whether additional octets are needed to
- // represent the length.
- if (size < 0x80) {
- data->push_front(static_cast<uint8>(size));
- } else {
- uint8 num_bytes = 0;
- while (size > 0) {
- data->push_front(static_cast<uint8>(size & 0xFF));
- size >>= 8;
- num_bytes++;
- }
- CHECK_LE(num_bytes, 4);
- data->push_front(0x80 | num_bytes);
- }
-}
-
-void PrivateKeyInfoCodec::PrependTypeHeaderAndLength(uint8 type,
- uint32 length,
- std::list<uint8>* output) {
- PrependLength(length, output);
- output->push_front(type);
-}
-
-void PrivateKeyInfoCodec::PrependBitString(uint8* val,
- int num_bytes,
- std::list<uint8>* output) {
- // Start with the data.
- PrependBytes(val, 0, num_bytes, output);
- // Zero unused bits.
- output->push_front(0);
- // Add the length.
- PrependLength(num_bytes + 1, output);
- // Finally, add the bit string tag.
- output->push_front((uint8) kBitStringTag);
-}
-
-bool PrivateKeyInfoCodec::ReadLength(uint8** pos, uint8* end, uint32* result) {
- READ_ASSERT(*pos < end);
- int length = 0;
-
- // If the MSB is not set, the length is just the byte itself.
- if (!(**pos & 0x80)) {
- length = **pos;
- (*pos)++;
- } else {
- // Otherwise, the lower 7 indicate the length of the length.
- int length_of_length = **pos & 0x7F;
- READ_ASSERT(length_of_length <= 4);
- (*pos)++;
- READ_ASSERT(*pos + length_of_length < end);
-
- length = 0;
- for (int i = 0; i < length_of_length; ++i) {
- length <<= 8;
- length |= **pos;
- (*pos)++;
- }
- }
-
- READ_ASSERT(*pos + length <= end);
- if (result) *result = length;
- return true;
-}
-
-bool PrivateKeyInfoCodec::ReadTypeHeaderAndLength(uint8** pos,
- uint8* end,
- uint8 expected_tag,
- uint32* length) {
- READ_ASSERT(*pos < end);
- READ_ASSERT(**pos == expected_tag);
- (*pos)++;
-
- return ReadLength(pos, end, length);
-}
-
-bool PrivateKeyInfoCodec::ReadSequence(uint8** pos, uint8* end) {
- return ReadTypeHeaderAndLength(pos, end, kSequenceTag, NULL);
-}
-
-bool PrivateKeyInfoCodec::ReadAlgorithmIdentifier(uint8** pos, uint8* end) {
- READ_ASSERT(*pos + sizeof(kRsaAlgorithmIdentifier) < end);
- READ_ASSERT(memcmp(*pos, kRsaAlgorithmIdentifier,
- sizeof(kRsaAlgorithmIdentifier)) == 0);
- (*pos) += sizeof(kRsaAlgorithmIdentifier);
- return true;
-}
-
-bool PrivateKeyInfoCodec::ReadVersion(uint8** pos, uint8* end) {
- uint32 length = 0;
- if (!ReadTypeHeaderAndLength(pos, end, kIntegerTag, &length))
- return false;
-
- // The version should be zero.
- for (uint32 i = 0; i < length; ++i) {
- READ_ASSERT(**pos == 0x00);
- (*pos)++;
- }
-
- return true;
-}
-
PrivateKeyInfoCodec::PrivateKeyInfoCodec(bool big_endian)
: big_endian_(big_endian) {}
@@ -321,6 +209,36 @@ bool PrivateKeyInfoCodec::ReadInteger(uint8** pos,
return ReadIntegerImpl(pos, end, out, big_endian_);
}
+bool PrivateKeyInfoCodec::ReadIntegerWithExpectedSize(uint8** pos,
+ uint8* end,
+ size_t expected_size,
+ std::vector<uint8>* out) {
+ std::vector<uint8> temp;
+ if (!ReadIntegerImpl(pos, end, &temp, true)) // Big-Endian
+ return false;
+
+ int pad = expected_size - temp.size();
+ int index = 0;
+ if (out->size() == expected_size + 1) {
+ READ_ASSERT(out->front() == 0x00);
+ pad++;
+ index++;
+ } else {
+ READ_ASSERT(out->size() <= expected_size);
+ }
+
+ while (pad) {
+ out->push_back(0x00);
+ pad--;
+ }
+ out->insert(out->end(), temp.begin(), temp.end());
+
+ // Reverse output if little-endian.
+ if (!big_endian_)
+ reverse(out->begin(), out->end());
+ return true;
+}
+
bool PrivateKeyInfoCodec::ReadIntegerImpl(uint8** pos,
uint8* end,
std::vector<uint8>* out,
@@ -346,33 +264,115 @@ bool PrivateKeyInfoCodec::ReadIntegerImpl(uint8** pos,
return true;
}
-bool PrivateKeyInfoCodec::ReadIntegerWithExpectedSize(uint8** pos,
- uint8* end,
- size_t expected_size,
- std::vector<uint8>* out) {
- std::vector<uint8> temp;
- if (!ReadIntegerImpl(pos, end, &temp, true)) // Big-Endian
- return false;
+void PrivateKeyInfoCodec::PrependBytes(uint8* val,
+ int start,
+ int num_bytes,
+ std::list<uint8>* data) {
+ while (num_bytes > 0) {
+ --num_bytes;
+ data->push_front(val[start + num_bytes]);
+ }
+}
- int pad = expected_size - temp.size();
- int index = 0;
- if (out->size() == expected_size + 1) {
- READ_ASSERT(out->front() == 0x00);
- pad++;
- index++;
+void PrivateKeyInfoCodec::PrependLength(size_t size, std::list<uint8>* data) {
+ // The high bit is used to indicate whether additional octets are needed to
+ // represent the length.
+ if (size < 0x80) {
+ data->push_front(static_cast<uint8>(size));
} else {
- READ_ASSERT(out->size() <= expected_size);
+ uint8 num_bytes = 0;
+ while (size > 0) {
+ data->push_front(static_cast<uint8>(size & 0xFF));
+ size >>= 8;
+ num_bytes++;
+ }
+ CHECK_LE(num_bytes, 4);
+ data->push_front(0x80 | num_bytes);
}
+}
- while (pad) {
- out->push_back(0x00);
- pad--;
+void PrivateKeyInfoCodec::PrependTypeHeaderAndLength(uint8 type,
+ uint32 length,
+ std::list<uint8>* output) {
+ PrependLength(length, output);
+ output->push_front(type);
+}
+
+void PrivateKeyInfoCodec::PrependBitString(uint8* val,
+ int num_bytes,
+ std::list<uint8>* output) {
+ // Start with the data.
+ PrependBytes(val, 0, num_bytes, output);
+ // Zero unused bits.
+ output->push_front(0);
+ // Add the length.
+ PrependLength(num_bytes + 1, output);
+ // Finally, add the bit string tag.
+ output->push_front((uint8) kBitStringTag);
+}
+
+bool PrivateKeyInfoCodec::ReadLength(uint8** pos, uint8* end, uint32* result) {
+ READ_ASSERT(*pos < end);
+ int length = 0;
+
+ // If the MSB is not set, the length is just the byte itself.
+ if (!(**pos & 0x80)) {
+ length = **pos;
+ (*pos)++;
+ } else {
+ // Otherwise, the lower 7 indicate the length of the length.
+ int length_of_length = **pos & 0x7F;
+ READ_ASSERT(length_of_length <= 4);
+ (*pos)++;
+ READ_ASSERT(*pos + length_of_length < end);
+
+ length = 0;
+ for (int i = 0; i < length_of_length; ++i) {
+ length <<= 8;
+ length |= **pos;
+ (*pos)++;
+ }
+ }
+
+ READ_ASSERT(*pos + length <= end);
+ if (result) *result = length;
+ return true;
+}
+
+bool PrivateKeyInfoCodec::ReadTypeHeaderAndLength(uint8** pos,
+ uint8* end,
+ uint8 expected_tag,
+ uint32* length) {
+ READ_ASSERT(*pos < end);
+ READ_ASSERT(**pos == expected_tag);
+ (*pos)++;
+
+ return ReadLength(pos, end, length);
+}
+
+bool PrivateKeyInfoCodec::ReadSequence(uint8** pos, uint8* end) {
+ return ReadTypeHeaderAndLength(pos, end, kSequenceTag, NULL);
+}
+
+bool PrivateKeyInfoCodec::ReadAlgorithmIdentifier(uint8** pos, uint8* end) {
+ READ_ASSERT(*pos + sizeof(kRsaAlgorithmIdentifier) < end);
+ READ_ASSERT(memcmp(*pos, kRsaAlgorithmIdentifier,
+ sizeof(kRsaAlgorithmIdentifier)) == 0);
+ (*pos) += sizeof(kRsaAlgorithmIdentifier);
+ return true;
+}
+
+bool PrivateKeyInfoCodec::ReadVersion(uint8** pos, uint8* end) {
+ uint32 length = 0;
+ if (!ReadTypeHeaderAndLength(pos, end, kIntegerTag, &length))
+ return false;
+
+ // The version should be zero.
+ for (uint32 i = 0; i < length; ++i) {
+ READ_ASSERT(**pos == 0x00);
+ (*pos)++;
}
- out->insert(out->end(), temp.begin(), temp.end());
- // Reverse output if little-endian.
- if (!big_endian_)
- reverse(out->begin(), out->end());
return true;
}
diff --git a/base/crypto/rsa_private_key_nss.cc b/base/crypto/rsa_private_key_nss.cc
index 7786521..3084636 100644
--- a/base/crypto/rsa_private_key_nss.cc
+++ b/base/crypto/rsa_private_key_nss.cc
@@ -41,28 +41,11 @@ static bool ReadAttribute(SECKEYPrivateKey* key,
namespace base {
-// static
-RSAPrivateKey* RSAPrivateKey::CreateWithParams(uint16 num_bits,
- bool permanent,
- bool sensitive) {
- base::EnsureNSSInit();
-
- scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
-
- PK11SlotInfo *slot = GetDefaultNSSKeySlot();
- if (!slot)
- return NULL;
-
- PK11RSAGenParams param;
- param.keySizeInBits = num_bits;
- param.pe = 65537L;
- result->key_ = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &param,
- &result->public_key_, permanent, sensitive, NULL);
- PK11_FreeSlot(slot);
- if (!result->key_)
- return NULL;
-
- return result.release();
+RSAPrivateKey::~RSAPrivateKey() {
+ if (key_)
+ SECKEY_DestroyPrivateKey(key_);
+ if (public_key_)
+ SECKEY_DestroyPublicKey(public_key_);
}
// static
@@ -80,41 +63,6 @@ RSAPrivateKey* RSAPrivateKey::CreateSensitive(uint16 num_bits) {
}
// static
-RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfoWithParams(
- const std::vector<uint8>& input, bool permanent, bool sensitive) {
- // This method currently leaks some memory.
- // See http://crbug.com/34742.
- ANNOTATE_SCOPED_MEMORY_LEAK;
- base::EnsureNSSInit();
-
- scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
-
- PK11SlotInfo *slot = GetDefaultNSSKeySlot();
- if (!slot)
- return NULL;
-
- SECItem der_private_key_info;
- der_private_key_info.data = const_cast<unsigned char*>(&input.front());
- der_private_key_info.len = input.size();
- SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(slot,
- &der_private_key_info, NULL, NULL, permanent, sensitive,
- KU_DIGITAL_SIGNATURE, &result->key_, NULL);
- PK11_FreeSlot(slot);
- if (rv != SECSuccess) {
- NOTREACHED();
- return NULL;
- }
-
- result->public_key_ = SECKEY_ConvertToPublicKey(result->key_);
- if (!result->public_key_) {
- NOTREACHED();
- return NULL;
- }
-
- return result.release();
-}
-
-// static
RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfo(
const std::vector<uint8>& input) {
return CreateFromPrivateKeyInfoWithParams(input,
@@ -193,16 +141,6 @@ RSAPrivateKey* RSAPrivateKey::FindFromPublicKeyInfo(
return result.release();
}
-RSAPrivateKey::RSAPrivateKey() : key_(NULL), public_key_(NULL) {
- EnsureNSSInit();
-}
-
-RSAPrivateKey::~RSAPrivateKey() {
- if (key_)
- SECKEY_DestroyPrivateKey(key_);
- if (public_key_)
- SECKEY_DestroyPublicKey(public_key_);
-}
bool RSAPrivateKey::ExportPrivateKey(std::vector<uint8>* output) {
PrivateKeyInfoCodec private_key_info(true);
@@ -240,4 +178,67 @@ bool RSAPrivateKey::ExportPublicKey(std::vector<uint8>* output) {
return true;
}
+RSAPrivateKey::RSAPrivateKey() : key_(NULL), public_key_(NULL) {
+ EnsureNSSInit();
+}
+
+// static
+RSAPrivateKey* RSAPrivateKey::CreateWithParams(uint16 num_bits,
+ bool permanent,
+ bool sensitive) {
+ base::EnsureNSSInit();
+
+ scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
+
+ PK11SlotInfo *slot = GetDefaultNSSKeySlot();
+ if (!slot)
+ return NULL;
+
+ PK11RSAGenParams param;
+ param.keySizeInBits = num_bits;
+ param.pe = 65537L;
+ result->key_ = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &param,
+ &result->public_key_, permanent, sensitive, NULL);
+ PK11_FreeSlot(slot);
+ if (!result->key_)
+ return NULL;
+
+ return result.release();
+}
+
+// static
+RSAPrivateKey* RSAPrivateKey::CreateFromPrivateKeyInfoWithParams(
+ const std::vector<uint8>& input, bool permanent, bool sensitive) {
+ // This method currently leaks some memory.
+ // See http://crbug.com/34742.
+ ANNOTATE_SCOPED_MEMORY_LEAK;
+ base::EnsureNSSInit();
+
+ scoped_ptr<RSAPrivateKey> result(new RSAPrivateKey);
+
+ PK11SlotInfo *slot = GetDefaultNSSKeySlot();
+ if (!slot)
+ return NULL;
+
+ SECItem der_private_key_info;
+ der_private_key_info.data = const_cast<unsigned char*>(&input.front());
+ der_private_key_info.len = input.size();
+ SECStatus rv = PK11_ImportDERPrivateKeyInfoAndReturnKey(slot,
+ &der_private_key_info, NULL, NULL, permanent, sensitive,
+ KU_DIGITAL_SIGNATURE, &result->key_, NULL);
+ PK11_FreeSlot(slot);
+ if (rv != SECSuccess) {
+ NOTREACHED();
+ return NULL;
+ }
+
+ result->public_key_ = SECKEY_ConvertToPublicKey(result->key_);
+ if (!result->public_key_) {
+ NOTREACHED();
+ return NULL;
+ }
+
+ return result.release();
+}
+
} // namespace base
diff --git a/base/crypto/signature_creator_nss.cc b/base/crypto/signature_creator_nss.cc
index ff1d271..4cc2c10 100644
--- a/base/crypto/signature_creator_nss.cc
+++ b/base/crypto/signature_creator_nss.cc
@@ -14,6 +14,13 @@
namespace base {
+SignatureCreator::~SignatureCreator() {
+ if (sign_context_) {
+ SGN_DestroyContext(sign_context_, PR_TRUE);
+ sign_context_ = NULL;
+ }
+}
+
// static
SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key) {
scoped_ptr<SignatureCreator> result(new SignatureCreator);
@@ -35,17 +42,6 @@ SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key) {
return result.release();
}
-SignatureCreator::SignatureCreator() : sign_context_(NULL) {
- EnsureNSSInit();
-}
-
-SignatureCreator::~SignatureCreator() {
- if (sign_context_) {
- SGN_DestroyContext(sign_context_, PR_TRUE);
- sign_context_ = NULL;
- }
-}
-
bool SignatureCreator::Update(const uint8* data_part, int data_part_len) {
// TODO(wtc): Remove this const_cast when we require NSS 3.12.5.
// See NSS bug https://bugzilla.mozilla.org/show_bug.cgi?id=518255
@@ -73,4 +69,8 @@ bool SignatureCreator::Final(std::vector<uint8>* signature) {
return true;
}
+SignatureCreator::SignatureCreator() : sign_context_(NULL) {
+ EnsureNSSInit();
+}
+
} // namespace base
diff --git a/base/crypto/symmetric_key_nss.cc b/base/crypto/symmetric_key_nss.cc
index d291e8d..1e3551d 100644
--- a/base/crypto/symmetric_key_nss.cc
+++ b/base/crypto/symmetric_key_nss.cc
@@ -12,10 +12,6 @@
namespace base {
-SymmetricKey::SymmetricKey(PK11SymKey* key) : key_(key) {
- DCHECK(key);
-}
-
SymmetricKey::~SymmetricKey() {}
// static
@@ -124,4 +120,8 @@ bool SymmetricKey::GetRawKey(std::string* raw_key) {
return true;
}
+SymmetricKey::SymmetricKey(PK11SymKey* key) : key_(key) {
+ DCHECK(key);
+}
+
} // namespace base
diff --git a/base/debug/trace_event.cc b/base/debug/trace_event.cc
index 16538c1..c219cec 100644
--- a/base/debug/trace_event.cc
+++ b/base/debug/trace_event.cc
@@ -28,22 +28,6 @@ static const char* kEventTypeNames[] = {
static const FilePath::CharType* kLogFileName =
FILE_PATH_LITERAL("trace_%d.log");
-TraceLog::TraceLog() : enabled_(false), log_file_(NULL) {
- base::ProcessHandle proc = base::GetCurrentProcessHandle();
-#if !defined(OS_MACOSX)
- process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc));
-#else
- // The default port provider is sufficient to get data for the current
- // process.
- process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc,
- NULL));
-#endif
-}
-
-TraceLog::~TraceLog() {
- Stop();
-}
-
// static
TraceLog* TraceLog::GetInstance() {
return Singleton<TraceLog, DefaultSingletonTraits<TraceLog> >::get();
@@ -59,61 +43,11 @@ bool TraceLog::StartTracing() {
return TraceLog::GetInstance()->Start();
}
-bool TraceLog::Start() {
- if (enabled_)
- return true;
- enabled_ = OpenLogFile();
- if (enabled_) {
- Log("var raw_trace_events = [\n");
- trace_start_time_ = TimeTicks::Now();
- timer_.Start(TimeDelta::FromMilliseconds(250), this, &TraceLog::Heartbeat);
- }
- return enabled_;
-}
-
// static
void TraceLog::StopTracing() {
return TraceLog::GetInstance()->Stop();
}
-void TraceLog::Stop() {
- if (enabled_) {
- enabled_ = false;
- Log("];\n");
- CloseLogFile();
- timer_.Stop();
- }
-}
-
-void TraceLog::Heartbeat() {
- std::string cpu = StringPrintf("%.0f", process_metrics_->GetCPUUsage());
- TRACE_EVENT_INSTANT("heartbeat.cpu", 0, cpu);
-}
-
-void TraceLog::CloseLogFile() {
- if (log_file_) {
- file_util::CloseFile(log_file_);
- }
-}
-
-bool TraceLog::OpenLogFile() {
- FilePath::StringType pid_filename =
- StringPrintf(kLogFileName, base::GetCurrentProcId());
- FilePath log_file_path;
- if (!PathService::Get(base::DIR_EXE, &log_file_path))
- return false;
- log_file_path = log_file_path.Append(pid_filename);
- log_file_ = file_util::OpenFile(log_file_path, "a");
- if (!log_file_) {
- // try the current directory
- log_file_ = file_util::OpenFile(FilePath(pid_filename), "a");
- if (!log_file_) {
- return false;
- }
- }
- return true;
-}
-
void TraceLog::Trace(const std::string& name,
EventType type,
const void* id,
@@ -158,6 +92,72 @@ void TraceLog::Trace(const std::string& name,
Log(msg);
}
+TraceLog::TraceLog() : enabled_(false), log_file_(NULL) {
+ base::ProcessHandle proc = base::GetCurrentProcessHandle();
+#if !defined(OS_MACOSX)
+ process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc));
+#else
+ // The default port provider is sufficient to get data for the current
+ // process.
+ process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(proc,
+ NULL));
+#endif
+}
+
+TraceLog::~TraceLog() {
+ Stop();
+}
+
+bool TraceLog::OpenLogFile() {
+ FilePath::StringType pid_filename =
+ StringPrintf(kLogFileName, base::GetCurrentProcId());
+ FilePath log_file_path;
+ if (!PathService::Get(base::DIR_EXE, &log_file_path))
+ return false;
+ log_file_path = log_file_path.Append(pid_filename);
+ log_file_ = file_util::OpenFile(log_file_path, "a");
+ if (!log_file_) {
+ // try the current directory
+ log_file_ = file_util::OpenFile(FilePath(pid_filename), "a");
+ if (!log_file_) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void TraceLog::CloseLogFile() {
+ if (log_file_) {
+ file_util::CloseFile(log_file_);
+ }
+}
+
+bool TraceLog::Start() {
+ if (enabled_)
+ return true;
+ enabled_ = OpenLogFile();
+ if (enabled_) {
+ Log("var raw_trace_events = [\n");
+ trace_start_time_ = TimeTicks::Now();
+ timer_.Start(TimeDelta::FromMilliseconds(250), this, &TraceLog::Heartbeat);
+ }
+ return enabled_;
+}
+
+void TraceLog::Stop() {
+ if (enabled_) {
+ enabled_ = false;
+ Log("];\n");
+ CloseLogFile();
+ timer_.Stop();
+ }
+}
+
+void TraceLog::Heartbeat() {
+ std::string cpu = StringPrintf("%.0f", process_metrics_->GetCPUUsage());
+ TRACE_EVENT_INSTANT("heartbeat.cpu", 0, cpu);
+}
+
void TraceLog::Log(const std::string& msg) {
AutoLock lock(file_lock_);
diff --git a/base/file_util.cc b/base/file_util.cc
index d1a46c9..c9661e7 100644
--- a/base/file_util.cc
+++ b/base/file_util.cc
@@ -315,13 +315,11 @@ MemoryMappedFile::~MemoryMappedFile() {
CloseHandles();
}
-bool MemoryMappedFile::Initialize(base::PlatformFile file) {
+bool MemoryMappedFile::Initialize(const FilePath& file_name) {
if (IsValid())
return false;
- file_ = file;
-
- if (!MapFileToMemoryInternal()) {
+ if (!MapFileToMemory(file_name)) {
CloseHandles();
return false;
}
@@ -329,11 +327,13 @@ bool MemoryMappedFile::Initialize(base::PlatformFile file) {
return true;
}
-bool MemoryMappedFile::Initialize(const FilePath& file_name) {
+bool MemoryMappedFile::Initialize(base::PlatformFile file) {
if (IsValid())
return false;
- if (!MapFileToMemory(file_name)) {
+ file_ = file;
+
+ if (!MapFileToMemoryInternal()) {
CloseHandles();
return false;
}
@@ -341,6 +341,10 @@ bool MemoryMappedFile::Initialize(const FilePath& file_name) {
return true;
}
+bool MemoryMappedFile::IsValid() {
+ return data_ != NULL;
+}
+
bool MemoryMappedFile::MapFileToMemory(const FilePath& file_name) {
file_ = base::CreatePlatformFile(
file_name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
@@ -354,10 +358,6 @@ bool MemoryMappedFile::MapFileToMemory(const FilePath& file_name) {
return MapFileToMemoryInternal();
}
-bool MemoryMappedFile::IsValid() {
- return data_ != NULL;
-}
-
// Deprecated functions ----------------------------------------------------
#if defined(OS_WIN)
diff --git a/base/file_util_posix.cc b/base/file_util_posix.cc
index cbfcfb0..7e4c3a9 100644
--- a/base/file_util_posix.cc
+++ b/base/file_util_posix.cc
@@ -641,26 +641,6 @@ FileEnumerator::FileEnumerator(const FilePath& root_path,
FileEnumerator::~FileEnumerator() {
}
-void FileEnumerator::GetFindInfo(FindInfo* info) {
- DCHECK(info);
-
- if (current_directory_entry_ >= directory_entries_.size())
- return;
-
- DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
- memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
- info->filename.assign(cur_entry->filename.value());
-}
-
-bool FileEnumerator::IsDirectory(const FindInfo& info) {
- return S_ISDIR(info.stat.st_mode);
-}
-
-// static
-FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
- return FilePath(find_info.filename);
-}
-
FilePath FileEnumerator::Next() {
++current_directory_entry_;
@@ -702,6 +682,26 @@ FilePath FileEnumerator::Next() {
].filename);
}
+void FileEnumerator::GetFindInfo(FindInfo* info) {
+ DCHECK(info);
+
+ if (current_directory_entry_ >= directory_entries_.size())
+ return;
+
+ DirectoryEntryInfo* cur_entry = &directory_entries_[current_directory_entry_];
+ memcpy(&(info->stat), &(cur_entry->stat), sizeof(info->stat));
+ info->filename.assign(cur_entry->filename.value());
+}
+
+bool FileEnumerator::IsDirectory(const FindInfo& info) {
+ return S_ISDIR(info.stat.st_mode);
+}
+
+// static
+FilePath FileEnumerator::GetFilename(const FindInfo& find_info) {
+ return FilePath(find_info.filename);
+}
+
bool FileEnumerator::ReadDirectory(std::vector<DirectoryEntryInfo>* entries,
const FilePath& source, bool show_links) {
base::ThreadRestrictions::AssertIOAllowed();
diff --git a/base/file_util_proxy.cc b/base/file_util_proxy.cc
index bd08909..b4d0d54 100644
--- a/base/file_util_proxy.cc
+++ b/base/file_util_proxy.cc
@@ -747,17 +747,6 @@ bool FileUtilProxy::CreateTemporary(
}
// static
-bool FileUtilProxy::CreateDirectory(
- scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& file_path,
- bool exclusive,
- bool recursive,
- StatusCallback* callback) {
- return Start(FROM_HERE, message_loop_proxy, new RelayCreateDirectory(
- file_path, exclusive, recursive, callback));
-}
-
-// static
bool FileUtilProxy::Close(scoped_refptr<MessageLoopProxy> message_loop_proxy,
base::PlatformFile file_handle,
StatusCallback* callback) {
@@ -774,13 +763,43 @@ bool FileUtilProxy::EnsureFileExists(
message_loop_proxy, file_path, callback));
}
+// Retrieves the information about a file. It is invalid to pass NULL for the
+// callback.
+bool FileUtilProxy::GetFileInfo(
+ scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ const FilePath& file_path,
+ GetFileInfoCallback* callback) {
+ return Start(FROM_HERE, message_loop_proxy, new RelayGetFileInfo(
+ file_path, callback));
+}
+
// static
-bool FileUtilProxy::Delete(scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& file_path,
- bool recursive,
- StatusCallback* callback) {
+bool FileUtilProxy::GetFileInfoFromPlatformFile(
+ scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ PlatformFile file,
+ GetFileInfoCallback* callback) {
return Start(FROM_HERE, message_loop_proxy,
- new RelayDelete(file_path, recursive, callback));
+ new RelayGetFileInfoFromPlatformFile(file, callback));
+}
+
+// static
+bool FileUtilProxy::ReadDirectory(
+ scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ const FilePath& file_path,
+ ReadDirectoryCallback* callback) {
+ return Start(FROM_HERE, message_loop_proxy, new RelayReadDirectory(
+ file_path, callback));
+}
+
+// static
+bool FileUtilProxy::CreateDirectory(
+ scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ const FilePath& file_path,
+ bool exclusive,
+ bool recursive,
+ StatusCallback* callback) {
+ return Start(FROM_HERE, message_loop_proxy, new RelayCreateDirectory(
+ file_path, exclusive, recursive, callback));
}
// static
@@ -802,22 +821,12 @@ bool FileUtilProxy::Move(scoped_refptr<MessageLoopProxy> message_loop_proxy,
}
// static
-bool FileUtilProxy::ReadDirectory(
- scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& file_path,
- ReadDirectoryCallback* callback) {
- return Start(FROM_HERE, message_loop_proxy, new RelayReadDirectory(
- file_path, callback));
-}
-
-// Retrieves the information about a file. It is invalid to pass NULL for the
-// callback.
-bool FileUtilProxy::GetFileInfo(
- scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& file_path,
- GetFileInfoCallback* callback) {
- return Start(FROM_HERE, message_loop_proxy, new RelayGetFileInfo(
- file_path, callback));
+bool FileUtilProxy::Delete(scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ const FilePath& file_path,
+ bool recursive,
+ StatusCallback* callback) {
+ return Start(FROM_HERE, message_loop_proxy,
+ new RelayDelete(file_path, recursive, callback));
}
// static
@@ -830,15 +839,6 @@ bool FileUtilProxy::RecursiveDelete(
}
// static
-bool FileUtilProxy::GetFileInfoFromPlatformFile(
- scoped_refptr<MessageLoopProxy> message_loop_proxy,
- PlatformFile file,
- GetFileInfoCallback* callback) {
- return Start(FROM_HERE, message_loop_proxy,
- new RelayGetFileInfoFromPlatformFile(file, callback));
-}
-
-// static
bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
diff --git a/base/file_util_proxy.h b/base/file_util_proxy.h
index 4181a26..b5e28c0 100644
--- a/base/file_util_proxy.h
+++ b/base/file_util_proxy.h
@@ -100,6 +100,15 @@ class FileUtilProxy {
const FilePath& file_path,
ReadDirectoryCallback* callback);
+ // Creates directory at given path. It's an error to create
+ // if |exclusive| is true and dir already exists.
+ static bool CreateDirectory(
+ scoped_refptr<MessageLoopProxy> message_loop_proxy,
+ const FilePath& file_path,
+ bool exclusive,
+ bool recursive,
+ StatusCallback* callback);
+
// Copies a file or a directory from |src_file_path| to |dest_file_path|
// Error cases:
// If destination file doesn't exist or destination's parent
@@ -113,13 +122,12 @@ class FileUtilProxy {
const FilePath& dest_file_path,
StatusCallback* callback);
- // Creates directory at given path. It's an error to create
- // if |exclusive| is true and dir already exists.
- static bool CreateDirectory(
+ // Moves a file or a directory from src_file_path to dest_file_path.
+ // Error cases are similar to Copy method's error cases.
+ static bool Move(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& file_path,
- bool exclusive,
- bool recursive,
+ const FilePath& src_file_path,
+ const FilePath& dest_file_path,
StatusCallback* callback);
// Deletes a file or a directory.
@@ -129,14 +137,6 @@ class FileUtilProxy {
bool recursive,
StatusCallback* callback);
- // Moves a file or a directory from src_file_path to dest_file_path.
- // Error cases are similar to Copy method's error cases.
- static bool Move(
- scoped_refptr<MessageLoopProxy> message_loop_proxy,
- const FilePath& src_file_path,
- const FilePath& dest_file_path,
- StatusCallback* callback);
-
// Deletes a directory and all of its contents.
static bool RecursiveDelete(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
diff --git a/base/global_descriptors_posix.cc b/base/global_descriptors_posix.cc
index 2fe953c..65e7955 100644
--- a/base/global_descriptors_posix.cc
+++ b/base/global_descriptors_posix.cc
@@ -11,10 +11,6 @@
namespace base {
-GlobalDescriptors::GlobalDescriptors() {}
-
-GlobalDescriptors::~GlobalDescriptors() {}
-
// static
GlobalDescriptors* GlobalDescriptors::GetInstance() {
typedef Singleton<base::GlobalDescriptors,
@@ -23,6 +19,14 @@ GlobalDescriptors* GlobalDescriptors::GetInstance() {
return GlobalDescriptorsSingleton::get();
}
+int GlobalDescriptors::Get(Key key) const {
+ const int ret = MaybeGet(key);
+
+ if (ret == -1)
+ LOG(FATAL) << "Unknown global descriptor: " << key;
+ return ret;
+}
+
int GlobalDescriptors::MaybeGet(Key key) const {
for (Mapping::const_iterator
i = descriptors_.begin(); i != descriptors_.end(); ++i) {
@@ -35,14 +39,6 @@ int GlobalDescriptors::MaybeGet(Key key) const {
return kBaseDescriptor + key;
}
-int GlobalDescriptors::Get(Key key) const {
- const int ret = MaybeGet(key);
-
- if (ret == -1)
- LOG(FATAL) << "Unknown global descriptor: " << key;
- return ret;
-}
-
void GlobalDescriptors::Set(Key key, int fd) {
for (Mapping::iterator
i = descriptors_.begin(); i != descriptors_.end(); ++i) {
@@ -55,4 +51,12 @@ void GlobalDescriptors::Set(Key key, int fd) {
descriptors_.push_back(std::make_pair(key, fd));
}
+void GlobalDescriptors::Reset(const Mapping& mapping) {
+ descriptors_ = mapping;
+}
+
+GlobalDescriptors::GlobalDescriptors() {}
+
+GlobalDescriptors::~GlobalDescriptors() {}
+
} // namespace base
diff --git a/base/global_descriptors_posix.h b/base/global_descriptors_posix.h
index 0cb5b4f..060bf0a 100644
--- a/base/global_descriptors_posix.h
+++ b/base/global_descriptors_posix.h
@@ -55,9 +55,7 @@ class GlobalDescriptors {
// Set the descriptor for the given key.
void Set(Key key, int fd);
- void Reset(const Mapping& mapping) {
- descriptors_ = mapping;
- }
+ void Reset(const Mapping& mapping);
private:
friend struct DefaultSingletonTraits<GlobalDescriptors>;
diff --git a/base/hmac_nss.cc b/base/hmac_nss.cc
index 2ca4f67..af0b3eb 100644
--- a/base/hmac_nss.cc
+++ b/base/hmac_nss.cc
@@ -36,6 +36,9 @@ HMAC::HMAC(HashAlgorithm hash_alg)
}
}
+HMAC::~HMAC() {
+}
+
bool HMAC::Init(const unsigned char *key, int key_length) {
base::EnsureNSSInit();
@@ -70,9 +73,6 @@ bool HMAC::Init(const unsigned char *key, int key_length) {
return true;
}
-HMAC::~HMAC() {
-}
-
bool HMAC::Sign(const std::string& data,
unsigned char* digest,
int digest_length) {
diff --git a/base/json/json_reader.cc b/base/json/json_reader.cc
index 391f58b3..dd5d088 100644
--- a/base/json/json_reader.cc
+++ b/base/json/json_reader.cc
@@ -81,6 +81,11 @@ const char* JSONReader::kUnsupportedEncoding =
const char* JSONReader::kUnquotedDictionaryKey =
"Dictionary keys must be quoted.";
+JSONReader::JSONReader()
+ : start_pos_(NULL), json_pos_(NULL), stack_depth_(0),
+ allow_trailing_comma_(false),
+ error_code_(JSON_NO_ERROR), error_line_(0), error_col_(0) {}
+
/* static */
Value* JSONReader::Read(const std::string& json,
bool allow_trailing_comma) {
@@ -106,16 +111,6 @@ Value* JSONReader::ReadAndReturnError(const std::string& json,
}
/* static */
-std::string JSONReader::FormatErrorMessage(int line, int column,
- const std::string& description) {
- if (line || column) {
- return StringPrintf("Line: %i, column: %i, %s",
- line, column, description.c_str());
- }
- return description;
-}
-
-/* static */
std::string JSONReader::ErrorCodeToString(JsonParseError error_code) {
switch (error_code) {
case JSON_NO_ERROR:
@@ -147,11 +142,6 @@ std::string JSONReader::GetErrorMessage() const {
ErrorCodeToString(error_code_));
}
-JSONReader::JSONReader()
- : start_pos_(NULL), json_pos_(NULL), stack_depth_(0),
- allow_trailing_comma_(false),
- error_code_(JSON_NO_ERROR), error_line_(0), error_col_(0) {}
-
Value* JSONReader::JsonToValue(const std::string& json, bool check_root,
bool allow_trailing_comma) {
// The input must be in UTF-8.
@@ -195,6 +185,16 @@ Value* JSONReader::JsonToValue(const std::string& json, bool check_root,
return NULL;
}
+/* static */
+std::string JSONReader::FormatErrorMessage(int line, int column,
+ const std::string& description) {
+ if (line || column) {
+ return StringPrintf("Line: %i, column: %i, %s",
+ line, column, description.c_str());
+ }
+ return description;
+}
+
Value* JSONReader::BuildValue(bool is_root) {
++stack_depth_;
if (stack_depth_ > kStackLimit) {
@@ -580,16 +580,6 @@ JSONReader::Token JSONReader::ParseToken() {
return token;
}
-bool JSONReader::NextStringMatch(const std::wstring& str) {
- for (size_t i = 0; i < str.length(); ++i) {
- if ('\0' == *json_pos_)
- return false;
- if (*(json_pos_ + i) != str[i])
- return false;
- }
- return true;
-}
-
void JSONReader::EatWhitespaceAndComments() {
while ('\0' != *json_pos_) {
switch (*json_pos_) {
@@ -645,6 +635,16 @@ bool JSONReader::EatComment() {
return true;
}
+bool JSONReader::NextStringMatch(const std::wstring& str) {
+ for (size_t i = 0; i < str.length(); ++i) {
+ if ('\0' == *json_pos_)
+ return false;
+ if (*(json_pos_ + i) != str[i])
+ return false;
+ }
+ return true;
+}
+
void JSONReader::SetErrorCode(JsonParseError error,
const wchar_t* error_pos) {
int line_number = 1;
diff --git a/base/json/json_reader.h b/base/json/json_reader.h
index 77c4e74..a6f0686 100644
--- a/base/json/json_reader.h
+++ b/base/json/json_reader.h
@@ -146,14 +146,12 @@ class JSONReader {
bool allow_trailing_comma);
private:
- static std::string FormatErrorMessage(int line, int column,
- const std::string& description);
-
- DISALLOW_COPY_AND_ASSIGN(JSONReader);
-
FRIEND_TEST(JSONReaderTest, Reading);
FRIEND_TEST(JSONReaderTest, ErrorMessages);
+ static std::string FormatErrorMessage(int line, int column,
+ const std::string& description);
+
// Recursively build Value. Returns NULL if we don't have a valid JSON
// string. If |is_root| is true, we verify that the root element is either
// an object or an array.
@@ -213,6 +211,8 @@ class JSONReader {
JsonParseError error_code_;
int error_line_;
int error_col_;
+
+ DISALLOW_COPY_AND_ASSIGN(JSONReader);
};
} // namespace base
diff --git a/base/logging.cc b/base/logging.cc
index cfb1065..5b6e2c1 100644
--- a/base/logging.cc
+++ b/base/logging.cc
@@ -530,71 +530,27 @@ LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
Init(file, line);
}
-LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
- : severity_(LOG_FATAL), file_(file), line_(line) {
+LogMessage::LogMessage(const char* file, int line)
+ : severity_(LOG_INFO), file_(file), line_(line) {
Init(file, line);
- stream_ << "Check failed: " << (*result.str_);
}
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
- const CheckOpString& result)
+LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
: severity_(severity), file_(file), line_(line) {
Init(file, line);
- stream_ << "Check failed: " << (*result.str_);
}
-LogMessage::LogMessage(const char* file, int line)
- : severity_(LOG_INFO), file_(file), line_(line) {
+LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
+ : severity_(LOG_FATAL), file_(file), line_(line) {
Init(file, line);
+ stream_ << "Check failed: " << (*result.str_);
}
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
+LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
+ const CheckOpString& result)
: severity_(severity), file_(file), line_(line) {
Init(file, line);
-}
-
-// writes the common header info to the stream
-void LogMessage::Init(const char* file, int line) {
- base::StringPiece filename(file);
- size_t last_slash_pos = filename.find_last_of("\\/");
- if (last_slash_pos != base::StringPiece::npos)
- filename.remove_prefix(last_slash_pos + 1);
-
- // TODO(darin): It might be nice if the columns were fixed width.
-
- stream_ << '[';
- if (log_process_id)
- stream_ << CurrentProcessId() << ':';
- if (log_thread_id)
- stream_ << CurrentThreadId() << ':';
- if (log_timestamp) {
- time_t t = time(NULL);
- struct tm local_time = {0};
-#if _MSC_VER >= 1400
- localtime_s(&local_time, &t);
-#else
- localtime_r(&t, &local_time);
-#endif
- struct tm* tm_time = &local_time;
- stream_ << std::setfill('0')
- << std::setw(2) << 1 + tm_time->tm_mon
- << std::setw(2) << tm_time->tm_mday
- << '/'
- << std::setw(2) << tm_time->tm_hour
- << std::setw(2) << tm_time->tm_min
- << std::setw(2) << tm_time->tm_sec
- << ':';
- }
- if (log_tickcount)
- stream_ << TickCount() << ':';
- if (severity_ >= 0)
- stream_ << log_severity_names[severity_];
- else
- stream_ << "VERBOSE" << -severity_;
-
- stream_ << ":" << filename << "(" << line << ")] ";
-
- message_start_ = stream_.tellp();
+ stream_ << "Check failed: " << (*result.str_);
}
LogMessage::~LogMessage() {
@@ -690,6 +646,50 @@ LogMessage::~LogMessage() {
}
}
+// writes the common header info to the stream
+void LogMessage::Init(const char* file, int line) {
+ base::StringPiece filename(file);
+ size_t last_slash_pos = filename.find_last_of("\\/");
+ if (last_slash_pos != base::StringPiece::npos)
+ filename.remove_prefix(last_slash_pos + 1);
+
+ // TODO(darin): It might be nice if the columns were fixed width.
+
+ stream_ << '[';
+ if (log_process_id)
+ stream_ << CurrentProcessId() << ':';
+ if (log_thread_id)
+ stream_ << CurrentThreadId() << ':';
+ if (log_timestamp) {
+ time_t t = time(NULL);
+ struct tm local_time = {0};
+#if _MSC_VER >= 1400
+ localtime_s(&local_time, &t);
+#else
+ localtime_r(&t, &local_time);
+#endif
+ struct tm* tm_time = &local_time;
+ stream_ << std::setfill('0')
+ << std::setw(2) << 1 + tm_time->tm_mon
+ << std::setw(2) << tm_time->tm_mday
+ << '/'
+ << std::setw(2) << tm_time->tm_hour
+ << std::setw(2) << tm_time->tm_min
+ << std::setw(2) << tm_time->tm_sec
+ << ':';
+ }
+ if (log_tickcount)
+ stream_ << TickCount() << ':';
+ if (severity_ >= 0)
+ stream_ << log_severity_names[severity_];
+ else
+ stream_ << "VERBOSE" << -severity_;
+
+ stream_ << ":" << filename << "(" << line << ")] ";
+
+ message_start_ = stream_.tellp();
+}
+
#if defined(OS_WIN)
// This has already been defined in the header, but defining it again as DWORD
// ensures that the type used in the header is equivalent to DWORD. If not,
diff --git a/base/message_loop_proxy_impl.cc b/base/message_loop_proxy_impl.cc
index 3b01fd6..b47c934 100644
--- a/base/message_loop_proxy_impl.cc
+++ b/base/message_loop_proxy_impl.cc
@@ -7,11 +7,6 @@
namespace base {
-MessageLoopProxyImpl::MessageLoopProxyImpl()
- : target_message_loop_(MessageLoop::current()) {
- target_message_loop_->AddDestructionObserver(this);
-}
-
MessageLoopProxyImpl::~MessageLoopProxyImpl() {
AutoLock lock(message_loop_lock_);
// If the target message loop still exists, the d'tor WILL execute on the
@@ -56,25 +51,10 @@ bool MessageLoopProxyImpl::BelongsToCurrentThread() {
(MessageLoop::current() == target_message_loop_));
}
-bool MessageLoopProxyImpl::PostTaskHelper(
- const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
- bool nestable) {
- bool ret = false;
- {
- AutoLock lock(message_loop_lock_);
- if (target_message_loop_) {
- if (nestable) {
- target_message_loop_->PostDelayedTask(from_here, task, delay_ms);
- } else {
- target_message_loop_->PostNonNestableDelayedTask(from_here, task,
- delay_ms);
- }
- ret = true;
- }
- }
- if (!ret)
- delete task;
- return ret;
+// MessageLoop::DestructionObserver implementation
+void MessageLoopProxyImpl::WillDestroyCurrentMessageLoop() {
+ AutoLock lock(message_loop_lock_);
+ target_message_loop_ = NULL;
}
void MessageLoopProxyImpl::OnDestruct() const {
@@ -96,10 +76,30 @@ void MessageLoopProxyImpl::OnDestruct() const {
delete this;
}
-// MessageLoop::DestructionObserver implementation
-void MessageLoopProxyImpl::WillDestroyCurrentMessageLoop() {
- AutoLock lock(message_loop_lock_);
- target_message_loop_ = NULL;
+MessageLoopProxyImpl::MessageLoopProxyImpl()
+ : target_message_loop_(MessageLoop::current()) {
+ target_message_loop_->AddDestructionObserver(this);
+}
+
+bool MessageLoopProxyImpl::PostTaskHelper(
+ const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
+ bool nestable) {
+ bool ret = false;
+ {
+ AutoLock lock(message_loop_lock_);
+ if (target_message_loop_) {
+ if (nestable) {
+ target_message_loop_->PostDelayedTask(from_here, task, delay_ms);
+ } else {
+ target_message_loop_->PostNonNestableDelayedTask(from_here, task,
+ delay_ms);
+ }
+ ret = true;
+ }
+ }
+ if (!ret)
+ delete task;
+ return ret;
}
scoped_refptr<MessageLoopProxy>
diff --git a/base/message_pump_glib.cc b/base/message_pump_glib.cc
index b9dcc46..721fedb6 100644
--- a/base/message_pump_glib.cc
+++ b/base/message_pump_glib.cc
@@ -303,16 +303,15 @@ void MessagePumpForUI::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
-MessagePumpForUI::Dispatcher* MessagePumpForUI::GetDispatcher() {
- return state_ ? state_->dispatcher : NULL;
-}
-
-void MessagePumpForUI::WillProcessEvent(GdkEvent* event) {
- FOR_EACH_OBSERVER(Observer, observers_, WillProcessEvent(event));
-}
-
-void MessagePumpForUI::DidProcessEvent(GdkEvent* event) {
- FOR_EACH_OBSERVER(Observer, observers_, DidProcessEvent(event));
+void MessagePumpForUI::DispatchEvents(GdkEvent* event) {
+ WillProcessEvent(event);
+ if (state_ && state_->dispatcher) { // state_ may be null during tests.
+ if (!state_->dispatcher->Dispatch(event))
+ state_->should_quit = true;
+ } else {
+ gtk_main_do_event(event);
+ }
+ DidProcessEvent(event);
}
void MessagePumpForUI::Run(Delegate* delegate) {
@@ -344,15 +343,16 @@ void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
ScheduleWork();
}
-void MessagePumpForUI::DispatchEvents(GdkEvent* event) {
- WillProcessEvent(event);
- if (state_ && state_->dispatcher) { // state_ may be null during tests.
- if (!state_->dispatcher->Dispatch(event))
- state_->should_quit = true;
- } else {
- gtk_main_do_event(event);
- }
- DidProcessEvent(event);
+MessagePumpForUI::Dispatcher* MessagePumpForUI::GetDispatcher() {
+ return state_ ? state_->dispatcher : NULL;
+}
+
+void MessagePumpForUI::WillProcessEvent(GdkEvent* event) {
+ FOR_EACH_OBSERVER(Observer, observers_, WillProcessEvent(event));
+}
+
+void MessagePumpForUI::DidProcessEvent(GdkEvent* event) {
+ FOR_EACH_OBSERVER(Observer, observers_, DidProcessEvent(event));
}
// static
diff --git a/base/message_pump_glib_x.cc b/base/message_pump_glib_x.cc
index 775e940..e72606d 100644
--- a/base/message_pump_glib_x.cc
+++ b/base/message_pump_glib_x.cc
@@ -82,6 +82,41 @@ MessagePumpGlibX::MessagePumpGlibX() : base::MessagePumpForUI(),
MessagePumpGlibX::~MessagePumpGlibX() {
}
+#if defined(HAVE_XINPUT2)
+void MessagePumpGlibX::SetupXInput2ForXWindow(Window xwindow) {
+ Display* xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
+
+ // Setup mask for mouse events.
+ unsigned char mask[(XI_LASTEVENT + 7)/8];
+ memset(mask, 0, sizeof(mask));
+
+ XISetMask(mask, XI_ButtonPress);
+ XISetMask(mask, XI_ButtonRelease);
+ XISetMask(mask, XI_Motion);
+
+ // It is necessary to select only for the master devices. XInput2 provides
+ // enough information to the event callback to decide which slave device
+ // triggered the event, thus decide whether the 'pointer event' is a 'mouse
+ // event' or a 'touch event'. So it is not necessary to select for the slave
+ // devices here.
+ XIEventMask evmasks[masters_.size()];
+ int count = 0;
+ for (std::set<int>::const_iterator iter = masters_.begin();
+ iter != masters_.end();
+ ++iter, ++count) {
+ evmasks[count].deviceid = *iter;
+ evmasks[count].mask_len = sizeof(mask);
+ evmasks[count].mask = mask;
+ }
+
+ XISelectEvents(xdisplay, xwindow, evmasks, masters_.size());
+
+ // TODO(sad): Setup masks for keyboard events.
+
+ XFlush(xdisplay);
+}
+#endif // HAVE_XINPUT2
+
bool MessagePumpGlibX::RunOnce(GMainContext* context, bool block) {
GdkDisplay* gdisp = gdk_display_get_default();
if (!gdisp)
@@ -166,6 +201,25 @@ bool MessagePumpGlibX::RunOnce(GMainContext* context, bool block) {
return retvalue;
}
+void MessagePumpGlibX::EventDispatcherX(GdkEvent* event, gpointer data) {
+ MessagePumpGlibX* pump_x = reinterpret_cast<MessagePumpGlibX*>(data);
+
+ if (!pump_x->gdksource_) {
+ pump_x->gdksource_ = g_main_current_source();
+ pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;
+ } else if (!pump_x->IsDispatchingEvent()) {
+ if (event->type != GDK_NOTHING &&
+ pump_x->capture_gdk_events_[event->type]) {
+ // TODO(sad): An X event is caught by the GDK handler. Put it back in the
+ // X queue so that we catch it in the next iteration. When done, the
+ // following DLOG statement will be removed.
+ DLOG(WARNING) << "GDK received an event it shouldn't have";
+ }
+ }
+
+ pump_x->DispatchEvents(event);
+}
+
void MessagePumpGlibX::InitializeEventsToCapture(void) {
// TODO(sad): Decide which events we want to capture and update the tables
// accordingly.
@@ -237,59 +291,6 @@ void MessagePumpGlibX::InitializeXInput2(void) {
// put it off for a later time.
// Note: It is not necessary to listen for XI_DeviceChanged events.
}
-
-void MessagePumpGlibX::SetupXInput2ForXWindow(Window xwindow) {
- Display* xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
-
- // Setup mask for mouse events.
- unsigned char mask[(XI_LASTEVENT + 7)/8];
- memset(mask, 0, sizeof(mask));
-
- XISetMask(mask, XI_ButtonPress);
- XISetMask(mask, XI_ButtonRelease);
- XISetMask(mask, XI_Motion);
-
- // It is necessary to select only for the master devices. XInput2 provides
- // enough information to the event callback to decide which slave device
- // triggered the event, thus decide whether the 'pointer event' is a 'mouse
- // event' or a 'touch event'. So it is not necessary to select for the slave
- // devices here.
- XIEventMask evmasks[masters_.size()];
- int count = 0;
- for (std::set<int>::const_iterator iter = masters_.begin();
- iter != masters_.end();
- ++iter, ++count) {
- evmasks[count].deviceid = *iter;
- evmasks[count].mask_len = sizeof(mask);
- evmasks[count].mask = mask;
- }
-
- XISelectEvents(xdisplay, xwindow, evmasks, masters_.size());
-
- // TODO(sad): Setup masks for keyboard events.
-
- XFlush(xdisplay);
-}
-
#endif // HAVE_XINPUT2
-void MessagePumpGlibX::EventDispatcherX(GdkEvent* event, gpointer data) {
- MessagePumpGlibX* pump_x = reinterpret_cast<MessagePumpGlibX*>(data);
-
- if (!pump_x->gdksource_) {
- pump_x->gdksource_ = g_main_current_source();
- pump_x->gdkdispatcher_ = pump_x->gdksource_->source_funcs->dispatch;
- } else if (!pump_x->IsDispatchingEvent()) {
- if (event->type != GDK_NOTHING &&
- pump_x->capture_gdk_events_[event->type]) {
- // TODO(sad): An X event is caught by the GDK handler. Put it back in the
- // X queue so that we catch it in the next iteration. When done, the
- // following DLOG statement will be removed.
- DLOG(WARNING) << "GDK received an event it shouldn't have";
- }
- }
-
- pump_x->DispatchEvents(event);
-}
-
} // namespace base
diff --git a/base/message_pump_libevent.cc b/base/message_pump_libevent.cc
index 1410f79..933d795 100644
--- a/base/message_pump_libevent.cc
+++ b/base/message_pump_libevent.cc
@@ -62,6 +62,19 @@ MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
}
}
+bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
+ event* e = ReleaseEvent();
+ if (e == NULL)
+ return true;
+
+ // event_del() is a no-op if the event isn't active.
+ int rv = event_del(e);
+ delete e;
+ pump_ = NULL;
+ watcher_ = NULL;
+ return (rv == 0);
+}
+
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
@@ -77,19 +90,6 @@ event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
return e;
}
-bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
- event* e = ReleaseEvent();
- if (e == NULL)
- return true;
-
- // event_del() is a no-op if the event isn't active.
- int rv = event_del(e);
- delete e;
- pump_ = NULL;
- watcher_ = NULL;
- return (rv == 0);
-}
-
void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanReadWithoutBlocking(
int fd, MessagePumpLibevent* pump) {
pump->WillProcessIOEvent();
@@ -104,20 +104,6 @@ void MessagePumpLibevent::FileDescriptorWatcher::OnFileCanWriteWithoutBlocking(
pump->DidProcessIOEvent();
}
-// Called if a byte is received on the wakeup pipe.
-void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
- base::MessagePumpLibevent* that =
- static_cast<base::MessagePumpLibevent*>(context);
- DCHECK(that->wakeup_pipe_out_ == socket);
-
- // Remove and discard the wakeup byte.
- char buf;
- int nread = HANDLE_EINTR(read(socket, &buf, 1));
- DCHECK_EQ(nread, 1);
- // Tell libevent to break out of inner loop.
- event_base_loopbreak(that->event_base_);
-}
-
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
@@ -128,33 +114,6 @@ MessagePumpLibevent::MessagePumpLibevent()
NOTREACHED();
}
-bool MessagePumpLibevent::Init() {
- int fds[2];
- if (pipe(fds)) {
- DLOG(ERROR) << "pipe() failed, errno: " << errno;
- return false;
- }
- if (SetNonBlocking(fds[0])) {
- DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
- return false;
- }
- if (SetNonBlocking(fds[1])) {
- DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
- return false;
- }
- wakeup_pipe_out_ = fds[0];
- wakeup_pipe_in_ = fds[1];
-
- wakeup_event_ = new event;
- event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
- OnWakeup, this);
- event_base_set(event_base_, wakeup_event_);
-
- if (event_add(wakeup_event_, 0))
- return false;
- return true;
-}
-
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
@@ -234,19 +193,12 @@ bool MessagePumpLibevent::WatchFileDescriptor(int fd,
return true;
}
-void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
- void* context) {
- FileDescriptorWatcher* controller =
- static_cast<FileDescriptorWatcher*>(context);
-
- MessagePumpLibevent* pump = controller->pump();
+void MessagePumpLibevent::AddIOObserver(IOObserver *obs) {
+ io_observers_.AddObserver(obs);
+}
- if (flags & EV_WRITE) {
- controller->OnFileCanWriteWithoutBlocking(fd, pump);
- }
- if (flags & EV_READ) {
- controller->OnFileCanReadWithoutBlocking(fd, pump);
- }
+void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) {
+ io_observers_.RemoveObserver(obs);
}
// Tell libevent to break out of inner loop.
@@ -334,14 +286,6 @@ void MessagePumpLibevent::ScheduleDelayedWork(
delayed_work_time_ = delayed_work_time;
}
-void MessagePumpLibevent::AddIOObserver(IOObserver *obs) {
- io_observers_.AddObserver(obs);
-}
-
-void MessagePumpLibevent::RemoveIOObserver(IOObserver *obs) {
- io_observers_.RemoveObserver(obs);
-}
-
void MessagePumpLibevent::WillProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, WillProcessIOEvent());
}
@@ -350,4 +294,62 @@ void MessagePumpLibevent::DidProcessIOEvent() {
FOR_EACH_OBSERVER(IOObserver, io_observers_, DidProcessIOEvent());
}
+bool MessagePumpLibevent::Init() {
+ int fds[2];
+ if (pipe(fds)) {
+ DLOG(ERROR) << "pipe() failed, errno: " << errno;
+ return false;
+ }
+ if (SetNonBlocking(fds[0])) {
+ DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
+ return false;
+ }
+ if (SetNonBlocking(fds[1])) {
+ DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
+ return false;
+ }
+ wakeup_pipe_out_ = fds[0];
+ wakeup_pipe_in_ = fds[1];
+
+ wakeup_event_ = new event;
+ event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
+ OnWakeup, this);
+ event_base_set(event_base_, wakeup_event_);
+
+ if (event_add(wakeup_event_, 0))
+ return false;
+ return true;
+}
+
+// static
+void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
+ void* context) {
+ FileDescriptorWatcher* controller =
+ static_cast<FileDescriptorWatcher*>(context);
+
+ MessagePumpLibevent* pump = controller->pump();
+
+ if (flags & EV_WRITE) {
+ controller->OnFileCanWriteWithoutBlocking(fd, pump);
+ }
+ if (flags & EV_READ) {
+ controller->OnFileCanReadWithoutBlocking(fd, pump);
+ }
+}
+
+// Called if a byte is received on the wakeup pipe.
+// static
+void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
+ base::MessagePumpLibevent* that =
+ static_cast<base::MessagePumpLibevent*>(context);
+ DCHECK(that->wakeup_pipe_out_ == socket);
+
+ // Remove and discard the wakeup byte.
+ char buf;
+ int nread = HANDLE_EINTR(read(socket, &buf, 1));
+ DCHECK_EQ(nread, 1);
+ // Tell libevent to break out of inner loop.
+ event_base_loopbreak(that->event_base_);
+}
+
} // namespace base
diff --git a/base/metrics/field_trial.cc b/base/metrics/field_trial.cc
index d29ed2d..654746c 100644
--- a/base/metrics/field_trial.cc
+++ b/base/metrics/field_trial.cc
@@ -117,6 +117,14 @@ void FieldTrialList::Register(FieldTrial* trial) {
}
// static
+FieldTrial* FieldTrialList::Find(const std::string& name) {
+ if (!global_)
+ return NULL;
+ AutoLock auto_lock(global_->lock_);
+ return global_->PreLockedFind(name);
+}
+
+// static
int FieldTrialList::FindValue(const std::string& name) {
FieldTrial* field_trial = Find(name);
if (field_trial)
@@ -133,21 +141,6 @@ std::string FieldTrialList::FindFullName(const std::string& name) {
}
// static
-FieldTrial* FieldTrialList::Find(const std::string& name) {
- if (!global_)
- return NULL;
- AutoLock auto_lock(global_->lock_);
- return global_->PreLockedFind(name);
-}
-
-FieldTrial* FieldTrialList::PreLockedFind(const std::string& name) {
- RegistrationList::iterator it = registered_.find(name);
- if (registered_.end() == it)
- return NULL;
- return it->second;
-}
-
-// static
void FieldTrialList::StatesToString(std::string* output) {
if (!global_)
return;
@@ -210,4 +203,11 @@ size_t FieldTrialList::GetFieldTrialCount() {
return global_->registered_.size();
}
+FieldTrial* FieldTrialList::PreLockedFind(const std::string& name) {
+ RegistrationList::iterator it = registered_.find(name);
+ if (registered_.end() == it)
+ return NULL;
+ return it->second;
+}
+
} // namespace base
diff --git a/base/metrics/stats_table.cc b/base/metrics/stats_table.cc
index 0e4cad9..bae2c96 100644
--- a/base/metrics/stats_table.cc
+++ b/base/metrics/stats_table.cc
@@ -278,6 +278,13 @@ StatsTable::~StatsTable() {
global_table_ = NULL;
}
+int StatsTable::GetSlot() const {
+ TLSData* data = GetTLSData();
+ if (!data)
+ return 0;
+ return data->slot;
+}
+
int StatsTable::RegisterThread(const std::string& name) {
int slot = 0;
if (!impl_)
@@ -311,15 +318,121 @@ int StatsTable::RegisterThread(const std::string& name) {
return slot;
}
-StatsTable::TLSData* StatsTable::GetTLSData() const {
- TLSData* data =
- static_cast<TLSData*>(tls_index_.Get());
- if (!data)
+int StatsTable::CountThreadsRegistered() const {
+ if (!impl_)
+ return 0;
+
+ // Loop through the shared memory and count the threads that are active.
+ // We intentionally do not lock the table during the operation.
+ int count = 0;
+ for (int index = 1; index <= impl_->max_threads(); index++) {
+ char* name = impl_->thread_name(index);
+ if (*name != '\0')
+ count++;
+ }
+ return count;
+}
+
+int StatsTable::FindCounter(const std::string& name) {
+ // Note: the API returns counters numbered from 1..N, although
+ // internally, the array is 0..N-1. This is so that we can return
+ // zero as "not found".
+ if (!impl_)
+ return 0;
+
+ // Create a scope for our auto-lock.
+ {
+ AutoLock scoped_lock(counters_lock_);
+
+ // Attempt to find the counter.
+ CountersMap::const_iterator iter;
+ iter = counters_.find(name);
+ if (iter != counters_.end())
+ return iter->second;
+ }
+
+ // Counter does not exist, so add it.
+ return AddCounter(name);
+}
+
+int* StatsTable::GetLocation(int counter_id, int slot_id) const {
+ if (!impl_)
+ return NULL;
+ if (slot_id > impl_->max_threads())
return NULL;
- DCHECK(data->slot);
- DCHECK_EQ(data->table, this);
- return data;
+ int* row = impl_->row(counter_id);
+ return &(row[slot_id-1]);
+}
+
+const char* StatsTable::GetRowName(int index) const {
+ if (!impl_)
+ return NULL;
+
+ return impl_->counter_name(index);
+}
+
+int StatsTable::GetRowValue(int index) const {
+ return GetRowValue(index, 0);
+}
+
+int StatsTable::GetRowValue(int index, int pid) const {
+ if (!impl_)
+ return 0;
+
+ int rv = 0;
+ int* row = impl_->row(index);
+ for (int slot_id = 0; slot_id < impl_->max_threads(); slot_id++) {
+ if (pid == 0 || *impl_->thread_pid(slot_id) == pid)
+ rv += row[slot_id];
+ }
+ return rv;
+}
+
+int StatsTable::GetCounterValue(const std::string& name) {
+ return GetCounterValue(name, 0);
+}
+
+int StatsTable::GetCounterValue(const std::string& name, int pid) {
+ if (!impl_)
+ return 0;
+
+ int row = FindCounter(name);
+ if (!row)
+ return 0;
+ return GetRowValue(row, pid);
+}
+
+int StatsTable::GetMaxCounters() const {
+ if (!impl_)
+ return 0;
+ return impl_->max_counters();
+}
+
+int StatsTable::GetMaxThreads() const {
+ if (!impl_)
+ return 0;
+ return impl_->max_threads();
+}
+
+int* StatsTable::FindLocation(const char* name) {
+ // Get the static StatsTable
+ StatsTable *table = StatsTable::current();
+ if (!table)
+ return NULL;
+
+ // Get the slot for this thread. Try to register
+ // it if none exists.
+ int slot = table->GetSlot();
+ if (!slot && !(slot = table->RegisterThread("")))
+ return NULL;
+
+ // Find the counter id for the counter.
+ std::string str_name(name);
+ int counter = table->FindCounter(str_name);
+
+ // Now we can find the location in the table.
+ return table->GetLocation(counter, slot);
}
void StatsTable::UnregisterThread() {
@@ -351,28 +464,6 @@ void StatsTable::SlotReturnFunction(void* data) {
}
}
-int StatsTable::CountThreadsRegistered() const {
- if (!impl_)
- return 0;
-
- // Loop through the shared memory and count the threads that are active.
- // We intentionally do not lock the table during the operation.
- int count = 0;
- for (int index = 1; index <= impl_->max_threads(); index++) {
- char* name = impl_->thread_name(index);
- if (*name != '\0')
- count++;
- }
- return count;
-}
-
-int StatsTable::GetSlot() const {
- TLSData* data = GetTLSData();
- if (!data)
- return 0;
- return data->slot;
-}
-
int StatsTable::FindEmptyThread() const {
// Note: the API returns slots numbered from 1..N, although
// internally, the array is 0..N-1. This is so that we can return
@@ -418,28 +509,6 @@ int StatsTable::FindCounterOrEmptyRow(const std::string& name) const {
return free_slot;
}
-int StatsTable::FindCounter(const std::string& name) {
- // Note: the API returns counters numbered from 1..N, although
- // internally, the array is 0..N-1. This is so that we can return
- // zero as "not found".
- if (!impl_)
- return 0;
-
- // Create a scope for our auto-lock.
- {
- AutoLock scoped_lock(counters_lock_);
-
- // Attempt to find the counter.
- CountersMap::const_iterator iter;
- iter = counters_.find(name);
- if (iter != counters_.end())
- return iter->second;
- }
-
- // Counter does not exist, so add it.
- return AddCounter(name);
-}
-
int StatsTable::AddCounter(const std::string& name) {
if (!impl_)
return 0;
@@ -470,84 +539,15 @@ int StatsTable::AddCounter(const std::string& name) {
return counter_id;
}
-int* StatsTable::GetLocation(int counter_id, int slot_id) const {
- if (!impl_)
- return NULL;
- if (slot_id > impl_->max_threads())
- return NULL;
-
- int* row = impl_->row(counter_id);
- return &(row[slot_id-1]);
-}
-
-const char* StatsTable::GetRowName(int index) const {
- if (!impl_)
- return NULL;
-
- return impl_->counter_name(index);
-}
-
-int StatsTable::GetRowValue(int index, int pid) const {
- if (!impl_)
- return 0;
-
- int rv = 0;
- int* row = impl_->row(index);
- for (int slot_id = 0; slot_id < impl_->max_threads(); slot_id++) {
- if (pid == 0 || *impl_->thread_pid(slot_id) == pid)
- rv += row[slot_id];
- }
- return rv;
-}
-
-int StatsTable::GetRowValue(int index) const {
- return GetRowValue(index, 0);
-}
-
-int StatsTable::GetCounterValue(const std::string& name, int pid) {
- if (!impl_)
- return 0;
-
- int row = FindCounter(name);
- if (!row)
- return 0;
- return GetRowValue(row, pid);
-}
-
-int StatsTable::GetCounterValue(const std::string& name) {
- return GetCounterValue(name, 0);
-}
-
-int StatsTable::GetMaxCounters() const {
- if (!impl_)
- return 0;
- return impl_->max_counters();
-}
-
-int StatsTable::GetMaxThreads() const {
- if (!impl_)
- return 0;
- return impl_->max_threads();
-}
-
-int* StatsTable::FindLocation(const char* name) {
- // Get the static StatsTable
- StatsTable *table = StatsTable::current();
- if (!table)
+StatsTable::TLSData* StatsTable::GetTLSData() const {
+ TLSData* data =
+ static_cast<TLSData*>(tls_index_.Get());
+ if (!data)
return NULL;
- // Get the slot for this thread. Try to register
- // it if none exists.
- int slot = table->GetSlot();
- if (!slot && !(slot = table->RegisterThread("")))
- return NULL;
-
- // Find the counter id for the counter.
- std::string str_name(name);
- int counter = table->FindCounter(str_name);
-
- // Now we can find the location in the table.
- return table->GetLocation(counter, slot);
+ DCHECK(data->slot);
+ DCHECK_EQ(data->table, this);
+ return data;
}
} // namespace base
diff --git a/base/ref_counted.cc b/base/ref_counted.cc
index 2f795ea..2d459ae 100644
--- a/base/ref_counted.cc
+++ b/base/ref_counted.cc
@@ -51,6 +51,11 @@ bool RefCountedBase::Release() const {
return false;
}
+bool RefCountedThreadSafeBase::HasOneRef() const {
+ return AtomicRefCountIsOne(
+ &const_cast<RefCountedThreadSafeBase*>(this)->ref_count_);
+}
+
RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) {
#ifndef NDEBUG
in_dtor_ = false;
@@ -85,11 +90,6 @@ bool RefCountedThreadSafeBase::Release() const {
return false;
}
-bool RefCountedThreadSafeBase::HasOneRef() const {
- return AtomicRefCountIsOne(
- &const_cast<RefCountedThreadSafeBase*>(this)->ref_count_);
-}
-
} // namespace subtle
} // namespace base
diff --git a/base/shared_memory_posix.cc b/base/shared_memory_posix.cc
index a44581e..843322b 100644
--- a/base/shared_memory_posix.cc
+++ b/base/shared_memory_posix.cc
@@ -196,24 +196,52 @@ bool SharedMemory::Open(const std::string& name, bool read_only) {
return PrepareMapFile(fp);
}
-// For the given shmem named |mem_name|, return a filename to mmap()
-// (and possibly create). Modifies |filename|. Return false on
-// error, or true of we are happy.
-bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
- FilePath* path) {
- // mem_name will be used for a filename; make sure it doesn't
- // contain anything which will confuse us.
- DCHECK(mem_name.find('/') == std::string::npos);
- DCHECK(mem_name.find('\0') == std::string::npos);
+bool SharedMemory::Map(uint32 bytes) {
+ if (mapped_file_ == -1)
+ return false;
- FilePath temp_dir;
- if (!file_util::GetShmemTempDir(&temp_dir))
+ memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
+ MAP_SHARED, mapped_file_, 0);
+
+ if (memory_)
+ mapped_size_ = bytes;
+
+ bool mmap_succeeded = (memory_ != (void*)-1);
+ DCHECK(mmap_succeeded) << "Call to mmap failed, errno=" << errno;
+ return mmap_succeeded;
+}
+
+bool SharedMemory::Unmap() {
+ if (memory_ == NULL)
return false;
- *path = temp_dir.AppendASCII("com.google.chrome.shmem." + mem_name);
+ munmap(memory_, mapped_size_);
+ memory_ = NULL;
+ mapped_size_ = 0;
return true;
}
+SharedMemoryHandle SharedMemory::handle() const {
+ return FileDescriptor(mapped_file_, false);
+}
+
+void SharedMemory::Close() {
+ Unmap();
+
+ if (mapped_file_ > 0) {
+ close(mapped_file_);
+ mapped_file_ = -1;
+ }
+}
+
+void SharedMemory::Lock() {
+ LockOrUnlockCommon(F_LOCK);
+}
+
+void SharedMemory::Unlock() {
+ LockOrUnlockCommon(F_ULOCK);
+}
+
bool SharedMemory::PrepareMapFile(FILE *fp) {
DCHECK(mapped_file_ == -1);
if (fp == NULL) return false;
@@ -243,55 +271,24 @@ bool SharedMemory::PrepareMapFile(FILE *fp) {
return true;
}
-bool SharedMemory::Map(uint32 bytes) {
- if (mapped_file_ == -1)
- return false;
-
- memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
- MAP_SHARED, mapped_file_, 0);
-
- if (memory_)
- mapped_size_ = bytes;
-
- bool mmap_succeeded = (memory_ != (void*)-1);
- DCHECK(mmap_succeeded) << "Call to mmap failed, errno=" << errno;
- return mmap_succeeded;
-}
+// For the given shmem named |mem_name|, return a filename to mmap()
+// (and possibly create). Modifies |filename|. Return false on
+// error, or true of we are happy.
+bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
+ FilePath* path) {
+ // mem_name will be used for a filename; make sure it doesn't
+ // contain anything which will confuse us.
+ DCHECK(mem_name.find('/') == std::string::npos);
+ DCHECK(mem_name.find('\0') == std::string::npos);
-bool SharedMemory::Unmap() {
- if (memory_ == NULL)
+ FilePath temp_dir;
+ if (!file_util::GetShmemTempDir(&temp_dir))
return false;
- munmap(memory_, mapped_size_);
- memory_ = NULL;
- mapped_size_ = 0;
- return true;
-}
-
-bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
- SharedMemoryHandle *new_handle,
- bool close_self) {
- const int new_fd = dup(mapped_file_);
- DCHECK(new_fd >= 0);
- new_handle->fd = new_fd;
- new_handle->auto_close = true;
-
- if (close_self)
- Close();
-
+ *path = temp_dir.AppendASCII("com.google.chrome.shmem." + mem_name);
return true;
}
-
-void SharedMemory::Close() {
- Unmap();
-
- if (mapped_file_ > 0) {
- close(mapped_file_);
- mapped_file_ = -1;
- }
-}
-
void SharedMemory::LockOrUnlockCommon(int function) {
DCHECK(mapped_file_ >= 0);
while (lockf(mapped_file_, function, 0) < 0) {
@@ -311,16 +308,18 @@ void SharedMemory::LockOrUnlockCommon(int function) {
}
}
-void SharedMemory::Lock() {
- LockOrUnlockCommon(F_LOCK);
-}
+bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
+ SharedMemoryHandle *new_handle,
+ bool close_self) {
+ const int new_fd = dup(mapped_file_);
+ DCHECK(new_fd >= 0);
+ new_handle->fd = new_fd;
+ new_handle->auto_close = true;
-void SharedMemory::Unlock() {
- LockOrUnlockCommon(F_ULOCK);
-}
+ if (close_self)
+ Close();
-SharedMemoryHandle SharedMemory::handle() const {
- return FileDescriptor(mapped_file_, false);
+ return true;
}
} // namespace base
diff --git a/base/synchronization/waitable_event_posix.cc b/base/synchronization/waitable_event_posix.cc
index 9cbc03a..ae03ead 100644
--- a/base/synchronization/waitable_event_posix.cc
+++ b/base/synchronization/waitable_event_posix.cc
@@ -149,6 +149,10 @@ class SyncWaiter : public WaitableEvent::Waiter {
base::ConditionVariable cv_;
};
+bool WaitableEvent::Wait() {
+ return TimedWait(TimeDelta::FromSeconds(-1));
+}
+
bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
const Time end_time(Time::Now() + max_time);
const bool finite_time = max_time.ToInternalValue() >= 0;
@@ -204,13 +208,6 @@ bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
}
}
-bool WaitableEvent::Wait() {
- return TimedWait(TimeDelta::FromSeconds(-1));
-}
-
-// -----------------------------------------------------------------------------
-
-
// -----------------------------------------------------------------------------
// Synchronous waiting on multiple objects.
diff --git a/base/threading/simple_thread.cc b/base/threading/simple_thread.cc
index 2b030f6..4441477 100644
--- a/base/threading/simple_thread.cc
+++ b/base/threading/simple_thread.cc
@@ -10,6 +10,22 @@
namespace base {
+SimpleThread::SimpleThread(const std::string& name_prefix)
+ : name_prefix_(name_prefix), name_(name_prefix),
+ thread_(), event_(true, false), tid_(0), joined_(false) {
+}
+
+SimpleThread::SimpleThread(const std::string& name_prefix,
+ const Options& options)
+ : name_prefix_(name_prefix), name_(name_prefix), options_(options),
+ thread_(), event_(true, false), tid_(0), joined_(false) {
+}
+
+SimpleThread::~SimpleThread() {
+ DCHECK(HasBeenStarted()) << "SimpleThread was never started.";
+ DCHECK(HasBeenJoined()) << "SimpleThread destroyed without being Join()ed.";
+}
+
void SimpleThread::Start() {
DCHECK(!HasBeenStarted()) << "Tried to Start a thread multiple times.";
bool success = PlatformThread::Create(options_.stack_size(), this, &thread_);
@@ -37,22 +53,6 @@ void SimpleThread::ThreadMain() {
Run();
}
-SimpleThread::SimpleThread(const std::string& name_prefix)
- : name_prefix_(name_prefix), name_(name_prefix),
- thread_(), event_(true, false), tid_(0), joined_(false) {
-}
-
-SimpleThread::SimpleThread(const std::string& name_prefix,
- const Options& options)
- : name_prefix_(name_prefix), name_(name_prefix), options_(options),
- thread_(), event_(true, false), tid_(0), joined_(false) {
-}
-
-SimpleThread::~SimpleThread() {
- DCHECK(HasBeenStarted()) << "SimpleThread was never started.";
- DCHECK(HasBeenJoined()) << "SimpleThread destroyed without being Join()ed.";
-}
-
DelegateSimpleThread::DelegateSimpleThread(Delegate* delegate,
const std::string& name_prefix)
: SimpleThread(name_prefix),
diff --git a/base/threading/thread.cc b/base/threading/thread.cc
index 09f8847..c0fb537 100644
--- a/base/threading/thread.cc
+++ b/base/threading/thread.cc
@@ -11,6 +11,17 @@
namespace base {
+namespace {
+
+// We use this thread-local variable to record whether or not a thread exited
+// because its Stop method was called. This allows us to catch cases where
+// MessageLoop::Quit() is called directly, which is unexpected when using a
+// Thread to setup and run a MessageLoop.
+base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool(
+ base::LINKER_INITIALIZED);
+
+} // namespace
+
// This task is used to trigger the message loop to exit.
class ThreadQuitTask : public Task {
public:
@@ -48,29 +59,6 @@ Thread::~Thread() {
Stop();
}
-namespace {
-
-// We use this thread-local variable to record whether or not a thread exited
-// because its Stop method was called. This allows us to catch cases where
-// MessageLoop::Quit() is called directly, which is unexpected when using a
-// Thread to setup and run a MessageLoop.
-base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool(
- base::LINKER_INITIALIZED);
-
-} // namespace
-
-void Thread::SetThreadWasQuitProperly(bool flag) {
- lazy_tls_bool.Pointer()->Set(flag);
-}
-
-bool Thread::GetThreadWasQuitProperly() {
- bool quit_properly = true;
-#ifndef NDEBUG
- quit_properly = lazy_tls_bool.Pointer()->Get();
-#endif
- return quit_properly;
-}
-
bool Thread::Start() {
return StartWithOptions(Options());
}
@@ -140,6 +128,18 @@ void Thread::Run(MessageLoop* message_loop) {
message_loop->Run();
}
+void Thread::SetThreadWasQuitProperly(bool flag) {
+ lazy_tls_bool.Pointer()->Set(flag);
+}
+
+bool Thread::GetThreadWasQuitProperly() {
+ bool quit_properly = true;
+#ifndef NDEBUG
+ quit_properly = lazy_tls_bool.Pointer()->Get();
+#endif
+ return quit_properly;
+}
+
void Thread::ThreadMain() {
{
// The message loop for this thread.
diff --git a/base/time.h b/base/time.h
index e1fbf96..ed4e772 100644
--- a/base/time.h
+++ b/base/time.h
@@ -411,10 +411,6 @@ class Time {
int64 us_;
};
-inline Time TimeDelta::operator+(Time t) const {
- return Time(t.us_ + delta_);
-}
-
// Inline the TimeDelta factory methods, for fast TimeDelta construction.
// static
@@ -447,6 +443,10 @@ inline TimeDelta TimeDelta::FromMicroseconds(int64 us) {
return TimeDelta(us);
}
+inline Time TimeDelta::operator+(Time t) const {
+ return Time(t.us_ + delta_);
+}
+
// TimeTicks ------------------------------------------------------------------
class TimeTicks {
diff --git a/base/time_posix.cc b/base/time_posix.cc
index 2490315..c2750b8 100644
--- a/base/time_posix.cc
+++ b/base/time_posix.cc
@@ -14,6 +14,19 @@
namespace base {
+struct timespec TimeDelta::ToTimeSpec() const {
+ int64 microseconds = InMicroseconds();
+ time_t seconds = 0;
+ if (microseconds >= Time::kMicrosecondsPerSecond) {
+ seconds = InSeconds();
+ microseconds -= seconds * Time::kMicrosecondsPerSecond;
+ }
+ struct timespec result =
+ {seconds,
+ microseconds * Time::kNanosecondsPerMicrosecond};
+ return result;
+}
+
#if !defined(OS_MACOSX)
// The Time routines in this file use standard POSIX routines, or almost-
// standard routines in the case of timegm. We need to use a Mach-specific
@@ -60,6 +73,30 @@ Time Time::NowFromSystemTime() {
return Now();
}
+void Time::Explode(bool is_local, Exploded* exploded) const {
+ // Time stores times with microsecond resolution, but Exploded only carries
+ // millisecond resolution, so begin by being lossy. Adjust from Windows
+ // epoch (1601) to Unix epoch (1970);
+ int64 milliseconds = (us_ - kWindowsEpochDeltaMicroseconds) /
+ kMicrosecondsPerMillisecond;
+ time_t seconds = milliseconds / kMillisecondsPerSecond;
+
+ struct tm timestruct;
+ if (is_local)
+ localtime_r(&seconds, &timestruct);
+ else
+ gmtime_r(&seconds, &timestruct);
+
+ exploded->year = timestruct.tm_year + 1900;
+ exploded->month = timestruct.tm_mon + 1;
+ exploded->day_of_week = timestruct.tm_wday;
+ exploded->day_of_month = timestruct.tm_mday;
+ exploded->hour = timestruct.tm_hour;
+ exploded->minute = timestruct.tm_min;
+ exploded->second = timestruct.tm_sec;
+ exploded->millisecond = milliseconds % kMillisecondsPerSecond;
+}
+
// static
Time Time::FromExploded(bool is_local, const Exploded& exploded) {
struct tm timestruct;
@@ -119,30 +156,6 @@ Time Time::FromExploded(bool is_local, const Exploded& exploded) {
kWindowsEpochDeltaMicroseconds);
}
-void Time::Explode(bool is_local, Exploded* exploded) const {
- // Time stores times with microsecond resolution, but Exploded only carries
- // millisecond resolution, so begin by being lossy. Adjust from Windows
- // epoch (1601) to Unix epoch (1970);
- int64 milliseconds = (us_ - kWindowsEpochDeltaMicroseconds) /
- kMicrosecondsPerMillisecond;
- time_t seconds = milliseconds / kMillisecondsPerSecond;
-
- struct tm timestruct;
- if (is_local)
- localtime_r(&seconds, &timestruct);
- else
- gmtime_r(&seconds, &timestruct);
-
- exploded->year = timestruct.tm_year + 1900;
- exploded->month = timestruct.tm_mon + 1;
- exploded->day_of_week = timestruct.tm_wday;
- exploded->day_of_month = timestruct.tm_mday;
- exploded->hour = timestruct.tm_hour;
- exploded->minute = timestruct.tm_min;
- exploded->second = timestruct.tm_sec;
- exploded->millisecond = milliseconds % kMillisecondsPerSecond;
-}
-
// TimeTicks ------------------------------------------------------------------
// FreeBSD 6 has CLOCK_MONOLITHIC but defines _POSIX_MONOTONIC_CLOCK to -1.
#if (defined(OS_POSIX) && \
@@ -177,19 +190,6 @@ TimeTicks TimeTicks::HighResNow() {
#endif // !OS_MACOSX
-struct timespec TimeDelta::ToTimeSpec() const {
- int64 microseconds = InMicroseconds();
- time_t seconds = 0;
- if (microseconds >= Time::kMicrosecondsPerSecond) {
- seconds = InSeconds();
- microseconds -= seconds * Time::kMicrosecondsPerSecond;
- }
- struct timespec result =
- {seconds,
- microseconds * Time::kNanosecondsPerMicrosecond};
- return result;
-}
-
struct timeval Time::ToTimeVal() const {
struct timeval result;
int64 us = us_ - kTimeTToMicrosecondsOffset;
diff --git a/base/tracked_objects.cc b/base/tracked_objects.cc
index 3646000..d62aa59 100644
--- a/base/tracked_objects.cc
+++ b/base/tracked_objects.cc
@@ -743,11 +743,6 @@ void Comparator::Clear() {
selector_ = NIL;
}
-void Comparator::Sort(DataCollector::Collection* collection) const {
- std::sort(collection->begin(), collection->end(), *this);
-}
-
-
bool Comparator::operator()(const Snapshot& left,
const Snapshot& right) const {
switch (selector_) {
@@ -816,6 +811,10 @@ bool Comparator::operator()(const Snapshot& left,
return false;
}
+void Comparator::Sort(DataCollector::Collection* collection) const {
+ std::sort(collection->begin(), collection->end(), *this);
+}
+
bool Comparator::Equivalent(const Snapshot& left,
const Snapshot& right) const {
switch (selector_) {
diff --git a/base/vlog.cc b/base/vlog.cc
index 8903f39..41bf2a5 100644
--- a/base/vlog.cc
+++ b/base/vlog.cc
@@ -13,6 +13,18 @@ namespace logging {
const int VlogInfo::kDefaultVlogLevel = 0;
+struct VlogInfo::VmodulePattern {
+ enum MatchTarget { MATCH_MODULE, MATCH_FILE };
+
+ explicit VmodulePattern(const std::string& pattern);
+
+ VmodulePattern();
+
+ std::string pattern;
+ int vlog_level;
+ MatchTarget match_target;
+};
+
VlogInfo::VmodulePattern::VmodulePattern(const std::string& pattern)
: pattern(pattern),
vlog_level(VlogInfo::kDefaultVlogLevel),
@@ -64,15 +76,6 @@ VlogInfo::VlogInfo(const std::string& v_switch,
VlogInfo::~VlogInfo() {}
-void VlogInfo::SetMaxVlogLevel(int level) {
- // Log severity is the negative verbosity.
- *min_log_level_ = -level;
-}
-
-int VlogInfo::GetMaxVlogLevel() const {
- return -*min_log_level_;
-}
-
namespace {
// Given a path, returns the basename with the extension chopped off
@@ -109,6 +112,15 @@ int VlogInfo::GetVlogLevel(const base::StringPiece& file) const {
return GetMaxVlogLevel();
}
+void VlogInfo::SetMaxVlogLevel(int level) {
+ // Log severity is the negative verbosity.
+ *min_log_level_ = -level;
+}
+
+int VlogInfo::GetMaxVlogLevel() const {
+ return -*min_log_level_;
+}
+
bool MatchVlogPattern(const base::StringPiece& string,
const base::StringPiece& vlog_pattern) {
base::StringPiece p(vlog_pattern);
diff --git a/base/vlog.h b/base/vlog.h
index 529afd5..54e777f 100644
--- a/base/vlog.h
+++ b/base/vlog.h
@@ -18,6 +18,8 @@ namespace logging {
// A helper class containing all the settings for vlogging.
class VlogInfo {
public:
+ static const int kDefaultVlogLevel;
+
// |v_switch| gives the default maximal active V-logging level; 0 is
// the default. Normally positive values are used for V-logging
// levels.
@@ -45,26 +47,13 @@ class VlogInfo {
// __FILE__).
int GetVlogLevel(const base::StringPiece& file) const;
- static const int kDefaultVlogLevel;
-
private:
void SetMaxVlogLevel(int level);
int GetMaxVlogLevel() const;
// VmodulePattern holds all the information for each pattern parsed
// from |vmodule_switch|.
- struct VmodulePattern {
- enum MatchTarget { MATCH_MODULE, MATCH_FILE };
-
- explicit VmodulePattern(const std::string& pattern);
-
- VmodulePattern();
-
- std::string pattern;
- int vlog_level;
- MatchTarget match_target;
- };
-
+ struct VmodulePattern;
std::vector<VmodulePattern> vmodule_levels_;
int* min_log_level_;