1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/trace_event/heap_profiler_allocation_context.h"
6
7 #include <cstring>
8
9 #include "base/hash.h"
10 #include "base/macros.h"
11
12 namespace base {
13 namespace trace_event {
14
15 // Constructor that does not initialize members.
AllocationContext()16 AllocationContext::AllocationContext() {}
17
18 // static
Empty()19 AllocationContext AllocationContext::Empty() {
20 AllocationContext ctx;
21
22 for (size_t i = 0; i < arraysize(ctx.backtrace.frames); i++)
23 ctx.backtrace.frames[i] = nullptr;
24
25 ctx.type_name = nullptr;
26
27 return ctx;
28 }
29
operator ==(const Backtrace & lhs,const Backtrace & rhs)30 bool operator==(const Backtrace& lhs, const Backtrace& rhs) {
31 // Pointer equality of the stack frames is assumed, so instead of doing a deep
32 // string comparison on all of the frames, a |memcmp| suffices.
33 return std::memcmp(lhs.frames, rhs.frames, sizeof(lhs.frames)) == 0;
34 }
35
operator ==(const AllocationContext & lhs,const AllocationContext & rhs)36 bool operator==(const AllocationContext& lhs, const AllocationContext& rhs) {
37 return (lhs.backtrace == rhs.backtrace) && (lhs.type_name == rhs.type_name);
38 }
39
40 } // namespace trace_event
41 } // namespace base
42
43 namespace BASE_HASH_NAMESPACE {
44 using base::trace_event::AllocationContext;
45 using base::trace_event::Backtrace;
46
operator ()(const Backtrace & backtrace) const47 size_t hash<Backtrace>::operator()(const Backtrace& backtrace) const {
48 return base::Hash(
49 std::string(reinterpret_cast<const char*>(backtrace.frames),
50 sizeof(backtrace.frames)));
51 }
52
operator ()(const AllocationContext & ctx) const53 size_t hash<AllocationContext>::operator()(const AllocationContext& ctx) const {
54 size_t backtrace_hash = hash<Backtrace>()(ctx.backtrace);
55
56 // Multiplicative hash from [Knuth 1998]. Works best if |size_t| is 32 bits,
57 // because the magic number is a prime very close to 2^32 / golden ratio, but
58 // will still redistribute keys bijectively on 64-bit architectures because
59 // the magic number is coprime to 2^64.
60 size_t type_hash = reinterpret_cast<size_t>(ctx.type_name) * 2654435761;
61
62 // Multiply one side to break the commutativity of +. Multiplication with a
63 // number coprime to |numeric_limits<size_t>::max() + 1| is bijective so
64 // randomness is preserved.
65 return (backtrace_hash * 3) + type_hash;
66 }
67
68 } // BASE_HASH_NAMESPACE
69