Esempio n. 1
0
        public static Header ReadHeader(this Stream stream, bool ReadSectionSignature = true)
        {
            Header Header = new Header
            {
                Format   = Main.Format.F2LE, Signature = stream.ReadInt32(),
                DataSize = stream.ReadInt32(),
                Length   = stream.ReadInt32()
            };

            if (stream.ReadUInt32() == 0x18000000)
            {
                Header.Format = Main.Format.F2BE;
            }
            Header.ID          = stream.ReadInt32();
            Header.SectionSize = stream.ReadInt32();
            Header.Count       = stream.ReadInt32();
            stream.ReadInt32();
            if (Header.Length == 0x40)
            {
                stream.ReadInt64();
                stream.ReadInt64();
                Header.InnerSignature = stream.ReadInt32();
                stream.ReadInt32();
                stream.ReadInt64();
            }
            stream.Format = Header.Format;
            if (ReadSectionSignature)
            {
                Header.SectionSignature = stream.ReadInt32Endian();
            }
            return(Header);
        }
Esempio n. 2
0
        }                                  // 插件二进制数据的长度

        internal void Read(Stream stream)
        {
            //Status = (AddinStatus)stream.ReadSByte();
            Enabled  = stream.ReadBoolean();
            AddinUid = stream.ReadInt32();
            Position = stream.ReadInt64();
            Length   = stream.ReadInt64();
        }
 public void ReadInt64Test()
 {
     long[] values = new long[] { 432, -56 };
     stream.Write(-9L);
     stream.Write(values);
     stream.Position = 0;
     AssertThat(stream.ReadInt64()).IsEqualTo(-9);
     AssertThat(stream.ReadInt64(2)).ContainsExactly(432, -56);
 }
Esempio n. 4
0
 public void Read(Stream source)
 {
     this.Id             = source.ReadInt32();
     this.Error          = source.ReadErrorCode();
     this.Offset         = source.ReadInt64();
     this.LogAppendTime  = source.ReadInt64();
     this.LogStartOffset = source.ReadInt64();
     this.Errors         = source.ReadArray <RecordError>();
     this.ErrorMessage   = source.ReadNullableString();
 }
Esempio n. 5
0
        public static Node Read(Stream indexStream, Encoding encoding)
        {
            long   offset           = indexStream.Position;
            int    valueLength      = indexStream.ReadInt32();
            string value            = indexStream.ReadString(valueLength, encoding);
            long   offsetInDataFile = indexStream.ReadInt64();
            long   nextOffset       = indexStream.ReadInt64();

            return(new Node(offset, valueLength, value, offsetInDataFile, nextOffset));
        }
 public void Read(Stream source)
 {
     this.Id                   = source.ReadInt32();
     this.Error                = source.ReadErrorCode();
     this.HighWatermark        = source.ReadInt64();
     this.LastStableOffset     = source.ReadInt64();
     this.LogStartOffset       = source.ReadInt64();
     this.AbortedTransactions  = source.ReadArray <AbortedTransaction>();
     this.PreferredReadReplica = source.ReadInt32();
 }
 private static LongRange?ReadItemData(Stream stream, Boolean flag, int size)
 {
     if (!flag)
     {
         return(default(LongRange?));
     }
     else
     {
         return(new LongRange(stream.ReadInt64(), stream.ReadInt64()));
     }
 }
Esempio n. 8
0
        bool DoRead(Stream stream)
        {
            if (stream.Length < _metadataTable.MinLength + SegmentLength)
            {
                return(false); // 虽然插件数据文件存在,但并未包含有效的数据
            }
            // 1. 读取各个分段的长度
            stream.Position = stream.Length - SegmentLength;
            var addinRecordSegmentLength           = stream.ReadInt64();
            var addinMetadataSegmentLength         = stream.ReadInt64();
            var invalidAddinFilePacksSegmentLength = stream.ReadInt64();
            var dataSegmentLength = stream.ReadInt64();

            if (dataSegmentLength + SegmentLength != stream.Length)
            {
                return(false); // 插件数据文件已被破坏,返回 false 以便让系统重新解析插件
            }
            // 2. 读取 AddinMetadata 分段 (AddinMetadataTable)
            stream.Position = addinRecordSegmentLength; // 指针指向 AddinMetadata 分段 (AddinMetadataTable) 的起始位置
            var hasAddins = _metadataTable.Read(stream);

            if (!hasAddins || _metadataTable.AddinCount == 0)
            {
                return(false); // 虽然插件数据文件存在,但并未包含有效的数据
            }
            // 3. 根据 AddinMetadata 读取 AddinRecord 分段,并进行验证
            foreach (var metadata in _metadataTable.Addins)
            {
                stream.Position = metadata.Position;
                var addin = new AddinRecord(metadata);
                addin.Read(stream);
                if (stream.Position - metadata.Position != metadata.Length || addin.Uid != metadata.AddinUid)
                {
                    return(false); // 插件数据文件已被破坏,返回 false 以便让系统重新解析插件
                }
                _addinRecords.Add(addin);
            }

            // 4. 读取 InvalidAddinFilePack 分段
            stream.Position        = addinRecordSegmentLength + addinMetadataSegmentLength; // 指针指向 InvalidAddinFilePack 分段的起始位置
            _invalidAddinFilePacks = RecordHelpers.Read(stream, ref AddinFilePack.Factory);
            if (stream.Position - (addinRecordSegmentLength + addinMetadataSegmentLength) != invalidAddinFilePacksSegmentLength)
            {
                return(false); // 插件数据文件已被破坏,返回 false 以便让系统重新解析插件
            }
            // 5. 读取 Uid 分段
            stream.Position = addinRecordSegmentLength + addinMetadataSegmentLength + invalidAddinFilePacksSegmentLength; // 指针指向 Uid 分段的起始位置
            UidStorage.Read(stream);

            return(true);
        }
Esempio n. 9
0
        public static void Decrypt(this string file)
        {
            Console.Title = "DIVAFILE Decrypt - File: " + Path.GetFileName(file);
            Stream reader = File.OpenReader(file);

            if (reader.ReadInt64() != 0x454C494641564944)
            {
                reader.Close(); return;
            }
            int StreamLenght = reader.ReadInt32();
            int FileLenght   = reader.ReadInt32();

            byte[] decrypted = new byte[StreamLenght];
            reader.Seek(0, 0);
            using (AesManaged crypto = new AesManaged())
            {
                crypto.Key  = Key; crypto.IV = new byte[16];
                crypto.Mode = CipherMode.ECB; crypto.Padding = PaddingMode.Zeros;
                using (CryptoStream cryptoData = new CryptoStream(reader.BaseStream,
                                                                  crypto.CreateDecryptor(crypto.Key, crypto.IV), CryptoStreamMode.Read))
                    cryptoData.Read(decrypted, 0, StreamLenght);
            }
            Stream writer = File.OpenWriter(file, FileLenght);

            for (int i = 0x10; i < StreamLenght && i < FileLenght + 0x10; i++)
            {
                writer.Write(decrypted[i]);
            }
            writer.Close();
        }
Esempio n. 10
0
        public override void Load(Stream stream)
        {
            TestForEditable();
            byte version = stream.ReadNextByte();

            switch (version)
            {
            case 1:
                m_directoryMethod       = (ArchiveDirectoryMethod)stream.ReadInt32();
                m_prefix                = stream.ReadString();
                m_pendingExtension      = stream.ReadString();
                m_finalExtension        = stream.ReadString();
                m_desiredRemainingSpace = stream.ReadInt64();
                m_encodingMethod        = new EncodingDefinition(stream);
                int cnt = stream.ReadInt32();
                m_writePath.Clear();
                while (cnt > 0)
                {
                    cnt--;
                    m_writePath.Add(stream.ReadString());
                }
                cnt = stream.ReadInt32();
                m_flags.Clear();
                while (cnt > 0)
                {
                    cnt--;
                    m_flags.Add(stream.ReadGuid());
                }
                break;

            default:
                throw new VersionNotFoundException("Unknown Version Code: " + version);
            }
        }
Esempio n. 11
0
 private static void ReadHeaders(Stream headerStream, IList <AssHeader> headers)
 {
     headerStream.Position = 0;
     while (headerStream.Position < headerStream.Length)
     {
         var fileName = headerStream.ReadString();
         var startPos = headerStream.ReadInt64();
         var endPos   = headerStream.ReadInt64();
         headers.Add(new AssHeader
         {
             fileName = fileName,
             startPos = startPos,
             endPos   = endPos
         });
     }
 }
Esempio n. 12
0
        public static void Decrypt(this string file)
        {
            Console.Title = "DIVAFILE Decrypt - File: " + Path.GetFileName(file);
            Stream IO = File.OpenReader(file);

            if (IO.ReadInt64() != 0x454C494641564944)
            {
                IO.Close(); return;
            }
            int StreamLength = IO.ReadInt32();
            int FileLength   = IO.ReadInt32();

            byte[] encrypted = IO.ReadBytes(StreamLength);
            byte[] decrypted = new byte[StreamLength];
            IO.Close();

            using (AesManaged crypto = new AesManaged())
            {
                crypto.Key  = Key; crypto.IV = new byte[16];
                crypto.Mode = CipherMode.ECB; crypto.Padding = PaddingMode.Zeros;
                using (CryptoStream cryptoData = new CryptoStream(new MSIO.MemoryStream(encrypted),
                                                                  crypto.CreateDecryptor(crypto.Key, crypto.IV), CryptoStreamMode.Read))
                    cryptoData.Read(decrypted, 0, StreamLength);
            }
            IO = File.OpenWriter(file, FileLength);
            IO.Write(decrypted, FileLength < StreamLength ? FileLength : StreamLength);
            IO.Close();
        }
Esempio n. 13
0
        /// <summary>
        /// Reads an object from a stream.
        /// </summary>
        /// <param name="stream">Source stream.</param>
        /// <returns>Decoded object.</returns>
        public static object?ReadObject(this Stream stream)
        {
            ObjectType type = (ObjectType)stream.ReadNextByte();

            return(type switch
            {
                ObjectType.Null => null,
                ObjectType.DbNull => DBNull.Value,
                ObjectType.BooleanTrue => true,
                ObjectType.BooleanFalse => false,
                ObjectType.Char => stream.ReadChar(),
                ObjectType.SByte => stream.ReadSByte(),
                ObjectType.Byte => stream.ReadNextByte(),
                ObjectType.Int16 => stream.ReadInt16(),
                ObjectType.UInt16 => stream.ReadUInt16(),
                ObjectType.Int32 => stream.ReadInt32(),
                ObjectType.UInt32 => stream.ReadUInt32(),
                ObjectType.Int64 => stream.ReadInt64(),
                ObjectType.UInt64 => stream.ReadUInt64(),
                ObjectType.Single => stream.ReadSingle(),
                ObjectType.Double => stream.ReadDouble(),
                ObjectType.Decimal => stream.ReadDecimal(),
                ObjectType.DateTime => stream.ReadDateTime(),
                ObjectType.String => stream.ReadString(),
                ObjectType.ByteArray => stream.ReadBytes(),
                ObjectType.CharArray => stream.ReadString().ToCharArray(),
                ObjectType.Guid => stream.ReadGuid(),
                _ => throw new ArgumentOutOfRangeException()
            });
Esempio n. 14
0
 private void ReadOffsets()
 {
     for (int i = 0; i < FileEntries.Length; i++)
     {
         FileEntries[i].RelativeOffset = Stream.ReadInt64();
     }
 }
Esempio n. 15
0
        public static decimal ReadDecimal(this Stream stream)
        {
            BSDebug.TraceStart("ReadDecimal", stream.Position);

            decimal result;

            unsafe
            {
                var p = (long *)&result;
                p[0] = stream.ReadInt64();
                p[1] = stream.ReadInt64();
            }

            BSDebug.TraceEnd("ReadDecimal", stream.Position);
            return(result);
        }
Esempio n. 16
0
 internal FreeRecord(Stream stream, int length)
 {
     Length         = length;
     Offset         = stream.Position;
     NextFreeRecord = stream.ReadInt64();
     stream.Seek(length - 16, SeekOrigin.Current);
 }
Esempio n. 17
0
        public void AddFilesV3(List <string> files, string srcdir, string dstdir)
        {
            Stream.Reopen(false);
            SetProgressMax?.Invoke(files.Count);
            int cl = Settings.CompressionLevel;

            Stream.Seek(-280, SeekOrigin.End);
            long current_end = Stream.ReadInt64() ^ Key.KEY_1;

            foreach (string file in files)
            {
                SetProgressNext?.Invoke();
                byte[] data       = File.ReadAllBytes(file);
                int    size       = data.Length;
                byte[] compressed = Zlib.Compress(data, cl);
                if (compressed.Length < size)
                {
                    data = compressed;
                }
                string path  = (dstdir + file.RemoveFirst(srcdir).RemoveFirstSeparator()).RemoveFirstSeparator();
                var    entry = Files.Where(x => x.Path == path).ToList();
                if (entry.Count > 0)
                {
                    if (data.Length <= entry[0].CSize)
                    {
                        entry[0].Size  = size;
                        entry[0].CSize = data.Length;
                        Stream.Seek(entry[0].Offset, SeekOrigin.Begin);
                        Stream.WriteBytes(data);
                    }
                    else
                    {
                        entry[0].Size   = size;
                        entry[0].CSize  = data.Length;
                        entry[0].Offset = current_end;
                        Stream.Seek(current_end, SeekOrigin.Begin);
                        current_end += data.Length;
                        Stream.WriteBytes(data);
                    }
                }
                else
                {
                    Files.Add(new ArchiveEntryV3()
                    {
                        Path   = path,
                        Size   = size,
                        CSize  = data.Length,
                        Offset = current_end
                    });
                    Stream.Seek(current_end, SeekOrigin.Begin);
                    current_end += data.Length;
                    Stream.WriteBytes(data);
                }
            }
            SaveFileTable(current_end);
            SetProgress?.Invoke(0);
            LoadData?.Invoke(0);
            LoadData?.Invoke(1);
        }
Esempio n. 18
0
        public static BlockHeader ReadBlockHeader(this Stream stream)
        {
            byte beginToken = (byte)stream.ReadByte();

            if (beginToken != Tokens.BlockBeginToken)
            {
                throw new InvalidOperationException();
            }

            BlockHeader header = new BlockHeader();

            header.BlockSequence = stream.ReadInt64();
            header.FreeBytes     = stream.ReadInt64();
            header.RecordCount   = stream.ReadInt64();

            return(header);
        }
 public void Read(Stream source)
 {
     this.Id = source.ReadInt32();
     this.CommittedOffset      = source.ReadInt64();
     this.CommittedLeaderEpoch = source.ReadInt32();
     this.Metadata             = source.ReadString();
     this.ErrorCode            = source.ReadInt16();
 }
 internal void Read(Stream reader)
 {
     FilePath      = reader.ReadString();
     Directory     = reader.ReadString();
     LastWriteTime = reader.ReadDateTime();
     FileLength    = reader.ReadInt64();
     FileHash      = reader.ReadString();
 }
Esempio n. 21
0
        /// <summary>
        /// Reads a single CIL instruction from a given data stream.
        /// </summary>
        /// <param name="stream">The source data stream.</param>
        /// <param name="instruction">The instruction that was read, undefined if the method returns zero.</param>
        /// <returns>A value indicating if an instruction was read, <c>false</c> if the end of the stream was reached.</returns>
        public static bool ReadInstruction(Stream stream, out RawInstruction instruction)
        {
            Contract.Requires(stream != null && stream.CanRead);

            int firstOpcodeByte = stream.ReadByte();

            if (unchecked ((byte)firstOpcodeByte) != firstOpcodeByte)
            {
                instruction = default(RawInstruction);
                return(false);
            }

            OpcodeValue opcodeValue;

            if (OpcodeValueEnum.IsFirstOfTwoBytes((byte)firstOpcodeByte))
            {
                opcodeValue = (OpcodeValue)((firstOpcodeByte << 8) | stream.ReadUInt8());
            }
            else
            {
                opcodeValue = (OpcodeValue)firstOpcodeByte;
            }

            var opcode = Opcode.FromValue(opcodeValue);

            if (opcode == Opcode.Switch)
            {
                // Read jump table
                int[] jumpTable = new int[stream.ReadUInt32()];
                for (int i = 0; i < jumpTable.Length; ++i)
                {
                    jumpTable[i] = stream.ReadInt32();
                }
                instruction = RawInstruction.CreateSwitch(jumpTable);
            }
            else
            {
                NumericalOperand operand;
                switch ((int)opcode.OperandKind.GetSizeInBytes())
                {
                case 0: operand = default(NumericalOperand); break;

                case 1: operand = stream.ReadInt8(); break;

                case 2: operand = stream.ReadInt16(); break;

                case 4: operand = stream.ReadInt32(); break;

                case 8: operand = stream.ReadInt64(); break;

                default: throw new NotSupportedException("Unexpected opcode operand size");
                }
                instruction = new RawInstruction(opcode, operand);
            }

            return(true);
        }
Esempio n. 22
0
        public static double ReadDouble(this Stream stream)
        {
            BSDebug.TraceStart("ReadDouble", stream.Position);

            var result = ToDouble(stream.ReadInt64());

            BSDebug.TraceEnd("ReadDouble", stream.Position);
            return(result);
        }
Esempio n. 23
0
        public void BINReader(string file)
        {
            Dictionary <string, object> Dict = new Dictionary <string, object>();

            string[] dataArray;

            IO = File.OpenReader(file + ".bin");

            IO.Format = Main.Format.F;
            Signature = IO.ReadInt32();
            if (Signature != 0x44334123)
            {
                return;
            }
            Signature = IO.ReadInt32();
            if (Signature != 0x5F5F5F41)
            {
                return;
            }
            IO.ReadInt64();

            string[] STRData = IO.ReadString(IO.Length - IO.Position).Replace("\r", "").Split('\n');
            for (int i = 0; i < STRData.Length; i++)
            {
                dataArray = STRData[i].Split('=');
                if (dataArray.Length == 2)
                {
                    Dict.GetDictionary(dataArray[0], dataArray[1]);
                }
            }

            if (Dict.FindValue(out string value, "category.length"))
            {
                Category = new string[int.Parse(value)];
                for (int i0 = 0; i0 < Category.Length; i0++)
                {
                    if (Dict.FindValue(out value, "category." + i0 + ".value"))
                    {
                        Category[i0] = value;
                    }
                }
            }

            if (Dict.FindValue(out value, "uid.length"))
            {
                _UID = new UID[int.Parse(value)];
                for (int i0 = 0; i0 < _UID.Length; i0++)
                {
                    Dict.FindValue(out _UID[i0].Category, "uid." + i0 + ".category");
                    Dict.FindValue(out _UID[i0].OrgUid, "uid." + i0 + ".org_uid");
                    Dict.FindValue(out _UID[i0].Size, "uid." + i0 + ".size");
                    Dict.FindValue(out _UID[i0].Value, "uid." + i0 + ".value");
                }
            }

            IO.Close();
        }
Esempio n. 24
0
        public static SqlInt64 ReadSqlInt64(this Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            return(stream.ReadBoolean(TypeCode.Byte) ? stream.ReadInt64() : SqlInt64.Null);
        }
Esempio n. 25
0
        public IEnumerable <long> GetOffsetFrom(string value)
        {
            long bucketOffset = 8 * GetBucketForValue(value);

            _bucketStream.Seek(bucketOffset, SeekOrigin.Begin);
            long offsetInIndexFile = _bucketStream.ReadInt64();

            while (offsetInIndexFile >= IndexFileHeaderSize)
            {
                _indexStream.Seek(offsetInIndexFile, SeekOrigin.Begin);
                var node = Node.Read(_indexStream, _encoding);
                if (string.Equals(node.Value, value))
                {
                    yield return(node.OffsetInDataFile);
                }
                offsetInIndexFile = node.NextOffset;
            }
        }
Esempio n. 26
0
        public static DateTime ReadDateTime(this Stream stream)
        {
            BSDebug.TraceStart("ReadDateTime", stream.Position);

            var ticks = stream.ReadInt64();

            BSDebug.TraceEnd("ReadDateTime", stream.Position);
            return(new DateTime(ticks));
        }
        internal static string ReadWithSizeString(this Stream stream)
        {
            var size = stream.ReadInt64();
            var data = new byte[size];

            stream.Read(data, 0, (int)size);

            return(System.Text.Encoding.Unicode.GetString(data, 0, data.Length));
        }
        public object Deserialize(GraphicsDevice device, Stream stream, string fileName)
        {
            var spriteSheet = new AnimatedSpriteSheet();

            var version = stream.ReadByte();

            spriteSheet.Name      = stream.ReadStringWithLength();
            spriteSheet.AssetName = stream.ReadStringWithLength();

            spriteSheet.StartDelay         = stream.ReadInt64();
            spriteSheet.TimeBetweenSprites = stream.ReadInt64();
            spriteSheet.Repeat             = stream.ReadBool();
            spriteSheet.ReverseAtEnd       = stream.ReadBool();

            ushort frameCount = stream.ReadUInt16();

            for (int i = 0; i < frameCount; i++)
            {
                Sprite sprite = new Sprite();

                stream.ReadUInt16(); // Frame index, unused

                sprite.Name   = stream.ReadStringWithLength();
                sprite.Width  = stream.ReadUInt16();
                sprite.Height = stream.ReadUInt16();
                sprite.X      = stream.ReadUInt16();
                sprite.Y      = stream.ReadUInt16();

                spriteSheet.Sprites[sprite.Name] = sprite;
            }

            using (var fs = new FileStream(Path.Combine(Path.GetDirectoryName(fileName), spriteSheet.AssetName + ".png"), FileMode.Open))
            {
                spriteSheet.Texture = Texture2D.FromStream(device, fs);
            }

            foreach (var sprite in spriteSheet.Sprites)
            {
                sprite.Value.Texture = spriteSheet.Texture;
            }


            return(spriteSheet);
        }
Esempio n. 29
0
        public static W2Dzip Read(Stream stream)
        {
            // ReSharper disable UseObjectOrCollectionInitializer
            var result = new W2Dzip();
            // ReSharper restore UseObjectOrCollectionInitializer

            stream.Seek(0, SeekOrigin.Begin);
            result.header = stream.ReadUtf8String(4);
            result.version = stream.ReadInt32();
            result.fileCount = stream.ReadInt32();
            result.userId = stream.ReadInt32();
            result.metaOffset = stream.ReadInt64();
            result.unknown = stream.ReadInt64();

            stream.Seek(result.metaOffset, SeekOrigin.Begin);
            result.fileEntry = FileEntry.Read(stream, result.fileCount, out result.estimatedMaximumBufferSize);

            return result;
        }
Esempio n. 30
0
        public void Read(Stream stream)
        {
            this.ChannelCount     = stream.ReadInt32();
            this.BitsPerSample    = stream.ReadInt32();
            this.SampleRate       = stream.ReadInt32();
            this.FinalSampleCount = stream.ReadInt64();

            this.OutputFormat     = stream.ReadString();
            this.CompressionLevel = stream.ReadInt32();
        }
Esempio n. 31
0
        /// <summary>
        /// Reads multiple signed longs from stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="count">The amount of signed longs.</param>
        /// <param name="endianness">Determines whether to interpret the values as big endian or little endian.</param>
        /// <returns>An array of signed longs read from stream.</returns>
        public static long[] ReadInt64(this Stream stream, int count, Endianness endianness)
        {
            long[] result = new long[count];
            for (int i = 0; i < count; i++)
            {
                result[i] = stream.ReadInt64(endianness);
            }

            return(result);
        }
Esempio n. 32
0
        public static Message FromStream(Stream stream)
        {
            char type = (char)stream.ReadByte();
            DateTime timestamp = DateTime.FromBinary(stream.ReadInt64());

            switch (type)
            {
                case 'g': return GuessMessage.FromStream(timestamp, stream);
                case 'p': return PlayerMessage.FromStream(timestamp, stream);
                case 'd': return RoundDoneMessage.FromStream(timestamp, stream);
                case 's': return RoundStartMessage.FromStream(timestamp, stream);
                case 'e': return SetupMessage.FromStream(timestamp, stream);
                case 't': return StateMessage.FromStream(timestamp, stream);

                default:
                    throw new InvalidOperationException($"Unknown message identifier: {type}.");
            }
        }
Esempio n. 33
0
 private void HandleStepDone(Stream stream) {
     // stepping done
     long threadId = stream.ReadInt64();
     var stepComp = StepComplete;
     if (stepComp != null) {
         stepComp(this, new ThreadEventArgs(_threads[threadId]));
     }
 }
Esempio n. 34
0
        private void HandleProcessLoad(Stream stream) {
            Debug.WriteLine("Process loaded " + _processGuid);

            // process is loaded, no user code has run
            long threadId = stream.ReadInt64();
            var thread = _threads[threadId];

            var loaded = ProcessLoaded;
            if (loaded != null) {
                loaded(this, new ThreadEventArgs(thread));
            }
        }
Esempio n. 35
0
        private void HandleThreadFrameList(Stream stream) {
            // list of thread frames
            var frames = new List<PythonStackFrame>();
            long tid = stream.ReadInt64();
            PythonThread thread;
            _threads.TryGetValue(tid, out thread);
            var threadName = stream.ReadString();

            int frameCount = stream.ReadInt32();
            for (int i = 0; i < frameCount; i++) {
                int startLine = stream.ReadInt32();
                int endLine = stream.ReadInt32();
                int lineNo = stream.ReadInt32();
                string frameName = stream.ReadString();
                string filename = stream.ReadString();
                int argCount = stream.ReadInt32();
                var frameKind = (FrameKind)stream.ReadInt32();
                PythonStackFrame frame = null; 
                if (thread != null) {
                    switch (frameKind) {
                        case FrameKind.Django:
                            string sourceFile = stream.ReadString();
                            var sourceLine = stream.ReadInt32();
                            frame = new DjangoStackFrame(thread, frameName, filename, startLine, endLine, lineNo, argCount, i, sourceFile, sourceLine);
                            break;
                        default:
                            frame = new PythonStackFrame(thread, frameName, filename, startLine, endLine, lineNo, argCount, i, frameKind);
                            break;
                    }
                    
                }

                int varCount = stream.ReadInt32();
                PythonEvaluationResult[] variables = new PythonEvaluationResult[varCount];
                for (int j = 0; j < variables.Length; j++) {
                    string name = stream.ReadString();
                    if (frame != null) {
                        variables[j] = ReadPythonObject(stream, name, name, frame);
                    }
                }
                if (frame != null) {
                    frame.SetVariables(variables);
                    frames.Add(frame);
                }
            }

            Debug.WriteLine("Received frames for thread {0}", tid);
            if (thread != null) {
                thread.Frames = frames;
                if (threadName != null) {
                    thread.Name = threadName;
                }
            }
        }
Esempio n. 36
0
        private PythonEvaluationResult ReadPythonObject(Stream stream, string expr, string childName, PythonStackFrame frame) {
            string objRepr = stream.ReadString();
            string hexRepr = stream.ReadString();
            string typeName = stream.ReadString();
            long length = stream.ReadInt64();
            var flags = (PythonEvaluationResultFlags)stream.ReadInt32();

            if (!flags.HasFlag(PythonEvaluationResultFlags.Raw) && ((typeName == "unicode" && LanguageVersion.Is2x()) || (typeName == "str" && LanguageVersion.Is3x()))) {
                objRepr = objRepr.FixupEscapedUnicodeChars();
            }

            if (typeName == "bool") {
                hexRepr = null;
            }

            return new PythonEvaluationResult(this, objRepr, hexRepr, typeName, length, expr, childName, frame, flags);
        }
Esempio n. 37
0
 private void HandleException(Stream stream) {
     string typeName = stream.ReadString();
     long tid = stream.ReadInt64();
     int breakType = stream.ReadInt32();
     string desc = stream.ReadString();
     if (typeName != null && desc != null) {
         Debug.WriteLine("Exception: " + desc);
         ExceptionRaised?.Invoke(this, new ExceptionRaisedEventArgs(
             _threads[tid],
             new PythonException {
                 TypeName = typeName,
                 FormattedDescription = desc,
                 UserUnhandled = (breakType == 1) /* BREAK_TYPE_UNHANLDED */
             }
         ));
     }
     _stoppedForException = true;
 }
Esempio n. 38
0
 private void HandleRichException(Stream stream) {
     var exc = new PythonException();
     long tid = stream.ReadInt64();
     int count = stream.ReadInt32();
     while (--count >= 0) {
         string key = stream.ReadString();
         string value = stream.ReadString();
         exc.SetValue(this, key, value);
     }
     if (tid != 0) {
         Debug.WriteLine("Exception: " + exc.FormattedDescription ?? exc.ExceptionMessage ?? exc.TypeName);
         ExceptionRaised?.Invoke(this, new ExceptionRaisedEventArgs(_threads[tid], exc));
         _stoppedForException = true;
     }
 }
Esempio n. 39
0
 private void HandleBreakPointHit(Stream stream) {
     int breakId = stream.ReadInt32();
     long threadId = stream.ReadInt64();
     var brkEvent = BreakpointHit;
     PythonBreakpoint unboundBreakpoint;
     if (brkEvent != null) {
         if (_breakpoints.TryGetValue(breakId, out unboundBreakpoint)) {
             brkEvent(this, new BreakpointHitEventArgs(unboundBreakpoint, _threads[threadId]));
         } else {
             SendResumeThread(threadId);
         }
     }
 }
Esempio n. 40
0
 private void HandleSetLineResult(Stream stream)
 {
     int res = stream.ReadInt32();
     long tid = stream.ReadInt64();
     int newLine = stream.ReadInt32();
     _setLineResult = res != 0;
     if (_setLineResult) {
         _threads[tid].Frames[0].LineNo = newLine;
     }
     _lineEvent.Set();
 }
Esempio n. 41
0
        /// <summary>
        /// Performs the initial handshake with the remote debugging server, verifying signature and version number and setting up SSL,
        /// and returns the opened socket and the SSL stream for that socket.
        /// </summary>
        /// <param name="hostName">Name of the host to connect to.</param>
        /// <param name="portNumber">Port number to connect to.</param>
        /// <param name="secret">Secret to authenticate with.</param>
        /// <param name="useSsl">Whether to use SSL for this connection.</param>
        /// <param name="sslErrorHandling">If using SSL, specifies how SSL certificate errors should be handled.</param>
        /// <param name="socket">Opened socket to the remote debugging server. The returned socket is owned by <paramref name="stream"/>.</param>
        /// <param name="stream">Opened SSL network stream to the remote debugging server. This stream owns the <paramref name="socket"/>, and will automatically close it.</param>
        /// <returns>Error code.</returns>
        /// <remarks><paramref name="socket"/> should not be used to send or receive data, since it is wrapped in a stream, and is owned by that stream.
        /// It is exposed solely to enable querying it for endpoint information and connectivity status.</remarks>
        public static ConnErrorMessages TryConnect(string hostName, ushort portNumber, string secret, bool useSsl, SslErrorHandling sslErrorHandling, out Socket socket, out Stream stream)
        {
            stream = null;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool connected = false;
            try {
                socket.Connect(hostName, portNumber);
                var rawStream = new NetworkStream(socket, ownsSocket: true);
                if (useSsl) {
                    var sslStream = new SslStream(rawStream, false, (sender, cert, chain, errs) => {
                        if (errs == SslPolicyErrors.None || sslErrorHandling == SslErrorHandling.Ignore) {
                            return true;
                        } else if (sslErrorHandling == SslErrorHandling.Fail) {
                            return false;
                        }

                        string errText = string.Format("Could not establish secure connection to {0}:{1} because of the following SSL issues:\n\n", hostName, portNumber);
                        if ((errs & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) {
                            errText += "- no remote certificate provided\n";
                        }
                        if ((errs & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) {
                            errText += "- remote certificate name does not match hostname\n";
                        }
                        if ((errs & SslPolicyErrors.RemoteCertificateChainErrors) != 0) {
                            errText += "- remote certificate is not trusted\n";
                        }

                        errText += "\nConnect anyway?";

                        var dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        return dlgRes == DialogResult.Yes;
                    });
                    try {
                        sslStream.AuthenticateAsClient(hostName);
                    } catch (AuthenticationException) {
                        return ConnErrorMessages.RemoteSslError;
                    }
                    stream = sslStream;
                } else {
                    stream = rawStream;
                }

                var buf = new byte[8];
                int bufLen = stream.Read(buf, 0, DebuggerSignature.Length);
                string sig = Encoding.ASCII.GetString(buf, 0, bufLen);
                if (sig != DebuggerSignature) {
                    return ConnErrorMessages.RemoteUnsupportedServer;
                }

                long ver = stream.ReadInt64();
                if (ver != DebuggerProtocolVersion) {
                    return ConnErrorMessages.RemoteUnsupportedServer;
                }

                stream.Write(DebuggerSignatureBytes);
                stream.WriteInt64(DebuggerProtocolVersion);

                stream.WriteString(secret);
                bufLen = stream.Read(buf, 0, Accepted.Length);
                string secretResp = Encoding.ASCII.GetString(buf, 0, bufLen);
                if (secretResp != Accepted) {
                    return ConnErrorMessages.RemoteSecretMismatch;
                }

                connected = true;
            } catch (IOException) {
                return ConnErrorMessages.RemoteNetworkError;
            } catch (SocketException) {
                return ConnErrorMessages.RemoteNetworkError;
            } finally {
                if (!connected) {
                    if (stream != null) {
                        stream.Close();
                    }
                    socket.Close();
                    socket = null;
                    stream = null;
                }
            }

            return ConnErrorMessages.None;
        }
Esempio n. 42
0
        private void HandleThreadExit(Stream stream) {
            // thread exit
            long threadId = stream.ReadInt64();
            PythonThread thread;
            if (_threads.TryGetValue(threadId, out thread)) {
                var exited = ThreadExited;
                if (exited != null) {
                    exited(this, new ThreadEventArgs(thread));
                }

                _threads.Remove(threadId);
                Debug.WriteLine("Thread exited, {0} active threads", _threads.Count);
            }

        }
Esempio n. 43
0
        private void HandleDebuggerOutput(Stream stream) {
            long tid = stream.ReadInt64();
            string output = stream.ReadString();

            PythonThread thread;
            if (_threads.TryGetValue(tid, out thread)) {
                var outputEvent = DebuggerOutput;
                if (outputEvent != null) {
                    outputEvent(this, new OutputEventArgs(thread, output));
                }
            }
        }
Esempio n. 44
0
        private void HandleThreadCreate(Stream stream) {
            // new thread
            long threadId = stream.ReadInt64();
            var thread = _threads[threadId] = new PythonThread(this, threadId, _createdFirstThread);
            _createdFirstThread = true;

            var created = ThreadCreated;
            if (created != null) {
                created(this, new ThreadEventArgs(thread));
            }
        }
Esempio n. 45
0
 private void HandleSetLineResult(Stream stream) {
     int res = stream.ReadInt32();
     long tid = stream.ReadInt64();
     int newLine = stream.ReadInt32();
     _setLineResult = res != 0;
     if (_setLineResult) {
         var frame = _threads[tid].Frames.FirstOrDefault();
         if (frame != null) {
             frame.LineNo = newLine;
         } else {
             Debug.Fail("SETL result received, but there is no frame to update");
         }
     }
     _lineEvent.Set();
 }
Esempio n. 46
0
 private void HandleException(Stream stream) {
     string typeName = stream.ReadString();
     long tid = stream.ReadInt64();
     int breakType = stream.ReadInt32();
     string desc = stream.ReadString();
     if (typeName != null && desc != null) {
         Debug.WriteLine("Exception: " + desc);
         var excepRaised = ExceptionRaised;
         if (excepRaised != null) {
             excepRaised(this, new ExceptionRaisedEventArgs(_threads[tid], new PythonException(typeName, desc), breakType == 1 /* BREAK_TYPE_UNHANLDED */));
         }
     }
     _stoppedForException = true;
 }
Esempio n. 47
0
 private void HandleAsyncBreak(Stream stream) {
     long tid = stream.ReadInt64();
     var thread = _threads[tid];
     var asyncBreak = AsyncBreakComplete;
     Debug.WriteLine("Received async break command from thread {0}", tid);
     if (asyncBreak != null) {
         asyncBreak(this, new ThreadEventArgs(thread));
     }
 }
Esempio n. 48
0
 public static object Read(Stream stream)
 {
     return stream.ReadInt64();
 }
Esempio n. 49
0
 /// <summary>
 /// インスタンスを初期化します。
 /// </summary>
 /// <param name="src">ヘッダの開始位置を指しているデータ ストリーム。</param>
 public ObjectHeader( Stream src )
 {
     this.Guid = src.ReadGuid();
     this.Size = src.ReadInt64();
 }