Debian Codegraph @

tools/build-tool/code/toolcompile.pas

raw
1 {
2 Copyright 2014-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Compiling with FPC. }
17 unit ToolCompile;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses Classes,
24 CastleStringUtils,
25 ToolManifest, ToolArchitectures;
26
27 type
28 TCompilationMode = (cmRelease, cmValgrind, cmDebug);
29
30 { Compiler options are passed to @link(Compile) procedure and friends,
31 and are read-only there.
32 Caller should set the fields of this class before calling @link(Compile).
33
34 The objects here (like TCastleStringList) are
35 - owned by this class (created in constructor and destroyed in destructor)
36 - never @nil
37 - initially empty. }
38 TCompilerOptions = class
39 OS: TOS;
40 CPU: TCPU;
41 Mode: TCompilationMode;
42 { Compile with memory leak detection.
43 For now, only supported by CompileFpc, ignored by CompileLazbuild and CompileDelphi. }
44 DetectMemoryLeaks: boolean;
45 { Define symbols during compilation.
46 For now, only supported by CompileFpc and CompileDelphi, ignored by CompileLazbuild. }
47 Defines: TCastleStringList;
48 { Units / includes paths.
49 For now, only supported by CompileFpc and CompileDelphi, ignored by CompileLazbuild. }
50 SearchPaths: TCastleStringList;
51 { Library path.
52 For now, only supported by CompileFpc, ignored by CompileDelphi and CompileLazbuild. }
53 LibraryPaths: TCastleStringList;
54 { Extra compiler options, directly passed to fpc/dcc on command-line.
55 For now, only supported by CompileFpc and CompileDelphi, ignored by CompileLazbuild. }
56 ExtraOptions: TCastleStringList;
57 { Allow using cache. @true by default. }
58 AllowCache: Boolean;
59 constructor Create;
60 destructor Destroy; override;
61 end;
62
63 { Compile with Pascal compiler.
64 SearchPaths, ExtraOptions may be @nil (same as empty). }
65 procedure Compile(Compiler: TCompiler;
66 const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
67
68 { Compile with FPC and proper command-line option given file.
69 SearchPaths, ExtraOptions may be @nil (same as empty). }
70 procedure CompileFpc(
71 const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
72
73 { Compile with Delphi and proper command-line option given file.
74 SearchPaths, ExtraOptions may be @nil (same as empty). }
75 procedure CompileDelphi(
76 const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
77
78 { Compile with lazbuild. }
79 procedure CompileLazbuild(
80 const WorkingDirectory, LazarusProjectFile: String; const Options: TCompilerOptions);
81
82 { Run lazbuild with specified command-line options.
83 Warning: This @italic(may) modify LazbuildOptions contents,
84 consider them undefined after this call. }
85 procedure RunLazbuild(const WorkingDirectory: String; const LazbuildOptions: TCastleStringList);
86 procedure RunLazbuild(const WorkingDirectory: String; const LazbuildOptions: array of String);
87
88 { Output path, where temporary things like units (and iOS stuff)
89 are placed. }
90 function CompilationOutputPath(const Compiler: TCompiler;
91 const OS: TOS; const CPU: TCPU;
92 const WorkingDirectory: String): String;
93
94 function ModeToString(const M: TCompilationMode): String;
95 function StringToMode(const S: String): TCompilationMode;
96
97 var
98 { Should we use the -Vxxx parameter, that is necessary if you got FPC
99 from the fpc-3.0.3.intel-macosx.cross.ios.dmg
100 (official "FPC for iOS" installation). }
101 FpcVersionForIPhoneSimulator: String = 'auto';
102
103 const
104 CompilationModeToStr: array [TCompilationMode] of string = (
105 'release',
106 'valgrind',
107 'debug'
108 );
109
110 implementation
111
112 uses SysUtils, Process,
113 CastleUtils, CastleLog, CastleFilesUtils, CastleFindFiles,
114 CastleInternalTools,
115 ToolCommonUtils, ToolUtils, ToolFpcVersion, ToolCompilerInfo;
116
117 { TCompilerOptions ----------------------------------------------------------- }
118
119 constructor TCompilerOptions.Create;
120 begin
121 inherited;
122 Defines := TCastleStringList.Create;
123 SearchPaths := TCastleStringList.Create;
124 LibraryPaths := TCastleStringList.Create;
125 ExtraOptions := TCastleStringList.Create;
126 AllowCache := true;
127 end;
128
129 destructor TCompilerOptions.Destroy;
130 begin;
131 FreeAndNil(Defines);
132 FreeAndNil(SearchPaths);
133 FreeAndNil(LibraryPaths);
134 FreeAndNil(ExtraOptions);
135 inherited;
136 end;
137
138 { TFpcVersionForIPhoneSimulatorChecked --------------------------------------- }
139
140 type
141 TFpcVersionForIPhoneSimulatorChecked = class
142 strict private
143 class var
144 IsCached: boolean;
145 CachedValue: String;
146 class function AutoDetect(const FpcVer: TFpcVersion): String; static;
147 public
148 { Return FpcVersionForIPhoneSimulator, but the 1st time this is run,
149 we check and optionally change the returned value to something better. }
150 class function Value(const FpcVer: TFpcVersion): String; static;
151 end;
152
153 class function TFpcVersionForIPhoneSimulatorChecked.AutoDetect(
154 const FpcVer: TFpcVersion): String; static;
155 begin
156 if (not Odd(FpcVer.Minor)) and
157 (not Odd(FpcVer.Release)) then
158 begin
159 { If we have a stable FPC version (like 3.0.0, 3.0.2, 3.0.4...)
160 then for iPhone Simulator pass -V with release bumped +1
161 (making it 3.0.1, 3.0.3, 3.0.5...). }
162 Result := Format('%d.%d.%d', [
163 FpcVer.Major,
164 FpcVer.Minor,
165 FpcVer.Release + 1]);
166 Writeln('Auto-detected FPC version for iPhone Simulator as ' + Result);
167 end else
168 { In other cases, do not pass any -Vxxx for iPhone Simulator.
169 This is OK for FPC 3.1.1 from FPC SVN. }
170 Result := '';
171 end;
172
173 class function TFpcVersionForIPhoneSimulatorChecked.Value(
174 const FpcVer: TFpcVersion): String; static;
175 var
176 FpcOutput, FpcExe: String;
177 FpcExitStatus: Integer;
178 begin
179 if not IsCached then
180 begin
181 CachedValue := FpcVersionForIPhoneSimulator;
182 IsCached := true;
183
184 if CachedValue = 'auto' then
185 CachedValue := AutoDetect(FpcVer);
186
187 if CachedValue <> '' then
188 begin
189 FpcExe := FindExeFpcCompiler;
190 MyRunCommandIndir(GetCurrentDir, FpcExe, ['-V' + CachedValue, '-iV'], FpcOutput, FpcExitStatus);
191 if FpcExitStatus <> 0 then
192 begin
193 WritelnWarning('Failed to execute FPC with "-V' + CachedValue + '" option, indicating that using this option for iPhone Simulator is invalid.' + NL +
194 ' We will continue assuming that --fpc-version-iphone-simulator is empty (using normal FPC version to compile for iPhone Simulator).' + NL +
195 ' Call with the correct --fpc-version-iphone-simulator on the command-line to get rid of this warning.');
196 CachedValue := '';
197 end;
198 end;
199 end;
200
201 Result := CachedValue;
202 end;
203
204 { CleanDirectory ------------------------------------------------------------- }
205
206 type
207 TCleanDirectoryHelper = class
208 DeletedFiles: Cardinal; //< only for DeleteFoundFile
209 procedure DeleteFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
210 end;
211
212 procedure TCleanDirectoryHelper.DeleteFoundFile(const FileInfo: TFileInfo; var StopSearch: boolean);
213 begin
214 if Verbose then
215 Writeln('Deleting ' + FileInfo.AbsoluteName);
216 CheckDeleteFile(FileInfo.AbsoluteName);
217 Inc(DeletedFiles);
218 end;
219
220 { Clean compilation trash in Directory, recursively. }
221 procedure CleanDirectory(const Directory: String);
222 var
223 Helper: TCleanDirectoryHelper;
224
225 procedure DeleteFilesRecursive(const Mask: String);
226 begin
227 FindFiles(Directory, Mask, false,
228 {$ifdef FPC}@{$endif} Helper.DeleteFoundFile, [ffRecursive]);
229 end;
230
231 begin
232 Helper := TCleanDirectoryHelper.Create;
233 try
234 // clean FPC compilation stuff
235 DeleteFilesRecursive('*.ppu');
236 DeleteFilesRecursive('*.o');
237 DeleteFilesRecursive('*.or');
238 DeleteFilesRecursive('*.rst');
239 DeleteFilesRecursive('*.rsj');
240 Writeln('Deleted ', Helper.DeletedFiles, ' files');
241 finally FreeAndNil(Helper) end;
242 end;
243
244 { CopyCacheContents ---------------------------------------------------------- }
245
246 type
247 TCopyFromCacheHelper = class
248 DestPath: String;
249 procedure FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
250 end;
251
252 procedure TCopyFromCacheHelper.FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
253 var
254 DestFile: String;
255 begin
256 DestFile := DestPath + FileInfo.Name;
257
258 { We copy from cache *without* overwriting. This way, in case the cache contained
259 outdated / invalid outputs, on first run new compilation (FPC) should overwrite it,
260 and we should not overwrite it back with cache. }
261
262 if FileExists(DestFile) then
263 begin
264 WritelnVerbose(Format('Not copying from cache "%s", already exists', [FileInfo.Name]));
265 end else
266 begin
267 WritelnVerbose(Format('Copying from cache "%s"', [FileInfo.Name]));
268 CheckCopyFile(FileInfo.AbsoluteName, DestFile);
269 end;
270 end;
271
272 procedure CopyCacheContents(const SourcePath, DestPath: String);
273 var
274 Helper: TCopyFromCacheHelper;
275 begin
276 Helper := TCopyFromCacheHelper.Create;
277 try
278 Helper.DestPath := InclPathDelim(DestPath);
279 FindFiles(SourcePath, '*', false, {$ifdef FPC}@{$endif}Helper.FoundFile, []);
280 finally FreeAndNil(Helper) end;
281 end;
282
283 { Other routines ------------------------------------------------------------- }
284
285 { Writeln a message that FPC/Lazarus crashed and we will retry,
286 and clean compilation leftover files. }
287 procedure FpcLazarusCrashRetry(const WorkingDirectory, ToolName, ProjectName: String);
288 begin
289 Writeln('-------------------------------------------------------------');
290 Writeln('It seems ' + ToolName + ' crashed. If you can reproduce this problem, please report it to http://bugs.freepascal.org/ ! We want to help ' + ProjectName + ' developers to fix this problem, and the only way to do it is to report it. If you need help creating a good bugreport, speak up on the ' + ProjectName + ' mailing list or Castle Game Engine forum.');
291 Writeln;
292 Writeln('As a workaround, right now we''ll clean your project, and (if we have permissions) the Castle Game Engine units, and try compiling again.');
293 Writeln('-------------------------------------------------------------');
294 { when we're called to compile a project, WorkingDirectory is the project path }
295 CleanDirectory(WorkingDirectory);
296 CleanDirectory(TempOutputPath(WorkingDirectory, false));
297 if CastleEnginePath <> '' then
298 begin
299 { Compiling project using build tool (through FPC or lazbuild)
300 should *not* leave any file in src/ .
301 But, just to be safe, try to clear it if possible. }
302 CleanDirectory(CastleEnginePath + 'src' + PathDelim);
303 CleanDirectory(CastleEnginePath + 'packages' + PathDelim + 'lib' + PathDelim);
304 end;
305 end;
306
307 function FilterFpcOutput(var Line: String; const Data: Pointer): Boolean;
308 var
309 LineLower: String;
310 begin
311 { Lowercase once and later use IsPrefix many times with IgnoreCase=false (faster). }
312 LineLower := LowerCase(Line);
313 Result := not (
314 { Occur without -vb }
315 IsPrefix('generics.collections.pas(', LineLower, false) or
316 IsPrefix('generics.dictionaries.inc(', LineLower, false) or
317 IsPrefix('generics.defaults.pas(', LineLower, false) or
318 { Occur with -vb }
319 (Pos('generics.collections.ppu:generics.collections.pas(', LineLower) <> 0) or
320 (Pos('generics.collections.ppu:generics.dictionaries.inc(', LineLower) <> 0) or
321 (Pos('generics.defaults.ppu:generics.defaults.pas(', LineLower) <> 0) or
322 { Others }
323 IsSuffix('warning: section "__datacoal_nt" is deprecated', LineLower, false) or
324 IsSuffix('note: change section name to "__data"', LineLower, false) or
325 (Line = '.section __DATA, __datacoal_nt, coalesced') or
326 (Line = ' ^ ~~~~~~~~~~~~~~')
327 );
328 // Uncomment this just to debug that our line splitting in TCaptureOutputFilter works
329 // Line := '<begin>' + Line + '<end>';
330 end;
331
332 procedure CompileFpc(const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
333 var
334 CastleEngineSrc: String;
335 FpcVer: TFpcVersion;
336 FpcOptions: TCastleStringList;
337
338 procedure AddEnginePath(Path: String);
339 begin
340 Path := CastleEngineSrc + Path;
341 if not DirectoryExists(Path) then
342 WritelnWarning('Path', 'Path "%s" does not exist. Make sure that $CASTLE_ENGINE_PATH points to the directory containing Castle Game Engine sources.', [Path]);
343 FpcOptions.Add('-Fu' + Path);
344 FpcOptions.Add('-Fi' + Path);
345 end;
346
347 procedure AddEngineSearchPaths;
348 var
349 S: String;
350 begin
351 if CastleEngineSrc <> '' then
352 begin
353 for S in EnginePaths do
354 AddEnginePath(S);
355
356 { Do not add castle-fpc.cfg.
357 Instead, rely on code below duplicating castle-fpc.cfg logic
358 (reasons: engine sources, with castle-fpc.cfg, may not be available
359 where build-tool is called).
360
361 FpcOptions.Add('-dCASTLE_ENGINE_PATHS_ALREADY_DEFINED');
362 FpcOptions.Add('@' + InclPathDelim(CastleEnginePath) + 'castle_game_engine(or castle-engine)/castle-fpc.cfg');
363 }
364 end;
365 end;
366
367 procedure AddSearchPaths;
368 var
369 S: String;
370 begin
371 for S in Options.SearchPaths do
372 begin
373 FpcOptions.Add('-Fu' + S);
374 FpcOptions.Add('-Fi' + S);
375 end;
376 end;
377
378 procedure AddEngineLibraryPaths;
379 var
380 S: String;
381 begin
382 if CastleEngineSrc <> '' then
383 for S in EngineLibraryPaths do
384 FpcOptions.Add('-Fl' + CastleEngineSrc + S);
385 end;
386
387 procedure AddLibraryPaths;
388 var
389 S: String;
390 begin
391 for S in Options.LibraryPaths do
392 FpcOptions.Add('-Fl' + S);
393 end;
394
395 function IsIOS: boolean;
396 begin
397 Result :=
398 (Options.OS = iphonesim) or
399 ((Options.OS = iOS) and (Options.CPU = arm)) or
400 ((Options.OS = iOS) and (Options.CPU = aarch64));
401 end;
402
403 procedure AddIOSOptions;
404 {$ifdef DARWIN}
405 const
406 SimulatorSdk = '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk';
407 DeviceSdk = '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk';
408 {$endif}
409 var
410 LikeIOS: boolean; // physical iOS or iPhoneSimulator
411 VersionForSimulator: String;
412 begin
413 LikeIOS := false;
414
415 if Options.OS = iphonesim then
416 begin
417 LikeIOS := true;
418 VersionForSimulator := TFpcVersionForIPhoneSimulatorChecked.Value(FpcVer);
419 if VersionForSimulator <> '' then
420 FpcOptions.Add('-V' + VersionForSimulator);
421 {$ifdef DARWIN}
422 FpcOptions.Add('-XR' + SimulatorSdk);
423 {$endif}
424 end;
425
426 if (Options.OS = iOS) and (Options.CPU = arm) then
427 begin
428 LikeIOS := true;
429 FpcOptions.Add('-Cparmv7');
430 FpcOptions.Add('-Cfvfpv3');
431 {$ifdef DARWIN}
432 FpcOptions.Add('-XR' + DeviceSdk);
433 {$endif}
434 end;
435
436 if (Options.OS = iOS) and (Options.CPU = aarch64) then
437 begin
438 LikeIOS := true;
439 {$ifdef DARWIN}
440 FpcOptions.Add('-XR' + DeviceSdk);
441 {$endif}
442 end;
443
444 Assert(LikeIOS = IsIOS);
445
446 // options for all iOS-like platforms
447 if LikeIOS then
448 begin
449 FpcOptions.Add('-Cn');
450 FpcOptions.Add('-dCASTLE_IOS');
451
452 { This corresponds to the iOS version used when compiling FPC 3.0.3 RTL
453 from the latest official FPC release for iOS.
454 With -WP5.1, I got a lot of warnings that FPC RTL was for iOS 7.0.
455 Also, I got an error:
456 clang: error: -fembed-bitcode is not supported on versions of iOS prior to 6.0
457 }
458 FpcOptions.Add('-WP7.0');
459
460 { This option is actually ununsed, since we pass -Cn
461 and later create the library manually.
462
463 Add -w to ignore linker warnings
464
465 This seems the only way to get rid of Xcode (>= 8.3) linker errors when
466 compiling iOS project. The error is
467
468 Warning:pointer not aligned at address...
469
470 and it is caused when compiling x86 code for iPhone Simulator.
471 The error is inside FPC RTL, FPC developers consider this warning
472 unnecessary, aligning the relevant structured would be wasteful:
473 https://bugs.freepascal.org/view.php?id=31696
474
475 See more:
476 https://forum.lazarus.freepascal.org/index.php?topic=36978.0
477 https://stackoverflow.com/questions/41229076/project-settings-recommends-compiler-warning-suspicious-moves
478 }
479 //FpcOptions.Add('-k-w');
480
481 { This option is actually ununsed, since we pass -Cn
482 and later create the library manually. }
483 FpcOptions.Add('-o' +
484 CompilationOutputPath(coFpc, Options.OS, Options.CPU, WorkingDirectory) +
485 'libcge_ios_project_unused.a');
486 end;
487 end;
488
489 procedure AddMacOSOptions;
490 begin
491 if (Options.OS = darwin) and (Options.CPU = X86_64) then
492 begin
493 // Lazarus passes such options to compile with Cocoa, so we do too. Do not seem necessary in practice.
494 FpcOptions.Add('-k-framework');
495 FpcOptions.Add('-kCocoa');
496 // TODO: Lazarus proposes such debugger options; should we pass them too? Why aren't they FPC defaults?
497 // FpcOptions.Add('-gw2');
498 // FpcOptions.Add('-godwarfsets');
499 end;
500 end;
501
502 procedure AddDefines;
503 var
504 S: String;
505 begin
506 for S in Options.Defines do
507 FpcOptions.Add('-d' + S);
508 end;
509
510 procedure CopyFromCache(const CompilationOutputPathFinal: String);
511 var
512 CachePathFull: String;
513 begin
514 CachePathFull := CachePath +
515 CPUToString(Options.CPU) + '-' + OSToString(Options.OS) + PathDelim +
516 CompilationModeToStr[Options.Mode] + PathDelim;
517 if DirectoryExists(CachePathFull) then
518 begin
519 WritelnVerbose(Format('Using cache "%s" to speed up compilation', [CachePathFull]));
520 CopyCacheContents(CachePathFull, CompilationOutputPathFinal);
521 end;
522 end;
523
524 var
525 FpcOutput, FpcExe, CompilationOutputPathFinal, FpcStandardUnitsPath: String;
526 FpcExitStatus: Integer;
527 begin
528 FpcVer := FpcVersion;
529
530 CompilationOutputPathFinal := CompilationOutputPath(coFpc, Options.OS, Options.CPU, WorkingDirectory);
531
532 if Options.AllowCache then
533 CopyFromCache(CompilationOutputPathFinal);
534
535 FpcOptions := TCastleStringList.Create;
536 try
537 if CastleEnginePath <> '' then
538 CastleEngineSrc := CastleEnginePath + 'src' + PathDelim
539 else
540 CastleEngineSrc := '';
541
542 AddEngineSearchPaths;
543 AddSearchPaths;
544 AddEngineLibraryPaths;
545 AddLibraryPaths;
546
547 { Specify the compilation options explicitly,
548 duplicating logic from ../castle-fpc.cfg .
549 (Engine sources may be possibly not available,
550 so we also cannot depend on castle-fpc.cfg being available.) }
551 FpcOptions.Add('-l');
552 FpcOptions.Add('-vwn');
553 FpcOptions.Add('-Ci');
554 FpcOptions.Add('-Mobjfpc');
555 FpcOptions.Add('-Sm');
556 FpcOptions.Add('-Sc');
557 FpcOptions.Add('-Sg');
558 FpcOptions.Add('-Si');
559 FpcOptions.Add('-Sh');
560 FpcOptions.Add('-vm2045'); // do not show Warning: (2045) APPTYPE is not supported by the target OS
561 FpcOptions.Add('-vm5024'); // do not show Hint: (5024) Parameter "..." not used
562 FpcOptions.Add('-vb'); // show full filenames, makes it easier for software (like VS Code problem matcher and CGE editor) to figure out the relevant file
563
564 // do not show
565 // Warning: Constructing a class "TCustomDictionaryEnumerator$4$crc6100464F" with abstract method "GetCurrent"
566 // Warning: Constructing a class "TCustomDictionaryEnumerator$4$crcBD4794B2" with abstract method "DoMoveNext"
567 // Update: No need to hide it anymore: our FilterFpcOutput handles it, and thus we don't need to hide this useful warning for user code
568 // FpcOptions.Add('-vm04046');
569
570 if FpcVer.AtLeast(3, 1, 1) then
571 begin
572 // do not show Warning: Symbol "TArrayHelper$1" is experimental
573 // (only for FPC 3.1.1, for 3.0.x we fix this in our custom Generics.Collections unit)
574 // Update: No need to hide it anymore: our FilterFpcOutput handles it, and thus we don't need to hide this useful warning for user code
575 // FpcOptions.Add('-vm05063');
576
577 // do not show
578 // Note: Private type "TCustomPointersEnumerator$2<CASTLEVECTORSINTERNALSINGLE.TGenericVector2,CASTLEVECTORS.TCustomList$1$crc1D7BB6F0.PT>.T" never used
579 // Update: No need to hide it anymore: our FilterFpcOutput handles it, and thus we don't need to hide this useful warning for user code
580 // FpcOptions.Add('-vm5071');
581 end;
582
583 if FpcVer.AtLeast(3, 2, 0) then
584 begin
585 // do not show
586 // Warning: function result variable of a managed type does not seem to be initialized
587 // (a lot of false warnings since FPC 3.3.1)
588 FpcOptions.Add('-vm5093');
589
590 // do not show
591 // Note: Call to subroutine "$1" marked as inline is not inlined
592 // (In FPC 3.3.1, not in FPC 3.1.1 rev 38027)
593 // (flood of notes after using Generics.Collections, but also from other units)
594 FpcOptions.Add('-vm6058');
595 end;
596
597 if FpcVer.AtLeast(3, 3, 1) then
598 begin
599 // do not show
600 // Warning: Local variable "$1" of a managed type does not seem to be initialized
601 // (a lot of false warnings since FPC 3.3.1)
602 FpcOptions.Add('-vm5089');
603
604 // do not show
605 // Warning: Variable "OutputFace" of a managed type does not seem to be initialized
606 // (3 false warnings since FPC 3.3.1 in Kraft)
607 FpcOptions.Add('-vm5090');
608 end;
609
610 if (Options.OS = iOS) and not FpcVer.AtLeast(3, 2, 2) then
611 // Before FPC 3.2.2, the OS=iOS was designated as OS=darwin for FPC
612 FpcOptions.Add('-Tdarwin')
613 else
614 FpcOptions.Add('-T' + OSToString(Options.OS));
615
616 FpcOptions.Add('-P' + CPUToString(Options.CPU));
617
618 { Release build and valgrind build are quite similar, they share many options. }
619 if Options.Mode in [cmRelease, cmValgrind] then
620 begin
621 { Aarch64 optimizations exhibit bugs, on all OSes, with older FPC:
622
623 - Bugs reproducible with FPC = 3.2.0 and FPC 3.3.1 (rev <= 48104).
624 - Fixed in FPC 3.2.0 and later FPC unstable from GitLab.
625
626 See https://trello.com/c/5ydB4MuA/113-enable-again-aarch64-optimizations .
627
628 Testcases:
629
630 - iOS:
631
632 With FPC 3.0.3 on iOS/aarch64 (physical iOS, 64-bit)
633 it seems all programs compiled with -O1 or -O2 crash at start.
634
635 - Android:
636
637 Reading some PNG fails (testcase: Silhouette), at least with -O2, fails.
638
639 It is unsure with which FPC version this was reproducible.
640 Probably some FPC 3.0.x.
641 Michalis can no longer reproduce it with FPC 3.3.1 revision 42921
642 (latest revision as of 2019/09/05).
643
644 - Android and Nintendo Switch and iOS:
645
646 TDrawableImage.Draw3x3 calculations are wildly wrong,
647 and in effect TDrawableImage.Draw3x3 usually doesn't seem to draw anything.
648 It seems like DrawWidth parameter is not received correctly,
649 but workarounding it only uncovers more problems, it looks like
650 the values in local Single variables there randomly change.
651
652 This is reproducible with FPC 3.3.1 revision 42921
653 (latest revision as of 2019/09/05).
654 }
655 if (Options.CPU = Aarch64) and
656 (not FpcVer.AtLeast(3, 2, 2)) then
657 begin
658 FpcOptions.Add('-O-');
659 WritelnWarning('Disabling optimizations, because they are buggy on Aarch64 with older FPC. Upgrade to FPC >= 3.2.2.');
660 end else
661 FpcOptions.Add('-O2');
662 // Not using -O3: Fails badly on 64-bit Raspberry Pi (Linux/Aarch64),
663 // at TTestCastleComponentSerialize.TestCustomSerialization
664 //FpcOptions.Add('-O3');
665 FpcOptions.Add('-dRELEASE');
666 end;
667
668 case Options.Mode of
669 cmRelease:
670 begin
671 FpcOptions.Add('-Xs');
672 end;
673 cmValgrind:
674 begin
675 { See https://castle-engine.io/profiling_using_valgrind
676 for reasons of Valgrind options. }
677 FpcOptions.Add('-gv');
678 FpcOptions.Add('-gl');
679 end;
680 cmDebug:
681 begin
682 FpcOptions.Add('-Cr'); // Range checking, see https://github.com/michaliskambi/modern-pascal-introduction/wiki/What-are-range-and-overflow-checks-(and-errors)-in-Pascal
683 FpcOptions.Add('-Co'); // Overflow checking, see https://github.com/michaliskambi/modern-pascal-introduction/wiki/What-are-range-and-overflow-checks-(and-errors)-in-Pascal
684 FpcOptions.Add('-Sa'); // Assertions
685 FpcOptions.Add('-CR'); // Verify method calls
686 FpcOptions.Add('-g'); // Debug info (automatic), for debuggers
687 FpcOptions.Add('-gl'); // Line info (in backtraces)
688 FpcOptions.Add('-dDEBUG');
689 { Disable -Ct (Stack checking) added to fpc.cfg in default
690 fpcupdeluxe installation when DEBUG is defined.
691 Because it crashes when application is run on iPhone,
692 at least with FPC 3.2.2. }
693 if IsIOS then
694 FpcOptions.Add('-Ct-');
695 end;
696 {$ifndef COMPILER_CASE_ANALYSIS}
697 else raise EInternalError.Create('CompileFpc: Mode?');
698 {$endif}
699 end;
700
701 if (Options.OS = Android) and (Options.CPU = arm) then
702 begin
703 { Our platform is armeabi-v7a, see ToolAndroidPackage
704 comments about armeabi-v7a.
705 Note: the option below seems not necessary when using -CfVFPV3?
706 At least, nothing crashes.
707 Possibly -CfVFPV3 implies this anyway. }
708 FpcOptions.Add('-CpARMV7A');
709
710 { Necessary to work fast.
711 See https://castle-engine.io/android-FAQ#notes-about-compiling-with-hard-floats--cfvfpv3 }
712 FpcOptions.Add('-CfVFPV3');
713
714 { This allows to "sacrifice precision for performance"
715 according to http://wiki.freepascal.org/ARM_compiler_options .
716
717 But it causes too much precision loss?
718 escape_universe fails with
719 I/escape_universe( 7761): Exception: Exception "EInvalidGameConfig" :
720 I/escape_universe( 7761): Gun auto_fire_interval cannot be <= 0
721
722 Speed gain untested.
723
724 For now unused. }
725 //FpcOptions.Add('-OoFASTMATH');
726
727 { This should *not* be defined (when compiling our code or RTL).
728 It makes our code use -CaEABIHF/armeabi-v7a-hard
729 https://android.googlesource.com/platform/ndk/+/353e653824b79c43b948429870d0abeedebde386/docs/HardFloatAbi.md
730 which has incompatible call mechanism.
731
732 And indeed, doing PlaySound crashes at alSourcef call (to OpenAL)
733 from TInternalSoundSource.SetMinGain. Reproducible with escape_universe.
734
735 fpcupdeluxe default cross-compiler to Android also uses this. }
736 //FpcOptions.Add('-CaEABIHF');
737 end;
738
739 if Options.DetectMemoryLeaks then // see https://castle-engine.io/memory_leaks
740 begin
741 FpcOptions.Add('-gl'); // HeapTrc
742 FpcOptions.Add('-gh'); // LineInfo
743 end;
744
745 AddIOSOptions;
746 AddMacOSOptions;
747 AddDefines;
748 FpcOptions.AddRange(Options.ExtraOptions);
749
750 FpcOptions.Add(CompileFile);
751 FpcOptions.Add('-FU' + CompilationOutputPathFinal);
752
753 Writeln('FPC executing...');
754 FpcExe := FindExeFpcCompiler(true, FpcStandardUnitsPath);
755
756 if FpcStandardUnitsPath <> '' then
757 begin
758 FpcOptions.Add('-Fu' + FpcStandardUnitsPath);
759
760 { Do not read system-wide FPC config, to allow this bundled FPC to coexist
761 with your system-wide FPC installation without any relation. }
762 FpcOptions.Add('-n');
763
764 { As the bundled FPC has no config, by default it is rather silent.
765 Add options to display info (and Warnings and Notes) during compilation to see progress. }
766 FpcOptions.Add('-viwn');
767 end;
768
769 RunCommandIndirPassthrough(WorkingDirectory, FpcExe, FpcOptions.ToArray, FpcOutput, FpcExitStatus, '', '', @FilterFpcOutput);
770 if FpcExitStatus <> 0 then
771 begin
772 if (Pos('Fatal: Internal error', FpcOutput) <> 0) or
773 (Pos('Error: Compilation raised exception internally', FpcOutput) <> 0) then
774 begin
775 FpcLazarusCrashRetry(WorkingDirectory, 'FPC', 'FPC');
776 RunCommandIndirPassthrough(WorkingDirectory, FpcExe, FpcOptions.ToArray, FpcOutput, FpcExitStatus, '', '', @FilterFpcOutput);
777 if FpcExitStatus <> 0 then
778 { do not retry compiling in a loop, give up }
779 raise Exception.Create('Failed to compile');
780 end else
781 raise Exception.Create('Failed to compile');
782 end;
783 finally FreeAndNil(FpcOptions) end;
784 end;
785
786 procedure Compile(Compiler: TCompiler; const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
787 begin
788 { resolve Compiler to something other than coAutodetect }
789 if Compiler = coAutodetect then
790 begin
791 if FindExeFpcCompiler(false) <> '' then
792 Compiler := coFpc
793 else
794 if FindDelphiPath(false) <> '' then
795 Compiler := coDelphi
796 else
797 raise Exception.Create('Neither FPC nor Delphi found, cannot autodetect compiler');
798 end;
799 Assert(Compiler <> coAutodetect);
800
801 case Compiler of
802 coFpc: CompileFpc(WorkingDirectory, CompileFile, Options);
803 coDelphi: CompileDelphi(WorkingDirectory, CompileFile, Options);
804 else raise EInternalError.Create('Compile: Compiler?');
805 end;
806 end;
807
808 procedure CompileDelphi(const WorkingDirectory, CompileFile: String; const Options: TCompilerOptions);
809 var
810 CastleEngineSrc: String;
811 DccOptions: TCastleStringList;
812
813 { Add search namespaces, to keep basic units like SysUtils accessible
814 without namespace. This follows the DPROJ settings generated by Delphi
815 for new projects. }
816 procedure AddSearchNamespaces;
817 const
818 SearchNamespacesGeneral = 'System;Xml;Data;Datasnap;Web;Soap';
819 SearchNamespacesWindows = 'Winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde';
820 var
821 SearchNamespaces: String;
822 begin
823 { calculate SearchNamespaces }
824 SearchNamespaces := SearchNamespacesGeneral;
825 if Options.OS in AllWindowsOSes then
826 SearchNamespaces := SAppendPart(SearchNamespaces, ';', SearchNamespacesWindows);
827
828 DccOptions.Add('-NS' + SearchNamespaces);
829 end;
830
831 procedure AddEnginePath(Path: String);
832 begin
833 Path := CastleEngineSrc + Path;
834 if not DirectoryExists(Path) then
835 WritelnWarning('Path', 'Path "%s" does not exist. Make sure that $CASTLE_ENGINE_PATH points to the directory containing Castle Game Engine sources.', [Path]);
836 DccOptions.Add('-U' + Path);
837 DccOptions.Add('-I' + Path);
838 end;
839
840 procedure AddEngineSearchPaths;
841 var
842 S: String;
843 begin
844 if CastleEngineSrc <> '' then
845 begin
846 for S in EnginePaths do
847 AddEnginePath(S);
848 for S in EnginePathsDelphi do
849 AddEnginePath(S);
850 end;
851 end;
852
853 procedure AddSearchPaths;
854 var
855 S: String;
856 begin
857 for S in Options.SearchPaths do
858 begin
859 DccOptions.Add('-U' + S);
860 DccOptions.Add('-I' + S);
861 end;
862 end;
863
864 procedure AddOutputPaths;
865 var
866 OutPath: String;
867 begin
868 OutPath := CompilationOutputPath(coDelphi, Options.OS, Options.CPU, WorkingDirectory);
869 { Looks like DCCxxx cannot handle parameters with spaces? Answers
870 Fatal: F1026 File not found: 'Game.dpr'
871 for
872 -NUC:\Users\michalis\Documents\Castle Game Engine Projects\my-new-project-delphi3d\castle-engine-output\compilation\delphi\x86_64-win64\
873 Workaround: pass relative paths. }
874 OutPath := ExtractRelativePath(InclPathDelim(WorkingDirectory), OutPath);
875 DccOptions.Add('-NU' + OutPath);
876 DccOptions.Add('-NH' + OutPath);
877 DccOptions.Add('-NO' + OutPath);
878 DccOptions.Add('-NB' + OutPath);
879 DccOptions.Add('-NX' + OutPath);
880 end;
881
882 procedure AddDefines;
883 var
884 S: String;
885 begin
886 for S in Options.Defines do
887 DccOptions.Add('-d' + S);
888 end;
889
890 var
891 DelphiPath, Dcc, DccExe: String;
892 DccOutput: String;
893 DccExitStatus: Integer;
894 begin
895 DelphiPath := FindDelphiPath(true);
896
897 { calculate Dcc, which is compiler basename with OS/CPU suffix.
898 The combinations confirmed to be possible in Delphi 11:
899
900 dcc32 - Win32
901 dcc64 - Win64
902 dccaarm - Android/Arm
903 dccaarm64 - Android/Arm64
904 dcciosarm64 - iOS/Arm64
905 dcclinux64 - Linux/x86_64
906 dccosx64 - macos/x86_64
907 dccosxarm64 - macos/Arm64
908 }
909 Dcc := 'dcc';
910 case Options.OS of
911 Win32, Win64: ;
912 Android: Dcc += 'a';
913 iOS : Dcc += 'ios';
914 Linux : Dcc += 'linux';
915 MacOSX : Dcc += 'osx';
916 else raise Exception.CreateFmt('Operating system "%s" not supported by Delphi', [OSToString(Options.OS)]);
917 end;
918 case Options.CPU of
919 i386 : Dcc += '32';
920 x86_64 : Dcc += '64';
921 Arm : Dcc += 'arm';
922 Aarch64: Dcc += 'arm64';
923 else raise Exception.CreateFmt('CPU "%s" not supported by Delphi', [CPUToString(Options.CPU)]);
924 end;
925
926 DccExe := DelphiPath + 'bin' + PathDelim + Dcc + ExeExtension;
927 if not RegularFileExists(DccExe) then
928 raise Exception.CreateFmt('Cannot find Delphi compiler for this OS/CPU: %s', [DccExe]);
929
930 if CastleEnginePath <> '' then
931 CastleEngineSrc := CastleEnginePath + 'src' + PathDelim
932 else
933 CastleEngineSrc := '';
934
935 DccOptions := TCastleStringList.Create;
936 try
937 Writeln('Delphi compiler executing...');
938
939 AddSearchNamespaces;
940 AddEngineSearchPaths;
941 AddSearchPaths;
942 AddOutputPaths;
943
944 // TODO: Do something more useful for release optimizations or debugging
945 case Options.Mode of
946 cmRelease, cmValgrind: DccOptions.Add('-dRELEASE');
947 cmDebug : DccOptions.Add('-dDEBUG');
948 {$ifndef COMPILER_CASE_ANALYSIS}
949 else raise EInternalError.Create('CompileDelphi: Mode?');
950 {$endif}
951 end;
952
953 AddDefines;
954 DccOptions.AddRange(Options.ExtraOptions);
955
956 DccOptions.Add(CompileFile);
957
958 RunCommandIndirPassthrough(WorkingDirectory, DccExe, DccOptions.ToArray, DccOutput, DccExitStatus);
959 if DccExitStatus <> 0 then
960 raise Exception.Create('Failed to compile');
961 finally FreeAndNil(DccOptions) end;
962 end;
963
964 procedure RunLazbuild(const WorkingDirectory: String; const LazbuildOptions: TCastleStringList);
965 var
966 LazbuildExe: String;
967 LazbuildOutput: String;
968 LazbuildExitStatus: Integer;
969 begin
970 LazbuildExe := FindExeLazarus('lazbuild');
971 if LazbuildExe = '' then
972 raise EExecutableNotFound.Create('Cannot find "lazbuild" program. Make sure it is installed, and available on environment variable $PATH. If you use the CGE editor, you can also set Lazarus location in "Preferences".');
973
974 RunCommandIndirPassthrough(WorkingDirectory,
975 LazbuildExe, LazbuildOptions.ToArray, LazbuildOutput, LazbuildExitStatus, '', '', @FilterFpcOutput);
976 if LazbuildExitStatus <> 0 then
977 begin
978 { Old lazbuild can fail with exception like this:
979
980 An unhandled exception occurred at $0000000000575F5F:
981 EAccessViolation: Access violation
982 $0000000000575F5F line 590 of exttools.pas
983 $000000000057A027 line 1525 of exttools.pas
984 $000000000057B231 line 1814 of exttools.pas
985
986 Simply retrying works.
987 }
988 if (Pos('Fatal: Internal error', LazbuildOutput) <> 0) or
989 (Pos('EAccessViolation: Access violation', LazbuildOutput) <> 0) then
990 begin
991 FpcLazarusCrashRetry(WorkingDirectory, 'Lazarus (lazbuild)', 'Lazarus');
992 RunCommandIndirPassthrough(WorkingDirectory,
993 LazbuildExe, LazbuildOptions.ToArray, LazbuildOutput, LazbuildExitStatus, '', '', @FilterFpcOutput);
994 if LazbuildExitStatus <> 0 then
995 { do not retry compiling in a loop, give up }
996 raise Exception.Create('Failed to compile');
997 end else
998 raise Exception.Create('Failed to compile');
999 end else
1000
1001 // lazbuild from Lazarus 1.6.4 doesn't support add-package-link
1002 if (Pos('Invalid option at position 3: "add-package-link"', LazbuildOutput) <> 0) and
1003 (LazbuildOptions.IndexOf('--add-package-link') <> -1) then
1004 begin
1005 Writeln('lazbuild does not support --add-package-link, retrying without it');
1006 LazbuildOptions.Delete(LazbuildOptions.IndexOf('--add-package-link'));
1007 RunCommandIndirPassthrough(WorkingDirectory,
1008 LazbuildExe, LazbuildOptions.ToArray, LazbuildOutput, LazbuildExitStatus, '', '', @FilterFpcOutput);
1009 if LazbuildExitStatus <> 0 then
1010 { do not retry compiling in a loop, give up }
1011 raise Exception.Create('Failed to compile');
1012 end;
1013 end;
1014
1015 procedure RunLazbuild(const WorkingDirectory: String; const LazbuildOptions: array of String);
1016 var
1017 L: TCastleStringList;
1018 begin
1019 L := TCastleStringList.Create;
1020 try
1021 L.Assign(LazbuildOptions);
1022 RunLazbuild(WorkingDirectory, L);
1023 finally FreeAndNil(L) end;
1024 end;
1025
1026 procedure CompileLazbuild(const WorkingDirectory, LazarusProjectFile: String; const Options: TCompilerOptions);
1027 var
1028 LazbuildOptions: TCastleStringList;
1029
1030 procedure LazbuildAddPackage(const LpkFileName: String);
1031 begin
1032 LazbuildOptions.Clear;
1033 LazbuildOptions.Add('--add-package-link');
1034 LazbuildOptions.Add(CastleEnginePath + LpkFileName);
1035 RunLazbuild(WorkingDirectory, LazbuildOptions);
1036 end;
1037
1038 begin
1039 LazbuildOptions := TCastleStringList.Create;
1040 try
1041 // register CGE packages first
1042 if CastleEnginePath <> '' then
1043 begin
1044 LazbuildAddPackage('packages/castle_base.lpk');
1045 LazbuildAddPackage('packages/castle_window.lpk');
1046 LazbuildAddPackage('packages/castle_components.lpk');
1047 LazbuildAddPackage('packages/castle_editor_components.lpk');
1048 end;
1049
1050 LazbuildOptions.Clear;
1051 LazbuildOptions.Add('--os=' + OSToString(Options.OS));
1052 LazbuildOptions.Add('--cpu=' + CPUToString(Options.CPU));
1053 { // Do not pass --build-mode, as project may not have it defined.
1054 if Options.Mode = cmDebug then
1055 LazbuildOptions.Add('--build-mode=Debug')
1056 else
1057 LazbuildOptions.Add('--build-mode=Release');
1058 }
1059
1060 { For historic reasons, Lazarus < 2.2 defaults to Carbon on macOS,
1061 even on 64-bit macOS where you cannot link with Carbon.
1062 And since macOS Catalina (10.15) all applications *must* be 64-bit
1063 (32-bit is no longer supported) so this is important.
1064 So we change it to cocoa.
1065
1066 TODO: This likely prevents the project from using it's own,
1067 custom widgetset in case of macOS.
1068
1069 But there doesn't seem any better way of fixing this per-project.
1070 I cannot use "Custom Options",
1071
1072 if (TargetOS='darwin') and (TargetCPU='x86_64') then
1073 LCLWidgetType := 'cocoa';
1074
1075 -- it looks like LCLWidgetType is ignored in "Custom Options".
1076
1077 I cannot use "Additions and Overrides", as it doesn't seem to allow
1078 to choose widgetset per-platform (like per-OS, or per-OS-and-CPU).
1079 It would only allow to set Cocoa always.
1080 Or in a specific build mode, but then I would need to
1081 - maintain this build mode in my examples,
1082 - 2 times (for both Debug/Release, I would need a copy DebugMacOS and ReleaseMacOS)
1083 - and require it in all user projects (this is not acceptable).
1084 }
1085 if (Options.OS = darwin) and (Options.CPU = X86_64) then
1086 LazbuildOptions.Add('--widgetset=cocoa');
1087 LazbuildOptions.Add(LazarusProjectFile);
1088
1089 RunLazbuild(WorkingDirectory, LazbuildOptions);
1090 finally FreeAndNil(LazbuildOptions) end;
1091 end;
1092
1093 function CompilationOutputPath(const Compiler: TCompiler;
1094 const OS: TOS; const CPU: TCPU;
1095 const WorkingDirectory: String): String;
1096 begin
1097 Result := TempOutputPath(WorkingDirectory) + 'compilation' + PathDelim;
1098 if Compiler = coDelphi then
1099 Result += 'delphi' + PathDelim;
1100 Result += CPUToString(CPU) + '-' + OSToString(OS) + PathDelim;
1101 CheckForceDirectories(Result);
1102 end;
1103
1104 const
1105 CompilationModeNames: array [TCompilationMode] of string =
1106 ('release', 'valgrind', 'debug');
1107
1108 function ModeToString(const M: TCompilationMode): String;
1109 begin
1110 Result := CompilationModeNames[M];
1111 end;
1112
1113 function StringToMode(const S: String): TCompilationMode;
1114 begin
1115 for Result in TCompilationMode do
1116 if AnsiSameText(CompilationModeNames[Result], S) then
1117 Exit;
1118 raise Exception.CreateFmt('Invalid compilation mode name "%s"', [S]);
1119 end;
1120
1121 end.