// Initializes the object with original string and translation.
        public CatalogEntry (Catalog owner, string str, string plural)
        {
			this.owner = owner;
			this.str = str;
			this.plural = plural;

			hasPlural = ! String.IsNullOrEmpty (plural);
			references = new List<string> ();
			autocomments = new List<string> ();
			translations = new List<string> ();
			isFuzzy = false;
			isModified = false;
			isAutomatic = false;
			validity = Validity.Unknown;
		}
Exemple #2
0
 /// <summary>
 ///  Creates an instance of Options2. Sets default values.
 /// </summary>
 /// <param name="x">x value of TubeSize. Half width of rectangle. </param>
 /// <param name="y">y value of TubeSize. Half height of rectangle.</param>
 /// <remarks>Default values: <para>
 /// Use relative values for calculation of TubeSize: Relativity = Relativity.Relative <para/>
 /// Delimiter = ';' <para/>
 /// Separator = '.' <para/>
 /// Don't save log file: log = new Log()<para/>
 /// Don't save image: reportFolder = ""<para/>
 /// Don't show window: showWindow = false<para/>
 /// Show all (valid and invalid): ShowValidity = Validity.All<para/>
 /// Always use normal drawing methods, never fast drawing methods: drawFastAbove = 0<para/>
 /// Always draw points: drawPointsBelow = Int32.MaxValue
 /// </para></remarks>
 public Options2(double x, double y)
 {
     this.x = x;
     this.y = y;
     relativity = Relativity.Relative;
     baseX = Double.NaN;
     baseY = Double.NaN;
     ratio = Double.NaN;
     log = new Log();
     reportFolder = "";
     showWindow = false;
     showValidity = Validity.All;
     drawFastAbove = 0;
     drawPointsBelow = Int32.MaxValue;
     drawLabelNumber = false;
 }
Exemple #3
0
 /// <summary>
 /// Creates an instance of Options1.
 /// </summary>
 /// <param name="value">Value of TubeSize.</param>
 /// <param name="axes">States, if value is x (half width of rectangle) or y (half height of rectangle).</param>
 /// /// <remarks>Default values: <para>
 /// Use relative values for calculation of TubeSize: Relativity = Relativity.Relative <para/>
 /// Delimiter = ';' <para/>
 /// Separator = '.' <para/>
 /// Don't save log file: log = new Log()<para/>
 /// Don't save image: reportFolder = ""<para/>
 /// Don't show window: showWindow = false<para/>
 /// Show all (valid and invalid): ShowValidity = Validity.All<para/>
 /// Always use normal drawing methods, never fast drawing methods: drawFastAbove = 0<para/>
 /// Always draw points: drawPointsBelow = Int32.MaxValue
 /// </para></remarks>
 public Options1(double value, Axes axes)
 {
     this.val = value;
     this.axes = axes;
     relativity = Relativity.Relative;
     baseX = Double.NaN;
     baseY = Double.NaN;
     ratio = Double.NaN;
     log = new Log();
     reportFolder = "";
     showWindow = false;
     showValidity = Validity.All;
     drawFastAbove = 0;
     drawPointsBelow = Int32.MaxValue;
     formerBaseAndRatio = false;
     drawLabelNumber = false;
 }
Exemple #4
0
        public void SetUpCallrForDebug(RuntimeCore runtimeCore, DSASM.Executive exec, ProcedureNode fNode, int pc, bool isBaseCall = false,
                                       CallSite callsite = null, List <StackValue> arguments         = null, List <List <ReplicationGuide> > replicationGuides = null, StackFrame stackFrame = null,
                                       List <StackValue> dotCallDimensions = null, bool hasDebugInfo = false, bool isMember = false, StackValue?thisPtr = null)
        {
            //ProtoCore.DSASM.Executive exec = core.CurrentExecutive.CurrentDSASMExec;

            DebugFrame debugFrame = new DebugFrame();

            debugFrame.IsBaseCall       = isBaseCall;
            debugFrame.Arguments        = arguments;
            debugFrame.IsMemberFunction = isMember;
            debugFrame.ThisPtr          = thisPtr;
            debugFrame.HasDebugInfo     = hasDebugInfo;

            if (CoreUtils.IsDisposeMethod(fNode.Name))
            {
                debugFrame.IsDisposeCall = true;
                ReturnPCFromDispose      = DebugEntryPC;
            }

            if (RunMode == Runmode.StepNext)
            {
                debugFrame.FunctionStepOver = true;
            }

            bool isReplicating      = false;
            bool isExternalFunction = false;

            // callsite is set to null for a base class constructor call in CALL
            if (callsite == null)
            {
                isReplicating      = false;
                isExternalFunction = false;

                SetUpCallr(ref debugFrame, isReplicating, isExternalFunction, exec);
                DebugStackFrame.Push(debugFrame);

                return;
            }

            // Comment Jun: A dot call does not replicate and  must be handled immediately
            if (fNode.Name == Constants.kDotMethodName)
            {
                isReplicating                = false;
                isExternalFunction           = false;
                debugFrame.IsDotCall         = true;
                debugFrame.DotCallDimensions = dotCallDimensions;

                SetUpCallr(ref debugFrame, isReplicating, isExternalFunction, exec);
                DebugStackFrame.Push(debugFrame);

                return;
            }

            List <List <ReplicationInstruction> > replicationTrials;
            bool willReplicate = callsite.WillCallReplicate(new Context(), arguments, replicationGuides, stackFrame, runtimeCore, out replicationTrials);

            // the inline conditional built-in is handled separately as 'WillCallReplicate' is always true in this case
            if (fNode.Name.Equals(Constants.kInlineConditionalMethodName))
            {
                // The inline conditional built-in is created only for associative blocks and needs to be handled separately as below
                InstructionStream istream = runtimeCore.DSExecutable.instrStreamList[CurrentBlockId];
                Validity.Assert(istream.language == Language.kAssociative);
                {
                    runtimeCore.DebugProps.InlineConditionOptions.isInlineConditional = true;
                    runtimeCore.DebugProps.InlineConditionOptions.startPc             = pc;

                    runtimeCore.DebugProps.InlineConditionOptions.endPc = FindEndPCForAssocGraphNode(pc, istream, fNode, exec.Properties.executingGraphNode, runtimeCore.Options.ExecuteSSA);


                    runtimeCore.DebugProps.InlineConditionOptions.instructionStream = runtimeCore.RunningBlock;
                    debugFrame.IsInlineConditional = true;
                }

                // no replication case
                if (willReplicate && replicationTrials.Count == 1)
                {
                    runtimeCore.DebugProps.InlineConditionOptions.ActiveBreakPoints.AddRange(runtimeCore.Breakpoints);

                    /*if (core.DebugProps.RunMode == Runmode.StepNext)
                     * {
                     *  core.Breakpoints.Clear();
                     * }*/

                    isReplicating      = false;
                    isExternalFunction = false;
                }
                else // an inline conditional call that replicates
                {
#if !__DEBUG_REPLICATE
                    // Clear all breakpoints for outermost replicated call
                    if (!DebugStackFrameContains(StackFrameFlagOptions.IsReplicating))
                    {
                        ActiveBreakPoints.AddRange(runtimeCore.Breakpoints);
                        runtimeCore.Breakpoints.Clear();
                    }
#endif
                    isExternalFunction = false;
                    isReplicating      = true;
                }
                SetUpCallr(ref debugFrame, isReplicating, isExternalFunction, exec, 0);

                DebugStackFrame.Push(debugFrame);

                return;
            }
            // Prevent breaking inside a function that is external except for dot calls
            // by clearing all breakpoints from outermost external function call
            // This check takes precedence over the replication check
            else if (fNode.IsExternal && fNode.Name != Constants.kDotMethodName)
            {
                // Clear all breakpoints
                if (!DebugStackFrameContains(StackFrameFlagOptions.IsExternalFunction) && fNode.Name != Constants.kFunctionRangeExpression)
                {
                    ActiveBreakPoints.AddRange(runtimeCore.Breakpoints);
                    runtimeCore.Breakpoints.Clear();
                }

                isExternalFunction = true;
                isReplicating      = false;
            }
            // Find if function call will replicate or not and if so
            // prevent stepping in by removing all breakpoints from outermost replicated call
            else if (willReplicate)
            {
#if !__DEBUG_REPLICATE
                // Clear all breakpoints for outermost replicated call
                if (!DebugStackFrameContains(StackFrameFlagOptions.IsReplicating))
                {
                    ActiveBreakPoints.AddRange(runtimeCore.Breakpoints);
                    runtimeCore.Breakpoints.Clear();
                }
#endif

                isReplicating      = true;
                isExternalFunction = false;
            }
            // For all other function calls
            else
            {
                isReplicating      = false;
                isExternalFunction = false;
            }

            SetUpCallr(ref debugFrame, isReplicating, isExternalFunction, exec);
            DebugStackFrame.Push(debugFrame);
        }
Exemple #5
0
 /// <summary>
 /// This method will return the string representation of the mirror data if it is available
 /// </summary>
 public string GetStringData()
 {
     Validity.Assert(this.runtimeCore != null);
     Validity.Assert(TargetExecutive != null);
     return(deprecateThisMirror.GetStringValue(mirrorData.GetStackValue(), TargetExecutive.rmem.Heap, blockDeclaration));
 }
Exemple #6
0
 protected virtual void EmitDoubleNode(ref ProtoCore.AST.AssociativeAST.DoubleNode doubleNode)
 {
     Validity.Assert(null != doubleNode);
     //EmitCode(doubleNode.value);
 }
Exemple #7
0
 public string GetType(Type type)
 {
     Validity.Assert(null != classTable);
     return(classTable.GetTypeName(type.UID));
 }
 public ValidationResult(Validity validity = Validity.Valid, params string[] reasons)
 {
     _validity = validity;
     _reasons = new List<string>(reasons);
 }
Exemple #9
0
        private void setLinkageValidity(Validity newValidity)
        {
            var oldValidity = LinkageValidity;
            if (newValidity == oldValidity)
            {
            return;
            }

            LinkageValidity = newValidity;
            var handlers = LinkageValidityChanged;
            handlers?.Invoke(this, oldValidity, newValidity);
        }
Exemple #10
0
 public override string ToScript()
 {
     Validity.Assert(ModuleName != null);
     importStatement = "import (" + '"'.ToString() + ModuleName + '"'.ToString() + ")";
     return(this.importStatement);
 }
        public CatalogEntry (Catalog owner, CatalogEntry dt)
		{
			this.owner = owner;
			str = dt.str;
			plural = dt.plural;
			hasPlural = dt.hasPlural;
			translations = new List<string> (dt.translations);
			references = new List<string> (dt.references);
			autocomments = new List<string> (dt.autocomments);
			isFuzzy = dt.isFuzzy;
			isModified = dt.isModified;
			isAutomatic = dt.isAutomatic;
            hasBadTokens = dt.hasBadTokens;
            moreFlags =dt.moreFlags;
            comment = dt.comment;
            validity = dt.validity;
            errorString = dt.errorString;
        }
Exemple #12
0
 // Sets the string.
 public void SetString(string str)
 {
     this.str = str;
     validity = Validity.Unknown;
 }
Exemple #13
0
        private static string Print(this NcaHolder ncaHolder)
        {
            Nca nca       = ncaHolder.Nca;
            int masterKey = Keyset.GetMasterKeyRevisionFromKeyGeneration(nca.Header.KeyGeneration);

            int colLen = 36;
            var sb     = new StringBuilder();

            sb.AppendLine();

            sb.AppendLine("NCA:");
            PrintItem(sb, colLen, "Magic:", MagicToString(nca.Header.Magic));
            PrintItem(sb, colLen, $"Fixed-Key Signature{nca.VerifyHeaderSignature().GetValidityString()}:", nca.Header.Signature1.ToArray());
            PrintItem(sb, colLen, $"NPDM Signature{nca.VerifySignature2().GetValidityString()}:", nca.Header.Signature2.ToArray());
            PrintItem(sb, colLen, "Content Size:", $"0x{nca.Header.NcaSize:x12}");
            PrintItem(sb, colLen, "TitleID:", $"{nca.Header.TitleId:X16}");
            PrintItem(sb, colLen, "SDK Version:", nca.Header.SdkVersion);
            PrintItem(sb, colLen, "Distribution type:", nca.Header.DistributionType);
            PrintItem(sb, colLen, "Content Type:", nca.Header.ContentType);
            PrintItem(sb, colLen, "Master Key Revision:", $"{masterKey} ({Util.GetKeyRevisionSummary(masterKey)})");
            PrintItem(sb, colLen, "Encryption Type:", $"{(nca.Header.HasRightsId ? "Titlekey crypto" : "Standard crypto")}");

            if (nca.Header.HasRightsId)
            {
                PrintItem(sb, colLen, "Rights ID:", nca.Header.RightsId.ToArray());
            }
            else
            {
                PrintItem(sb, colLen, "Key Area Encryption Key:", nca.Header.KeyAreaKeyIndex);
                sb.AppendLine("Key Area (Encrypted):");
                for (int i = 0; i < 4; i++)
                {
                    PrintItem(sb, colLen, $"    Key {i} (Encrypted):", nca.Header.GetEncryptedKey(i).ToArray());
                }

                sb.AppendLine("Key Area (Decrypted):");
                for (int i = 0; i < 4; i++)
                {
                    PrintItem(sb, colLen, $"    Key {i} (Decrypted):", nca.GetDecryptedKey(i));
                }
            }

            PrintSections();

            return(sb.ToString());

            void PrintSections()
            {
                sb.AppendLine("Sections:");

                for (int i = 0; i < 4; i++)
                {
                    if (!nca.Header.IsSectionEnabled(i))
                    {
                        continue;
                    }

                    NcaFsHeader sectHeader = nca.Header.GetFsHeader(i);
                    bool        isExefs    = nca.Header.ContentType == ContentType.Program && i == 0;

                    sb.AppendLine($"    Section {i}:");
                    PrintItem(sb, colLen, "        Offset:", $"0x{nca.Header.GetSectionStartOffset(i):x12}");
                    PrintItem(sb, colLen, "        Size:", $"0x{nca.Header.GetSectionSize(i):x12}");
                    PrintItem(sb, colLen, "        Partition Type:", (isExefs ? "ExeFS" : sectHeader.FormatType.ToString()) + (sectHeader.IsPatchSection() ? " patch" : ""));
                    PrintItem(sb, colLen, "        Section CTR:", $"{sectHeader.Counter:x16}");
                    PrintItem(sb, colLen, "        Section Validity:", $"{ncaHolder.Validities[i]}");

                    switch (sectHeader.HashType)
                    {
                    case NcaHashType.Sha256:
                        PrintSha256Hash(sectHeader, i);
                        break;

                    case NcaHashType.Ivfc:
                        Validity masterHashValidity = nca.ValidateSectionMasterHash(i);

                        PrintIvfcHashNew(sb, colLen, 8, sectHeader.GetIntegrityInfoIvfc(), IntegrityStorageType.RomFs, masterHashValidity);
                        break;

                    default:
                        sb.AppendLine("        Unknown/invalid superblock!");
                        break;
                    }
                }
            }

            void PrintSha256Hash(NcaFsHeader sect, int index)
            {
                NcaFsIntegrityInfoSha256 hashInfo = sect.GetIntegrityInfoSha256();

                PrintItem(sb, colLen, $"        Master Hash{nca.ValidateSectionMasterHash(index).GetValidityString()}:", hashInfo.MasterHash.ToArray());
                sb.AppendLine($"        Hash Table:");

                PrintItem(sb, colLen, "            Offset:", $"0x{hashInfo.GetLevelOffset(0):x12}");
                PrintItem(sb, colLen, "            Size:", $"0x{hashInfo.GetLevelSize(0):x12}");
                PrintItem(sb, colLen, "            Block Size:", $"0x{hashInfo.BlockSize:x}");
                PrintItem(sb, colLen, "        PFS0 Offset:", $"0x{hashInfo.GetLevelOffset(1):x12}");
                PrintItem(sb, colLen, "        PFS0 Size:", $"0x{hashInfo.GetLevelSize(1):x12}");
            }
        }
Exemple #14
0
 internal static void WriteFloat(this XmlWriter file, float val, string elementName, string attributeName, Validity valid)
 {
     file.WriteStartElement(elementName);
     file.WriteAttributeString(attributeName, val.ToString(FORMAT_FLOAT));
     file.WriteAttributeString("Validity", valid.ToString());
     file.WriteEndElement();
 }
Exemple #15
0
 internal static void Write2D <T>(this XmlWriter file, T point, string elementName, string attributeName, Validity valid) where T : NormalizedPoint2D
 {
     file.WriteStartElement(elementName);
     file.WriteAttributeString(attributeName, string.Format("({0}, {1})",
                                                            point.X.ToString(FORMAT_FLOAT), point.Y.ToString(FORMAT_FLOAT)));
     file.WriteAttributeString("Validity", valid.ToString());
     file.WriteEndElement();
 }
Exemple #16
0
 internal static bool Valid(this Validity validity)
 {
     return(validity == Validity.Valid);
 }
		// Sets the string.
		public void SetString (string str)
		{
			this.str = str;
			validity = Validity.Unknown;
		}
Exemple #18
0
 public static string GetMethodName(StackValue pointer, Interpreter dsi)
 {
     Validity.Assert(pointer.IsFunctionPointer);
     return(dsi.runtime.exe.procedureTable[0].procList[(int)pointer.opdata].name);
 }
		// Sets all translations.
		public void SetTranslations (string[] translations)
		{
			this.translations = new List<string> (translations);
			
			validity = Validity.Unknown;
			MarkOwnerDirty ();
		}
Exemple #20
0
        public StackValue Evaluate(List <StackValue> args, StackFrame stackFrame)
        {
            // Build the stackframe
            var runtimeCore = interpreter.runtime.Core;

            int        classScopeCaller = stackFrame.ClassScope;
            int        returnAddr       = stackFrame.ReturnPC;
            int        blockDecl        = procNode.runtimeIndex;
            int        blockCaller      = stackFrame.FunctionCallerBlock;
            int        framePointer     = runtimeCore.Rmem.FramePointer;
            StackValue thisPtr          = StackValue.BuildPointer(Constants.kInvalidIndex);

            // Functoion has variable input parameter. This case only happen
            // for FFI functions whose last parameter's type is (params T[]).
            // In this case, we need to convert argument list from
            //
            //    {a1, a2, ..., am, v1, v2, ..., vn}
            //
            // to
            //
            //    {a1, a2, ..., am, {v1, v2, ..., vn}}
            if (procNode.isVarArg)
            {
                int paramCount = procNode.argInfoList.Count;
                Validity.Assert(paramCount >= 1);

                int varParamCount = args.Count - (paramCount - 1);
                var varParams     = args.GetRange(paramCount - 1, varParamCount).ToArray();
                args.RemoveRange(paramCount - 1, varParamCount);

                var packedParams = interpreter.runtime.Core.Heap.AllocateArray(varParams, null);
                args.Add(packedParams);
            }

            bool isCallingMemberFunciton = procNode.classScope != Constants.kInvalidIndex &&
                                           !procNode.isConstructor &&
                                           !procNode.isStatic;

            bool isValidThisPointer = true;

            if (isCallingMemberFunciton)
            {
                Validity.Assert(args.Count >= 1);
                thisPtr = args[0];
                if (thisPtr.IsArray)
                {
                    isValidThisPointer = ArrayUtils.GetFirstNonArrayStackValue(thisPtr, ref thisPtr, runtimeCore);
                }
                else
                {
                    args.RemoveAt(0);
                }
            }

            if (!isValidThisPointer || (!thisPtr.IsPointer && !thisPtr.IsArray))
            {
                runtimeCore.RuntimeStatus.LogWarning(WarningID.kDereferencingNonPointer,
                                                     WarningMessage.kDeferencingNonPointer);
                return(StackValue.Null);
            }

            var callerType = stackFrame.StackFrameType;

            interpreter.runtime.TX = StackValue.BuildCallingConversion((int)ProtoCore.DSASM.CallingConvention.BounceType.kImplicit);

            StackValue svBlockDecl = StackValue.BuildBlockIndex(blockDecl);

            interpreter.runtime.SX = svBlockDecl;

            var repGuides = new List <List <ProtoCore.ReplicationGuide> >();

            List <StackValue> registers = new List <StackValue>();

            interpreter.runtime.SaveRegisters(registers);
            var newStackFrame = new StackFrame(thisPtr,
                                               classScopeCaller,
                                               1,
                                               returnAddr,
                                               blockDecl,
                                               blockCaller,
                                               callerType,
                                               StackFrameType.kTypeFunction,
                                               0,   // depth
                                               framePointer,
                                               registers,
                                               null);

            bool isInDebugMode = runtimeCore.Options.IDEDebugMode &&
                                 runtimeCore.ExecMode != InterpreterMode.kExpressionInterpreter;

            if (isInDebugMode)
            {
                runtimeCore.DebugProps.SetUpCallrForDebug(runtimeCore,
                                                          interpreter.runtime,
                                                          procNode,
                                                          returnAddr - 1,
                                                          false,
                                                          callsite,
                                                          args,
                                                          repGuides,
                                                          newStackFrame);
            }

            StackValue rx = callsite.JILDispatchViaNewInterpreter(
                new Runtime.Context(),
                args,
                repGuides,
                newStackFrame,
                runtimeCore);

            if (isInDebugMode)
            {
                runtimeCore.DebugProps.RestoreCallrForNoBreak(runtimeCore, procNode);
            }

            interpreter.runtime.DecRefCounter(rx);

            return(rx);
        }
Exemple #21
0
 public void EditValidity(Validity validity, string reason = null)
 {
     _validity = validity;
     if (_validity == Validity.Valid) Reasons.Clear();
     else if (!String.IsNullOrEmpty(reason)) Reasons.Add(reason);
 }
Exemple #22
0
        private void setSourceValidity(Validity newValidity)
        {
            var oldValidity = SourceValidity;
            if (newValidity == oldValidity)
            {
            return;
            }

            SourceValidity = newValidity;
            var handlers = SourceValidityChanged;
            handlers?.Invoke(this, oldValidity, newValidity);
        }
Exemple #23
0
 public void AddDLLExtensionAppType(System.Type type)
 {
     Validity.Assert(DllTypesToLoad != null);
     DllTypesToLoad.Add(type);
 }
Exemple #24
0
        public XciHeader(KeySet keySet, Stream stream)
        {
            using (var reader = new BinaryReader(stream, Encoding.Default, true))
            {
                Signature = reader.ReadBytes(SignatureSize);
                Magic     = reader.ReadAscii(4);
                if (Magic != HeaderMagic)
                {
                    throw new InvalidDataException("Invalid XCI file: Header magic invalid.");
                }

                reader.BaseStream.Position = SignatureSize;
                byte[] sigData = reader.ReadBytes(SignatureSize);
                reader.BaseStream.Position = SignatureSize + 4;

                SignatureValidity = CryptoOld.Rsa2048Pkcs1Verify(sigData, Signature, _xciHeaderPubk);

                RomAreaStartPage    = reader.ReadInt32();
                BackupAreaStartPage = reader.ReadInt32();
                byte keyIndex = reader.ReadByte();
                KekIndex          = (byte)(keyIndex >> 4);
                TitleKeyDecIndex  = (byte)(keyIndex & 7);
                GameCardSize      = (GameCardSizeInternal)reader.ReadByte();
                CardHeaderVersion = reader.ReadByte();
                Flags             = (GameCardAttribute)reader.ReadByte();
                PackageId         = reader.ReadUInt64();
                ValidDataEndPage  = reader.ReadInt64();
                AesCbcIv          = reader.ReadBytes(Aes.KeySize128);
                Array.Reverse(AesCbcIv);
                RootPartitionOffset     = reader.ReadInt64();
                RootPartitionHeaderSize = reader.ReadInt64();
                RootPartitionHeaderHash = reader.ReadBytes(Sha256.DigestSize);
                InitialDataHash         = reader.ReadBytes(Sha256.DigestSize);
                SelSec      = reader.ReadInt32();
                SelT1Key    = reader.ReadInt32();
                SelKey      = reader.ReadInt32();
                LimAreaPage = reader.ReadInt32();

                if (keySet != null && !keySet.XciHeaderKey.IsZeros())
                {
                    byte[] encHeader = reader.ReadBytes(EncryptedHeaderSize);
                    var    decHeader = new byte[EncryptedHeaderSize];
                    Aes.DecryptCbc128(encHeader, decHeader, keySet.XciHeaderKey, AesCbcIv);

                    using (var decreader = new BinaryReader(new MemoryStream(decHeader)))
                    {
                        FwVersion      = decreader.ReadUInt64();
                        AccCtrl1       = (CardClockRate)decreader.ReadInt32();
                        Wait1TimeRead  = decreader.ReadInt32();
                        Wait2TimeRead  = decreader.ReadInt32();
                        Wait1TimeWrite = decreader.ReadInt32();
                        Wait2TimeWrite = decreader.ReadInt32();
                        FwMode         = decreader.ReadInt32();
                        UppVersion     = decreader.ReadInt32();
                        decreader.BaseStream.Position += 4;
                        UppHash = decreader.ReadBytes(8);
                        UppId   = decreader.ReadUInt64();
                    }
                }

                ImageHash = new byte[Sha256.DigestSize];
                Sha256.GenerateSha256Hash(sigData, ImageHash);

                reader.BaseStream.Position = RootPartitionOffset;
                byte[] headerBytes = reader.ReadBytes((int)RootPartitionHeaderSize);

                Span <byte> actualHeaderHash = stackalloc byte[Sha256.DigestSize];
                Sha256.GenerateSha256Hash(headerBytes, actualHeaderHash);

                PartitionFsHeaderValidity = Utilities.SpansEqual(RootPartitionHeaderHash, actualHeaderHash) ? Validity.Valid : Validity.Invalid;
            }
        }
Exemple #25
0
 protected virtual void EmitIntNode(ref ProtoCore.AST.AssociativeAST.IntNode intNode)
 {
     Validity.Assert(null != intNode);
     //EmitCode(intNode.value);
 }
Exemple #26
0
        public void SetTypeSystem()
        {
            Validity.Assert(null == classTable);
            if (null != classTable)
            {
                return;
            }

            classTable = new DSASM.ClassTable();

            classTable.Reserve((int)PrimitiveType.kMaxPrimitives);

            ClassNode cnode;

            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Array, size = 0, rank = 5, symbols = null, vtable = null, typeSystem = this
            };

            /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
             * cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
             * cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
             * cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
             * cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
             */
            cnode.classId = (int)PrimitiveType.kTypeArray;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeArray);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Double, size = 0, rank = 4, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceDoubleToIntScore);
            cnode.classId = (int)PrimitiveType.kTypeDouble;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeDouble);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Int, size = 0, rank = 3, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceIntToDoubleScore);
            cnode.classId = (int)PrimitiveType.kTypeInt;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeInt);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Bool, size = 0, rank = 2, symbols = null, vtable = null, typeSystem = this
            };
            // if convert operator to method call, without the following statement
            // a = true + 1 will fail, because _add expects two integers
            //cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.classId = (int)PrimitiveType.kTypeBool;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeBool);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Char, size = 0, rank = 1, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);

            cnode.classId = (int)PrimitiveType.kTypeChar;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeChar);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.String, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.classId = (int)PrimitiveType.kTypeString;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeString);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Var, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };

            /*cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            *  cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            *  cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            *  cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            *  cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);*/
            cnode.classId = (int)PrimitiveType.kTypeVar;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeVar);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Null, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeDouble, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeBool, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeChar, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeString, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.classId = (int)PrimitiveType.kTypeNull;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeNull);

            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.Void, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.classId = (int)PrimitiveType.kTypeVoid;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeVoid);

            //
            //
            cnode = new ClassNode {
                name = "hostentityid", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.classId = (int)PrimitiveType.kTypeHostEntityID;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeHostEntityID);
            //
            //
            cnode = new ClassNode {
                name = "pointer_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            // if convert operator to method call, without the following statement,
            // a = b.c + d.e will fail, b.c and d.e are resolved as pointer and _add method requires two integer
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.classId = (int)PrimitiveType.kTypePointer;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypePointer);
            //
            //
            cnode = new ClassNode {
                name = DSDefinitions.Keyword.FunctionPointer, size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.coerceTypes.Add((int)PrimitiveType.kTypeInt, (int)ProtoCore.DSASM.ProcedureDistance.kCoerceScore);
            cnode.classId = (int)PrimitiveType.kTypeFunctionPointer;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeFunctionPointer);

            //
            //
            cnode = new ClassNode {
                name = "return_reserved", size = 0, rank = 0, symbols = null, vtable = null, typeSystem = this
            };
            cnode.classId = (int)PrimitiveType.kTypeReturn;
            classTable.SetClassNodeAt(cnode, (int)PrimitiveType.kTypeReturn);
        }
Exemple #27
0
 protected virtual void EmitNullNode(ref ProtoCore.AST.AssociativeAST.NullNode nullNode)
 {
     Validity.Assert(null != nullNode);
     //EmitCode("null");
 }
Exemple #28
0
 public string GetType(int UID)
 {
     Validity.Assert(null != classTable);
     return(classTable.GetTypeName(UID));
 }
Exemple #29
0
        public static StackValue Coerce(StackValue sv, Type targetType, Core core)
        {
            //@TODO(Jun): FIX ME - abort coersion for default args
            if (sv.optype == AddressType.DefaultArg)
            {
                return(sv);
            }

            if (!(
                    (int)sv.metaData.type == targetType.UID ||
                    (core.ClassTable.ClassNodes[(int)sv.metaData.type].ConvertibleTo(targetType.UID)) ||
                    sv.optype == AddressType.ArrayPointer))
            {
                core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kConversionNotPossible, ProtoCore.RuntimeData.WarningMessage.kConvertNonConvertibleTypes);
                return(StackUtils.BuildNull());
            }



            //if it's an array
            if (sv.optype == AddressType.ArrayPointer && !targetType.IsIndexable && targetType.rank != DSASM.Constants.kUndefinedRank)// && targetType.UID != (int)PrimitiveType.kTypeVar)
            {
                //This is an array rank reduction
                //this may only be performed in recursion and is illegal here
                string errorMessage = String.Format(ProtoCore.RuntimeData.WarningMessage.kConvertArrayToNonArray, core.TypeSystem.GetType(targetType.UID));
                core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kConversionNotPossible, errorMessage);
                return(StackUtils.BuildNull());
            }


            if (sv.optype == AddressType.ArrayPointer && targetType.IsIndexable)
            {
                Validity.Assert(ArrayUtils.IsArray(sv));

                //We're being asked to convert an array into an array
                //walk over the structure converting each othe elements

                if (targetType.UID == (int)PrimitiveType.kTypeVar && targetType.rank == DSASM.Constants.kArbitraryRank && core.Heap.IsTemporaryPointer(sv))
                {
                    return(sv);
                }

                HeapElement  he        = core.Heap.Heaplist[(int)sv.opdata];
                StackValue[] newSubSVs = new StackValue[he.VisibleSize];

                //Validity.Assert(targetType.rank != -1, "Arbitrary rank array conversion not yet implemented {2EAF557F-62DE-48F0-9BFA-F750BBCDF2CB}");

                //Decrease level of reductions by one
                Type newTargetType = new Type();
                newTargetType.UID = targetType.UID;
                if (targetType.rank != ProtoCore.DSASM.Constants.kArbitraryRank)
                {
                    newTargetType.rank        = targetType.rank - 1;
                    newTargetType.IsIndexable = newTargetType.rank > 0;
                }
                else
                {
                    if (ArrayUtils.GetMaxRankForArray(sv, core) == 1)
                    {
                        //Last unpacking
                        newTargetType.rank        = 0;
                        newTargetType.IsIndexable = false;
                    }
                    else
                    {
                        newTargetType.rank        = ProtoCore.DSASM.Constants.kArbitraryRank;
                        newTargetType.IsIndexable = true;
                    }
                }


                for (int i = 0; i < he.VisibleSize; i++)
                {
                    StackValue coercedValue = Coerce(he.Stack[i], newTargetType, core);
                    GCUtils.GCRetain(coercedValue, core);
                    newSubSVs[i] = coercedValue;
                }

                StackValue newSV = HeapUtils.StoreArray(newSubSVs, core);
                return(newSV);
            }

            if (sv.optype != AddressType.ArrayPointer && sv.optype != AddressType.Null &&
                targetType.IsIndexable &&
                targetType.rank != DSASM.Constants.kArbitraryRank)
            {
                //We're being asked to promote the value into an array
                if (targetType.rank == 1)
                {
                    Type newTargetType = new Type();
                    newTargetType.UID         = targetType.UID;
                    newTargetType.IsIndexable = false;
                    newTargetType.Name        = targetType.Name;
                    newTargetType.rank        = 0;


                    //Upcast once
                    StackValue coercedValue = Coerce(sv, newTargetType, core);
                    GCUtils.GCRetain(coercedValue, core);
                    StackValue newSv = HeapUtils.StoreArray(new StackValue[] { coercedValue }, core);
                    return(newSv);
                }
                else
                {
                    Validity.Assert(targetType.rank > 1, "Target rank should be greater than one for this clause");

                    Type newTargetType = new Type();
                    newTargetType.UID         = targetType.UID;
                    newTargetType.IsIndexable = true;
                    newTargetType.Name        = targetType.Name;
                    newTargetType.rank        = targetType.rank - 1;


                    //Upcast once
                    StackValue coercedValue = Coerce(sv, newTargetType, core);
                    GCUtils.GCRetain(coercedValue, core);
                    StackValue newSv = HeapUtils.StoreArray(new StackValue[] { coercedValue }, core);
                    return(newSv);
                }
            }


            if (sv.optype == AddressType.Pointer)
            {
                StackValue ret = ClassCoerece(sv, targetType, core);
                return(ret);
            }

            //If it's anything other than array, just create a new copy
            switch (targetType.UID)
            {
            case (int)PrimitiveType.kInvalidType:
                Validity.Assert(false, "Can't convert invalid type");
                break;

            case (int)PrimitiveType.kTypeBool:
                return(sv.AsBoolean(core));

            case (int)PrimitiveType.kTypeChar:
            {
                StackValue newSV = sv.ShallowClone();
                newSV.metaData = new MetaData {
                    type = (int)PrimitiveType.kTypeChar
                };
                return(newSV);
            }

            case (int)PrimitiveType.kTypeDouble:
                return(sv.AsDouble());

            case (int)PrimitiveType.kTypeFunctionPointer:
                if (sv.metaData.type != (int)PrimitiveType.kTypeFunctionPointer)
                {
                    core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToFunction);
                    return(StackUtils.BuildNull());
                }
                return(sv.ShallowClone());

            case (int)PrimitiveType.kTypeHostEntityID:
            {
                StackValue newSV = sv.ShallowClone();
                newSV.metaData = new MetaData {
                    type = (int)PrimitiveType.kTypeHostEntityID
                };
                return(newSV);
            }

            case (int)PrimitiveType.kTypeInt:
            {
                if (sv.metaData.type == (int)PrimitiveType.kTypeDouble)
                {
                    core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeConvertionCauseInfoLoss, ProtoCore.RuntimeData.WarningMessage.kConvertDoubleToInt);
                }
                return(sv.AsInt());
            }

            case (int)PrimitiveType.kTypeNull:
            {
                if (sv.metaData.type != (int)PrimitiveType.kTypeNull)
                {
                    core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToNull);
                    return(StackUtils.BuildNull());
                }
                return(sv.ShallowClone());
            }

            case (int)PrimitiveType.kTypePointer:
            {
                if (sv.metaData.type != (int)PrimitiveType.kTypeNull)
                {
                    core.RuntimeStatus.LogWarning(RuntimeData.WarningID.kTypeMismatch, ProtoCore.RuntimeData.WarningMessage.kFailToConverToPointer);
                    return(StackUtils.BuildNull());
                }
                StackValue ret = sv.ShallowClone();
                return(ret);
            }

            case (int)PrimitiveType.kTypeString:
            {
                StackValue newSV = sv.ShallowClone();
                newSV.metaData = new MetaData {
                    type = (int)PrimitiveType.kTypeString
                };
                if (sv.metaData.type == (int)PrimitiveType.kTypeChar)
                {
                    char ch = ProtoCore.Utils.EncodingUtils.ConvertInt64ToCharacter(newSV.opdata);
                    newSV = StackUtils.BuildString(ch.ToString(), core.Heap);
                }
                return(newSV);
            }

            case (int)PrimitiveType.kTypeVar:
            {
                return(sv);
            }


            case (int)PrimitiveType.kTypeArray:
            {
                HeapElement  he        = core.Heap.Heaplist[(int)sv.opdata];
                StackValue[] newSubSVs = new StackValue[he.VisibleSize];

                for (int i = 0; i < he.VisibleSize; i++)
                {
                    StackValue coercedValue = Coerce(he.Stack[i], targetType, core);
                    GCUtils.GCRetain(coercedValue, core);
                    newSubSVs[i] = coercedValue;
                }

                StackValue newSV = HeapUtils.StoreArray(newSubSVs, core);
                return(newSV);
            }


            default:
                if (sv.optype == AddressType.Null)
                {
                    return(StackUtils.BuildNull());
                }
                else
                {
                    throw new NotImplementedException("Requested coercion not implemented");
                }
            }



            throw new NotImplementedException("Requested coercion not implemented");
        }
Exemple #30
0
 public int GetType(string ident)
 {
     Validity.Assert(null != classTable);
     return(classTable.IndexOf(ident));
 }
Exemple #31
0
 /// <summary>
 ///  Retrieve the data associated with this RuntimeMirror
 /// </summary>
 /// <returns></returns>
 public MirrorData GetData()
 {
     Validity.Assert(mirrorData != null);
     return(mirrorData);
 }
Exemple #32
0
        public static bool CheckInvalidArrayCoersion(FunctionEndPoint fep, List <StackValue> reducedSVs, ClassTable classTable, RuntimeCore runtimeCore, bool allowArrayPromotion)
        {
            for (int i = 0; i < reducedSVs.Count; i++)
            {
                Type typ = fep.FormalParams[i];
                if (typ.UID == (int)ProtoCore.PrimitiveType.kInvalidType)
                {
                    return(true);
                }

                if (!typ.IsIndexable)
                {
                    continue; //It wasn't an array param, skip
                }
                //Compute the type of target param
                if (!allowArrayPromotion)
                {
                    Validity.Assert(reducedSVs[i].IsArray, "This should be an array otherwise this shouldn't have passed previous tests");
                }


                if (!allowArrayPromotion)
                {
                    if (typ.rank != ArrayUtils.GetMaxRankForArray(reducedSVs[i], runtimeCore) &&
                        typ.rank != DSASM.Constants.kArbitraryRank)
                    {
                        return(true); //Invalid co-ercsion
                    }
                }
                else
                {
                    if (typ.rank < ArrayUtils.GetMaxRankForArray(reducedSVs[i], runtimeCore) &&
                        typ.rank != DSASM.Constants.kArbitraryRank)
                    {
                        return(true); //Invalid co-ercsion
                    }
                }


                Dictionary <ClassNode, int> arrayTypes = ArrayUtils.GetTypeStatisticsForArray(reducedSVs[i], runtimeCore);

                ClassNode cn = null;

                if (arrayTypes.Count == 0)
                {
                    //This was an empty array
                    Validity.Assert(cn == null, "If it was an empty array, there shouldn't be a type node");
                    cn = runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull];
                }
                else if (arrayTypes.Count == 1)
                {
                    //UGLY, get the key out of the array types, of which there is only one
                    foreach (ClassNode key in arrayTypes.Keys)
                    {
                        cn = key;
                    }
                }
                else if (arrayTypes.Count > 1)
                {
                    ClassNode commonBaseType = ArrayUtils.GetGreatestCommonSubclassForArray(reducedSVs[i], runtimeCore);

                    if (commonBaseType == null)
                    {
                        throw new ProtoCore.Exceptions.ReplicationCaseNotCurrentlySupported("Array with no common superclass not yet supported: {0C644179-14F5-4172-8EF8-A2F3739901B2}");
                    }

                    cn = commonBaseType; //From now on perform tests on the commmon base type
                }



                ClassNode argTypeNode = classTable.ClassNodes[typ.UID];

                //cn now represents the class node of the argument
                //argTypeNode represents the class node of the argument



                bool isNotExactTypeMatch  = cn != argTypeNode;
                bool argumentsNotNull     = cn != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull];
                bool recievingTypeNotAVar = argTypeNode != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeVar];
                bool isNotConvertible     = !cn.ConvertibleTo(typ.UID);

                //bool isCalleeVar = cn == core.classTable.list[(int) PrimitiveType.kTypeVar];


                //Is it an invalid conversion?
                if (isNotExactTypeMatch && argumentsNotNull && recievingTypeNotAVar && isNotConvertible) // && !isCalleeVar)
                {
                    return(true);                                                                        //It's an invalid coersion
                }
            }

            return(false);
        }
Exemple #33
0
 public TubeReport()
 {
     validity = Validity.Undefined;
 }
Exemple #34
0
 public FunctionGroup(List <FunctionEndPoint> rhs)
 {
     Validity.Assert(null != rhs);
     Validity.Assert(null == FunctionEndPoints);
     FunctionEndPoints = new List <FunctionEndPoint>(rhs);
 }
		// Sets the translation. Changes "translated" status to true if \a t is not empty.
		public void SetTranslation (string translation, int index)
		{
			while (index >= translations.Count)
				translations.Add (String.Empty);
			
			if (translations[index] != translation) {
				translations[index] = translation;
				
				validity = Validity.Unknown;
				MarkOwnerDirty ();
			}
		}
Exemple #36
0
 public TubeReport()
 {
     validity = Validity.Undefined;
 }
 public ValidationResult(Validity validity = Validity.Valid, params string[] reasons)
 {
     _validity = validity;
     _reasons  = new List <string>(reasons);
 }
Exemple #38
0
        public override StackValue Execute(ProtoCore.Runtime.Context c, List <StackValue> formalParameters, ProtoCore.DSASM.StackFrame stackFrame, RuntimeCore runtimeCore)
        {   //  ensure there is no data race, function resolution and execution happens in parallel
            //  but for FFI we want it to be serial cause the code we are calling into may not cope
            //  with parallelism.
            //
            //  we are always looking and putting our function pointers in handler with each lang
            //  so better lock for FFIHandler (being static) it  will be good object to lock
            //
            lock (FFIHandlers)
            {
                Interpreter interpreter = new Interpreter(runtimeCore, true);

                // Setup the stack frame data
                StackValue svThisPtr    = stackFrame.ThisPtr;
                int        ci           = activation.JILRecord.classIndex;
                int        fi           = activation.JILRecord.funcIndex;
                int        returnAddr   = stackFrame.ReturnPC;
                int        blockDecl    = stackFrame.FunctionBlock;
                int        blockCaller  = stackFrame.FunctionCallerBlock;
                int        framePointer = runtimeCore.RuntimeMemory.FramePointer;
                int        locals       = activation.JILRecord.locals;


                FFIHandler          handler = FFIHandlers[activation.ModuleType];
                FFIActivationRecord r       = activation;
                string className            = "";
                if (activation.JILRecord.classIndex > 0)
                {
                    className = runtimeCore.DSExecutable.classTable.ClassNodes[activation.JILRecord.classIndex].Name;
                }

                bool gcThisPtr = false;
                List <ProtoCore.Type> argTypes = new List <Type>(r.ParameterTypes);

                ProcedureNode fNode = null;
                if (ProtoCore.DSASM.Constants.kInvalidIndex != ci)
                {
                    fNode = interpreter.runtime.exe.classTable.ClassNodes[ci].ProcTable.procList[fi];
                }

                // Check if this is a 'this' pointer function overload that was generated by the compiler
                if (null != fNode && fNode.IsAutoGeneratedThisProc)
                {
                    int  thisPtrIndex = 0;
                    bool isStaticCall = svThisPtr.IsPointer && Constants.kInvalidPointer == (int)svThisPtr.opdata;
                    if (isStaticCall)
                    {
                        thisPtrIndex = formalParameters.Count - 1;
                    }
                    argTypes.RemoveAt(thisPtrIndex);

                    // Comment Jun: Execute() can handle a null this pointer.
                    // But since we dont even need to to reach there if we dont have a valid this pointer, then just return null
                    if (formalParameters[thisPtrIndex].IsNull)
                    {
                        runtimeCore.RuntimeStatus.LogWarning(ProtoCore.Runtime.WarningID.kDereferencingNonPointer, Resources.kDeferencingNonPointer);
                        return(StackValue.Null);
                    }

                    // These are the op types allowed.
                    Validity.Assert(formalParameters[thisPtrIndex].IsPointer ||
                                    formalParameters[thisPtrIndex].IsDefaultArgument);

                    svThisPtr = formalParameters[thisPtrIndex];
                    gcThisPtr = true;

                    formalParameters.RemoveAt(thisPtrIndex);
                }

                FFIFunctionPointer functionPointer = handler.GetFunctionPointer(r.ModuleName, className, r.FunctionName, argTypes, r.ReturnType);
                mFunctionPointer       = Validate(functionPointer) ? functionPointer : null;
                mFunctionPointer.IsDNI = activation.IsDNI;


                if (mFunctionPointer == null)
                {
                    return(ProtoCore.DSASM.StackValue.Null);
                }

                {
                    interpreter.runtime.executingBlock = runtimeCore.RunningBlock;
                    activation.JILRecord.globs         = runtimeCore.DSExecutable.runtimeSymbols[runtimeCore.RunningBlock].GetGlobalSize();

                    // Params
                    formalParameters.Reverse();
                    for (int i = 0; i < formalParameters.Count; i++)
                    {
                        interpreter.Push(formalParameters[i]);
                    }

                    List <StackValue> registers = new List <DSASM.StackValue>();
                    interpreter.runtime.SaveRegisters(registers);

                    // Comment Jun: the depth is always 0 for a function call as we are reseting this for each function call
                    // This is only incremented for every language block bounce
                    int            depth      = 0;
                    StackFrameType callerType = stackFrame.CallerStackFrameType;

                    // FFI calls do not have execution states
                    runtimeCore.RuntimeMemory.PushStackFrame(svThisPtr, ci, fi, returnAddr, blockDecl, blockCaller, callerType, ProtoCore.DSASM.StackFrameType.kTypeFunction, depth, framePointer, registers, locals, 0);

                    //is there a way the current stack be passed across and back into the managed runtime by FFI calling back into the language?
                    //e.g. DCEnv* carrying all the stack information? look at how vmkit does this.
                    // = jilMain.Run(ActivationRecord.JILRecord.pc, null, true);

                    //double[] tempArray = GetUnderlyingArray<double>(jilMain.runtime.rmem.stack);
                    Object     ret = mFunctionPointer.Execute(c, interpreter);
                    StackValue op;
                    if (ret == null)
                    {
                        op = StackValue.Null;
                    }
                    else if (ret is StackValue)
                    {
                        op = (StackValue)ret;
                    }
                    else if (ret is Int64 || ret is int)
                    {
                        op = StackValue.BuildInt((Int64)ret);
                    }
                    else if (ret is double)
                    {
                        op = StackValue.BuildDouble((double)ret);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("FFI: incorrect return type {0} from external function {1}:{2}", activation.ReturnType.Name,
                                                                  activation.ModuleName, activation.FunctionName));
                    }

                    // Clear the FFI stack frame
                    // FFI stack frames have no local variables
                    interpreter.runtime.rmem.FramePointer = (int)interpreter.runtime.rmem.GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexFramePointer).opdata;
                    interpreter.runtime.rmem.PopFrame(ProtoCore.DSASM.StackFrame.kStackFrameSize + formalParameters.Count);

                    return(op); //DSASM.Mirror.ExecutionMirror.Unpack(op, core.heap, core);
                }
            }
        }
        internal void UpdateFromMem(IntPtr keyPtr)
        {
            _gpgme_key key = (_gpgme_key)
                Marshal.PtrToStructure(keyPtr,
                    typeof(_gpgme_key));

            this.keyPtr = keyPtr;

            revoked = key.revoked;
            expired = key.expired;
            disabled = key.disabled;
            invalid = key.invalid;
            can_encrypt = key.can_encrypt;
            can_sign = key.can_sign;
            can_certify = key.can_certify;
            can_authenticate = key.can_authenticate;
            is_qualified = key.is_qualified;
            secret = key.secret;

            protocol = (Protocol)key.protocol;
            owner_trust = (Validity)key.owner_trust;
            keylistmode = (KeylistMode)key.keylist_mode;

            issuer_name = Gpgme.PtrToStringUTF8(key.issuer_name);
            issuer_serial = Gpgme.PtrToStringAnsi(key.issuer_serial);
            chain_id = Gpgme.PtrToStringAnsi(key.chain_id);

            if (key.subkeys != (IntPtr)0)
                subkeys = new Subkey(key.subkeys);

            if (key.uids != (IntPtr)0)
                uids = new UserId(key.uids);
        }
            public void SetValidity(Validity validity)
            {
                value = (UInt16)(value & 0xfffc);

                value += (ushort)validity;
            }
Exemple #41
0
 /// <summary>
 /// Allows two <c>ValidationResult</c> objects to combine their reason lists
 /// if they indicate the same state of validity.
 /// </summary>
 /// <param name="other">The <c>ValidationResult</c> with which to merge.</param>
 public void Merge(ValidationResult other)
 {
     if (other._validity <= _validity) return;
     _validity = other._validity;
     Reasons.AddRange(other.Reasons);
 }
 private void activeProgramValidityChanged(Program sender, Validity oldValidity, Validity newValidity)
 {
     resetActiveProgramValues();
 }
Exemple #43
0
        public bool DoesTypeDeepMatch(List <StackValue> formalParameters, RuntimeCore runtimeCore)
        {
            if (formalParameters.Count != FormalParams.Length)
            {
                return(false);
            }

            for (int i = 0; i < FormalParams.Length; i++)
            {
                if (FormalParams[i].IsIndexable != formalParameters[i].IsArray)
                {
                    return(false);
                }

                if (FormalParams[i].IsIndexable && formalParameters[i].IsArray)
                {
                    if (FormalParams[i].rank != ArrayUtils.GetMaxRankForArray(formalParameters[i], runtimeCore) &&
                        FormalParams[i].rank != DSASM.Constants.kArbitraryRank)
                    {
                        return(false);
                    }


                    Type typ = FormalParams[i];
                    Dictionary <ClassNode, int> arrayTypes = ArrayUtils.GetTypeStatisticsForArray(formalParameters[i], runtimeCore);

                    ClassNode cn = null;

                    if (arrayTypes.Count == 0)
                    {
                        //This was an empty array
                        Validity.Assert(cn == null, "If it was an empty array, there shouldn't be a type node");
                        cn = runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull];
                    }
                    else if (arrayTypes.Count == 1)
                    {
                        //UGLY, get the key out of the array types, of which there is only one
                        foreach (ClassNode key in arrayTypes.Keys)
                        {
                            cn = key;
                        }
                    }
                    else if (arrayTypes.Count > 1)
                    {
                        ClassNode commonBaseType = ArrayUtils.GetGreatestCommonSubclassForArray(formalParameters[i], runtimeCore);

                        if (commonBaseType == null)
                        {
                            throw new ProtoCore.Exceptions.ReplicationCaseNotCurrentlySupported(
                                      string.Format(Resources.ArrayWithNotSupported, "{0C644179-14F5-4172-8EF8-A2F3739901B2}"));
                        }

                        cn = commonBaseType; //From now on perform tests on the commmon base type
                    }


                    ClassNode argTypeNode = runtimeCore.DSExecutable.classTable.ClassNodes[typ.UID];

                    //cn now represents the class node of the argument
                    //argTypeNode represents the class node of the argument

                    //TODO(Jun)This is worrying test

                    //Disable var as exact match, otherwise resolution between double and var will fail
                    if (cn != argTypeNode && cn != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeNull] && argTypeNode != runtimeCore.DSExecutable.classTable.ClassNodes[(int)PrimitiveType.kTypeVar])
                    {
                        return(false);
                    }

                    //if (coersionScore != (int)ProcedureDistance.kExactMatchScore)
                    //    return false;

                    continue;
                }

                if (FormalParams[i].UID != formalParameters[i].metaData.type)
                {
                    return(false);
                }
            }
            return(true);
        }
Exemple #44
0
        public static Validity ValidateSectionMasterHash(this Nca nca, int index)
        {
            if (!nca.SectionExists(index))
            {
                throw new ArgumentException(nameof(index), Messages.NcaSectionMissing);
            }
            if (!nca.CanOpenSection(index))
            {
                return(Validity.MissingKey);
            }

            NcaFsHeader header = nca.Header.GetFsHeader(index);

            // The base data is needed to validate the hash, so use a trick involving the AES-CTR extended
            // encryption table to check if the decryption is invalid.
            // todo: If the patch replaces the data checked by the master hash, use that directly
            if (header.IsPatchSection())
            {
                if (header.EncryptionType != NcaEncryptionType.AesCtrEx)
                {
                    return(Validity.Unchecked);
                }

                Validity ctrExValidity = ValidateCtrExDecryption(nca, index);
                return(ctrExValidity == Validity.Invalid ? Validity.Invalid : Validity.Unchecked);
            }

            byte[] expectedHash;
            long   offset;
            long   size;

            switch (header.HashType)
            {
            case NcaHashType.Ivfc:
                NcaFsIntegrityInfoIvfc ivfcInfo = header.GetIntegrityInfoIvfc();

                expectedHash = ivfcInfo.MasterHash.ToArray();
                offset       = ivfcInfo.GetLevelOffset(0);
                size         = 1 << ivfcInfo.GetLevelBlockSize(0);

                break;

            case NcaHashType.Sha256:
                NcaFsIntegrityInfoSha256 sha256Info = header.GetIntegrityInfoSha256();
                expectedHash = sha256Info.MasterHash.ToArray();

                offset = sha256Info.GetLevelOffset(0);
                size   = sha256Info.GetLevelSize(0);

                break;

            default:
                return(Validity.Unchecked);
            }

            IStorage storage = nca.OpenRawStorage(index);

            var data = new byte[size];

            storage.Read(data, offset);

            byte[] actualHash = Crypto.ComputeSha256(data, 0, data.Length);

            if (Util.ArraysEqual(expectedHash, actualHash))
            {
                return(Validity.Valid);
            }

            return(Validity.Invalid);
        }
Exemple #45
0
 protected virtual void EmitIdentifierNode(ProtoCore.AST.AssociativeAST.IdentifierNode identNode)
 {
     Validity.Assert(null != identNode);
     EmitCode(identNode.Value);
     EmitArrayNode(identNode.ArrayDimensions);
 }
Exemple #46
0
        protected virtual void EmitFunctionCallNode(ProtoCore.AST.AssociativeAST.FunctionCallNode funcCallNode)
        {
            Validity.Assert(null != funcCallNode);

            Validity.Assert(funcCallNode.Function is ProtoCore.AST.AssociativeAST.IdentifierNode);
            string functionName = (funcCallNode.Function as ProtoCore.AST.AssociativeAST.IdentifierNode).Value;

            Validity.Assert(!string.IsNullOrEmpty(functionName));
            if (functionName.StartsWith("%"))
            {
                EmitCode("(");
                DFSTraverse(funcCallNode.FormalArguments[0], true);
                switch (functionName)
                {
                case "%add":
                    EmitCode("+");
                    break;

                case "%sub":
                    EmitCode("-");
                    break;

                case "%mul":
                    EmitCode("*");
                    break;

                case "%div":
                    EmitCode("/");
                    break;

                case "%mod":
                    EmitCode("%");
                    break;

                case "%Not":
                    EmitCode("!");
                    break;
                }

                if (funcCallNode.FormalArguments.Count > 1)
                {
                    DFSTraverse(funcCallNode.FormalArguments[1], true);
                }
                EmitCode(")");
            }
            else
            {
                EmitCode(functionName);

                EmitCode("(");
                for (int n = 0; n < funcCallNode.FormalArguments.Count; ++n)
                {
                    ProtoCore.AST.AssociativeAST.AssociativeNode argNode = funcCallNode.FormalArguments[n];
                    DFSTraverse(argNode, true);
                    if (n + 1 < funcCallNode.FormalArguments.Count)
                    {
                        EmitCode(",");
                    }
                }
                EmitCode(")");
            }
        }
 private void onSourceValidityChanged(
 Shader sender, Validity oldValidity, Validity newValidity)
 {
     OnPropertyChanged("SourceValidity");
     OnPropertyChanged("CompilationError");
 }
 private void onLinkageValidityChanged(
 Program sender, Validity oldValidity, Validity newValidity)
 {
     OnPropertyChanged("LinkageValidity");
     OnPropertyChanged("LinkError");
 }