• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
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 */
15
16import { SpRecordTrace } from '../trace/component/SpRecordTrace';
17import { CmdConstant } from './CmdConstant';
18import { HdcDeviceManager } from '../hdc/HdcDeviceManager';
19import { TypeConstants } from '../webSocket/Constants';
20import { WebSocketManager } from '../webSocket/WebSocketManager';
21
22export class Cmd {
23  static CmdSendPostUtils(uri: string, callback: Function, requestData: unknown): void {
24    // @ts-ignore
25    if (window.useWb) {
26      return;
27    }
28    fetch(uri, {
29      method: 'POST',
30      headers: {
31        'Content-Type': 'application/json',
32      },
33      body: JSON.stringify(requestData),
34    }).then((response): void => {
35      if (response.ok) {
36        let result = response.text();
37        result.then((output) => {
38          callback(output);
39        });
40      }
41    });
42  }
43
44  /**
45   * exec objdump to disassembling binary and find addr to show 100 line
46   * @param command  obj dump command
47   * @param addr addr of select line
48   * @param callback result callback
49   */
50  static execObjDump(command: string, addr: string, callback: Function): void {
51    // @ts-ignore
52    if (window.useWb) {
53      return;
54    }
55    const data = { cmd: command, addr: addr };
56    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/exec`;
57    Cmd.CmdSendPostUtils(uri, callback, data);
58  }
59
60  static execHdcCmd(command: string, callback: Function): void {
61    // @ts-ignore
62    if (window.useWb) {
63      return;
64    }
65    const data = {
66      cmd: command,
67      tag: 'shell',
68    };
69    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
70    Cmd.CmdSendPostUtils(uri, callback, data);
71  }
72
73  static async execFileRecv(command: string, filePath: string, callback: Function): Promise<void> {
74    // @ts-ignore
75    if (window.useWb) {
76      return;
77    }
78    let fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
79    const data = {
80      cmd: command,
81      tag: 'file',
82      fileName: fileName,
83    };
84    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
85    let buf = await fetch(uri, {
86      method: 'POST',
87      headers: {
88        'Content-Type': 'application/json',
89      },
90      body: JSON.stringify(data),
91    }).then((res) => res.arrayBuffer());
92    callback(buf);
93  }
94
95  static execHdcTraceCmd(command: string, serialNumber: string, callback: Function): void {
96    // @ts-ignore
97    if (window.useWb) {
98      return;
99    }
100    const data = {
101      cmd: command,
102      tag: 'hiprofiler_cmd',
103      serialNumber: serialNumber,
104    };
105    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/hdcCmd`;
106    Cmd.CmdSendPostUtils(uri, callback, data);
107  }
108
109  static formatString(string: string, params: string[]): string {
110    if (params.length === 0) {
111      return string;
112    }
113    for (let i = 0; i < params.length; i++) {
114      string = string.replace(new RegExp('\\{' + i + '\\}', 'g'), params[i]);
115    }
116    return string;
117  }
118
119  static showSaveFile(callback: Function): void {
120    // @ts-ignore
121    if (window.useWb) {
122      return;
123    }
124    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/showSaveDialog`;
125    fetch(uri, {
126      method: 'GET',
127    }).then((response) => {
128      if (response.ok) {
129        let result = response.text();
130        result.then((output) => {
131          callback(output);
132        });
133      }
134    });
135  }
136
137  static uploadFile(fd: FormData, callback: Function): void {
138    // @ts-ignore
139    if (window.useWb) {
140      return;
141    }
142    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/upload`;
143    fetch(uri, {
144      method: 'POST',
145      body: fd,
146    }).then((response): void => {
147      callback(response);
148    });
149  }
150
151  static copyFile(fileName: string, distFile: string, callback: Function): void {
152    // @ts-ignore
153    if (window.useWb) {
154      return;
155    }
156    const data = {
157      filename: fileName,
158      distfile: distFile,
159    };
160    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/copyfile`;
161    fetch(uri, {
162      method: 'POST',
163      headers: {
164        'Content-Type': 'application/json',
165      },
166      body: JSON.stringify(data),
167    }).then((response): void => {
168      callback(response);
169    });
170  }
171
172  static async openFileDialog(): Promise<string> {
173    // @ts-ignore
174    if (window.useWb) {
175      return '';
176    }
177    let uri = `http://${window.location.host.split(':')[0]}:${window.location.port}/showOpenDialog`;
178    let res = await fetch(uri, { method: 'POST' });
179    let result = res.ok ? await res.text() : '';
180    return result;
181  }
182
183  static convertOutProcessList(res: string): string[] {
184    let processData: string[] = [];
185    if (res) {
186      let lineValues: string[] = res.replace(/\r\n/g, '\r').replace(/\n/g, '\r').split(/\r/);
187      for (let lineVal of lineValues) {
188        lineVal = lineVal.trim();
189        if (lineVal.indexOf('__progname') !== -1 || lineVal.indexOf('CMD') !== -1 || lineVal.length === 0) {
190          continue;
191        } else {
192          let process: string[] = lineVal.split(' ');
193          if (process.length === 2) {
194            processData.push(`${process[1]}(${process[0]})`);
195          }
196        }
197      }
198    }
199    return processData;
200  }
201  static convertOutPackageList(res: string): string[] {
202    let packageData: string[] = [];
203    res ? (packageData = res.replace(/\r\n/g, '\r').replace(/\n\t/g, '\r').split(/\r/)) : [];
204    packageData.shift();
205    return packageData;
206  }
207
208  static getDebugProcess(): Promise<string[]> {
209    return new Promise((resolve, reject) => {
210      if (SpRecordTrace.isVscode) {
211        let cmd = Cmd.formatString(CmdConstant.CMD_GET_DEBUG_PROCESS_DEVICES, [SpRecordTrace.serialNumber]);
212        Cmd.execHdcCmd(cmd, (res: string) => {
213          resolve(Cmd.convertOutProcessList(res));
214        });
215      } else {
216        HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn) => {
217          if (conn) {
218            HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_DEBUG_PROCESS, false).then((res) => {
219              resolve(Cmd.convertOutProcessList(res));
220            });
221          } else {
222            reject(-1);
223          }
224        });
225      }
226    });
227  }
228
229  static getProcess(): Promise<string[]> {
230    return new Promise((resolve, reject): void => {
231      if (SpRecordTrace.isVscode) {
232        let cmd = Cmd.formatString(CmdConstant.CMD_GET_PROCESS_DEVICES, [SpRecordTrace.serialNumber]);
233        Cmd.execHdcCmd(cmd, (res: string): void => {
234          resolve(Cmd.convertOutProcessList(res));
235        });
236      } else if (SpRecordTrace.useExtend) {
237        WebSocketManager.getInstance()!.sendMessage(
238          TypeConstants.USB_TYPE,
239          TypeConstants.USB_GET_PROCESS,
240          new TextEncoder().encode(SpRecordTrace.serialNumber)
241        );
242        setTimeout(() => {
243          if (SpRecordTrace.allProcessListStr) {
244            resolve(Cmd.convertOutProcessList(SpRecordTrace.allProcessListStr));
245          }
246        }, 1000);
247      } else {
248        HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn): void => {
249          if (conn) {
250            HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_PROCESS, false).then((res): void => {
251              resolve(Cmd.convertOutProcessList(res));
252            });
253          } else {
254            reject(-1);
255          }
256        });
257      }
258    });
259  }
260
261  static getPackage(): Promise<string[]> {
262    return new Promise((resolve, reject): void => {
263      if (SpRecordTrace.useExtend) {
264        //@ts-ignore
265        WebSocketManager.getInstance()!.sendMessage(TypeConstants.USB_TYPE, TypeConstants.USB_GET_APP, new TextEncoder().encode(SpRecordTrace.serialNumber));
266        setTimeout(() => {
267          if (SpRecordTrace.usbGetApp) {
268            resolve(Cmd.convertOutPackageList(SpRecordTrace.usbGetApp));
269          }
270        }, 1000);
271      } else {
272        HdcDeviceManager.connect(SpRecordTrace.serialNumber).then((conn) => {
273          if (conn) {
274            HdcDeviceManager.shellResultAsString(CmdConstant.CMD_GET_PACKAGE, false).then((res): void => {
275              resolve(Cmd.convertOutPackageList(res));
276            });
277          } else {
278            reject(-1);
279          }
280        });
281      }
282    });
283  }
284}
285