-
-
Notifications
You must be signed in to change notification settings - Fork 368
/
sketch.go
332 lines (285 loc) · 9.69 KB
/
sketch.go
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
// This file is part of arduino-cli.
//
// Copyright 2020 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to license@arduino.cc.
package builder
import (
"bytes"
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
f "github.com/arduino/arduino-cli/internal/algorithms"
"github.com/arduino/arduino-cli/internal/arduino/builder/cpp"
"github.com/arduino/arduino-cli/internal/i18n"
"github.com/arduino/go-paths-helper"
"github.com/marcinbor85/gohex"
)
var (
includesArduinoH = regexp.MustCompile(`(?m)^\s*#\s*include\s*[<\"]Arduino\.h[>\"]`)
)
// prepareSketchBuildPath copies the sketch source files in the build path.
// The .ino files are merged together to create a .cpp file (by the way, the
// .cpp file still needs to be Arduino-preprocessed to compile).
func (b *Builder) prepareSketchBuildPath() error {
if err := b.sketchBuildPath.MkdirAll(); err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to create a folder to save the sketch"), err)
}
offset, mergedSource, err := b.sketchMergeSources(b.sourceOverrides)
if err != nil {
return err
}
destFile := b.sketchBuildPath.Join(b.sketch.MainFile.Base() + ".cpp")
if err := destFile.WriteFile([]byte(mergedSource)); err != nil {
return err
}
if err := b.sketchCopyAdditionalFiles(b.sketchBuildPath, b.sourceOverrides); err != nil {
return err
}
b.lineOffset = offset
return nil
}
// sketchMergeSources merges all the .ino source files included in a sketch to produce
// a single .cpp file.
func (b *Builder) sketchMergeSources(overrides map[string]string) (int, string, error) {
lineOffset := 0
mergedSource := ""
getSource := func(f *paths.Path) (string, error) {
path, err := b.sketch.FullPath.RelTo(f)
if err != nil {
return "", fmt.Errorf("%s: %w", i18n.Tr("unable to compute relative path to the sketch for the item"), err)
}
if override, ok := overrides[path.String()]; ok {
return override, nil
}
data, err := f.ReadFile()
if err != nil {
return "", errors.New(i18n.Tr("reading file %[1]s: %[2]s", f, err))
}
return string(data), nil
}
// add Arduino.h inclusion directive if missing
mainSrc, err := getSource(b.sketch.MainFile)
if err != nil {
return 0, "", err
}
if !includesArduinoH.MatchString(mainSrc) {
mergedSource += "#include <Arduino.h>\n"
lineOffset++
}
mergedSource += "#line 1 " + cpp.QuoteString(b.sketch.MainFile.String()) + "\n"
mergedSource += mainSrc + "\n"
lineOffset++
for _, file := range b.sketch.OtherSketchFiles {
src, err := getSource(file)
if err != nil {
return 0, "", err
}
mergedSource += "#line 1 " + cpp.QuoteString(file.String()) + "\n"
mergedSource += src + "\n"
}
return lineOffset, mergedSource, nil
}
// sketchCopyAdditionalFiles copies the additional files for a sketch to the
// specified destination directory.
func (b *Builder) sketchCopyAdditionalFiles(buildPath *paths.Path, overrides map[string]string) error {
for _, file := range b.sketch.AdditionalFiles {
relpath, err := b.sketch.FullPath.RelTo(file)
if err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to compute relative path to the sketch for the item"), err)
}
targetPath := buildPath.JoinPath(relpath)
// create the directory containing the target
if err = targetPath.Parent().MkdirAll(); err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to create the folder containing the item"), err)
}
var sourceBytes []byte
if override, ok := overrides[relpath.String()]; ok {
// use override source
sourceBytes = []byte(override)
} else {
// read the source file
s, err := file.ReadFile()
if err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to read contents of the source item"), err)
}
sourceBytes = s
}
// tag each additional file with the filename of the source it was copied from
sourceBytes = append([]byte("#line 1 "+cpp.QuoteString(file.String())+"\n"), sourceBytes...)
err = writeIfDifferent(sourceBytes, targetPath)
if err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to write to destination file"), err)
}
}
return nil
}
func writeIfDifferent(source []byte, destPath *paths.Path) error {
// Check whether the destination file exists
if destPath.NotExist() {
// Write directly
return destPath.WriteFile(source)
}
// Read the destination file if it exists
existingBytes, err := destPath.ReadFile()
if err != nil {
return fmt.Errorf("%s: %w", i18n.Tr("unable to read contents of the destination item"), err)
}
// Overwrite if contents are different
if !bytes.Equal(existingBytes, source) {
return destPath.WriteFile(source)
}
// Source and destination are the same, don't write anything
return nil
}
// buildSketch fixdoc
func (b *Builder) buildSketch(includesFolders paths.PathList) error {
includes := f.Map(includesFolders.AsStrings(), cpp.WrapWithHyphenI)
if err := b.sketchBuildPath.MkdirAll(); err != nil {
return err
}
sketchObjectFiles, err := b.compileFiles(
b.sketchBuildPath, b.sketchBuildPath,
false, /** recursive **/
includes,
)
if err != nil {
return err
}
// The "src/" subdirectory of a sketch is compiled recursively
sketchSrcPath := b.sketchBuildPath.Join("src")
if sketchSrcPath.IsDir() {
srcObjectFiles, err := b.compileFiles(
sketchSrcPath, sketchSrcPath,
true, /** recursive **/
includes,
)
if err != nil {
return err
}
sketchObjectFiles.AddAll(srcObjectFiles)
}
b.buildArtifacts.sketchObjectFiles = sketchObjectFiles
return nil
}
// mergeSketchWithBootloader fixdoc
func (b *Builder) mergeSketchWithBootloader() error {
if b.onlyUpdateCompilationDatabase {
return nil
}
if !b.buildProperties.ContainsKey("bootloader.noblink") && !b.buildProperties.ContainsKey("bootloader.file") {
return nil
}
sketchFileName := b.sketch.MainFile.Base()
sketchInBuildPath := b.buildPath.Join(sketchFileName + ".hex")
sketchInSubfolder := b.buildPath.Join("sketch", sketchFileName+".hex")
var builtSketchPath *paths.Path
if sketchInBuildPath.Exist() {
builtSketchPath = sketchInBuildPath
} else if sketchInSubfolder.Exist() {
builtSketchPath = sketchInSubfolder
} else {
return nil
}
bootloader := ""
if bootloaderNoBlink, ok := b.buildProperties.GetOk("bootloader.noblink"); ok {
bootloader = bootloaderNoBlink
} else {
bootloader = b.buildProperties.Get("bootloader.file")
}
bootloader = b.buildProperties.ExpandPropsInString(bootloader)
bootloaderPath := b.buildProperties.GetPath("runtime.platform.path").Join("bootloaders", bootloader)
if bootloaderPath.NotExist() {
if b.logger.Verbose() {
b.logger.Warn(i18n.Tr("Bootloader file specified but missing: %[1]s", bootloaderPath))
}
return nil
}
mergedSketchPath := builtSketchPath.Parent().Join(sketchFileName + ".with_bootloader.hex")
// Ignore merger errors for the first iteration
maximumBinSize := 16000000
if uploadMaxSize, ok := b.buildProperties.GetOk("upload.maximum_size"); ok {
maximumBinSize, _ = strconv.Atoi(uploadMaxSize)
maximumBinSize *= 2
}
err := merge(builtSketchPath, bootloaderPath, mergedSketchPath, maximumBinSize)
if err != nil && b.logger.Verbose() {
b.logger.Info(err.Error())
}
return nil
}
func merge(builtSketchPath, bootloaderPath, mergedSketchPath *paths.Path, maximumBinSize int) error {
if bootloaderPath.Ext() == ".bin" {
bootloaderPath = paths.New(strings.TrimSuffix(bootloaderPath.String(), ".bin") + ".hex")
}
memBoot := gohex.NewMemory()
if bootFile, err := bootloaderPath.Open(); err == nil {
defer bootFile.Close()
if err := memBoot.ParseIntelHex(bootFile); err != nil {
return errors.New(bootFile.Name() + " " + err.Error())
}
} else {
return err
}
memSketch := gohex.NewMemory()
if buildFile, err := builtSketchPath.Open(); err == nil {
defer buildFile.Close()
if err := memSketch.ParseIntelHex(buildFile); err != nil {
return errors.New(buildFile.Name() + " " + err.Error())
}
} else {
return err
}
memMerged := gohex.NewMemory()
initialAddress := uint32(math.MaxUint32)
lastAddress := uint32(0)
for _, segment := range memBoot.GetDataSegments() {
if err := memMerged.AddBinary(segment.Address, segment.Data); err != nil {
continue
}
if segment.Address < initialAddress {
initialAddress = segment.Address
}
if segment.Address+uint32(len(segment.Data)) > lastAddress {
lastAddress = segment.Address + uint32(len(segment.Data))
}
}
for _, segment := range memSketch.GetDataSegments() {
if err := memMerged.AddBinary(segment.Address, segment.Data); err != nil {
continue
}
if segment.Address < initialAddress {
initialAddress = segment.Address
}
if segment.Address+uint32(len(segment.Data)) > lastAddress {
lastAddress = segment.Address + uint32(len(segment.Data))
}
}
if mergeFile, err := mergedSketchPath.Create(); err == nil {
defer mergeFile.Close()
memMerged.DumpIntelHex(mergeFile, 16)
} else {
return err
}
// Write out a .bin if the addresses doesn't go too far away from origin
// (and consequently produce a very large bin)
size := lastAddress - initialAddress
if size > uint32(maximumBinSize) {
return nil
}
mergedSketchPathBin := paths.New(strings.TrimSuffix(mergedSketchPath.String(), ".hex") + ".bin")
data := memMerged.ToBinary(initialAddress, size, 0xFF)
return mergedSketchPathBin.WriteFile(data)
}