def test_inst(code, inst):
  prgm = code.prgm
  code += inst
  prgm.cache_code()

  nasm_hex_str = get_nasm_output(prgm, inst)
  corepy_hex_str = get_corepy_output(prgm, inst)

  if nasm_hex_str == None:
      print "***************************  NASM ERROR"
      print "corepy output:", corepy_hex_str
      printer.PrintProgram(prgm,
          printer.x86_64_Nasm(show_epilogue = False, show_prologue = False))
      return 'nasm_fail'
  elif nasm_hex_str == corepy_hex_str:
    print "PASS"
    return 'pass'
  else:
    nasm_rex = int(nasm_hex_str[0:2], 16)
    corepy_rex = int(corepy_hex_str[0:2], 16)
    if corepy_rex - nasm_rex == 8 and (nasm_rex & 0xF0 == 0x40):
      print "WARNING CorePy is enabling 64bit for this inst, NASM is not"
      print "nasm output:   ", nasm_hex_str
      print "corepy output: ", corepy_hex_str
      return 'rex_pass'
    else:
      print "***************************  ERROR"
      print "nasm output:   ", nasm_hex_str
      print "corepy output: ", corepy_hex_str
      printer.PrintProgram(prgm,
          printer.x86_64_Nasm(show_epilogue = False, show_prologue = False))
      return 'fail'
  return
def get_nasm_output(prgm, inst):
  """Take an instruction, and return a hex string of its encoding, as encoded by GAS"""
 
  fd = open("x86_64_test.s", "w")
  printer.PrintProgram(prgm, printer.x86_64_Nasm(function_name="_start"), fd = fd)
  fd.close()

  ret = subprocess.call(["nasm", "-Ox", "x86_64_test.s"])
  if ret != 0:
    return

  output = subprocess.Popen(["xxd", "-ps", "x86_64_test"], stdout=subprocess.PIPE).communicate()[0]
  hex = ''.join(output.splitlines())

  # If the prolog/epilog change, these need to be updated
  #startstr = "554889e54157415641554154575653"
  startstr = "554889e5415741564155415453"
  #stopstr = "5b5e5f415c415d415e415fc9c3"
  stopstr = "5b415c415d415e415fc9c3"
  startpos = hex.find(startstr) + len(startstr)
  stoppos = hex.find(stopstr)

  return hex[startpos:stoppos]