Skip to content

fix: divide cpu_usage by TH_USAGE_SCALE in SentrySystemWrapper.cpuUsage() #7456

@philprime

Description

@philprime

Problem

The cpuUsage() function in SentrySystemWrapper calculates total CPU usage by summing threadInfo.cpu_usage for each thread. However, it omits a necessary division by TH_USAGE_SCALE (1000), which is the scale factor for thread_basic_info.cpu_usage per Apple's Mach API.

This causes the reported CPU usage to be 1000× larger than the actual value. For example, a true usage of 0.1% would be reported as 100%.

Evidence

  • Apple docs: cpu_usage is a scaled value; divide by TH_USAGE_SCALE (1000) to get percentage
  • SentryThreadHandle.cpp (line 175): correctly uses static_cast<float>(data.cpu_usage) / TH_USAGE_SCALE
  • Current code: usage += Float(threadInfo.cpu_usage) / processorCount — missing the scale division

Proposed fix

usage += Float(threadInfo.cpu_usage) / Float(TH_USAGE_SCALE) / processorCount

TH_USAGE_SCALE is defined in <mach/thread_info.h> (1000) and is available when importing Darwin.

Location

Sources/Swift/Helper/SentrySystemWrapper.swiftcpuUsage() method

Note

The existing unit test testCPUUsageReportsData only asserts (0.0...100.0).contains(cpuUsage.doubleValue). It can pass by chance when the process is nearly idle and the raw unscaled value stays under 100. Consider adding a test that verifies reasonable percentage values under load.

Metadata

Metadata

Assignees

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions