-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzmake.cpp
1631 lines (1528 loc) · 61.3 KB
/
zmake.cpp
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
#include <sys/stat.h>
#include <signal.h>
#include <set>
#include <sstream>
#include <mutex>
#include "zmake.h"
#include "zmake_util.h"
#define BUILD_DIR_NAME ".zmade"
#define FP(f) f->GetFilePath().data()
namespace fs = std::filesystem;
using FSCO = fs::copy_options;
namespace zmake {
//TODO use an uniform way to create global resources, such as:
enum GlobalResourceType {
GRT_FILE = 1,
GRT_DEFAULT_COMPILER = 2, GRT_DC = 2,
GRT_MD5 = 3,
GRT_RUNNER_BEFORE_BUILD_ALL = 12, GRT_RBB = 12,
GRT_RUNNER_AFTER_BUILD_ALL = 13, GRT_RAB = 13,
};
template <typename T, GlobalResourceType>
struct GlobalResource {
static T& Resource() {
static T s_resource{};
return s_resource;
}
static void InitOnce(std::function<void(T&)> initializer) {
static std::once_flag s_flag;
std::call_once(s_flag, [&initializer]() { initializer(Resource()); });
}
};
auto& GlobalFiles() { return GlobalResource<std::map<std::string, ZFile*>, GRT_FILE>::Resource(); }
constexpr auto GlobalRBB = GlobalResource<std::vector<std::function<void()>>, GRT_RBB>::Resource;
constexpr auto GlobalRAB = GlobalResource<std::vector<std::function<void()>>, GRT_RAB>::Resource;
uint32_t* AccessDebugLevel() {
static uint32_t s_debug_level = 0;
return &s_debug_level;
}
std::string* AccessDefaultCompiler(const std::string& suffix) {
using T = std::map<std::string, std::string>;
GlobalResource<T, GRT_DC>::InitOnce(
[](T& compilers) {
for (auto& x : StringSplit(C_CPP_SOURCE_SUFFIXES, '|')) compilers[x] = "g++";
compilers[".c"] = "gcc";
compilers[".C"] = "gcc";
compilers[".a"] = "ar";
compilers[".so"] = "g++";
compilers[".proto"] = "protoc";
compilers[".cu"] = "nvcc";
compilers[""] = "g++";
});
return &GlobalResource<T, GRT_DC>::Resource()[suffix];
}
//TODO no need Access these root dirs
std::string* AccessProjectRootDir() {
static std::string s_prj_root_dir = fs::current_path();
//TODO init once
if ('/' != *s_prj_root_dir.rbegin()) s_prj_root_dir += "/";
return &s_prj_root_dir;
}
//TODO change to any other dir and validate it
std::string* AccessBuildRootDir() {
static std::string s_build_root_dir = *AccessProjectRootDir() + BUILD_DIR_NAME + "/";
return &s_build_root_dir;
}
bool* AccessVerboseMode() {
static bool s_verbose = true;
return &s_verbose;
}
void SetVerboseMode(bool verbose) {
*AccessVerboseMode() = verbose;
}
void SetDebugLevel(uint32_t level) {
*AccessDebugLevel() = level;
}
std::string ExecuteCmd(const std::string& cmd, int* ret_code = nullptr) {
std::string result;
std::array<char, 128> buffer;
FILE* f = popen(cmd.data(), "r");
if (!f) ZTHROW("popen \"%s\" failed", cmd.data());
int n = 0, rc = 0;
while ((n = fread(buffer.data(), 1, buffer.size(), f))) result.append(buffer.data(), n);
if ((rc = pclose(f)) && ret_code) *ret_code = rc;
return StringRightTrim(result);
}
//wrap all friend functions into this class.
class ZF {
public:
static void ExecuteBuild(ZFile* f) {
auto exec_cmd = StringPrintf("(cd %s; %s)", f->_cwd.data(), f->_cmd.data());
auto tm_start = std::chrono::system_clock::now();
int ret_code = 0;
(void)ExecuteCmd(exec_cmd, &ret_code);
auto spend_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now() - tm_start).count();
{
static std::mutex s_mtx;
std::lock_guard<std::mutex> guard(s_mtx);
ColorPrint(StringPrintf("@ Build target %s %s, file: %s, spend: %d ms\n",
f->_name.data(), ret_code ? "failed" : "OK",
f->_file.data(), spend_ms), CT_BRIGHT_YELLOW);
if (*AccessVerboseMode()) printf("# %s\n", exec_cmd.data());
}
if (0 != ret_code) {
kill(0, SIGKILL);
_exit(2);
}
}
static void UpdateGeneratedByDep(ZFile* f, bool val) { f->_generated_by_dep = val; }
static void UpdateCwd(ZFile* f, const std::string& val) { f->_cwd = val; }
static void AddObjectUser(ZObject* obj, ZFile* user) { obj->AddObjectUser(user); }
template <typename T, typename... Args>
static T* Create(Args... args) { return new T(args...); }
};
const std::unordered_map<std::string, std::string>& ZConfig::GetFlags() const {
return _flags;
}
ZConfig* ZConfig::SetFlag(const std::string& flag) {
auto parts = StringSplit(flag, '=');
if (parts.size() > 2) {
parts.resize(1);
parts[0] = flag;
}
if (!_flags.count(parts[0])) _flag_names.push_back(parts[0]);
_flags[parts[0]] = (1 == parts.size()) ? "" : parts[1];
return this;
}
ZConfig* ZConfig::SetFlags(const std::vector<std::string>& flags) {
for (auto& x : flags) SetFlag(x);
return this;
}
bool ZConfig::HasFlag(const std::string& flag_name) const {
return _flags.end() != _flags.find(flag_name);
}
std::string ZConfig::GetFlag(const std::string& flag_name) const {
auto iter = _flags.find(flag_name);
return (_flags.end() != iter) ? iter->second : "";
}
void ZConfig::Merge(const ZConfig& other, bool prior_other) {
for (auto x : other.GetFlags()) {
if (!HasFlag(x.first)) _flag_names.push_back(x.first);
else if (!prior_other) continue;
_flags[x.first] = x.second;
}
}
std::string ZConfig::ToString(ZConfig* default_conf) const {
std::ostringstream oss;
int flag_idx = 0;
auto process_fn = [&](const ZConfig* cfg, const std::string& name) {
oss << (flag_idx++ ? " " : "") << name;
auto iter = cfg->_flags.find(name);
if (cfg->_flags.end() != iter && "" != iter->second) {
oss << "=" << iter->second;
}
};
for (auto& n : _flag_names) process_fn(this, n);
if (default_conf) {
for (auto& n : default_conf->_flag_names) if (!HasFlag(n)) process_fn(default_conf, n);
}
return oss.str();
}
bool ZConfig::Empty() const {
return _flag_names.empty();
}
ZGenerator::ZGenerator(const std::string& rule): _rule(rule) {}
void ZGenerator::SetRule(const std::string& rule) { _rule = rule; }
std::string ZGenerator::GetRule() const { return _rule; }
std::string ZGenerator::Generate(const std::vector<std::string>& inputs) {
auto res = _rule;
for (int idx = 0; ; ++idx) {
char buf[16];
int n = snprintf(buf, sizeof(buf), "${%d}", idx + 1);
auto p = res.find(buf);
if (std::string::npos == p) break;
if (idx >= (int)inputs.size()) {
ZTHROW("no enough inputs(size:%lu) for rule(%s)", inputs.size(), _rule.data());
}
res.replace(p, n, inputs[idx]);
}
return res;
}
//TODO analyze these macros:
//CPPFLAGS - is the variable name for flags to the C preprocessor.
//CXXFLAGS - is the standard variable name for flags to the C++ compiler.
//CFLAGS - is the standard name for a variable with compilation flags.
//LDFLAGS - should be used for search flags/paths (-L).
//LDLIBS - for linking libraries.
ZConfig* DefaultObjectConfig() {
static ZConfig s_obj_conf;
//TODO execute only once
//TODO modify SetFlag -> Set
s_obj_conf.SetFlag("-idirafter " + *AccessBuildRootDir());
return &s_obj_conf;
}
ZConfig* DefaultStaticLibraryConfig() {
static ZConfig s_static_lib_conf;
if (!s_static_lib_conf.HasFlag("crs")) {
s_static_lib_conf.SetFlag("crs");
}
return &s_static_lib_conf;
}
ZConfig* DefaultSharedLibraryConfig() {
static ZConfig s_shared_lib_conf;
return &s_shared_lib_conf;
}
ZConfig* DefaultBinaryConfig() {
static ZConfig s_binary_conf;
return &s_binary_conf;
}
//the scenario is like this:
// project root dir(running ./BUILD): /workspace/
// project build root dir: /workspace/${BUILD_DIR_NAME}/
// cur_dir(including BUILD.cpp): /workspace/core/
// p(lib_name): curl/net
// project inner path: /core/curl/net
// build path: /workspace/${BUILD_DIR_NAME}/core/curl/libnet.a
std::string ConvertToProjectInnerPath(const std::string& p) {
if ('/' == p.at(0) || '@' == p.at(0)) return p;
std::string result =
fs::absolute(p).lexically_relative(*AccessProjectRootDir()).lexically_normal();
#ifdef __MACH__
result = fs::path(result).lexically_relative(fs::current_path());
#endif
if ('/' != result.at(0)) result = "/" + result;
return result;
}
std::string GetBuildPath(const std::string& path) {
if ("" == path) return path;
fs::path build_path = path;
if ('/' != path.at(0) || !StringBeginWith(path, *AccessBuildRootDir())) {
const std::string prj_inner_path = ConvertToProjectInnerPath(path);
if (StringBeginWith(prj_inner_path, *AccessProjectRootDir())) {
build_path = *AccessBuildRootDir() +
prj_inner_path.substr(AccessProjectRootDir()->size());
} else {
build_path = *AccessBuildRootDir() + prj_inner_path.substr(1);
}
}
build_path = build_path.lexically_normal();
auto build_dir = build_path.parent_path();
if (!fs::exists(build_dir)) {
fs::create_directories(build_dir);
}
return build_path;
}
std::string GetBuildRootPath(const std::string& path) {
std::string root = path;
if ('/' != *root.rbegin()) root += "/";
auto p = root.find(StringPrintf("/%s/", BUILD_DIR_NAME));
if (std::string::npos != p) {
return root.substr(0, p + strlen(BUILD_DIR_NAME) + 2);
}
return path;
}
ZFile*& AccessFileInternal(const std::string& file, bool create_file = false,
bool need_build = false, FileType ft = FT_NONE) {
std::string p = file;
if (FT_SOURCE_FILE == ft || StringEndWith(file, C_CPP_SOURCE_SUFFIXES)) {
if (FT_NONE == ft) ft = FT_SOURCE_FILE;
p = fs::absolute(file).lexically_normal();
} else if (FT_HEADER_FILE == ft || StringEndWith(file, C_CPP_HEADER_SUFFIXES)) {
if (FT_NONE == ft) ft = FT_HEADER_FILE;
p = fs::absolute(file).lexically_normal();
} if (FT_PROTO_FILE == ft || StringEndWith(file, ".proto")) {
if (FT_NONE == ft) ft = FT_PROTO_FILE;
p = fs::absolute(file).lexically_normal();
} else {
p = ConvertToProjectInnerPath(p);
}
auto*& result = GlobalFiles()[p];
if (!result) {
if (create_file) {
if ('@' == file.at(0)) {
ZTHROW("can't create external library(%s), please import it first", file.data());
}
result = ZF::Create<ZFile>(p, ft, need_build);
}
}
return result;
}
std::vector<std::string> Glob(const std::vector<std::string>& rules,
const std::vector<std::string>& exclude_rules, const std::string& dir) {
std::vector<std::regex> exclude_regexes = {std::regex("(^|/)BUILD.cpp$")};
for (auto exclude_rule : exclude_rules) {
exclude_rule = StringReplaceAll(exclude_rule, ".", "\\.");
exclude_rule = StringReplaceAll(exclude_rule, "**", "*");
exclude_rule = StringReplaceAll(exclude_rule, "*", "[^/]*");
if (std::string::npos == exclude_rule.find("/")) {
exclude_regexes.emplace_back("(^|/)" + exclude_rule + "$");
} else {
exclude_regexes.emplace_back(exclude_rule + "$");
}
}
auto hit_exclude_rule_fn = [&](const std::string& f) -> bool {
for (const auto& r : exclude_regexes) if (std::regex_search(f, r)) return true;
return false;
};
std::vector<std::string> result;
std::set<std::string> uniq_results;
for (auto rule : rules) {
bool recursive = std::string::npos != rule.find("**");
recursive = recursive || std::string::npos != rule.find("/"); //detect sub dir
rule = StringReplaceAll(rule, ".", "\\.");
rule = StringReplaceAll(rule, "**", "*");
rule = StringReplaceAll(rule, "*", "[^/]*");
std::regex r(rule + "$");
for (auto f : ListFilesUnderDir(dir, "", recursive)) {
if (uniq_results.count(f)) continue;
auto rf = f; //rf(reg file): file for matching regex rules
if (StringBeginWith(rf, dir)) {
rf = rf.substr(dir.size());
if ('/' == rf.at(0)) rf = rf.substr(1);
}
if (std::regex_search(rf, r) && !hit_exclude_rule_fn(rf)) {
uniq_results.insert(f);
result.push_back(f);
}
}
}
return result;
}
void SetObjsFlags(const std::vector<std::string>& paths, const std::vector<std::string>& flags) {
for (auto path : paths) {
if (std::string::npos != GetDirnameFromPath(path).find('*')) {
ZTHROW("doesn't support '*' glob within dir name(%s)", path.data());
}
if (std::string::npos == path.find('*')) {
for (auto flag : flags) AccessObject(path)->SetFlag(flag);
} else {
for (const auto& f :
Glob({GetFilenameFromPath(path)}, {"BUILD.cpp"}, GetDirnameFromPath(path))) {
for (auto flag : flags) AccessObject(f)->SetFlag(flag);
}
}
}
}
ZGenerator*& AccessDefaultGenerator(const std::string& suffix) {
static std::unordered_map<std::string, ZGenerator*> s_generators;
return s_generators[suffix];
}
ZGenerator* GetDefaultGenerator(const std::string& suffix) {
return AccessDefaultGenerator(suffix);
}
void RegisterDefaultGenerator(const std::string& suffix, const ZGenerator& g) {
auto*& def_g = AccessDefaultGenerator(suffix);
if (!def_g) {
def_g = new ZGenerator(g);
} else {
*def_g = g;
}
}
long AcquireFileMTime(const std::string& path) {
static std::unordered_map<std::string, long> s_file_stats;
static std::mutex s_mtx;
long mtime = 0;
RunWithLock(s_mtx, [&mtime, &path]() {
if (s_file_stats.count(path)) mtime = s_file_stats[path];
});
if (0 == mtime) {
struct stat result;
if (0 != stat(path.data(), &result)) return -1;
#ifdef __MACH__
mtime = result.st_mtimespec.tv_sec * 1000000000UL + result.st_mtimespec.tv_nsec;
#else
mtime = result.st_mtim.tv_sec * 1000000000UL + result.st_mtim.tv_nsec;
#endif
RunWithLock(s_mtx, [&mtime, &path]() { s_file_stats[path] = mtime; });
}
return mtime;
}
std::string FormalizeLibraryName(const std::string& lib_name, bool is_imported_lib = false) {
std::string name = lib_name;
if (is_imported_lib && '@' != name.at(0)) name = "@" + name;
if (':' == name.at(0)) name = name.substr(1);
std::string filename = GetFilenameFromPath(name);
auto p = filename.rfind(':');
if (std::string::npos != p) {
filename[p] = '/';
if (std::string::npos != filename.find(':')) {
ZTHROW("the filename part of lib_name(%s) should only have one ':' at most",
lib_name.data());
}
name = GetDirnameFromPath(name) + filename;
}
name = ConvertToProjectInnerPath(name);
if ('@' == name.at(0) && std::string::npos == name.find('/')) name += "/";
return fs::path(name).lexically_normal();
}
void ProcessDepsRecursively(const std::vector<ZFile*>& deps, const std::function<void(ZFile*)>& fn,
std::set<ZFile*>* uniq_deps = nullptr) {
auto valid_uniq_deps = uniq_deps ? uniq_deps : new std::set<ZFile*>();
for (auto iter = deps.rbegin(); deps.rend() != iter; ++iter) {
if (!valid_uniq_deps->insert(*iter).second) continue;
ProcessDepsRecursively((*iter)->GetDeps(), fn, valid_uniq_deps);
fn(*iter);
}
if (!uniq_deps) delete valid_uniq_deps;
}
void UpdateOptimizationLevel(std::string& cmd, size_t pos = 0, bool del_other_opts = false) {
if (!CommandArgs::Has("-O") || pos >= cmd.size()) return;
auto o_level = StringPrintf(" -O%d", CommandArgs::Get<int>("-O", 0));
auto p = cmd.find(" -O", pos);
if (std::string::npos == p) {
if (0 != CommandArgs::Get<int>("-O", 0) && !del_other_opts) cmd.append(o_level);
} else {
auto p_end = cmd.find(" ", p + 3);
//it's compatible with std::string::npos == p_end
auto level = cmd.substr(p + 3, p_end - (p + 3));
if ("" == level || "0" == level || "1" == level || "2" == level ||
"3" == level || "g" == level || "s" == level || "fast" == level) {
cmd.replace(p, p_end - p, del_other_opts ? "" : o_level);
if (!del_other_opts) del_other_opts = true;
}
//process other duplicated -O flags
UpdateOptimizationLevel(cmd, p + 3, del_other_opts);
}
}
ZFile::ZFile(const std::string& path, FileType ft, bool need_build):
_file(path), _ft(ft), _build_done(!need_build) {
if (need_build) _file = GetBuildPath(path);
_cwd = fs::current_path();
_compiler = *AccessDefaultCompiler(fs::path(_file).extension());
}
ZFile::~ZFile() {
if (_conf) delete _conf;
if (_generator) delete _generator;
}
ZFile* ZFile::SetGenerator(const ZGenerator& g) {
if (!_generator) _generator = new ZGenerator();
*_generator = g;
return this;
}
ZGenerator* ZFile::GetGenerator() const {
return _generator;
}
ZConfig* ZFile::GetConfig() {
if (!_conf) _conf = new ZConfig();
return _conf;
}
void ZFile::SetConfig(const ZConfig& conf) {
if (!_conf) {
_conf = new ZConfig();
} else if (!_conf->Empty()) {
fprintf(stderr, "[Warn]substitute the existed config for file '%s'\n", _file.data());
}
*_conf = conf;
}
ZFile* ZFile::SetFlag(const std::string& flag) {
GetConfig()->SetFlag(flag);
return this;
}
ZFile* ZFile::SetFlags(const std::vector<std::string>& flags) {
GetConfig()->SetFlags(flags);
return this;
}
ZFile* ZFile::AddDep(ZFile* dep) {
if (_uniq_deps.insert(dep->GetFilePath()).second) {
_deps.push_back(dep);
ProcessDepsRecursively(_deps, [&](ZFile* dep) {
if (dep == this) ZTHROW("Detected circular dependency for '%s'", _file.data());
});
//libs should be built before objs, considering following scenario:
// AccessLibrary("cc_base_proto")->AddProto("base.proto");
// AccessLibrary("cc_ps_proto")
// ->AddProto("ps.proto")
// ->AddDep("cc_base_proto");
//
//for libcc_ps_proto.a, libcc_base_proto.a should be compiled first, because
//compiling ps.pb.cc needs base.pb.h;
if (FT_OBJ_FILE != dep->GetFileType() && _deps.size() > 1) {
for (int i = _deps.size() - 2; i >= -1; --i) {
if (i >= 0 && FT_OBJ_FILE == _deps[i]->GetFileType()) continue;
std::swap(_deps[i + 1], _deps.back());
break;
}
}
}
return this;
}
ZFile* ZFile::AddDep(const std::string& dep) {
auto f = AccessFileInternal(dep);
if (!f) ZTHROW("no this dep(%s), please use AccessXXX to create it first", dep.data());
return AddDep(f);
}
ZFile* ZFile::AddDepLibs(const std::vector<std::string>& dep_libs) {
for (auto dep : dep_libs) {
std::string dep_name = FormalizeLibraryName(dep);
bool is_glob_match = ('/' == *dep_name.rbegin());
if ('*' == *dep_name.rbegin()) {
dep_name.pop_back();
if (std::string::npos != dep_name.find('*')) {
ZTHROW("contain '*' in the middle of dep name(%s)", dep_name.data());
}
is_glob_match = true;
}
if ('@' == dep_name.at(0) && !is_glob_match) {
auto pkg_name = StringSplit(dep_name, '/')[0].substr(1);
if ("@" + pkg_name + "/" + pkg_name == dep_name) {
if (auto f = AccessFileInternal(dep_name)) {
AddDep(f);
continue;
}
dep_name = "@" + pkg_name + "/";
is_glob_match = true;
}
}
auto process_fn = [this](const std::string& dep_name, bool is_glob_match) {
bool find_libs = false;
auto& files = GlobalFiles();
for (auto iter = files.lower_bound(dep_name); files.end() != iter; ++iter) {
if (!StringBeginWith(iter->first, is_glob_match ? dep_name : dep_name + "/")) break;
if (iter->second && FT_LIB_FILE == iter->second->GetFileType()) {
AddDep(iter->second);
find_libs = true;
if (!is_glob_match && iter->first == dep_name) break;
}
}
if (!find_libs) {
if (!is_glob_match) AddDep(AccessLibrary(dep_name));
else ZTHROW("can't find any lib with the '%s' prefix", dep_name.data());
}
};
if ('@' != dep_name.at(0)) {
if (is_glob_match || fs::is_directory(*AccessProjectRootDir() + dep_name)) {
if ('/' != *dep_name.rbegin()) dep_name += "/";
RegisterRunnerBeforeBuildAll([process_fn, dep_name]() {
process_fn(dep_name, true);
});
continue;
}
}
process_fn(dep_name, is_glob_match);
}
return this;
}
const std::vector<ZFile*>& ZFile::GetDeps() const {
return _deps;
}
void ZFile::DumpDepsRecursively(std::string* dump_sinker) const {
std::ostringstream oss;
std::string indent;
std::function<void(const ZFile*)> process_dep_fn;
process_dep_fn = [&](const ZFile* file) {
auto p = file->GetFilePath();
if (StringBeginWith(p, "/usr/include/")) return;
if (FT_HEADER_FILE == file->GetFileType() && StringBeginWith(p, "/usr/")) return;
oss << indent << (indent.empty() ? "" : " ") << p << std::endl;
indent += ".";
for (auto dep : file->GetDeps()) process_dep_fn(dep);
indent.pop_back();
};
process_dep_fn(this);
if (dump_sinker) *dump_sinker = oss.str();
else printf("%s", oss.str().data());
}
void ZFile::SetFullCommand(const std::string& cmd) {
_cmd = cmd;
}
std::string ZFile::GetFullCommand(bool print_pretty) {
if ("" == _cmd) ComposeCommand();
if (print_pretty) {
auto p = _cmd.find(" -o ");
if (std::string::npos != p) {
p = _cmd.find(" ", p + 4);
if (std::string::npos != p) {
return _cmd.substr(0, p) + StringReplaceAll(_cmd.substr(p), " ", "\n");
}
}
return StringReplaceAll(_cmd, " ", "\n");
}
return _cmd;
}
std::string ZFile::GetFilePath() const {
return _file;
}
FileType ZFile::GetFileType() const {
return _ft;
}
std::string ZFile::GetCwd() const {
return _cwd;
}
bool ZFile::ComposeCommand() {
if ("" == _cmd && !_generated_by_dep) {
if (_generator) {
_cmd = _generator->Generate({_file});
} else {
fs::path p(_file);
auto g = GetDefaultGenerator(p.extension());
if (g) {
_cmd = g->Generate({_file});
} else if (StringEndWith(_file, C_CPP_HEADER_SUFFIXES)) {
_ft = FT_HEADER_FILE;
_build_done = true;
return false;
} else {
fprintf(stderr, "[Warn]no need to build this file(%s)\n", _file.data());
_build_done = true;
return false;
}
}
}
return "" != _cmd || _generated_by_dep;
}
void ZFile::BeTarget() {
AddTarget(this);
}
struct Md5Cache {
static auto& GetAll() {
using T = std::map<std::string, std::string>;
GlobalResource<T, GRT_MD5>::InitOnce([](T& file_md5s) {
for (auto& line : StringSplit(StringFromFile(*AccessBuildRootDir() +
"BUILD.md5s"), '\n')) {
const auto& infos = StringSplit(line, ' ');
if (2 == infos.size()) file_md5s[infos[0]] = infos[1];
}
});
return GlobalResource<T, GRT_MD5>::Resource();
}
static std::string Get(const std::string& file, bool check_change = true) {
auto& file_md5s = GetAll();
std::string old_md5;
static std::mutex s_mtx;
RunWithLock(s_mtx, [&]() { if (file_md5s.count(file)) old_md5 = file_md5s[file]; });
//start with '@': checked md5 already, and it changed
//start with '*': checked md5 already, and it has no change
if ("" != old_md5 && (!check_change || ('@' == old_md5.at(0) || '*' == old_md5.at(0)))) {
return old_md5;
}
auto new_md5 = ExecuteCmd(StringPrintf("md5sum %s | awk '{print $1}'", file.data()));
new_md5 = (new_md5 != old_md5 ? "@" : "*") + new_md5;
RunWithLock(s_mtx, [&]() { file_md5s[file] = new_md5; });
return new_md5;
}
};
bool ZFile::Build() {
bool debug_flag = true;
if (_build_done && !_forced_build) return _has_been_built;
bool build_dependencies = false;
for (auto dep : GetDeps()) {
bool build_res = dep->Build();
build_dependencies |= build_res;
if (*AccessDebugLevel() > 0 && debug_flag && build_dependencies) {
printf("> build %s since the dependency '%s' has been built\n",
_file.data(), dep->GetFilePath().data());
debug_flag = false;
}
}
if (!ComposeCommand()) return false;
bool need_build = (build_dependencies || !fs::exists(_file) ||
fs::is_empty(_file) || _forced_build);
if (*AccessDebugLevel() > 0 && debug_flag && need_build) {
if (!fs::exists(_file)) {
printf("> build %s since it doesn't exist\n", _file.data());
} else if (_forced_build) {
printf("> build %s since _forced_build == true\n", _file.data());
}
debug_flag = false;
}
if (!need_build) need_build = (_cmd != StringFromFile(GetBuildPath(_file) + ".cmd"));
if (*AccessDebugLevel() > 0 && debug_flag && need_build) {
printf("> build %s since the cmd '%s' has been changed to '%s'\n", _file.data(),
StringFromFile(GetBuildPath(_file) + ".cmd").data(), _cmd.data());
debug_flag = false;
}
if (!need_build) {
auto mtime = AcquireFileMTime(_file);
for (auto dep : GetDeps()) {
if (!fs::exists(dep->GetFilePath())) continue;
if (AcquireFileMTime(dep->GetFilePath()) >= mtime) {
if ('@' != Md5Cache::Get(dep->GetFilePath()).at(0)) continue; //md5 has no change
need_build = true;
if (*AccessDebugLevel() > 0 && debug_flag && need_build) {
printf("> build %s since the mtime(%ld) of dependence '%s' is bigger than "
"target's mtime(%ld)\n", _file.data(),
AcquireFileMTime(dep->GetFilePath()),
dep->GetFilePath().data(), mtime);
debug_flag = false;
}
break;
}
}
}
if (need_build) {
_has_been_built = true;
if (_generated_by_dep) {
for (auto dep : GetDeps()) {
if (fs::exists(_file)) break;
if (*AccessDebugLevel() > 0) {
printf("> generate %s by build dep(%s)\n", _file.data(),
dep->GetFilePath().data());
}
dep->_forced_build = true;
dep->Build();
}
} else {
StringToFile(_cmd, GetBuildPath(_file) + ".cmd");
ZF::ExecuteBuild(this);
if (_forced_build) _forced_build = false;
}
}
_build_done = true;
return _has_been_built;
}
ZObject::ZObject(const std::string& src_file, const std::string& obj_file):
ZFile(obj_file, FT_OBJ_FILE, true) {
_name = src_file;
_src = fs::absolute(src_file).lexically_normal();
_compiler = *AccessDefaultCompiler(fs::path(_src).extension());
_file = GetBuildPath("" == obj_file ?
StringReplaceSuffix(_src, C_CPP_SOURCE_SUFFIXES, ".o") : obj_file);
auto dep_file = _file + ".d";
auto load_dep_file_fn = [this, dep_file]() {
if (!fs::exists(dep_file)) return;
auto s = StringFromFile(dep_file);
auto parts = StringSplit(s, ':');
if (2 != parts.size()) ZTHROW("can't parse the dependence file(%s)", dep_file.data());
for (auto dep : StringSplit(StringRightTrim(StringReplaceAll(parts[1], "\\\n", "")), ' ')) {
//skip check fs::exists(dep), e.g. header file renamed
AddDep(AccessFile(dep));
}
};
if (fs::exists(dep_file)) load_dep_file_fn();
else RegisterRunnerAfterBuildAll(load_dep_file_fn);
}
std::string ZObject::GetSourceFile() const {
return _src;
}
ZObject* ZObject::AddIncludeDir(const std::string& dir) {
if ("" == dir) return this;
std::string inc = fs::absolute(dir).lexically_normal();
if ('/' != *inc.rbegin()) inc += "/";
if (!_uniq_inc_dirs.count(inc)) {
_inc_dirs.push_back(inc);
_uniq_inc_dirs.insert(inc);
}
return this;
}
std::vector<std::string> ZObject::GetIncludeDirs() const {
return _inc_dirs;
}
void ZObject::AddObjectUser(ZFile* file) {
_users.push_back(file);
}
bool ZObject::ComposeCommand() {
if ("" == _cmd) {
_cmd = StringPrintf("%s -c -o %s -MD -MF %s.d", _compiler.data(), _file.data(), _file.data());
std::set<ZFile*> uniq_deps;
auto handle_dep_fn = [&](ZFile* dep) {
if (FT_LIB_FILE == dep->GetFileType()) {
for (auto inc_dir : ((ZLibrary*)dep)->GetIncludeDirs()) AddIncludeDir(inc_dir);
}
};
//it makes sense to add project root as one include path
AddIncludeDir(*AccessProjectRootDir());
ProcessDepsRecursively(GetDeps(), handle_dep_fn, &uniq_deps);
ProcessDepsRecursively(_users, handle_dep_fn, &uniq_deps);
for (const auto& inc : _inc_dirs) {
//avoid hiding system header like <string.h>
_cmd += StringPrintf(" -idirafter %s", inc.data());
}
if (_conf) {
_cmd += " " + _conf->ToString(DefaultObjectConfig());
} else {
_cmd += " " + DefaultObjectConfig()->ToString();
}
_cmd += " " + _src;
}
UpdateOptimizationLevel(_cmd);
return true;
}
//TODO support always_link = true
ZLibrary::ZLibrary(const std::string& lib_name, bool is_static_lib): ZFile("", FT_LIB_FILE, true) {
_name = lib_name;
std::string lib_file = lib_name;
if (!StringEndWith(lib_file, ".a|.so")) {
lib_file += (is_static_lib ? ".a" : ".so");
}
if (!StringBeginWith(GetFilenameFromPath(lib_file), "lib")) {
lib_file = GetDirnameFromPath(lib_file) + "lib" + GetFilenameFromPath(lib_file);
}
_file = GetBuildPath(lib_file);
_compiler = *AccessDefaultCompiler(fs::path(_file).extension());
_is_static_lib = is_static_lib;
}
ZLibrary::ZLibrary(const std::string& name, const std::vector<std::string>& inc_dirs,
const std::string& lib_file): ZFile("", FT_LIB_FILE, false) {
_name = name;
if ("" != lib_file) _file = fs::absolute(lib_file).lexically_normal();
for (auto& inc_dir : inc_dirs) {
_inc_dirs.insert(fs::absolute(inc_dir).lexically_normal());
}
_is_static_lib = StringEndWith(_file, ".a");
}
std::string GetObjBindName(const std::string& src, const std::string& bind_name) {
std::string suffix = StringReplaceAll(bind_name, "/", "-");
suffix = StringReplaceAll(suffix, ".", "-");
return StringReplaceSuffix(src, C_CPP_SOURCE_SUFFIXES, suffix + ".o");
}
ZLibrary* ZLibrary::AddObjs(const std::vector<std::string>& src_files, bool bind_flag) {
for (auto src : src_files) AddObj(AccessObject(src, bind_flag ? GetObjBindName(src, _name) : ""));
return this;
}
ZLibrary* ZLibrary::AddObj(ZFile* obj) {
if (FT_OBJ_FILE != obj->GetFileType()) {
ZTHROW("for lib(%s), '%s' is not an ZObject instance", FP(this), FP(obj));
}
if (!_is_static_lib && !obj->GetConfig()->HasFlag("-fPIC")) {
obj->GetConfig()->SetFlag("-fPIC");
}
auto f = (ZObject*)obj;
f->SetFlags(_objs_flags);
_objs.push_back(f);
ZF::AddObjectUser(f, this);
AddDep(f);
return this;
}
const std::vector<ZObject*>& ZLibrary::GetObjs() const {
return _objs;
}
ZLibrary* ZLibrary::SetObjsFlags(const std::vector<std::string>& flags) {
for (auto f : flags) _objs_flags.push_back(f);
for (auto obj : _objs) obj->SetFlags(flags);
return this;
}
ZLibrary* ZLibrary::AddProto(const std::string& proto_file) {
if (!_added_protobuf_lib_dep) {
auto& files = GlobalFiles();
for (auto iter = files.lower_bound("@protobuf/"); files.end() != iter; ++iter) {
if (!StringBeginWith(iter->first, "@protobuf/")) break;
if (iter->second && FT_LIB_FILE == iter->second->GetFileType()) {
AddDep(iter->second);
_added_protobuf_lib_dep = true;
}
}
}
return AddObj(AccessProto(proto_file)->SpawnObj());
}
ZLibrary* ZLibrary::AddProtos(const std::vector<std::string>& proto_files) {
for (auto p : proto_files) AddProto(p);
return this;
}
const std::set<std::string>& ZLibrary::GetIncludeDirs() {
if (_inc_dirs.empty()) {
bool all_srcs_are_pb_cc = !_objs.empty();
for (auto obj : _objs) {
if (!StringEndWith(obj->GetSourceFile(), ".pb.cc")) {
all_srcs_are_pb_cc = false;
break;
}
}
if (all_srcs_are_pb_cc) {
_inc_dirs.insert(*AccessBuildRootDir());
} else {
_inc_dirs.insert(_cwd);
}
}
return _inc_dirs;
}
ZLibrary* ZLibrary::AddIncludeDir(const std::string& dir, bool create_alias_name) {
if (!create_alias_name) _inc_dirs.insert(fs::absolute(dir).lexically_normal());
else {
_inc_dirs.insert(GetBuildPath(GetCwd()));
std::string alias = dir;
if ('/' == *alias.rbegin()) alias.pop_back();
auto alias_build_path = fs::path(GetBuildPath(GetCwd()) + "/" + alias).lexically_normal();
if (fs::exists(alias_build_path)) {
if (fs::is_symlink(alias_build_path) &&
fs::equivalent(fs::read_symlink(alias_build_path), GetCwd())) return this;
ZTHROW("create alias(%s) for lib inc dir failed, since it exists already",
alias_build_path.string().data());
}
fs::create_directories(alias_build_path.parent_path());
fs::create_directory_symlink(GetCwd(), alias_build_path);
}
return this;
}
std::string ZLibrary::GetLinkDir() const {
return fs::path(_file).parent_path();
}
std::string ZLibrary::GetLinkLib() const {
std::string fn = fs::path(_file).filename().string();
fn = StringReplaceSuffix(fn, ".a|.so", "");
if (StringBeginWith(fn, "lib")) fn = fn.substr(3);
return fn;
}
bool ZLibrary::IsStaticLibrary() const {
return _is_static_lib;
}
ZLibrary* ZLibrary::AddLib(ZFile* lib, bool whole_archive) {
if (_is_static_lib) {
ZTHROW("can't add static library(%s) to build a new static library(%s)", FP(lib), FP(this));
}
if (FT_LIB_FILE != lib->GetFileType()) {
ZTHROW("for lib(%s), this file(%s) is not an instance of ZLibrary", FP(this), FP(lib));
}
auto f = (ZLibrary*)lib;
for (auto obj : f->GetObjs()) {
if (!obj->GetConfig()->HasFlag("-fPIC")) obj->GetConfig()->SetFlag("-fPIC");
}
if (whole_archive) _whole_archive_libs.push_back(f);
else _libs.push_back(f);
AddDep(f);
return this;
}
std::vector<ZLibrary*> ZLibrary::GetLibs() const {
auto result = _whole_archive_libs;
result.insert(result.end(), _libs.begin(), _libs.end());
return result;
}
bool ZLibrary::ComposeCommand() {
if ("" == _cmd) {
if (_is_static_lib) {
if (_objs.empty()) {
if (GetDeps().empty()) ZTHROW("found uninitialized library(%s)", _name.data());
_build_done = true;
return false;
}
_cmd = StringPrintf("%s", _file.data());
} else {
_cmd = StringPrintf("%s -shared -o %s", _compiler.data(), _file.data());
}
for (auto obj : _objs) {
_cmd += StringPrintf(" %s", obj->GetFilePath().data());
}
for (auto lib : _libs) {
if (lib->IsUsedAsWholeArchive()) {
_cmd += " -Wl,--whole-archive";
_cmd += StringPrintf(" %s", lib->GetFilePath().data());
_cmd += " -Wl,--no-whole-archive";
} else _cmd += StringPrintf(" %s", lib->GetFilePath().data());
}
if (!_whole_archive_libs.empty()) {
_cmd += " -Wl,--whole-archive";
for (auto lib : _whole_archive_libs) {
_cmd += StringPrintf(" %s", lib->GetFilePath().data());
}
_cmd += " -Wl,--no-whole-archive";
}