Integrate changes from SD between [SD:715912] and [SD:717473]

This commit is contained in:
PowerShell Team
2016-06-22 06:24:08 -07:00
committed by Sergei Vorobev
parent dfea5de391
commit 207d2b3195
23 changed files with 279 additions and 259 deletions
@@ -463,10 +463,6 @@ namespace Microsoft.PowerShell
if (!noexitSeen)
showBanner = false;
// Exit on script completion unless -noexit was specified...
if (!noexitSeen)
noExit = false;
// Process interactive input...
if (args[i] == "-")
{
@@ -477,6 +473,10 @@ namespace Microsoft.PowerShell
}
else
{
// Exit on script completion unless -noexit was specified...
if (!noexitSeen)
noExit = false;
// We need to get the full path to the script because it will be
// executed after the profiles are run and they may change the current
// directory.
@@ -877,10 +877,9 @@ namespace Microsoft.PowerShell
commandLineCommand = cmdLineCmdSB.ToString();
}
if (!noexitSeen)
if (!noexitSeen && !explicitReadCommandsFromStdin)
{
// don't reset this if they've already specified -noexit
noExit = false;
}
@@ -1360,7 +1360,7 @@ namespace Microsoft.PowerShell
inputFormat = cpp.InputFormat;
wasInitialCommandEncoded = cpp.WasInitialCommandEncoded;
ui.ReadFromStdin = cpp.ExplicitReadCommandsFromStdin || (Console.IsInputRedirected && !cpp.NonInteractive);
ui.ReadFromStdin = cpp.ExplicitReadCommandsFromStdin || Console.IsInputRedirected;
ui.NoPrompt = cpp.NoPrompt;
ui.ThrowOnReadAndPrompt = cpp.ThrowOnReadAndPrompt;
noExit = cpp.NoExit;
@@ -1421,7 +1421,7 @@ namespace Microsoft.PowerShell
if (ExitCode == ExitCodeInitFailure) { break; }
if (!noExit && (!ui.ReadFromStdin || Console.In.Peek() == -1))
if (!noExit)
{
// Wait for runspace to open, init, and run init script before
// setting ShouldEndSession, to allow debugger to work.
@@ -2452,14 +2452,8 @@ namespace Microsoft.PowerShell
if (Console.IsInputRedirected)
{
// null is also the result of reading stdin to EOF.
if (!parent.noExit)
{
parent.ShouldEndSession = true;
break;
}
ui.ReadFromStdin = false;
parent.ShouldEndSession = true;
break;
}
continue;
@@ -233,7 +233,7 @@ namespace Microsoft.PowerShell.Commands
System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
this.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool(), this.Context.CurrentRunspace.InstanceId);
Host.UI.StartTranscribing(effectiveFilePath, psSenderInfo, IncludeInvocationHeader.ToBool());
// ch.StartTranscribing(effectiveFilePath, Append);
@@ -249,7 +249,7 @@ namespace Microsoft.PowerShell.Commands
{
try
{
Host.UI.StopTranscribing(this.Context.CurrentRunspace.InstanceId);
Host.UI.StopTranscribing();
}
catch
{
@@ -35,7 +35,7 @@ namespace Microsoft.PowerShell.Commands
{
try
{
string outFilename = Host.UI.StopTranscribing(this.Context.CurrentRunspace.InstanceId);
string outFilename = Host.UI.StopTranscribing();
if (outFilename != null)
{
PSObject outputObject = new PSObject(
@@ -698,6 +698,10 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
{
loadingInfo.isFullyTrusted = isFullyTrusted;
}
protected void SetLoadingInfoIsProductCode(bool isProductCode)
{
loadingInfo.isProductCode = isProductCode;
}
private DatabaseLoadingInfo loadingInfo = new DatabaseLoadingInfo ();
@@ -709,6 +713,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
info.filePath = loadingInfo.filePath;
info.fileDirectory = loadingInfo.fileDirectory;
info.isFullyTrusted = loadingInfo.isFullyTrusted;
info.isProductCode = loadingInfo.isProductCode;
return info;
}
}
@@ -53,6 +53,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
internal string fileDirectory = null;
internal string filePath = null;
internal bool isFullyTrusted = false;
internal bool isProductCode = false;
internal string xPath = null;
internal DateTime loadTime = DateTime.Now;
}
@@ -430,7 +430,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
// Loads formatting data from ExtendedTypeDefinition instance
if (file.FormatData != null)
{
LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isTrusted: false, isForHelp: false);
LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: false, isForHelp: false);
continue;
}
@@ -474,12 +474,12 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
ExtendedTypeDefinition formatData,
MshExpressionFactory expressionFactory, List<XmlLoaderLoggerEntry> logEntries, ref bool success,
PSSnapInTypeAndFormatErrors file, TypeInfoDataBase db,
bool isTrusted,
bool isBuiltInFormatData,
bool isForHelp)
{
using (TypeInfoDataBaseLoader loader = new TypeInfoDataBaseLoader())
{
if (!loader.LoadFormattingData(formatData, db, expressionFactory, isTrusted, isForHelp))
if (!loader.LoadFormattingData(formatData, db, expressionFactory, isBuiltInFormatData, isForHelp))
success = false;
foreach (XmlLoaderLoggerEntry entry in loader.LogEntries)
@@ -552,7 +552,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
{
foreach (var v in views)
{
LoadFormatDataHelper(v, expressionFactory, logEntries, ref success, file, db, isTrusted: true, isForHelp: isForHelp);
LoadFormatDataHelper(v, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: true, isForHelp: isForHelp);
}
}
@@ -210,6 +210,11 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
if (expressionFactory == null)
throw PSTraceSource.NewArgumentNullException ("expressionFactory");
if (SecuritySupport.IsProductBinary(info.filePath))
{
this.SetLoadingInfoIsProductCode(true);
}
this.displayResourceManagerCache = db.displayResourceManagerCache;
this.expressionFactory = expressionFactory;
@@ -276,14 +281,14 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
/// <param name="typeDefinition">the ExtendedTypeDefinition instance to load formatting data from</param>
/// <param name="db">database instance to load the formatting data into</param>
/// <param name="expressionFactory">expression factory to validate the script block</param>
/// <param name="isTrusted">do we implicitly trust the script blocks (so they should run in full langauge mode)?</param>
/// <param name="isBuiltInFormatData">do we implicitly trust the script blocks (so they should run in full langauge mode)?</param>
/// <param name="isForHelp">true when the view is for help output</param>
/// <returns></returns>
internal bool LoadFormattingData(
ExtendedTypeDefinition typeDefinition,
TypeInfoDataBase db,
MshExpressionFactory expressionFactory,
bool isTrusted,
bool isBuiltInFormatData,
bool isForHelp)
{
if (typeDefinition == null)
@@ -300,7 +305,8 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
try
{
this.SetLoadingInfoIsFullyTrusted(isTrusted);
this.SetLoadingInfoIsFullyTrusted(isBuiltInFormatData);
this.SetLoadingInfoIsProductCode(isBuiltInFormatData);
this.LoadData(typeDefinition, db, isForHelp);
}
catch (TooManyErrorsException)
@@ -666,11 +666,19 @@ namespace Microsoft.PowerShell.Commands.Internal.Format
_expressionCache = new Dictionary<ExpressionToken, MshExpression>();
}
bool isFullyTrusted = false;
bool isProductCode = false;
if (loadingInfo != null)
{
isFullyTrusted = loadingInfo.isFullyTrusted;
isProductCode = loadingInfo.isProductCode;
}
// no hit, we build one and we cache
ScriptBlock sb = ScriptBlock.CreateDelayParsedScriptBlock(et.expressionValue);
ScriptBlock sb = ScriptBlock.CreateDelayParsedScriptBlock(et.expressionValue, isProductCode: isProductCode);
sb.DebuggerStepThrough = true;
if ((loadingInfo != null) && loadingInfo.isFullyTrusted)
if (isFullyTrusted)
{
sb.LanguageMode = PSLanguageMode.FullLanguage;
}
@@ -29,7 +29,7 @@ namespace System.Management.Automation.Runspaces
static ScriptBlock GetScriptBlock(string s)
{
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s);
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s, isProductCode: true);
sb.LanguageMode = PSLanguageMode.FullLanguage;
return sb;
}
@@ -855,9 +855,9 @@ namespace System.Management.Automation.Runspaces
_helpFile = helpFile;
}
internal static SessionStateFunctionEntry GetDelayParsedFunctionEntry(string name, string definition)
internal static SessionStateFunctionEntry GetDelayParsedFunctionEntry(string name, string definition, bool isProductCode)
{
var sb = ScriptBlock.CreateDelayParsedScriptBlock(definition);
var sb = ScriptBlock.CreateDelayParsedScriptBlock(definition, isProductCode);
return new SessionStateFunctionEntry(name, definition, ScopedItemOptions.None,
SessionStateEntryVisibility.Public, sb, null);
}
@@ -5498,23 +5498,23 @@ if($paths) {
";
internal const string DefaultSetDriveFunctionText = "Set-Location $MyInvocation.MyCommand.Name";
internal static ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText);
internal static ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true);
internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[]
{
// Functions. Only the name and definitions are used
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", TabExpansionFunctionText),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", GetClearHostFunctionText()),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText, isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", TabExpansionFunctionText, isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", GetClearHostFunctionText(), isProductCode: true),
// Porting note: we keep more because the function acts correctly on Linux
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("more", DefaultMoreFunctionText),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("help", GetHelpPagingFunctionText()),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("more", DefaultMoreFunctionText, isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("help", GetHelpPagingFunctionText(), isProductCode: true),
// Porting note: we remove mkdir on Linux because it is a conflict
#if !LINUX
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("mkdir", GetMkdirFunctionText()),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("mkdir", GetMkdirFunctionText(), isProductCode: true),
#endif
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Get-Verb", GetGetVerbText()),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("oss", GetOSTFunctionText()),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Get-Verb", GetGetVerbText(), isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("oss", GetOSTFunctionText(), isProductCode: true),
// Porting note: we remove the drive functions from Linux because they make no sense
#if !LINUX
@@ -5547,12 +5547,12 @@ if($paths) {
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Z:", DefaultSetDriveFunctionText, SetDriveScriptBlock),
#endif
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location .."),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\"),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\", isProductCode: true),
// Win8: 320909. Retaining the original definition to ensure backward compatability.
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("ImportSystemModules", ImportSystemModulesText),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("ImportSystemModules", ImportSystemModulesText, isProductCode: true),
SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Pause",
string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString),"'"))
string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString),"'"), isProductCode: true)
};
static internal void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInternal ssi)
@@ -649,29 +649,40 @@ namespace System.Management.Automation
(cmdRuntime.LogPipelineExecutionDetail || isTranscribing) &&
(cmdRuntime.PipelineProcessor != null))
{
// Unroll parameter value
IEnumerable values = LanguagePrimitives.GetEnumerable(parameterValue);
if (values != null)
string stringToPrint = null;
try
{
var stringToPrint = string.Join(", ", values.Cast<object>().ToArray());
cmdRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName,
stringToPrint);
}
else
{
string stringToPrint = "";
if (parameterValue != null)
// Unroll parameter value
IEnumerable values = LanguagePrimitives.GetEnumerable(parameterValue);
if (values != null)
{
try
var sb = new Text.StringBuilder(256);
var sep = "";
foreach (var value in values)
{
stringToPrint = parameterValue.ToString();
}
catch (Exception e) // Catch-all OK, 3rd party callout
{
CommandProcessorBase.CheckForSevereException(e);
sb.Append(sep);
sep = ", ";
sb.Append(value);
// For better performance, avoid logging too much
if (sb.Length > 256)
{
sb.Append(", ...");
break;
}
}
stringToPrint = sb.ToString();
}
else if (parameterValue != null)
{
stringToPrint = parameterValue.ToString();
}
}
catch (Exception e) // Catch-all OK, 3rd party callout
{
CommandProcessorBase.CheckForSevereException(e);
}
if (stringToPrint != null)
{
cmdRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, stringToPrint);
}
}
@@ -165,7 +165,9 @@ namespace System.Management.Automation.Runspaces
ScriptBlock scriptBlock;
try
{
scriptBlock = ScriptBlock.Create(text);
scriptBlock = _context.IsProductCode
? ScriptBlock.CreateDelayParsedScriptBlock(text, isProductCode: true)
: ScriptBlock.Create(text);
}
catch (ParseException pe)
{
@@ -1483,6 +1485,8 @@ namespace System.Management.Automation.Runspaces
set { isFullyTrusted = value; }
}
internal bool IsProductCode { get; set; }
internal void AddError(string resourceString, params object[] formatArguments)
{
string errorMsg = StringUtil.Format(resourceString, formatArguments);
@@ -4072,14 +4076,15 @@ namespace System.Management.Automation.Runspaces
return;
bool isFullyTrusted;
string fileContents = GetModuleContents(snapinName, fileToLoad, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile);
bool isProductCode;
string fileContents = GetModuleContents(snapinName, fileToLoad, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile, out isProductCode);
if (fileContents == null)
{
return;
}
UpdateWithModuleContents(fileContents, snapinName, fileToLoad, isFullyTrusted, errors);
UpdateWithModuleContents(fileContents, snapinName, fileToLoad, isFullyTrusted, isProductCode, errors);
}
/// <summary>
@@ -4092,13 +4097,15 @@ namespace System.Management.Automation.Runspaces
AuthorizationManager authorizationManager,
PSHost host,
out bool isFullyTrusted,
out bool failToLoadFile)
out bool failToLoadFile,
out bool isProductCode)
{
Dbg.Assert(Path.IsPathRooted(fileToLoad), "fileToLoad should be a fully-qualified path.");
ExternalScriptInfo ps1xmlInfo;
string fileContents;
isFullyTrusted = false;
isProductCode = false;
try
{
@@ -4109,6 +4116,11 @@ namespace System.Management.Automation.Runspaces
{
isFullyTrusted = true;
}
if (SecuritySupport.IsProductBinary(fileToLoad))
{
isProductCode = true;
}
}
catch (SecurityException e)
{
@@ -4148,18 +4160,21 @@ namespace System.Management.Automation.Runspaces
/// <param name="moduleName">Module name</param>
/// <param name="fileToLoad">Module file path</param>
/// <param name="isFullyTrusted">Whether the module contents are fully trusted</param>
/// <param name="isProductCode">Whether the module contents are considered part of Windows (e.g. catalog signed)</param>
/// <param name="errors">Errors</param>
private void UpdateWithModuleContents(
string fileContents,
string moduleName,
string fileToLoad,
bool isFullyTrusted,
bool isProductCode,
ConcurrentBag<string> errors)
{
typesInfo.Add(new SessionStateTypeEntry(fileToLoad));
LoadContext loadContext = new LoadContext(moduleName, fileToLoad, errors)
{
IsFullyTrusted = isFullyTrusted,
IsProductCode = isProductCode,
};
using (StringReader xmlStream = new StringReader(fileContents))
@@ -4361,12 +4376,13 @@ namespace System.Management.Automation.Runspaces
// Get file contents and perform authorization check
// (including possible user prompt) outside of the lock.
bool isFullyTrusted;
bool isProductCode;
var fileContents = GetModuleContents(moduleName, filePath, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile);
var fileContents = GetModuleContents(moduleName, filePath, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile, out isProductCode);
if (fileContents != null)
{
UpdateWithModuleContents(fileContents, moduleName, filePath, isFullyTrusted, errors);
UpdateWithModuleContents(fileContents, moduleName, filePath, isFullyTrusted, isProductCode, errors);
}
}
if (etwEnabled) RunspaceEventSource.Log.ProcessTypeFileStop(filePath);
@@ -28,7 +28,7 @@ namespace System.Management.Automation.Runspaces
static ScriptBlock GetScriptBlock(string s)
{
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s);
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s, isProductCode: true);
sb.LanguageMode = PSLanguageMode.FullLanguage;
return sb;
}
@@ -22,7 +22,7 @@ namespace System.Management.Automation.Runspaces
static ScriptBlock GetScriptBlock(string s)
{
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s);
var sb = ScriptBlock.CreateDelayParsedScriptBlock(s, isProductCode: true);
sb.LanguageMode = PSLanguageMode.FullLanguage;
return sb;
}
@@ -68,8 +68,8 @@ namespace System.Management.Automation
NewSuggestion(2, "Transactions", SuggestionMatchType.Command, "^Use-Transaction",
SuggestionStrings.Suggestion_UseTransaction, true),
NewSuggestion(3, "General", SuggestionMatchType.Dynamic,
ScriptBlock.Create(checkForCommandInCurrentDirectoryScript),
ScriptBlock.Create(createCommandExistsInCurrentDirectoryScript),
ScriptBlock.CreateDelayParsedScriptBlock(checkForCommandInCurrentDirectoryScript, isProductCode: true),
ScriptBlock.CreateDelayParsedScriptBlock(createCommandExistsInCurrentDirectoryScript, isProductCode: true),
new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory) },
true)
}
@@ -878,7 +878,7 @@ namespace System.Management.Automation.Runspaces
PSHostUserInterface host = executionContext.EngineHostInterface.UI;
if (host != null)
{
host.StopAllTranscribing(executionContext.CurrentRunspace.InstanceId);
host.StopAllTranscribing();
}
}
}
@@ -420,13 +420,12 @@ namespace System.Management.Automation.Host
}
}
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader, Guid runspaceInstanceId)
{
internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader)
{
TranscriptionOption transcript = new TranscriptionOption();
transcript.Path = path;
transcript.IncludeInvocationHeader = includeInvocationHeader;
transcript.RunspaceInstanceId = runspaceInstanceId;
TranscriptionData.Transcripts.Add(transcript);
TranscriptionData.Transcripts.Add(transcript);
LogTranscriptHeader(senderInfo, transcript);
}
@@ -448,10 +447,12 @@ namespace System.Management.Automation.Host
{
Object value = versionInfo[versionKey];
var arrayValue = value as object[];
string valueString = arrayValue != null ? string.Join(", ", arrayValue) : value.ToString();
psVersionInfo.AppendLine(versionKey + ": " + valueString);
if (value != null)
{
var arrayValue = value as object[];
string valueString = arrayValue != null ? string.Join(", ", arrayValue) : value.ToString();
psVersionInfo.AppendLine(versionKey + ": " + valueString);
}
}
// Transcribe the transcript header
@@ -477,7 +478,7 @@ namespace System.Management.Automation.Host
TranscribeCommandComplete(null);
}
internal string StopTranscribing(Guid runspaceInstanceId)
internal string StopTranscribing()
{
if (TranscriptionData.Transcripts.Count == 0)
{
@@ -485,17 +486,11 @@ namespace System.Management.Automation.Host
}
TranscriptionOption stoppedTranscript = TranscriptionData.Transcripts[TranscriptionData.Transcripts.Count - 1];
if (stoppedTranscript.RunspaceInstanceId == runspaceInstanceId)
{
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
}
return null;
LogTranscriptFooter(stoppedTranscript);
stoppedTranscript.Dispose();
TranscriptionData.Transcripts.Remove(stoppedTranscript);
return stoppedTranscript.Path;
}
private void LogTranscriptFooter(TranscriptionOption stoppedTranscript)
@@ -521,13 +516,13 @@ namespace System.Management.Automation.Host
}
}
internal void StopAllTranscribing(Guid runspaceInstanceId)
internal void StopAllTranscribing()
{
TranscribeCommandComplete(null);
foreach(var transcription in TranscriptionData.Transcripts)
while (TranscriptionData.Transcripts.Count > 0)
{
StopTranscribing(runspaceInstanceId);
StopTranscribing();
}
lock (TranscriptionData)
@@ -1006,7 +1001,7 @@ namespace System.Management.Automation.Host
internal TranscriptionOption SystemTranscript { get; set; }
internal string CommandBeingIgnored { get; set; }
internal bool IsHelperCommand { get; set; }
internal string PromptText { get; set; }
internal string PromptText { get; set; }
}
@@ -1066,12 +1061,6 @@ namespace System.Management.Automation.Host
/// </summary>
internal Encoding Encoding { get; private set; }
/// <summary>
/// RunspaceInstanceId of the transcription session.
/// This is used to choose which transcriptions are closed when runspace is disposed.
/// </summary>
internal Guid RunspaceInstanceId { get; set; }
/// <summary>
/// Logs buffered content to disk. We use this instead of File.AppendAllLines
/// so that we don't need to pay seek penalties all the time, and so that we
@@ -115,9 +115,9 @@ namespace System.Management.Automation
return Create(new Language.Parser(), null, script);
}
internal static ScriptBlock CreateDelayParsedScriptBlock(string script)
internal static ScriptBlock CreateDelayParsedScriptBlock(string script, bool isProductCode)
{
return new ScriptBlock(new CompiledScriptBlockData(script));
return new ScriptBlock(new CompiledScriptBlockData(script, isProductCode));
}
/// <summary>
@@ -1613,31 +1613,28 @@ namespace System.Management.Automation.Language
_sequencePoints.Add(ast.Extent);
}
var compileInterpretChoice = (_stmtCount > 300) ? CompileInterpretChoice.NeverCompile : CompileInterpretChoice.CompileOnDemand;
if (optimize)
{
scriptBlock.DynamicParamBlockTree = _dynamicParamBlockLambda;
scriptBlock.BeginBlockTree = _beginBlockLambda;
scriptBlock.ProcessBlockTree = _processBlockLambda;
scriptBlock.EndBlockTree = _endBlockLambda;
scriptBlock.DynamicParamBlock = CompileTree(_dynamicParamBlockLambda, compileInterpretChoice);
scriptBlock.BeginBlock = CompileTree(_beginBlockLambda, compileInterpretChoice);
scriptBlock.ProcessBlock = CompileTree(_processBlockLambda, compileInterpretChoice);
scriptBlock.EndBlock = CompileTree(_endBlockLambda, compileInterpretChoice);
scriptBlock.LocalsMutableTupleType = LocalVariablesTupleType;
scriptBlock.LocalsMutableTupleCreator = MutableTuple.TupleCreator(LocalVariablesTupleType);
scriptBlock.NameToIndexMap = nameToIndexMap;
}
else
{
scriptBlock.UnoptimizedDynamicParamBlockTree = _dynamicParamBlockLambda;
scriptBlock.UnoptimizedBeginBlockTree = _beginBlockLambda;
scriptBlock.UnoptimizedProcessBlockTree = _processBlockLambda;
scriptBlock.UnoptimizedEndBlockTree = _endBlockLambda;
scriptBlock.UnoptimizedDynamicParamBlock = CompileTree(_dynamicParamBlockLambda, compileInterpretChoice);
scriptBlock.UnoptimizedBeginBlock = CompileTree(_beginBlockLambda, compileInterpretChoice);
scriptBlock.UnoptimizedProcessBlock = CompileTree(_processBlockLambda, compileInterpretChoice);
scriptBlock.UnoptimizedEndBlock = CompileTree(_endBlockLambda, compileInterpretChoice);
scriptBlock.UnoptimizedLocalsMutableTupleType = LocalVariablesTupleType;
scriptBlock.UnoptimizedLocalsMutableTupleCreator = MutableTuple.TupleCreator(LocalVariablesTupleType);
}
scriptBlock.CompileInterpretDecision =
(_stmtCount > 300)
? CompileInterpretChoice.NeverCompile
: CompileInterpretChoice.CompileOnDemand;
// The sequence points are identical optimized or not. Regardless, we want to ensure
// that the list is unique no matter when the property is accessed, so make sure it is set just once.
if (scriptBlock.SequencePoints == null)
@@ -1646,6 +1643,24 @@ namespace System.Management.Automation.Language
}
}
private Action<FunctionContext> CompileTree(Expression<Action<FunctionContext>> lambda, CompileInterpretChoice compileInterpretChoice)
{
if (lambda == null)
return null;
if (compileInterpretChoice == CompileInterpretChoice.AlwaysCompile)
{
return lambda.Compile();
}
// threshold is # of times the script must run before we decide to compile
// NeverCompile sets the threshold to int.MaxValue, so theoretically we might compile
// at some point, but it's very unlikely.
int threshold = (compileInterpretChoice == CompileInterpretChoice.NeverCompile) ? int.MaxValue : -1;
var deleg = new LightCompiler(threshold).CompileTop(lambda).CreateDelegate();
return (Action<FunctionContext>)deleg;
}
internal static object GetExpressionValue(ExpressionAst expressionAst, bool isTrustedInput, ExecutionContext context, IDictionary usingValues = null)
{
return GetExpressionValue(expressionAst, isTrustedInput, context, null, usingValues);
@@ -53,6 +53,7 @@ namespace System.Management.Automation.Language
internal interface IParameterMetadataProvider
{
bool HasAnyScriptBlockAttributes();
RuntimeDefinedParameterDictionary GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding);
IEnumerable<Attribute> GetScriptBlockAttributes();
@@ -1383,6 +1384,11 @@ namespace System.Management.Automation.Language
#region IParameterMetadataProvider implementation
bool IParameterMetadataProvider.HasAnyScriptBlockAttributes()
{
return Attributes.Count > 0 || ParamBlock != null && ParamBlock.Attributes.Count > 0;
}
RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding)
{
if (ParamBlock != null)
@@ -3388,6 +3394,11 @@ namespace System.Management.Automation.Language
#region IParameterMetadataProvider implementation
bool IParameterMetadataProvider.HasAnyScriptBlockAttributes()
{
return ((IParameterMetadataProvider)_functionDefinitionAst).HasAnyScriptBlockAttributes();
}
ReadOnlyCollection<ParameterAst> IParameterMetadataProvider.Parameters
{
get { return ((IParameterMetadataProvider)_functionDefinitionAst).Parameters; }
@@ -3507,6 +3518,11 @@ namespace System.Management.Automation.Language
return Ast.EmptyPSTypeNameArray;
}
public bool HasAnyScriptBlockAttributes()
{
return ((IParameterMetadataProvider)Body).HasAnyScriptBlockAttributes();
}
public RuntimeDefinedParameterDictionary GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding)
{
return new RuntimeDefinedParameterDictionary { Data = RuntimeDefinedParameterDictionary.EmptyParameterArray };
@@ -3780,6 +3796,11 @@ namespace System.Management.Automation.Language
#region IParameterMetadataProvider implementation
bool IParameterMetadataProvider.HasAnyScriptBlockAttributes()
{
return ((IParameterMetadataProvider)Body).HasAnyScriptBlockAttributes();
}
RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding)
{
if (Parameters != null)
@@ -6819,9 +6840,10 @@ namespace System.Management.Automation.Language
if (_configurationBuildInParameters == null)
{
_configurationBuildInParameters = new List<ParameterAst>();
var sb = ScriptBlock.Create(ConfigurationBuildInParametersStr);
var sba = sb.Ast as ScriptBlockAst;
Token[] tokens;
ParseError[] errors;
var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors);
if (sba != null)
{
foreach (var parameterAst in sba.ParamBlock.Parameters)
@@ -6842,9 +6864,10 @@ namespace System.Management.Automation.Language
if (_configurationBuildInParameterAttrAsts == null)
{
_configurationBuildInParameterAttrAsts = new List<AttributeAst>();
var sb = ScriptBlock.Create(ConfigurationBuildInParametersStr);
var sba = sb.Ast as ScriptBlockAst;
Token[] tokens;
ParseError[] errors;
var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors);
if (sba != null)
{
if (_configurationBuildInParameters == null)
@@ -6876,16 +6899,16 @@ namespace System.Management.Automation.Language
if (_configurationExtraParameterStatements == null)
{
_configurationExtraParameterStatements = new List<StatementAst>();
var sb = ScriptBlock.Create(@"
Token[] tokens;
ParseError[] errors;
var sba = Parser.ParseInput(@"
Import-Module Microsoft.PowerShell.Management -Verbose:$false
Import-Module PSDesiredStateConfiguration -Verbose:$false
$toBody = @{}+$PSBoundParameters
$toBody.Remove(""OutputPath"")
$toBody.Remove(""ConfigurationData"")
$ConfigurationData = $psboundparameters[""ConfigurationData""]
$Outputpath = $psboundparameters[""Outputpath""]");
var sba = sb.Ast as ScriptBlockAst;
$Outputpath = $psboundparameters[""Outputpath""]", out tokens, out errors);
if (sba != null)
{
foreach (var statementAst in sba.EndBlock.Statements)
@@ -681,11 +681,27 @@ namespace System.Management.Automation.Remoting
{
return result;
}
tracer.WriteLine("Loading assembly from path {0}", applicationBase);
try
{
result = ClrFacade.LoadFrom(assemblyName);
String assemblyPath;
if (!Path.IsPathRooted(assemblyName))
{
if (!String.IsNullOrEmpty(applicationBase) && Directory.Exists(applicationBase))
{
assemblyPath = Path.Combine(applicationBase, assemblyName);
}
else
{
assemblyPath = Path.Combine(Directory.GetCurrentDirectory(), assemblyName);
}
}
else
{
//Rooted path of dll is provided.
assemblyPath = assemblyName;
}
result = ClrFacade.LoadFrom(assemblyPath);
}
catch (FileLoadException e)
{
@@ -708,7 +724,6 @@ namespace System.Management.Automation.Remoting
Directory.SetCurrentDirectory(originalDirectory);
}
}
return result;
}
@@ -56,16 +56,15 @@ namespace System.Management.Automation
this.Id = Guid.NewGuid();
}
internal CompiledScriptBlockData(string scriptText)
internal CompiledScriptBlockData(string scriptText, bool isProductCode)
{
this.IsProductCode = isProductCode;
this._scriptText = scriptText;
this.Id = Guid.NewGuid();
}
internal bool Compile(bool optimized)
{
var sw = new Stopwatch();
sw.Start();
if (_attributes == null)
{
InitializeMetadata();
@@ -89,9 +88,6 @@ namespace System.Management.Automation
CompileOptimized();
}
sw.Stop();
TelemetryAPI.ReportScriptTelemetry((Ast)_ast, !optimized, sw.ElapsedMilliseconds);
return optimized;
}
@@ -105,29 +101,34 @@ namespace System.Management.Automation
return;
}
Attribute[] attributes;
CmdletBindingAttribute cmdletBindingAttribute = null;
var attributes = Ast.GetScriptBlockAttributes().ToArray();
foreach (var attribute in attributes)
if (!Ast.HasAnyScriptBlockAttributes())
{
if (attribute is CmdletBindingAttribute)
{
cmdletBindingAttribute = cmdletBindingAttribute ?? (CmdletBindingAttribute)attribute;
}
else if (attribute is DebuggerHiddenAttribute)
{
DebuggerHidden = true;
}
else if (attribute is DebuggerStepThroughAttribute || attribute is DebuggerNonUserCodeAttribute)
{
DebuggerStepThrough = true;
}
attributes = Utils.EmptyArray<Attribute>();
}
_usesCmdletBinding = cmdletBindingAttribute != null;
bool automaticPosition = cmdletBindingAttribute != null
? cmdletBindingAttribute.PositionalBinding
: true;
var runtimeDefinedParameterDictionary = Ast.GetParameterMetadata(automaticPosition,
ref _usesCmdletBinding);
else
{
attributes = Ast.GetScriptBlockAttributes().ToArray();
foreach (var attribute in attributes)
{
if (attribute is CmdletBindingAttribute)
{
cmdletBindingAttribute = cmdletBindingAttribute ?? (CmdletBindingAttribute) attribute;
}
else if (attribute is DebuggerHiddenAttribute)
{
DebuggerHidden = true;
}
else if (attribute is DebuggerStepThroughAttribute || attribute is DebuggerNonUserCodeAttribute)
{
DebuggerStepThrough = true;
}
}
_usesCmdletBinding = cmdletBindingAttribute != null;
}
bool automaticPosition = cmdletBindingAttribute == null || cmdletBindingAttribute.PositionalBinding;
var runtimeDefinedParameterDictionary = Ast.GetParameterMetadata(automaticPosition, ref _usesCmdletBinding);
// Initialize these fields last - if there were any exceptions, we don't want the partial results cached.
_attributes = attributes;
@@ -145,38 +146,8 @@ namespace System.Management.Automation
return;
}
bool etwEnabled = ParserEventSource.Log.IsEnabled();
if (etwEnabled)
{
var extent = _ast.Body.Extent;
var text = extent.Text;
ParserEventSource.Log.CompileStart(ParserEventSource.GetFileOrScript(extent.File, text), text.Length, Optimized: false);
}
PerformSecurityChecks();
Compiler compiler = new Compiler();
compiler.Compile(this, optimize: false);
if (UnoptimizedDynamicParamBlockTree != null)
{
UnoptimizedDynamicParamBlock = CompileTree(UnoptimizedDynamicParamBlockTree);
}
if (UnoptimizedBeginBlockTree != null)
{
UnoptimizedBeginBlock = CompileTree(UnoptimizedBeginBlockTree);
}
if (UnoptimizedProcessBlockTree != null)
{
UnoptimizedProcessBlock = CompileTree(UnoptimizedProcessBlockTree);
}
if (UnoptimizedEndBlockTree != null)
{
UnoptimizedEndBlock = CompileTree(UnoptimizedEndBlockTree);
}
ReallyCompile(false);
_compiledUnoptimized = true;
if (etwEnabled) ParserEventSource.Log.CompileStop();
}
}
@@ -190,56 +161,40 @@ namespace System.Management.Automation
return;
}
bool etwEnabled = ParserEventSource.Log.IsEnabled();
if (etwEnabled)
{
var extent = _ast.Body.Extent;
var text = extent.Text;
ParserEventSource.Log.CompileStart(ParserEventSource.GetFileOrScript(extent.File, text), text.Length, Optimized: true);
}
PerformSecurityChecks();
Compiler compiler = new Compiler();
compiler.Compile(this, optimize: true);
if (DynamicParamBlockTree != null)
{
DynamicParamBlock = CompileTree(DynamicParamBlockTree);
}
if (BeginBlockTree != null)
{
BeginBlock = CompileTree(BeginBlockTree);
}
if (ProcessBlockTree != null)
{
ProcessBlock = CompileTree(ProcessBlockTree);
}
if (EndBlockTree != null)
{
EndBlock = CompileTree(EndBlockTree);
}
ReallyCompile(true);
_compiledOptimized = true;
if (etwEnabled) ParserEventSource.Log.CompileStop();
}
}
private Action<FunctionContext> CompileTree(Expression<Action<FunctionContext>> lambda)
private void ReallyCompile(bool optimize)
{
if (this.CompileInterpretDecision == CompileInterpretChoice.AlwaysCompile)
var sw = new Stopwatch();
sw.Start();
if (!IsProductCode && SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File))
{
return lambda.Compile();
this.IsProductCode = true;
}
// threshold is # of times the script must run before we decide to compile
// NeverCompile sets the threshold to int.MaxValue, so theoretically we might compile
// at some point, but it's very unlikely.
int threshold =
(this.CompileInterpretDecision == CompileInterpretChoice.NeverCompile)
? int.MaxValue
: -1;
var deleg = new LightCompiler(threshold).CompileTop(lambda).CreateDelegate();
return (Action<FunctionContext>)deleg;
bool etwEnabled = ParserEventSource.Log.IsEnabled();
if (etwEnabled)
{
var extent = _ast.Body.Extent;
var text = extent.Text;
ParserEventSource.Log.CompileStart(ParserEventSource.GetFileOrScript(extent.File, text), text.Length, optimize);
}
PerformSecurityChecks();
Compiler compiler = new Compiler();
compiler.Compile(this, optimize);
if (!IsProductCode)
{
TelemetryAPI.ReportScriptTelemetry((Ast)_ast, !optimize, sw.ElapsedMilliseconds);
}
if (etwEnabled) ParserEventSource.Log.CompileStop();
}
private void PerformSecurityChecks()
@@ -289,30 +244,21 @@ namespace System.Management.Automation
}
}
internal Expression<Action<FunctionContext>> UnoptimizedDynamicParamBlockTree { get; set; }
internal Expression<Action<FunctionContext>> DynamicParamBlockTree { get; set; }
internal Expression<Action<FunctionContext>> BeginBlockTree { get; set; }
internal Expression<Action<FunctionContext>> UnoptimizedBeginBlockTree { get; set; }
internal Expression<Action<FunctionContext>> ProcessBlockTree { get; set; }
internal Expression<Action<FunctionContext>> UnoptimizedProcessBlockTree { get; set; }
internal Expression<Action<FunctionContext>> EndBlockTree { get; set; }
internal Expression<Action<FunctionContext>> UnoptimizedEndBlockTree { get; set; }
internal CompileInterpretChoice CompileInterpretDecision { get; set; }
internal Type LocalsMutableTupleType { get; set; }
internal Type UnoptimizedLocalsMutableTupleType { get; set; }
internal Func<MutableTuple> LocalsMutableTupleCreator { get; set; }
internal Func<MutableTuple> UnoptimizedLocalsMutableTupleCreator { get; set; }
internal Dictionary<string, int> NameToIndexMap { get; set; }
internal Action<FunctionContext> DynamicParamBlock { get; private set; }
internal Action<FunctionContext> UnoptimizedDynamicParamBlock { get; private set; }
internal Action<FunctionContext> BeginBlock { get; private set; }
internal Action<FunctionContext> UnoptimizedBeginBlock { get; private set; }
internal Action<FunctionContext> ProcessBlock { get; private set; }
internal Action<FunctionContext> UnoptimizedProcessBlock { get; private set; }
internal Action<FunctionContext> EndBlock { get; private set; }
internal Action<FunctionContext> UnoptimizedEndBlock { get; private set; }
internal Action<FunctionContext> DynamicParamBlock { get; set; }
internal Action<FunctionContext> UnoptimizedDynamicParamBlock { get; set; }
internal Action<FunctionContext> BeginBlock { get; set; }
internal Action<FunctionContext> UnoptimizedBeginBlock { get; set; }
internal Action<FunctionContext> ProcessBlock { get; set; }
internal Action<FunctionContext> UnoptimizedProcessBlock { get; set; }
internal Action<FunctionContext> EndBlock { get; set; }
internal Action<FunctionContext> UnoptimizedEndBlock { get; set; }
internal IScriptExtent[] SequencePoints { get; set; }
private RuntimeDefinedParameterDictionary _runtimeDefinedParameterDictionary;
private Attribute[] _attributes;
@@ -325,6 +271,7 @@ namespace System.Management.Automation
internal Guid Id { get; private set; }
internal bool HasLogged { get; set; }
internal bool IsFilter { get; private set; }
internal bool IsProductCode { get; private set; }
internal bool GetIsConfiguration()
{
@@ -563,7 +510,7 @@ namespace System.Management.Automation
_cachedScripts.Clear();
}
internal static ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock("");
internal static ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock("", isProductCode: true);
internal static ScriptBlock Create(Parser parser, string fileName, string fileContents)
{
@@ -1298,9 +1245,9 @@ namespace System.Management.Automation
if (!scriptBlock.HasLogged || InternalTestHooks.ForceScriptBlockLogging)
{
// If script block logging is explicitly disabled, or it's from a trusted
// file, skip logging.
// file or internal, skip logging.
if (ScriptBlockLoggingExplicitlyDisabled() ||
SecuritySupport.IsProductBinary(scriptBlock.File))
scriptBlock.ScriptBlockData.IsProductCode)
{
return;
}
@@ -1788,15 +1735,6 @@ namespace System.Management.Automation
internal Action<FunctionContext> EndBlock { get { return _scriptBlockData.EndBlock; } }
internal Action<FunctionContext> UnoptimizedEndBlock { get { return _scriptBlockData.UnoptimizedEndBlock; } }
internal Expression<Action<FunctionContext>> UnoptimizedDynamicParamBlockTree { get { return _scriptBlockData.UnoptimizedDynamicParamBlockTree; } }
internal Expression<Action<FunctionContext>> DynamicParamBlockTree { get { return _scriptBlockData.DynamicParamBlockTree; } }
internal Expression<Action<FunctionContext>> BeginBlockTree { get { return _scriptBlockData.BeginBlockTree; } }
internal Expression<Action<FunctionContext>> UnoptimizedBeginBlockTree { get { return _scriptBlockData.UnoptimizedBeginBlockTree; } }
internal Expression<Action<FunctionContext>> ProcessBlockTree { get { return _scriptBlockData.ProcessBlockTree; } }
internal Expression<Action<FunctionContext>> UnoptimizedProcessBlockTree { get { return _scriptBlockData.UnoptimizedProcessBlockTree; } }
internal Expression<Action<FunctionContext>> EndBlockTree { get { return _scriptBlockData.EndBlockTree; } }
internal Expression<Action<FunctionContext>> UnoptimizedEndBlockTree { get { return _scriptBlockData.UnoptimizedEndBlockTree; } }
internal bool HasBeginBlock { get { return AstInternal.Body.BeginBlock != null; } }
internal bool HasProcessBlock { get { return AstInternal.Body.ProcessBlock != null; } }
internal bool HasEndBlock { get { return AstInternal.Body.EndBlock != null; } }