| 199 | void JavaScriptANRDetector::cancelNextSample() { |
| 200 | if (_nextSampleTask != 0) { |
| 201 | _dispatchQueue->cancel(_nextSampleTask); |
| 202 | _nextSampleTask = 0; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | bool JavaScriptANRDetector::onANR(JavaScriptTaskScheduler& taskScheduler, |
| 207 | std::chrono::steady_clock::duration detectionThreshold, |
| 208 | const std::atomic<bool>& ack, |
| 209 | const JavaScriptANRSampler* sampler) { |
| 210 | // Read the native-side attribution before waiting on the stack capture. The capture can take up |
| 211 | // to kCaptureStacktraceTimeoutSeconds, and a native call that finishes during that wait clears |
| 212 | // its name, which would report the stall as unattributed. The getter reads saved native state, |
| 213 | // not JS, so it is safe to call while the JS thread is stuck. |
| 214 | auto attributionInfo = taskScheduler.getANRAttributionInfo(); |
| 215 | std::optional<JavaScriptANRSampleTree> sampleTree; |
| 216 | if (sampler != nullptr && sampler->hasEnoughSamples()) { |
| 217 | sampleTree = buildSampleTree(sampler->getSampledStacks()); |
| 218 | } |
| 219 | auto stacktraces = taskScheduler.captureStackTraces(std::chrono::seconds(kCaptureStacktraceTimeoutSeconds)); |
| 220 | StringBox moduleName; |
| 221 | std::string message; |
| 222 | |
| 223 | if (!stacktraces.empty()) { |
| 224 | if (stacktraces[0].getContext() != nullptr) { |
| 225 | moduleName = stacktraces[0].getContext()->getPath().getResourceId().bundleName; |
| 226 | } |
| 227 | // Work under the global context (native callbacks, module evaluation) has no bundle on its context, |
| 228 | // but the innermost feature frame still names the module whose code was running. |
| 229 | if (moduleName.isEmpty()) { |
| 230 | moduleName = stacktraces[0].getStackBundleName(); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | if (!hasRunningStacktrace(stacktraces) && ack.load()) { |
| 235 | // The ack was submitted while waiting to capture stacktraces. |
| 236 | // We consider that task scheduler has recovered |
| 237 | return true; |
| 238 | } |
| 239 | |
| 240 | auto detectionThresholdString = |
| 241 | snap::utils::time::Duration<std::chrono::steady_clock>(detectionThreshold).toString(); |
| 242 | if (moduleName.isEmpty()) { |
| 243 | message = fmt::format("Detected unattributed ANR after {}", detectionThresholdString); |
| 244 | } else { |
| 245 | message = fmt::format("Detected ANR in '{}' after {}", moduleName, detectionThresholdString); |
| 246 | } |
| 247 | // The bundle name says which module stalled; the stuck-in name says which file or bridge call, |
| 248 | // so attributed reports need the suffix as much as unattributed ones do. |
| 249 | message += attributionInfo; |
| 250 | |
| 251 | if (stacktraces.empty()) { |
| 252 | message += " but unable to capture stack traces."; |
| 253 | } |
no test coverage detected