1// Copyright (C) 2023 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 {Engine} from '../../trace_processor/engine'; 16import {NUM, NUM_NULL, STR_NULL} from '../../trace_processor/query_result'; 17import {fromNumNull} from '../../trace_processor/sql_utils'; 18import {ProcessInfo, getProcessInfo, getProcessName} from './process'; 19import {Upid, Utid} from './core_types'; 20 21// TODO(altimin): We should consider implementing some form of cache rather than querying 22// the data from trace processor each time. 23 24export interface ThreadInfo { 25 utid: Utid; 26 tid?: number; 27 name?: string; 28 process?: ProcessInfo; 29} 30 31export async function getThreadInfo( 32 engine: Engine, 33 utid: Utid, 34): Promise<ThreadInfo> { 35 const it = ( 36 await engine.query(` 37 SELECT tid, name, upid 38 FROM thread 39 WHERE utid = ${utid}; 40 `) 41 ).iter({tid: NUM, name: STR_NULL, upid: NUM_NULL}); 42 if (!it.valid()) { 43 return { 44 utid, 45 }; 46 } 47 const upid = fromNumNull(it.upid) as Upid | undefined; 48 return { 49 utid, 50 tid: it.tid, 51 name: it.name ?? undefined, 52 process: upid ? await getProcessInfo(engine, upid) : undefined, 53 }; 54} 55 56function getDisplayName( 57 name: string | undefined, 58 id: number | undefined, 59): string | undefined { 60 if (name === undefined) { 61 return id === undefined ? undefined : `${id}`; 62 } 63 return id === undefined ? name : `${name} [${id}]`; 64} 65 66export function getThreadName(info?: { 67 name?: string; 68 tid?: number; 69}): string | undefined { 70 return getDisplayName(info?.name, info?.tid); 71} 72 73// Return the full thread name, including the process name. 74export function getFullThreadName(info?: ThreadInfo): string | undefined { 75 if (info?.process === undefined) { 76 return getThreadName(info); 77 } 78 return `${getThreadName(info)} ${getProcessName(info.process)}`; 79} 80