This source file includes following definitions.
- submit
- allRecordsSubmitted
- await
- jitter
- createAddr2LineProcess
- run
- processLocation
- tryDedupe
- createDisambiguationTable
- findInterestingFiles
- poll
- getDisambiguationSuccessCount
- getDisambiguationFailureCount
- getDedupeCount
package org.chromium.tools.binary_size;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
class Addr2LineWorkerPool {
private static final Charset sAscii = Charset.forName("US-ASCII");
private final Addr2LineWorker[] mWorkers;
private final ArrayBlockingQueue<Record> mRecordsIn = new ArrayBlockingQueue<Record>(1000);
private final Queue<Record> mRecordsOut = new ConcurrentLinkedQueue<Record>();
private final CountDownLatch mCompletionLatch;
private final String mAddr2linePath;
private final String mLibraryPath;
private final boolean mDisambiguate;
private final boolean mDedupe;
private final String stripLocation;
private final ConcurrentMap<Long, Record> mAddressesSeen =
new ConcurrentHashMap<Long, Record>(100000, 0.75f, 32);
private volatile Map<String,String> mFileLookupTable = null;
private final AtomicInteger mDisambiguationSuccessCount = new AtomicInteger(0);
private final AtomicInteger mDisambiguationFailureCount = new AtomicInteger(0);
private final AtomicInteger mDedupeCount = new AtomicInteger(0);
private static final String[] INTERESTING_FILE_ENDINGS = new String[]{
".c", ".cc", ".h", ".cp", ".cpp", ".cxx", ".c++", ".asm", ".inc", ".s", ".hxx"
};
Addr2LineWorkerPool(final int size,
final String addr2linePath, final String libraryPath,
final boolean disambiguate, final boolean dedupe)
throws IOException {
this.mAddr2linePath = addr2linePath;
this.mLibraryPath = libraryPath;
this.mDisambiguate = disambiguate;
this.mDedupe = dedupe;
if (disambiguate) {
try {
createDisambiguationTable();
} catch (IOException e) {
throw new RuntimeException("Can't create lookup table", e);
}
}
String canonical = new File(libraryPath).getCanonicalPath();
int end = canonical.lastIndexOf("/src/");
if (end < 0) {
throw new RuntimeException("Bad library path: " + libraryPath +
". Library is expected to be within a build directory.");
}
stripLocation = canonical.substring(0, end + "/src/".length());
mWorkers = new Addr2LineWorker[size];
mCompletionLatch = new CountDownLatch(size);
for (int x = 0; x < mWorkers.length; x++) {
mWorkers[x] = new Addr2LineWorker();
}
}
void submit(Record record) throws InterruptedException {
mRecordsIn.put(record);
}
void allRecordsSubmitted() {
for (Addr2LineWorker worker : mWorkers) {
worker.stopIfQueueIsEmpty = true;
}
}
boolean await(int amount, TimeUnit unit) throws InterruptedException {
return mCompletionLatch.await(amount, unit);
}
private static int jitter(final int value, final int percent) {
Random r = new Random();
int delta = (r.nextBoolean() ? 1 : -1) * r.nextInt((percent * value) / 100);
return value + delta;
}
private class Addr2LineWorker {
private final AtomicReference<Process> processRef = new AtomicReference<Process>();
private final Thread workerThread;
private volatile boolean stopIfQueueIsEmpty = false;
private final int processRecycleThreshold = jitter(2000, 10);
private Addr2LineWorker() throws IOException {
this.processRef.set(createAddr2LineProcess());
workerThread = new Thread(new Addr2LineTask(), "Addr2Line Worker");
workerThread.setDaemon(true);
workerThread.start();
}
private Process createAddr2LineProcess()
throws IOException {
ProcessBuilder builder = new ProcessBuilder(mAddr2linePath, "-e", mLibraryPath, "-f");
Process process = builder.start();
return process;
}
private class Addr2LineTask implements Runnable {
@Override
public void run() {
int processTaskCounter = 0;
InputStream inStream = processRef.get().getInputStream();
Reader isr = new InputStreamReader(inStream);
BufferedReader reader = new BufferedReader(isr);
try {
while (true) {
final Record record = mRecordsIn.poll(1, TimeUnit.SECONDS);
if (record == null) {
if (stopIfQueueIsEmpty) {
return;
}
continue;
}
if (tryDedupe(record)) continue;
final Process process = processRef.get();
if (inStream == null) {
inStream = process.getInputStream();
isr = new InputStreamReader(inStream);
reader = new BufferedReader(isr);
}
process.getOutputStream().write(record.address.getBytes(sAscii));
process.getOutputStream().write('\n');
process.getOutputStream().flush();
final String name = reader.readLine();
if (name == null || name.isEmpty()) {
stopIfQueueIsEmpty = true;
continue;
}
String location = reader.readLine();
if (location == null || location.isEmpty()) {
stopIfQueueIsEmpty = true;
continue;
}
record.resolvedSuccessfully = !(
name.equals("??") && location.equals("??:0"));
if (record.resolvedSuccessfully) {
record.location = processLocation(location);;
}
if (inStream.available() > 0) {
throw new IllegalStateException(
"Alignment mismatch in output from address " + record.address);
}
processTaskCounter++;
mRecordsOut.add(record);
if (processTaskCounter >= processRecycleThreshold) {
try {
processRef.get().destroy();
} catch (Exception e) {
System.err.println("WARNING: zombie process");
e.printStackTrace();
}
try {
processRef.set(createAddr2LineProcess());
} catch (IOException e) {
e.printStackTrace();
}
processTaskCounter = 0;
inStream = null;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
processRef.get().destroy();
} catch (Exception e) {
}
mCompletionLatch.countDown();
}
}
}
private String processLocation(String location) {
if (location.startsWith("/")) {
try {
location = new File(location).getCanonicalPath();
} catch (IOException e) {
System.err.println("Unable to canonicalize path: " + location);
}
} else if (mDisambiguate) {
final int indexOfColon = location.lastIndexOf(':');
final String key;
final String line;
if (indexOfColon != -1) {
key = location.substring(0, indexOfColon);
line = location.substring(indexOfColon + 1);
} else {
key = location;
line = null;
}
final String found = mFileLookupTable.get(key);
if (found != null) {
mDisambiguationSuccessCount.incrementAndGet();
location = found;
if (line != null) location = location + ":" + line;
} else {
mDisambiguationFailureCount.incrementAndGet();
}
}
if (location.startsWith(stripLocation)) {
location = location.substring(stripLocation.length());
}
return location;
}
private boolean tryDedupe(Record record) {
if (mDedupe) {
long addressLong = Long.parseLong(record.address, 16);
Record existing = mAddressesSeen.get(addressLong);
if (existing != null) {
if (!existing.size.equals(record.size)) {
System.err.println("WARNING: Deduped address " +
record.address + " has a size mismatch, " +
existing.size + " != " + record.size);
}
mDedupeCount.incrementAndGet();
return true;
}
if (mAddressesSeen.putIfAbsent(addressLong, record) != null) {
mDedupeCount.incrementAndGet();
return true;
}
}
return false;
}
}
private void createDisambiguationTable() throws IOException {
final File libraryOutputDirectory = new File(mLibraryPath)
.getParentFile().getParentFile().getCanonicalFile();
final File root = libraryOutputDirectory
.getParentFile().getParentFile().getCanonicalFile();
mFileLookupTable = new HashMap<String, String>();
Set<String> dupes = new HashSet<String>();
for (File file : root.listFiles()) {
if (file.isDirectory()) {
String name = file.getName();
if (name.startsWith("out")) {
if (new File(file, "Release").exists() || new File(file, "Debug").exists()) {
continue;
}
} else if (name.startsWith(".")) {
continue;
}
findInterestingFiles(file, dupes);
}
}
findInterestingFiles(new File(libraryOutputDirectory, "gen"), dupes);
findInterestingFiles(new File(libraryOutputDirectory, "obj"), dupes);
for (String dupe : dupes) {
mFileLookupTable.remove(dupe);
}
}
private void findInterestingFiles(File directory, Set<String> dupes) {
for (File file : directory.listFiles()) {
if (file.isDirectory() && file.canRead()) {
if (!file.getName().startsWith(".")) {
findInterestingFiles(file, dupes);
}
} else {
String name = file.getName();
String normalized = name.toLowerCase();
for (String ending : INTERESTING_FILE_ENDINGS) {
if (normalized.endsWith(ending)) {
String other = mFileLookupTable.put(
name, file.getAbsolutePath());
if (other != null) dupes.add(name);
}
}
}
}
}
Record poll() {
return mRecordsOut.poll();
}
int getDisambiguationSuccessCount() {
return mDisambiguationSuccessCount.get();
}
int getDisambiguationFailureCount() {
return mDisambiguationFailureCount.get();
}
int getDedupeCount() {
return mDedupeCount.get();
}