[rbuild]
[reactos.git] / reactos / tools / rbuild / backend / mingw / mingw.cpp
1 /*
2 * Copyright (C) 2005 Casper S. Hornstrup
3 * 2006 Christoph von Wittich
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 #include "../../pch.h"
20
21 #include "mingw.h"
22 #include <assert.h>
23 #include "modulehandler.h"
24
25 #ifdef _MSC_VER
26 #define popen _popen
27 #define pclose _pclose
28 #endif//_MSC_VER
29
30 using std::string;
31 using std::vector;
32 using std::set;
33 using std::map;
34
35 typedef set<string> set_string;
36
37 const struct ModuleHandlerInformations ModuleHandlerInformations[] = {
38 { HostTrue, "", "", "" }, // BuildTool
39 { HostFalse, "", "", "" }, // StaticLibrary
40 { HostFalse, "", "", "" }, // ObjectLibrary
41 { HostFalse, "", "", "$(LDFLAG_DRIVER)" }, // Kernel
42 { HostFalse, "", "", "$(LDFLAG_DRIVER)" }, // KernelModeDLL
43 { HostFalse, "-D__NTDRIVER__", "", "$(LDFLAG_DRIVER)" }, // KernelModeDriver
44 { HostFalse, "", "", "$(LDFLAG_DLL)" }, // NativeDLL
45 { HostFalse, "-D__NTAPP__", "", "$(LDFLAG_NATIVE)" }, // NativeCUI
46 { HostFalse, "", "", "$(LDFLAG_DLL)" }, // Win32DLL
47 { HostFalse, "", "", "$(LDFLAG_DLL)" }, // Win32OCX
48 { HostFalse, "", "", "$(LDFLAG_CONSOLE)" }, // Win32CUI
49 { HostFalse, "", "", "$(LDFLAG_WINDOWS)" }, // Win32GUI
50 { HostFalse, "", "", "" }, // BootLoader
51 { HostFalse, "", "-f bin", "" }, // BootSector
52 { HostFalse, "", "", "" }, // Iso
53 { HostFalse, "", "", "" }, // LiveIso
54 { HostFalse, "", "", "" }, // Test
55 { HostFalse, "", "", "" }, // RpcServer
56 { HostFalse, "", "", "" }, // RpcClient
57 { HostFalse, "", "", "" }, // Alias
58 { HostFalse, "", "", "" }, // BootProgram
59 { HostFalse, "", "", "$(LDFLAG_WINDOWS)" }, // Win32SCR
60 { HostFalse, "", "", "" }, // IdlHeader
61 { HostFalse, "", "", "" }, // IdlInterface
62 { HostFalse, "", "", "" }, // EmbeddedTypeLib
63 { HostFalse, "", "", "" }, // ElfExecutable
64 { HostFalse, "", "", "" }, // RpcProxy
65 { HostTrue, "", "", "" }, // HostStaticLibrary
66 { HostFalse, "", "", "" }, // Cabinet
67 { HostFalse, "", "", "$(LDFLAG_DLL)" }, // KeyboardLayout
68 { HostFalse, "", "", "" }, // MessageHeader
69 };
70
71 static std::string mscPath;
72 static std::string mslinkPath;
73
74 string
75 MingwBackend::GetFullPath ( const FileLocation& file ) const
76 {
77 MingwModuleHandler::PassThruCacheDirectory ( &file );
78
79 string directory;
80 switch ( file.directory )
81 {
82 case SourceDirectory:
83 directory = "";
84 break;
85 case IntermediateDirectory:
86 directory = "$(INTERMEDIATE)";
87 break;
88 case OutputDirectory:
89 directory = "$(OUTPUT)";
90 break;
91 case InstallDirectory:
92 directory = "$(INSTALL)";
93 break;
94 case TemporaryDirectory:
95 directory = "$(TEMPORARY)";
96 break;
97 default:
98 throw InvalidOperationException ( __FILE__,
99 __LINE__,
100 "Invalid directory %d.",
101 file.directory );
102 }
103
104 if ( file.relative_path.length () > 0 )
105 {
106 if ( directory.length () > 0 )
107 directory += sSep;
108 directory += file.relative_path;
109 }
110 return directory;
111 }
112
113 string
114 MingwBackend::GetFullName ( const FileLocation& file ) const
115 {
116 string directory;
117 switch ( file.directory )
118 {
119 case SourceDirectory:
120 directory = "";
121 break;
122 case IntermediateDirectory:
123 directory = "$(INTERMEDIATE)";
124 break;
125 case OutputDirectory:
126 directory = "$(OUTPUT)";
127 break;
128 case InstallDirectory:
129 directory = "$(INSTALL)";
130 break;
131 case TemporaryDirectory:
132 directory = "$(TEMPORARY)";
133 break;
134 default:
135 throw InvalidOperationException ( __FILE__,
136 __LINE__,
137 "Invalid directory %d.",
138 file.directory );
139 }
140
141 if ( file.relative_path.length () > 0 )
142 {
143 if ( directory.length () > 0 )
144 directory += sSep;
145 directory += file.relative_path;
146 }
147
148 if ( directory.length () > 0 )
149 directory += sSep;
150
151 return directory + file.name;
152 }
153
154 string
155 v2s ( const Backend* backend, const vector<FileLocation>& files, int wrap_at )
156 {
157 if ( !files.size() )
158 return "";
159 string s;
160 int wrap_count = 0;
161 for ( size_t i = 0; i < files.size(); i++ )
162 {
163 const FileLocation& file = files[i];
164 if ( wrap_at > 0 && wrap_count++ == wrap_at )
165 {
166 s += " \\\n\t\t";
167 wrap_count = 1;
168 }
169 else if ( s.size() )
170 s += " ";
171 s += backend->GetFullName ( file );
172 }
173 return s;
174 }
175
176
177 string
178 v2s ( const string_list& v, int wrap_at )
179 {
180 if ( !v.size() )
181 return "";
182 string s;
183 int wrap_count = 0;
184 for ( size_t i = 0; i < v.size(); i++ )
185 {
186 if ( !v[i].size() )
187 continue;
188 if ( wrap_at > 0 && wrap_count++ == wrap_at )
189 {
190 s += " \\\n\t\t";
191 wrap_count = 1;
192 }
193 else if ( s.size() )
194 s += " ";
195 s += v[i];
196 }
197 return s;
198 }
199
200
201 static class MingwFactory : public Backend::Factory
202 {
203 public:
204 MingwFactory() : Factory ( "mingw", "Minimalist GNU Win32" ) {}
205 Backend* operator() ( Project& project,
206 Configuration& configuration )
207 {
208 return new MingwBackend ( project,
209 configuration );
210 }
211 } factory;
212
213
214 MingwBackend::MingwBackend ( Project& project,
215 Configuration& configuration )
216 : Backend ( project, configuration ),
217 manualBinutilsSetting( false ),
218 intermediateDirectory ( new Directory ( "" ) ),
219 outputDirectory ( new Directory ( "" ) ),
220 installDirectory ( new Directory ( "" ) )
221 {
222 compilerPrefix = "";
223 }
224
225 MingwBackend::~MingwBackend()
226 {
227 delete intermediateDirectory;
228 delete outputDirectory;
229 delete installDirectory;
230 }
231
232 string
233 MingwBackend::AddDirectoryTarget ( const string& directory,
234 Directory* directoryTree )
235 {
236 if ( directory.length () > 0)
237 directoryTree->Add ( directory.c_str() );
238 return directoryTree->name;
239 }
240
241 bool
242 MingwBackend::CanEnablePreCompiledHeaderSupportForModule ( const Module& module )
243 {
244 if ( !configuration.CompilationUnitsEnabled )
245 return true;
246
247 const vector<CompilationUnit*>& compilationUnits = module.non_if_data.compilationUnits;
248 size_t i;
249 for ( i = 0; i < compilationUnits.size (); i++ )
250 {
251 CompilationUnit& compilationUnit = *compilationUnits[i];
252 if ( compilationUnit.GetFiles ().size () != 1 )
253 return false;
254 }
255 return true;
256 }
257
258 void
259 MingwBackend::ProcessModules ()
260 {
261 printf ( "Processing modules..." );
262
263 vector<MingwModuleHandler*> v;
264 size_t i;
265
266 for ( std::map<std::string, Module*>::iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
267 fprintf ( fMakefile, "%s_TYPE:=%u\n", p->second->name.c_str(), p->second->type );
268
269 for ( std::map<std::string, Module*>::iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
270 {
271 Module& module = *p->second;
272 if ( !module.enabled )
273 continue;
274 MingwModuleHandler* h = MingwModuleHandler::InstanciateHandler (
275 module,
276 this );
277 h->AddImplicitLibraries ( module );
278 if ( use_pch && CanEnablePreCompiledHeaderSupportForModule ( module ) )
279 h->EnablePreCompiledHeaderSupport ();
280 v.push_back ( h );
281 }
282
283 size_t iend = v.size ();
284
285 for ( i = 0; i < iend; i++ )
286 v[i]->GenerateSourceMacro();
287 for ( i = 0; i < iend; i++ )
288 v[i]->GenerateObjectMacro();
289 fprintf ( fMakefile, "\n" );
290 for ( i = 0; i < iend; i++ )
291 v[i]->GenerateTargetMacro();
292 fprintf ( fMakefile, "\n" );
293
294 GenerateAllTarget ( v );
295 GenerateRegTestsRunTarget ();
296
297 for ( i = 0; i < iend; i++ )
298 v[i]->GenerateOtherMacros();
299
300 for ( i = 0; i < iend; i++ )
301 {
302 MingwModuleHandler& h = *v[i];
303 h.GeneratePreconditionDependencies ();
304 h.Process ();
305 h.GenerateInvocations ();
306 h.GenerateCleanTarget ();
307 h.GenerateInstallTarget ();
308 h.GenerateDependsTarget ();
309 delete v[i];
310 }
311
312 printf ( "done\n" );
313 }
314
315 void
316 MingwBackend::Process ()
317 {
318 if ( configuration.CheckDependenciesForModuleOnly )
319 CheckAutomaticDependenciesForModuleOnly ();
320 else
321 ProcessNormal ();
322 }
323
324 void
325 MingwBackend::CheckAutomaticDependenciesForModuleOnly ()
326 {
327 if ( configuration.Dependencies == AutomaticDependencies )
328 {
329 Module* module = ProjectNode.LocateModule ( configuration.CheckDependenciesForModuleOnlyModule );
330 if ( module == NULL )
331 {
332 printf ( "Module '%s' does not exist\n",
333 configuration.CheckDependenciesForModuleOnlyModule.c_str () );
334 return;
335 }
336
337 printf ( "Checking automatic dependencies for module '%s'...",
338 module->name.c_str () );
339 AutomaticDependency automaticDependency ( ProjectNode );
340 automaticDependency.CheckAutomaticDependenciesForModule ( *module,
341 configuration.Verbose );
342 printf ( "done\n" );
343 }
344 }
345
346 void
347 MingwBackend::ProcessNormal ()
348 {
349 assert(sizeof(ModuleHandlerInformations)/sizeof(ModuleHandlerInformations[0]) == TypeDontCare);
350
351 DetectCompiler ();
352 DetectBinutils ();
353 DetectNetwideAssembler ();
354 DetectPipeSupport ();
355 DetectPCHSupport ();
356 CreateMakefile ();
357 GenerateHeader ();
358 GenerateGlobalVariables ();
359 GenerateXmlBuildFilesMacro ();
360 ProcessModules ();
361 GenerateInstallTarget ();
362 GenerateTestTarget ();
363 GenerateDirectoryTargets ();
364 GenerateDirectories ();
365 GenerateTestSupportCode ();
366 GenerateCompilationUnitSupportCode ();
367 GenerateSysSetup ();
368 GenerateInstallerFileList();
369 GenerateProxyMakefiles ();
370 CheckAutomaticDependencies ();
371 CloseMakefile ();
372 }
373
374 void
375 MingwBackend::GenerateInstallerFileList()
376 {
377 this->ProjectNode.GenerateInstallerFileList();
378 }
379
380 void
381 MingwBackend::CreateMakefile ()
382 {
383 fMakefile = fopen ( ProjectNode.makefile.c_str (), "w" );
384 if ( !fMakefile )
385 throw AccessDeniedException ( ProjectNode.makefile );
386 MingwModuleHandler::SetBackend ( this );
387 MingwModuleHandler::SetMakefile ( fMakefile );
388 }
389
390 void
391 MingwBackend::CloseMakefile () const
392 {
393 if (fMakefile)
394 fclose ( fMakefile );
395 }
396
397 void
398 MingwBackend::GenerateHeader () const
399 {
400 fprintf ( fMakefile, "# THIS FILE IS AUTOMATICALLY GENERATED, EDIT '%s' INSTEAD\n\n",
401 ProjectNode.GetProjectFilename ().c_str () );
402 }
403
404 void
405 MingwBackend::GenerateGlobalProperties (
406 const char* assignmentOperation,
407 const IfableData& data ) const
408 {
409 for ( std::map<std::string, Property*>::const_iterator p = data.properties.begin(); p != data.properties.end(); ++ p )
410 {
411 Property& prop = *p->second;
412
413 if (!prop.isInternal)
414 {
415 fprintf ( fMakefile, "%s := %s\n",
416 prop.name.c_str(),
417 prop.value.c_str() );
418 }
419 }
420 }
421
422 string
423 MingwBackend::GenerateProjectLDFLAGS () const
424 {
425 string ldflags;
426 for ( size_t i = 0; i < ProjectNode.linkerFlags.size (); i++ )
427 {
428 LinkerFlag& linkerFlag = *ProjectNode.linkerFlags[i];
429 if ( ldflags.length () > 0 )
430 ldflags += " ";
431 ldflags += linkerFlag.flag;
432 }
433 return ldflags;
434 }
435
436 void
437 MingwBackend::GenerateGlobalVariables () const
438 {
439 fputs ( "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)rules.mak\n", fMakefile );
440 fprintf ( fMakefile, "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)linkers$(SEP)%s.mak\n", ProjectNode.GetLinkerSet ().c_str () );
441 fprintf ( fMakefile, "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)compilers$(SEP)%s.mak\n", ProjectNode.GetCompilerSet ().c_str () );
442
443 if ( mscPath.length() )
444 fprintf ( fMakefile, "export RBUILD_CL_PATH=%s\n", mscPath.c_str () );
445
446 if ( mslinkPath.length() )
447 fprintf ( fMakefile, "export RBUILD_LINK_PATH=%s\n", mslinkPath.c_str () );
448
449 if ( configuration.Dependencies == FullDependencies )
450 {
451 fprintf ( fMakefile,
452 "ifeq ($(ROS_BUILDDEPS),)\n"
453 "ROS_BUILDDEPS:=%s\n"
454 "endif\n",
455 "full" );
456 }
457
458 fprintf ( fMakefile,
459 "PREFIX := %s\n",
460 compilerPrefix.c_str () );
461 fprintf ( fMakefile,
462 "nasm := $(Q)%s\n",
463 nasmCommand.c_str () );
464
465 GenerateGlobalProperties ( "=", ProjectNode.non_if_data );
466
467 if ( ProjectNode.configuration.Compiler == GnuGcc )
468 {
469 fprintf ( fMakefile, "ifneq ($(OARCH),)\n" );
470 fprintf ( fMakefile, "PROJECT_ASFLAGS += -march=$(OARCH)\n" );
471 fprintf ( fMakefile, "PROJECT_CFLAGS += -march=$(OARCH)\n" );
472 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -march=$(OARCH)\n" );
473 fprintf ( fMakefile, "endif\n" );
474 fprintf ( fMakefile, "ifneq ($(TUNE),)\n" );
475 fprintf ( fMakefile, "PROJECT_CFLAGS += -mtune=$(TUNE)\n" );
476 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -mtune=$(TUNE)\n" );
477 fprintf ( fMakefile, "endif\n" );
478
479 if ( usePipe )
480 {
481 fprintf ( fMakefile, "PROJECT_CFLAGS += -pipe\n" );
482 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -pipe\n" );
483 fprintf ( fMakefile, "PROJECT_ASFLAGS += -pipe\n" );
484 }
485
486 // Would be nice to have our own C++ runtime
487 fputs ( "BUILTIN_CXXINCLUDES+= $(TARGET_CPPFLAGS)\n", fMakefile );
488
489 fprintf ( fMakefile, "PROJECT_CCLIBS := \"$(shell ${TARGET_CC} -print-libgcc-file-name)\"\n" );
490 fprintf ( fMakefile, "PROJECT_CXXLIBS := \"$(shell ${TARGET_CPP} -print-file-name=libstdc++.a)\" \"$(shell ${TARGET_CPP} -print-libgcc-file-name)\" \"$(shell ${TARGET_CPP} -print-file-name=libmingw32.a)\" \"$(shell ${TARGET_CPP} -print-file-name=libmingwex.a)\" " );
491
492 /* hack to get libgcc_eh.a, should check mingw version or something */
493 if (Environment::GetArch() == "amd64")
494 fprintf ( fMakefile, " \"$(shell ${TARGET_CPP} -print-file-name=libgcc_eh.a)\"" );
495 /* hack to get _get_output_format, needed by libmingwex */
496 else if (Environment::GetArch() == "i386")
497 fprintf ( fMakefile, "\"$(shell ${TARGET_CPP} -print-file-name=ofmt_stub.a)\"");
498 fprintf ( fMakefile,"\n");
499 }
500 MingwModuleHandler::GenerateParameters ( "PROJECT", "+=", ProjectNode.non_if_data );
501 MingwModuleHandler::GenerateParameters ( "PROJECT_HOST", "+=", ProjectNode.host_non_if_data );
502
503 fprintf ( fMakefile, "PROJECT_LDFLAGS := %s\n", GenerateProjectLDFLAGS ().c_str () );
504
505 // TODO: use symbolic names for module types
506 for ( size_t i = 0; i < sizeof(ModuleHandlerInformations) / sizeof(ModuleHandlerInformations[0]); ++ i )
507 {
508 if ( ModuleHandlerInformations[i].cflags && ModuleHandlerInformations[i].cflags[0] )
509 {
510 fprintf ( fMakefile,
511 "MODULETYPE%d_%sFLAGS:=%s\n",
512 (int)i,
513 "C",
514 ModuleHandlerInformations[i].cflags );
515 }
516
517 if ( ModuleHandlerInformations[i].nasmflags && ModuleHandlerInformations[i].nasmflags[0] )
518 {
519 fprintf ( fMakefile,
520 "MODULETYPE%d_%sFLAGS:=%s\n",
521 (int)i,
522 "NASM",
523 ModuleHandlerInformations[i].nasmflags );
524 }
525
526 if ( ModuleHandlerInformations[i].linkerflags && ModuleHandlerInformations[i].linkerflags[0] )
527 {
528 fprintf ( fMakefile,
529 "MODULETYPE%d_%sFLAGS:=%s\n",
530 (int)i,
531 "LD",
532 ModuleHandlerInformations[i].linkerflags );
533 }
534 }
535
536 fprintf ( fMakefile,
537 "MODULETYPE%d_KMODE:=yes\n",
538 (int)Kernel );
539
540 fprintf ( fMakefile,
541 "MODULETYPE%d_KMODE:=yes\n",
542 (int)KernelModeDLL );
543
544 fprintf ( fMakefile,
545 "MODULETYPE%d_KMODE:=yes\n",
546 (int)KernelModeDriver );
547
548 fprintf ( fMakefile, "\n" );
549 }
550
551 bool
552 MingwBackend::IncludeInAllTarget ( const Module& module ) const
553 {
554 if ( MingwModuleHandler::ReferenceObjects ( module ) )
555 return false;
556 if ( module.type == BootSector )
557 return false;
558 if ( module.type == Iso )
559 return false;
560 if ( module.type == LiveIso )
561 return false;
562 if ( module.type == Test )
563 return false;
564 if ( module.type == Alias )
565 return false;
566 return true;
567 }
568
569 void
570 MingwBackend::GenerateAllTarget ( const vector<MingwModuleHandler*>& handlers ) const
571 {
572 fprintf ( fMakefile, "all:" );
573 int wrap_count = 0;
574 size_t iend = handlers.size ();
575 for ( size_t i = 0; i < iend; i++ )
576 {
577 const Module& module = handlers[i]->module;
578 if ( IncludeInAllTarget ( module ) )
579 {
580 if ( wrap_count++ == 5 )
581 fprintf ( fMakefile, " \\\n\t\t" ), wrap_count = 0;
582 fprintf ( fMakefile,
583 " %s",
584 GetTargetMacro(module).c_str () );
585 }
586 }
587 fprintf ( fMakefile, "\n\t\n\n" );
588 }
589
590 void
591 MingwBackend::GenerateRegTestsRunTarget () const
592 {
593 fprintf ( fMakefile,
594 "REGTESTS_RUN_TARGET = regtests.dll\n" );
595 fprintf ( fMakefile,
596 "$(REGTESTS_RUN_TARGET): $(REGTESTS_TARGET)\n" );
597 fprintf ( fMakefile,
598 "\t$(cp) $(REGTESTS_TARGET) $(REGTESTS_RUN_TARGET)\n" );
599 fprintf ( fMakefile, "\n" );
600 }
601
602 void
603 MingwBackend::GenerateXmlBuildFilesMacro() const
604 {
605 fprintf ( fMakefile,
606 "XMLBUILDFILES = %s \\\n",
607 ProjectNode.GetProjectFilename ().c_str () );
608 string xmlbuildFilenames;
609 int numberOfExistingFiles = 0;
610 struct stat statbuf;
611 time_t SystemTime, lastWriteTime;
612
613 for ( size_t i = 0; i < ProjectNode.xmlbuildfiles.size (); i++ )
614 {
615 XMLInclude& xmlbuildfile = *ProjectNode.xmlbuildfiles[i];
616 if ( !xmlbuildfile.fileExists )
617 continue;
618 numberOfExistingFiles++;
619 if ( xmlbuildFilenames.length () > 0 )
620 xmlbuildFilenames += " ";
621
622 FILE* f = fopen ( xmlbuildfile.topIncludeFilename.c_str (), "rb" );
623 if ( !f )
624 throw FileNotFoundException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
625
626 if ( fstat ( fileno ( f ), &statbuf ) != 0 )
627 {
628 fclose ( f );
629 throw AccessDeniedException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
630 }
631
632 lastWriteTime = statbuf.st_mtime;
633 SystemTime = time(NULL);
634
635 if (SystemTime != -1)
636 {
637 if (difftime (lastWriteTime, SystemTime) > 0)
638 throw InvalidDateException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
639 }
640
641 fclose ( f );
642
643 xmlbuildFilenames += NormalizeFilename ( xmlbuildfile.topIncludeFilename );
644 if ( numberOfExistingFiles % 5 == 4 || i == ProjectNode.xmlbuildfiles.size () - 1 )
645 {
646 fprintf ( fMakefile,
647 "\t%s",
648 xmlbuildFilenames.c_str ());
649 if ( i == ProjectNode.xmlbuildfiles.size () - 1 )
650 {
651 fprintf ( fMakefile, "\n" );
652 }
653 else
654 {
655 fprintf ( fMakefile,
656 " \\\n" );
657 }
658 xmlbuildFilenames.resize ( 0 );
659 }
660 numberOfExistingFiles++;
661 }
662 fprintf ( fMakefile, "\n" );
663 }
664
665 void
666 MingwBackend::GenerateTestSupportCode ()
667 {
668 printf ( "Generating test support code..." );
669 TestSupportCode testSupportCode ( ProjectNode );
670 testSupportCode.GenerateTestSupportCode ( configuration.Verbose );
671 printf ( "done\n" );
672 }
673
674 void
675 MingwBackend::GenerateCompilationUnitSupportCode ()
676 {
677 if ( configuration.CompilationUnitsEnabled )
678 {
679 printf ( "Generating compilation unit support code..." );
680 CompilationUnitSupportCode compilationUnitSupportCode ( ProjectNode );
681 compilationUnitSupportCode.Generate ( configuration.Verbose );
682 printf ( "done\n" );
683 }
684 }
685
686 void
687 MingwBackend::GenerateSysSetup ()
688 {
689 printf ( "Generating syssetup.inf..." );
690 SysSetupGenerator sysSetupGenerator ( ProjectNode );
691 sysSetupGenerator.Generate ();
692 printf ( "done\n" );
693 }
694
695 string
696 MingwBackend::GetProxyMakefileTree () const
697 {
698 if ( configuration.GenerateProxyMakefilesInSourceTree )
699 return "";
700 else
701 return Environment::GetOutputPath ();
702 }
703
704 void
705 MingwBackend::GenerateProxyMakefiles ()
706 {
707 printf ( "Generating proxy makefiles..." );
708 ProxyMakefile proxyMakefile ( ProjectNode );
709 proxyMakefile.GenerateProxyMakefiles ( configuration.Verbose,
710 GetProxyMakefileTree () );
711 printf ( "done\n" );
712 }
713
714 void
715 MingwBackend::CheckAutomaticDependencies ()
716 {
717 if ( configuration.Dependencies == AutomaticDependencies )
718 {
719 printf ( "Checking automatic dependencies..." );
720 AutomaticDependency automaticDependency ( ProjectNode );
721 automaticDependency.CheckAutomaticDependencies ( configuration.Verbose );
722 printf ( "done\n" );
723 }
724 }
725
726 void
727 MingwBackend::GenerateDirectories ()
728 {
729 printf ( "Creating directories..." );
730 intermediateDirectory->GenerateTree ( IntermediateDirectory, configuration.Verbose );
731 outputDirectory->GenerateTree ( OutputDirectory, configuration.Verbose );
732 if ( !configuration.MakeHandlesInstallDirectories )
733 installDirectory->GenerateTree ( InstallDirectory, configuration.Verbose );
734 printf ( "done\n" );
735 }
736
737 bool
738 MingwBackend::TryToDetectThisCompiler ( const string& compiler )
739 {
740 string command = ssprintf (
741 "%s -v 1>%s 2>%s",
742 FixSeparatorForSystemCommand(compiler).c_str (),
743 NUL,
744 NUL );
745 int exitcode = system ( command.c_str () );
746 return (bool) (exitcode == 0);
747 }
748
749 void
750 MingwBackend::DetectCompiler ()
751 {
752 printf ( "Detecting compiler..." );
753
754 bool detectedCompiler = false;
755 bool supportedCompiler = false;
756 string compilerVersion;
757
758 if ( ProjectNode.configuration.Compiler == GnuGcc )
759 {
760 const string& TARGET_CCValue = Environment::GetVariable ( "TARGET_CC" );
761 const string& ROS_PREFIXValue = Environment::GetVariable ( "ROS_PREFIX" );
762
763 if ( TARGET_CCValue.length () > 0 )
764 {
765 compilerPrefix = "";
766 compilerCommand = TARGET_CCValue;
767 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
768 }
769
770 if ( !detectedCompiler )
771 {
772 if ( ROS_PREFIXValue.length () > 0 )
773 {
774 compilerPrefix = ROS_PREFIXValue;
775 compilerCommand = compilerPrefix + "-gcc";
776 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
777 }
778 }
779 #if defined(WIN32)
780 if ( !detectedCompiler )
781 {
782 compilerPrefix = "";
783 compilerCommand = "gcc";
784 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
785 }
786 #endif
787 if ( !detectedCompiler )
788 {
789 compilerPrefix = "mingw32";
790 compilerCommand = compilerPrefix + "-gcc";
791 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
792 }
793
794 if ( detectedCompiler )
795 compilerVersion = GetCompilerVersion ( compilerCommand );
796
797 supportedCompiler = IsSupportedCompilerVersion ( compilerVersion );
798 }
799 else if ( ProjectNode.configuration.Compiler == MicrosoftC )
800 {
801 compilerCommand = "cl";
802 detectedCompiler = DetectMicrosoftCompiler ( compilerVersion, mscPath );
803 supportedCompiler = true; // TODO
804 }
805
806 if ( detectedCompiler )
807 {
808 if ( supportedCompiler )
809 printf ( "detected (%s %s)\n", compilerCommand.c_str (), compilerVersion.c_str() );
810 else
811 {
812 printf ( "detected (%s), but with unsupported version (%s)\n",
813 compilerCommand.c_str (),
814 compilerVersion.c_str () );
815 throw UnsupportedBuildToolException ( compilerCommand, compilerVersion );
816 }
817 }
818 else
819 printf ( "not detected\n" );
820
821 }
822
823 bool
824 MingwBackend::TryToDetectThisNetwideAssembler ( const string& assembler )
825 {
826 string command = ssprintf (
827 "%s -h 1>%s 2>%s",
828 FixSeparatorForSystemCommand(assembler).c_str (),
829 NUL,
830 NUL );
831 int exitcode = system ( command.c_str () );
832 return (bool) (exitcode == 0);
833 }
834
835 string
836 MingwBackend::GetVersionString ( const string& versionCommand )
837 {
838 FILE *fp;
839 int ch, i;
840 size_t newline;
841 char buffer[81];
842
843 fp = popen ( versionCommand.c_str () , "r" );
844 for( i = 0;
845 ( i < 80 ) &&
846 ( feof ( fp ) == 0 &&
847 ( ( ch = fgetc( fp ) ) != -1 ) );
848 i++ )
849 {
850 buffer[i] = (char) ch;
851 }
852 buffer[i] = '\0';
853 pclose ( fp );
854
855 char separators[] = " ()\n";
856 char *token;
857 char *prevtoken = NULL;
858
859 string version;
860
861 token = strtok ( buffer, separators );
862 while ( token != NULL )
863 {
864 prevtoken = token;
865 version = string( prevtoken );
866 if ( (newline = version.find('\n')) != std::string::npos )
867 version.erase(newline, 1);
868 if ( version.find('.') != std::string::npos )
869 break;
870 token = strtok ( NULL, separators );
871 }
872 return version;
873 }
874
875 string
876 MingwBackend::GetNetwideAssemblerVersion ( const string& nasmCommand )
877 {
878 string versionCommand;
879 if ( nasmCommand.find("yasm") != std::string::npos )
880 {
881 versionCommand = ssprintf ( "%s --version",
882 nasmCommand.c_str (),
883 NUL,
884 NUL );
885 }
886 else
887 {
888 versionCommand = ssprintf ( "%s -v",
889 nasmCommand.c_str (),
890 NUL,
891 NUL );
892 }
893 return GetVersionString( versionCommand );
894 }
895
896 string
897 MingwBackend::GetCompilerVersion ( const string& compilerCommand )
898 {
899 string versionCommand = ssprintf ( "%s --version",
900 compilerCommand.c_str (),
901 NUL,
902 NUL );
903 return GetVersionString( versionCommand );
904 }
905
906 string
907 MingwBackend::GetBinutilsVersion ( const string& binutilsCommand )
908 {
909 string versionCommand = ssprintf ( "%s -v",
910 binutilsCommand.c_str (),
911 NUL,
912 NUL );
913 return GetVersionString( versionCommand );
914 }
915
916 bool
917 MingwBackend::IsSupportedCompilerVersion ( const string& compilerVersion )
918 {
919 if ( strcmp ( compilerVersion.c_str (), "4.4.2") < 0 )
920 return false;
921 else
922 return true;
923 }
924
925 bool
926 MingwBackend::TryToDetectThisBinutils ( const string& binutils )
927 {
928 string command = ssprintf (
929 "%s -v 1>%s 2>%s",
930 FixSeparatorForSystemCommand(binutils).c_str (),
931 NUL,
932 NUL );
933 int exitcode = system ( command.c_str () );
934 return (exitcode == 0);
935 }
936
937 string
938 MingwBackend::GetBinutilsVersionDate ( const string& binutilsCommand )
939 {
940 FILE *fp;
941 int ch, i;
942 char buffer[81];
943
944 string versionCommand = ssprintf ( "%s -v",
945 binutilsCommand.c_str (),
946 NUL,
947 NUL );
948 fp = popen ( versionCommand.c_str () , "r" );
949 for( i = 0;
950 ( i < 80 ) &&
951 ( feof ( fp ) == 0 &&
952 ( ( ch = fgetc( fp ) ) != -1 ) );
953 i++ )
954 {
955 buffer[i] = (char) ch;
956 }
957 buffer[i] = '\0';
958 pclose ( fp );
959
960 char separators[] = " ";
961 char *token;
962 char *prevtoken = NULL;
963
964 token = strtok ( buffer, separators );
965 while ( token != NULL )
966 {
967 prevtoken = token;
968 token = strtok ( NULL, separators );
969 }
970 string version = string ( prevtoken );
971 int lastDigit = version.find_last_not_of ( "\t\r\n" );
972 if ( lastDigit != -1 )
973 return string ( version, 0, lastDigit+1 );
974 else
975 return version;
976 }
977
978 bool
979 MingwBackend::IsSupportedBinutilsVersion ( const string& binutilsVersion )
980 {
981 int digit = binutilsVersion.find_last_of(".");
982 if(digit == -1)
983 {
984 printf("Unable to detect binutils version!\n");
985 return false;
986 }
987
988 string date = string(binutilsVersion, digit + 1);
989 if(date.length() == 8)
990 {
991 /* This is a real date in the format YYYYMMDD.
992 Check whether we have at least Binutils 20091017 (older versions
993 don't support the -exclude-all-symbols option we use). */
994 if(strcmp(date.c_str(), "20091119") < 0)
995 return false;
996 }
997 else
998 {
999 /* This is no date, so binutilsVersion should just contain the version
1000 number.
1001 Binutils 2.20 will hopefully contain the required features. */
1002 if(strcmp(binutilsVersion.c_str(), "2.20") < 0)
1003 return false;
1004 }
1005
1006 return true;
1007 }
1008
1009 void
1010 MingwBackend::DetectBinutils ()
1011 {
1012 printf ( "Detecting binutils..." );
1013
1014 bool detectedBinutils = false;
1015 bool supportedBinutils = false;
1016 string binutilsVersion;
1017
1018 if ( ProjectNode.configuration.Linker == GnuLd )
1019 {
1020 const string& ROS_PREFIXValue = Environment::GetVariable ( "ROS_PREFIX" );
1021
1022 if ( ROS_PREFIXValue.length () > 0 )
1023 {
1024 binutilsPrefix = ROS_PREFIXValue;
1025 binutilsCommand = binutilsPrefix + "-ld";
1026 manualBinutilsSetting = true;
1027 detectedBinutils = true;
1028 }
1029 #if defined(WIN32)
1030 if ( !detectedBinutils )
1031 {
1032 binutilsPrefix = "";
1033 binutilsCommand = "ld";
1034 detectedBinutils = TryToDetectThisBinutils ( binutilsCommand );
1035 }
1036 #endif
1037 if ( !detectedBinutils )
1038 {
1039 binutilsPrefix = "mingw32";
1040 binutilsCommand = binutilsPrefix + "-ld";
1041 detectedBinutils = TryToDetectThisBinutils ( binutilsCommand );
1042 }
1043 if ( detectedBinutils )
1044 {
1045 binutilsVersion = GetBinutilsVersionDate ( binutilsCommand );
1046 supportedBinutils = IsSupportedBinutilsVersion ( binutilsVersion );
1047 }
1048 }
1049 else if ( ProjectNode.configuration.Linker == MicrosoftLink )
1050 {
1051 compilerCommand = "link";
1052 detectedBinutils = DetectMicrosoftLinker ( binutilsVersion, mslinkPath );
1053 supportedBinutils = true; // TODO
1054 }
1055
1056 if ( detectedBinutils )
1057 {
1058 if ( supportedBinutils )
1059 printf ( "detected (%s %s)\n", binutilsCommand.c_str (), binutilsVersion.c_str() );
1060 else
1061 {
1062 printf ( "detected (%s), but with unsupported version (%s)\n",
1063 binutilsCommand.c_str (),
1064 binutilsVersion.c_str () );
1065 throw UnsupportedBuildToolException ( binutilsCommand, binutilsVersion );
1066 }
1067 }
1068 else
1069 printf ( "not detected\n" );
1070
1071 }
1072
1073 void
1074 MingwBackend::DetectNetwideAssembler ()
1075 {
1076 printf ( "Detecting netwide assembler..." );
1077
1078 nasmCommand = "nasm";
1079 bool detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1080 #if defined(WIN32)
1081 if ( !detectedNasm )
1082 {
1083 nasmCommand = "nasmw";
1084 detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1085 }
1086 #endif
1087 if ( !detectedNasm )
1088 {
1089 nasmCommand = "yasm";
1090 detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1091 }
1092 if ( detectedNasm )
1093 printf ( "detected (%s %s)\n", nasmCommand.c_str (), GetNetwideAssemblerVersion( nasmCommand ).c_str() );
1094 else
1095 printf ( "not detected\n" );
1096 }
1097
1098 void
1099 MingwBackend::DetectPipeSupport ()
1100 {
1101 if ( ProjectNode.configuration.Compiler == GnuGcc )
1102 {
1103 printf ( "Detecting compiler -pipe support..." );
1104
1105 string pipe_detection = "tools" + sSep + "rbuild" + sSep + "backend" + sSep + "mingw" + sSep + "pipe_detection.c";
1106 string pipe_detectionObjectFilename = ReplaceExtension ( pipe_detection,
1107 ".o" );
1108 string command = ssprintf (
1109 "%s -pipe -c %s -o %s 1>%s 2>%s",
1110 FixSeparatorForSystemCommand(compilerCommand).c_str (),
1111 pipe_detection.c_str (),
1112 pipe_detectionObjectFilename.c_str (),
1113 NUL,
1114 NUL );
1115 int exitcode = system ( command.c_str () );
1116 FILE* f = fopen ( pipe_detectionObjectFilename.c_str (), "rb" );
1117 if ( f )
1118 {
1119 usePipe = (exitcode == 0);
1120 fclose ( f );
1121 unlink ( pipe_detectionObjectFilename.c_str () );
1122 }
1123 else
1124 usePipe = false;
1125
1126 if ( usePipe )
1127 printf ( "detected\n" );
1128 else
1129 printf ( "not detected\n" );
1130 }
1131 else
1132 usePipe = false;
1133 }
1134
1135 void
1136 MingwBackend::DetectPCHSupport ()
1137 {
1138 printf ( "Detecting compiler pre-compiled header support..." );
1139
1140 if ( configuration.PrecompiledHeadersEnabled && ProjectNode.configuration.Compiler == GnuGcc )
1141 {
1142 string path = "tools" + sSep + "rbuild" + sSep + "backend" + sSep + "mingw" + sSep + "pch_detection.h";
1143 string cmd = ssprintf (
1144 "%s -c %s 1>%s 2>%s",
1145 FixSeparatorForSystemCommand(compilerCommand).c_str (),
1146 path.c_str (),
1147 NUL,
1148 NUL );
1149 system ( cmd.c_str () );
1150 path += ".gch";
1151
1152 FILE* f = fopen ( path.c_str (), "rb" );
1153 if ( f )
1154 {
1155 use_pch = true;
1156 fclose ( f );
1157 unlink ( path.c_str () );
1158 }
1159 else
1160 use_pch = false;
1161
1162 if ( use_pch )
1163 printf ( "detected\n" );
1164 else
1165 printf ( "not detected\n" );
1166 }
1167 else
1168 {
1169 use_pch = false;
1170 printf ( "disabled\n" );
1171 }
1172 }
1173
1174 void
1175 MingwBackend::GetNonModuleInstallTargetFiles (
1176 vector<FileLocation>& out ) const
1177 {
1178 for ( size_t i = 0; i < ProjectNode.installfiles.size (); i++ )
1179 {
1180 const InstallFile& installfile = *ProjectNode.installfiles[i];
1181 out.push_back ( *installfile.target );
1182 }
1183 }
1184
1185 void
1186 MingwBackend::GetModuleInstallTargetFiles (
1187 vector<FileLocation>& out ) const
1188 {
1189 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1190 {
1191 const Module& module = *p->second;
1192 if ( !module.enabled )
1193 continue;
1194 if ( module.install )
1195 out.push_back ( *module.install );
1196 }
1197 }
1198
1199 void
1200 MingwBackend::GetInstallTargetFiles (
1201 vector<FileLocation>& out ) const
1202 {
1203 GetNonModuleInstallTargetFiles ( out );
1204 GetModuleInstallTargetFiles ( out );
1205 }
1206
1207 void
1208 MingwBackend::OutputInstallTarget ( const FileLocation& source,
1209 const FileLocation& target )
1210 {
1211 fprintf ( fMakefile,
1212 "%s: %s | %s\n",
1213 GetFullName ( target ).c_str (),
1214 GetFullName ( source ).c_str (),
1215 GetFullPath ( target ).c_str () );
1216 fprintf ( fMakefile,
1217 "\t$(ECHO_CP)\n" );
1218 fprintf ( fMakefile,
1219 "\t${cp} %s %s 1>$(NUL)\n",
1220 GetFullName ( source ).c_str (),
1221 GetFullName ( target ).c_str () );
1222 }
1223
1224 void
1225 MingwBackend::OutputNonModuleInstallTargets ()
1226 {
1227 for ( size_t i = 0; i < ProjectNode.installfiles.size (); i++ )
1228 {
1229 const InstallFile& installfile = *ProjectNode.installfiles[i];
1230 OutputInstallTarget ( *installfile.source, *installfile.target );
1231 }
1232 }
1233
1234 const Module&
1235 MingwBackend::GetAliasedModuleOrModule ( const Module& module ) const
1236 {
1237 if ( module.aliasedModuleName.size () > 0 )
1238 {
1239 const Module* aliasedModule = ProjectNode.LocateModule ( module.aliasedModuleName );
1240 assert ( aliasedModule );
1241 return *aliasedModule;
1242 }
1243 else
1244 return module;
1245 }
1246
1247 void
1248 MingwBackend::OutputModuleInstallTargets ()
1249 {
1250 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1251 {
1252 const Module& module = *p->second;
1253 if ( !module.enabled )
1254 continue;
1255 if ( module.install )
1256 {
1257 const Module& aliasedModule = GetAliasedModuleOrModule ( module );
1258 OutputInstallTarget ( *aliasedModule.output, *module.install );
1259 }
1260 }
1261 }
1262
1263 string
1264 MingwBackend::GetRegistrySourceFiles ()
1265 {
1266 return "boot" + sSep + "bootdata" + sSep + "hivecls_" + Environment::GetArch() + ".inf "
1267 "boot" + sSep + "bootdata" + sSep + "hivedef_" + Environment::GetArch() + ".inf "
1268 "boot" + sSep + "bootdata" + sSep + "hiveinst_" + Environment::GetArch() + ".inf "
1269 "boot" + sSep + "bootdata" + sSep + "hivesft_" + Environment::GetArch() + ".inf "
1270 "boot" + sSep + "bootdata" + sSep + "hivesys_" + Environment::GetArch() + ".inf ";
1271 }
1272
1273 string
1274 MingwBackend::GetRegistryTargetFiles ()
1275 {
1276 string system32ConfigDirectory = "system32" + sSep + "config";
1277 FileLocation system32 ( InstallDirectory, system32ConfigDirectory, "" );
1278
1279 vector<FileLocation> registry_files;
1280 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "default" ) );
1281 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "sam" ) );
1282 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "security" ) );
1283 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "software" ) );
1284 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "system" ) );
1285
1286 return v2s( this, registry_files, 6 );
1287 }
1288
1289 void
1290 MingwBackend::OutputRegistryInstallTarget ()
1291 {
1292 FileLocation system32 ( InstallDirectory, "system32" + sSep + "config", "" );
1293
1294 string registrySourceFiles = GetRegistrySourceFiles ();
1295 string registryTargetFiles = GetRegistryTargetFiles ();
1296 fprintf ( fMakefile,
1297 "install_registry: %s\n",
1298 registryTargetFiles.c_str () );
1299 fprintf ( fMakefile,
1300 "%s: %s %s $(mkhive_TARGET)\n",
1301 registryTargetFiles.c_str (),
1302 registrySourceFiles.c_str (),
1303 GetFullPath ( system32 ).c_str () );
1304 fprintf ( fMakefile,
1305 "\t$(ECHO_MKHIVE)\n" );
1306 fprintf ( fMakefile,
1307 "\t$(mkhive_TARGET) boot%cbootdata %s $(ARCH) boot%cbootdata%chiveinst_$(ARCH).inf\n",
1308 cSep, GetFullPath ( system32 ).c_str (),
1309 cSep, cSep );
1310 fprintf ( fMakefile,
1311 "\n" );
1312 }
1313
1314 void
1315 MingwBackend::GenerateInstallTarget ()
1316 {
1317 vector<FileLocation> vInstallTargetFiles;
1318 GetInstallTargetFiles ( vInstallTargetFiles );
1319 string installTargetFiles = v2s ( this, vInstallTargetFiles, 5 );
1320 string registryTargetFiles = GetRegistryTargetFiles ();
1321
1322 fprintf ( fMakefile,
1323 "install: %s %s\n",
1324 installTargetFiles.c_str (),
1325 registryTargetFiles.c_str () );
1326 OutputNonModuleInstallTargets ();
1327 OutputModuleInstallTargets ();
1328 OutputRegistryInstallTarget ();
1329 fprintf ( fMakefile,
1330 "\n" );
1331 }
1332
1333 void
1334 MingwBackend::GetModuleTestTargets (
1335 vector<string>& out ) const
1336 {
1337 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1338 {
1339 const Module& module = *p->second;
1340 if ( !module.enabled )
1341 continue;
1342 if ( module.type == Test )
1343 out.push_back ( module.name );
1344 }
1345 }
1346
1347 void
1348 MingwBackend::GenerateTestTarget ()
1349 {
1350 vector<string> vTestTargets;
1351 GetModuleTestTargets ( vTestTargets );
1352 string testTargets = v2s ( vTestTargets, 5 );
1353
1354 fprintf ( fMakefile,
1355 "test: %s\n",
1356 testTargets.c_str () );
1357 fprintf ( fMakefile,
1358 "\n" );
1359 }
1360
1361 void
1362 MingwBackend::GenerateDirectoryTargets ()
1363 {
1364 intermediateDirectory->CreateRule ( fMakefile, "$(INTERMEDIATE)" );
1365 outputDirectory->CreateRule ( fMakefile, "$(OUTPUT)" );
1366 installDirectory->CreateRule ( fMakefile, "$(INSTALL)" );
1367 }