Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GNUCompiler.cs « Compiler « CBinding « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b75471a9ff2df43d6da7a91cdf60a440205eeba0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
//
// GNUCompiler.cs: Provides most functionality to compile using a GNU compiler (gcc and g++)
//
// Authors:
//   Marcos David Marin Amador <MarcosMarin@gmail.com>
//   Mitchell Wheeler <mitchell.wheeler@gmail.com>
//
// Copyright (C) 2007 Marcos David Marin Amador
//
//
// This source code is licenced under The MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Diagnostics;
using System.CodeDom.Compiler;

using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Core.ProgressMonitoring;
using MonoDevelop.Projects;

namespace CBinding
{
	public abstract class GNUCompiler : CCompiler
	{
		bool appsChecked;
		bool compilerFound;
		bool linkerFound;
		
		public override BuildResult Compile (
		    Project project,
		    ProjectFileCollection projectFiles,
		    ProjectPackageCollection packages,
		    CProjectConfiguration configuration,
		    IProgressMonitor monitor)
		{
			if (!appsChecked) {
				appsChecked = true;
				compilerFound = CheckApp (compilerCommand);
				linkerFound = CheckApp (linkerCommand);
			}
				
			if (!compilerFound) {
				BuildResult cres = new BuildResult ();
				cres.AddError ("Compiler not found: " + compilerCommand);
				return cres;
			}
			
			if (!linkerFound) {
				BuildResult cres = new BuildResult ();
				cres.AddError ("Linker not found: " + linkerCommand);
				return cres;
			}
			
			CompilerResults cr = new CompilerResults (new TempFileCollection ());
			bool success = true;
			string compilerArgs = GetCompilerFlags (project, configuration) + " " + GeneratePkgCompilerArgs (packages);
			
			string outputName = Path.Combine (configuration.OutputDirectory,
			                                  configuration.CompiledOutputName);
			
			// Precompile header files and place them in prec/<config_name>/
			if (configuration.PrecompileHeaders) {
				string precDir = Path.Combine (configuration.IntermediateOutputDirectory, "prec");
				string precConfigDir = Path.Combine (precDir, configuration.Id);
				if (!Directory.Exists (precDir))
					Directory.CreateDirectory (precDir);
				if (!Directory.Exists (precConfigDir))
					Directory.CreateDirectory (precConfigDir);
				
				if (!PrecompileHeaders (projectFiles, configuration, compilerArgs, monitor, cr))
					success = false;
			} else {
				//old headers could interfere with the build
				CleanPrecompiledHeaders (configuration);
			}
			
			//compile source to object files
			monitor.BeginTask (GettextCatalog.GetString ("Compiling source to object files"), 1);
			foreach (ProjectFile f in projectFiles) {
				if (!success) break;
				if (f.Subtype == Subtype.Directory || f.BuildAction != BuildAction.Compile || CProject.IsHeaderFile (f.FilePath))
					continue;
				
				if (configuration.UseCcache || NeedsCompiling (f, configuration))
					success = DoCompilation (f, configuration, compilerArgs, monitor, cr, configuration.UseCcache);
			}
			if (success)
				monitor.Step (1);
			monitor.EndTask ();

			if (success) {
				switch (configuration.CompileTarget)
				{
				case CBinding.CompileTarget.Bin:
					MakeBin (project, projectFiles, configuration, packages, cr, monitor, outputName);
					break;
				case CBinding.CompileTarget.StaticLibrary:
					MakeStaticLibrary (project, projectFiles, configuration, packages, cr, monitor, outputName);
					break;
				case CBinding.CompileTarget.SharedLibrary:
					MakeSharedLibrary (project, projectFiles, configuration, packages, cr, monitor, outputName);
					break;
				}
			}
			
			return new BuildResult (cr, "");
		}
		
		public override bool SupportsCcache {
			get { return true; }
		}
		
		public override bool SupportsPrecompiledHeaders {
			get { return true; }
		}
		
		Dictionary<string, string> GetStringTags (Project project)
		{
			Dictionary<string, string> result = new Dictionary<string, string> (StringComparer.InvariantCultureIgnoreCase);
			result["PROJECTDIR"] = project.BaseDirectory;
			result["PROJECTFILENAME"] = project.FileName;
			return result;
		}
		
		public override string GetCompilerFlags (Project project, CProjectConfiguration configuration)
		{
			StringBuilder args = new StringBuilder ();
			
			if (configuration.DebugMode)
				args.Append ("-g ");
			
			if (configuration.CompileTarget == CBinding.CompileTarget.SharedLibrary)
				args.Append ("-fPIC ");
			
			switch (configuration.WarningLevel)
			{
			case WarningLevel.None:
				args.Append ("-w ");
				break;
			case WarningLevel.Normal:
				// nothing
				break;
			case WarningLevel.All:
				args.Append ("-Wall ");
				break;
			}
			
			if (configuration.WarningsAsErrors)
				args.Append ("-Werror ");
			
			args.Append ("-O" + configuration.OptimizationLevel + " ");
			
			if (configuration.ExtraCompilerArguments != null && configuration.ExtraCompilerArguments.Length > 0) {
				string extraCompilerArgs = ExpandBacktickedParameters(configuration.ExtraCompilerArguments.Replace ('\n', ' '));
				args.Append (extraCompilerArgs + " ");
			}
			
			if (configuration.DefineSymbols != null && configuration.DefineSymbols.Length > 0)
				args.Append (ProcessDefineSymbols (configuration.DefineSymbols) + " ");
			
			if (configuration.Includes != null)
				foreach (string inc in configuration.Includes)
					args.Append ("-I\"" + StringParserService.Parse (inc, GetStringTags (project)) + "\" ");
			
			if (configuration.PrecompileHeaders) {
				string precdir = Path.Combine (configuration.IntermediateOutputDirectory, "prec");
				precdir = Path.Combine (precdir, configuration.Id);
				args.Append ("-I\"" + precdir + "\"");
			}
			
			return args.ToString ();
		}
		
		public override string GetDefineFlags (Project project, CProjectConfiguration configuration)
		{
			return ProcessDefineSymbols (configuration.DefineSymbols);
		}
		
		private bool NeedsCompiling (ProjectFile file, CProjectConfiguration configuration)
		{
			string objectFile = Path.Combine(configuration.OutputDirectory, Path.GetFileName(file.Name));
			objectFile = Path.ChangeExtension(objectFile, ".o");
			if (!File.Exists (objectFile))
				return true;
			
			string[] dependedOnFiles = DependedOnFiles (file, configuration);
			if (dependedOnFiles == null) {
				return true;
			}
			
			DateTime lastObjectTime = File.GetLastWriteTime (objectFile);
			
			try {
				foreach (string depfile in dependedOnFiles) {
					if (File.GetLastWriteTime (depfile) > lastObjectTime) {
						return true;
					}
				}
			} catch (IOException e) {
				// This means the dependency file is telling us our source file
				// depends on a file that no longer exists, all this means is that 
				// the dependency file is outdated. We should just ignore this
				// since the dependency file will be automatically updated when
				// the source file is compiled.
				e.ToString (); // suppress warning.
			}
			
			return false;
		}
		
		/// <summary>
		/// Returns an array of depended on files or null if the
		/// file containing the depended on files (.d) does does not exist.
		/// </summary>
		private string[] DependedOnFiles (ProjectFile file, CProjectConfiguration configuration)
		{
			List<string> dependencies = new List<string> ();
			string dependenciesFile = Path.Combine(configuration.OutputDirectory, Path.GetFileName(file.Name));
			dependenciesFile = Path.ChangeExtension(dependenciesFile, ".d");
			
			if (!File.Exists (dependenciesFile))
				return null;
			
			// It always depends on itself ;)
			dependencies.Add (file.Name);
			
			string temp;
			using (StreamReader reader = new StreamReader (dependenciesFile)) {
				while ((temp = reader.ReadLine ()) != null) {
					// TODO: We really should be using a regex here,
					// this will have issues with pathnames containing double spaces.
					string depfile = temp.Replace(" \\", String.Empty).Trim();
	
					// Ignore empty strings &  object files...
					if(String.IsNullOrEmpty(depfile) ||
					   depfile.EndsWith(".o:") || depfile.EndsWith(".o"))
					   continue;
					
					dependencies.Add(depfile.Replace(@"\ ", " "));
				}
			}

			return dependencies.ToArray();
		}
		
		private bool PrecompileHeaders (ProjectFileCollection projectFiles,
		                                CProjectConfiguration configuration,
		                                string args,
		                                IProgressMonitor monitor,
		                                CompilerResults cr)
		{
			monitor.BeginTask (GettextCatalog.GetString ("Precompiling headers"), 1);
			bool success = true;
			
			foreach (ProjectFile file in projectFiles) {
				if (file.Subtype == Subtype.Code && CProject.IsHeaderFile (file.Name)) {
					string precomp = Path.Combine (configuration.IntermediateOutputDirectory, "prec");
					precomp = Path.Combine (precomp, configuration.Id);
					precomp = Path.Combine (precomp, Path.GetFileName (file.Name) + ".ghc");
					if (file.BuildAction == BuildAction.Compile) {
						if (!File.Exists (precomp) || configuration.UseCcache || File.GetLastWriteTime (file.Name) > File.GetLastWriteTime (precomp)) {
							if (DoPrecompileHeader (file, precomp, args, monitor, cr) == false) {
								success = false;
								break;
							}
						}
					} else {
						//remove old files or they'll interfere with the build
						if (File.Exists (precomp))
							File.Delete (precomp);
					}
				}
				
			}
			if (success)
				monitor.Step (1);
			monitor.EndTask ();
			return success;
		}
		
		private bool DoPrecompileHeader (ProjectFile file, string output, string args, IProgressMonitor monitor, CompilerResults cr)
		{
			string completeArgs = String.Format ("\"{0}\" {1} -o {2}", file.Name, args, output);
			string errorOutput;
			int exitCode = ExecuteCommand (compilerCommand, completeArgs, Path.GetDirectoryName (output), monitor, out errorOutput);
			ParseCompilerOutput (errorOutput, cr);
			return (exitCode == 0);
		}

		static readonly string[] libraryExtensions = { ".so", ".a", ".dll", ".dylib" };
		/// <summary>
		/// Checks whether a library can be linked with -lbasename
		/// </summary>
		/// <remarks>
		/// This should return true iff directory is empty or in 
		/// the configured library paths, and library is of the form blah
		/// or libblah.(a|so|dll|dylib), 
		/// </remarks>
		internal bool IsStandardLibrary(CProjectConfiguration configuration,
		                                string directory, string library,
		                                ref string std_lib)
		{
			std_lib = library;
			
			if(!(String.IsNullOrEmpty(directory) || 
			    configuration.LibPaths.Contains(directory)))
				return false;
				
			string libraryExtension = Path.GetExtension (library);
			
			foreach (string extension in libraryExtensions)
			{
				if (libraryExtension.Equals (extension, StringComparison.OrdinalIgnoreCase)) {
					if (library.StartsWith("lib", StringComparison.OrdinalIgnoreCase)) {
						std_lib = std_lib.Substring(3);
						return true;
					} else {
						return false;
					}
				}
			}
			
			return true;
		}
		
		private void MakeBin (Project project,
		                      ProjectFileCollection projectFiles,
		                     CProjectConfiguration configuration,
		                     ProjectPackageCollection packages,
		                     CompilerResults cr,
		                     IProgressMonitor monitor, string outputName)
		{
			if (!NeedsUpdate (projectFiles, configuration, outputName)) return;
			
			string objectFiles = string.Join (" ", ObjectFiles (projectFiles, configuration, true));
			string pkgargs = GeneratePkgLinkerArgs (packages);
			StringBuilder args = new StringBuilder ();
			
			if (configuration.ExtraLinkerArguments != null && configuration.ExtraLinkerArguments.Length > 0) {
				string extraLinkerArgs = ExpandBacktickedParameters(configuration.ExtraLinkerArguments.Replace ('\n', ' '));
				args.Append (extraLinkerArgs + " ");
			}
			
			if (configuration.LibPaths != null)
				foreach (string libpath in configuration.LibPaths)
					args.Append ("-L\"" + StringParserService.Parse (libpath, GetStringTags (project)) + "\" ");
			
			if (configuration.Libs != null) {
				foreach (string lib in configuration.Libs) {
					string directory = Path.GetDirectoryName(lib);
					string library = Path.GetFileName(lib);

					// Is this a 'standard' (as in, uses an orthodox naming convention) library..?
					string link_lib = String.Empty;
					if(IsStandardLibrary(configuration, directory, library, ref link_lib))
						args.Append ("-l\"" + link_lib + "\" ");
					// If not, reference the library by it's full pathname.
					else
						args.Append ("\"" + lib + "\" ");
				}
			}
			
			string linker_args = string.Format ("-o \"{0}\" {1} {2} {3}",
			    outputName, objectFiles, pkgargs, args.ToString ());
			
			monitor.BeginTask (GettextCatalog.GetString ("Generating binary \"{0}\" from object files", Path.GetFileName (outputName)), 1);
			
			string errorOutput;
			int exitCode = ExecuteCommand (linkerCommand, linker_args, Path.GetDirectoryName (outputName), monitor, out errorOutput);
			if (exitCode == 0)
				monitor.Step (1);
			monitor.EndTask ();
			
			ParseCompilerOutput (errorOutput, cr);
			ParseLinkerOutput (errorOutput, cr);
			CheckReturnCode (exitCode, cr);
		}
		
		private void MakeStaticLibrary (Project project,
		                                ProjectFileCollection projectFiles,
		                                CProjectConfiguration configuration,
		                                ProjectPackageCollection packages,
		                                CompilerResults cr,
		                                IProgressMonitor monitor, string outputName)
		{
			if (!NeedsUpdate (projectFiles, configuration, outputName)) return;
			
			string objectFiles = string.Join (" ", ObjectFiles (projectFiles, configuration, true));
			string args = string.Format ("rcs \"{0}\" {1}", outputName, objectFiles);
			
			monitor.BeginTask (GettextCatalog.GetString ("Generating static library {0} from object files", Path.GetFileName (outputName)), 1);
			
			string errorOutput;
			int exitCode = ExecuteCommand ("ar", args, Path.GetDirectoryName (outputName), monitor, out errorOutput);
			if (exitCode == 0)
				monitor.Step (1);
			monitor.EndTask ();
			
			ParseCompilerOutput (errorOutput, cr);
			ParseLinkerOutput (errorOutput, cr);
			CheckReturnCode (exitCode, cr);
		}
		
		private void MakeSharedLibrary(Project project,
		                               ProjectFileCollection projectFiles,
		                               CProjectConfiguration configuration,
		                               ProjectPackageCollection packages,
		                               CompilerResults cr,
		                               IProgressMonitor monitor, string outputName)
		{
			if (!NeedsUpdate (projectFiles, configuration, outputName)) return;
			
			string objectFiles = string.Join (" ", ObjectFiles (projectFiles, configuration, true));
			string pkgargs = GeneratePkgLinkerArgs (packages);
			StringBuilder args = new StringBuilder ();
			
			if (configuration.ExtraLinkerArguments != null && configuration.ExtraLinkerArguments.Length > 0) {
				string extraLinkerArgs = ExpandBacktickedParameters(configuration.ExtraLinkerArguments.Replace ('\n', ' '));
				args.Append (extraLinkerArgs + " ");
			}
			
			if (configuration.LibPaths != null)
				foreach (string libpath in configuration.LibPaths)
					args.Append ("-L\"" + StringParserService.Parse (libpath, GetStringTags (project)) + "\" ");
			
			if (configuration.Libs != null) {
				foreach (string lib in configuration.Libs) {
					string directory = Path.GetDirectoryName(lib);
					string library = Path.GetFileName(lib);

					// Is this a 'standard' (as in, uses an orthodox naming convention) library..?
					string link_lib = String.Empty;
					if(IsStandardLibrary(configuration, directory, library, ref link_lib))
						args.Append ("-l\"" + link_lib + "\" ");
					// If not, reference the library by it's full pathname.
					else
						args.Append ("\"" + lib + "\" ");
				}
			}
			
			string linker_args = string.Format ("-shared -o \"{0}\" {1} {2} {3}",
			    outputName, objectFiles, pkgargs, args.ToString ());
			
			monitor.BeginTask (GettextCatalog.GetString ("Generating shared object \"{0}\" from object files", Path.GetFileName (outputName)), 1);
			
			string errorOutput;
			int exitCode = ExecuteCommand (linkerCommand , linker_args, Path.GetDirectoryName (outputName), monitor, out errorOutput);
			if (exitCode == 0)
				monitor.Step (1);
			monitor.EndTask ();
			
			ParseCompilerOutput (errorOutput, cr);
			ParseLinkerOutput (errorOutput, cr);
			CheckReturnCode (exitCode, cr);
		}
		
		int ExecuteCommand (string command, string args, string baseDirectory, IProgressMonitor monitor, out string errorOutput)
		{
			errorOutput = string.Empty;
			int exitCode = -1;
			
			using (var swError = new StringWriter ()) {
				using (var chainedError = new LogTextWriter ()) {
					chainedError.ChainWriter (monitor.Log);
					chainedError.ChainWriter (swError);
			
					monitor.Log.WriteLine ("{0} {1}", command, args);
			
					using (var operationMonitor = new AggregatedOperationMonitor (monitor)) {
						using (ProcessWrapper p = Runtime.ProcessService.StartProcess (command, args, baseDirectory, monitor.Log, chainedError, null)) {
							operationMonitor.AddOperation (p); //handles cancellation
				
							p.WaitForOutput ();
							chainedError.UnchainWriter (monitor.Log);
							chainedError.UnchainWriter (swError);

							errorOutput = swError.ToString ();
							exitCode = p.ExitCode;
				
							if (monitor.IsCancelRequested) {
								monitor.Log.WriteLine (GettextCatalog.GetString ("Build cancelled"));
								monitor.ReportError (GettextCatalog.GetString ("Build cancelled"), null);
								if (exitCode == 0)
									exitCode = -1;
							}
						}
					}
				}
			}
			
			return exitCode;
		}
		
		private string ProcessDefineSymbols (string symbols)
		{
			StringBuilder processed = new StringBuilder (symbols);
			
			// Take care of multi adyacent spaces
			for (int i = 0; i < processed.Length; i++) {
				if (i + 1 < processed.Length &&
				    processed[i] == ' ' &&
				    processed[i + 1] == ' ') {
					processed.Remove (i--, 1);
				}
			}
			
			return processed.ToString ()
				            .Trim ()
				            .Replace (" ", " -D")
				            .Insert (0, "-D");
		}
		
		/// <summary>
		/// Compiles a single source file into object code
		/// and creates a file with it's dependencies.
		/// </summary>
		private bool DoCompilation (ProjectFile file,
		                            CProjectConfiguration configuration,
		                            string args,
		                            IProgressMonitor monitor,
		                            CompilerResults cr,
		                            bool use_ccache)
		{

			string outputName = Path.Combine(configuration.OutputDirectory, Path.GetFileName(Path.ChangeExtension (file.Name, ".o")));
			
			string compiler_args = string.Format ("{0} -MMD \"{1}\" {2} -c -o \"{3}\"",
			    (use_ccache ? compilerCommand : string.Empty), file.Name, args, outputName);

			string errorOutput;
			int exitCode = ExecuteCommand ((use_ccache ? "ccache" : compilerCommand), compiler_args, configuration.OutputDirectory, monitor, out errorOutput);
			
			ParseCompilerOutput (errorOutput, cr);
			CheckReturnCode (exitCode, cr);
			return exitCode == 0;
		}
		
		/// <summary>
		/// Gets the files that get compiled into object code.
		/// </summary>
		/// <param name="projectFiles">
		/// A <see cref="ProjectFileCollection"/>
		/// The project's files, extracts from here the files that get compiled into object code.
		/// </param>
		/// <param name="configuration">
		/// A <see cref="CProjectConfiguration"/>
		/// The configuration to get the object files for...
		/// </param>
		/// <param name="withQuotes">
		/// A <see cref="System.Boolean"/>
		/// If true, it will surround each object file with quotes 
		/// so that gcc has no problem with paths that contain spaces.
		/// </param>
		/// <returns>
		/// An array of strings, each string is the name of a file
		/// that will get compiled into object code. The file name
		/// will already have the .o extension.
		/// </returns>
		private string[] ObjectFiles (ProjectFileCollection projectFiles, CProjectConfiguration configuration, bool withQuotes)
		{
			if(projectFiles.Count == 0)
				return new string[] {};

			List<string> objectFiles = new List<string> ();
			
			foreach (ProjectFile f in projectFiles) {
				if (f.BuildAction == BuildAction.Compile) {
					string PathName = Path.Combine(configuration.OutputDirectory, Path.GetFileNameWithoutExtension(f.Name) + ".o");

					if(File.Exists(PathName) == false)
						continue;
					
					if (!withQuotes)
						objectFiles.Add (PathName);
					else
						objectFiles.Add ("\"" + PathName + "\"");
				}
			}
			
			return objectFiles.ToArray ();
		}
		
		public override void Clean (ProjectFileCollection projectFiles, CProjectConfiguration configuration, IProgressMonitor monitor)
		{
			//clean up object files
			foreach (string oFile in ObjectFiles(projectFiles, configuration, false)) {
				if (File.Exists (oFile))
					File.Delete (oFile);
				
				string dFile = Path.ChangeExtension (oFile, ".d");
				if (File.Exists (dFile))
					File.Delete (dFile);
			}
			
			CleanPrecompiledHeaders (configuration);
		}
		
		void CleanPrecompiledHeaders (CProjectConfiguration configuration)
		{
			if (string.IsNullOrEmpty (configuration.IntermediateOutputDirectory))
			    return;
			
			string precDir = Path.Combine (configuration.IntermediateOutputDirectory, "prec");			

			if (Directory.Exists (precDir))
				Directory.Delete (precDir, true);
		}
		
		private bool NeedsUpdate (ProjectFileCollection projectFiles, CProjectConfiguration configuration, string target)
		{
			if (!File.Exists (target))
				return true;
			
			foreach (string obj in ObjectFiles (projectFiles, configuration, false))
				if (File.GetLastWriteTime (obj) > File.GetLastWriteTime (target))
					return true;
			
			return false;
		}
		
		protected override void ParseCompilerOutput (string errorString, CompilerResults cr)
		{
			TextReader reader = new StringReader (errorString);
			string next;
				
			while ((next = reader.ReadLine ()) != null) {
				CompilerError error = CreateErrorFromErrorString (next, reader);
				if (error != null)
					cr.Errors.Add (error);
			}
			
			reader.Close ();
		}
		
		private static Regex withColRegex = new Regex (
		    @"^\s*(?<file>.*):(?<line>\d*):(?<column>\d*):\s*(?<level>.*)\s*:\s(?<message>.*)",
		    RegexOptions.Compiled | RegexOptions.ExplicitCapture);
		private static Regex noColRegex = new Regex (
		    @"^\s*(?<file>.*):(?<line>\d*):\s*(?<level>.*)\s*:\s(?<message>.*)",
		    RegexOptions.Compiled | RegexOptions.ExplicitCapture);
		private static Regex linkerRegex = new Regex (
		    @"^\s*(?<file>[^:]*):(?<line>\d*):\s*(?<message>.*)",
		    RegexOptions.Compiled | RegexOptions.ExplicitCapture);
		
		private CompilerError CreateErrorFromErrorString (string errorString, TextReader reader)
		{
			CompilerError error = new CompilerError ();
			string warning = GettextCatalog.GetString ("warning");
			string note = GettextCatalog.GetString ("note");
			
			Match match = withColRegex.Match (errorString);
			
			if (match.Success)
			{
				error.FileName = match.Groups["file"].Value;
				error.Line = int.Parse (match.Groups["line"].Value);
				error.Column = int.Parse (match.Groups["column"].Value);
				error.IsWarning = (match.Groups["level"].Value.Equals (warning, StringComparison.Ordinal) ||
				                   match.Groups["level"].Value.Equals (note, StringComparison.Ordinal));
				error.ErrorText = match.Groups["message"].Value;
				
				return error;
			}
			
			match = noColRegex.Match (errorString);
			
			if (match.Success)
			{
				error.FileName = match.Groups["file"].Value;
				error.Line = int.Parse (match.Groups["line"].Value);
				error.IsWarning = (match.Groups["level"].Value.Equals (warning, StringComparison.Ordinal) ||
				                   match.Groups["level"].Value.Equals (note, StringComparison.Ordinal));
				error.ErrorText = match.Groups["message"].Value;
				
				// Skip messages that begin with ( and end with ), since they're generic.
				//Attempt to capture multi-line versions too.
				if (error.ErrorText.StartsWith ("(")) {
					string error_continued = error.ErrorText;
					do {
						if (error_continued.EndsWith (")"))
							return null;
					} while ((error_continued = reader.ReadLine ()) != null);
				}
				
				return error;
			}
			
			return null;
		}
		
		protected override void ParseLinkerOutput (string errorString, CompilerResults cr)
		{
			TextReader reader = new StringReader (errorString);
			string next;
			
			while ((next = reader.ReadLine ()) != null) {
				CompilerError error = CreateLinkerErrorFromErrorString (next);
				if (error != null)
					cr.Errors.Insert (0, error);
			}
			
			reader.Close ();
		}
		
		private CompilerError CreateLinkerErrorFromErrorString (string errorString)
		{
			CompilerError error = new CompilerError ();
			
			Match linkerMatch = linkerRegex.Match (errorString);
			
			if (linkerMatch.Success)
			{
				error.FileName = linkerMatch.Groups["file"].Value;
				error.Line = int.Parse (linkerMatch.Groups["line"].Value);
				error.ErrorText = linkerMatch.Groups["message"].Value;
				
				return error;
			}
			
			return null;
		}

		// expands backticked portions of the parameter-list using "sh" and "echo"
		// TODO: Do this ourselves, relying on sh/echo - and launching an entire process just for this is ... excessive.
		public string ExpandBacktickedParameters (string tmp)
		{
			// 1) Quadruple \ required, to escape both echo's and sh's escape character filtering
			// 2) \\\" required inside of echo, to translate into \" in sh, so it translates back as a " to MD...
			string parameters = "-c \"echo " + tmp.Replace("\\", "\\\\\\\\").Replace("\"", "\\\\\\\"") + "\"";

			var p = Process.Start (new ProcessStartInfo ("sh", parameters) {
				UseShellExecute = false,
				RedirectStandardOutput = true
			});
			p.Start ();
			p.WaitForExit ();

			//TODO: use async reads so we don't deadlock if stdout fills up
			//TODO: check return code
			return p.StandardOutput.ReadToEnd ().Trim ();
		}
		
		bool CheckApp (string app)
		{
			try {
				ProcessWrapper p = Runtime.ProcessService.StartProcess (app, "--version", null, null);
				p.WaitForOutput ();
				return true;
			} catch {
				return false;
			}
		}
		
		/// <summary>
		/// Checks a compilation return code, 
		/// and adds an error result if the compiler results
		/// show no errors.
		/// </summary>
		/// <param name="returnCode">
		/// A <see cref="System.Int32"/>: A process return code
		/// </param>
		/// <param name="cr">
		/// A <see cref="CompilerResults"/>: The return code from a compilation run
		/// </param>
		void CheckReturnCode (int returnCode, CompilerResults cr)
		{
			cr.NativeCompilerReturnValue = returnCode;
			if (0 != returnCode && 0 == cr.Errors.Count) { 
				cr.Errors.Add (new CompilerError (string.Empty, 0, 0, string.Empty,
				                                  GettextCatalog.GetString ("Build failed - check build output for details")));
			}
		}
	}
}