#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Simple mock for addr2line.

Outputs mock symbol information, with each symbol being a function of the
original address (so it is easy to double-check consistency in unittests).
"""

import optparse
import os
import posixpath
import sys
import time


def main(argv):
  parser = optparse.OptionParser()
  parser.add_option('-e', '--exe', dest='exe')  # Path of the debug-library.so.
  # Silently swallow the other unnecessary arguments.
  parser.add_option('-C', '--demangle', action='store_true')
  parser.add_option('-f', '--functions', action='store_true')
  parser.add_option('-i', '--inlines', action='store_true')
  options, _ = parser.parse_args(argv[1:])
  lib_file_name = posixpath.basename(options.exe)
  processed_sym_count = 0
  crash_every = int(os.environ.get('MOCK_A2L_CRASH_EVERY', 0))
  hang_every = int(os.environ.get('MOCK_A2L_HANG_EVERY', 0))

  while(True):
    line = sys.stdin.readline().rstrip('\r')
    if not line:
      break

    # An empty line should generate '??,??:0' (is used as marker for inlines).
    if line == '\n':
      print '??'
      print '??:0'
      sys.stdout.flush()
      continue

    addr = int(line, 16)
    processed_sym_count += 1
    if crash_every and processed_sym_count % crash_every == 0:
      sys.exit(1)
    if hang_every and processed_sym_count % hang_every == 0:
      time.sleep(1)

    # Addresses < 1M will return good mock symbol information.
    if addr < 1024 * 1024:
      print 'mock_sym_for_addr_%d' % addr
      print 'mock_src/%s.c:%d' % (lib_file_name, addr)

    # Addresses 1M <= x < 2M will return symbols with a name but a missing path.
    elif addr < 2 * 1024 * 1024:
      print 'mock_sym_for_addr_%d' % addr
      print '??:0'

    # Addresses 2M <= x < 3M will return unknown symbol information.
    elif addr < 3 * 1024 * 1024:
      print '??'
      print '??'

    # Addresses 3M <= x < 4M will return inlines.
    elif addr < 4 * 1024 * 1024:
      print 'mock_sym_for_addr_%d_inner' % addr
      print 'mock_src/%s.c:%d' % (lib_file_name, addr)
      print 'mock_sym_for_addr_%d_middle' % addr
      print 'mock_src/%s.c:%d' % (lib_file_name, addr)
      print 'mock_sym_for_addr_%d_outer' % addr
      print 'mock_src/%s.c:%d' % (lib_file_name, addr)

    sys.stdout.flush()


if __name__ == '__main__':
  main(sys.argv)