#!/usr/bin/env python

import re

rx = re.compile('#define __NR_(.*?)\s+(.*)')
ry = re.compile('\(__NR_(.*?)\+(\d+)\)')

out_cc = file('common/misc/syscall_strings.cc', 'w')
out_py = file('scripts/syscall_strings.py', 'w')

print >> out_cc, '''\
// Automatically generated by %s

#include "syscall_strings.h"

const char * syscall_string(int syscall_number)
{
   switch(syscall_number)
   {
''' % __file__

print >> out_py, '''\
# Automatically generated by %s
''' % __file__

def make(bits):
  seen = set()
  names = {}
  for line in open('/usr/include/asm/unistd_%d.h' % bits, 'r').readlines():
    m = rx.match(line)
    if m:
      name, number = m.group(1), m.group(2)

      mm = ry.match(number)
      if mm:
        number = names[mm.group(1)] + int(mm.group(2))
      else:
        try:
          number = int(number.split()[0])
        except ValueError:
          continue

      if number not in seen:
        seen.add(number)
        names[name] = number
        print >> out_cc, '      case %s: return "%s";' % (number, name)
        print >> out_py, '  %s: "%s",' % (number, name)

print >> out_cc, '#ifdef TARGET_IA32'
print >> out_py, 'syscall_strings_32 = {'
make(32)
print >> out_cc, '#else'
print >> out_py, '}'
print >> out_py, 'syscall_strings_64 = {'
make(64)
print >> out_cc, '#endif'
print >> out_py, '''
}

# Determine whether we're in 32-bit or 64-bit mode
import sys
if sys.maxsize == 2**31-1:
  syscall_strings = syscall_strings_32
else:
  syscall_strings = syscall_strings_64
'''

print >> out_cc, '''\
      default: return "(unknown)";
   }
}
'''
