Skip to content

Commit e12c3a4

Browse files
committed
v1
1 parent e963b3a commit e12c3a4

2 files changed

Lines changed: 81 additions & 1 deletion

File tree

ddprof-lib/src/main/cpp/threadFilter.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,8 @@ int ThreadFilter::mapThreadId(int thread_id) {
9999

100100
// Get bitmap that contains the thread id, create one if it does not exist
101101
u64* ThreadFilter::getBitmapFor(int thread_id) {
102-
int index = static_cast<u32>(thread_id) / BITMAP_CAPACITY;
102+
int index = thread_id / BITMAP_CAPACITY;
103+
assert(index >= 0 && index < (int)_max_bitmaps);
103104
u64* b = _bitmap[index];
104105
if (b == NULL) {
105106
b = (u64 *)OS::safeAlloc(BITMAP_SIZE);
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.datadoghq.profiler;
2+
3+
import sun.misc.Unsafe;
4+
import java.lang.reflect.Field;
5+
6+
7+
class ActiveBitmaps {
8+
private static final Unsafe UNSAFE;
9+
static {
10+
Unsafe unsafe = null;
11+
try {
12+
Field f = Unsafe.class.getDeclaredField("theUnsafe");
13+
f.setAccessible(true);
14+
unsafe = (Unsafe) f.get(null);
15+
} catch (Exception ignore) { }
16+
UNSAFE = unsafe;
17+
}
18+
19+
private static long activeCountAddr = 0;
20+
21+
private static final ThreadLocal<Long> Address = new ThreadLocal<Long>() {
22+
@Override protected Long initialValue() {
23+
return -1L;
24+
}
25+
};
26+
27+
public static void initialize() {
28+
activeCountAddr = getActiveCountAddr0();
29+
}
30+
31+
static long getBitmask(int tid) {
32+
int tmp = (tid >> 8) & 0xff ;
33+
int bits = 0;
34+
for (int index = 0; index < 7 ; index++) {
35+
if ((tmp & 0x01) == 0x01) {
36+
bits |= 0x01;
37+
}
38+
tmp >>= 1;
39+
bits <<= 1;
40+
}
41+
return 1L << (bits & 0x3f);
42+
}
43+
44+
static void setActive(int tid, boolean active) {
45+
long addr = Address.get();
46+
if (addr == -1) {
47+
addr = bitmapAddressFor0(tid);
48+
Address.set(addr);
49+
}
50+
long bitmask = getBitmask(tid);
51+
long value = UNSAFE.getLong(addr);
52+
long newVal;
53+
if (active) {
54+
newVal = value | bitmask;
55+
} else {
56+
newVal = value & ~bitmask;
57+
}
58+
while (!UNSAFE.compareAndSwapLong(null, addr, value, newVal)) {
59+
value = UNSAFE.getLong(addr);
60+
newVal = active ? (value | bitmask) : (value & ~bitmask);
61+
}
62+
int delta = active ? 1 : -1;
63+
assert activeCountAddr != 0;
64+
UNSAFE.getAndAddInt(null, activeCountAddr, delta);
65+
if (isActive0(tid) != active) {
66+
throw new RuntimeException("SetActive failed");
67+
}
68+
69+
assert isActive0(tid) == active;
70+
}
71+
72+
// For verification
73+
private static native boolean isActive0(int tid);
74+
75+
// Setup bitmap and active count locations
76+
private static native long bitmapAddressFor0(int tid);
77+
private static native long getActiveCountAddr0();
78+
}
79+

0 commit comments

Comments
 (0)