import logging


def _VerifySymbolOrder(orderfile_symbols, symbol_infos, threshold):
  """Verify symbol ordering.

  Checks that the non-section symbols in |orderfile_filename| are consistent
  with the offsets |symbol_infos|.

  Args:
    orderfile_symbols: ([str]) list of symbols from orderfile.
    symbol_infos: ([SymbolInfo]) symbol infos from binary.
    threshold: (int) The number of misordered symbols beyond which we error.

  Returns:
    True iff the ordering is consistent within |threshold|.
  """
  last_offset = 0
  name_to_offset = {si.name: si.offset for si in symbol_infos}
  missing_count = 0
  misorder_count = 0
  misordered_syms = []
  for sym in orderfile_symbols:
    if '.' in sym:
      continue  # sym is a section name.
    if sym not in name_to_offset:
      missing_count += 1
      continue
    next_offset = name_to_offset[sym]
    if next_offset < last_offset:
      misorder_count += 1
      misordered_syms.append((sym, next_offset, last_offset))
    last_offset = next_offset
  logging.warning('Missing symbols in verification: %d', missing_count)
  if misorder_count:
    logging.warning('%d misordered symbols:\n %s', misorder_count,
                    '\n '.join(str(x) for x in misordered_syms[:10]))
    if misorder_count > threshold:
      logging.error('%d misordered symbols over threshold %d, failing',
                    misorder_count, threshold)
      return False
  return True