Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 2eb3f679645938a6bc10d9d592c7da14aff77129 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/*******************************************************************************
 * Copyright (c) 2009 STMicroelectronics.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Xavier Raynaud <xavier.raynaud@st.com> - initial API and implementation
 *******************************************************************************/
package org.eclipse.linuxtools.binutils.utils;


import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.IAddress;
import org.eclipse.cdt.core.IBinaryParser;
import org.eclipse.cdt.core.IBinaryParser.IBinaryFile;
import org.eclipse.cdt.core.IBinaryParser.IBinaryObject;
import org.eclipse.cdt.core.IBinaryParser.ISymbol;
import org.eclipse.cdt.core.model.CModelException;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.CoreModelUtil;
import org.eclipse.cdt.core.model.IBinary;
import org.eclipse.cdt.core.model.ICProject;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.utils.Addr2line;
import org.eclipse.cdt.utils.CPPFilt;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.linuxtools.binutils.Activator;


/**
 * This class Is a utility on top of c++filt and addr2line.
 * 
 * It allows an easy conversion between address and source location,
 * and between mangled and demangled symbols.
 * 
 * @author Xavier Raynaud <xavier.raynaud@st.com>
 */
public class STSymbolManager {

	/**
	 * Auto dispose timeout:
	 * If some tools has been unused since more that this time (in ms),
	 * they are disposed.
	 */
	private final static long AUTO_DISPOSE_TIMEOUT = 30000;

	/**
	 * Singleton instance
	 */
	public final static STSymbolManager sharedInstance = new STSymbolManager();

	private final class AutoDisposeAddr2line {
		private Addr2line addr2line;
		private long startTime;
	}

	private final class AutoDisposeCPPFilt {
		private CPPFilt cppfilt;
		private long startTime;
	}

	/** Map of all living instance of addr2line */
	private final HashMap<IBinaryObject, AutoDisposeAddr2line> addr2lines = new HashMap<IBinaryObject, AutoDisposeAddr2line>();
	/** Map of all living instance of cppfilt */
	private final HashMap<String, AutoDisposeCPPFilt> cppfilts = new HashMap<String, AutoDisposeCPPFilt>();

	/**
	 * Constructor
	 */
	private STSymbolManager() {
		Runnable worker = new Runnable() {
			public void run() {
				try {
					do {
						try {
							Thread.sleep(AUTO_DISPOSE_TIMEOUT);
						} catch (InterruptedException e) {
							break;
						}
						cleanup();
					} while (true);
				} catch (Exception _) {
					Status s = new Status(Status.ERROR, Activator.PLUGIN_ID, _.getMessage(), _);
					Activator.getDefault().getLog().log(s);
				}
			}
		};
		new Thread(worker, "ST System Analysis Symbol Manager").start(); //$NON-NLS-1$
		// TODO: perhaps this thread has to be lazy-created ?
		// and perhaps this thread has to destroy itself when it is no longer used ?
	}

	/**
	 * each {@link #AUTO_DISPOSE_TIMEOUT} ms, the unused addr2line and c++filt programs
	 * are disposed.
	 */
	private synchronized void cleanup() {
		long currentTime = System.currentTimeMillis();
		Iterator<Entry<IBinaryObject, AutoDisposeAddr2line> > iter = addr2lines.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<IBinaryObject, AutoDisposeAddr2line> entry = iter.next();
			AutoDisposeAddr2line ada2l = entry.getValue();
			long diff = currentTime-ada2l.startTime;
			if (diff > AUTO_DISPOSE_TIMEOUT) {
				ada2l.addr2line.dispose();
				ada2l.addr2line = null;
				iter.remove();
			}
		}

		Iterator<Entry<String, AutoDisposeCPPFilt> > iter2 = cppfilts.entrySet().iterator();
		while (iter2.hasNext()) {
			Entry<String, AutoDisposeCPPFilt> entry = iter2.next();
			AutoDisposeCPPFilt adcppf = entry.getValue();
			long diff = currentTime-adcppf.startTime;
			if (diff > AUTO_DISPOSE_TIMEOUT) {
				if (adcppf.cppfilt != null) {
					adcppf.cppfilt.dispose();
					adcppf.cppfilt = null;
				}
				iter2.remove();
			}
		}
	}


	/**
	 * Demangle the given symbol
	 * @param symbol
	 * @return
	 */
	public synchronized String demangle(ISymbol symbol) {
		String cpu = symbol.getBinaryObject().getCPU();
		String symbolName = symbol.getName();
		return demangleImpl(symbolName, cpu);
	}

	/**
	 * Demangle the given symbol
	 * @param program 
	 * @param symbolName 
	 * @return
	 */
	public synchronized String demangle(IBinaryObject program, String symbolName) {
		String cpu = program.getCPU();
		return demangleImpl(symbolName, cpu);
	}


	/**
	 * Demangle the given symbol
	 * @param symbol
	 * @return
	 */
	private synchronized String demangleImpl(String symbolName, String cpu) {
		CPPFilt cppfilt = getCppFilt(cpu);
		if (cppfilt != null && (symbolName.startsWith("_Z") || symbolName.startsWith("_G"))) {
			try {
				symbolName = cppfilt.getFunction(symbolName);
			} catch (IOException _) {
				// TODO: log the error ?
			}
		}
		return symbolName;
	}


	/**
	 * @param symbol 
	 * @return the location (as returned by addr2line, e.g. file:line) of the given address
	 */
	public synchronized String getLine(ISymbol symbol) {
		IBinaryObject binary = symbol.getBinaryObject();
		IAddress address = symbol.getAddress();
		return getLine(binary, address);
	}


	/**
	 * @param program 
	 * @param address 
	 * @return the location (as returned by addr2line, e.g. file:line) of the given address
	 */
	public synchronized String getLine(IBinaryObject program, IAddress address) {
		Addr2line addr2line = getAddr2line(program);
		if (addr2line == null) return "??:0";
		try {
			return addr2line.getLine(address);
		} catch (IOException _) {
			// TODO: log the error ?;
			// Perhaps log the error only once, because 
			// this method is called many many times...
			return "??:0";
		}
	}

	/**
	 * @param program 
	 * @param address an address, in hex, octal or decimal format (0xabcdef, 07654, 12345)
	 * @return the location (as returned by addr2line, e.g. file:line) of the given address
	 */
	public synchronized String getLine(IBinaryObject program, String address) {
		IAddress addr = program.getAddressFactory().createAddress(address);
		return getLine(program, addr);
	}

	/**
	 * @param program 
	 * @param address
	 * @return the location (as returned by addr2line, e.g. file:line) of the given address
	 */
	public synchronized String getLine(IBinaryObject program, long address) {
		IAddress addr = program.getAddressFactory().createAddress(Long.toString(address));
		return getLine(program, addr);
	}

	/**
	 * @param program 
	 * @param address 
	 * @return the line number of the given address
	 */
	public synchronized int getLineNumber(IBinaryObject program, IAddress address) {
		Addr2line addr2line = getAddr2line(program);
		if (addr2line == null) return -1;
		try {
			return addr2line.getLineNumber(address);
		} catch (IOException _) {
			// TODO: log the error ?;
			// Perhaps log the error only once, because 
			// this method is called many many times...
			return -1;
		}
	}

	/**
	 * @param program 
	 * @param address 
	 * @return the line number of the given address
	 */
	public synchronized int getLineNumber(IBinaryObject program, String address) {
		IAddress addr = program.getAddressFactory().createAddress(address);
		return getLineNumber(program, addr);
	}

	/**
	 * @param program 
	 * @param address 
	 * @return the line number of the given address
	 */
	public synchronized int getLineNumber(IBinaryObject program, long address) {
		IAddress addr = program.getAddressFactory().createAddress(Long.toString(address));
		return getLineNumber(program, addr);
	}

	/**
	 * 
	 * @param symbol
	 * @return the line number of the given symbol
	 */
	public int getLineNumber(ISymbol symbol) {
		IBinaryObject obj = symbol.getBinaryObject();
		IAddress address = symbol.getAddress();
		return getLineNumber(obj,address);
	}

	/**
	 * 
	 * @param program 
	 * @param address 
	 * @return the file name of the given address
	 */
	public synchronized String getFileName(IBinaryObject program, IAddress address) {
		Addr2line addr2line = getAddr2line(program);
		if (addr2line == null) return null;
		try {
			return addr2line.getFileName(address);
		} catch (IOException _) {
			// TODO: log the error ?;
			// Perhaps log the error only once, because 
			// this method is called many many times...
			return null;
		}
	}

	/**
	 * 
	 * @param program 
	 * @param address 
	 * @return the file name of the given address
	 */
	public synchronized String getFileName(IBinaryObject program, String address) {
		IAddress addr = program.getAddressFactory().createAddress(address);
		return getFileName(program, addr);
	}

	/**
	 * 
	 * @param program 
	 * @param address 
	 * @return the file name of the given address
	 */
	public synchronized String getFileName(IBinaryObject program, long address) {
		IAddress addr = program.getAddressFactory().createAddress(Long.toString(address));
		return getFileName(program, addr);
	}

	/**
	 * 
	 * @param symbol
	 * @return the filename of the given symbol
	 */
	public String getFilename(ISymbol symbol) {
		IBinaryObject obj = symbol.getBinaryObject();
		IAddress address = symbol.getAddress();
		return getFileName(obj,address);
	}


	/**
	 * @param program 
	 * @param address an address
	 * @return the function name of the given address, based on addr2line output
	 */
	public synchronized String getFunctionName(IBinaryObject program, long address) {
		IAddress addr = program.getAddressFactory().createAddress(Long.toString(address));
		return getFunctionName(program, addr);
	}

	/**
	 * @param program 
	 * @param address an address, in hex, octal or decimal format (0xabcdef, 07654, 12345)
	 * @return the function name of the given address, based on addr2line output
	 */
	public synchronized String getFunctionName(IBinaryObject program, String address) {
		IAddress addr = program.getAddressFactory().createAddress(address);
		return getFunctionName(program, addr);
	}

	/**
	 * @param program 
	 * @param address an address
	 * @return the function name of the given address, based on addr2line output
	 */
	public synchronized String getFunctionName(IBinaryObject program, IAddress address) {
		Addr2line addr2line = getAddr2line(program);
		if (addr2line == null) return null;
		try {
			return addr2line.getFunction(address);
		} catch (IOException _) {
			// TODO: log the error ?;
			// Perhaps log the error only once, because 
			// this method is called many many times...
			return null;
		}
	}


	/**
	 * Gets the c++filt support for the given program
	 * Note that the instance if kept in a local hashmap, and discarded after 30 seconds of inactivity.
	 * @param program
	 * @return an instance of CPPFilt suitable for the given program
	 */
	private synchronized CPPFilt getCppFilt(String cpu) {
		AutoDisposeCPPFilt adCppfilt = cppfilts.get(cpu);
		if (adCppfilt == null) {
			adCppfilt = new AutoDisposeCPPFilt();
			cppfilts.put(cpu, adCppfilt);
		}
		if (adCppfilt.cppfilt == null) {
			try {
				adCppfilt.cppfilt = STCPPFiltFactory.getCPPFilt(cpu);
			} catch (IOException _) {
				// TODO: log the error ?;
				// Perhaps log the error only once, because 
				// this method is called many many times...
				return null;
			}
		}
		adCppfilt.startTime = System.currentTimeMillis();
		return adCppfilt.cppfilt;
	}

	/**
	 * Gets the addr2line support for the given program
	 * Note that the instance if kept in a local hashmap, and discarded after 30 seconds of inactivity.
	 * @param program
	 * @return an instance of Addr2line suitable for the given program
	 */
	private synchronized Addr2line getAddr2line(IBinaryObject program) {
		AutoDisposeAddr2line adAddr2line = addr2lines.get(program);
		if (adAddr2line == null) {
			adAddr2line = new AutoDisposeAddr2line();
			addr2lines.put(program, adAddr2line);
		}
		if (adAddr2line.addr2line == null) {
			try {
				adAddr2line.addr2line = STAddr2LineFactory.getAddr2line(program.getCPU(), program.getPath().toOSString());
			} catch (IOException _) {
				// TODO: log the error ?;
				// Perhaps log the error only once, because 
				// this method is called many many times...
				return null;
			}
		}
		adAddr2line.startTime = System.currentTimeMillis();
		return adAddr2line.addr2line;
	}

	/**
	 * Gets the IBinaryObject corresponding to the given path (absolute path in filesystem).
	 * If a IBinaryObject corresponding to the given path has been already built by eclipse, return it.
	 * Otherwise build a new IBinaryObject, according to project preferences.
	 * Note that it may return null if the path is invalid, or is not a valid binary file.
	 * @param path
	 * @return a IBinaryObject
	 */
	public IBinaryObject getBinaryObject(String loc) {
		IPath path = new Path(loc);
		return getBinaryObject(path);
	}


	/**
	 * Gets the IBinaryObject corresponding to the given path (absolute path in filesystem).
	 * If a IBinaryObject corresponding to the given path has been already built by eclipse, return it.
	 * Otherwise build a new IBinaryObject, according to project preferences.
	 * Note that it may return null if the path is invalid, or is not a valid binary file.
	 * @param path
	 * @return a IBinaryObject
	 */
	public IBinaryObject getBinaryObject(IPath path) {

		return getBinaryObject(path, null);
	}

	/**
	 * Gets the IBinaryObject corresponding to the given path (absolute path in filesystem).
	 * If a IBinaryObject corresponding to the given path has been already built by eclipse, return it.
	 * Otherwise build a new IBinaryObject, according to project preferences.
	 * Note that it may return null if the path is invalid, or is not a valid binary file.
	 * @param path
	 * @param default parser
	 * @return a IBinaryObject
	 */
	public IBinaryObject getBinaryObject(IPath path, IBinaryParser defaultparser) {
		IFile c = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
		List<IBinaryParser> parsers;
		if (c != null) {
			IBinaryObject object = getAlreadyExistingBinaryObject(c);
			if (object != null) return object;
			parsers = getBinaryParser(c.getProject());
		} else {
			parsers = new LinkedList<IBinaryParser>();
		}
		
		if (defaultparser == null) {
			try {
				defaultparser = CCorePlugin.getDefault().getDefaultBinaryParser();
			} catch (CoreException _) {
				Activator.getDefault().getLog().log(_.getStatus());
			}
		}
		if (defaultparser != null) {
			parsers.add(defaultparser);
		}
		return buildBinaryObject(path, parsers);
	}
	
	/**
	 * Validate the binary file.
	 * In particular, verify that this binary file can be decoded.
	 * @param o
	 * @return the binary object, or null.
	 */
	private IBinaryObject validateBinary(IBinaryFile o) {
		if (o instanceof IBinaryObject) {
			IBinaryObject object = (IBinaryObject) o;
			String s = null;
			try {
				s = object.getCPU(); // 
			} catch (Exception _) {}
			if (s.length() > 0) {
				return object;
			}
		}
		return null;
	}

	private IBinaryObject buildBinaryObject(IPath path, List<IBinaryParser> parsers) {
		for (IBinaryParser iBinaryParser : parsers) {
			IBinaryObject o = buildBinaryObject(path, iBinaryParser);
			if (o != null) return o;
		}
		return null;
	}
	
	/**
	 * Build a binary object with the given file and parser.
	 * Also verify that the builded binary object is valid (@see #validateBinary)
	 */
	private IBinaryObject buildBinaryObject(IPath path, IBinaryParser parser) {
		if (parser == null) return null;
		IBinaryFile bf = null;
		try {
			bf = parser.getBinary(path);
		} catch (IOException _) {
			// do nothing ?
		}
		return validateBinary(bf);
	}

	/**
	 * Ask the workbench to find if a binary object already exist for the given file
	 */
	private IBinaryObject getAlreadyExistingBinaryObject(IFile c) {
		IProject project = c.getProject();
		if (project != null && project.exists()) {
			ICProject cproject = CoreModel.getDefault().create(project);
			if (cproject != null) {
				try {
					IBinary[] b = cproject.getBinaryContainer()
					.getBinaries();
					for (IBinary binary : b) {
						IResource r = binary.getResource();
						if (r.equals(c)) {
							IBinaryObject binaryObject = (IBinaryObject) binary.getAdapter(IBinaryObject.class);
							return validateBinary(binaryObject);
						}
					}
				} catch (CModelException _) {
				}
			}
		}
		return null;
	}

	/**
	 * Retrieve the list of binary parsers defined for the given project
	 */
	private List<IBinaryParser> getBinaryParser(IProject project) {
		List<IBinaryParser> parsers = new LinkedList<IBinaryParser>();
		
		ICProjectDescription projDesc = CCorePlugin.getDefault().getProjectDescription(project);
		if (projDesc == null) return parsers;
		ICConfigurationDescription[] cfgs = projDesc.getConfigurations();
		String[] binaryParserIds = CoreModelUtil.getBinaryParserIds(cfgs);
		
		IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(CCorePlugin.PLUGIN_ID, CCorePlugin.BINARY_PARSER_SIMPLE_ID);
		for (String id : binaryParserIds) {
			IExtension extension = extensionPoint.getExtension(id);
			if (extension != null) {
				IConfigurationElement element[] = extension.getConfigurationElements();
				for (IConfigurationElement element2 : element) {
					if (element2.getName().equalsIgnoreCase("cextension")) { //$NON-NLS-1$
						try {
							IBinaryParser parser = (IBinaryParser) element2.createExecutableExtension("run"); //$NON-NLS-1$
							if (parser != null) parsers.add(parser);
						} catch (CoreException _) {
							// TODO: handle exception ?
						}
					}
				}
			}
		}
		return parsers;
	}


}

Back to the top