You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

irq2nvic_h 5.6 KiB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python
  2. # This file is part of the libopencm3 project.
  3. #
  4. # Copyright (C) 2012 chrysn <chrysn@fsfe.org>
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Lesser General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License
  17. # along with this library. If not, see <http://www.gnu.org/licenses/>.
  18. """Generate an nvic.h header from a small JSON file describing the interrupt
  19. numbers.
  20. Code generation is chosen here because the resulting C code needs to be very
  21. repetetive (definition of the IRQ numbers, function prototypes, weak fallback
  22. definition and vector table definition), all being very repetitive. No portable
  23. method to achieve the same thing with C preprocessor is known to the author.
  24. (Neither is any non-portable method, for that matter.)"""
  25. import sys
  26. import os
  27. import os.path
  28. import json
  29. template_nvic_h = '''\
  30. /* This file is part of the libopencm3 project.
  31. *
  32. * It was generated by the irq2nvic_h script from {sourcefile}
  33. */
  34. #ifndef {includeguard}
  35. #define {includeguard}
  36. #include <libopencm3/cm3/nvic.h>
  37. /** @defgroup CM3_nvic_defines_irqs User interrupts for {partname_humanreadable}
  38. @ingroup CM3_nvic_defines
  39. @{{*/
  40. {irqdefinitions}
  41. #define NVIC_IRQ_COUNT {irqcount}
  42. /**@}}*/
  43. /** @defgroup CM3_nvic_isrprototypes_{partname_doxygen} User interrupt service routines (ISR) prototypes for {partname_humanreadable}
  44. @ingroup CM3_nvic_isrprototypes
  45. @{{*/
  46. BEGIN_DECLS
  47. {isrprototypes}
  48. END_DECLS
  49. /**@}}*/
  50. #endif /* {includeguard} */
  51. '''
  52. template_vector_nvic_c = '''\
  53. /* This file is part of the libopencm3 project.
  54. *
  55. * It was generated by the irq2nvic_h script.
  56. *
  57. * This part needs to get included in the compilation unit where
  58. * blocking_handler gets defined due to the way #pragma works.
  59. */
  60. /** @defgroup CM3_nvic_isrdecls_{partname_doxygen} User interrupt service routines (ISR) defaults for {partname_humanreadable}
  61. @ingroup CM3_nvic_isrdecls
  62. @{{*/
  63. {isrdecls}
  64. /**@}}*/
  65. /* Initialization template for the interrupt vector table. This definition is
  66. * used by the startup code generator (vector.c) to set the initial values for
  67. * the interrupt handling routines to the chip family specific _isr weak
  68. * symbols. */
  69. #define IRQ_HANDLERS \\
  70. {vectortableinitialization}
  71. '''
  72. template_cmsis_h = '''\
  73. /* This file is part of the libopencm3 project.
  74. *
  75. * It was generated by the irq2nvic_h script.
  76. *
  77. * These definitions bend every interrupt handler that is defined CMSIS style
  78. * to the weak symbol exported by libopencm3.
  79. */
  80. {cmsisbends}
  81. '''
  82. def convert(infile, outfile_nvic, outfile_vectornvic, outfile_cmsis):
  83. data = json.load(infile)
  84. irq2name = list(enumerate(data['irqs']) if isinstance(data['irqs'], list) else data['irqs'].items())
  85. irqnames = [v for (k,v) in irq2name]
  86. if isinstance(data['irqs'], list):
  87. data['irqcount'] = len(irq2name)
  88. else:
  89. data['irqcount'] = max([int(x) for x in data['irqs'].keys()]) + 1
  90. data['irqdefinitions'] = "\n".join('#define NVIC_%s_IRQ %d'%(v.upper(),int(k)) for (k,v) in irq2name)
  91. data['isrprototypes'] = "\n".join('void %s_isr(void);'%name.lower() for name in irqnames)
  92. data['isrdecls'] = "\n".join('void %s_isr(void) __attribute__((weak, alias("blocking_handler")));'%name.lower() for name in irqnames)
  93. data['vectortableinitialization'] = ', \\\n '.join('[NVIC_%s_IRQ] = %s_isr'%(name.upper(), name.lower()) for name in irqnames)
  94. data['cmsisbends'] = "\n".join("#define %s_IRQHandler %s_isr"%(name.upper(), name.lower()) for name in irqnames)
  95. data['sourcefile'] = infile.name
  96. outfile_nvic.write(template_nvic_h.format(**data))
  97. outfile_vectornvic.write(template_vector_nvic_c.format(**data))
  98. outfile_cmsis.write(template_cmsis_h.format(**data))
  99. def makeparentdir(filename):
  100. try:
  101. os.makedirs(os.path.dirname(filename))
  102. except OSError:
  103. # where is my 'mkdir -p'?
  104. pass
  105. def needs_update(infiles, outfiles):
  106. timestamp = lambda filename: os.stat(filename).st_mtime
  107. return any(not os.path.exists(o) for o in outfiles) or max(map(timestamp, infiles)) > min(map(timestamp, outfiles))
  108. def main():
  109. if sys.argv[1] == '--remove':
  110. remove = True
  111. del sys.argv[1]
  112. else:
  113. remove = False
  114. infile = sys.argv[1]
  115. if not infile.startswith('./include/libopencm3/') or not infile.endswith('/irq.json'):
  116. raise ValueError("Argument must match ./include/libopencm3/**/irq.json")
  117. nvic_h = infile.replace('irq.json', 'nvic.h')
  118. vector_nvic_c = infile.replace('./include/libopencm3/', './lib/').replace('irq.json', 'vector_nvic.c')
  119. cmsis = infile.replace('irq.json', 'irqhandlers.h').replace('/libopencm3/', '/libopencmsis/')
  120. if remove:
  121. if os.path.exists(nvic_h):
  122. os.unlink(nvic_h)
  123. if os.path.exists(vector_nvic_c):
  124. os.unlink(vector_nvic_c)
  125. if os.path.exists(cmsis):
  126. os.unlink(cmsis)
  127. sys.exit(0)
  128. if not needs_update([__file__, infile], [nvic_h, vector_nvic_c]):
  129. sys.exit(0)
  130. makeparentdir(nvic_h)
  131. makeparentdir(vector_nvic_c)
  132. makeparentdir(cmsis)
  133. convert(open(infile), open(nvic_h, 'w'), open(vector_nvic_c, 'w'), open(cmsis, 'w'))
  134. if __name__ == "__main__":
  135. main()