Add support for ToolsVersion and correctly build msbuild+xbuild assemblies
[mono.git] / mcs / class / Microsoft.Build.Engine / Microsoft.Build.BuildEngine / Project.cs
index 2e73f5a8ae821be51a3ef3ed4525ba423b895e52..a103b762a177da64651c6379b30f040ec0b987f7 100644 (file)
@@ -32,11 +32,13 @@ using System.Collections;
 using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.IO;
+using System.Reflection;
 using System.Text;
 using System.Xml;
 using System.Xml.Schema;
 using Microsoft.Build.Framework;
 using Mono.XBuild.Framework;
+using Mono.XBuild.CommandLine;
 
 namespace Microsoft.Build.BuildEngine {
        public class Project {
@@ -58,7 +60,7 @@ namespace Microsoft.Build.BuildEngine {
                bool                            isValidated;
                BuildItemGroupCollection        itemGroups;
                ImportCollection                imports;
-               string                          initialTargets;
+               List<string>                    initialTargets;
                Dictionary <string, BuildItemGroup> last_item_group_containing;
                bool                            needToReevaluate;
                Engine                          parentEngine;
@@ -70,7 +72,15 @@ namespace Microsoft.Build.BuildEngine {
                UsingTaskCollection             usingTasks;
                XmlDocument                     xmlDocument;
                bool                            unloaded;
+               bool                            initialTargetsBuilt;
+               List<string>                    builtTargetKeys;
+               bool                            building;
+               BuildSettings                   current_settings;
+               Stack<Batch>                    batches;
+               ProjectLoadSettings             project_load_settings;
 
+
+               static string extensions_path;
                static XmlNamespaceManager      manager;
                static string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
 
@@ -79,9 +89,14 @@ namespace Microsoft.Build.BuildEngine {
                {
                }
 
-               public Project (Engine engine)
+               public Project (Engine engine) : this (engine, null)
+               {
+               }
+               
+               public Project (Engine engine, string toolsVersion)
                {
                        parentEngine  = engine;
+                       ToolsVersion = toolsVersion;
 
                        buildEnabled = ParentEngine.BuildEnabled;
                        xmlDocument = new XmlDocument ();
@@ -90,12 +105,23 @@ namespace Microsoft.Build.BuildEngine {
                        xmlDocument.DocumentElement.SetAttribute ("xmlns", ns);
                        
                        fullFileName = String.Empty;
+                       timeOfLastDirty = DateTime.Now;
+                       current_settings = BuildSettings.None;
+                       project_load_settings = ProjectLoadSettings.None;
+
+                       encoding = null;
+
+                       builtTargetKeys = new List<string> ();
+                       initialTargets = new List<string> ();
+                       defaultTargets = new string [0];
+                       batches = new Stack<Batch> ();
 
                        globalProperties = new BuildPropertyGroup (null, this, null, false);
                        foreach (BuildProperty bp in parentEngine.GlobalProperties)
                                GlobalProperties.AddProperty (bp.Clone (true));
                        
                        ProcessXml ();
+
                }
 
                [MonoTODO ("Not tested")]
@@ -227,8 +253,9 @@ namespace Microsoft.Build.BuildEngine {
                public bool Build (string targetName)
                {
                        if (targetName == null)
-                               return false;
-                       return Build (new string [1] { targetName });
+                               return Build ((string[]) null);
+                       else
+                               return Build (new string [1] { targetName });
                }
                
                [MonoTODO ("Not tested")]
@@ -250,14 +277,34 @@ namespace Microsoft.Build.BuildEngine {
                                   BuildSettings buildFlags)
                
                {
-                       if (targetNames == null)
-                               return false;
+                       bool result = false;
+                       ParentEngine.StartProjectBuild (this, targetNames);
+                       string current_directory = Environment.CurrentDirectory;
+                       try {
+                               current_settings = buildFlags;
+                               if (!String.IsNullOrEmpty (fullFileName))
+                                       Directory.SetCurrentDirectory (Path.GetDirectoryName (fullFileName));
+                               building = true;
+                               result = BuildInternal (targetNames, targetOutputs, buildFlags);
+                       } finally {
+                               ParentEngine.EndProjectBuild (this, result);
+                               current_settings = BuildSettings.None;
+                               Directory.SetCurrentDirectory (current_directory);
+                               building = false;
+                       }
+
+                       return result;
+               }
 
+               bool BuildInternal (string [] targetNames,
+                                  IDictionary targetOutputs,
+                                  BuildSettings buildFlags)
+               {
                        CheckUnloaded ();
-                       ParentEngine.StartBuild ();
-                       NeedToReevaluate ();
+                       if (buildFlags == BuildSettings.None)
+                               Reevaluate ();
                        
-                       if (targetNames.Length == 0) {
+                       if (targetNames == null || targetNames.Length == 0) {
                                if (defaultTargets != null && defaultTargets.Length != 0)
                                        targetNames = defaultTargets;
                                else if (firstTargetName != null)
@@ -265,25 +312,58 @@ namespace Microsoft.Build.BuildEngine {
                                else
                                        return false;
                        }
-                       
-                       foreach (string target in targetNames) {
-                               if (target == null)
-                                       throw new ArgumentException ("targetNames cannot contain null strings");
 
-                               if (!targets.Exists (target))
-                                       // FIXME: test if it's logged
+                       if (!initialTargetsBuilt) {
+                               foreach (string target in initialTargets) {
+                                       if (!BuildTarget (target.Trim (), targetOutputs))
+                                               return false;
+                               }
+                               initialTargetsBuilt = true;
+                       }
+
+                       foreach (string target in targetNames)
+                               if (!BuildTarget (target.Trim (), targetOutputs))
                                        return false;
                                
-                               if (!targets [target].Build ())
-                                       return false;
+                       return true;
+               }
+
+               bool BuildTarget (string target_name, IDictionary targetOutputs)
+               {
+                       if (target_name == null)
+                               throw new ArgumentException ("targetNames cannot contain null strings");
 
+                       if (!targets.Exists (target_name)) {
+                               LogError (fullFileName, "Target named '{0}' not found in the project.", target_name);
+                               return false;
+                       }
+
+                       string key = GetKeyForTarget (target_name);
+                       if (!targets [target_name].Build (key))
+                               return false;
+
+                       ITaskItem[] outputs;
+                       if (ParentEngine.BuiltTargetsOutputByName.TryGetValue (key, out outputs)) {
                                if (targetOutputs != null)
-                                       targetOutputs.Add (target, targets [target].Outputs);
+                                       targetOutputs.Add (target_name, outputs);
                        }
-                               
                        return true;
                }
 
+               internal string GetKeyForTarget (string target_name)
+               {
+                       // target name is case insensitive
+                       return fullFileName + ":" + target_name.ToLower () + ":" + GlobalPropertiesToString (GlobalProperties);
+               }
+
+               string GlobalPropertiesToString (BuildPropertyGroup bgp)
+               {
+                       StringBuilder sb = new StringBuilder ();
+                       foreach (BuildProperty bp in bgp)
+                               sb.AppendFormat (" {0}:{1}", bp.Name, bp.FinalValue);
+                       return sb.ToString ();
+               }
+
                [MonoTODO]
                public string [] GetConditionedPropertyValues (string propertyName)
                {
@@ -303,7 +383,7 @@ namespace Microsoft.Build.BuildEngine {
                        if (evaluatedItemsByName.ContainsKey (itemName))
                                return evaluatedItemsByName [itemName];
                        else
-                               return new BuildItemGroup ();
+                               return new BuildItemGroup (this);
                }
 
                public BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition (string itemName)
@@ -316,7 +396,7 @@ namespace Microsoft.Build.BuildEngine {
                        if (evaluatedItemsByNameIgnoringCondition.ContainsKey (itemName))
                                return evaluatedItemsByNameIgnoringCondition [itemName];
                        else
-                               return new BuildItemGroup ();
+                               return new BuildItemGroup (this);
                }
 
                public string GetEvaluatedProperty (string propertyName)
@@ -351,19 +431,63 @@ namespace Microsoft.Build.BuildEngine {
 
                public void Load (string projectFileName)
                {
-                       this.fullFileName = Path.GetFullPath (projectFileName);
-                       DoLoad (new StreamReader (projectFileName));
+                       Load (projectFileName, ProjectLoadSettings.None);
+               }
+
+               public void Load (string projectFileName, ProjectLoadSettings settings)
+               {
+                       project_load_settings = settings;
+                       if (String.IsNullOrEmpty (projectFileName))
+                               throw new ArgumentNullException ("projectFileName");
+
+                       if (!File.Exists (projectFileName))
+                               throw new ArgumentException (String.Format ("Project file {0} not found", projectFileName),
+                                               "projectFileName");
+
+                       this.fullFileName = Utilities.FromMSBuildPath (Path.GetFullPath (projectFileName));
+
+                       string filename = fullFileName;
+                       if (String.Compare (Path.GetExtension (fullFileName), ".sln", true) == 0) {
+                               Project tmp_project = ParentEngine.CreateNewProject ();
+                               SolutionParser sln_parser = new SolutionParser ();
+                               sln_parser.ParseSolution (fullFileName, tmp_project, delegate (int errorNumber, string message) {
+                                               LogWarning (filename, message);
+                                       });
+                               filename = fullFileName + ".proj";
+                               try {
+                                       tmp_project.Save (filename);
+                                       ParentEngine.RemoveLoadedProject (tmp_project);
+                                       DoLoad (new StreamReader (filename));
+                               } finally {
+                                       if (Environment.GetEnvironmentVariable ("XBUILD_EMIT_SOLUTION") == null)
+                                               File.Delete (filename);
+                               }
+                       } else {
+                               DoLoad (new StreamReader (filename));
+                       }
                }
                
                [MonoTODO ("Not tested")]
                public void Load (TextReader textReader)
                {
+                       Load (textReader, ProjectLoadSettings.None);
+               }
+
+               public void Load (TextReader textReader, ProjectLoadSettings projectLoadSettings)
+               {
+                       project_load_settings = projectLoadSettings;
                        fullFileName = String.Empty;
                        DoLoad (textReader);
                }
 
                public void LoadXml (string projectXml)
                {
+                       LoadXml (projectXml, ProjectLoadSettings.None);
+               }
+
+               public void LoadXml (string projectXml, ProjectLoadSettings projectLoadSettings)
+               {
+                       project_load_settings = projectLoadSettings;
                        fullFileName = String.Empty;
                        DoLoad (new StringReader (projectXml));
                        MarkProjectAsDirty ();
@@ -410,7 +534,7 @@ namespace Microsoft.Build.BuildEngine {
                        if (itemToRemove == null)
                                throw new ArgumentNullException ("itemToRemove");
 
-                       if (!itemToRemove.FromXml && !itemToRemove.HasParent)
+                       if (!itemToRemove.FromXml && !itemToRemove.HasParentItem)
                                throw new InvalidOperationException ("The object passed in is not part of the project.");
 
                        BuildItemGroup big = itemToRemove.ParentItemGroup;
@@ -478,7 +602,10 @@ namespace Microsoft.Build.BuildEngine {
                [MonoTODO]
                public void ResetBuildStatus ()
                {
-                       throw new NotImplementedException ();
+                       // hack to allow built targets to be removed
+                       building = true;
+                       Reevaluate ();
+                       building = false;
                }
 
                public void Save (string projectFileName)
@@ -619,16 +746,19 @@ namespace Microsoft.Build.BuildEngine {
                        try {
                                ParentEngine.RemoveLoadedProject (this);
        
-                               XmlReaderSettings settings = new XmlReaderSettings ();
-       
+                               xmlDocument.Load (textReader);
+
+                               if (xmlDocument.DocumentElement.Name == "VisualStudioProject")
+                                       throw new InvalidProjectFileException (String.Format (
+                                                       "Project file '{0}' is a VS2003 project, which is not " +
+                                                       "supported by xbuild. You need to convert it to msbuild " +
+                                                       "format to build with xbuild.", fullFileName));
+
                                if (SchemaFile != null) {
-                                       settings.Schemas.Add (null, SchemaFile);
-                                       settings.ValidationType = ValidationType.Schema;
-                                       settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
+                                       xmlDocument.Schemas.Add (XmlSchema.Read (
+                                                               new StreamReader (SchemaFile), ValidationCallBack));
+                                       xmlDocument.Validate (ValidationCallBack);
                                }
-       
-                               XmlReader xmlReader = XmlReader.Create (textReader, settings);
-                               xmlDocument.Load (xmlReader);
 
                                if (xmlDocument.DocumentElement.Name != "Project") {
                                        throw new InvalidProjectFileException (String.Format (
@@ -645,9 +775,11 @@ namespace Microsoft.Build.BuildEngine {
                                ProcessXml ();
                                ParentEngine.AddLoadedProject (this);
                        } catch (Exception e) {
-                               throw new InvalidProjectFileException (e.Message, e);
+                               throw new InvalidProjectFileException (String.Format ("{0}: {1}",
+                                                       fullFileName, e.Message), e);
                        } finally {
-                               textReader.Close ();
+                               if (textReader != null)
+                                       textReader.Close ();
                        }
                }
 
@@ -667,22 +799,41 @@ namespace Microsoft.Build.BuildEngine {
                        last_item_group_containing = new Dictionary <string, BuildItemGroup> ();
                        
                        taskDatabase = new TaskDatabase ();
-                       if (ParentEngine.DefaultTasksRegistered)
-                               taskDatabase.CopyTasks (ParentEngine.DefaultTasks);     
+                       taskDatabase.CopyTasks (ParentEngine.GetDefaultTasks (GetToolsVersionToUse ()));
 
-                       if (xmlDocument.DocumentElement.GetAttributeNode ("DefaultTargets") != null)
-                               defaultTargets = xmlDocument.DocumentElement.GetAttribute ("DefaultTargets").Split (';');
-                       else
-                               defaultTargets = new string [0];
-                       
+                       initialTargets = new List<string> ();
+                       defaultTargets = new string [0];
+                       PrepareForEvaluate ();
                        ProcessElements (xmlDocument.DocumentElement, null);
                        
                        isDirty = false;
                        Evaluate ();
                }
-               
+
+               void ProcessProjectAttributes (XmlAttributeCollection attributes)
+               {
+                       foreach (XmlAttribute attr in attributes) {
+                               switch (attr.Name) {
+                               case "InitialTargets":
+                                       initialTargets.AddRange (attr.Value.Split (
+                                                                       new char [] {';', ' '},
+                                                                       StringSplitOptions.RemoveEmptyEntries));
+                                       break;
+                               case "DefaultTargets":
+                                       // first non-empty DefaultTargets found is used
+                                       if (defaultTargets == null || defaultTargets.Length == 0)
+                                               defaultTargets = attr.Value.Split (new char [] {';', ' '},
+                                                       StringSplitOptions.RemoveEmptyEntries);
+                                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets",
+                                                               DefaultTargets, PropertyType.Reserved));
+                                       break;
+                               }
+                       }
+               }
+
                internal void ProcessElements (XmlElement rootElement, ImportedProject ip)
                {
+                       ProcessProjectAttributes (rootElement.Attributes);
                        foreach (XmlNode xn in rootElement.ChildNodes) {
                                if (xn is XmlElement) {
                                        XmlElement xe = (XmlElement) xn;
@@ -714,22 +865,26 @@ namespace Microsoft.Build.BuildEngine {
                                                AddChoose (xe);
                                                break;
                                        default:
-                                               throw new InvalidProjectFileException ("Invalid element in project file.");
+                                               throw new InvalidProjectFileException (String.Format ("Invalid element '{0}' in project file.", xe.Name));
                                        }
                                }
                        }
                }
                
-               void Evaluate ()
+               void PrepareForEvaluate ()
                {
                        evaluatedItems = new BuildItemGroup (null, this, null, true);
                        evaluatedItemsIgnoringCondition = new BuildItemGroup (null, this, null, true);
                        evaluatedItemsByName = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
                        evaluatedItemsByNameIgnoringCondition = new Dictionary <string, BuildItemGroup> (StringComparer.InvariantCultureIgnoreCase);
-                       evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
+                       if (building && current_settings == BuildSettings.None)
+                               RemoveBuiltTargets ();
 
                        InitializeProperties ();
+               }
 
+               void Evaluate ()
+               {
                        groupingCollection.Evaluate ();
 
                        //FIXME: UsingTasks aren't really evaluated. (shouldn't use expressions or anything)
@@ -737,21 +892,56 @@ namespace Microsoft.Build.BuildEngine {
                                usingTask.Evaluate ();
                }
 
+               // Removes entries of all earlier built targets for this project
+               void RemoveBuiltTargets ()
+               {
+                       foreach (string key in builtTargetKeys)
+                               ParentEngine.BuiltTargetsOutputByName.Remove (key);
+               }
+
                void InitializeProperties ()
                {
                        BuildProperty bp;
 
+                       evaluatedProperties = new BuildPropertyGroup (null, null, null, true);
+
                        foreach (BuildProperty gp in GlobalProperties) {
                                bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
                                EvaluatedProperties.AddProperty (bp);
                        }
                        
+                       foreach (BuildProperty gp in GlobalProperties)
+                               ParentEngine.GlobalProperties.AddProperty (gp);
+
+                       // add properties that we dont have from parent engine's
+                       // global properties
+                       foreach (BuildProperty gp in ParentEngine.GlobalProperties) {
+                               if (EvaluatedProperties [gp.Name] == null) {
+                                       bp = new BuildProperty (gp.Name, gp.Value, PropertyType.Global);
+                                       EvaluatedProperties.AddProperty (bp);
+                               }
+                       }
+
                        foreach (DictionaryEntry de in Environment.GetEnvironmentVariables ()) {
                                bp = new BuildProperty ((string) de.Key, (string) de.Value, PropertyType.Environment);
                                EvaluatedProperties.AddProperty (bp);
                        }
 
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectFile", Path.GetFileName (fullFileName),
+                                               PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectName",
+                                               Path.GetFileNameWithoutExtension (fullFileName),
+                                               PropertyType.Reserved));
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildBinPath", parentEngine.BinPath, PropertyType.Reserved));
+                       string toolsVersionToUse = GetToolsVersionToUse ();
+                       string toolsPath = parentEngine.Toolsets [toolsVersionToUse].ToolsPath;
+                       if (toolsPath == null)
+                               throw new Exception ("Unknown toolsVersion: " + toolsVersionToUse);
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsPath", toolsPath, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildToolsVersion", toolsVersionToUse, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildExtensionsPath", ExtensionsPath, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDefaultTargets", DefaultTargets, PropertyType.Reserved));
+                       EvaluatedProperties.AddProperty (new BuildProperty ("OS", OS, PropertyType.Environment));
 
                        // FIXME: make some internal method that will work like GetDirectoryName but output String.Empty on null/String.Empty
                        string projectDir;
@@ -762,6 +952,18 @@ namespace Microsoft.Build.BuildEngine {
 
                        EvaluatedProperties.AddProperty (new BuildProperty ("MSBuildProjectDirectory", projectDir, PropertyType.Reserved));
                }
+
+               string GetToolsVersionToUse ()
+               {
+                       if (String.IsNullOrEmpty (ToolsVersion)) {
+                               if (HasToolsVersionAttribute)
+                                       return DefaultToolsVersion;
+                               else
+                                       return parentEngine.DefaultToolsVersion;
+                       } else {
+                               return ToolsVersion;
+                       }
+               }
                
                void AddProjectExtensions (XmlElement xmlElement)
                {
@@ -790,10 +992,32 @@ namespace Microsoft.Build.BuildEngine {
                
                void AddImport (XmlElement xmlElement, ImportedProject importingProject)
                {
-                       Import import;
-                       
-                       import = new Import (xmlElement, this, importingProject);
+                       // eval all the properties etc till the import
+                       groupingCollection.Evaluate (EvaluationType.Property);
+
+                       Import import = new Import (xmlElement, this, importingProject);
+                       if (!ConditionParser.ParseAndEvaluate (import.Condition, this))
+                               return;
+
+                       if (Imports.Contains (import)) {
+                               LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
+                                               "A circular reference was found involving the import of {0}. Only" +
+                                               " the first import of this file will be used, ignoring others.",
+                                               import.ProjectPath);
+
+                               return;
+                       }
+
+                       if (String.Compare (fullFileName, import.EvaluatedProjectPath) == 0) {
+                               LogWarning (importingProject != null ? importingProject.FullFileName : fullFileName,
+                                               "The main project file was imported here, which creates a circular " +
+                                               "reference. Ignoring this import.");
+
+                               return;
+                       }
+
                        Imports.Add (import);
+                       import.Evaluate (project_load_settings == ProjectLoadSettings.IgnoreMissingImports);
                }
                
                void AddItemGroup (XmlElement xmlElement, ImportedProject importedProject)
@@ -835,11 +1059,13 @@ namespace Microsoft.Build.BuildEngine {
 
                public string DefaultTargets {
                        get {
-                               return xmlDocument.DocumentElement.GetAttribute ("DefaultTargets");
+                               return String.Join ("; ", defaultTargets);
                        }
                        set {
                                xmlDocument.DocumentElement.SetAttribute ("DefaultTargets", value);
-                               defaultTargets = value.Split (';');
+                               if (value != null)
+                                       defaultTargets = value.Split (new char [] {';', ' '},
+                                                       StringSplitOptions.RemoveEmptyEntries);
                        }
                }
 
@@ -889,7 +1115,39 @@ namespace Microsoft.Build.BuildEngine {
                Dictionary<string, BuildItemGroup> perBatchItemsByName;
                Dictionary<string, BuildItemGroup> commonItemsByName;
 
-               internal void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
+               struct Batch {
+                       public Dictionary<string, BuildItemGroup> perBatchItemsByName;
+                       public Dictionary<string, BuildItemGroup> commonItemsByName;
+
+                       public Batch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
+                       {
+                               this.perBatchItemsByName = perBatchItemsByName;
+                               this.commonItemsByName = commonItemsByName;
+                       }
+               }
+
+               Stack<Batch> Batches {
+                       get { return batches; }
+               }
+
+               internal void PushBatch (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
+               {
+                       batches.Push (new Batch (perBatchItemsByName, commonItemsByName));
+                       SetBatchedItems (perBatchItemsByName, commonItemsByName);
+               }
+
+               internal void PopBatch ()
+               {
+                       batches.Pop ();
+                       if (batches.Count > 0) {
+                               Batch b = batches.Peek ();
+                               SetBatchedItems (b.perBatchItemsByName, b.commonItemsByName);
+                       } else {
+                               SetBatchedItems (null, null);
+                       }
+               }
+
+               void SetBatchedItems (Dictionary<string, BuildItemGroup> perBatchItemsByName, Dictionary<string, BuildItemGroup> commonItemsByName)
                {
                        this.perBatchItemsByName = perBatchItemsByName;
                        this.commonItemsByName = commonItemsByName;
@@ -898,17 +1156,14 @@ namespace Microsoft.Build.BuildEngine {
                // Honors batching
                internal bool TryGetEvaluatedItemByNameBatched (string itemName, out BuildItemGroup group)
                {
-                       if (perBatchItemsByName == null && commonItemsByName == null)
-                               return EvaluatedItemsByName.TryGetValue (itemName, out group);
-
-                       if (perBatchItemsByName != null)
-                               return perBatchItemsByName.TryGetValue (itemName, out group);
+                       if (perBatchItemsByName != null && perBatchItemsByName.TryGetValue (itemName, out group))
+                               return true;
 
-                       if (commonItemsByName != null)
-                               return commonItemsByName.TryGetValue (itemName, out group);
+                       if (commonItemsByName != null && commonItemsByName.TryGetValue (itemName, out group))
+                               return true;
 
                        group = null;
-                       return false;
+                       return EvaluatedItemsByName.TryGetValue (itemName, out group);
                }
 
                internal string GetMetadataBatched (string itemName, string metadataName)
@@ -928,7 +1183,7 @@ namespace Microsoft.Build.BuildEngine {
                        if (group != null) {
                                foreach (BuildItem item in group) {
                                        if (item.HasMetadata (metadataName))
-                                               return item.GetMetadata (metadataName);
+                                               return item.GetEvaluatedMetadata (metadataName);
                                }
                        }
                        return String.Empty;
@@ -960,6 +1215,41 @@ namespace Microsoft.Build.BuildEngine {
                        return default (T);
                }
 
+               internal void LogWarning (string filename, string message, params object[] messageArgs)
+               {
+                       BuildWarningEventArgs bwea = new BuildWarningEventArgs (
+                               null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
+                               null, null);
+                       ParentEngine.EventSource.FireWarningRaised (this, bwea);
+               }
+
+               internal void LogError (string filename, string message,
+                                    params object[] messageArgs)
+               {
+                       BuildErrorEventArgs beea = new BuildErrorEventArgs (
+                               null, null, filename, 0, 0, 0, 0, String.Format (message, messageArgs),
+                               null, null);
+                       ParentEngine.EventSource.FireErrorRaised (this, beea);
+               }
+
+               static string ExtensionsPath {
+                       get {
+                               if (extensions_path == null) {
+                                       // NOTE: code from mcs/tools/gacutil/driver.cs
+                                       PropertyInfo gac = typeof (System.Environment).GetProperty (
+                                                       "GacPath", BindingFlags.Static | BindingFlags.NonPublic);
+
+                                       if (gac != null) {
+                                               MethodInfo get_gac = gac.GetGetMethod (true);
+                                               string gac_path = (string) get_gac.Invoke (null, null);
+                                               extensions_path = Path.GetFullPath (Path.Combine (
+                                                                       gac_path, Path.Combine ("..", "xbuild")));
+                                       }
+                               }
+                               return extensions_path;
+                       }
+               }
+
                public BuildPropertyGroup EvaluatedProperties {
                        get {
                                if (needToReevaluate) {
@@ -985,7 +1275,6 @@ namespace Microsoft.Build.BuildEngine {
                                        throw new InvalidOperationException ("GlobalProperties can not be set to persisted property group.");
                                
                                globalProperties = value;
-                               NeedToReevaluate ();
                        }
                }
 
@@ -1007,8 +1296,16 @@ namespace Microsoft.Build.BuildEngine {
                }
                
                public string InitialTargets {
-                       get { return initialTargets; }
-                       set { initialTargets = value; }
+                       get {
+                               return String.Join ("; ", initialTargets.ToArray ());
+                       }
+                       set {
+                               initialTargets.Clear ();
+                               xmlDocument.DocumentElement.SetAttribute ("InitialTargets", value);
+                               if (value != null)
+                                       initialTargets.AddRange (value.Split (
+                                                               new char [] {';', ' '}, StringSplitOptions.RemoveEmptyEntries));
+                       }
                }
 
                public Engine ParentEngine {
@@ -1041,6 +1338,33 @@ namespace Microsoft.Build.BuildEngine {
                        get { return xmlDocument.InnerXml; }
                }
 
+               // corresponds to the xml attribute
+               public string DefaultToolsVersion {
+                       get {
+                               if (xmlDocument != null)
+                                       return xmlDocument.DocumentElement.GetAttribute ("ToolsVersion");
+                               return null;
+                       }
+                       set {
+                               if (xmlDocument != null)
+                                       xmlDocument.DocumentElement.SetAttribute ("ToolsVersion", value);
+                       }
+               }
+
+               public bool HasToolsVersionAttribute {
+                       get {
+                               return xmlDocument != null && xmlDocument.DocumentElement.HasAttribute ("ToolsVersion");
+                       }
+               }
+               
+               public string ToolsVersion {
+                       get; internal set;
+               }
+
+               internal List<string> BuiltTargetKeys {
+                       get { return builtTargetKeys; }
+               }
+
                internal Dictionary <string, BuildItemGroup> LastItemGroupContaining {
                        get { return last_item_group_containing; }
                }
@@ -1067,6 +1391,22 @@ namespace Microsoft.Build.BuildEngine {
                internal static string XmlNamespace {
                        get { return ns; }
                }
+
+               static string OS {
+                       get {
+                               PlatformID pid = Environment.OSVersion.Platform;
+                               switch ((int)pid) {
+                               case 128:
+                               case 4:
+                                       return "Unix";
+                               case 6:
+                                       return "OSX";
+                               default:
+                                       return "Windows_NT";
+                               }
+                       }
+               }
+
        }
 }