-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathgen-device-svd.go
More file actions
executable file
·1509 lines (1383 loc) · 44.1 KB
/
Copy pathgen-device-svd.go
File metadata and controls
executable file
·1509 lines (1383 loc) · 44.1 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"encoding/xml"
"errors"
"flag"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"unicode"
)
var validName = regexp.MustCompile("^[a-zA-Z0-9_]+$")
var enumBitSpecifier = regexp.MustCompile("^#x*[01]+[01x]*$")
type SVDFile struct {
XMLName xml.Name `xml:"device"`
Name string `xml:"name"`
Description string `xml:"description"`
LicenseText string `xml:"licenseText"`
CPU *struct {
Name string `xml:"name"`
FPUPresent bool `xml:"fpuPresent"`
NVICPrioBits int `xml:"nvicPrioBits"`
} `xml:"cpu"`
Peripherals []SVDPeripheral `xml:"peripherals>peripheral"`
}
type SVDPeripheral struct {
Name string `xml:"name"`
Description string `xml:"description"`
BaseAddress string `xml:"baseAddress"`
GroupName string `xml:"groupName"`
DerivedFrom string `xml:"derivedFrom,attr"`
Interrupts []struct {
Name string `xml:"name"`
Index int `xml:"value"`
} `xml:"interrupt"`
Registers []*SVDRegister `xml:"registers>register"`
Clusters []*SVDCluster `xml:"registers>cluster"`
}
type SVDRegister struct {
Name string `xml:"name"`
Description string `xml:"description"`
Dim *string `xml:"dim"`
DimIndex *string `xml:"dimIndex"`
DimIncrement string `xml:"dimIncrement"`
Size *string `xml:"size"`
Fields []*SVDField `xml:"fields>field"`
Offset *string `xml:"offset"`
AddressOffset *string `xml:"addressOffset"`
}
type SVDField struct {
Name string `xml:"name"`
Description string `xml:"description"`
Lsb *uint32 `xml:"lsb"`
Msb *uint32 `xml:"msb"`
BitOffset *uint32 `xml:"bitOffset"`
BitWidth *uint32 `xml:"bitWidth"`
BitRange *string `xml:"bitRange"`
EnumeratedValues struct {
DerivedFrom string `xml:"derivedFrom,attr"`
Name string `xml:"name"`
EnumeratedValue []struct {
Name string `xml:"name"`
Description string `xml:"description"`
Value string `xml:"value"`
} `xml:"enumeratedValue"`
} `xml:"enumeratedValues"`
}
type SVDCluster struct {
Dim *int `xml:"dim"`
DimIncrement string `xml:"dimIncrement"`
DimIndex *string `xml:"dimIndex"`
Name string `xml:"name"`
Description string `xml:"description"`
Registers []*SVDRegister `xml:"register"`
Clusters []*SVDCluster `xml:"cluster"`
AddressOffset string `xml:"addressOffset"`
}
type Device struct {
Metadata *Metadata
Interrupts []*Interrupt
Peripherals []*Peripheral
PeripheralDict map[string]*Peripheral
}
type Metadata struct {
File string
DescriptorSource string
Name string
NameLower string
Description string
LicenseBlock string
HasCPUInfo bool // set if the following fields are populated
CPUName string
FPUPresent bool
NVICPrioBits int
}
type Interrupt struct {
Name string
HandlerName string
PeripheralIndex int
Value int // interrupt number
Description string
}
type Peripheral struct {
Name string
GroupName string
BaseAddress uint64
Description string
ClusterName string
Registers []*PeripheralField
Subtypes []*Peripheral
}
// A PeripheralField is a single field in a peripheral type. It may be a full
// peripheral or a cluster within a peripheral.
type PeripheralField struct {
Name string
Address uint64
Description string
Registers []*PeripheralField // contains fields if this is a cluster
Array int
ElementSize int
Constants []Constant
ShortName string // name stripped of "spaced array" suffix
Bitfields []Bitfield // set of bit-fields provided by this
HasBitfields bool // set true when Bitfields was set for a first PeripheralField of "spaced array".
}
type Constant struct {
Name string
Description string
Value uint64
}
type Bitfield struct {
Name string
Offset uint32
Mask uint32
}
func formatText(text string) string {
text = regexp.MustCompile(`[ \t\n]+`).ReplaceAllString(text, " ") // Collapse whitespace (like in HTML)
text = strings.ReplaceAll(text, "\\n ", "\n")
text = strings.TrimSpace(text)
return text
}
func isMultiline(s string) bool {
return strings.Index(s, "\n") >= 0
}
func splitLine(s string) []string {
return strings.Split(s, "\n")
}
// Replace characters that are not allowed in a symbol name with a '_'. This is
// useful to be able to process SVD files with errors.
func cleanName(text string) string {
if !validName.MatchString(text) {
result := make([]rune, 0, len(text))
for _, c := range text {
if validName.MatchString(string(c)) {
result = append(result, c)
} else {
result = append(result, '_')
}
}
text = string(result)
}
if len(text) != 0 && (text[0] >= '0' && text[0] <= '9') {
// Identifiers may not start with a number.
// Add an underscore instead.
text = "_" + text
}
return text
}
func processSubCluster(p *Peripheral, cluster *SVDCluster, clusterOffset uint64, clusterName string, peripheralDict map[string]*Peripheral) []*Peripheral {
var peripheralsList []*Peripheral
clusterPrefix := clusterName + "_"
cpRegisters := []*PeripheralField{}
for _, regEl := range cluster.Registers {
cpRegisters = append(cpRegisters, parseRegister(p.GroupName, regEl, p.BaseAddress+clusterOffset, clusterPrefix)...)
}
// handle sub-clusters of registers
for _, subClusterEl := range cluster.Clusters {
subclusterName := strings.ReplaceAll(subClusterEl.Name, "[%s]", "")
subclusterPrefix := subclusterName + "_"
subclusterOffset, err := strconv.ParseUint(subClusterEl.AddressOffset, 0, 32)
if err != nil {
panic(err)
}
subdim := *subClusterEl.Dim
subdimIncrement, err := strconv.ParseInt(subClusterEl.DimIncrement, 0, 32)
if err != nil {
panic(err)
}
if subdim > 1 {
subcpRegisters := []*PeripheralField{}
for _, regEl := range subClusterEl.Registers {
subcpRegisters = append(subcpRegisters, parseRegister(p.GroupName, regEl, p.BaseAddress+clusterOffset+subclusterOffset, subclusterPrefix)...)
}
cpRegisters = append(cpRegisters, &PeripheralField{
Name: subclusterName,
Address: p.BaseAddress + clusterOffset + subclusterOffset,
Description: subClusterEl.Description,
Registers: subcpRegisters,
Array: subdim,
ElementSize: int(subdimIncrement),
ShortName: clusterPrefix + subclusterName,
})
} else {
for _, regEl := range subClusterEl.Registers {
cpRegisters = append(cpRegisters, parseRegister(regEl.Name, regEl, p.BaseAddress+clusterOffset+subclusterOffset, subclusterPrefix)...)
}
}
}
sort.SliceStable(cpRegisters, func(i, j int) bool {
return cpRegisters[i].Address < cpRegisters[j].Address
})
clusterPeripheral := &Peripheral{
Name: p.Name + "_" + clusterName,
GroupName: p.GroupName + "_" + clusterName,
Description: p.Description + " - " + clusterName,
ClusterName: clusterName,
BaseAddress: p.BaseAddress + clusterOffset,
Registers: cpRegisters,
}
peripheralsList = append(peripheralsList, clusterPeripheral)
peripheralDict[clusterPeripheral.Name] = clusterPeripheral
p.Subtypes = append(p.Subtypes, clusterPeripheral)
return peripheralsList
}
func processCluster(p *Peripheral, clusters []*SVDCluster, peripheralDict map[string]*Peripheral) []*Peripheral {
var peripheralsList []*Peripheral
for _, cluster := range clusters {
clusterName := strings.ReplaceAll(cluster.Name, "[%s]", "")
if cluster.DimIndex != nil {
clusterName = strings.ReplaceAll(clusterName, "%s", "")
}
clusterPrefix := clusterName + "_"
clusterOffset, err := strconv.ParseUint(cluster.AddressOffset, 0, 32)
if err != nil {
panic(err)
}
var dim, dimIncrement int
if cluster.Dim == nil {
// Nordic SVD have sub-clusters with another sub-clusters.
if clusterOffset == 0 || len(cluster.Clusters) > 0 {
peripheralsList = append(peripheralsList, processSubCluster(p, cluster, clusterOffset, clusterName, peripheralDict)...)
continue
}
dim = -1
dimIncrement = -1
} else {
dim = *cluster.Dim
if dim == 1 {
dimIncrement = -1
} else {
inc, err := strconv.ParseUint(cluster.DimIncrement, 0, 32)
if err != nil {
panic(err)
}
dimIncrement = int(inc)
}
}
clusterRegisters := []*PeripheralField{}
for _, regEl := range cluster.Registers {
regName := p.GroupName
if regName == "" {
regName = p.Name
}
clusterRegisters = append(clusterRegisters, parseRegister(regName, regEl, p.BaseAddress+clusterOffset, clusterPrefix)...)
}
sort.SliceStable(clusterRegisters, func(i, j int) bool {
return clusterRegisters[i].Address < clusterRegisters[j].Address
})
if dimIncrement == -1 && len(clusterRegisters) > 0 {
lastReg := clusterRegisters[len(clusterRegisters)-1]
lastAddress := lastReg.Address
if lastReg.Array != -1 {
lastAddress = lastReg.Address + uint64(lastReg.Array*lastReg.ElementSize)
}
firstAddress := clusterRegisters[0].Address
dimIncrement = int(lastAddress - firstAddress)
}
if !unicode.IsUpper(rune(clusterName[0])) && !unicode.IsDigit(rune(clusterName[0])) {
clusterName = strings.ToUpper(clusterName)
}
p.Registers = append(p.Registers, &PeripheralField{
Name: clusterName,
Address: p.BaseAddress + clusterOffset,
Description: cluster.Description,
Registers: clusterRegisters,
Array: dim,
ElementSize: dimIncrement,
ShortName: clusterName,
})
}
sort.SliceStable(p.Registers, func(i, j int) bool {
return p.Registers[i].Address < p.Registers[j].Address
})
return peripheralsList
}
// Read ARM SVD files.
func readSVD(path, sourceURL string) (*Device, error) {
// Open the XML file.
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
decoder := xml.NewDecoder(f)
device := &SVDFile{}
err = decoder.Decode(device)
if err != nil {
return nil, err
}
peripheralDict := map[string]*Peripheral{}
groups := map[string]*Peripheral{}
interrupts := make(map[string]*Interrupt)
var peripheralsList []*Peripheral
// Some SVD files have peripheral elements derived from a peripheral that
// comes later in the file. To make sure this works, sort the peripherals if
// needed.
orderedPeripherals := orderPeripherals(device.Peripherals)
for _, periphEl := range orderedPeripherals {
description := formatText(periphEl.Description)
baseAddress, err := strconv.ParseUint(periphEl.BaseAddress, 0, 64)
if err != nil {
return nil, fmt.Errorf("invalid base address: %w", err)
}
// Some group names (for example the STM32H7A3x) have an invalid
// group name. Replace invalid characters with "_".
groupName := cleanName(periphEl.GroupName)
if groupName == "" {
groupName = cleanName(periphEl.Name)
}
for _, interrupt := range periphEl.Interrupts {
interruptName := cleanName(strings.TrimSpace(interrupt.Name))
addInterrupt(interrupts, interruptName, interruptName, interrupt.Index, description)
// As a convenience, also use the peripheral name as the interrupt
// name. Only do that for the nrf for now, as the stm32 .svd files
// don't always put interrupts in the correct peripheral...
if len(periphEl.Interrupts) == 1 && strings.HasPrefix(device.Name, "nrf") {
addInterrupt(interrupts, periphEl.Name, interrupt.Name, interrupt.Index, description)
}
}
if _, ok := groups[groupName]; ok || periphEl.DerivedFrom != "" {
var derivedFrom *Peripheral
if periphEl.DerivedFrom != "" {
derivedFrom = peripheralDict[periphEl.DerivedFrom]
if derivedFrom == nil {
return nil, fmt.Errorf("peripheral %s derivedFrom %s not found", periphEl.Name, periphEl.DerivedFrom)
}
} else {
derivedFrom = groups[groupName]
}
p := &Peripheral{
Name: periphEl.Name,
GroupName: derivedFrom.GroupName,
Description: description,
BaseAddress: baseAddress,
}
if p.Description == "" {
p.Description = derivedFrom.Description
}
peripheralsList = append(peripheralsList, p)
peripheralDict[p.Name] = p
for _, subtype := range derivedFrom.Subtypes {
peripheralsList = append(peripheralsList, &Peripheral{
Name: periphEl.Name + "_" + subtype.ClusterName,
GroupName: subtype.GroupName,
Description: subtype.Description,
BaseAddress: baseAddress,
})
}
continue
}
p := &Peripheral{
Name: periphEl.Name,
GroupName: groupName,
Description: description,
BaseAddress: baseAddress,
Registers: []*PeripheralField{},
}
if p.GroupName == "" {
p.GroupName = periphEl.Name
}
peripheralsList = append(peripheralsList, p)
peripheralDict[periphEl.Name] = p
if _, ok := groups[groupName]; !ok && groupName != "" {
groups[groupName] = p
}
for _, register := range periphEl.Registers {
regName := groupName // preferably use the group name
if regName == "" {
regName = periphEl.Name // fall back to peripheral name
}
p.Registers = append(p.Registers, parseRegister(regName, register, baseAddress, "")...)
}
peripheralsList = append(peripheralsList, processCluster(p, periphEl.Clusters, peripheralDict)...)
}
// Make a sorted list of interrupts.
interruptList := make([]*Interrupt, 0, len(interrupts))
for _, intr := range interrupts {
interruptList = append(interruptList, intr)
}
sort.SliceStable(interruptList, func(i, j int) bool {
if interruptList[i].Value != interruptList[j].Value {
return interruptList[i].Value < interruptList[j].Value
}
return interruptList[i].PeripheralIndex < interruptList[j].PeripheralIndex
})
// Properly format the description, with comments.
description := ""
if text := device.Description; text != "" {
description = "// " + strings.ReplaceAll(text, "\n", "\n// ")
description = regexp.MustCompile(`\s+\n`).ReplaceAllString(description, "\n")
}
// Properly format the license block, with comments.
licenseBlock := ""
if text := formatText(device.LicenseText); text != "" {
licenseBlock = "// " + strings.ReplaceAll(text, "\n", "\n// ")
licenseBlock = regexp.MustCompile(`\s+\n`).ReplaceAllString(licenseBlock, "\n")
}
// Remove "-" characters from the device name because such characters cannot
// be used in build tags. Necessary for the ESP32-C3 for example.
nameLower := strings.ReplaceAll(strings.ToLower(device.Name), "-", "")
metadata := &Metadata{
File: filepath.Base(path),
DescriptorSource: sourceURL,
Name: device.Name,
NameLower: nameLower,
Description: description,
LicenseBlock: licenseBlock,
}
if device.CPU != nil {
metadata.HasCPUInfo = true
metadata.CPUName = device.CPU.Name
metadata.FPUPresent = device.CPU.FPUPresent
metadata.NVICPrioBits = device.CPU.NVICPrioBits
}
return &Device{
Metadata: metadata,
Interrupts: interruptList,
Peripherals: peripheralsList,
PeripheralDict: peripheralDict,
}, nil
}
// orderPeripherals sorts the peripherals so that derived peripherals come after
// base peripherals. This is necessary for some SVD files.
func orderPeripherals(input []SVDPeripheral) []*SVDPeripheral {
var sortedPeripherals []*SVDPeripheral
var missingBasePeripherals []*SVDPeripheral
knownPeripherals := map[string]struct{}{}
for i := range input {
p := &input[i]
// Track by peripheral name since derivedFrom references names, not group names
knownPeripherals[p.Name] = struct{}{}
if p.DerivedFrom != "" {
if _, ok := knownPeripherals[p.DerivedFrom]; !ok {
missingBasePeripherals = append(missingBasePeripherals, p)
continue
}
}
sortedPeripherals = append(sortedPeripherals, p)
}
// Let's hope all base peripherals are now included.
sortedPeripherals = append(sortedPeripherals, missingBasePeripherals...)
return sortedPeripherals
}
func addInterrupt(interrupts map[string]*Interrupt, name, interruptName string, index int, description string) {
if _, ok := interrupts[name]; ok {
if interrupts[name].Value != index {
// Note: some SVD files like the one for STM32H7x7 contain mistakes.
// Instead of throwing an error, simply log it.
fmt.Fprintf(os.Stderr, "interrupt with the same name has different indexes: %s (%d vs %d)\n",
name, interrupts[name].Value, index)
}
parts := strings.Split(interrupts[name].Description, " // ")
hasDescription := false
for _, part := range parts {
if part == description {
hasDescription = true
}
}
if !hasDescription {
interrupts[name].Description += " // " + description
}
} else {
interrupts[name] = &Interrupt{
Name: name,
HandlerName: interruptName + "_IRQHandler",
PeripheralIndex: len(interrupts),
Value: index,
Description: description,
}
}
}
func parseBitfields(groupName, regName string, fieldEls []*SVDField, bitfieldPrefix string) ([]Constant, []Bitfield) {
var fields []Constant
var bitfields []Bitfield
enumSeen := map[string]int64{}
for _, fieldEl := range fieldEls {
// Some bitfields (like the STM32H7x7) contain invalid bitfield
// names like "CNT[31]". Replace invalid characters with "_" when
// needed.
fieldName := cleanName(fieldEl.Name)
if !unicode.IsUpper(rune(fieldName[0])) && !unicode.IsDigit(rune(fieldName[0])) {
fieldName = strings.ToUpper(fieldName)
}
// Find the lsb/msb that is encoded in various ways.
// Standards are great, that's why there are so many to choose from!
var lsb, msb uint32
if fieldEl.Lsb != nil && fieldEl.Msb != nil {
// try to use lsb/msb tags
lsb = *fieldEl.Lsb
msb = *fieldEl.Msb
} else if fieldEl.BitOffset != nil && fieldEl.BitWidth != nil {
// try to use bitOffset/bitWidth tags
lsb = *fieldEl.BitOffset
msb = *fieldEl.BitWidth + lsb - 1
} else if fieldEl.BitRange != nil {
// try use bitRange
// example string: "[20:16]"
parts := strings.Split(strings.Trim(*fieldEl.BitRange, "[]"), ":")
l, err := strconv.ParseUint(parts[1], 0, 32)
if err != nil {
panic(err)
}
lsb = uint32(l)
m, err := strconv.ParseUint(parts[0], 0, 32)
if err != nil {
panic(err)
}
msb = uint32(m)
} else {
// this is an error. what to do?
fmt.Fprintln(os.Stderr, "unable to find lsb/msb in field:", fieldName)
continue
}
// The enumerated values can be the same as another field, so to avoid
// duplication SVD files can simply refer to another set of enumerated
// values in the same register.
// See: https://www.keil.com/pack/doc/CMSIS/SVD/html/elem_registers.html#elem_enumeratedValues
enumeratedValues := fieldEl.EnumeratedValues
if enumeratedValues.DerivedFrom != "" {
parts := strings.Split(enumeratedValues.DerivedFrom, ".")
if len(parts) == 1 {
found := false
for _, otherFieldEl := range fieldEls {
if otherFieldEl.EnumeratedValues.Name == parts[0] {
found = true
enumeratedValues = otherFieldEl.EnumeratedValues
}
}
if !found {
fmt.Fprintf(os.Stderr, "Warning: could not find enumeratedValue.derivedFrom of %s for register field %s\n", enumeratedValues.DerivedFrom, fieldName)
}
} else {
// The derivedFrom attribute may also point to enumerated values
// in other registers and even peripherals, but this feature
// isn't often used in SVD files.
fmt.Fprintf(os.Stderr, "TODO: enumeratedValue.derivedFrom to a different register: %s\n", enumeratedValues.DerivedFrom)
}
}
bitfields = append(bitfields, Bitfield{
Name: fieldName,
Offset: lsb,
Mask: (0xffffffff >> (31 - (msb - lsb))) << lsb,
})
fields = append(fields, Constant{
Name: fmt.Sprintf("%s_%s%s_%s_Pos", groupName, bitfieldPrefix, regName, fieldName),
Description: fmt.Sprintf("Position of %s field.", fieldName),
Value: uint64(lsb),
})
fields = append(fields, Constant{
Name: fmt.Sprintf("%s_%s%s_%s_Msk", groupName, bitfieldPrefix, regName, fieldName),
Description: fmt.Sprintf("Bit mask of %s field.", fieldName),
Value: (0xffffffffffffffff >> (63 - (msb - lsb))) << lsb,
})
if lsb == msb { // single bit
fields = append(fields, Constant{
Name: fmt.Sprintf("%s_%s%s_%s", groupName, bitfieldPrefix, regName, fieldName),
Description: fmt.Sprintf("Bit %s.", fieldName),
Value: 1 << lsb,
})
}
for _, enumEl := range enumeratedValues.EnumeratedValue {
enumName := enumEl.Name
// Renesas has enum without actual values that we have to skip
if enumEl.Value == "" {
continue
}
if strings.EqualFold(enumName, "reserved") || !validName.MatchString(enumName) {
continue
}
if !unicode.IsUpper(rune(enumName[0])) && !unicode.IsDigit(rune(enumName[0])) {
enumName = strings.ToUpper(enumName)
}
enumDescription := formatText(enumEl.Description)
var enumValue uint64
var err error
if strings.HasPrefix(enumEl.Value, "0b") {
val := strings.TrimPrefix(enumEl.Value, "0b")
enumValue, err = strconv.ParseUint(val, 2, 64)
} else {
enumValue, err = strconv.ParseUint(enumEl.Value, 0, 64)
}
if err != nil {
if enumBitSpecifier.MatchString(enumEl.Value) {
// NXP and Renesas SVDs use the form #xx1x, #x0xx, etc for values
enumValue, err = strconv.ParseUint(strings.ReplaceAll(enumEl.Value[1:], "x", "0"), 2, 64)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
enumName = fmt.Sprintf("%s_%s%s_%s_%s", groupName, bitfieldPrefix, regName, fieldName, enumName)
// Avoid duplicate values. Duplicate names with the same value are
// allowed, but the same name with a different value is not. Instead
// of trying to work around those cases, remove the value entirely
// as there is probably not one correct answer in such a case.
// For example, SVD files from NXP have enums limited to 20
// characters, leading to lots of duplicates when these enum names
// are long. Nothing here can really fix those cases.
previousEnumValue, seenBefore := enumSeen[enumName]
if seenBefore {
if previousEnumValue < 0 {
// There was a mismatch before, ignore all equally named fields.
continue
}
if int64(enumValue) != previousEnumValue {
// There is a mismatch. Mark it as such, and remove the
// existing enum bitfield value.
enumSeen[enumName] = -1
for i, field := range fields {
if field.Name == enumName {
fields = append(fields[:i], fields[i+1:]...)
break
}
}
}
continue
}
enumSeen[enumName] = int64(enumValue)
fields = append(fields, Constant{
Name: enumName,
Description: enumDescription,
Value: enumValue,
})
}
}
return fields, bitfields
}
type Register struct {
element *SVDRegister
baseAddress uint64
}
func NewRegister(element *SVDRegister, baseAddress uint64) *Register {
return &Register{
element: element,
baseAddress: baseAddress,
}
}
func (r *Register) name() string {
return strings.ReplaceAll(r.element.Name, "[%s]", "")
}
func (r *Register) description() string {
return formatText(r.element.Description)
}
func (r *Register) address() uint64 {
offsetString := r.element.Offset
if offsetString == nil {
offsetString = r.element.AddressOffset
}
addr, err := strconv.ParseUint(*offsetString, 0, 32)
if err != nil {
panic(err)
}
return r.baseAddress + addr
}
func (r *Register) dim() int {
if r.element.Dim == nil {
return -1 // no dim elements
}
dim, err := strconv.ParseInt(*r.element.Dim, 0, 32)
if err != nil {
panic(err)
}
return int(dim)
}
func (r *Register) dimIndex() []string {
defer func() {
if err := recover(); err != nil {
fmt.Println("register", r.name())
panic(err)
}
}()
dim := r.dim()
if r.element.DimIndex == nil {
if dim <= 0 {
return nil
}
idx := make([]string, dim)
for i := range idx {
idx[i] = strconv.FormatInt(int64(i), 10)
}
return idx
}
t := strings.Split(*r.element.DimIndex, "-")
if len(t) == 2 {
// renesas uses hex letters e.g. A-B
if strings.Contains("ABCDEFabcdef", t[0]) {
t[0] = "0x" + t[0]
}
if strings.Contains("ABCDEFabcdef", t[1]) {
t[1] = "0x" + t[1]
}
x, err := strconv.ParseInt(t[0], 0, 32)
if err != nil {
panic(err)
}
y, err := strconv.ParseInt(t[1], 0, 32)
if err != nil {
panic(err)
}
if x < 0 || y < x || y-x != int64(dim-1) {
panic("invalid dimIndex")
}
idx := make([]string, dim)
for i := x; i <= y; i++ {
idx[i-x] = strconv.FormatInt(i, 10)
}
return idx
} else if len(t) > 2 {
panic("invalid dimIndex")
}
s := strings.Split(*r.element.DimIndex, ",")
if len(s) != dim {
panic("invalid dimIndex")
}
return s
}
func (r *Register) size() int {
if r.element.Size != nil {
size, err := strconv.ParseInt(*r.element.Size, 0, 32)
if err != nil {
panic(err)
}
return int(size) / 8
}
return 4
}
func parseRegister(groupName string, regEl *SVDRegister, baseAddress uint64, bitfieldPrefix string) []*PeripheralField {
reg := NewRegister(regEl, baseAddress)
if reg.dim() != -1 {
dimIncrement, err := strconv.ParseUint(regEl.DimIncrement, 0, 32)
if err != nil {
panic(err)
}
if strings.Contains(reg.name(), "%s") {
// a "spaced array" of registers, special processing required
// we need to generate a separate register for each "element"
var results []*PeripheralField
shortName := strings.ToUpper(strings.ReplaceAll(strings.ReplaceAll(reg.name(), "_%s", ""), "%s", ""))
for i, j := range reg.dimIndex() {
regAddress := reg.address() + (uint64(i) * dimIncrement)
results = append(results, &PeripheralField{
Name: strings.ToUpper(strings.ReplaceAll(reg.name(), "%s", j)),
Address: regAddress,
Description: reg.description(),
Array: -1,
ElementSize: reg.size(),
ShortName: shortName,
})
}
// set first result bitfield
results[0].Constants, results[0].Bitfields = parseBitfields(groupName, shortName, regEl.Fields, bitfieldPrefix)
results[0].HasBitfields = len(results[0].Bitfields) > 0
for i := 1; i < len(results); i++ {
results[i].Bitfields = results[0].Bitfields
results[i].HasBitfields = results[0].HasBitfields
}
return results
}
}
regName := reg.name()
if !unicode.IsUpper(rune(regName[0])) && !unicode.IsDigit(rune(regName[0])) {
regName = strings.ToUpper(regName)
}
regName = cleanName(regName)
constants, bitfields := parseBitfields(groupName, regName, regEl.Fields, bitfieldPrefix)
return []*PeripheralField{&PeripheralField{
Name: regName,
Address: reg.address(),
Description: reg.description(),
Constants: constants,
Array: reg.dim(),
ElementSize: reg.size(),
ShortName: regName,
Bitfields: bitfields,
HasBitfields: len(bitfields) > 0,
}}
}
// The Go module for this device.
func writeGo(outdir string, device *Device, interruptSystem string) error {
outf, err := os.Create(filepath.Join(outdir, device.Metadata.NameLower+".go"))
if err != nil {
return err
}
defer outf.Close()
w := bufio.NewWriter(outf)
maxInterruptValue := 0
for _, intr := range device.Interrupts {
if intr.Value > maxInterruptValue {
maxInterruptValue = intr.Value
}
}
interruptHandlerMap := make(map[string]*Interrupt)
var interruptHandlers []*Interrupt
for _, intr := range device.Interrupts {
if _, ok := interruptHandlerMap[intr.HandlerName]; !ok {
interruptHandlerMap[intr.HandlerName] = intr
interruptHandlers = append(interruptHandlers, intr)
}
}
t := template.Must(template.New("go").Funcs(template.FuncMap{
"bytesNeeded": func(i, j uint64) uint64 { return j - i },
"isMultiline": isMultiline,
"splitLine": splitLine,
}).Parse(`// Automatically generated file. DO NOT EDIT.
// Generated by gen-device-svd.go from {{.device.Metadata.File}}, see {{.device.Metadata.DescriptorSource}}
//go:build {{.pkgName}} && {{.device.Metadata.NameLower}}
/*
{{.device.Metadata.Description}}
*/
{{.device.Metadata.LicenseBlock}}
package {{.pkgName}}
import (
"runtime/volatile"
"unsafe"
)
// Some information about this device.
const (
Device = "{{.device.Metadata.Name}}"
{{- if .device.Metadata.HasCPUInfo }}
CPU = "{{.device.Metadata.CPUName}}"
FPUPresent = {{.device.Metadata.FPUPresent}}
NVICPrioBits = {{.device.Metadata.NVICPrioBits}}
{{- end }}
)
// Interrupt numbers.
const (
{{- range .device.Interrupts}}
{{- if .Description}}
{{- range .Description|splitLine}}
// {{.}}
{{- end}}
{{- end}}
IRQ_{{.Name}} = {{.Value}}
{{- "\n"}}
{{- end}}
// Highest interrupt number on this device.
IRQ_max = {{.interruptMax}}
)
// Pseudo function call that is replaced by the compiler with the actual
// functions registered through interrupt.New.
//go:linkname callHandlers runtime/interrupt.callHandlers
func callHandlers(num int)
{{- if eq .interruptSystem "hardware"}}
{{- range .interruptHandlers}}
//export {{.HandlerName}}
func interrupt{{.Name}}() {
callHandlers(IRQ_{{.Name}})
}
{{- end}}
{{- end}}
{{- if eq .interruptSystem "software"}}
func HandleInterrupt(num int) {
switch num {
{{- range .interruptHandlers}}
case IRQ_{{.Name}}:
callHandlers(IRQ_{{.Name}})
{{- end}}
}
}
{{- end}}
// Peripherals.
var (
{{- range .device.Peripherals}}
{{- if .Description}}
{{- range .Description|splitLine}}
// {{.}}
{{- end}}
{{- end}}
{{.Name}} = (*{{.GroupName}}_Type)(unsafe.Pointer(uintptr(0x{{printf "%x" .BaseAddress}})))
{{- "\n"}}
{{- end}}
)
`))
err = t.Execute(w, map[string]interface{}{
"device": device,
"pkgName": filepath.Base(strings.TrimRight(outdir, "/")),
"interruptMax": maxInterruptValue,
"interruptSystem": interruptSystem,
"interruptHandlers": interruptHandlers,
})
if err != nil {
return err
}
// Define peripheral struct types.
for _, peripheral := range device.Peripherals {