public override void GenerateCode(ILGenerator gen, CodeFlow cf) { if (_cachedReadAccessor is not ICompilablePropertyAccessor accessorToUse) { throw new InvalidOperationException("Property accessor is not compilable: " + _cachedReadAccessor); } Label?skipIfNullLabel = null; if (_nullSafe) { skipIfNullLabel = gen.DefineLabel(); gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Ldnull); gen.Emit(OpCodes.Cgt_Un); gen.Emit(OpCodes.Brfalse, skipIfNullLabel.Value); } accessorToUse.GenerateCode(_name, gen, cf); cf.PushDescriptor(_exitTypeDescriptor); if (_originalPrimitiveExitTypeDescriptor != null) { // The output of the accessor is a primitive but from the block above it might be null, // so to have a common stack element type at skipIfNull target it is necessary // to box the primitive CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor); } if (skipIfNullLabel.HasValue) { gen.MarkLabel(skipIfNullLabel.Value); } }
public override void GenerateCode(DynamicMethod mv, CodeFlow cf) { //// exit type descriptor can be null if both components are literal expressions // computeExitTypeDescriptor(); // cf.enterCompilationScope(); // this.children[0].generateCode(mv, cf); // String lastDesc = cf.lastDescriptor(); // Assert.state(lastDesc != null, "No last descriptor"); // CodeFlow.insertBoxIfNecessary(mv, lastDesc.charAt(0)); // cf.exitCompilationScope(); // Label elseTarget = new Label(); // Label endOfIf = new Label(); // mv.visitInsn(DUP); // mv.visitJumpInsn(IFNULL, elseTarget); //// Also check if empty string, as per the code in the interpreted version // mv.visitInsn(DUP); // mv.visitLdcInsn(""); // mv.visitInsn(SWAP); // mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false); // mv.visitJumpInsn(IFEQ, endOfIf); // if not empty, drop through to elseTarget // mv.visitLabel(elseTarget); // mv.visitInsn(POP); // cf.enterCompilationScope(); // this.children[1].generateCode(mv, cf); // if (!CodeFlow.isPrimitive(this.exitTypeDescriptor)) // { // lastDesc = cf.lastDescriptor(); // Assert.state(lastDesc != null, "No last descriptor"); // CodeFlow.insertBoxIfNecessary(mv, lastDesc.charAt(0)); // } // cf.exitCompilationScope(); // mv.visitLabel(endOfIf); // cf.pushDescriptor(this.exitTypeDescriptor); }
public static LocationCollection ToThreadFlowLocationCollection(this CodeFlow codeFlow, Run run, int resultId, int runIndex) { if (codeFlow == null) { return(null); } var model = new LocationCollection(codeFlow.Message.Text); if (codeFlow.ThreadFlows?[0]?.Locations != null) { foreach (ThreadFlowLocation location in codeFlow.ThreadFlows[0].Locations) { // TODO we are not yet properly hardened against locationless // code locations (and what this means is also in flux as // far as SARIF producers). For now we skip these. if (location.Location?.PhysicalLocation == null) { continue; } model.Add(location.ToLocationModel(run, resultId, runIndex)); } } return(model); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { CodeFlow.LoadEvaluationContext(gen); var leftDesc = LeftOperand.ExitDescriptor; var rightDesc = RightOperand.ExitDescriptor; var leftPrim = CodeFlow.IsValueType(leftDesc); var rightPrim = CodeFlow.IsValueType(rightDesc); cf.EnterCompilationScope(); LeftOperand.GenerateCode(gen, cf); cf.ExitCompilationScope(); if (leftPrim) { CodeFlow.InsertBoxIfNecessary(gen, leftDesc); } cf.EnterCompilationScope(); RightOperand.GenerateCode(gen, cf); cf.ExitCompilationScope(); if (rightPrim) { CodeFlow.InsertBoxIfNecessary(gen, rightDesc); } gen.Emit(OpCodes.Call, _equalityCheck); cf.PushDescriptor(TypeDescriptor.Z); }
private CompiledExpression CreateExpressionClass(ISpelNode expressionToCompile) { var compiledExpression = new SpelCompiledExpression(_loggerFactory); var methodName = "SpelExpression" + _suffixId.GetAndIncrement(); var method = new DynamicMethod(methodName, typeof(object), new Type[] { typeof(SpelCompiledExpression), typeof(object), typeof(IEvaluationContext) }, typeof(SpelCompiledExpression)); var ilGenerator = method.GetILGenerator(4096); var cf = new CodeFlow(compiledExpression); try { expressionToCompile.GenerateCode(ilGenerator, cf); var lastDescriptor = cf.LastDescriptor(); CodeFlow.InsertBoxIfNecessary(ilGenerator, lastDescriptor); if (lastDescriptor == TypeDescriptor.V) { ilGenerator.Emit(OpCodes.Ldnull); } ilGenerator.Emit(OpCodes.Ret); compiledExpression.MethodDelegate = method.CreateDelegate(typeof(SpelExpressionDelegate)); var initMethod = cf.Finish(_suffixId.Value); if (initMethod != null) { compiledExpression.InitDelegate = initMethod.CreateDelegate(typeof(SpelExpressionInitDelegate)); } return(compiledExpression); } catch (Exception ex) { _logger?.LogDebug(expressionToCompile.GetType().Name + ".GenerateCode opted out of compilation: " + ex.Message); return(null); } }
public override ITypedValue GetValueInternal(ExpressionState state) { if (_name.Equals(_THIS)) { return(state.GetActiveContextObject()); } if (_name.Equals(_ROOT)) { var obj = state.RootContextObject; _exitTypeDescriptor = CodeFlow.ToDescriptorFromObject(obj.Value); return(obj); } var result = state.LookupVariable(_name); var value = result.Value; if (value == null || !value.GetType().IsPublic) { // If the type is not public then when generateCode produces a checkcast to it // then an IllegalAccessError will occur. // If resorting to Object isn't sufficient, the hierarchy could be traversed for // the first public type. _exitTypeDescriptor = "Ljava/lang/Object"; } else { _exitTypeDescriptor = CodeFlow.ToDescriptorFromObject(value); } // a null value will mean either the value was null or the variable was not found return(result); }
protected static void GenerateCodeForArgument(ILGenerator gen, CodeFlow cf, SpelNode argument, TypeDescriptor paramDesc) { cf.EnterCompilationScope(); argument.GenerateCode(gen, cf); var lastDesc = cf.LastDescriptor(); if (lastDesc == null) { throw new InvalidOperationException("No last descriptor"); } var valueTypeOnStack = CodeFlow.IsValueType(lastDesc); // Check if need to box it for the method reference? if (valueTypeOnStack && paramDesc.IsReferenceType) { CodeFlow.InsertBoxIfNecessary(gen, lastDesc); } else if (paramDesc.IsValueType && !paramDesc.IsBoxed && !valueTypeOnStack) { gen.Emit(OpCodes.Unbox_Any, paramDesc.Value); } else { // This would be unnecessary in the case of subtyping (e.g. method takes Number but Integer passed in) CodeFlow.InsertCastClass(gen, paramDesc); } cf.ExitCompilationScope(); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { // pseudo: if (leftOperandValue) { result=true; } else { result=rightOperandValue; } var elseTarget = gen.DefineLabel(); var endIfTarget = gen.DefineLabel(); var result = gen.DeclareLocal(typeof(bool)); cf.EnterCompilationScope(); LeftOperand.GenerateCode(gen, cf); cf.UnboxBooleanIfNecessary(gen); cf.ExitCompilationScope(); gen.Emit(OpCodes.Brfalse, elseTarget); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Stloc, result); gen.Emit(OpCodes.Br, endIfTarget); gen.MarkLabel(elseTarget); cf.EnterCompilationScope(); RightOperand.GenerateCode(gen, cf); cf.UnboxBooleanIfNecessary(gen); cf.ExitCompilationScope(); gen.Emit(OpCodes.Stloc, result); gen.MarkLabel(endIfTarget); gen.Emit(OpCodes.Ldloc, result); cf.PushDescriptor(_exitTypeDescriptor); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { if (_exitTypeDescriptor == TypeDescriptor.STRING) { gen.Emit(OpCodes.Newobj, _sbConstructor); Walk(gen, cf, LeftOperand); Walk(gen, cf, RightOperand); gen.Emit(OpCodes.Callvirt, _toString); } else { _children[0].GenerateCode(gen, cf); var leftDesc = _children[0].ExitDescriptor; var exitDesc = _exitTypeDescriptor; if (exitDesc == null) { throw new InvalidOperationException("No exit type descriptor"); } CodeFlow.InsertNumericUnboxOrPrimitiveTypeCoercion(gen, leftDesc, exitDesc); if (_children.Length > 1) { cf.EnterCompilationScope(); _children[1].GenerateCode(gen, cf); var rightDesc = _children[1].ExitDescriptor; cf.ExitCompilationScope(); CodeFlow.InsertNumericUnboxOrPrimitiveTypeCoercion(gen, rightDesc, exitDesc); gen.Emit(OpCodes.Add); } } cf.PushDescriptor(_exitTypeDescriptor); }
public override void GenerateCode(DynamicMethod mv, CodeFlow cf) { // PropertyAccessor accessorToUse = this.cachedReadAccessor; // if (!(accessorToUse is CompilablePropertyAccessor)) // { // throw new IllegalStateException("Property accessor is not compilable: " + accessorToUse); // } // Label skipIfNull = null; // if (this.nullSafe) // { // mv.visitInsn(DUP); // skipIfNull = new Label(); // Label continueLabel = new Label(); // mv.visitJumpInsn(IFNONNULL, continueLabel); // CodeFlow.insertCheckCast(mv, this.exitTypeDescriptor); // mv.visitJumpInsn(GOTO, skipIfNull); // mv.visitLabel(continueLabel); // } // ((CompilablePropertyAccessor)accessorToUse).generateCode(this.name, mv, cf); // cf.pushDescriptor(this.exitTypeDescriptor); // if (this.originalPrimitiveExitTypeDescriptor != null) // { // // The output of the accessor is a primitive but from the block above it might be null, // // so to have a common stack element type at skipIfNull target it is necessary // // to box the primitive // CodeFlow.insertBoxIfNecessary(mv, this.originalPrimitiveExitTypeDescriptor); // } // if (skipIfNull != null) // { // mv.visitLabel(skipIfNull); // } }
public ITypedValue GetValue() { var value = _map[_key]; _indexer._exitTypeDescriptor = CodeFlow.ToDescriptor(typeof(object)); return(new TypedValue(value, ReflectionHelper.GetMapValueTypeDescriptor(_mapEntryDescriptor, value))); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { LeftOperand.GenerateCode(gen, cf); var leftDesc = LeftOperand.ExitDescriptor; var exitDesc = _exitTypeDescriptor; if (exitDesc == null) { throw new InvalidOperationException("No exit type descriptor"); } CodeFlow.InsertNumericUnboxOrPrimitiveTypeCoercion(gen, leftDesc, exitDesc); if (_children.Length > 1) { cf.EnterCompilationScope(); RightOperand.GenerateCode(gen, cf); var rightDesc = RightOperand.ExitDescriptor; cf.ExitCompilationScope(); CodeFlow.InsertNumericUnboxOrPrimitiveTypeCoercion(gen, rightDesc, exitDesc); gen.Emit(OpCodes.Sub); } else { gen.Emit(OpCodes.Neg); } cf.PushDescriptor(_exitTypeDescriptor); }
private void GenerateStaticMethodCode(ILGenerator gen, CodeFlow cf, MethodInfo method) { var stackDescriptor = cf.LastDescriptor(); Label?skipIfNullTarget = null; if (_nullSafe) { skipIfNullTarget = GenerateNullCheckCode(gen); } if (stackDescriptor != null) { // Something on the stack when nothing is needed gen.Emit(OpCodes.Pop); } GenerateCodeForArguments(gen, cf, method, _children); gen.Emit(OpCodes.Call, method); if (_originalPrimitiveExitTypeDescriptor != null) { // The output of the accessor will be a primitive but from the block above it might be null, // so to have a 'common stack' element at skipIfNull target we need to box the primitive CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor); } if (skipIfNullTarget.HasValue) { gen.MarkLabel(skipIfNullTarget.Value); } }
public override ITypedValue GetValueInternal(ExpressionState state) { var leftOperand = LeftOperand.GetValueInternal(state).Value; var rightOperand = RightOperand.GetValueInternal(state).Value; if (IsNumber(leftOperand) && IsNumber(rightOperand)) { var leftConv = (IConvertible)leftOperand; var rightConv = (IConvertible)rightOperand; if (leftOperand is decimal || rightOperand is decimal) { var leftVal = leftConv.ToDecimal(CultureInfo.InvariantCulture); var rightVal = rightConv.ToDecimal(CultureInfo.InvariantCulture); return(new TypedValue(leftVal / rightVal)); } else if (leftOperand is double || rightOperand is double) { var leftVal = leftConv.ToDouble(CultureInfo.InvariantCulture); var rightVal = rightConv.ToDouble(CultureInfo.InvariantCulture); _exitTypeDescriptor = TypeDescriptor.D; return(new TypedValue(leftVal / rightVal)); } else if (leftOperand is float || rightOperand is float) { var leftVal = leftConv.ToSingle(CultureInfo.InvariantCulture); var rightVal = rightConv.ToSingle(CultureInfo.InvariantCulture); _exitTypeDescriptor = TypeDescriptor.F; return(new TypedValue(leftVal / rightVal)); } // Look at need to add support for .NET types not present in Java, e.g. ulong, ushort, byte, uint else if (leftOperand is long || rightOperand is long) { var leftVal = leftConv.ToInt64(CultureInfo.InvariantCulture); var rightVal = rightConv.ToInt64(CultureInfo.InvariantCulture); _exitTypeDescriptor = TypeDescriptor.J; return(new TypedValue(leftVal / rightVal)); } else if (CodeFlow.IsIntegerForNumericOp(leftOperand) || CodeFlow.IsIntegerForNumericOp(rightOperand)) { var leftVal = leftConv.ToInt32(CultureInfo.InvariantCulture); var rightVal = rightConv.ToInt32(CultureInfo.InvariantCulture); _exitTypeDescriptor = TypeDescriptor.I; return(new TypedValue(leftVal / rightVal)); } else { var leftVal = leftConv.ToDouble(CultureInfo.InvariantCulture); var rightVal = rightConv.ToDouble(CultureInfo.InvariantCulture); // Unknown Number subtypes -> best guess is double division // Look at need to add support for .NET types not present in Java, e.g. ulong, ushort, byte, uint return(new TypedValue(leftVal / rightVal)); } } return(state.Operate(Operation.DIVIDE, leftOperand, rightOperand)); }
// // Inherit methods from parent class override public object Authorize(HttpRequest Request, string accountName) { try { var uri = Request.Url.ToString(); var code = Request["code"]; var error = Request["error"]; if (!string.IsNullOrEmpty(error)) { if (error == "access_denied") { return(new UserRejectException()); } else { return(new UnknownException(error)); } } // перед авторизацией нужно обнулить CalendarService = null; if (code != null) { string redirectUri = uri.Substring(0, uri.IndexOf("?")); var token = CodeFlow.ExchangeCodeForTokenAsync(accountName, code, redirectUri, CancellationToken.None).Result; string state = Request["state"]; var result = AuthWebUtility.ExtracRedirectFromState(CodeFlow.DataStore, accountName, state); return(result); } else { string redirectUri = uri; string state = "ostate_";// Guid.NewGuid().ToString("N"); var result = new AuthorizationCodeWebApp(CodeFlow, redirectUri, state).AuthorizeAsync(accountName, CancellationToken.None).Result; if (result.RedirectUri != null) { return(result); } else { CalendarService = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = result.Credential, ApplicationName = APPLICATION_NAME }); // alright return("OK"); } } } catch (Exception ex) { return(ex); } return(null); }
private void GenerateInstanceMethodCode(ILGenerator gen, CodeFlow cf, MethodInfo targetMethod, Type targetType) { var stackDescriptor = cf.LastDescriptor(); if (stackDescriptor == null) { // Nothing on the stack but something is needed CodeFlow.LoadTarget(gen); stackDescriptor = TypeDescriptor.OBJECT; } Label?skipIfNullTarget = null; if (_nullSafe) { skipIfNullTarget = GenerateNullCheckCode(gen); } if (targetType.IsValueType) { if (stackDescriptor.IsBoxed || stackDescriptor.IsReferenceType) { gen.Emit(OpCodes.Unbox_Any, targetType); } var local = gen.DeclareLocal(targetType); gen.Emit(OpCodes.Stloc, local); gen.Emit(OpCodes.Ldloca, local); } else { if (stackDescriptor.Value != targetType) { CodeFlow.InsertCastClass(gen, new TypeDescriptor(targetType)); } } GenerateCodeForArguments(gen, cf, targetMethod, _children); if (targetType.IsValueType) { gen.Emit(OpCodes.Call, targetMethod); } else { gen.Emit(OpCodes.Callvirt, targetMethod); } if (_originalPrimitiveExitTypeDescriptor != null) { // The output of the accessor will be a primitive but from the block above it might be null, // so to have a 'common stack' element at skipIfNull target we need to box the primitive CodeFlow.InsertBoxIfNecessary(gen, _originalPrimitiveExitTypeDescriptor); } if (skipIfNullTarget.HasValue) { gen.MarkLabel(skipIfNullTarget.Value); } }
public override void GenerateCode(DynamicMethod mv, CodeFlow cf) { // foreach (var child in _children) // { // child.generateCode(mv, cf); // } // cf.pushDescriptor(this.exitTypeDescriptor); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { foreach (var child in _children) { child.GenerateCode(gen, cf); } cf.PushDescriptor(_exitTypeDescriptor); }
internal static List <AnalysisStepNode> Convert(CodeFlow codeFlow, Run run, int resultId, int runIndex) { var root = new AnalysisStepNode(resultId: resultId, runIndex: runIndex) { Children = new List <AnalysisStepNode>(), }; ThreadFlow threadFlow = codeFlow.ThreadFlows?[0]; if (threadFlow != null) { int lastNestingLevel = 0; AnalysisStepNode lastParent = root; AnalysisStepNode lastNewNode = null; foreach (ThreadFlowLocation location in threadFlow.Locations) { ArtifactLocation artifactLocation = location.Location?.PhysicalLocation?.ArtifactLocation; if (artifactLocation != null) { Uri uri = location.Location?.PhysicalLocation?.ArtifactLocation?.Uri; if (uri == null && artifactLocation.Index > -1) { artifactLocation.Uri = run.Artifacts[artifactLocation.Index].Location.Uri; } } var newNode = new AnalysisStepNode(resultId: resultId, runIndex: runIndex) { Location = location, Children = new List <AnalysisStepNode>(), }; if (location.NestingLevel > lastNestingLevel) { // The previous node was a call, so this new node's parent is that node lastParent = lastNewNode; } else if (location.NestingLevel < lastNestingLevel) { // The previous node was a return, so this new node's parent is the previous node's grandparent lastParent = lastNewNode.Parent.Parent; } newNode.Parent = lastParent; lastParent.Children.Add(newNode); lastNewNode = newNode; lastNestingLevel = location.NestingLevel; } root.Children.ForEach(n => n.Parent = null); } return(root.Children); }
protected static void GenerateCodeForArguments(ILGenerator gen, CodeFlow cf, MethodBase member, SpelNode[] arguments) { var paramDescriptors = CodeFlow.ToDescriptors(member.GetParameterTypes()); var isVarargs = member.IsVarArgs(); if (isVarargs) { var childCount = arguments.Length; // The final parameter may or may not need packaging into an array, or nothing may // have been passed to satisfy the varargs and so something needs to be built. int p; // Fulfill all the parameter requirements except the last one for (p = 0; p < paramDescriptors.Length - 1; p++) { GenerateCodeForArgument(gen, cf, arguments[p], paramDescriptors[p]); } var lastChild = childCount == 0 ? null : arguments[childCount - 1]; var arrayType = paramDescriptors[paramDescriptors.Length - 1]; // Determine if the final passed argument is already suitably packaged in array // form to be passed to the method if (lastChild != null && arrayType.Equals(lastChild.ExitDescriptor)) { GenerateCodeForArgument(gen, cf, lastChild, paramDescriptors[p]); } else { var arrElemType = arrayType.Value.GetElementType(); var arrElemDesc = new TypeDescriptor(arrElemType); gen.Emit(OpCodes.Ldc_I4, childCount - p); gen.Emit(OpCodes.Newarr, arrElemType); // Package up the remaining arguments into the array var arrayindex = 0; while (p < childCount) { var child = arguments[p]; gen.Emit(OpCodes.Dup); gen.Emit(OpCodes.Ldc_I4, arrayindex++); GenerateCodeForArgument(gen, cf, child, arrElemDesc); gen.Emit(GetStelemInsn(arrElemType)); p++; } } } else { for (var i = 0; i < paramDescriptors.Length; i++) { GenerateCodeForArgument(gen, cf, arguments[i], paramDescriptors[i]); } } }
public override bool IsCompilable() { var left = LeftOperand; var right = RightOperand; return(left.IsCompilable() && right.IsCompilable() && CodeFlow.IsBooleanCompatible(left.ExitDescriptor) && CodeFlow.IsBooleanCompatible(right.ExitDescriptor)); }
public override void GenerateCode(DynamicMethod mv, CodeFlow cf) { // getLeftOperand().generateCode(mv, cf); // String leftDesc = getLeftOperand().exitTypeDescriptor; // String exitDesc = this.exitTypeDescriptor; // Assert.state(exitDesc != null, "No exit type descriptor"); // char targetDesc = exitDesc.charAt(0); // CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, leftDesc, targetDesc); // if (this.children.length > 1) // { // cf.enterCompilationScope(); // getRightOperand().generateCode(mv, cf); // String rightDesc = getRightOperand().exitTypeDescriptor; // cf.exitCompilationScope(); // CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); // switch (targetDesc) // { // case 'I': // mv.visitInsn(ISUB); // break; // case 'J': // mv.visitInsn(LSUB); // break; // case 'F': // mv.visitInsn(FSUB); // break; // case 'D': // mv.visitInsn(DSUB); // break; // default: // throw new IllegalStateException( // "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'"); // } // } // else // { // switch (targetDesc) // { // case 'I': // mv.visitInsn(INEG); // break; // case 'J': // mv.visitInsn(LNEG); // break; // case 'F': // mv.visitInsn(FNEG); // break; // case 'D': // mv.visitInsn(DNEG); // break; // default: // throw new IllegalStateException( // "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'"); // } // } // cf.pushDescriptor(this.exitTypeDescriptor); }
public override ITypedValue GetValueInternal(ExpressionState state) { var leftValue = LeftOperand.GetValueInternal(state).Value; var rightValue = RightOperand.GetValueInternal(state).Value; _leftActualDescriptor = CodeFlow.ToDescriptorFromObject(leftValue); _rightActualDescriptor = CodeFlow.ToDescriptorFromObject(rightValue); return(BooleanTypedValue.ForValue(!EqualityCheck(state.EvaluationContext, leftValue, rightValue))); }
protected internal TypeDescriptor ComputeExitDescriptor(object result, Type propertyReturnType) { if (propertyReturnType.IsValueType) { return(CodeFlow.ToDescriptor(propertyReturnType)); } return(CodeFlow.ToDescriptorFromObject(result)); }
public void GenerateInitCode(string constantFieldName, ILGenerator gen, CodeFlow codeflow, bool nested = false) { LocalBuilder listLocal = null; if (!nested) { // Get list on stack GenerateLoadListCode(gen, constantFieldName); // Save to local for easy access listLocal = gen.DeclareLocal(typeof(IList)); gen.Emit(OpCodes.Stloc, listLocal); } else { // Create nested list to work with gen.Emit(OpCodes.Newobj, _listConstr); gen.Emit(OpCodes.Castclass, typeof(IList)); } var childCount = ChildCount; for (var c = 0; c < childCount; c++) { if (!nested) { gen.Emit(OpCodes.Ldloc, listLocal); } else { gen.Emit(OpCodes.Dup); } // The children might be further lists if they are not constants. In this // situation do not call back into generateCode() because it will register another clinit adder. // Instead, directly build the list here: if (_children[c] is InlineList list) { list.GenerateInitCode(constantFieldName, gen, codeflow, true); } else { _children[c].GenerateCode(gen, codeflow); var lastDesc = codeflow.LastDescriptor(); if (CodeFlow.IsValueType(lastDesc)) { CodeFlow.InsertBoxIfNecessary(gen, lastDesc); } } gen.Emit(OpCodes.Callvirt, _addMethod); // Ignore int return gen.Emit(OpCodes.Pop); } }
public override void GenerateCode(DynamicMethod mv, CodeFlow cf) { // Method method = this.method; // Assert.state(method != null, "No method handle"); // String classDesc = method.getDeclaringClass().getName().replace('.', '/'); // generateCodeForArguments(mv, cf, method, this.children); // mv.visitMethodInsn(INVOKESTATIC, classDesc, method.getName(), // CodeFlow.createSignatureDescriptor(method), false); // cf.pushDescriptor(this.exitTypeDescriptor); }
public override void GenerateCode(ILGenerator gen, CodeFlow cf) { var constantFieldName = "inlineList$" + cf.NextFieldId(); cf.RegisterNewField(constantFieldName, new List <object>()); cf.RegisterNewInitGenerator((initGenerator, cflow) => { GenerateInitCode(constantFieldName, initGenerator, cflow); }); GenerateLoadListCode(gen, constantFieldName); cf.PushDescriptor(new TypeDescriptor(typeof(IList))); }
public override bool IsCompilable() { var condition = _children[0]; var left = _children[1]; var right = _children[2]; return(condition.IsCompilable() && left.IsCompilable() && right.IsCompilable() && CodeFlow.IsBooleanCompatible(condition.ExitDescriptor) && left.ExitDescriptor != null && right.ExitDescriptor != null); }
public override ITypedValue GetValueInternal(ExpressionState state) { var leftOperand = LeftOperand.GetValueInternal(state).Value; var rightOperand = RightOperand.GetValueInternal(state).Value; if (IsNumber(leftOperand) && IsNumber(rightOperand)) { var leftNumber = (IConvertible)leftOperand; var rightNumber = (IConvertible)rightOperand; if (leftNumber is decimal || rightNumber is decimal) { var leftVal = leftNumber.ToDecimal(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToDecimal(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } else if (leftNumber is double || rightNumber is double) { _exitTypeDescriptor = "D"; var leftVal = leftNumber.ToDouble(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToDouble(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } else if (leftNumber is float || rightNumber is float) { _exitTypeDescriptor = "F"; var leftVal = leftNumber.ToSingle(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToSingle(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } else if (leftNumber is long || rightNumber is long) { _exitTypeDescriptor = "J"; var leftVal = leftNumber.ToInt64(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToInt64(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } else if (CodeFlow.IsIntegerForNumericOp(leftNumber) || CodeFlow.IsIntegerForNumericOp(rightNumber)) { _exitTypeDescriptor = "I"; var leftVal = leftNumber.ToInt32(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToInt32(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } else { // Unknown Number subtypes -> best guess is double division var leftVal = leftNumber.ToDouble(CultureInfo.InvariantCulture); var rightVal = rightNumber.ToDouble(CultureInfo.InvariantCulture); return(new TypedValue(leftVal % rightVal)); } } return(state.Operate(Operation.MODULUS, leftOperand, rightOperand)); }
public void SelectPreviousNextCommandsTest() { CodeFlow codeFlow = SarifUtilities.CreateSingleThreadedCodeFlow(new[] { new ThreadFlowLocation { NestingLevel = 0, }, new ThreadFlowLocation { NestingLevel = 1, }, new ThreadFlowLocation { NestingLevel = 1, }, new ThreadFlowLocation { NestingLevel = 1, }, new ThreadFlowLocation { NestingLevel = 0, }, new ThreadFlowLocation { NestingLevel = 0, }, }); var analysisStep = new AnalysisStep(CodeFlowToTreeConverter.Convert(codeFlow, run: null, resultId: 0, runIndex: 0)); analysisStep.FindPrevious().Should().Be(null); analysisStep.FindNext().Should().Be(null); analysisStep.SelectedItem = analysisStep.TopLevelNodes[0]; analysisStep.FindPrevious().Should().Be(analysisStep.TopLevelNodes[0]); analysisStep.FindNext().Should().Be(analysisStep.TopLevelNodes[0].Children[0]); analysisStep.SelectedItem = analysisStep.TopLevelNodes[0].Children[0]; analysisStep.FindPrevious().Should().Be(analysisStep.TopLevelNodes[0]); analysisStep.FindNext().Should().Be(analysisStep.TopLevelNodes[0].Children[1]); analysisStep.SelectedItem = analysisStep.TopLevelNodes[0].Children[2]; analysisStep.FindPrevious().Should().Be(analysisStep.TopLevelNodes[0].Children[1]); analysisStep.FindNext().Should().Be(analysisStep.TopLevelNodes[1]); analysisStep.SelectedItem = analysisStep.TopLevelNodes[1]; analysisStep.FindPrevious().Should().Be(analysisStep.TopLevelNodes[0].Children[2]); analysisStep.FindNext().Should().Be(analysisStep.TopLevelNodes[2]); analysisStep.SelectedItem = analysisStep.TopLevelNodes[2]; analysisStep.FindPrevious().Should().Be(analysisStep.TopLevelNodes[1]); analysisStep.FindNext().Should().Be(analysisStep.TopLevelNodes[2]); }
protected override void Analyze(CodeFlow codeFlow, string codeFlowPointer) { var pointer = new JsonPointer(codeFlowPointer); JToken codeFlowToken = pointer.Evaluate(Context.InputLogToken); JProperty locationsProperty = codeFlowToken.Children<JProperty>() .FirstOrDefault(prop => prop.Name.Equals(SarifPropertyName.Locations, StringComparison.Ordinal)); if (locationsProperty != null) { JArray annotatedCodeLocationArray = locationsProperty.Value as JArray; string annotatedCodeLocationsPointer = codeFlowPointer.AtProperty(SarifPropertyName.Locations); ReportMissingStepProperty( annotatedCodeLocationArray, annotatedCodeLocationsPointer); ReportInvalidStepValues( codeFlow.Locations.ToArray(), annotatedCodeLocationArray, annotatedCodeLocationsPointer); } }
protected override void Analyze(CodeFlow codeFlow, string codeFlowPointer) { Analyze(codeFlow.Message, codeFlowPointer); }
/// <summary>Converts this instance to <see cref="Result"/>.</summary> /// <returns>This instance as an <see cref="Result"/>.</returns> public Result ToSarifIssue() { if (this.Locations.Length == 0) { throw new InvalidOperationException("At least one location must be present in a SARIF result."); } var result = new Result { RuleId = this.Id, }; result.SetProperty("Severity", this.Severity); if (!string.IsNullOrEmpty(this.VerboseMessage)) { result.Message = this.VerboseMessage; } else { result.Message = this.Message; } PhysicalLocation lastLocationConverted; if (this.Locations.Length == 1) { lastLocationConverted = this.Locations[0].ToSarifPhysicalLocation(); } else { var locations = new List<AnnotatedCodeLocation> { Capacity = this.Locations.Length }; foreach (CppCheckLocation loc in this.Locations) { locations.Add(new AnnotatedCodeLocation { PhysicalLocation = loc.ToSarifPhysicalLocation(), Importance = AnnotatedCodeLocationImportance.Essential }); } var flow = new CodeFlow { Locations = locations }; result.CodeFlows = new List<CodeFlow> { flow }; // In the N != 1 case, set the overall location's location to // the last entry in the execution flow. lastLocationConverted = locations[locations.Count - 1].PhysicalLocation; } result.Locations = new List<Location> { new Location { ResultFile = lastLocationConverted } }; return result; }