Clarify clockid_t generation.
For both clock_getcpuclockid() and pthread_getcpuclockid(). These are non-obvious enough that we keep coming back to them, and there's even a stackoverflow question that links to the bionic source as the least unclear existing implementation!
clang optimizes out the unnecessary explicit clearing of CPUCLOCK_PERTHREAD_MASK in the clock_getcpuclockid() -- unnecessary because we just shifted zeroes into the bottom three bits -- so let's leave that in for readability and ease of comparison with pthread_getcpuclockid().
Bug: http://b/376715376
Change-Id: I094c7e270cc88debebd9cd3e9c102614060411a0
diff --git a/libc/bionic/clock_getcpuclockid.cpp b/libc/bionic/clock_getcpuclockid.cpp
index 9ff1845..65ba2c7 100644
--- a/libc/bionic/clock_getcpuclockid.cpp
+++ b/libc/bionic/clock_getcpuclockid.cpp
@@ -34,11 +34,12 @@
int clock_getcpuclockid(pid_t pid, clockid_t* clockid) {
ErrnoRestorer errno_restorer;
- // The tid is stored in the top bits, but negated.
+ // The pid is stored in the top bits, but negated.
clockid_t result = ~static_cast<clockid_t>(pid) << 3;
// Bits 0 and 1: clock type (0 = CPUCLOCK_PROF, 1 = CPUCLOCK_VIRT, 2 = CPUCLOCK_SCHED).
- result |= 2;
- // Bit 2: thread (set) or process (clear). Bit 2 already 0.
+ result |= 2 /* CPUCLOCK_SCHED */;
+ // Bit 2: thread (set) or process (clear).
+ result &= ~4 /* CPUCLOCK_PERTHREAD_MASK */;
if (clock_getres(result, nullptr) == -1) {
return ESRCH;
diff --git a/libc/bionic/pthread_getcpuclockid.cpp b/libc/bionic/pthread_getcpuclockid.cpp
index 6d1884e..ccadc98 100644
--- a/libc/bionic/pthread_getcpuclockid.cpp
+++ b/libc/bionic/pthread_getcpuclockid.cpp
@@ -39,9 +39,9 @@
// The tid is stored in the top bits, but negated.
clockid_t result = ~static_cast<clockid_t>(tid) << 3;
// Bits 0 and 1: clock type (0 = CPUCLOCK_PROF, 1 = CPUCLOCK_VIRT, 2 = CPUCLOCK_SCHED).
- result |= 2;
+ result |= 2 /* CPUCLOCK_SCHED */;
// Bit 2: thread (set) or process (clear)?
- result |= (1 << 2);
+ result |= 4 /* CPUCLOCK_PERTHREAD_MASK */;
*clockid = result;
return 0;