aboutsummaryrefslogtreecommitdiff
path: root/scripts/irq2nvic_h
blob: d1a8a40f92371fabe766dd4dec84e771f4722d45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python

# This file is part of the libopencm3 project.
# 
# Copyright (C) 2012 chrysn <chrysn@fsfe.org>
# 
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.

"""Generate an nvic.h header from a small YAML file describing the interrupt
numbers.

Code generation is chosen here because the resulting C code needs to be very
repetetive (definition of the IRQ numbers, function prototypes, weak fallback
definition and vector table definition), all being very repetitive. No portable
method to achive the same thing with C preprocessor is known to the author.
(Neither is any non-portable method, for that matter.)"""

import sys
import os
import os.path
import yaml

template_nvic_h = '''\
/* This file is part of the libopencm3 project.
 *
 * It was generated by the irq2nvic_h script.
 */

#ifndef {includeguard}
#define {includeguard}

#include <libopencm3/cm3/nvic.h>

/** @defgroup CM3_nvic_defines_{partname_doxygen} User interrupts for {partname_humanreadable}
    @ingroup CM3_nvic_defines

    @{{*/

{irqdefinitions}

#define NVIC_IRQ_COUNT {irqcount}

/**@}}*/

#define WEAK __attribute__ ((weak))

/** @defgroup CM3_nvic_isrprototypes_{partname_doxygen} User interrupt service routines (ISR) prototypes for {partname_humanreadable}
    @ingroup CM3_nvic_isrprototypes

    @{{*/

BEGIN_DECLS

{isrprototypes}

END_DECLS

/**@}}*/

#endif /* {includeguard} */
'''

template_vector_nvic_c = '''\
/* This file is part of the libopencm3 project.
 *
 * It was generated by the irq2nvic_h script.
 *
 * This part needs to get included in the compilation unit where
 * blocking_handler gets defined due to the way #pragma works.
 */


/** @defgroup CM3_nvic_isrpragmas_{partname_doxygen} User interrupt service routines (ISR) defaults for {partname_humanreadable}
    @ingroup CM3_nvic_isrpragmas

    @{{*/

{isrpragmas}

/**@}}*/

/* Initialization template for the interrupt vector table. This definition is
 * used by the startup code generator (vector.c) to set the initial values for
 * the interrupt handling routines to the chip family specific _isr weak
 * symbols. */

#define IRQ_HANDLERS \\
    {vectortableinitialization}
'''

template_cmsis_h = '''\
/* This file is part of the libopencm3 project.
 *
 * It was generated by the irq2nvic_h script.
 *
 * These definitions bend every interrupt handler that is defined CMSIS style
 * to the weak symbol exported by libopenmc3.
 */

{cmsisbends}
'''

def convert(infile, outfile_nvic, outfile_vectornvic, outfile_cmsis):
    data = yaml.load(infile)

    irq2name = list(enumerate(data['irqs']) if isinstance(data['irqs'], list) else data['irqs'].items())
    irqnames = [v for (k,v) in irq2name]

    if isinstance(data['irqs'], list):
        data['irqcount'] = len(irq2name)
    else:
        data['irqcount'] = max(data['irqs'].keys()) + 1

    data['irqdefinitions'] = "\n".join('#define NVIC_%s_IRQ %d'%(v.upper(),k) for (k,v) in irq2name)
    data['isrprototypes'] = "\n".join('void WEAK %s_isr(void);'%name.lower() for name in irqnames)
    data['isrpragmas'] = "\n".join('#pragma weak %s_isr = blocking_handler'%name.lower() for name in irqnames)
    data['vectortableinitialization'] = ', \\\n    '.join('[NVIC_%s_IRQ] = %s_isr'%(name.upper(), name.lower()) for name in irqnames)
    data['cmsisbends'] = "\n".join("#define %s_IRQHandler %s_isr"%(name.upper(), name.lower()) for name in irqnames)

    outfile_nvic.write(template_nvic_h.format(**data))
    outfile_vectornvic.write(template_vector_nvic_c.format(**data))
    outfile_cmsis.write(template_cmsis_h.format(**data))

def makeparentdir(filename):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError:
        # where is my 'mkdir -p'?
        pass

def needs_update(infiles, outfiles):
    timestamp = lambda filename: os.stat(filename).st_mtime
    return any(not os.path.exists(o) for o in outfiles) or max(map(timestamp, infiles)) > min(map(timestamp, outfiles))

def main():
    if sys.argv[1] == '--remove':
        remove = True
        del sys.argv[1]
    else:
        remove = False
    infile = sys.argv[1]
    if not infile.startswith('./include/libopencm3/') or not infile.endswith('/irq.yaml'):
        raise ValueError("Arguent must match ./include/libopencm3/**/irq.yaml")
    nvic_h = infile.replace('irq.yaml', 'nvic.h')
    vector_nvic_c = infile.replace('./include/libopencm3/', './lib/').replace('irq.yaml', 'vector_nvic.c')
    cmsis = infile.replace('irq.yaml', 'irqhandlers.h').replace('/libopencm3/', '/libopencmsis/')

    if remove:
        if os.path.exists(nvic_h):
            os.unlink(nvic_h)
        if os.path.exists(vector_nvic_c):
            os.unlink(vector_nvic_c)
        sys.exit(0)

    if not needs_update([__file__, infile], [nvic_h, vector_nvic_c]):
        sys.exit(0)

    makeparentdir(nvic_h)
    makeparentdir(vector_nvic_c)
    makeparentdir(cmsis)

    convert(open(infile), open(nvic_h, 'w'), open(vector_nvic_c, 'w'), open(cmsis, 'w'))

if __name__ == "__main__":
    main()