This repository has been archived by the owner on Aug 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
compile.js
527 lines (455 loc) · 16.1 KB
/
compile.js
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
/*
use this as a guide:
http://arduino.cc/en/Hacking/BuildProcess
*/
var fs = require('fs');
var async = require('async');
var wrench = require('wrench');
var child_process = require('child_process');
var LIBRARIES = require('./libraries');
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
String.prototype.startsWith = function(suffix) {
return this.indexOf(suffix) == 0;
};
function checkfile(path) {
if(!fs.existsSync(path)) throw new Error("file not found " + path);
}
function detectLibs(code) {
var libs = [];
var lines = code.split('\n');
lines.forEach(function(line){
var re = /\s*#include\s*[<"](\w+)\.h[>"]/i;
var res = line.match(re);
if(res) libs.push(res[1]);
});
return libs;
}
var FUNCTION_DEFINITION_REGEX = /(unsigned )*\s*(void|short|long|char|int)\s+(\w+)\((.*)\)/;
function generateDecs(code) {
var decs = [];
code.split('\n').forEach(function(line) {
var def = line.match(FUNCTION_DEFINITION_REGEX);
if(def) {
var dec = def[1]+' '+def[2]+'('+def[3]+');\n';
decs.push(def[0]+';\n');
}
});
return decs;
}
function generateCPPFile(cfile,sketchPath) {
//write the standard header
fs.writeFileSync(cfile,'#include "Arduino.h"\n');
var funcdecs = [];
var codes = [];
//loop through all sketch files
fs.readdirSync(sketchPath).forEach(function(file){
if(file.toLowerCase().endsWith('.ino')) {
var code = fs.readFileSync(sketchPath+'/'+file).toString();
generateDecs(code).forEach(function(dec){
funcdecs.push(dec);
});
codes.push(code);
}
})
//insert the generated definitions
funcdecs.forEach(function(dec){
fs.appendFileSync(cfile,dec);
});
//insert the code chunks
codes.forEach(function(def){
fs.appendFileSync(cfile,def);
})
//extra newline just in case
fs.appendFileSync(cfile,"\n");
}
function calculateLibs(list, paths, libs, debug, cb, plat) {
LIBRARIES.install(list,function() {
//install libs if needed, and add to the include paths
list.forEach(function(libname){
if(libname == 'Arduino') return; //already included, skip it
debug('scanning lib',libname);
if(LIBRARIES.isUserLib(libname,plat)) {
console.log("it's a user lib");
var lib = LIBRARIES.getUserLib(libname,plat);
lib.getIncludePaths(plat).forEach(function(path) {
paths.push(path);
});
libs.push(lib);
return;
}
var lib = LIBRARIES.getById(libname.toLowerCase());
if(!lib) {
debug("ERROR. couldn't find library",libname);
throw new Error("Missing Library! " + libname);
}
if(!lib.isInstalled()) {
throw new Error("library should already be installed! " + libname);
}
debug("include path = ",lib.getIncludePaths(plat));
lib.getIncludePaths(plat).forEach(function(path) { paths.push(path); });
libs.push(lib);
if(lib.dependencies) {
console.log("deps = ",lib.dependencies);
lib.dependencies.map(function(libname) {
return LIBRARIES.getById(libname);
}).map(function(lib){
console.log("looking at lib",lib);
debug("include path = ",lib.getIncludePaths(plat));
lib.getIncludePaths(plat).forEach(function(path) { paths.push(path); });
libs.push(lib);
})
}
});
cb();
});
}
function listdir(path) {
return fs.readdirSync(path)
.filter(function(file) {
if(file.startsWith('.')) return false;
return true;
})
.map(function(file) {
return path+'/'+file;
});
}
function exec(cmd, cb, debug) {
var result = child_process.execFile(
cmd[0],
cmd.slice(1),
function(error, stdout, stderr) {
if(error) {
console.log(error);
console.log("code = ",error.code);
console.log(cmd.join(" "));
console.log(stdout);
console.log(stderr);
var err = new Error("there was a problem running " + cmd.join(" "));
err.cmd = cmd;
err.output = stdout + stderr;
if(debug) debug(err);
cb(err);
return;
}
if(cb) cb();
}
);
}
function linkFile(options, file, outdir, cb, debug) {
var cmd = [
options.platform.getCompilerBinaryPath()+'/avr-ar',
'rcs',
outdir+'/core.a',
file,
];
exec(cmd, cb, debug);
}
function linkElfFile(options, libofiles, outdir, cb, debug) {
//link everything into the .elf file
var elfcmd = [
options.platform.getCompilerBinaryPath()+'/avr-gcc', //gcc
'-Os', //??
'-Wl,--gc-sections', //not using relax yet
'-mmcu='+options.device.build.mcu, //the mcu, ex: atmega168
'-o', //??
outdir+'/'+options.name+'.cpp.elf',
outdir+'/'+options.name+'.cpp.o',
];
elfcmd = elfcmd.concat(libofiles);
elfcmd = elfcmd.concat([
outdir+'/core.a',
'-L'+__dirname+'/'+outdir,
'-lm',
]);
exec(elfcmd, cb, debug);
}
function extractEEPROMData(options, outdir, cb, debug) {
var eepcmd = [
options.platform.getCompilerBinaryPath()+'/avr-objcopy',
'-O',
'ihex',
'-j',
'.eeprom',
'--set-section-flags=.eeprom=alloc,load',
'--no-change-warnings',
'--change-section-lma',
'.eeprom=0',
outdir+'/'+options.name+'.cpp.elf',
outdir+'/'+options.name+'.eep',
];
exec(eepcmd, cb, debug);
}
function buildHexFile(options, outdir, cb, debug) {
var hexcmd = [
options.platform.getCompilerBinaryPath()+'/avr-objcopy',
'-O',
'ihex',
'-R',
'.eeprom',
outdir+'/'+options.name+'.cpp.elf',
outdir+'/'+options.name+'.hex',
];
exec(hexcmd, cb, debug);
}
function processList(list, cb, publish) {
if(list.length <= 0) {
cb();
return;
}
var item = list.shift();
try {
item(function(err) {
console.log("--------------------");
if(err) return cb(err);
processList(list,cb, publish);
});
} catch(err) {
console.log("there was an error");
console.log(err.toString());
console.log("publish = ", publish);
publish({
type:'error',
message:err.toString(),
path:err.path,
errno: err.errno,
code: err.code,
});
}
}
exports.compile = function(sketchPath, outdir,options, publish, sketchDir, finalcb) {
console.log("compiling to");
console.log("sketchpath ", sketchPath);
console.log("outdir = ", outdir);
// console.log("optiosn = ", options);
console.log("sketchdir = ", sketchDir);
var errorHit = false;
function debug(message) {
var args = Array.prototype.slice.call(arguments);
console.log("message = " + message + args.join(" ")+'\n');
if(message instanceof Error) {
errorHit = true;
publish({type:'error', message: args.join(" ") + message.output});
} else {
publish({type:"compile", message:args.join(" ")});
}
}
checkfile(options.platform.getCompilerBinaryPath());
debug("compiling ",sketchPath,"to dir",outdir);
debug("root sketch dir = ",sketchDir);
wrench.rmdirSyncRecursive(outdir, true);
wrench.mkdirSyncRecursive(outdir);
// wrench.mkdirSyncRecursive(sketchPath);
debug("assembling the sketch in the directory\n",outdir);
checkfile(outdir);
var tasks = [];
var cfile = outdir + '/' + options.name + '.cpp';
var cfiles = [];
var includepaths = [];
var libextra = [];
var plat = options.platform;
//generate the CPP file and copy all files to the output directory
tasks.push(function(cb) {
debug("generating",cfile);
generateCPPFile(cfile,sketchPath);
cfiles.push(cfile);
//compile sketch files
function copyToDir(file, indir, outdir) {
console.log("copying ",file);
var text = fs.readFileSync(indir+'/'+file);
fs.writeFileSync(outdir+'/'+file,text);
}
fs.readdirSync(sketchDir).forEach(function(file) {
if(file.toLowerCase().endsWith('.h')) copyToDir(file,sketchDir,sketchPath);
if(file.toLowerCase().endsWith('.cpp')) copyToDir(file,sketchDir,sketchPath);
cfiles.push(sketchPath+'/'+file);
});
cb();
});
// scan for the included libs
// make sure they are all installed
// collect their include paths
tasks.push(function(cb) {
var includedLibs = detectLibs(fs.readFileSync(cfile).toString());
debug('========= scanned for included libs',includedLibs);
//assemble library paths
var librarypaths = [];
//global libs
debug("standard arduino libs = ",plat.getStandardLibraryPath());
fs.readdirSync(plat.getStandardLibraryPath()).forEach(function(lib) {
librarypaths.push(plat.getStandardLibraryPath()+'/'+lib);
});
//userlibs
listdir(plat.getUserLibraryDir()).forEach(function(lib) {
librarypaths.push(lib);
});
//standard global includes for the arduino core itself
includepaths.push(plat.getCorePath());
includepaths.push(plat.getVariantPath());
includepaths.push(sketchDir);
console.log("include path =",includepaths);
console.log("includedlibs = ", includedLibs);
calculateLibs(includedLibs,includepaths,libextra, debug, cb, plat);
});
//actually compile code
tasks.push(function(cb) {
console.log("moving on now");
//debug("included libs = ", includedLibs);
debug("include paths = ", JSON.stringify(includepaths,null, ' '));
debug("using 3rd party libraries",libextra.map(function(lib) { return lib.id }).join(', '));
compileFiles(options,outdir,includepaths,cfiles,debug, cb);
});
//compile the 3rd party libs
tasks.push(function(cb) {
debug("compiling 3rd party libs");
async.map(libextra, function(lib,cb) {
debug('compiling library: ',lib.id);
var paths = lib.getIncludePaths(plat);
var cfiles = [];
paths.forEach(function(path) {
wrench.readdirSyncRecursive(path)
.filter(function(filename) {
if(filename.startsWith('examples/')) return false;
if(filename.toLowerCase().endsWith('.c')) return true;
if(filename.toLowerCase().endsWith('.cpp')) return true;
return false;
})
.forEach(function(filename) {
cfiles.push(path+'/'+filename);
})
;
});
debug('cfiles',cfiles);
compileFiles(options, outdir, includepaths, cfiles, debug,cb);
},cb);
});
//compile core
tasks.push(function(cb) {
debug("compiling core files");
var cfiles = listdir(plat.getCorePath());
compileFiles(options,outdir,includepaths,cfiles,debug,cb);
});
//compile core avr-libc
tasks.push(function(cb) {
var libcdir = plat.getCorePath()+'/avr-libc';
if(fs.existsSync(libcdir)) {
var cfiles = listdir(plat.getCorePath()+'/avr-libc');
compileFiles(options,outdir,includepaths,cfiles,debug,cb);
} else {
if(cb) cb();
}
});
//link everything into core.a
tasks.push(function(cb) {
var dfiles = listdir(outdir)
.filter(function(file){
if(file.endsWith('.d')) return false;
return true;
});
async.mapSeries(dfiles, function(file, cb) {
debug("linking",file);
linkFile(options,file,outdir, cb, debug);
}, cb);
});
//build the elf file
tasks.push(function(cb) {
debug("building elf file");
var libofiles = [];
libextra.forEach(function(lib) {
var paths = lib.getIncludePaths(plat);
paths.forEach(function(path) {
listdir(path).filter(function(file) {
if(file.endsWith('.cpp')) return true;
return false;
}).map(function(filename) {
libofiles.push(outdir+'/'+filename.substring(filename.lastIndexOf('/')+1) + '.o');
});
});
});
linkElfFile(options,libofiles,outdir,cb, debug);
});
// 5. extract EEPROM data (from EEMEM directive) to .eep file.
tasks.push(function(cb) {
debug("extracting EEPROM data");
extractEEPROMData(options,outdir,cb,debug);
});
// 6. build the .hex file
tasks.push(function(cb) {
debug("building .HEX file");
buildHexFile(options,outdir,cb, debug);
});
processList(tasks, finalcb, publish);
}
function compileFiles(options, outdir, includepaths, cfiles,debug, cb) {
function comp(file,cb) {
var fname = file.substring(file.lastIndexOf('/')+1);
if(fname.startsWith('.')) return cb(null, null);
if(file.toLowerCase().endsWith('examples')) return cb(null,null);
if(file.toLowerCase().endsWith('/avr-libc')) return cb(null,null);
if(file.toLowerCase().endsWith('.c')) {
compileC(options,outdir, includepaths, file,debug, cb);
return;
}
if(file.toLowerCase().endsWith('.cpp')) {
compileCPP(options,outdir, includepaths, file,debug, cb);
return;
}
//debug("still need to compile",file);
cb(null,null);
}
async.mapSeries(cfiles, comp, cb);
}
function compileCPP(options, outdir, includepaths, cfile,debug, cb) {
debug("compiling ",cfile);
var cmd = [
options.platform.getCompilerBinaryPath()+"/avr-g++",
"-c", //compile, don't link
'-g', //include debug info and line numbers
'-Os', //optimize for size
'-Wall', //turn on verbose warnings
'-fno-exceptions',// ??
'-ffunction-sections',// put each function in it's own section
'-fdata-sections', //??
'-mmcu='+options.device.build.mcu,
'-DF_CPU='+options.device.build.f_cpu,
'-MMD',//output dependency info
'-DARDUINO=105', //??
'-DUSB_VID='+options.device.build.vid, //??
'-DUSB_PID='+options.device.build.pid, //??
];
includepaths.forEach(function(path){
cmd.push("-I"+path);
})
cmd.push(cfile); //add the actual c++ file
cmd.push('-o'); //output object file
var filename = cfile.substring(cfile.lastIndexOf('/')+1);
cmd.push(outdir+'/'+filename+'.o');
exec(cmd,cb, debug);
}
function compileC(options, outdir, includepaths, cfile, debug, cb) {
debug("compiling ",cfile);//,"to",outdir,"with options",options);
var cmd = [
options.platform.getCompilerBinaryPath()+"/avr-gcc", //gcc
"-c", //compile, don't link
'-g', //include debug info and line numbers
'-Os', //optimize for size
'-Wall', //turn on verbose warnings
'-ffunction-sections',// put each function in it's own section
'-fdata-sections', //??
'-mmcu='+options.device.build.mcu,
'-DF_CPU='+options.device.build.f_cpu,
'-MMD',//output dependency info
'-DARDUINO=105', //??
'-DUSB_VID='+options.device.vid, //??
'-DUSB_PID='+options.device.pid, //??
];
includepaths.forEach(function(path){
cmd.push("-I"+path);
})
cmd.push(cfile); //add the actual c file
cmd.push('-o');
var filename = cfile.substring(cfile.lastIndexOf('/')+1);
cmd.push(outdir+'/'+filename+'.o');
exec(cmd, cb, debug);
}