 (keys(%{$profile})) {
    my $count = $profile->{$k};
    my @addrs = split(/\n/, $k);
    my $matched = 0;
    foreach my $a (@addrs) {
      # Reply if it matches either the address/shortname/fileline
      if (($a =~ m/$ignore/) || SymbolMatches($symbols->{$a}, $ignore)) {
        $matched = 1;
        last;
      }
    }
    if (!$matched) {
      AddEntry($result, $k, $count);
    }
  }
  return $result;
}

# Get total count in profile
sub TotalProfile {
  my $profile = shift;
  my $result = 0;
  foreach my $k (keys(%{$profile})) {
    $result += $profile->{$k};
  }
  return $result;
}

# Add A to B
sub AddProfile {
  my $A = shift;
  my $B = shift;

  my $R = {};
  # add all keys in A
  foreach my $k (keys(%{$A})) {
    my $v = $A->{$k};
    AddEntry($R, $k, $v);
  }
  # add all keys in B
  foreach my $k (keys(%{$B})) {
    my $v = $B->{$k};
    AddEntry($R, $k, $v);
  }
  return $R;
}

# Merges symbol maps
sub MergeSymbols {
  my $A = shift;
  my $B = shift;

  my $R = {};
  foreach my $k (keys(%{$A})) {
    $R->{$k} = $A->{$k};
  }
  if (defined($B)) {
    foreach my $k (keys(%{$B})) {
      $R->{$k} = $B->{$k};
    }
  }
  return $R;
}


# Add A to B
sub AddPcs {
  my $A = shift;
  my $B = shift;

  my $R = {};
  # add all keys in A
  foreach my $k (keys(%{$A})) {
    $R->{$k} = 1
  }
  # add all keys in B
  foreach my $k (keys(%{$B})) {
    $R->{$k} = 1
  }
  return $R;
}

# Subtract B from A
sub SubtractProfile {
  my $A = shift;
  my $B = shift;

  my $R = {};
  foreach my $k (keys(%{$A})) {
    my $v = $A->{$k} - GetEntry($B, $k);
    if ($v < 0 && $main::opt_drop_negative) {
      $v = 0;
    }
    AddEntry($R, $k, $v);
  }
  if (!$main::opt_drop_negative) {
    # Take care of when subtracted profile has more entries
    foreach my $k (keys(%{$B})) {
      if (!exists($A->{$k})) {
        AddEntry($R, $k, 0 - $B->{$k});
      }
    }
  }
  return $R;
}

# Get entry from profile; zero if not present
sub GetEntry {
  my $profile = shift;
  my $k = shift;
  if (exists($profile->{$k})) {
    return $profile->{$k};
  } else {
    return 0;
  }
}

# Add entry to specified profile
sub AddEntry {
  my $profile = shift;
  my $k = shift;
  my $n = shift;
  if (!exists($profile->{$k})) {
    $profile->{$k} = 0;
  }
  $profile->{$k} += $n;
}

# Add a stack of entries to specified profile, and add them to the $pcs
# list.
sub AddEntries {
  my $profile = shift;
  my $pcs = shift;
  my $stack = shift;
  my $count = shift;
  my @k = ();

  foreach my $e (split(/\s+/, $stack)) {
    my $pc = HexExtend($e);
    $pcs->{$pc} = 1;
    push @k, $pc;
  }
  AddEntry($profile, (join "\n", @k), $count);
}

##### Code to profile a server dynamically #####

sub CheckSymbolPage {
  my $url = SymbolPageURL();
  my $command = ShellEscape(@URL_FETCHER, $url);
  open(SYMBOL, "$command |") or error($command);
  my $line = <SYMBOL>;
  $line =~ s/\r//g;         # turn windows-looking lines into unix-looking lines
  close(SYMBOL);
  unless (defined($line)) {
    error("$url doesn't exist\n");
  }

  if ($line =~ /^num_symbols:\s+(\d+)$/) {
    if ($1 == 0) {
      error("Stripped binary. No symbols available.\n");
    }
  } else {
    error("Failed to get the number of symbols from $url\n");
  }
}

sub IsProfileURL {
  my $profile_name = shift;
  if (-f $profile_name) {
    printf STDERR "Using local file $profile_name.\n";
    return 0;
  }
  return 1;
}

sub ParseProfileURL {
  my $profile_name = shift;

  if (!defined($profile_name) || $profile_name eq "") {
    return ();
  }

  # Split profile URL - matches all non-empty strings, so no test.
  $profile_name =~ m,^(https?://)?([^/]+)(.*?)(/|$PROFILES)?$,;

  my $proto = $1 || "http://";
  my $hostport = $2;
  my $prefix = $3;
  my $profile = $4 || "/";

  my $host = $hostport;
  $host =~ s/:.*//;

  my $baseurl = "$proto$hostport$prefix";
  return ($host, $baseurl, $profile);
}

# We fetch symbols from the first profile argument.
sub SymbolPageURL {
  my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
  return "$baseURL$SYMBOL_PAGE";
}

sub FetchProgramName() {
  my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
  my $url = "$baseURL$PROGRAM_NAME_PAGE";
  my $command_line = ShellEscape(@URL_FETCHER, $url);
  open(CMDLINE, "$command_line |") or error($command_line);
  my $cmdline = <CMDLINE>;
  $cmdline =~ s/\r//g;   # turn windows-looking lines into unix-looking lines
  close(CMDLINE);
  error("Failed to get program name from $url\n") unless defined($cmdline);
  $cmdline =~ s/\x00.+//;  # Remove argv[1] and latters.
  $cmdline =~ s!\n!!g;  # Remove LFs.
  return $cmdline;
}

# Gee, curl's -L (--location) option isn't reliable at least
# with its 7.12.3 version.  Curl will forget to post data if
# there is a redirection.  This function is a workaround for
# curl.  Redirection happens on borg hosts.
sub ResolveRedirectionForCurl {
  my $url = shift;
  my $command_line = ShellEscape(@URL_FETCHER, "--head", $url);
  open(CMDLINE, "$command_line |") or error($command_line);
  while (<CMDLINE>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    if (/^Location: (.*)/) {
      $url = $1;
    }
  }
  close(CMDLINE);
  return $url;
}

# Add a timeout flat to URL_FETCHER.  Returns a new list.
sub AddFetchTimeout {
  my $timeout = shift;
  my @fetcher = @_;
  if (defined($timeout)) {
    if (join(" ", @fetcher) =~ m/\bcurl -s/) {
      push(@fetcher, "--max-time", sprintf("%d", $timeout));
    } elsif (join(" ", @fetcher) =~ m/\brpcget\b/) {
      push(@fetcher, sprintf("--deadline=%d", $timeout));
    }
  }
  return @fetcher;
}

# Reads a symbol map from the file handle name given as $1, returning
# the resulting symbol map.  Also processes variables relating to symbols.
# Currently, the only variable processed is 'binary=<value>' which updates
# $main::prog to have the correct program name.
sub ReadSymbols {
  my $in = shift;
  my $map = {};
  while (<$in>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    # Removes all the leading zeroes from the symbols, see comment below.
    if (m/^0x0*([0-9a-f]+)\s+(.+)/) {
      $map->{$1} = $2;
    } elsif (m/^---/) {
      last;
    } elsif (m/^([a-z][^=]*)=(.*)$/ ) {
      my ($variable, $value) = ($1, $2);
      for ($variable, $value) {
        s/^\s+//;
        s/\s+$//;
      }
      if ($variable eq "binary") {
        if ($main::prog ne $UNKNOWN_BINARY && $main::prog ne $value) {
          printf STDERR ("Warning: Mismatched binary name '%s', using '%s'.\n",
                         $main::prog, $value);
        }
        $main::prog = $value;
      } else {
        printf STDERR ("Ignoring unknown variable in symbols list: " .
            "'%s' = '%s'\n", $variable, $value);
      }
    }
  }
  return $map;
}

sub URLEncode {
  my $str = shift;
  $str =~ s/([^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%02x", ord $1 /eg;
  return $str;
}

sub AppendSymbolFilterParams {
  my $url = shift;
  my @params = ();
  if ($main::opt_retain ne '') {
    push(@params, sprintf("retain=%s", URLEncode($main::opt_retain)));
  }
  if ($main::opt_exclude ne '') {
    push(@params, sprintf("exclude=%s", URLEncode($main::opt_exclude)));
  }
  if (scalar @params > 0) {
    $url = sprintf("%s?%s", $url, join("&", @params));
  }
  return $url;
}

# Fetches and processes symbols to prepare them for use in the profile output
# code.  If the optional 'symbol_map' arg is not given, fetches symbols from
# $SYMBOL_PAGE for all PC values found in profile.  Otherwise, the raw symbols
# are assumed to have already been fetched into 'symbol_map' and are simply
# extracted and processed.
sub FetchSymbols {
  my $pcset = shift;
  my $symbol_map = shift;

  my %seen = ();
  my @pcs = grep { !$seen{$_}++ } keys(%$pcset);  # uniq

  if (!defined($symbol_map)) {
    my $post_data = join("+", sort((map {"0x" . "$_"} @pcs)));

    open(POSTFILE, ">$main::tmpfile_sym");
    print POSTFILE $post_data;
    close(POSTFILE);

    my $url = SymbolPageURL();

    my $command_line;
    if (join(" ", @URL_FETCHER) =~ m/\bcurl -s/) {
      $url = ResolveRedirectionForCurl($url);
      $url = AppendSymbolFilterParams($url);
      $command_line = ShellEscape(@URL_FETCHER, "-d", "\@$main::tmpfile_sym",
                                  $url);
    } else {
      $url = AppendSymbolFilterParams($url);
      $command_line = (ShellEscape(@URL_FETCHER, "--post", $url)
                       . " < " . ShellEscape($main::tmpfile_sym));
    }
    # We use c++filt in case $SYMBOL_PAGE gives us mangled symbols.
    my $escaped_cppfilt = ShellEscape($obj_tool_map{"c++filt"});
    open(SYMBOL, "$command_line | $escaped_cppfilt |") or error($command_line);
    $symbol_map = ReadSymbols(*SYMBOL{IO});
    close(SYMBOL);
  }

  my $symbols = {};
  foreach my $pc (@pcs) {
    my $fullname;
    # For 64 bits binaries, symbols are extracted with 8 leading zeroes.
    # Then /symbol reads the long symbols in as uint64, and outputs
    # the result with a "0x%08llx" format which get rid of the zeroes.
    # By removing all the leading zeroes in both $pc and the symbols from
    # /symbol, the symbols match and are retrievable from the map.
    my $shortpc = $pc;
    $shortpc =~ s/^0*//;
    # Each line may have a list of names, which includes the function
    # and also other functions it has inlined.  They are separated (in
    # PrintSymbolizedProfile), by --, which is illegal in function names.
    my $fullnames;
    if (defined($symbol_map->{$shortpc})) {
      $fullnames = $symbol_map->{$shortpc};
    } else {
      $fullnames = "0x" . $pc;  # Just use addresses
    }
    my $sym = [];
    $symbols->{$pc} = $sym;
    foreach my $fullname (split("--", $fullnames)) {
      my $name = ShortFunctionName($fullname);
      push(@{$sym}, $name, "?", $fullname);
    }
  }
  return $symbols;
}

sub BaseName {
  my $file_name = shift;
  $file_name =~ s!^.*/!!;  # Remove directory name
  return $file_name;
}

sub MakeProfileBaseName {
  my ($binary_name, $profile_name) = @_;
  my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
  my $binary_shortname = BaseName($binary_name);
  return sprintf("%s.%s.%s",
                 $binary_shortname, $main::op_time, $host);
}

sub FetchDynamicProfile {
  my $binary_name = shift;
  my $profile_name = shift;
  my $fetch_name_only = shift;
  my $encourage_patience = shift;

  if (!IsProfileURL($profile_name)) {
    return $profile_name;
  } else {
    my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
    if ($path eq "" || $path eq "/") {
      # Missing type specifier defaults to cpu-profile
      $path = $PROFILE_PAGE;
    }

    my $profile_file = MakeProfileBaseName($binary_name, $profile_name);

    my $url = "$baseURL$path";
    my $fetch_timeout = undef;
    if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE/) {
      if ($path =~ m/[?]/) {
        $url .= "&";
      } else {
        $url .= "?";
      }
      $url .= sprintf("seconds=%d", $main::opt_seconds);
      $fetch_timeout = $main::opt_seconds * 1.01 + 60;
      # Set $profile_type for consumption by PrintSymbolizedProfile.
      $main::profile_type = 'cpu';
    } else {
      # For non-CPU profiles, we add a type-extension to
      # the target profile file name.
      my $suffix = $path;
      $suffix =~ s,/,.,g;
      $profile_file .= $suffix;
      # Set $profile_type for consumption by PrintSymbolizedProfile.
      if ($path =~ m/$HEAP_PAGE/) {
        $main::profile_type = 'heap';
      } elsif ($path =~ m/$GROWTH_PAGE/) {
        $main::profile_type = 'growth';
      } elsif ($path =~ m/$CONTENTION_PAGE/) {
        $main::profile_type = 'contention';
      }
    }

    my $profile_dir = $ENV{"JEPROF_TMPDIR"} || ($ENV{HOME} . "/jeprof");
    if (! -d $profile_dir) {
      mkdir($profile_dir)
          || die("Unable to create profile directory $profile_dir: $!\n");
    }
    my $tmp_profile = "$profile_dir/.tmp.$profile_file";
    my $real_profile = "$profile_dir/$profile_file";

    if ($fetch_name_only > 0) {
      return $real_profile;
    }

    my @fetcher = AddFetchTimeout($fetch_timeout, @URL_FETCHER);
    my $cmd = ShellEscape(@fetcher, $url) . " > " . ShellEscape($tmp_profile);
    if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE|$CENSUSPROFILE_PAGE/){
      print STDERR "Gathering CPU profile from $url for $main::opt_seconds seconds to\n  ${real_profile}\n";
      if ($encourage_patience) {
        print STDERR "Be patient...\n";
      }
    } else {
      print STDERR "Fetching $path profile from $url to\n  ${real_profile}\n";
    }

    (system($cmd) == 0) || error("Failed to get profile: $cmd: $!\n");
    (system("mv", $tmp_profile, $real_profile) == 0) || error("Unable to rename profile\n");
    print STDERR "Wrote profile to $real_profile\n";
    $main::collected_profile = $real_profile;
    return $main::collected_profile;
  }
}

# Collect profiles in parallel
sub FetchDynamicProfiles {
  my $items = scalar(@main::pfile_args);
  my $levels = log($items) / log(2);

  if ($items == 1) {
    $main::profile_files[0] = FetchDynamicProfile($main::prog, $main::pfile_args[0], 0, 1);
  } else {
    # math rounding issues
    if ((2 ** $levels) < $items) {
     $levels++;
    }
    my $count = scalar(@main::pfile_args);
    for (my $i = 0; $i < $count; $i++) {
      $main::profile_files[$i] = FetchDynamicProfile($main::prog, $main::pfile_args[$i], 1, 0);
    }
    print STDERR "Fetching $count profiles, Be patient...\n";
    FetchDynamicProfilesRecurse($levels, 0, 0);
    $main::collected_profile = join(" \\\n    ", @main::profile_files);
  }
}

# Recursively fork a process to get enough processes
# collecting profiles
sub FetchDynamicProfilesRecurse {
  my $maxlevel = shift;
  my $level = shift;
  my $position = shift;

  if (my $pid = fork()) {
    $position = 0 | ($position << 1);
    TryCollectProfile($maxlevel, $level, $position);
    wait;
  } else {
    $position = 1 | ($position << 1);
    TryCollectProfile($maxlevel, $level, $position);
    cleanup();
    exit(0);
  }
}

# Collect a single profile
sub TryCollectProfile {
  my $maxlevel = shift;
  my $level = shift;
  my $position = shift;

  if ($level >= ($maxlevel - 1)) {
    if ($position < scalar(@main::pfile_args)) {
      FetchDynamicProfile($main::prog, $main::pfile_args[$position], 0, 0);
    }
  } else {
    FetchDynamicProfilesRecurse($maxlevel, $level+1, $position);
  }
}

##### Parsing code #####

# Provide a small streaming-read module to handle very large
# cpu-profile files.  Stream in chunks along a sliding window.
# Provides an interface to get one 'slot', correctly handling
# endian-ness differences.  A slot is one 32-bit or 64-bit word
# (depending on the input profile).  We tell endianness and bit-size
# for the profile by looking at the first 8 bytes: in cpu profiles,
# the second slot is always 3 (we'll accept anything that's not 0).
BEGIN {
  package CpuProfileStream;

  sub new {
    my ($class, $file, $fname) = @_;
    my $self = { file        => $file,
                 base        => 0,
                 stride      => 512 * 1024,   # must be a multiple of bitsize/8
                 slots       => [],
                 unpack_code => "",           # N for big-endian, V for little
                 perl_is_64bit => 1,          # matters if profile is 64-bit
    };
    bless $self, $class;
    # Let unittests adjust the stride
    if ($main::opt_test_stride > 0) {
      $self->{stride} = $main::opt_test_stride;
    }
    # Read the first two slots to figure out bitsize and endianness.
    my $slots = $self->{slots};
    my $str;
    read($self->{file}, $str, 8);
    # Set the global $address_length based on what we see here.
    # 8 is 32-bit (8 hexadecimal chars); 16 is 64-bit (16 hexadecimal chars).
    $address_length = ($str eq (chr(0)x8)) ? 16 : 8;
    if ($address_length == 8) {
      if (substr($str, 6, 2) eq chr(0)x2) {
        $self->{unpack_code} = 'V';  # Little-endian.
      } elsif (substr($str, 4, 2) eq chr(0)x2) {
        $self->{unpack_code} = 'N';  # Big-endian
      } else {
        ::error("$fname: header size >= 2**16\n");
      }
      @$slots = unpack($self->{unpack_code} . "*", $str);
    } else {
      # If we're a 64-bit profile, check if we're a 64-bit-capable
      # perl.  Otherwise, each slot will be represented as a float
      # instead of an int64, losing precision and making all the
      # 64-bit addresses wrong.  We won't complain yet, but will
      # later if we ever see a value that doesn't fit in 32 bits.
      my $has_q = 0;
      eval { $has_q = pack("Q", "1") ? 1 : 1; };
      if (!$has_q) {
        $self->{perl_is_64bit} = 0;
      }
      read($self->{file}, $str, 8);
      if (substr($str, 4, 4) eq chr(0)x4) {
        # We'd love to use 'Q', but it's a) not universal, b) not endian-proof.
        $self->{unpack_code} = 'V';  # Little-endian.
      } elsif (substr($str, 0, 4) eq chr(0)x4) {
        $self->{unpack_code} = 'N';  # Big-endian
      } else {
        ::error("$fname: header size >= 2**32\n");
      }
      my @pair = unpack($self->{unpack_code} . "*", $str);
      # Since we know one of the pair is 0, it's fine to just add them.
      @$slots = (0, $pair[0] + $pair[1]);
    }
    return $self;
  }

  # Load more data when we access slots->get(X) which is not yet in memory.
  sub overflow {
    my ($self) = @_;
    my $slots = $self->{slots};
    $self->{base} += $#$slots + 1;   # skip over data we're replacing
    my $str;
    read($self->{file}, $str, $self->{stride});
    if ($address_length == 8) {      # the 32-bit case
      # This is the easy case: unpack provides 32-bit unpacking primitives.
      @$slots = unpack($self->{unpack_code} . "*", $str);
    } else {
      # We need to unpack 32 bits at a time and combine.
      my @b32_values = unpack($self->{unpack_code} . "*", $str);
      my @b64_values = ();
      for (my $i = 0; $i < $#b32_values; $i += 2) {
        # TODO(csilvers): if this is a 32-bit perl, the math below
        #    could end up in a too-large int, which perl will promote
        #    to a double, losing necessary precision.  Deal with that.
        #    Right now, we just die.
        my ($lo, $hi) = ($b32_values[$i], $b32_values[$i+1]);
        if ($self->{unpack_code} eq 'N') {    # big-endian
          ($lo, $hi) = ($hi, $lo);
        }
        my $value = $lo + $hi * (2**32);
        if (!$self->{perl_is_64bit} &&   # check value is exactly represented
            (($value % (2**32)) != $lo || int($value / (2**32)) != $hi)) {
          ::error("Need a 64-bit perl to process this 64-bit profile.\n");
        }
        push(@b64_values, $value);
      }
      @$slots = @b64_values;
    }
  }

  # Access the i-th long in the file (logically), or -1 at EOF.
  sub get {
    my ($self, $idx) = @_;
    my $slots = $self->{slots};
    while ($#$slots >= 0) {
      if ($idx < $self->{base}) {
        # The only time we expect a reference to $slots[$i - something]
        # after referencing $slots[$i] is reading the very first header.
        # Since $stride > |header|, that shouldn't cause any lookback
        # errors.  And everything after the header is sequential.
        print STDERR "Unexpected look-back reading CPU profile";
        return -1;   # shrug, don't know what better to return
      } elsif ($idx > $self->{base} + $#$slots) {
        $self->overflow();
      } else {
        return $slots->[$idx - $self->{base}];
      }
    }
    # If we get here, $slots is [], which means we've reached EOF
    return -1;  # unique since slots is supposed to hold unsigned numbers
  }
}

# Reads the top, 'header' section of a profile, and returns the last
# line of the header, commonly called a 'header line'.  The header
# section of a profile consists of zero or more 'command' lines that
# are instructions to jeprof, which jeprof executes when reading the
# header.  All 'command' lines start with a %.  After the command
# lines is the 'header line', which is a profile-specific line that
# indicates what type of profile it is, and perhaps other global
# information about the profile.  For instance, here's a header line
# for a heap profile:
#   heap profile:     53:    38236 [  5525:  1284029] @ heapprofile
# For historical reasons, the CPU profile does not contain a text-
# readable header line.  If the profile looks like a CPU profile,
# this function returns "".  If no header line could be found, this
# function returns undef.
#
# The following commands are recognized:
#   %warn -- emit the rest of this line to stderr, prefixed by 'WARNING:'
#
# The input file should be in binmode.
sub ReadProfileHeader {
  local *PROFILE = shift;
  my $firstchar = "";
  my $line = "";
  read(PROFILE, $firstchar, 1);
  seek(PROFILE, -1, 1);                    # unread the firstchar
  if ($firstchar !~ /[[:print:]]/) {       # is not a text character
    return "";
  }
  while (defined($line = <PROFILE>)) {
    $line =~ s/\r//g;   # turn windows-looking lines into unix-looking lines
    if ($line =~ /^%warn\s+(.*)/) {        # 'warn' command
      # Note this matches both '%warn blah\n' and '%warn\n'.
      print STDERR "WARNING: $1\n";        # print the rest of the line
    } elsif ($line =~ /^%/) {
      print STDERR "Ignoring unknown command from profile header: $line";
    } else {
      # End of commands, must be the header line.
      return $line;
    }
  }
  return undef;     # got to EOF without seeing a header line
}

sub IsSymbolizedProfileFile {
  my $file_name = shift;
  if (!(-e $file_name) || !(-r $file_name)) {
    return 0;
  }
  # Check if the file contains a symbol-section marker.
  open(TFILE, "<$file_name");
  binmode TFILE;
  my $firstline = ReadProfileHeader(*TFILE);
  close(TFILE);
  if (!$firstline) {
    return 0;
  }
  $SYMBOL_PAGE =~ m,[^/]+$,;    # matches everything after the last slash
  my $symbol_marker = $&;
  return $firstline =~ /^--- *$symbol_marker/;
}

# Parse profile generated by common/profiler.cc and return a reference
# to a map:
#      $result->{version}     Version number of profile file
#      $result->{period}      Sampling period (in microseconds)
#      $result->{profile}     Profile object
#      $result->{threads}     Map of thread IDs to profile objects
#      $result->{map}         Memory map info from profile
#      $result->{pcs}         Hash of all PC values seen, key is hex address
sub ReadProfile {
  my $prog = shift;
  my $fname = shift;
  my $result;            # return value

  $CONTENTION_PAGE =~ m,[^/]+$,;    # matches everything after the last slash
  my $contention_marker = $&;
  $GROWTH_PAGE  =~ m,[^/]+$,;    # matches everything after the last slash
  my $growth_marker = $&;
  $SYMBOL_PAGE =~ m,[^/]+$,;    # matches everything after the last slash
  my $symbol_marker = $&;
  $PROFILE_PAGE =~ m,[^/]+$,;    # matches everything after the last slash
  my $profile_marker = $&;
  $HEAP_PAGE =~ m,[^/]+$,;    # matches everything after the last slash
  my $heap_marker = $&;

  # Look at first line to see if it is a heap or a CPU profile.
  # CPU profile may start with no header at all, and just binary data
  # (starting with \0\0\0\0) -- in that case, don't try to read the
  # whole firstline, since it may be gigabytes(!) of data.
  open(PROFILE, "<$fname") || error("$fname: $!\n");
  binmode PROFILE;      # New perls do UTF-8 processing
  my $header = ReadProfileHeader(*PROFILE);
  if (!defined($header)) {   # means "at EOF"
    error("Profile is empty.\n");
  }

  my $symbols;
  if ($header =~ m/^--- *$symbol_marker/o) {
    # Verify that the user asked for a symbolized profile
    if (!$main::use_symbolized_profile) {
      # we have both a binary and symbolized profiles, abort
      error("FATAL ERROR: Symbolized profile\n   $fname\ncannot be used with " .
            "a binary arg. Try again without passing\n   $prog\n");
    }
    # Read the symbol section of the symbolized profile file.
    $symbols = ReadSymbols(*PROFILE{IO});
    # Read the next line to get the header for the remaining profile.
    $header = ReadProfileHeader(*PROFILE) || "";
  }

  if ($header =~ m/^--- *($heap_marker|$growth_marker)/o) {
    # Skip "--- ..." line for profile types that have their own headers.
    $header = ReadProfileHeader(*PROFILE) || "";
  }

  $main::profile_type = '';

  if ($header =~ m/^heap profile:.*$growth_marker/o) {
    $main::profile_type = 'growth';
    $result =  ReadHeapProfile($prog, *PROFILE, $header);
  } elsif ($header =~ m/^heap profile:/) {
    $main::profile_type = 'heap';
    $result =  ReadHeapProfile($prog, *PROFILE, $header);
  } elsif ($header =~ m/^heap/) {
    $main::profile_type = 'heap';
    $result = ReadThreadedHeapProfile($prog, $fname, $header);
  } elsif ($header =~ m/^--- *$contention_marker/o) {
    $main::profile_type = 'contention';
    $result = ReadSynchProfile($prog, *PROFILE);
  } elsif ($header =~ m/^--- *Stacks:/) {
    print STDERR
      "Old format contention profile: mistakenly reports " .
      "condition variable signals as lock contentions.\n";
    $main::profile_type = 'contention';
    $result = ReadSynchProfile($prog, *PROFILE);
  } elsif ($header =~ m/^--- *$profile_marker/) {
    # the binary cpu profile data starts immediately after this line
    $main::profile_type = 'cpu';
    $result = ReadCPUProfile($prog, $fname, *PROFILE);
  } else {
    if (defined($symbols)) {
      # a symbolized profile contains a format we don't recognize, bail out
      error("$fname: Cannot recognize profile section after symbols.\n");
    }
    # no ascii header present -- must be a CPU profile
    $main::profile_type = 'cpu';
    $result = ReadCPUProfile($prog, $fname, *PROFILE);
  }

  close(PROFILE);

  # if we got symbols along with the profile, return those as well
  if (defined($symbols)) {
    $result->{symbols} = $symbols;
  }

  return $result;
}

# Subtract one from caller pc so we map back to call instr.
# However, don't do this if we're reading a symbolized profile
# file, in which case the subtract-one was done when the file
# was written.
#
# We apply the same logic to all readers, though ReadCPUProfile uses an
# independent implementation.
sub FixCallerAddresses {
  my $stack = shift;
  # --raw/http: Always subtract one from pc's, because PrintSymbolizedProfile()
  # dumps unadjusted profiles.
  {
    $stack =~ /(\s)/;
    my $delimiter = $1;
    my @addrs = split(' ', $stack);
    my @fixedaddrs;
    $#fixedaddrs = $#addrs;
    if ($#addrs >= 0) {
      $fixedaddrs[0] = $addrs[0];
    }
    for (my $i = 1; $i <= $#addrs; $i++) {
      $fixedaddrs[$i] = AddressSub($addrs[$i], "0x1");
    }
    return join $delimiter, @fixedaddrs;
  }
}

# CPU profile reader
sub ReadCPUProfile {
  my $prog = shift;
  my $fname = shift;       # just used for logging
  local *PROFILE = shift;
  my $version;
  my $period;
  my $i;
  my $profile = {};
  my $pcs = {};

  # Parse string into array of slots.
  my $slots = CpuProfileStream->new(*PROFILE, $fname);

  # Read header.  The current header version is a 5-element structure
  # containing:
  #   0: header count (always 0)
  #   1: header "words" (after this one: 3)
  #   2: format version (0)
  #   3: sampling period (usec)
  #   4: unused padding (always 0)
  if ($slots->get(0) != 0 ) {
    error("$fname: not a profile file, or old format profile file\n");
  }
  $i = 2 + $slots->get(1);
  $version = $slots->get(2);
  $period = $slots->get(3);
  # Do some sanity checking on these header values.
  if ($version > (2**32) || $period > (2**32) || $i > (2**32) || $i < 5) {
    error("$fname: not a profile file, or corrupted profile file\n");
  }

  # Parse profile
  while ($slots->get($i) != -1) {
    my $n = $slots->get($i++);
    my $d = $slots->get($i++);
    if ($d > (2**16)) {  # TODO(csilvers): what's a reasonable max-stack-depth?
      my $addr = sprintf("0%o", $i * ($address_length == 8 ? 4 : 8));
      print STDERR "At index $i (address $addr):\n";
      error("$fname: stack trace depth >= 2**32\n");
    }
    if ($slots->get($i) == 0) {
      # End of profile data marker
      $i += $d;
      last;
    }

    # Make key out of the stack entries
    my @k = ();
    for (my $j = 0; $j < $d; $j++) {
      my $pc = $slots->get($i+$j);
      # Subtract one from caller pc so we map back to call instr.
      $pc--;
      $pc = sprintf("%0*x", $address_length, $pc);
      $pcs->{$pc} = 1;
      push @k, $pc;
    }

    AddEntry($profile, (join "\n", @k), $n);
    $i += $d;
  }

  # Parse map
  my $map = '';
  seek(PROFILE, $i * 4, 0);
  read(PROFILE, $map, (stat PROFILE)[7]);

  my $r = {};
  $r->{version} = $version;
  $r->{period} = $period;
  $r->{profile} = $profile;
  $r->{libs} = ParseLibraries($prog, $map, $pcs);
  $r->{pcs} = $pcs;

  return $r;
}

sub HeapProfileIndex {
  my $index = 1;
  if ($main::opt_inuse_space) {
    $index = 1;
  } elsif ($main::opt_inuse_objects) {
    $index = 0;
  } elsif ($main::opt_alloc_space) {
    $index = 3;
  } elsif ($main::opt_alloc_objects) {
    $index = 2;
  }
  return $index;
}

sub ReadMappedLibraries {
  my $fh = shift;
  my $map = "";
  # Read the /proc/self/maps data
  while (<$fh>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    $map .= $_;
  }
  return $map;
}

sub ReadMemoryMap {
  my $fh = shift;
  my $map = "";
  # Read /proc/self/maps data as formatted by DumpAddressMap()
  my $buildvar = "";
  while (<PROFILE>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    # Parse "build=<dir>" specification if supplied
    if (m/^\s*build=(.*)\n/) {
      $buildvar = $1;
    }

    # Expand "$build" variable if available
    $_ =~ s/\$build\b/$buildvar/g;

    $map .= $_;
  }
  return $map;
}

sub AdjustSamples {
  my ($sample_adjustment, $sampling_algorithm, $n1, $s1, $n2, $s2) = @_;
  if ($sample_adjustment) {
    if ($sampling_algorithm == 2) {
      # Remote-heap version 2
      # The sampling frequency is the rate of a Poisson process.
      # This means that the probability of sampling an allocation of
      # size X with sampling rate Y is 1 - exp(-X/Y)
      if ($n1 != 0) {
        my $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
        my $scale_factor = 1/(1 - exp(-$ratio));
        $n1 *= $scale_factor;
        $s1 *= $scale_factor;
      }
      if ($n2 != 0) {
        my $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
        my $scale_factor = 1/(1 - exp(-$ratio));
        $n2 *= $scale_factor;
        $s2 *= $scale_factor;
      }
    } else {
      # Remote-heap version 1
      my $ratio;
      $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
      if ($ratio < 1) {
        $n1 /= $ratio;
        $s1 /= $ratio;
      }
      $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
      if ($ratio < 1) {
        $n2 /= $ratio;
        $s2 /= $ratio;
      }
    }
  }
  return ($n1, $s1, $n2, $s2);
}

sub ReadHeapProfile {
  my $prog = shift;
  local *PROFILE = shift;
  my $header = shift;

  my $index = HeapProfileIndex();

  # Find the type of this profile.  The header line looks like:
  #    heap profile:   1246:  8800744 [  1246:  8800744] @ <heap-url>/266053
  # There are two pairs <count: size>, the first inuse objects/space, and the
  # second allocated objects/space.  This is followed optionally by a profile
  # type, and if that is present, optionally by a sampling frequency.
  # For remote heap profiles (v1):
  # The interpretation of the sampling frequency is that the profiler, for
  # each sample, calculates a uniformly distributed random integer less than
  # the given value, and records the next sample after that many bytes have
  # been allocated.  Therefore, the expected sample interval is half of the
  # given frequency.  By default, if not specified, the expected sample
  # interval is 128KB.  Only remote-heap-page profiles are adjusted for
  # sample size.
  # For remote heap profiles (v2):
  # The sampling frequency is the rate of a Poisson process. This means that
  # the probability of sampling an allocation of size X with sampling rate Y
  # is 1 - exp(-X/Y)
  # For version 2, a typical header line might look like this:
  # heap profile:   1922: 127792360 [  1922: 127792360] @ <heap-url>_v2/524288
  # the trailing number (524288) is the sampling rate. (Version 1 showed
  # double the 'rate' here)
  my $sampling_algorithm = 0;
  my $sample_adjustment = 0;
  chomp($header);
  my $type = "unknown";
  if ($header =~ m"^heap profile:\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\](\s*@\s*([^/]*)(/(\d+))?)?") {
    if (defined($6) && ($6 ne '')) {
      $type = $6;
      my $sample_period = $8;
      # $type is "heapprofile" for profiles generated by the
      # heap-profiler, and either "heap" or "heap_v2" for profiles
      # generated by sampling directly within tcmalloc.  It can also
      # be "growth" for heap-growth profiles.  The first is typically
      # found for profiles generated locally, and the others for
      # remote profiles.
      if (($type eq "heapprofile") || ($type !~ /heap/) ) {
        # No need to adjust for the sampling rate with heap-profiler-derived data
        $sampling_algorithm = 0;
      } elsif ($type =~ /_v2/) {
        $sampling_algorithm = 2;     # version 2 sampling
        if (defined($sample_period) && ($sample_period ne '')) {
          $sample_adjustment = int($sample_period);
        }
      } else {
        $sampling_algorithm = 1;     # version 1 sampling
        if (defined($sample_period) && ($sample_period ne '')) {
          $sample_adjustment = int($sample_period)/2;
        }
      }
    } else {
      # We detect whether or not this is a remote-heap profile by checking
      # that the total-allocated stats ($n2,$s2) are exactly the
      # same as the in-use stats ($n1,$s1).  It is remotely conceivable
      # that a non-remote-heap profile may pass this check, but it is hard
      # to imagine how that could happen.
      # In this case it's so old it's guaranteed to be remote-heap version 1.
      my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
      if (($n1 == $n2) && ($s1 == $s2)) {
        # This is likely to be a remote-heap based sample profile
        $sampling_algorithm = 1;
      }
    }
  }

  if ($sampling_algorithm > 0) {
    # For remote-heap generated profiles, adjust the counts and sizes to
    # account for the sample rate (we sample once every 128KB by default).
    if ($sample_adjustment == 0) {
      # Turn on profile adjustment.
      $sample_adjustment = 128*1024;
      print STDERR "Adjusting heap profiles for 1-in-128KB sampling rate\n";
    } else {
      printf STDERR ("Adjusting heap profiles for 1-in-%d sampling rate\n",
                     $sample_adjustment);
    }
    if ($sampling_algorithm > 1) {
      # We don't bother printing anything for the original version (version 1)
      printf STDERR "Heap version $sampling_algorithm\n";
    }
  }

  my $profile = {};
  my $pcs = {};
  my $map = "";

  while (<PROFILE>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    if (/^MAPPED_LIBRARIES:/) {
      $map .= ReadMappedLibraries(*PROFILE);
      last;
    }

    if (/^--- Memory map:/) {
      $map .= ReadMemoryMap(*PROFILE);
      last;
    }

    # Read entry of the form:
    #  <count1>: <bytes1> [<count2>: <bytes2>] @ a1 a2 a3 ... an
    s/^\s*//;
    s/\s*$//;
    if (m/^\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]\s+@\s+(.*)$/) {
      my $stack = $5;
      my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
      my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
                                 $n1, $s1, $n2, $s2);
      AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
    }
  }

  my $r = {};
  $r->{version} = "heap";
  $r->{period} = 1;
  $r->{profile} = $profile;
  $r->{libs} = ParseLibraries($prog, $map, $pcs);
  $r->{pcs} = $pcs;
  return $r;
}

sub ReadThreadedHeapProfile {
  my ($prog, $fname, $header) = @_;

  my $index = HeapProfileIndex();
  my $sampling_algorithm = 0;
  my $sample_adjustment = 0;
  chomp($header);
  my $type = "unknown";
  # Assuming a very specific type of header for now.
  if ($header =~ m"^heap_v2/(\d+)") {
    $type = "_v2";
    $sampling_algorithm = 2;
    $sample_adjustment = int($1);
  }
  if ($type ne "_v2" || !defined($sample_adjustment)) {
    die "Threaded heap profiles require v2 sampling with a sample rate\n";
  }

  my $profile = {};
  my $thread_profiles = {};
  my $pcs = {};
  my $map = "";
  my $stack = "";

  while (<PROFILE>) {
    s/\r//g;
    if (/^MAPPED_LIBRARIES:/) {
      $map .= ReadMappedLibraries(*PROFILE);
      last;
    }

    if (/^--- Memory map:/) {
      $map .= ReadMemoryMap(*PROFILE);
      last;
    }

    # Read entry of the form:
    # @ a1 a2 ... an
    #   t*: <count1>: <bytes1> [<count2>: <bytes2>]
    #   t1: <count1>: <bytes1> [<count2>: <bytes2>]
    #     ...
    #   tn: <count1>: <bytes1> [<count2>: <bytes2>]
    s/^\s*//;
    s/\s*$//;
    if (m/^@\s+(.*)$/) {
      $stack = $1;
    } elsif (m/^\s*(t(\*|\d+)):\s+(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]$/) {
      if ($stack eq "") {
        # Still in the header, so this is just a per-thread summary.
        next;
      }
      my $thread = $2;
      my ($n1, $s1, $n2, $s2) = ($3, $4, $5, $6);
      my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
                                 $n1, $s1, $n2, $s2);
      if ($thread eq "*") {
        AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
      } else {
        if (!exists($thread_profiles->{$thread})) {
          $thread_profiles->{$thread} = {};
        }
        AddEntries($thread_profiles->{$thread}, $pcs,
                   FixCallerAddresses($stack), $counts[$index]);
      }
    }
  }

  my $r = {};
  $r->{version} = "heap";
  $r->{period} = 1;
  $r->{profile} = $profile;
  $r->{threads} = $thread_profiles;
  $r->{libs} = ParseLibraries($prog, $map, $pcs);
  $r->{pcs} = $pcs;
  return $r;
}

sub ReadSynchProfile {
  my $prog = shift;
  local *PROFILE = shift;
  my $header = shift;

  my $map = '';
  my $profile = {};
  my $pcs = {};
  my $sampling_period = 1;
  my $cyclespernanosec = 2.8;   # Default assumption for old binaries
  my $seen_clockrate = 0;
  my $line;

  my $index = 0;
  if ($main::opt_total_delay) {
    $index = 0;
  } elsif ($main::opt_contentions) {
    $index = 1;
  } elsif ($main::opt_mean_delay) {
    $index = 2;
  }

  while ( $line = <PROFILE> ) {
    $line =~ s/\r//g;      # turn windows-looking lines into unix-looking lines
    if ( $line =~ /^\s*(\d+)\s+(\d+) \@\s*(.*?)\s*$/ ) {
      my ($cycles, $count, $stack) = ($1, $2, $3);

      # Convert cycles to nanoseconds
      $cycles /= $cyclespernanosec;

      # Adjust for sampling done by application
      $cycles *= $sampling_period;
      $count *= $sampling_period;

      my @values = ($cycles, $count, $cycles / $count);
      AddEntries($profile, $pcs, FixCallerAddresses($stack), $values[$index]);

    } elsif ( $line =~ /^(slow release).*thread \d+  \@\s*(.*?)\s*$/ ||
              $line =~ /^\s*(\d+) \@\s*(.*?)\s*$/ ) {
      my ($cycles, $stack) = ($1, $2);
      if ($cycles !~ /^\d+$/) {
        next;
      }

      # Convert cycles to nanoseconds
      $cycles /= $cyclespernanosec;

      # Adjust for sampling done by application
      $cycles *= $sampling_period;

      AddEntries($profile, $pcs, FixCallerAddresses($stack), $cycles);

    } elsif ( $line =~ m/^([a-z][^=]*)=(.*)$/ ) {
      my ($variable, $value) = ($1,$2);
      for ($variable, $value) {
        s/^\s+//;
        s/\s+$//;
      }
      if ($variable eq "cycles/second") {
        $cyclespernanosec = $value / 1e9;
        $seen_clockrate = 1;
      } elsif ($variable eq "sampling period") {
        $sampling_period = $value;
      } elsif ($variable eq "ms since reset") {
        # Currently nothing is done with this value in jeprof
        # So we just silently ignore it for now
      } elsif ($variable eq "discarded samples") {
        # Currently nothing is done with this value in jeprof
        # So we just silently ignore it for now
      } else {
        printf STDERR ("Ignoring unnknown variable in /contention output: " .
                       "'%s' = '%s'\n",$variable,$value);
      }
    } else {
      # Memory map entry
      $map .= $line;
    }
  }

  if (!$seen_clockrate) {
    printf STDERR ("No cycles/second entry in profile; Guessing %.1f GHz\n",
                   $cyclespernanosec);
  }

  my $r = {};
  $r->{version} = 0;
  $r->{period} = $sampling_period;
  $r->{profile} = $profile;
  $r->{libs} = ParseLibraries($prog, $map, $pcs);
  $r->{pcs} = $pcs;
  return $r;
}

# Given a hex value in the form "0x1abcd" or "1abcd", return either
# "0001abcd" or "000000000001abcd", depending on the current (global)
# address length.
sub HexExtend {
  my $addr = shift;

  $addr =~ s/^(0x)?0*//;
  my $zeros_needed = $address_length - length($addr);
  if ($zeros_needed < 0) {
    printf STDERR "Warning: address $addr is longer than address length $address_length\n";
    return $addr;
  }
  return ("0" x $zeros_needed) . $addr;
}

##### Symbol extraction #####

# Aggressively search the lib_prefix values for the given library
# If all else fails, just return the name of the library unmodified.
# If the lib_prefix is "/my/path,/other/path" and $file is "/lib/dir/mylib.so"
# it will search the following locations in this order, until it finds a file:
#   /my/path/lib/dir/mylib.so
#   /other/path/lib/dir/mylib.so
#   /my/path/dir/mylib.so
#   /other/path/dir/mylib.so
#   /my/path/mylib.so
#   /other/path/mylib.so
#   /lib/dir/mylib.so              (returned as last resort)
sub FindLibrary {
  my $file = shift;
  my $suffix = $file;

  # Search for the library as described above
  do {
    foreach my $prefix (@prefix_list) {
      my $fullpath = $prefix . $suffix;
      if (-e $fullpath) {
        return $fullpath;
      }
    }
  } while ($suffix =~ s|^/[^/]+/|/|);
  return $file;
}

# Return path to library with debugging symbols.
# For libc libraries, the copy in /usr/lib/debug contains debugging symbols
sub DebuggingLibrary {
  my $file = shift;
      
  if ($file !~ m|^/|) {
    return undef;
  }
      
  # Find debug symbol file if it's named after the library's name.
  
  if (-f "/usr/lib/debug$file") {                 
    if($main::opt_debug) { print STDERR "found debug info for $file in /usr/lib/debug$file\n"; }
    return "/usr/lib/debug$file";
  } elsif (-f "/usr/lib/debug$file.debug") {
    if($main::opt_debug) { print STDERR "found debug info for $file in /usr/lib/debug$file.debug\n"; }
    return "/usr/lib/debug$file.debug"; 
  }

  if(!$main::opt_debug_syms_by_id) {
    if($main::opt_debug) { print STDERR "no debug symbols found for $file\n" };
    return undef;
  }

  # Find debug file if it's named after the library's build ID.
  
  my $readelf = '';
  if (!$main::gave_up_on_elfutils) {
    $readelf = qx/eu-readelf -n ${file}/;
    if ($?) {
      print STDERR "Cannot run eu-readelf. To use --debug-syms-by-id you must be on Linux, with elfutils installed.\n";
      $main::gave_up_on_elfutils = 1;
      return undef;
    }
    my $buildID = $1 if $readelf =~ /Build ID: ([A-Fa-f0-9]+)/s;
    if (defined $buildID && length $buildID > 0) {
      my $symbolFile = '/usr/lib/debug/.build-id/' . substr($buildID, 0, 2) . '/' . substr($buildID, 2) . '.debug';
      if (-e $symbolFile) {
        if($main::opt_debug) { print STDERR "found debug symbol file $symbolFile for $file\n" };
        return $symbolFile;
      } else {
        if($main::opt_debug) { print STDERR "no debug symbol file found for $file, build ID: $buildID\n" };
        return undef;
      }
    }
  }

  if($main::opt_debug) { print STDERR "no debug symbols found for $file, build ID unknown\n" };
  return undef;
}


# Parse text section header of a library using objdump
sub ParseTextSectionHeaderFromObjdump {
  my $lib = shift;

  my $size = undef;
  my $vma;
  my $file_offset;
  # Get objdump output from the library file to figure out how to
  # map between mapped addresses and addresses in the library.
  my $cmd = ShellEscape($obj_tool_map{"objdump"}, "-h", $lib);
  open(OBJDUMP, "$cmd |") || error("$cmd: $!\n");
  while (<OBJDUMP>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    # Idx Name          Size      VMA       LMA       File off  Algn
    #  10 .text         00104b2c  420156f0  420156f0  000156f0  2**4
    # For 64-bit objects, VMA and LMA will be 16 hex digits, size and file
    # offset may still be 8.  But AddressSub below will still handle that.
    my @x = split;
    if (($#x >= 6) && ($x[1] eq '.text')) {
      $size = $x[2];
      $vma = $x[3];
      $file_offset = $x[5];
      last;
    }
  }
  close(OBJDUMP);

  if (!defined($size)) {
    return undef;
  }

  my $r = {};
  $r->{size} = $size;
  $r->{vma} = $vma;
  $r->{file_offset} = $file_offset;

  return $r;
}

# Parse text section header of a library using otool (on OS X)
sub ParseTextSectionHeaderFromOtool {
  my $lib = shift;

  my $size = undef;
  my $vma = undef;
  my $file_offset = undef;
  # Get otool output from the library file to figure out how to
  # map between mapped addresses and addresses in the library.
  my $command = ShellEscape($obj_tool_map{"otool"}, "-l", $lib);
  open(OTOOL, "$command |") || error("$command: $!\n");
  my $cmd = "";
  my $sectname = "";
  my $segname = "";
  foreach my $line (<OTOOL>) {
    $line =~ s/\r//g;      # turn windows-looking lines into unix-looking lines
    # Load command <#>
    #       cmd LC_SEGMENT
    # [...]
    # Section
    #   sectname __text
    #    segname __TEXT
    #       addr 0x000009f8
    #       size 0x00018b9e
    #     offset 2552
    #      align 2^2 (4)
    # We will need to strip off the leading 0x from the hex addresses,
    # and convert the offset into hex.
    if ($line =~ /Load command/) {
      $cmd = "";
      $sectname = "";
      $segname = "";
    } elsif ($line =~ /Section/) {
      $sectname = "";
      $segname = "";
    } elsif ($line =~ /cmd (\w+)/) {
      $cmd = $1;
    } elsif ($line =~ /sectname (\w+)/) {
      $sectname = $1;
    } elsif ($line =~ /segname (\w+)/) {
      $segname = $1;
    } elsif (!(($cmd eq "LC_SEGMENT" || $cmd eq "LC_SEGMENT_64") &&
               $sectname eq "__text" &&
               $segname eq "__TEXT")) {
      next;
    } elsif ($line =~ /\baddr 0x([0-9a-fA-F]+)/) {
      $vma = $1;
    } elsif ($line =~ /\bsize 0x([0-9a-fA-F]+)/) {
      $size = $1;
    } elsif ($line =~ /\boffset ([0-9]+)/) {
      $file_offset = sprintf("%016x", $1);
    }
    if (defined($vma) && defined($size) && defined($file_offset)) {
      last;
    }
  }
  close(OTOOL);

  if (!defined($vma) || !defined($size) || !defined($file_offset)) {
     return undef;
  }

  my $r = {};
  $r->{size} = $size;
  $r->{vma} = $vma;
  $r->{file_offset} = $file_offset;

  return $r;
}

sub ParseTextSectionHeader {
  # obj_tool_map("otool") is only defined if we're in a Mach-O environment
  if (defined($obj_tool_map{"otool"})) {
    my $r = ParseTextSectionHeaderFromOtool(@_);
    if (defined($r)){
      return $r;
    }
  }
  # If otool doesn't work, or we don't have it, fall back to objdump
  return ParseTextSectionHeaderFromObjdump(@_);
}

# Split /proc/pid/maps dump into a list of libraries
sub ParseLibraries {
  return if $main::use_symbol_page;  # We don't need libraries info.
  my $prog = Cwd::abs_path(shift);
  my $map = shift;
  my $pcs = shift;

  my $result = [];
  my $h = "[a-f0-9]+";
  my $zero_offset = HexExtend("0");

  my $buildvar = "";
  foreach my $l (split("\n", $map)) {
    if ($l =~ m/^\s*build=(.*)$/) {
      $buildvar = $1;
    }

    my $start;
    my $finish;
    my $offset;
    my $lib;
    if ($l =~ /^($h)-($h)\s+..x.\s+($h)\s+\S+:\S+\s+\d+\s+(\S+\.(so|dll|dylib|bundle)((\.\d+)+\w*(\.\d+){0,3})?)$/i) {
      # Full line from /proc/self/maps.  Example:
      #   40000000-40015000 r-xp 00000000 03:01 12845071   /lib/ld-2.3.2.so
      $start = HexExtend($1);
      $finish = HexExtend($2);
      $offset = HexExtend($3);
      $lib = $4;
      $lib =~ s|\\|/|g;     # turn windows-style paths into unix-style paths
    } elsif ($l =~ /^\s*($h)-($h):\s*(\S+\.so(\.\d+)*)/) {
      # Cooked line from DumpAddressMap.  Example:
      #   40000000-40015000: /lib/ld-2.3.2.so
      $start = HexExtend($1);
      $finish = HexExtend($2);
      $offset = $zero_offset;
      $lib = $3;
    } elsif (($l =~ /^($h)-($h)\s+..x.\s+($h)\s+\S+:\S+\s+\d+\s+(\S+)$/i) && ($4 eq $prog)) {
      # PIEs and address space randomization do not play well with our
      # default assumption that main executable is at lowest
      # addresses. So we're detecting main executable in
      # /proc/self/maps as well.
      $start = HexExtend($1);
      $finish = HexExtend($2);
      $offset = HexExtend($3);
      $lib = $4;
      $lib =~ s|\\|/|g;     # turn windows-style paths into unix-style paths
    }
    # FreeBSD 10.0 virtual memory map /proc/curproc/map as defined in
    # function procfs_doprocmap (sys/fs/procfs/procfs_map.c)
    #
    # Example:
    # 0x800600000 0x80061a000 26 0 0xfffff800035a0000 r-x 75 33 0x1004 COW NC vnode /libexec/ld-elf.s
    # o.1 NCH -1
    elsif ($l =~ /^(0x$h)\s(0x$h)\s\d+\s\d+\s0x$h\sr-x\s\d+\s\d+\s0x\d+\s(COW|NCO)\s(NC|NNC)\svnode\s(\S+\.so(\.\d+)*)/) {
      $start = HexExtend($1);
      $finish = HexExtend($2);
      $offset = $zero_offset;
      $lib = FindLibrary($5);

    } else {
      next;
    }

    # Expand "$build" variable if available
    $lib =~ s/\$build\b/$buildvar/g;

    $lib = FindLibrary($lib);

    # Check for pre-relocated libraries, which use pre-relocated symbol tables
    # and thus require adjusting the offset that we'll use to translate
    # VM addresses into symbol table addresses.
    # Only do this if we're not going to fetch the symbol table from a
    # debugging copy of the library.
    if (!DebuggingLibrary($lib)) {
      my $text = ParseTextSectionHeader($lib);
      if (defined($text)) {
         my $vma_offset = AddressSub($text->{vma}, $text->{file_offset});
         $offset = AddressAdd($offset, $vma_offset);
      }
    }

    if($main::opt_debug) { printf STDERR "$start:$finish ($offset) $lib\n"; }
    push(@{$result}, [$lib, $start, $finish, $offset]);
  }

  # Append special entry for additional library (not relocated)
  if ($main::opt_lib ne "") {
    my $text = ParseTextSectionHeader($main::opt_lib);
    if (defined($text)) {
       my $start = $text->{vma};
       my $finish = AddressAdd($start, $text->{size});

       push(@{$result}, [$main::opt_lib, $start, $finish, $start]);
    }
  }

  # Append special entry for the main program.  This covers
  # 0..max_pc_value_seen, so that we assume pc values not found in one
  # of the library ranges will be treated as coming from the main
  # program binary.
  my $min_pc = HexExtend("0");
  my $max_pc = $min_pc;          # find the maximal PC value in any sample
  foreach my $pc (keys(%{$pcs})) {
    if (HexExtend($pc) gt $max_pc) { $max_pc = HexExtend($pc); }
  }
  push(@{$result}, [$prog, $min_pc, $max_pc, $zero_offset]);

  return $result;
}

# Add two hex addresses of length $address_length.
# Run jeprof --test for unit test if this is changed.
sub AddressAdd {
  my $addr1 = shift;
  my $addr2 = shift;
  my $sum;

  if ($address_length == 8) {
    # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
    $sum = (hex($addr1)+hex($addr2)) % (0x10000000 * 16);
    return sprintf("%08x", $sum);

  } else {
    # Do the addition in 7-nibble chunks to trivialize carry handling.

    if ($main::opt_debug and $main::opt_test) {
      print STDERR "AddressAdd $addr1 + $addr2 = ";
    }

    my $a1 = substr($addr1,-7);
    $addr1 = substr($addr1,0,-7);
    my $a2 = substr($addr2,-7);
    $addr2 = substr($addr2,0,-7);
    $sum = hex($a1) + hex($a2);
    my $c = 0;
    if ($sum > 0xfffffff) {
      $c = 1;
      $sum -= 0x10000000;
    }
    my $r = sprintf("%07x", $sum);

    $a1 = substr($addr1,-7);
    $addr1 = substr($addr1,0,-7);
    $a2 = substr($addr2,-7);
    $addr2 = substr($addr2,0,-7);
    $sum = hex($a1) + hex($a2) + $c;
    $c = 0;
    if ($sum > 0xfffffff) {
      $c = 1;
      $sum -= 0x10000000;
    }
    $r = sprintf("%07x", $sum) . $r;

    $sum = hex($addr1) + hex($addr2) + $c;
    if ($sum > 0xff) { $sum -= 0x100; }
    $r = sprintf("%02x", $sum) . $r;

    if ($main::opt_debug and $main::opt_test) { print STDERR "$r\n"; }

    return $r;
  }
}


# Subtract two hex addresses of length $address_length.
# Run jeprof --test for unit test if this is changed.
sub AddressSub {
  my $addr1 = shift;
  my $addr2 = shift;
  my $diff;

  if ($address_length == 8) {
    # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
    $diff = (hex($addr1)-hex($addr2)) % (0x10000000 * 16);
    return sprintf("%08x", $diff);

  } else {
    # Do the addition in 7-nibble chunks to trivialize borrow handling.
    # if ($main::opt_debug) { print STDERR "AddressSub $addr1 - $addr2 = "; }

    my $a1 = hex(substr($addr1,-7));
    $addr1 = substr($addr1,0,-7);
    my $a2 = hex(substr($addr2,-7));
    $addr2 = substr($addr2,0,-7);
    my $b = 0;
    if ($a2 > $a1) {
      $b = 1;
      $a1 += 0x10000000;
    }
    $diff = $a1 - $a2;
    my $r = sprintf("%07x", $diff);

    $a1 = hex(substr($addr1,-7));
    $addr1 = substr($addr1,0,-7);
    $a2 = hex(substr($addr2,-7)) + $b;
    $addr2 = substr($addr2,0,-7);
    $b = 0;
    if ($a2 > $a1) {
      $b = 1;
      $a1 += 0x10000000;
    }
    $diff = $a1 - $a2;
    $r = sprintf("%07x", $diff) . $r;

    $a1 = hex($addr1);
    $a2 = hex($addr2) + $b;
    if ($a2 > $a1) { $a1 += 0x100; }
    $diff = $a1 - $a2;
    $r = sprintf("%02x", $diff) . $r;

    # if ($main::opt_debug) { print STDERR "$r\n"; }

    return $r;
  }
}

# Increment a hex addresses of length $address_length.
# Run jeprof --test for unit test if this is changed.
sub AddressInc {
  my $addr = shift;
  my $sum;

  if ($address_length == 8) {
    # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
    $sum = (hex($addr)+1) % (0x10000000 * 16);
    return sprintf("%08x", $sum);

  } else {
    # Do the addition in 7-nibble chunks to trivialize carry handling.
    # We are always doing this to step through the addresses in a function,
    # and will almost never overflow the first chunk, so we check for this
    # case and exit early.

    # if ($main::opt_debug) { print STDERR "AddressInc $addr1 = "; }

    my $a1 = substr($addr,-7);
    $addr = substr($addr,0,-7);
    $sum = hex($a1) + 1;
    my $r = sprintf("%07x", $sum);
    if ($sum <= 0xfffffff) {
      $r = $addr . $r;
      # if ($main::opt_debug) { print STDERR "$r\n"; }
      return HexExtend($r);
    } else {
      $r = "0000000";
    }

    $a1 = substr($addr,-7);
    $addr = substr($addr,0,-7);
    $sum = hex($a1) + 1;
    $r = sprintf("%07x", $sum) . $r;
    if ($sum <= 0xfffffff) {
      $r = $addr . $r;
      # if ($main::opt_debug) { print STDERR "$r\n"; }
      return HexExtend($r);
    } else {
      $r = "00000000000000";
    }

    $sum = hex($addr) + 1;
    if ($sum > 0xff) { $sum -= 0x100; }
    $r = sprintf("%02x", $sum) . $r;

    # if ($main::opt_debug) { print STDERR "$r\n"; }
    return $r;
  }
}

# Extract symbols for all PC values found in profile
sub ExtractSymbols {
  my $libs = shift;
  my $pcset = shift;

  my $symbols = {};

  # Map each PC value to the containing library.  To make this faster,
  # we sort libraries by their starting pc value (highest first), and
  # advance through the libraries as we advance the pc.  Sometimes the
  # addresses of libraries may overlap with the addresses of the main
  # binary, so to make sure the libraries 'win', we iterate over the
  # libraries in reverse order (which assumes the binary doesn't start
  # in the middle of a library, which seems a fair assumption).
  my @pcs = (sort { $a cmp $b } keys(%{$pcset}));  # pcset is 0-extended strings
  foreach my $lib (sort {$b->[1] cmp $a->[1]} @{$libs}) {
    my $libname = $lib->[0];
    my $start = $lib->[1];
    my $finish = $lib->[2];
    my $offset = $lib->[3];

    # Use debug library if it exists
    my $debug_libname = DebuggingLibrary($libname);
    if ($debug_libname) {
        $libname = $debug_libname;
    }

    # Get list of pcs that belong in this library.
    my $contained = [];
    my ($start_pc_index, $finish_pc_index);
    # Find smallest finish_pc_index such that $finish < $pc[$finish_pc_index].
    for ($finish_pc_index = $#pcs + 1; $finish_pc_index > 0;
         $finish_pc_index--) {
      last if $pcs[$finish_pc_index - 1] le $finish;
    }
    # Find smallest start_pc_index such that $start <= $pc[$start_pc_index].
    for ($start_pc_index = $finish_pc_index; $start_pc_index > 0;
         $start_pc_index--) {
      last if $pcs[$start_pc_index - 1] lt $start;
    }
    # This keeps PC values higher than $pc[$finish_pc_index] in @pcs,
    # in case there are overlaps in libraries and the main binary.
    @{$contained} = splice(@pcs, $start_pc_index,
                           $finish_pc_index - $start_pc_index);
    # Map to symbols
    MapToSymbols($libname, AddressSub($start, $offset), $contained, $symbols);
  }

  return $symbols;
}

# Map list of PC values to symbols for a given image
sub MapToSymbols {
  my $image = shift;
  my $offset = shift;
  my $pclist = shift;
  my $symbols = shift;

  my $debug = 0;

  # Ignore empty binaries
  if ($#{$pclist} < 0) { return; }

  # Figure out the addr2line command to use
  my $addr2line = $obj_tool_map{"addr2line"};
  my $cmd = ShellEscape($addr2line, "-f", "-C", "-e", $image);
  if (exists $obj_tool_map{"addr2line_pdb"}) {
    $addr2line = $obj_tool_map{"addr2line_pdb"};
    $cmd = ShellEscape($addr2line, "--demangle", "-f", "-C", "-e", $image);
  }

  # If "addr2line" isn't installed on the system at all, just use
  # nm to get what info we can (function names, but not line numbers).
  if (system(ShellEscape($addr2line, "--help") . " >$dev_null 2>&1") != 0) {
    MapSymbolsWithNM($image, $offset, $pclist, $symbols);
    return;
  }

  # "addr2line -i" can produce a variable number of lines per input
  # address, with no separator that allows us to tell when data for
  # the next address starts.  So we find the address for a special
  # symbol (_fini) and interleave this address between all real
  # addresses passed to addr2line.  The name of this special symbol
  # can then be used as a separator.
  $sep_address = undef;  # May be filled in by MapSymbolsWithNM()
  my $nm_symbols = {};
  MapSymbolsWithNM($image, $offset, $pclist, $nm_symbols);
  if (defined($sep_address)) {
    # Only add " -i" to addr2line if the binary supports it.
    # addr2line --help returns 0, but not if it sees an unknown flag first.
    if (system("$cmd -i --help >$dev_null 2>&1") == 0) {
      $cmd .= " -i";
    } else {
      $sep_address = undef;   # no need for sep_address if we don't support -i
    }
  }

  # Make file with all PC values with intervening 'sep_address' so
  # that we can reliably detect the end of inlined function list
  open(ADDRESSES, ">$main::tmpfile_sym") || error("$main::tmpfile_sym: $!\n");
  if ($debug) { print("---- $image ---\n"); }
  for (my $i = 0; $i <= $#{$pclist}; $i++) {
    # addr2line always reads hex addresses, and does not need '0x' prefix.
    if ($debug) { printf STDERR ("%s\n", $pclist->[$i]); }
    printf ADDRESSES ("%s\n", AddressSub($pclist->[$i], $offset));
    if (defined($sep_address)) {
      printf ADDRESSES ("%s\n", $sep_address);
    }
  }
  close(ADDRESSES);
  if ($debug) {
    print("----\n");
    system("cat", $main::tmpfile_sym);
    print("----\n");
    system("$cmd < " . ShellEscape($main::tmpfile_sym));
    print("----\n");
  }

  open(SYMBOLS, "$cmd <" . ShellEscape($main::tmpfile_sym) . " |")
      || error("$cmd: $!\n");
  my $count = 0;   # Index in pclist
  while (<SYMBOLS>) {
    # Read fullfunction and filelineinfo from next pair of lines
    s/\r?\n$//g;
    my $fullfunction = $_;
    $_ = <SYMBOLS>;
    s/\r?\n$//g;
    my $filelinenum = $_;

    if (defined($sep_address) && $fullfunction eq $sep_symbol) {
      # Terminating marker for data for this address
      $count++;
      next;
    }

    $filelinenum =~ s|\\|/|g; # turn windows-style paths into unix-style paths

    my $pcstr = $pclist->[$count];
    my $function = ShortFunctionName($fullfunction);
    my $nms = $nm_symbols->{$pcstr};
    if (defined($nms)) {
      if ($fullfunction eq '??') {
        # nm found a symbol for us.
        $function = $nms->[0];
        $fullfunction = $nms->[2];
      } else {
	# MapSymbolsWithNM tags each routine with its starting address,
	# useful in case the image has multiple occurrences of this
	# routine.  (It uses a syntax that resembles template parameters,
	# that are automatically stripped out by ShortFunctionName().)
	# addr2line does not provide the same information.  So we check
	# if nm disambiguated our symbol, and if so take the annotated
	# (nm) version of the routine-name.  TODO(csilvers): this won't
	# catch overloaded, inlined symbols, which nm doesn't see.
	# Better would be to do a check similar to nm's, in this fn.
	if ($nms->[2] =~ m/^\Q$function\E/) {  # sanity check it's the right fn
	  $function = $nms->[0];
	  $fullfunction = $nms->[2];
	}
      }
    }

    # Prepend to accumulated symbols for pcstr
    # (so that caller comes before callee)
    my $sym = $symbols->{$pcstr};
    if (!defined($sym)) {
      $sym = [];
      $symbols->{$pcstr} = $sym;
    }
    unshift(@{$sym}, $function, $filelinenum, $fullfunction);
    if ($debug) { printf STDERR ("%s => [%s]\n", $pcstr, join(" ", @{$sym})); }
    if (!defined($sep_address)) {
      # Inlining is off, so this entry ends immediately
      $count++;
    }
  }
  close(SYMBOLS);
}

# Use nm to map the list of referenced PCs to symbols.  Return true iff we
# are able to read procedure information via nm.
sub MapSymbolsWithNM {
  my $image = shift;
  my $offset = shift;
  my $pclist = shift;
  my $symbols = shift;

  # Get nm output sorted by increasing address
  my $symbol_table = GetProcedureBoundaries($image, ".");
  if (!%{$symbol_table}) {
    return 0;
  }
  # Start addresses are already the right length (8 or 16 hex digits).
  my @names = sort { $symbol_table->{$a}->[0] cmp $symbol_table->{$b}->[0] }
    keys(%{$symbol_table});

  if ($#names < 0) {
    # No symbols: just use addresses
    foreach my $pc (@{$pclist}) {
      my $pcstr = "0x" . $pc;
      $symbols->{$pc} = [$pcstr, "?", $pcstr];
    }
    return 0;
  }

  # Sort addresses so we can do a join against nm output
  my $index = 0;
  my $fullname = $names[0];
  my $name = ShortFunctionName($fullname);
  foreach my $pc (sort { $a cmp $b } @{$pclist}) {
    # Adjust for mapped offset
    my $mpc = AddressSub($pc, $offset);
    while (($index < $#names) && ($mpc ge $symbol_table->{$fullname}->[1])){
      $index++;
      $fullname = $names[$index];
      $name = ShortFunctionName($fullname);
    }
    if ($mpc lt $symbol_table->{$fullname}->[1]) {
      $symbols->{$pc} = [$name, "?", $fullname];
    } else {
      my $pcstr = "0x" . $pc;
      $symbols->{$pc} = [$pcstr, "?", $pcstr];
    }
  }
  return 1;
}

sub ShortFunctionName {
  my $function = shift;
  while ($function =~ s/\([^()]*\)(\s*const)?//g) { }   # Argument types
  while ($function =~ s/<[^<>]*>//g)  { }    # Remove template arguments
  $function =~ s/^.*\s+(\w+::)/$1/;          # Remove leading type
  return $function;
}

# Trim overly long symbols found in disassembler output
sub CleanDisassembly {
  my $d = shift;
  while ($d =~ s/\([^()%]*\)(\s*const)?//g) { } # Argument types, not (%rax)
  while ($d =~ s/(\w+)<[^<>]*>/$1/g)  { }       # Remove template arguments
  return $d;
}

# Clean file name for display
sub CleanFileName {
  my ($f) = @_;
  $f =~ s|^/proc/self/cwd/||;
  $f =~ s|^\./||;
  return $f;
}

# Make address relative to section and clean up for display
sub UnparseAddress {
  my ($offset, $address) = @_;
  $address = AddressSub($address, $offset);
  $address =~ s/^0x//;
  $address =~ s/^0*//;
  return $address;
}

##### Miscellaneous #####

# Find the right versions of the above object tools to use.  The
# argument is the program file being analyzed, and should be an ELF
# 32-bit or ELF 64-bit executable file.  The location of the tools
# is determined by considering the following options in this order:
#   1) --tools option, if set
#   2) JEPROF_TOOLS environment variable, if set
#   3) the environment
sub ConfigureObjTools {
  my $prog_file = shift;

  # Check for the existence of $prog_file because /usr/bin/file does not
  # predictably return error status in prod.
  (-e $prog_file)  || error("$prog_file does not exist.\n");

  my $file_type = undef;
  if (-e "/usr/bin/file") {
    # Follow symlinks (at least for systems where "file" supports that).
    my $escaped_prog_file = ShellEscape($prog_file);
    $file_type = `/usr/bin/file -L $escaped_prog_file 2>$dev_null ||
                  /usr/bin/file $escaped_prog_file`;
  } elsif ($^O == "MSWin32") {
    $file_type = "MS Windows";
  } else {
    print STDERR "WARNING: Can't determine the file type of $prog_file";
  }

  if ($file_type =~ /64-bit/) {
    # Change $address_length to 16 if the program file is ELF 64-bit.
    # We can't detect this from many (most?) heap or lock contention
    # profiles, since the actual addresses referenced are generally in low
    # memory even for 64-bit programs.
    $address_length = 16;
  }

  if ($file_type =~ /MS Windows/) {
    # For windows, we provide a version of nm and addr2line as part of
    # the opensource release, which is capable of parsing
    # Windows-style PDB executables.  It should live in the path, or
    # in the same directory as jeprof.
    $obj_tool_map{"nm_pdb"} = "nm-pdb";
    $obj_tool_map{"addr2line_pdb"} = "addr2line-pdb";
  }

  if ($file_type =~ /Mach-O/) {
    # OS X uses otool to examine Mach-O files, rather than objdump.
    $obj_tool_map{"otool"} = "otool";
    $obj_tool_map{"addr2line"} = "false";  # no addr2line
    $obj_tool_map{"objdump"} = "false";  # no objdump
  }

  # Go fill in %obj_tool_map with the pathnames to use:
  foreach my $tool (keys %obj_tool_map) {
    $obj_tool_map{$tool} = ConfigureTool($obj_tool_map{$tool});
  }
}

# Returns the path of a caller-specified object tool.  If --tools or
# JEPROF_TOOLS are specified, then returns the full path to the tool
# with that prefix.  Otherwise, returns the path unmodified (which
# means we will look for it on PATH).
sub ConfigureTool {
  my $tool = shift;
  my $path;

  # --tools (or $JEPROF_TOOLS) is a comma separated list, where each
  # item is either a) a pathname prefix, or b) a map of the form
  # <tool>:<path>.  First we look for an entry of type (b) for our
  # tool.  If one is found, we use it.  Otherwise, we consider all the
  # pathname prefixes in turn, until one yields an existing file.  If
  # none does, we use a default path.
  my $tools = $main::opt_tools || $ENV{"JEPROF_TOOLS"} || "";
  if ($tools =~ m/(,|^)\Q$tool\E:([^,]*)/) {
    $path = $2;
    # TODO(csilvers): sanity-check that $path exists?  Hard if it's relative.
  } elsif ($tools ne '') {
    foreach my $prefix (split(',', $tools)) {
      next if ($prefix =~ /:/);    # ignore "tool:fullpath" entries in the list
      if (-x $prefix . $tool) {
        $path = $prefix . $tool;
        last;
      }
    }
    if (!$path) {
      error("No '$tool' found with prefix specified by " .
            "--tools (or \$JEPROF_TOOLS) '$tools'\n");
    }
  } else {
    # ... otherwise use the version that exists in the same directory as
    # jeprof.  If there's nothing there, use $PATH.
    $0 =~ m,[^/]*$,;     # this is everything after the last slash
    my $dirname = $`;    # this is everything up to and including the last slash
    if (-x "$dirname$tool") {
      $path = "$dirname$tool";
    } else {
      $path = $tool;
    }
  }
  if ($main::opt_debug) { print STDERR "Using '$path' for '$tool'.\n"; }
  return $path;
}

sub ShellEscape {
  my @escaped_words = ();
  foreach my $word (@_) {
    my $escaped_word = $word;
    if ($word =~ m![^a-zA-Z0-9/.,_=-]!) {  # check for anything not in whitelist
      $escaped_word =~ s/'/'\\''/;
      $escaped_word = "'$escaped_word'";
    }
    push(@escaped_words, $escaped_word);
  }
  return join(" ", @escaped_words);
}

sub cleanup {
  unlink($main::tmpfile_sym);
  unlink(keys %main::tempnames);

  # We leave any collected profiles in $HOME/jeprof in case the user wants
  # to look at them later.  We print a message informing them of this.
  if ((scalar(@main::profile_files) > 0) &&
      defined($main::collected_profile)) {
    if (scalar(@main::profile_files) == 1) {
      print STDERR "Dynamically gathered profile is in $main::collected_profile\n";
    }
    print STDERR "If you want to investigate this profile further, you can do:\n";
    print STDERR "\n";
    print STDERR "  jeprof \\\n";
    print STDERR "    $main::prog \\\n";
    print STDERR "    $main::collected_profile\n";
    print STDERR "\n";
  }
}

sub sighandler {
  cleanup();
  exit(1);
}

sub error {
  my $msg = shift;
  print STDERR $msg;
  cleanup();
  exit(1);
}


# Run $nm_command and get all the resulting procedure boundaries whose
# names match "$regexp" and returns them in a hashtable mapping from
# procedure name to a two-element vector of [start address, end address]
sub GetProcedureBoundariesViaNm {
  my $escaped_nm_command = shift;    # shell-escaped
  my $regexp = shift;

  my $symbol_table = {};
  open(NM, "$escaped_nm_command |") || error("$escaped_nm_command: $!\n");
  my $last_start = "0";
  my $routine = "";
  while (<NM>) {
    s/\r//g;         # turn windows-looking lines into unix-looking lines
    if (m/^\s*([0-9a-f]+) (.) (..*)/) {
      my $start_val = $1;
      my $type = $2;
      my $this_routine = $3;

      # It's possible for two symbols to share the same address, if
      # one is a zero-length variable (like __start_google_malloc) or
      # one symbol is a weak alias to another (like __libc_malloc).
      # In such cases, we want to ignore all values except for the
      # actual symbol, which in nm-speak has type "T".  The logic
      # below does this, though it's a bit tricky: what happens when
      # we have a series of lines with the same address, is the first
      # one gets queued up to be processed.  However, it won't
      # *actually* be processed until later, when we read a line with
      # a different address.  That means that as long as we're reading
      # lines with the same address, we have a chance to replace that
      # item in the queue, which we do whenever we see a 'T' entry --
      # that is, a line with type 'T'.  If we never see a 'T' entry,
      # we'll just go ahead and process the first entry (which never
      # got touched in the queue), and ignore the others.
      if ($start_val eq $last_start && $type =~ /t/i) {
        # We are the 'T' symbol at this address, replace previous symbol.
        $routine = $this_routine;
        next;
      } elsif ($start_val eq $last_start) {
        # We're not the 'T' symbol at this address, so ignore us.
        next;
      }

      if ($this_routine eq $sep_symbol) {
        $sep_address = HexExtend($start_val);
      }

      # Tag this routine with the starting address in case the image
      # has multiple occurrences of this routine.  We use a syntax
      # that resembles template parameters that are automatically
      # stripped out by ShortFunctionName()
      $this_routine .= "<$start_val>";

      if (defined($routine) && $routine =~ m/$regexp/) {
        $symbol_table->{$routine} = [HexExtend($last_start),
                                     HexExtend($start_val)];
      }
      $last_start = $start_val;
      $routine = $this_routine;
    } elsif (m/^Loaded image name: (.+)/) {
      # The win32 nm workalike emits information about the binary it is using.
      if ($main::opt_debug) { print STDERR "Using Image $1\n"; }
    } elsif (m/^PDB file name: (.+)/) {
      # The win32 nm workalike emits information about the pdb it is using.
      if ($main::opt_debug) { print STDERR "Using PDB $1\n"; }
    }
  }
  close(NM);
  # Handle the last line in the nm output.  Unfortunately, we don't know
  # how big this last symbol is, because we don't know how big the file
  # is.  For now, we just give it a size of 0.
  # TODO(csilvers): do better here.
  if (defined($routine) && $routine =~ m/$regexp/) {
    $symbol_table->{$routine} = [HexExtend($last_start),
                                 HexExtend($last_start)];
  }
  return $symbol_table;
}

# Gets the procedure boundaries for all routines in "$image" whose names
# match "$regexp" and returns them in a hashtable mapping from procedure
# name to a two-element vector of [start address, end address].
# Will return an empty map if nm is not installed or not working properly.
sub GetProcedureBoundaries {
  my $image = shift;
  my $regexp = shift;

  # If $image doesn't start with /, then put ./ in front of it.  This works
  # around an obnoxious bug in our probing of nm -f behavior.
  # "nm -f $image" is supposed to fail on GNU nm, but if:
  #
  # a. $image starts with [BbSsPp] (for example, bin/foo/bar), AND
  # b. you have a.out in your current directory (a not uncommon occurrence)
  #
  # then "nm -f $image" succeeds because -f only looks at the first letter of
  # the argument, which looks valid because it's [BbSsPp], and then since
  # there's no image provided, it looks for a.out and finds it.
  #
  # This regex makes sure that $image starts with . or /, forcing the -f
  # parsing to fail since . and / are not valid formats.
  $image =~ s#^[^/]#./$&#;

  # For libc libraries, the copy in /usr/lib/debug contains debugging symbols
  my $debugging = DebuggingLibrary($image);
  if ($debugging) {
    $image = $debugging;
  }

  my $nm = $obj_tool_map{"nm"};
  my $cppfilt = $obj_tool_map{"c++filt"};

  # nm can fail for two reasons: 1) $image isn't a debug library; 2) nm
  # binary doesn't support --demangle.  In addition, for OS X we need
  # to use the -f flag to get 'flat' nm output (otherwise we don't sort
  # properly and get incorrect results).  Unfortunately, GNU nm uses -f
  # in an incompatible way.  So first we test whether our nm supports
  # --demangle and -f.
  my $demangle_flag = "";
  my $cppfilt_flag = "";
  my $to_devnull = ">$dev_null 2>&1";
  if (system(ShellEscape($nm, "--demangle", $image) . $to_devnull) == 0) {
    # In this mode, we do "nm --demangle <foo>"
    $demangle_flag = "--demangle";
    $cppfilt_flag = "";
  } elsif (system(ShellEscape($cppfilt, $image) . $to_devnull) == 0) {
    # In this mode, we do "nm <foo> | c++filt"
    $cppfilt_flag = " | " . ShellEscape($cppfilt);
  };
  my $flatten_flag = "";
  if (system(ShellEscape($nm, "-f", $image) . $to_devnull) == 0) {
    $flatten_flag = "-f";
  }

  # Finally, in the case $imagie isn't a debug library, we try again with
  # -D to at least get *exported* symbols.  If we can't use --demangle,
  # we use c++filt instead, if it exists on this system.
  my @nm_commands = (ShellEscape($nm, "-n", $flatten_flag, $demangle_flag,
                                 $image) . " 2>$dev_null $cppfilt_flag",
                     ShellEscape($nm, "-D", "-n", $flatten_flag, $demangle_flag,
                                 $image) . " 2>$dev_null $cppfilt_flag",
                     # 6nm is for Go binaries
                     ShellEscape("6nm", "$image") . " 2>$dev_null | sort",
                     );

  # If the executable is an MS Windows PDB-format executable, we'll
  # have set up obj_tool_map("nm_pdb").  In this case, we actually
  # want to use both unix nm and windows-specific nm_pdb, since
  # PDB-format executables can apparently include dwarf .o files.
  if (exists $obj_tool_map{"nm_pdb"}) {
    push(@nm_commands,
         ShellEscape($obj_tool_map{"nm_pdb"}, "--demangle", $image)
         . " 2>$dev_null");
  }

  foreach my $nm_command (@nm_commands) {
    my $symbol_table = GetProcedureBoundariesViaNm($nm_command, $regexp);
    return $symbol_table if (%{$symbol_table});
  }
  my $symbol_table = {};
  return $symbol_table;
}


# The test vectors for AddressAdd/Sub/Inc are 8-16-nibble hex strings.
# To make them more readable, we add underscores at interesting places.
# This routine removes the underscores, producing the canonical representation
# used by jeprof to represent addresses, particularly in the tested routines.
sub CanonicalHex {
  my $arg = shift;
  return join '', (split '_',$arg);
}


# Unit test for AddressAdd:
sub AddressAddUnitTest {
  my $test_data_8 = shift;
  my $test_data_16 = shift;
  my $error_count = 0;
  my $fail_count = 0;
  my $pass_count = 0;
  # print STDERR "AddressAddUnitTest: ", 1+$#{$test_data_8}, " tests\n";

  # First a few 8-nibble addresses.  Note that this implementation uses
  # plain old arithmetic, so a quick sanity check along with verifying what
  # happens to overflow (we want it to wrap):
  $address_length = 8;
  foreach my $row (@{$test_data_8}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressAdd ($row->[0], $row->[1]);
    if ($sum ne $row->[2]) {
      printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
             $row->[0], $row->[1], $row->[2];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressAdd 32-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count = $fail_count;
  $fail_count = 0;
  $pass_count = 0;

  # Now 16-nibble addresses.
  $address_length = 16;
  foreach my $row (@{$test_data_16}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressAdd (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
    my $expected = join '', (split '_',$row->[2]);
    if ($sum ne CanonicalHex($row->[2])) {
      printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
             $row->[0], $row->[1], $row->[2];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressAdd 64-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count += $fail_count;

  return $error_count;
}


# Unit test for AddressSub:
sub AddressSubUnitTest {
  my $test_data_8 = shift;
  my $test_data_16 = shift;
  my $error_count = 0;
  my $fail_count = 0;
  my $pass_count = 0;
  # print STDERR "AddressSubUnitTest: ", 1+$#{$test_data_8}, " tests\n";

  # First a few 8-nibble addresses.  Note that this implementation uses
  # plain old arithmetic, so a quick sanity check along with verifying what
  # happens to overflow (we want it to wrap):
  $address_length = 8;
  foreach my $row (@{$test_data_8}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressSub ($row->[0], $row->[1]);
    if ($sum ne $row->[3]) {
      printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
             $row->[0], $row->[1], $row->[3];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressSub 32-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count = $fail_count;
  $fail_count = 0;
  $pass_count = 0;

  # Now 16-nibble addresses.
  $address_length = 16;
  foreach my $row (@{$test_data_16}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressSub (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
    if ($sum ne CanonicalHex($row->[3])) {
      printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
             $row->[0], $row->[1], $row->[3];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressSub 64-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count += $fail_count;

  return $error_count;
}


# Unit test for AddressInc:
sub AddressIncUnitTest {
  my $test_data_8 = shift;
  my $test_data_16 = shift;
  my $error_count = 0;
  my $fail_count = 0;
  my $pass_count = 0;
  # print STDERR "AddressIncUnitTest: ", 1+$#{$test_data_8}, " tests\n";

  # First a few 8-nibble addresses.  Note that this implementation uses
  # plain old arithmetic, so a quick sanity check along with verifying what
  # happens to overflow (we want it to wrap):
  $address_length = 8;
  foreach my $row (@{$test_data_8}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressInc ($row->[0]);
    if ($sum ne $row->[4]) {
      printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
             $row->[0], $row->[4];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressInc 32-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count = $fail_count;
  $fail_count = 0;
  $pass_count = 0;

  # Now 16-nibble addresses.
  $address_length = 16;
  foreach my $row (@{$test_data_16}) {
    if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
    my $sum = AddressInc (CanonicalHex($row->[0]));
    if ($sum ne CanonicalHex($row->[4])) {
      printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
             $row->[0], $row->[4];
      ++$fail_count;
    } else {
      ++$pass_count;
    }
  }
  printf STDERR "AddressInc 64-bit tests: %d passes, %d failures\n",
         $pass_count, $fail_count;
  $error_count += $fail_count;

  return $error_count;
}


# Driver for unit tests.
# Currently just the address add/subtract/increment routines for 64-bit.
sub RunUnitTests {
  my $error_count = 0;

  # This is a list of tuples [a, b, a+b, a-b, a+1]
  my $unit_test_data_8 = [
    [qw(aaaaaaaa 50505050 fafafafa 5a5a5a5a aaaaaaab)],
    [qw(50505050 aaaaaaaa fafafafa a5a5a5a6 50505051)],
    [qw(ffffffff aaaaaaaa aaaaaaa9 55555555 00000000)],
    [qw(00000001 ffffffff 00000000 00000002 00000002)],
    [qw(00000001 fffffff0 fffffff1 00000011 00000002)],
  ];
  my $unit_test_data_16 = [
    # The implementation handles data in 7-nibble chunks, so those are the
    # interesting boundaries.
    [qw(aaaaaaaa 50505050
        00_000000f_afafafa 00_0000005_a5a5a5a 00_000000a_aaaaaab)],
    [qw(50505050 aaaaaaaa
        00_000000f_afafafa ff_ffffffa_5a5a5a6 00_0000005_0505051)],
    [qw(ffffffff aaaaaaaa
        00_000001a_aaaaaa9 00_0000005_5555555 00_0000010_0000000)],
    [qw(00000001 ffffffff
        00_0000010_0000000 ff_ffffff0_0000002 00_0000000_0000002)],
    [qw(00000001 fffffff0
        00_000000f_ffffff1 ff_ffffff0_0000011 00_0000000_0000002)],

    [qw(00_a00000a_aaaaaaa 50505050
        00_a00000f_afafafa 00_a000005_a5a5a5a 00_a00000a_aaaaaab)],
    [qw(0f_fff0005_0505050 aaaaaaaa
        0f_fff000f_afafafa 0f_ffefffa_5a5a5a6 0f_fff0005_0505051)],
    [qw(00_000000f_fffffff 01_800000a_aaaaaaa
        01_800001a_aaaaaa9 fe_8000005_5555555 00_0000010_0000000)],
    [qw(00_0000000_0000001 ff_fffffff_fffffff
        00_0000000_0000000 00_0000000_0000002 00_0000000_0000002)],
    [qw(00_0000000_0000001 ff_fffffff_ffffff0
        ff_fffffff_ffffff1 00_0000000_0000011 00_0000000_0000002)],
  ];

  $error_count += AddressAddUnitTest($unit_test_data_8, $unit_test_data_16);
  $error_count += AddressSubUnitTest($unit_test_data_8, $unit_test_data_16);
  $error_count += AddressIncUnitTest($unit_test_data_8, $unit_test_data_16);
  if ($error_count > 0) {
    print STDERR $error_count, " errors: FAILED\n";
  } else {
    print STDERR "PASS\n";
  }
  exit ($error_count);
}
