xref: /aosp_15_r20/external/perfetto/ui/src/plugins/dev.perfetto.CpuProfile/index.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2021 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {CPU_PROFILE_TRACK_KIND} from '../../public/track_kinds';
16import {Trace} from '../../public/trace';
17import {PerfettoPlugin} from '../../public/plugin';
18import {NUM, NUM_NULL, STR_NULL} from '../../trace_processor/query_result';
19import {CpuProfileTrack} from './cpu_profile_track';
20import {getThreadUriPrefix} from '../../public/utils';
21import {exists} from '../../base/utils';
22import {TrackNode} from '../../public/workspace';
23import ProcessThreadGroupsPlugin from '../dev.perfetto.ProcessThreadGroups';
24
25export default class implements PerfettoPlugin {
26  static readonly id = 'dev.perfetto.CpuProfile';
27  static readonly dependencies = [ProcessThreadGroupsPlugin];
28
29  async onTraceLoad(ctx: Trace): Promise<void> {
30    const result = await ctx.engine.query(`
31      with thread_cpu_sample as (
32        select distinct utid
33        from cpu_profile_stack_sample
34        where utid != 0
35      )
36      select
37        utid,
38        tid,
39        upid,
40        thread.name as threadName
41      from thread_cpu_sample
42      join thread using(utid)
43    `);
44
45    const it = result.iter({
46      utid: NUM,
47      upid: NUM_NULL,
48      tid: NUM_NULL,
49      threadName: STR_NULL,
50    });
51    for (; it.valid(); it.next()) {
52      const utid = it.utid;
53      const upid = it.upid;
54      const threadName = it.threadName;
55      const uri = `${getThreadUriPrefix(upid, utid)}_cpu_samples`;
56      const title = `${threadName} (CPU Stack Samples)`;
57      ctx.tracks.registerTrack({
58        uri,
59        title,
60        tags: {
61          kind: CPU_PROFILE_TRACK_KIND,
62          utid,
63          ...(exists(upid) && {upid}),
64        },
65        track: new CpuProfileTrack(ctx, uri, utid),
66      });
67      const group = ctx.plugins
68        .getPlugin(ProcessThreadGroupsPlugin)
69        .getGroupForThread(utid);
70      const track = new TrackNode({uri, title, sortOrder: -40});
71      group?.addChildInOrder(track);
72    }
73  }
74}
75