index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import {createRef, Fragment, PureComponent} from 'react';
  2. import {
  3. AutoSizer,
  4. CellMeasurer,
  5. CellMeasurerCache,
  6. List,
  7. ListRowProps,
  8. } from 'react-virtualized';
  9. import styled from '@emotion/styled';
  10. import isEqual from 'lodash/isEqual';
  11. import isNil from 'lodash/isNil';
  12. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  13. import Button from 'sentry/components/button';
  14. import Checkbox from 'sentry/components/checkbox';
  15. import EventDataSection from 'sentry/components/events/eventDataSection';
  16. import {getImageRange, parseAddress} from 'sentry/components/events/interfaces/utils';
  17. import {Panel, PanelBody} from 'sentry/components/panels';
  18. import SearchBar from 'sentry/components/searchBar';
  19. import {IconWarning} from 'sentry/icons';
  20. import {t, tct} from 'sentry/locale';
  21. import DebugMetaStore, {DebugMetaActions} from 'sentry/stores/debugMetaStore';
  22. import space from 'sentry/styles/space';
  23. import {Frame, Organization, Project} from 'sentry/types';
  24. import {Event} from 'sentry/types/event';
  25. import EmptyMessage from 'sentry/views/settings/components/emptyMessage';
  26. import {shouldSkipSection} from '../debugMeta-v2/utils';
  27. import DebugImage from './debugImage';
  28. import ImageForBar from './imageForBar';
  29. import {getFileName} from './utils';
  30. const MIN_FILTER_LEN = 3;
  31. const PANEL_MAX_HEIGHT = 400;
  32. type Image = React.ComponentProps<typeof DebugImage>['image'];
  33. type DefaultProps = {
  34. data: {
  35. images: Array<Image>;
  36. };
  37. };
  38. type Props = DefaultProps & {
  39. event: Event;
  40. organization: Organization;
  41. projectId: Project['id'];
  42. };
  43. type State = {
  44. debugImages: Array<Image>;
  45. filter: string;
  46. filteredImages: Array<Image>;
  47. showDetails: boolean;
  48. showUnused: boolean;
  49. foundFrame?: Frame;
  50. panelBodyHeight?: number;
  51. };
  52. function normalizeId(id: string | undefined): string {
  53. return id ? id.trim().toLowerCase().replace(/[- ]/g, '') : '';
  54. }
  55. const cache = new CellMeasurerCache({
  56. fixedWidth: true,
  57. defaultHeight: 81,
  58. });
  59. class DebugMeta extends PureComponent<Props, State> {
  60. static defaultProps: DefaultProps = {
  61. data: {images: []},
  62. };
  63. state: State = {
  64. filter: '',
  65. debugImages: [],
  66. filteredImages: [],
  67. showUnused: false,
  68. showDetails: false,
  69. };
  70. componentDidMount() {
  71. this.unsubscribeFromStore = DebugMetaStore.listen(this.onStoreChange, undefined);
  72. cache.clearAll();
  73. this.filterImages();
  74. }
  75. componentDidUpdate(_prevProps: Props, prevState: State) {
  76. if (
  77. prevState.showUnused !== this.state.showUnused ||
  78. prevState.filter !== this.state.filter
  79. ) {
  80. this.filterImages();
  81. }
  82. if (
  83. !isEqual(prevState.foundFrame, this.state.foundFrame) ||
  84. this.state.showDetails !== prevState.showDetails ||
  85. prevState.showUnused !== this.state.showUnused ||
  86. (prevState.filter && !this.state.filter)
  87. ) {
  88. this.updateGrid();
  89. }
  90. if (prevState.filteredImages.length === 0 && this.state.filteredImages.length > 0) {
  91. this.getPanelBodyHeight();
  92. }
  93. }
  94. componentWillUnmount() {
  95. if (this.unsubscribeFromStore) {
  96. this.unsubscribeFromStore();
  97. }
  98. }
  99. unsubscribeFromStore: any;
  100. panelBodyRef = createRef<HTMLDivElement>();
  101. listRef: List | null = null;
  102. updateGrid() {
  103. cache.clearAll();
  104. this.listRef?.forceUpdateGrid();
  105. }
  106. getPanelBodyHeight() {
  107. const panelBodyHeight = this.panelBodyRef?.current?.offsetHeight;
  108. if (!panelBodyHeight) {
  109. return;
  110. }
  111. this.setState({panelBodyHeight});
  112. }
  113. onStoreChange = (store: {filter: string}) => {
  114. this.setState({
  115. filter: store.filter,
  116. });
  117. };
  118. filterImage(image: Image) {
  119. const {showUnused, filter} = this.state;
  120. const searchTerm = filter.trim().toLowerCase();
  121. if (searchTerm.length < MIN_FILTER_LEN) {
  122. if (showUnused) {
  123. return true;
  124. }
  125. // A debug status of `null` indicates that this information is not yet
  126. // available in an old event. Default to showing the image.
  127. if (image.debug_status !== 'unused') {
  128. return true;
  129. }
  130. // An unwind status of `null` indicates that symbolicator did not unwind.
  131. // Ignore the status in this case.
  132. if (!isNil(image.unwind_status) && image.unwind_status !== 'unused') {
  133. return true;
  134. }
  135. return false;
  136. }
  137. // When searching for an address, check for the address range of the image
  138. // instead of an exact match. Note that images cannot be found by index
  139. // if they are at 0x0. For those relative addressing has to be used.
  140. if (searchTerm.indexOf('0x') === 0) {
  141. const needle = parseAddress(searchTerm);
  142. if (needle > 0 && image.image_addr !== '0x0') {
  143. const [startAddress, endAddress] = getImageRange(image);
  144. return needle >= startAddress && needle < endAddress;
  145. }
  146. }
  147. // the searchTerm ending at "!" is the end of the ID search.
  148. const relMatch = searchTerm.match(/^\s*(.*?)!/); // debug_id!address
  149. const idSearchTerm = normalizeId(relMatch?.[1] || searchTerm);
  150. return (
  151. // Prefix match for identifiers
  152. normalizeId(image.code_id).indexOf(idSearchTerm) === 0 ||
  153. normalizeId(image.debug_id).indexOf(idSearchTerm) === 0 ||
  154. // Any match for file paths
  155. (image.code_file?.toLowerCase() || '').indexOf(searchTerm) >= 0 ||
  156. (image.debug_file?.toLowerCase() || '').indexOf(searchTerm) >= 0
  157. );
  158. }
  159. filterImages() {
  160. const foundFrame = this.getFrame();
  161. // skip null values indicating invalid debug images
  162. const debugImages = this.getDebugImages();
  163. if (!debugImages.length) {
  164. return;
  165. }
  166. const filteredImages = debugImages.filter(image => this.filterImage(image));
  167. this.setState({debugImages, filteredImages, foundFrame});
  168. }
  169. isValidImage(image: Image) {
  170. // in particular proguard images do not have a code file, skip them
  171. if (image === null || image.code_file === null || image.type === 'proguard') {
  172. return false;
  173. }
  174. if (getFileName(image.code_file) === 'dyld_sim') {
  175. // this is only for simulator builds
  176. return false;
  177. }
  178. return true;
  179. }
  180. getFrame(): Frame | undefined {
  181. const {
  182. event: {entries},
  183. } = this.props;
  184. const frames: Array<Frame> | undefined = entries.find(
  185. ({type}) => type === 'exception'
  186. )?.data?.values?.[0]?.stacktrace?.frames;
  187. if (!frames) {
  188. return undefined;
  189. }
  190. const searchTerm = normalizeId(this.state.filter);
  191. const relMatch = searchTerm.match(/^\s*(.*?)!(.*)$/); // debug_id!address
  192. if (relMatch) {
  193. const debugImages = this.getDebugImages().map(
  194. (image, idx) => [idx, image] as [number, Image]
  195. );
  196. const filteredImages = debugImages.filter(([_, image]) => this.filterImage(image));
  197. if (filteredImages.length === 1) {
  198. return frames.find(
  199. frame =>
  200. frame.addrMode === `rel:${filteredImages[0][0]}` &&
  201. frame.instructionAddr?.toLowerCase() === relMatch[2]
  202. );
  203. }
  204. return undefined;
  205. }
  206. return frames.find(frame => frame.instructionAddr?.toLowerCase() === searchTerm);
  207. }
  208. getDebugImages() {
  209. const {
  210. data: {images},
  211. } = this.props;
  212. // There are a bunch of images in debug_meta that are not relevant to this
  213. // component. Filter those out to reduce the noise. Most importantly, this
  214. // includes proguard images, which are rendered separately.
  215. const filtered = images.filter(image => this.isValidImage(image));
  216. // Sort images by their start address. We assume that images have
  217. // non-overlapping ranges. Each address is given as hex string (e.g.
  218. // "0xbeef").
  219. filtered.sort((a, b) => parseAddress(a.image_addr) - parseAddress(b.image_addr));
  220. return filtered;
  221. }
  222. getNoImagesMessage() {
  223. const {filter, showUnused, debugImages} = this.state;
  224. if (debugImages.length === 0) {
  225. return t('No loaded images available.');
  226. }
  227. if (!showUnused && !filter) {
  228. return tct(
  229. 'No images are referenced in the stack trace. [toggle: Show Unreferenced]',
  230. {
  231. toggle: (
  232. <Button
  233. priority="link"
  234. onClick={this.handleShowUnused}
  235. aria-label={t('Show Unreferenced')}
  236. />
  237. ),
  238. }
  239. );
  240. }
  241. return t('Sorry, no images match your query.');
  242. }
  243. renderToolbar() {
  244. const {filter, showDetails, showUnused} = this.state;
  245. return (
  246. <ToolbarWrapper>
  247. <Label>
  248. <Checkbox checked={showDetails} onChange={this.handleChangeShowDetails} />
  249. {t('details')}
  250. </Label>
  251. <Label>
  252. <Checkbox
  253. checked={showUnused || !!filter}
  254. disabled={!!filter}
  255. onChange={this.handleChangeShowUnused}
  256. />
  257. {t('show unreferenced')}
  258. </Label>
  259. <SearchInputWrapper>
  260. <StyledSearchBar
  261. onChange={this.handleChangeFilter}
  262. query={filter}
  263. placeholder={t('Search images\u2026')}
  264. />
  265. </SearchInputWrapper>
  266. </ToolbarWrapper>
  267. );
  268. }
  269. renderRow = ({index, key, parent, style}: ListRowProps) => {
  270. const {organization, projectId} = this.props;
  271. const {filteredImages, showDetails} = this.state;
  272. return (
  273. <CellMeasurer
  274. cache={cache}
  275. columnIndex={0}
  276. key={key}
  277. parent={parent}
  278. rowIndex={index}
  279. >
  280. <DebugImage
  281. style={style}
  282. image={filteredImages[index]}
  283. organization={organization}
  284. projectId={projectId}
  285. showDetails={showDetails}
  286. />
  287. </CellMeasurer>
  288. );
  289. };
  290. getListHeight() {
  291. const {showUnused, showDetails, panelBodyHeight} = this.state;
  292. if (
  293. !panelBodyHeight ||
  294. panelBodyHeight > PANEL_MAX_HEIGHT ||
  295. showUnused ||
  296. showDetails
  297. ) {
  298. return PANEL_MAX_HEIGHT;
  299. }
  300. return panelBodyHeight;
  301. }
  302. renderImageList() {
  303. const {filteredImages, showDetails, panelBodyHeight} = this.state;
  304. const {organization, projectId} = this.props;
  305. if (!panelBodyHeight) {
  306. return filteredImages.map(filteredImage => (
  307. <DebugImage
  308. key={filteredImage.debug_id}
  309. image={filteredImage}
  310. organization={organization}
  311. projectId={projectId}
  312. showDetails={showDetails}
  313. />
  314. ));
  315. }
  316. return (
  317. <AutoSizer disableHeight>
  318. {({width}) => (
  319. <StyledList
  320. ref={(el: List | null) => {
  321. this.listRef = el;
  322. }}
  323. deferredMeasurementCache={cache}
  324. height={this.getListHeight()}
  325. overscanRowCount={5}
  326. rowCount={filteredImages.length}
  327. rowHeight={cache.rowHeight}
  328. rowRenderer={this.renderRow}
  329. width={width}
  330. isScrolling={false}
  331. />
  332. )}
  333. </AutoSizer>
  334. );
  335. }
  336. handleChangeShowUnused = (event: React.ChangeEvent<HTMLInputElement>) => {
  337. const showUnused = event.target.checked;
  338. this.setState({showUnused});
  339. };
  340. handleShowUnused = () => {
  341. this.setState({showUnused: true});
  342. };
  343. handleChangeShowDetails = (event: React.ChangeEvent<HTMLInputElement>) => {
  344. const showDetails = event.target.checked;
  345. this.setState({showDetails});
  346. };
  347. handleChangeFilter = (value = '') => {
  348. DebugMetaActions.updateFilter(value);
  349. };
  350. render() {
  351. const {filteredImages, foundFrame} = this.state;
  352. const {data} = this.props;
  353. const {images} = data;
  354. if (shouldSkipSection(filteredImages, images)) {
  355. return null;
  356. }
  357. return (
  358. <EventDataSection
  359. type="images-loaded"
  360. title={
  361. <GuideAnchor target="images-loaded" position="bottom">
  362. <h3>{t('Images Loaded')}</h3>
  363. </GuideAnchor>
  364. }
  365. actions={this.renderToolbar()}
  366. wrapTitle={false}
  367. isCentered
  368. >
  369. <DebugImagesPanel>
  370. {filteredImages.length > 0 ? (
  371. <Fragment>
  372. {foundFrame && (
  373. <ImageForBar
  374. frame={foundFrame}
  375. onShowAllImages={this.handleChangeFilter}
  376. />
  377. )}
  378. <PanelBody ref={this.panelBodyRef}>{this.renderImageList()}</PanelBody>
  379. </Fragment>
  380. ) : (
  381. <EmptyMessage icon={<IconWarning size="xl" />}>
  382. {this.getNoImagesMessage()}
  383. </EmptyMessage>
  384. )}
  385. </DebugImagesPanel>
  386. </EventDataSection>
  387. );
  388. }
  389. }
  390. export default DebugMeta;
  391. // XXX(ts): Emotion11 has some trouble with List's defaultProps
  392. //
  393. // It gives the list have a dynamic height; otherwise, in the case of filtered
  394. // options, a list will be displayed with an empty space
  395. const StyledList = styled(List as any)<React.ComponentProps<typeof List>>`
  396. height: auto !important;
  397. max-height: ${p => p.height}px;
  398. outline: none;
  399. `;
  400. const Label = styled('label')`
  401. font-weight: normal;
  402. margin-right: 1em;
  403. margin-bottom: 0;
  404. white-space: nowrap;
  405. > input {
  406. margin-right: 1ex;
  407. }
  408. `;
  409. const DebugImagesPanel = styled(Panel)`
  410. margin-bottom: ${space(1)};
  411. max-height: ${PANEL_MAX_HEIGHT}px;
  412. overflow: hidden;
  413. `;
  414. const ToolbarWrapper = styled('div')`
  415. display: flex;
  416. align-items: center;
  417. @media (max-width: ${p => p.theme.breakpoints.small}) {
  418. flex-wrap: wrap;
  419. margin-top: ${space(1)};
  420. }
  421. `;
  422. const SearchInputWrapper = styled('div')`
  423. width: 100%;
  424. @media (max-width: ${p => p.theme.breakpoints.small}) {
  425. width: 100%;
  426. max-width: 100%;
  427. margin-top: ${space(1)};
  428. }
  429. @media (min-width: ${p => p.theme.breakpoints.small}) and (max-width: ${p =>
  430. p.theme.breakpoints.xlarge}) {
  431. max-width: 180px;
  432. display: inline-block;
  433. }
  434. @media (min-width: ${props => props.theme.breakpoints.xlarge}) {
  435. width: 330px;
  436. max-width: none;
  437. }
  438. @media (min-width: 1550px) {
  439. width: 510px;
  440. }
  441. `;
  442. // TODO(matej): remove this once we refactor SearchBar to not use css classes
  443. // - it could accept size as a prop
  444. const StyledSearchBar = styled(SearchBar)`
  445. .search-input {
  446. height: 30px;
  447. }
  448. `;