Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Dockerfile.Packages
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ RUN npm i --nodedir="$NODE_DIR" unix-dgram@${UNIX_DGRAM_VERSION}
# GitHub to build the native binding against our pointer-compressed V8.
RUN npm i @datadog/pprof@${PPROF_VERSION} --ignore-scripts
RUN git clone --branch v${PPROF_VERSION} --depth 1 https://github.com/DataDog/pprof-nodejs.git /usr/src/pprof-source
# Stock pprof reads the AsyncContextFrame map in its signal handler assuming 8-byte tagged fields,
# so sample labels segfault on our pointer-compressed V8 (DataDog/pprof-nodejs#428).
COPY asana-pprof-pointer-compression.patch /usr/src/
WORKDIR /usr/src/pprof-source
RUN git apply /usr/src/asana-pprof-pointer-compression.patch
RUN npm install --unsafe-perm --ignore-scripts
RUN npm install --unsafe-perm --no-save node-gyp
RUN node_modules/.bin/node-gyp rebuild --jobs=max --nodedir="$NODE_DIR"
Expand Down Expand Up @@ -98,6 +102,8 @@ RUN node -e " \
assert(Array.isArray(pprof.time.stop().sample)); \
console.log('All native packages load'); \
"
COPY asana-pprof-cped-smoke-test.js .
RUN node asana-pprof-cped-smoke-test.js 5 && node --stress-compaction asana-pprof-cped-smoke-test.js 5

RUN ls node_modules

Expand Down
89 changes: 89 additions & 0 deletions asana-pprof-cped-smoke-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Checks @datadog/pprof's AsyncContextFrame (CPED) sample labels on this Node build. Stock pprof
// segfaults here on pointer-compressed V8, and a wrong layout in the patch would segfault or
// mislabel, so this fails the image build instead of LunaServer.
// Usage: node [--stress-compaction] asana-pprof-cped-smoke-test.js [soak seconds]
const assert = require('assert');
const { AsyncLocalStorage } = require('async_hooks');
const pprof = require('@datadog/pprof');

const soakSeconds = Number(process.argv[2] ?? 5);

function burn(ms) {
const end = performance.now() + ms;
let junk = [];
while (performance.now() < end) {
junk.push({ a: Math.random(), b: new Map([[junk.length, 'x'.repeat(16)]]) });
if (junk.length > 2000) {
junk = [];
}
}
}

async function interleavedLabels() {
pprof.time.start({ intervalMicros: 500, withContexts: true, useCPED: true, lineNumbers: false });
const worker = async (steps, msPerStep) => {
for (let i = 0; i < steps; i++) {
await new Promise(resolve => setImmediate(resolve));
burn(msPerStep);
}
};
await Promise.all([
pprof.time.runWithContext({ label: 'A' }, async () => await worker(60, 3)),
pprof.time.runWithContext({ label: 'B' }, async () => await worker(60, 1)),
]);
const counts = { A: 0, B: 0 };
pprof.time.stop(false, ({ context }) => {
const label = context?.context?.label;
if (label in counts) {
counts[label]++;
}
return {};
});
console.log('labeled samples', JSON.stringify(counts));
assert(counts.B > 20, `Too few samples labeled B: ${JSON.stringify(counts)}`);
const ratio = counts.A / counts.B;
assert(ratio > 1.5 && ratio < 6, `A should get about 3x B's samples: ${JSON.stringify(counts)}`);
}

// Many concurrent labels, a growing and rehashing AsyncContextFrame map, allocation churn and
// profile restarts. Passing means no crash; run under --stress-compaction to move objects.
async function soak() {
const stores = Array.from({ length: 40 }, () => new AsyncLocalStorage());
pprof.time.start({ intervalMicros: 100, withContexts: true, useCPED: true });
let labeled = 0;
const collect = () =>
pprof.time.stop(true, ({ context }) => {
if (context?.context?.id !== undefined) {
labeled++;
}
return {};
});
const restarter = setInterval(collect, 1000);
const deadline = performance.now() + soakSeconds * 1000;
const task = async id => {
for (let depth = 0; performance.now() < deadline; depth++) {
await stores[depth % stores.length].run({ depth }, async () => {
await new Promise(resolve => setImmediate(resolve));
burn(0.5);
});
}
};
await Promise.all(
Array.from({ length: 30 }, (_, id) => pprof.time.runWithContext({ id }, async () => await task(id)))
);
clearInterval(restarter);
collect();
pprof.time.stop(false);
console.log('soak labeled samples', labeled);
assert(labeled > 0, 'The soak recorded no labeled samples');
}

(async () => {
console.log(`node ${process.version} pointer compression ${process.config.variables.v8_enable_pointer_compression}`);
await interleavedLabels();
await soak();
console.log('pprof CPED labels work');
})().catch(error => {
console.error(error);
process.exit(1);
});
260 changes: 260 additions & 0 deletions asana-pprof-pointer-compression.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,260 @@
diff --git a/bindings/map-get.cc b/bindings/map-get.cc
index 7d3c3f5..a1bb6b8 100644
--- a/bindings/map-get.cc
+++ b/bindings/map-get.cc
@@ -37,10 +37,23 @@

#include <cstdint>

+#include <v8.h>
+
namespace dd {

using Address = uintptr_t;

+// With pointer compression, tagged fields inside heap objects are 32-bit offsets from a 4 GB
+// aligned cage base, and Smis are 31-bit values in the low 32 bits. Handles, roots and the
+// isolate's CPED slot still hold full pointers.
+#ifdef V8_COMPRESS_POINTERS
+using Tagged = uint32_t;
+#else
+using Tagged = Address;
+#endif
+static_assert(sizeof(Tagged) == v8::internal::kApiTaggedSize,
+ "Tagged field width must match the V8 headers");
+
#ifndef _WIN32
// ============================================================================
// Constants from V8 internals
@@ -65,15 +78,42 @@ inline Address UntagPointer(Address tagged) {
// only ones we support.
static_assert(sizeof(void*) == 8, "Only 64-bit platforms supported");

-inline bool IsSmi(Address value) {
+#ifdef V8_COMPRESS_POINTERS
+inline bool IsSmi(Tagged value) {
+ return (value & 1) == 0;
+}
+
+inline int SmiToInt(Tagged smi) {
+ return static_cast<int32_t>(smi) >> 1;
+}
+
+// Rebuilds a full pointer to a field's target from any full pointer into the same cage.
+inline Address Decompress(Address full_pointer_in_cage, Tagged value) {
+ return (full_pointer_in_cage & ~Address{0xFFFFFFFF}) | value;
+}
+
+inline Tagged Compress(Address full_pointer) {
+ return static_cast<Tagged>(full_pointer);
+}
+#else
+inline bool IsSmi(Tagged value) {
// More rigorous than (value & 1) but valid on 64-bit platforms only.
return (value & 0xFFFFFFFF) == 0;
}

-inline int SmiToInt(Address smi) {
+inline int SmiToInt(Tagged smi) {
return static_cast<int>(static_cast<intptr_t>(smi) >> 32);
}

+inline Address Decompress(Address, Tagged value) {
+ return value;
+}
+
+inline Tagged Compress(Address full_pointer) {
+ return full_pointer;
+}
+#endif
+
// ============================================================================
// V8 Hashtable Structure Definitions
// ============================================================================
@@ -81,23 +121,23 @@ inline int SmiToInt(Address smi) {
// HeapObject layout - base for all V8 heap objects
// From v8/src/objects/heap-object.h
struct HeapObjectLayout {
- Address classMap_; // Tagged pointer to the class map
+ Tagged classMap_; // Tagged pointer to the class map
};

// JavaScript Map object
struct JSMapLayout {
HeapObjectLayout header_; // Map is a HeapObject
- Address properties_or_hash_; // not used by us
- Address elements_; // not used by us
+ Tagged properties_or_hash_; // not used by us
+ Tagged elements_; // not used by us
// Tagged pointer to a [Small]OrderedHashMapLayout
- Address table_;
+ Tagged table_;
};

// V8 FixedArray: length_ is a Smi, followed by that many element slots
struct FixedArrayLayout {
HeapObjectLayout header_; // FixedArray is a HeapObject
- Address length_;
- Address elements_[0];
+ Tagged length_;
+ Tagged elements_[0];
};

// NOTE: both OrderedHashMap and SmallOrderedHashMap have compatible method
@@ -110,9 +150,9 @@ struct OrderedHashMapLayout {
FixedArrayLayout fixedArray_; // OrderedHashMap is a FixedArray
// The first 3 address slots in the FixedArray that is a Hashtable are the
// number of elements, deleted elements, and buckets. Each one is a Smi.
- Address number_of_elements_;
- Address number_of_deleted_elements_;
- Address number_of_buckets_;
+ Tagged number_of_elements_;
+ Tagged number_of_deleted_elements_;
+ Tagged number_of_buckets_;
// First number_of_buckets_ entries in head_and_data_table_ is the head table:
// each entry is an index of the first entry (head of the linked list of
// entries) in the data table for that bucket. This is followed by the data
@@ -125,7 +165,7 @@ struct OrderedHashMapLayout {
// expressed in number of entries from the start of the data table, so to
// convert it into a head_and_data_table_ you need to add number_of_buckets_
// (length of the head table) and then 3 * index.
- Address head_and_data_table_[0]; // Variable: [head_table][data_table]
+ Tagged head_and_data_table_[0]; // Variable: [head_table][data_table]

// Constants for entry structure
static constexpr int kEntrySize = 3;
@@ -144,7 +184,7 @@ struct OrderedHashMapLayout {

// Get first entry index for a bucket
int GetFirstEntry(int bucket) const {
- Address entry_smi = head_and_data_table_[bucket];
+ Tagged entry_smi = head_and_data_table_[bucket];
return IsSmi(entry_smi) ? SmiToInt(entry_smi) : kNotFound;
}

@@ -154,13 +194,13 @@ struct OrderedHashMapLayout {
}

// Get key at entry index
- Address GetKey(int entry) const {
+ Tagged GetKey(int entry) const {
int index = EntryToIndex(entry);
return head_and_data_table_[index + kKeyOffset];
}

// Get value at entry index
- Address GetValue(int entry) const {
+ Tagged GetValue(int entry) const {
int index = EntryToIndex(entry);
return head_and_data_table_[index + kValueOffset];
}
@@ -168,7 +208,7 @@ struct OrderedHashMapLayout {
// Get next entry in chain
int GetNextChainEntry(int entry) const {
int index = EntryToIndex(entry);
- Address chain_smi = head_and_data_table_[index + kChainOffset];
+ Tagged chain_smi = head_and_data_table_[index + kChainOffset];
return IsSmi(chain_smi) ? SmiToInt(chain_smi) : kNotFound;
}
};
@@ -194,12 +234,12 @@ struct SmallOrderedHashMapLayout {
uint8_t number_of_elements_;
uint8_t number_of_deleted_elements_;
uint8_t number_of_buckets_;
- uint8_t padding_[5]; // 5 bytes on 64-bit
+ uint8_t padding_[sizeof(Tagged) - 3]; // to tagged alignment
// Variable length:
// - Address data_table_[capacity * kEntrySize] // Keys and values
// - uint8_t hash_table_[number_of_buckets_] // Bucket -> first entry
// - uint8_t chain_table_[capacity] // Entry -> next entry
- Address data_table_[0];
+ Tagged data_table_[0];

// Constants for entry structure
static constexpr int kEntrySize = 2;
@@ -226,12 +266,12 @@ struct SmallOrderedHashMapLayout {
}

// Get key at entry index
- Address GetKey(int entry) const {
+ Tagged GetKey(int entry) const {
return data_table_[entry * kEntrySize + kKeyOffset];
}

// Get value at entry index
- Address GetValue(int entry) const {
+ Tagged GetValue(int entry) const {
return data_table_[entry * kEntrySize + kValueOffset];
}

@@ -256,7 +296,7 @@ struct SmallOrderedHashMapLayout {
// Template parameter LayoutT should be either OrderedHashMapLayout or
// SmallOrderedHashMapLayout
template <typename LayoutT>
-int FindEntryByHash(const LayoutT* layout, int hash, Address key_to_find) {
+int FindEntryByHash(const LayoutT* layout, int hash, Tagged key_to_find) {
const int entry_count = layout->GetEntryCount();
const int bucket = hash & (layout->NumberOfBuckets() - 1);
int entry = layout->GetFirstEntry(bucket);
@@ -269,7 +309,7 @@ int FindEntryByHash(const LayoutT* layout, int hash, Address key_to_find) {
entry != LayoutT::kNotFoundValue && entry >= 0 && entry < entry_count &&
max_entries_left > 0;
max_entries_left--) {
- Address key_at_entry = layout->GetKey(entry);
+ Tagged key_at_entry = layout->GetKey(entry);
if (key_at_entry == key_to_find) {
return entry;
}
@@ -280,16 +320,26 @@ int FindEntryByHash(const LayoutT* layout, int hash, Address key_to_find) {
}

// Find an entry by a key and its hash in any hash table layout, and return its
-// value or the zero address if it is not found.
+// value (a full pointer or Smi) or zero if it is not found.
// Template parameter LayoutT should be either OrderedHashMapLayout or
// SmallOrderedHashMapLayout
template <typename LayoutT>
-Address FindValueByHash(const LayoutT* layout, int hash, Address key_to_find) {
- auto entry = FindEntryByHash(layout, hash, key_to_find);
- return entry == kNotFound ? 0 : layout->GetValue(entry);
+Address FindValueByHash(const LayoutT* layout,
+ int hash,
+ Address key_to_find,
+ Address full_pointer_in_cage) {
+ auto entry = FindEntryByHash(layout, hash, Compress(key_to_find));
+ if (entry == kNotFound) return 0;
+ Tagged value = layout->GetValue(entry);
+ return IsSmi(value) ? 0 : Decompress(full_pointer_in_cage, value);
}

static bool IsSmallOrderedHashMap(Address table_untagged) {
+#ifdef V8_COMPRESS_POINTERS
+ // The header check below needs 5 bytes of padding, which compressed layouts don't have.
+ // AsyncContextFrame maps use OrderedHashMap in practice, and upstream dropped this path.
+ return false;
+#endif
const SmallOrderedHashMapLayout* potential_small =
reinterpret_cast<const SmallOrderedHashMapLayout*>(table_untagged);

@@ -366,16 +416,18 @@ static bool IsOrderedHashMap(Address table_untagged) {
Address GetValueFromMap(Address map_addr, int hash, Address key) {
const JSMapLayout* map_untagged =
reinterpret_cast<const JSMapLayout*>(UntagPointer(map_addr));
- Address table_untagged = UntagPointer(map_untagged->table_);
+ Tagged table = map_untagged->table_;
+ if (IsSmi(table)) return 0;
+ Address table_untagged = UntagPointer(Decompress(map_addr, table));

if (IsSmallOrderedHashMap(table_untagged)) {
const SmallOrderedHashMapLayout* layout =
reinterpret_cast<const SmallOrderedHashMapLayout*>(table_untagged);
- return FindValueByHash(layout, hash, key);
+ return FindValueByHash(layout, hash, key, map_addr);
} else if (IsOrderedHashMap(table_untagged)) {
const OrderedHashMapLayout* layout =
reinterpret_cast<const OrderedHashMapLayout*>(table_untagged);
- return FindValueByHash(layout, hash, key);
+ return FindValueByHash(layout, hash, key, map_addr);
}
return 0; // We couldn't determine the kind of the map, just return zero.
}
Loading