Merge trunk HEAD (r44067)
[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, "", "", "" }, // Kernel
42 { HostFalse, "", "", "" }, // KernelModeDLL
43 { HostFalse, "-D__NTDRIVER__", "", "" }, // KernelModeDriver
44 { HostFalse, "", "", "" }, // NativeDLL
45 { HostFalse, "-D__NTAPP__", "", "" }, // NativeCUI
46 { HostFalse, "", "", "" }, // Win32DLL
47 { HostFalse, "", "", "" }, // Win32OCX
48 { HostFalse, "", "", "" }, // Win32CUI
49 { HostFalse, "", "", "" }, // Win32GUI
50 { HostFalse, "", "", "-nostartfiles -nostdlib" }, // 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, "", "", "-nostartfiles -nostdlib" }, // BootProgram
59 { HostFalse, "", "", "" }, // Win32SCR
60 { HostFalse, "", "", "" }, // IdlHeader
61 { HostFalse, "", "", "" }, // IdlInterface
62 { HostFalse, "", "", "" }, // EmbeddedTypeLib
63 { HostFalse, "", "", "" }, // ElfExecutable
64 { HostFalse, "", "", "" }, // RpcProxy
65 { HostTrue, "", "", "" }, // HostStaticLibrary
66 { HostFalse, "", "", "" }, // Cabinet
67 { HostFalse, "", "", "" }, // 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 GenerateProxyMakefiles ();
369 CheckAutomaticDependencies ();
370 CloseMakefile ();
371 }
372
373 void
374 MingwBackend::CreateMakefile ()
375 {
376 fMakefile = fopen ( ProjectNode.makefile.c_str (), "w" );
377 if ( !fMakefile )
378 throw AccessDeniedException ( ProjectNode.makefile );
379 MingwModuleHandler::SetBackend ( this );
380 MingwModuleHandler::SetMakefile ( fMakefile );
381 }
382
383 void
384 MingwBackend::CloseMakefile () const
385 {
386 if (fMakefile)
387 fclose ( fMakefile );
388 }
389
390 void
391 MingwBackend::GenerateHeader () const
392 {
393 fprintf ( fMakefile, "# THIS FILE IS AUTOMATICALLY GENERATED, EDIT '%s' INSTEAD\n\n",
394 ProjectNode.GetProjectFilename ().c_str () );
395 }
396
397 void
398 MingwBackend::GenerateGlobalProperties (
399 const char* assignmentOperation,
400 const IfableData& data ) const
401 {
402 for ( std::map<std::string, Property*>::const_iterator p = data.properties.begin(); p != data.properties.end(); ++ p )
403 {
404 Property& prop = *p->second;
405
406 if (!prop.isInternal)
407 {
408 fprintf ( fMakefile, "%s := %s\n",
409 prop.name.c_str(),
410 prop.value.c_str() );
411 }
412 }
413 }
414
415 string
416 MingwBackend::GenerateProjectLFLAGS () const
417 {
418 string lflags;
419 for ( size_t i = 0; i < ProjectNode.linkerFlags.size (); i++ )
420 {
421 LinkerFlag& linkerFlag = *ProjectNode.linkerFlags[i];
422 if ( lflags.length () > 0 )
423 lflags += " ";
424 lflags += linkerFlag.flag;
425 }
426 return lflags;
427 }
428
429 void
430 MingwBackend::GenerateGlobalVariables () const
431 {
432 fputs ( "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)rules.mak\n", fMakefile );
433 fprintf ( fMakefile, "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)linkers$(SEP)%s.mak\n", ProjectNode.GetLinkerSet ().c_str () );
434 fprintf ( fMakefile, "include tools$(SEP)rbuild$(SEP)backend$(SEP)mingw$(SEP)compilers$(SEP)%s.mak\n", ProjectNode.GetCompilerSet ().c_str () );
435
436 if ( mscPath.length() )
437 fprintf ( fMakefile, "export RBUILD_CL_PATH=%s\n", mscPath.c_str () );
438
439 if ( mslinkPath.length() )
440 fprintf ( fMakefile, "export RBUILD_LINK_PATH=%s\n", mslinkPath.c_str () );
441
442 if ( configuration.Dependencies == FullDependencies )
443 {
444 fprintf ( fMakefile,
445 "ifeq ($(ROS_BUILDDEPS),)\n"
446 "ROS_BUILDDEPS:=%s\n"
447 "endif\n",
448 "full" );
449 }
450
451 fprintf ( fMakefile,
452 "PREFIX := %s\n",
453 compilerPrefix.c_str () );
454 fprintf ( fMakefile,
455 "nasm := $(Q)%s\n",
456 nasmCommand.c_str () );
457
458 GenerateGlobalProperties ( "=", ProjectNode.non_if_data );
459
460 if ( ProjectNode.configuration.Compiler == GnuGcc )
461 {
462 fprintf ( fMakefile, "ifneq ($(OARCH),)\n" );
463 fprintf ( fMakefile, "PROJECT_ASFLAGS += -march=$(OARCH)\n" );
464 fprintf ( fMakefile, "PROJECT_CFLAGS += -march=$(OARCH)\n" );
465 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -march=$(OARCH)\n" );
466 fprintf ( fMakefile, "endif\n" );
467 fprintf ( fMakefile, "ifneq ($(TUNE),)\n" );
468 fprintf ( fMakefile, "PROJECT_CFLAGS += -mtune=$(TUNE)\n" );
469 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -mtune=$(TUNE)\n" );
470 fprintf ( fMakefile, "endif\n" );
471
472 if ( usePipe )
473 {
474 fprintf ( fMakefile, "PROJECT_CFLAGS += -pipe\n" );
475 fprintf ( fMakefile, "PROJECT_CXXFLAGS += -pipe\n" );
476 fprintf ( fMakefile, "PROJECT_ASFLAGS += -pipe\n" );
477 }
478
479 // Would be nice to have our own C++ runtime
480 fputs ( "BUILTIN_CXXINCLUDES+= $(TARGET_CPPFLAGS)\n", fMakefile );
481 }
482
483 // Because RosBE gcc is built to suck
484 fputs ( "BUILTIN_HOST_CINCLUDES+= $(HOST_CFLAGS)\n", fMakefile );
485 fputs ( "BUILTIN_HOST_CPPINCLUDES+= $(HOST_CFLAGS)\n", fMakefile );
486 fputs ( "BUILTIN_HOST_CXXINCLUDES+= $(HOST_CPPFLAGS)\n", fMakefile );
487
488 MingwModuleHandler::GenerateParameters ( "PROJECT", "+=", ProjectNode.non_if_data );
489 MingwModuleHandler::GenerateParameters ( "PROJECT_HOST", "+=", ProjectNode.host_non_if_data );
490
491 // TODO: linker flags
492 fprintf ( fMakefile, "PROJECT_LFLAGS := '$(shell ${TARGET_CC} -print-libgcc-file-name)' %s\n", GenerateProjectLFLAGS ().c_str () );
493 fprintf ( fMakefile, "PROJECT_LPPFLAGS := '$(shell ${TARGET_CPP} -print-file-name=libstdc++.a)' '$(shell ${TARGET_CPP} -print-file-name=libgcc.a)' '$(shell ${TARGET_CPP} -print-file-name=libmingw32.a)' '$(shell ${TARGET_CPP} -print-file-name=libmingwex.a)'\n" );
494 /* hack to get libgcc_eh.a, should check mingw version or something */
495 if (Environment::GetArch() == "amd64")
496 {
497 fprintf ( fMakefile, "PROJECT_LPPFLAGS += '$(shell ${TARGET_CPP} -print-file-name=libgcc_eh.a)'\n" );
498 }
499
500 // TODO: use symbolic names for module types
501 for ( size_t i = 0; i < sizeof(ModuleHandlerInformations) / sizeof(ModuleHandlerInformations[0]); ++ i )
502 {
503 if ( ModuleHandlerInformations[i].cflags && ModuleHandlerInformations[i].cflags[0] )
504 {
505 fprintf ( fMakefile,
506 "MODULETYPE%d_%sFLAGS:=%s\n",
507 (int)i,
508 "C",
509 ModuleHandlerInformations[i].cflags );
510 }
511
512 if ( ModuleHandlerInformations[i].cflags && ModuleHandlerInformations[i].cflags[0] )
513 {
514 fprintf ( fMakefile,
515 "MODULETYPE%d_%sFLAGS:=%s\n",
516 (int)i,
517 "CXX",
518 ModuleHandlerInformations[i].cflags );
519 }
520
521 if ( ModuleHandlerInformations[i].nasmflags && ModuleHandlerInformations[i].nasmflags[0] )
522 {
523 fprintf ( fMakefile,
524 "MODULETYPE%d_%sFLAGS:=%s\n",
525 (int)i,
526 "NASM",
527 ModuleHandlerInformations[i].nasmflags );
528 }
529 }
530
531 fprintf ( fMakefile, "\n" );
532 }
533
534 bool
535 MingwBackend::IncludeInAllTarget ( const Module& module ) const
536 {
537 if ( MingwModuleHandler::ReferenceObjects ( module ) )
538 return false;
539 if ( module.type == BootSector )
540 return false;
541 if ( module.type == Iso )
542 return false;
543 if ( module.type == LiveIso )
544 return false;
545 if ( module.type == Test )
546 return false;
547 if ( module.type == Alias )
548 return false;
549 return true;
550 }
551
552 void
553 MingwBackend::GenerateAllTarget ( const vector<MingwModuleHandler*>& handlers ) const
554 {
555 fprintf ( fMakefile, "all:" );
556 int wrap_count = 0;
557 size_t iend = handlers.size ();
558 for ( size_t i = 0; i < iend; i++ )
559 {
560 const Module& module = handlers[i]->module;
561 if ( IncludeInAllTarget ( module ) )
562 {
563 if ( wrap_count++ == 5 )
564 fprintf ( fMakefile, " \\\n\t\t" ), wrap_count = 0;
565 fprintf ( fMakefile,
566 " %s",
567 GetTargetMacro(module).c_str () );
568 }
569 }
570 fprintf ( fMakefile, "\n\t\n\n" );
571 }
572
573 void
574 MingwBackend::GenerateRegTestsRunTarget () const
575 {
576 fprintf ( fMakefile,
577 "REGTESTS_RUN_TARGET = regtests.dll\n" );
578 fprintf ( fMakefile,
579 "$(REGTESTS_RUN_TARGET): $(REGTESTS_TARGET)\n" );
580 fprintf ( fMakefile,
581 "\t$(cp) $(REGTESTS_TARGET) $(REGTESTS_RUN_TARGET)\n" );
582 fprintf ( fMakefile, "\n" );
583 }
584
585 void
586 MingwBackend::GenerateXmlBuildFilesMacro() const
587 {
588 fprintf ( fMakefile,
589 "XMLBUILDFILES = %s \\\n",
590 ProjectNode.GetProjectFilename ().c_str () );
591 string xmlbuildFilenames;
592 int numberOfExistingFiles = 0;
593 struct stat statbuf;
594 time_t SystemTime, lastWriteTime;
595
596 for ( size_t i = 0; i < ProjectNode.xmlbuildfiles.size (); i++ )
597 {
598 XMLInclude& xmlbuildfile = *ProjectNode.xmlbuildfiles[i];
599 if ( !xmlbuildfile.fileExists )
600 continue;
601 numberOfExistingFiles++;
602 if ( xmlbuildFilenames.length () > 0 )
603 xmlbuildFilenames += " ";
604
605 FILE* f = fopen ( xmlbuildfile.topIncludeFilename.c_str (), "rb" );
606 if ( !f )
607 throw FileNotFoundException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
608
609 if ( fstat ( fileno ( f ), &statbuf ) != 0 )
610 {
611 fclose ( f );
612 throw AccessDeniedException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
613 }
614
615 lastWriteTime = statbuf.st_mtime;
616 SystemTime = time(NULL);
617
618 if (SystemTime != -1)
619 {
620 if (difftime (lastWriteTime, SystemTime) > 0)
621 throw InvalidDateException ( NormalizeFilename ( xmlbuildfile.topIncludeFilename ) );
622 }
623
624 fclose ( f );
625
626 xmlbuildFilenames += NormalizeFilename ( xmlbuildfile.topIncludeFilename );
627 if ( numberOfExistingFiles % 5 == 4 || i == ProjectNode.xmlbuildfiles.size () - 1 )
628 {
629 fprintf ( fMakefile,
630 "\t%s",
631 xmlbuildFilenames.c_str ());
632 if ( i == ProjectNode.xmlbuildfiles.size () - 1 )
633 {
634 fprintf ( fMakefile, "\n" );
635 }
636 else
637 {
638 fprintf ( fMakefile,
639 " \\\n" );
640 }
641 xmlbuildFilenames.resize ( 0 );
642 }
643 numberOfExistingFiles++;
644 }
645 fprintf ( fMakefile, "\n" );
646 }
647
648 void
649 MingwBackend::GenerateTestSupportCode ()
650 {
651 printf ( "Generating test support code..." );
652 TestSupportCode testSupportCode ( ProjectNode );
653 testSupportCode.GenerateTestSupportCode ( configuration.Verbose );
654 printf ( "done\n" );
655 }
656
657 void
658 MingwBackend::GenerateCompilationUnitSupportCode ()
659 {
660 if ( configuration.CompilationUnitsEnabled )
661 {
662 printf ( "Generating compilation unit support code..." );
663 CompilationUnitSupportCode compilationUnitSupportCode ( ProjectNode );
664 compilationUnitSupportCode.Generate ( configuration.Verbose );
665 printf ( "done\n" );
666 }
667 }
668
669 void
670 MingwBackend::GenerateSysSetup ()
671 {
672 printf ( "Generating syssetup.inf..." );
673 SysSetupGenerator sysSetupGenerator ( ProjectNode );
674 sysSetupGenerator.Generate ();
675 printf ( "done\n" );
676 }
677
678 string
679 MingwBackend::GetProxyMakefileTree () const
680 {
681 if ( configuration.GenerateProxyMakefilesInSourceTree )
682 return "";
683 else
684 return Environment::GetOutputPath ();
685 }
686
687 void
688 MingwBackend::GenerateProxyMakefiles ()
689 {
690 printf ( "Generating proxy makefiles..." );
691 ProxyMakefile proxyMakefile ( ProjectNode );
692 proxyMakefile.GenerateProxyMakefiles ( configuration.Verbose,
693 GetProxyMakefileTree () );
694 printf ( "done\n" );
695 }
696
697 void
698 MingwBackend::CheckAutomaticDependencies ()
699 {
700 if ( configuration.Dependencies == AutomaticDependencies )
701 {
702 printf ( "Checking automatic dependencies..." );
703 AutomaticDependency automaticDependency ( ProjectNode );
704 automaticDependency.CheckAutomaticDependencies ( configuration.Verbose );
705 printf ( "done\n" );
706 }
707 }
708
709 void
710 MingwBackend::GenerateDirectories ()
711 {
712 printf ( "Creating directories..." );
713 intermediateDirectory->GenerateTree ( IntermediateDirectory, configuration.Verbose );
714 outputDirectory->GenerateTree ( OutputDirectory, configuration.Verbose );
715 if ( !configuration.MakeHandlesInstallDirectories )
716 installDirectory->GenerateTree ( InstallDirectory, configuration.Verbose );
717 printf ( "done\n" );
718 }
719
720 bool
721 MingwBackend::TryToDetectThisCompiler ( const string& compiler )
722 {
723 string command = ssprintf (
724 "%s -v 1>%s 2>%s",
725 FixSeparatorForSystemCommand(compiler).c_str (),
726 NUL,
727 NUL );
728 int exitcode = system ( command.c_str () );
729 return (bool) (exitcode == 0);
730 }
731
732 void
733 MingwBackend::DetectCompiler ()
734 {
735 printf ( "Detecting compiler..." );
736
737 bool detectedCompiler = false;
738 bool supportedCompiler = false;
739 string compilerVersion;
740
741 if ( ProjectNode.configuration.Compiler == GnuGcc )
742 {
743 const string& TARGET_CCValue = Environment::GetVariable ( "TARGET_CC" );
744 const string& ROS_PREFIXValue = Environment::GetVariable ( "ROS_PREFIX" );
745
746 if ( TARGET_CCValue.length () > 0 )
747 {
748 compilerPrefix = "";
749 compilerCommand = TARGET_CCValue;
750 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
751 }
752
753 if ( !detectedCompiler )
754 {
755 if ( ROS_PREFIXValue.length () > 0 )
756 {
757 compilerPrefix = ROS_PREFIXValue;
758 compilerCommand = compilerPrefix + "-gcc";
759 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
760 }
761 }
762 #if defined(WIN32)
763 if ( !detectedCompiler )
764 {
765 compilerPrefix = "";
766 compilerCommand = "gcc";
767 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
768 }
769 #endif
770 if ( !detectedCompiler )
771 {
772 compilerPrefix = "mingw32";
773 compilerCommand = compilerPrefix + "-gcc";
774 detectedCompiler = TryToDetectThisCompiler ( compilerCommand );
775 }
776
777 if ( detectedCompiler )
778 compilerVersion = GetCompilerVersion ( compilerCommand );
779
780 supportedCompiler = IsSupportedCompilerVersion ( compilerVersion );
781 }
782 else if ( ProjectNode.configuration.Compiler == MicrosoftC )
783 {
784 compilerCommand = "cl";
785 detectedCompiler = DetectMicrosoftCompiler ( compilerVersion, mscPath );
786 supportedCompiler = true; // TODO
787 }
788
789 if ( detectedCompiler )
790 {
791 if ( supportedCompiler )
792 printf ( "detected (%s %s)\n", compilerCommand.c_str (), compilerVersion.c_str() );
793 else
794 {
795 printf ( "detected (%s), but with unsupported version (%s)\n",
796 compilerCommand.c_str (),
797 compilerVersion.c_str () );
798 throw UnsupportedBuildToolException ( compilerCommand, compilerVersion );
799 }
800 }
801 else
802 printf ( "not detected\n" );
803
804 }
805
806 bool
807 MingwBackend::TryToDetectThisNetwideAssembler ( const string& assembler )
808 {
809 string command = ssprintf (
810 "%s -h 1>%s 2>%s",
811 FixSeparatorForSystemCommand(assembler).c_str (),
812 NUL,
813 NUL );
814 int exitcode = system ( command.c_str () );
815 return (bool) (exitcode == 0);
816 }
817
818 string
819 MingwBackend::GetVersionString ( const string& versionCommand )
820 {
821 FILE *fp;
822 int ch, i;
823 size_t newline;
824 char buffer[81];
825
826 fp = popen ( versionCommand.c_str () , "r" );
827 for( i = 0;
828 ( i < 80 ) &&
829 ( feof ( fp ) == 0 &&
830 ( ( ch = fgetc( fp ) ) != -1 ) );
831 i++ )
832 {
833 buffer[i] = (char) ch;
834 }
835 buffer[i] = '\0';
836 pclose ( fp );
837
838 char separators[] = " ()";
839 char *token;
840 char *prevtoken = NULL;
841
842 string version;
843
844 token = strtok ( buffer, separators );
845 while ( token != NULL )
846 {
847 prevtoken = token;
848 version = string( prevtoken );
849 if ( (newline = version.find('\n')) != std::string::npos )
850 version.erase(newline, 1);
851 if ( version.find('.') != std::string::npos )
852 break;
853 token = strtok ( NULL, separators );
854 }
855 return version;
856 }
857
858 string
859 MingwBackend::GetNetwideAssemblerVersion ( const string& nasmCommand )
860 {
861 string versionCommand;
862 if ( nasmCommand.find("yasm") != std::string::npos )
863 {
864 versionCommand = ssprintf ( "%s --version",
865 nasmCommand.c_str (),
866 NUL,
867 NUL );
868 }
869 else
870 {
871 versionCommand = ssprintf ( "%s -v",
872 nasmCommand.c_str (),
873 NUL,
874 NUL );
875 }
876 return GetVersionString( versionCommand );
877 }
878
879 string
880 MingwBackend::GetCompilerVersion ( const string& compilerCommand )
881 {
882 string versionCommand = ssprintf ( "%s --version gcc",
883 compilerCommand.c_str (),
884 NUL,
885 NUL );
886 return GetVersionString( versionCommand );
887 }
888
889 string
890 MingwBackend::GetBinutilsVersion ( const string& binutilsCommand )
891 {
892 string versionCommand = ssprintf ( "%s -v",
893 binutilsCommand.c_str (),
894 NUL,
895 NUL );
896 return GetVersionString( versionCommand );
897 }
898
899 bool
900 MingwBackend::IsSupportedCompilerVersion ( const string& compilerVersion )
901 {
902 if ( strcmp ( compilerVersion.c_str (), "3.4.2") < 0 )
903 return false;
904 else
905 return true;
906 }
907
908 bool
909 MingwBackend::TryToDetectThisBinutils ( const string& binutils )
910 {
911 string command = ssprintf (
912 "%s -v 1>%s 2>%s",
913 FixSeparatorForSystemCommand(binutils).c_str (),
914 NUL,
915 NUL );
916 int exitcode = system ( command.c_str () );
917 return (exitcode == 0);
918 }
919
920 string
921 MingwBackend::GetBinutilsVersionDate ( const string& binutilsCommand )
922 {
923 FILE *fp;
924 int ch, i;
925 char buffer[81];
926
927 string versionCommand = ssprintf ( "%s -v",
928 binutilsCommand.c_str (),
929 NUL,
930 NUL );
931 fp = popen ( versionCommand.c_str () , "r" );
932 for( i = 0;
933 ( i < 80 ) &&
934 ( feof ( fp ) == 0 &&
935 ( ( ch = fgetc( fp ) ) != -1 ) );
936 i++ )
937 {
938 buffer[i] = (char) ch;
939 }
940 buffer[i] = '\0';
941 pclose ( fp );
942
943 char separators[] = " ";
944 char *token;
945 char *prevtoken = NULL;
946
947 token = strtok ( buffer, separators );
948 while ( token != NULL )
949 {
950 prevtoken = token;
951 token = strtok ( NULL, separators );
952 }
953 string version = string ( prevtoken );
954 int lastDigit = version.find_last_not_of ( "\t\r\n" );
955 if ( lastDigit != -1 )
956 return string ( version, 0, lastDigit+1 );
957 else
958 return version;
959 }
960
961 bool
962 MingwBackend::IsSupportedBinutilsVersion ( const string& binutilsVersion )
963 {
964 if ( manualBinutilsSetting ) return true;
965
966 /* linux */
967 if ( binutilsVersion.find('.') != std::string::npos )
968 {
969 /* TODO: blacklist versions on version number instead of date */
970 return true;
971 }
972
973 /*
974 * - Binutils older than 2003/10/01 have broken windres which can't handle
975 * icons with alpha channel.
976 * - Binutils between 2004/09/02 and 2004/10/08 have broken handling of
977 * forward exports in dlltool.
978 */
979 if ( ( ( strcmp ( binutilsVersion.c_str (), "20040902") >= 0 ) &&
980 ( strcmp ( binutilsVersion.c_str (), "20041008") <= 0 ) ) ||
981 ( strcmp ( binutilsVersion.c_str (), "20031001") < 0 ) )
982 return false;
983 else
984 return true;
985 }
986
987 void
988 MingwBackend::DetectBinutils ()
989 {
990 printf ( "Detecting binutils..." );
991
992 bool detectedBinutils = false;
993 bool supportedBinutils = false;
994 string binutilsVersion;
995
996 if ( ProjectNode.configuration.Linker == GnuLd )
997 {
998 const string& ROS_PREFIXValue = Environment::GetVariable ( "ROS_PREFIX" );
999
1000 if ( ROS_PREFIXValue.length () > 0 )
1001 {
1002 binutilsPrefix = ROS_PREFIXValue;
1003 binutilsCommand = binutilsPrefix + "-ld";
1004 manualBinutilsSetting = true;
1005 detectedBinutils = true;
1006 }
1007 #if defined(WIN32)
1008 if ( !detectedBinutils )
1009 {
1010 binutilsPrefix = "";
1011 binutilsCommand = "ld";
1012 detectedBinutils = TryToDetectThisBinutils ( binutilsCommand );
1013 }
1014 #endif
1015 if ( !detectedBinutils )
1016 {
1017 binutilsPrefix = "mingw32";
1018 binutilsCommand = binutilsPrefix + "-ld";
1019 detectedBinutils = TryToDetectThisBinutils ( binutilsCommand );
1020 }
1021 if ( detectedBinutils )
1022 {
1023 binutilsVersion = GetBinutilsVersionDate ( binutilsCommand );
1024 supportedBinutils = IsSupportedBinutilsVersion ( binutilsVersion );
1025 }
1026 }
1027 else if ( ProjectNode.configuration.Linker == MicrosoftLink )
1028 {
1029 compilerCommand = "link";
1030 detectedBinutils = DetectMicrosoftLinker ( binutilsVersion, mslinkPath );
1031 supportedBinutils = true; // TODO
1032 }
1033
1034 if ( detectedBinutils )
1035 {
1036 if ( supportedBinutils )
1037 printf ( "detected (%s %s)\n", binutilsCommand.c_str (), binutilsVersion.c_str() );
1038 else
1039 {
1040 printf ( "detected (%s), but with unsupported version (%s)\n",
1041 binutilsCommand.c_str (),
1042 binutilsVersion.c_str () );
1043 throw UnsupportedBuildToolException ( binutilsCommand, binutilsVersion );
1044 }
1045 }
1046 else
1047 printf ( "not detected\n" );
1048
1049 }
1050
1051 void
1052 MingwBackend::DetectNetwideAssembler ()
1053 {
1054 printf ( "Detecting netwide assembler..." );
1055
1056 nasmCommand = "nasm";
1057 bool detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1058 #if defined(WIN32)
1059 if ( !detectedNasm )
1060 {
1061 nasmCommand = "nasmw";
1062 detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1063 }
1064 #endif
1065 if ( !detectedNasm )
1066 {
1067 nasmCommand = "yasm";
1068 detectedNasm = TryToDetectThisNetwideAssembler ( nasmCommand );
1069 }
1070 if ( detectedNasm )
1071 printf ( "detected (%s %s)\n", nasmCommand.c_str (), GetNetwideAssemblerVersion( nasmCommand ).c_str() );
1072 else
1073 printf ( "not detected\n" );
1074 }
1075
1076 void
1077 MingwBackend::DetectPipeSupport ()
1078 {
1079 if ( ProjectNode.configuration.Compiler == GnuGcc )
1080 {
1081 printf ( "Detecting compiler -pipe support..." );
1082
1083 string pipe_detection = "tools" + sSep + "rbuild" + sSep + "backend" + sSep + "mingw" + sSep + "pipe_detection.c";
1084 string pipe_detectionObjectFilename = ReplaceExtension ( pipe_detection,
1085 ".o" );
1086 string command = ssprintf (
1087 "%s -pipe -c %s -o %s 1>%s 2>%s",
1088 FixSeparatorForSystemCommand(compilerCommand).c_str (),
1089 pipe_detection.c_str (),
1090 pipe_detectionObjectFilename.c_str (),
1091 NUL,
1092 NUL );
1093 int exitcode = system ( command.c_str () );
1094 FILE* f = fopen ( pipe_detectionObjectFilename.c_str (), "rb" );
1095 if ( f )
1096 {
1097 usePipe = (exitcode == 0);
1098 fclose ( f );
1099 unlink ( pipe_detectionObjectFilename.c_str () );
1100 }
1101 else
1102 usePipe = false;
1103
1104 if ( usePipe )
1105 printf ( "detected\n" );
1106 else
1107 printf ( "not detected\n" );
1108 }
1109 else
1110 usePipe = false;
1111 }
1112
1113 void
1114 MingwBackend::DetectPCHSupport ()
1115 {
1116 printf ( "Detecting compiler pre-compiled header support..." );
1117
1118 if ( configuration.PrecompiledHeadersEnabled && ProjectNode.configuration.Compiler == GnuGcc )
1119 {
1120 string path = "tools" + sSep + "rbuild" + sSep + "backend" + sSep + "mingw" + sSep + "pch_detection.h";
1121 string cmd = ssprintf (
1122 "%s -c %s 1>%s 2>%s",
1123 FixSeparatorForSystemCommand(compilerCommand).c_str (),
1124 path.c_str (),
1125 NUL,
1126 NUL );
1127 system ( cmd.c_str () );
1128 path += ".gch";
1129
1130 FILE* f = fopen ( path.c_str (), "rb" );
1131 if ( f )
1132 {
1133 use_pch = true;
1134 fclose ( f );
1135 unlink ( path.c_str () );
1136 }
1137 else
1138 use_pch = false;
1139
1140 if ( use_pch )
1141 printf ( "detected\n" );
1142 else
1143 printf ( "not detected\n" );
1144 }
1145 else
1146 {
1147 use_pch = false;
1148 printf ( "disabled\n" );
1149 }
1150 }
1151
1152 void
1153 MingwBackend::GetNonModuleInstallTargetFiles (
1154 vector<FileLocation>& out ) const
1155 {
1156 for ( size_t i = 0; i < ProjectNode.installfiles.size (); i++ )
1157 {
1158 const InstallFile& installfile = *ProjectNode.installfiles[i];
1159 out.push_back ( *installfile.target );
1160 }
1161 }
1162
1163 void
1164 MingwBackend::GetModuleInstallTargetFiles (
1165 vector<FileLocation>& out ) const
1166 {
1167 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1168 {
1169 const Module& module = *p->second;
1170 if ( !module.enabled )
1171 continue;
1172 if ( module.install )
1173 out.push_back ( *module.install );
1174 }
1175 }
1176
1177 void
1178 MingwBackend::GetInstallTargetFiles (
1179 vector<FileLocation>& out ) const
1180 {
1181 GetNonModuleInstallTargetFiles ( out );
1182 GetModuleInstallTargetFiles ( out );
1183 }
1184
1185 void
1186 MingwBackend::OutputInstallTarget ( const FileLocation& source,
1187 const FileLocation& target )
1188 {
1189 fprintf ( fMakefile,
1190 "%s: %s | %s\n",
1191 GetFullName ( target ).c_str (),
1192 GetFullName ( source ).c_str (),
1193 GetFullPath ( target ).c_str () );
1194 fprintf ( fMakefile,
1195 "\t$(ECHO_CP)\n" );
1196 fprintf ( fMakefile,
1197 "\t${cp} %s %s 1>$(NUL)\n",
1198 GetFullName ( source ).c_str (),
1199 GetFullName ( target ).c_str () );
1200 }
1201
1202 void
1203 MingwBackend::OutputNonModuleInstallTargets ()
1204 {
1205 for ( size_t i = 0; i < ProjectNode.installfiles.size (); i++ )
1206 {
1207 const InstallFile& installfile = *ProjectNode.installfiles[i];
1208 OutputInstallTarget ( *installfile.source, *installfile.target );
1209 }
1210 }
1211
1212 const Module&
1213 MingwBackend::GetAliasedModuleOrModule ( const Module& module ) const
1214 {
1215 if ( module.aliasedModuleName.size () > 0 )
1216 {
1217 const Module* aliasedModule = ProjectNode.LocateModule ( module.aliasedModuleName );
1218 assert ( aliasedModule );
1219 return *aliasedModule;
1220 }
1221 else
1222 return module;
1223 }
1224
1225 void
1226 MingwBackend::OutputModuleInstallTargets ()
1227 {
1228 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1229 {
1230 const Module& module = *p->second;
1231 if ( !module.enabled )
1232 continue;
1233 if ( module.install )
1234 {
1235 const Module& aliasedModule = GetAliasedModuleOrModule ( module );
1236 OutputInstallTarget ( *aliasedModule.output, *module.install );
1237 }
1238 }
1239 }
1240
1241 string
1242 MingwBackend::GetRegistrySourceFiles ()
1243 {
1244 return "boot" + sSep + "bootdata" + sSep + "hivecls_" + Environment::GetArch() + ".inf "
1245 "boot" + sSep + "bootdata" + sSep + "hivedef_" + Environment::GetArch() + ".inf "
1246 "boot" + sSep + "bootdata" + sSep + "hiveinst_" + Environment::GetArch() + ".inf "
1247 "boot" + sSep + "bootdata" + sSep + "hivesft_" + Environment::GetArch() + ".inf "
1248 "boot" + sSep + "bootdata" + sSep + "hivesys_" + Environment::GetArch() + ".inf ";
1249 }
1250
1251 string
1252 MingwBackend::GetRegistryTargetFiles ()
1253 {
1254 string system32ConfigDirectory = "system32" + sSep + "config";
1255 FileLocation system32 ( InstallDirectory, system32ConfigDirectory, "" );
1256
1257 vector<FileLocation> registry_files;
1258 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "default" ) );
1259 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "sam" ) );
1260 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "security" ) );
1261 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "software" ) );
1262 registry_files.push_back ( FileLocation ( InstallDirectory, system32ConfigDirectory, "system" ) );
1263
1264 return v2s( this, registry_files, 6 );
1265 }
1266
1267 void
1268 MingwBackend::OutputRegistryInstallTarget ()
1269 {
1270 FileLocation system32 ( InstallDirectory, "system32" + sSep + "config", "" );
1271
1272 string registrySourceFiles = GetRegistrySourceFiles ();
1273 string registryTargetFiles = GetRegistryTargetFiles ();
1274 fprintf ( fMakefile,
1275 "install_registry: %s\n",
1276 registryTargetFiles.c_str () );
1277 fprintf ( fMakefile,
1278 "%s: %s %s $(MKHIVE_TARGET)\n",
1279 registryTargetFiles.c_str (),
1280 registrySourceFiles.c_str (),
1281 GetFullPath ( system32 ).c_str () );
1282 fprintf ( fMakefile,
1283 "\t$(ECHO_MKHIVE)\n" );
1284 fprintf ( fMakefile,
1285 "\t$(MKHIVE_TARGET) boot%cbootdata %s $(ARCH) boot%cbootdata%chiveinst_$(ARCH).inf\n",
1286 cSep, GetFullPath ( system32 ).c_str (),
1287 cSep, cSep );
1288 fprintf ( fMakefile,
1289 "\n" );
1290 }
1291
1292 void
1293 MingwBackend::GenerateInstallTarget ()
1294 {
1295 vector<FileLocation> vInstallTargetFiles;
1296 GetInstallTargetFiles ( vInstallTargetFiles );
1297 string installTargetFiles = v2s ( this, vInstallTargetFiles, 5 );
1298 string registryTargetFiles = GetRegistryTargetFiles ();
1299
1300 fprintf ( fMakefile,
1301 "install: %s %s\n",
1302 installTargetFiles.c_str (),
1303 registryTargetFiles.c_str () );
1304 OutputNonModuleInstallTargets ();
1305 OutputModuleInstallTargets ();
1306 OutputRegistryInstallTarget ();
1307 fprintf ( fMakefile,
1308 "\n" );
1309 }
1310
1311 void
1312 MingwBackend::GetModuleTestTargets (
1313 vector<string>& out ) const
1314 {
1315 for ( std::map<std::string, Module*>::const_iterator p = ProjectNode.modules.begin (); p != ProjectNode.modules.end (); ++ p )
1316 {
1317 const Module& module = *p->second;
1318 if ( !module.enabled )
1319 continue;
1320 if ( module.type == Test )
1321 out.push_back ( module.name );
1322 }
1323 }
1324
1325 void
1326 MingwBackend::GenerateTestTarget ()
1327 {
1328 vector<string> vTestTargets;
1329 GetModuleTestTargets ( vTestTargets );
1330 string testTargets = v2s ( vTestTargets, 5 );
1331
1332 fprintf ( fMakefile,
1333 "test: %s\n",
1334 testTargets.c_str () );
1335 fprintf ( fMakefile,
1336 "\n" );
1337 }
1338
1339 void
1340 MingwBackend::GenerateDirectoryTargets ()
1341 {
1342 intermediateDirectory->CreateRule ( fMakefile, "$(INTERMEDIATE)" );
1343 outputDirectory->CreateRule ( fMakefile, "$(OUTPUT)" );
1344 installDirectory->CreateRule ( fMakefile, "$(INSTALL)" );
1345 }