Esempio n. 1
0
        public int Read(byte[] buffer, int offset, int count)
        {
            var toread = Math.Min(count, BytesToRead);

            return(BaseStream.Read(buffer, offset, toread));
        }
Esempio n. 2
0
        public byte[] ReadPacket()
        {
            byte[] buffer    = new byte[260];
            int    count     = 0;
            int    length    = 0;
            int    readcount = 0;

            lastbad = new byte[2];

            BaseStream.ReadTimeout = 1200; // 1200 ms between chars - the gps detection requires this.

            DateTime start = DateTime.Now;

            lock (readlock)
            {
                while (BaseStream.IsOpen)
                {
                    try
                    {
                        if (readcount > 300)
                        {
                            //No valid mavlink package
                            break;
                        }
                        readcount++;
                        //MAV.cs.datetime = DateTime.Now;

                        DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);

                        // Console.WriteLine(DateTime.Now.Millisecond + " SR1a " + BaseStream.BytesToRead);

                        while (BaseStream.IsOpen && BaseStream.BytesToRead <= 0)
                        {
                            if (DateTime.Now > to)
                            {
                                //log.InfoFormat("MAVLINK: 1 wait time out btr {0} len {1}", BaseStream.BytesToRead, length);
                                throw new Exception("Timeout");
                            }
                            System.Threading.Thread.Sleep(1);
                            //Console.WriteLine(DateTime.Now.Millisecond + " SR0b " + BaseStream.BytesToRead);
                        }

                        if (BaseStream.IsOpen)
                        {
                            BaseStream.Read(buffer, count, 1);
                        }
                    }
                    catch (Exception e)
                    {
                        break;
                    }

                    // check if looks like a mavlink packet and check for exclusions and write to console
                    if (buffer[0] != 254)
                    {
                        if (buffer[0] >= 0x20 && buffer[0] <= 127 || buffer[0] == '\n' || buffer[0] == '\r')
                        {
                            // check for line termination
                            if (buffer[0] == '\r' || buffer[0] == '\n')
                            {
                                // check new line is valid
                                if (buildplaintxtline.Length > 3)
                                {
                                    plaintxtline = buildplaintxtline;
                                }

                                // reset for next line
                                buildplaintxtline = "";
                            }
                            form.UpdateTextBox(((char)buffer[0]).ToString());
                            //TCPConsole.Write(buffer[0]);
                            //Console.Write((char)buffer[0]);
                            buildplaintxtline += (char)buffer[0];
                        }
                        _bytesReceivedSubj.OnNext(1);
                        count      = 0;
                        lastbad[0] = lastbad[1];
                        lastbad[1] = buffer[0];
                        buffer[1]  = 0;
                        continue;
                    }
                    // reset count on valid packet
                    readcount = 0;

                    // check for a header
                    if (buffer[0] == 254)
                    {
                        if (count == 0)
                        {
                            DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);
                            while (BaseStream.IsOpen && BaseStream.BytesToRead < 5)
                            {
                                if (DateTime.Now > to)
                                {
                                    throw new Exception("Timeout");
                                }
                                System.Threading.Thread.Sleep(1);
                            }
                            int read = BaseStream.Read(buffer, 1, 5);
                            count = read;
                        }
                        // packet length
                        length = buffer[1] + 6 + 2 - 2; // data + header + checksum - U - length
                        if (count >= 5)
                        {
                            if (MAV.sysid != 0)
                            {
                                if (MAV.sysid != buffer[3] || MAV.compid != buffer[4])
                                {
                                    if (buffer[3] == '3' && buffer[4] == 'D')
                                    {
                                        // this is a 3dr radio rssi packet
                                    }
                                    else
                                    {
                                        //log.InfoFormat("Mavlink Bad Packet (not addressed to this MAV) got {0} {1} vs {2} {3}", buffer[3], buffer[4], MAV.sysid, MAV.compid);
                                        return(new byte[0]);
                                    }
                                }
                            }

                            try
                            {
                                DateTime to = DateTime.Now.AddMilliseconds(BaseStream.ReadTimeout);

                                while (BaseStream.IsOpen && BaseStream.BytesToRead < (length - 4))
                                {
                                    if (DateTime.Now > to)
                                    {
                                        //log.InfoFormat("MAVLINK: 3 wait time out btr {0} len {1}", BaseStream.BytesToRead, length);
                                        break;
                                    }
                                    System.Threading.Thread.Sleep(1);
                                }
                                if (BaseStream.IsOpen)
                                {
                                    int read = BaseStream.Read(buffer, 6, length - 4);
                                }
                                count = length + 2;
                            }
                            catch
                            {
                                break;
                            }

                            break;
                        }
                    }

                    count++;
                    if (count == 299)
                    {
                        break;
                    }
                }
            } // end readlock

            Array.Resize <byte>(ref buffer, count);

            _bytesReceivedSubj.OnNext(buffer.Length);

            if (packetlosttimer.AddSeconds(5) < DateTime.Now)
            {
                packetlosttimer = DateTime.Now;
                packetslost     = (packetslost * 0.8f);
                packetsnotlost  = (packetsnotlost * 0.8f);
            }

            if (bpstime.Second != DateTime.Now.Second && BaseStream.IsOpen)
            {
                Console.Write("bps {0} loss {1} left {2} mem {3}      \n", bps1, synclost, BaseStream.BytesToRead, System.GC.GetTotalMemory(false) / 1024 / 1024.0);
                bps2    = bps1; // prev sec
                bps1    = 0;    // current sec
                bpstime = DateTime.Now;
            }

            bps1 += buffer.Length;
            bps   = (bps1 + bps2) / 2;

            ushort crc = MavlinkCRC.crc_calculate(buffer, buffer.Length - 2);

            if (buffer.Length > 5 && buffer[0] == 254)
            {
                crc = MavlinkCRC.crc_accumulate(MAVLINK_MESSAGE_CRCS[buffer[5]], crc);
            }

            if (buffer.Length > 5 && buffer[1] != MAVLINK_MESSAGE_LENGTHS[buffer[5]])
            {
                if (MAVLINK_MESSAGE_LENGTHS[buffer[5]] == 0) // pass for unknown packets
                {
                }
                else
                {
                    //log.InfoFormat("Mavlink Bad Packet (Len Fail) len {0} pkno {1}", buffer.Length, buffer[5]);
                    if (buffer.Length == 11 && buffer[0] == 'U' && buffer[5] == 0)
                    {
                        string message = "Mavlink 0.9 Heartbeat, Please upgrade your AP, This planner is for Mavlink 1.0\n\n";
                        MessageBox.Show(message);
                        throw new Exception(message);
                    }
                    return(new byte[0]);
                }
            }

            if (buffer.Length < 5 || buffer[buffer.Length - 1] != (crc >> 8) || buffer[buffer.Length - 2] != (crc & 0xff))
            {
                int packetno = -1;
                if (buffer.Length > 5)
                {
                    packetno = buffer[5];
                }
                if (packetno != -1 && buffer.Length > 5 && MAVLINK_MESSAGE_INFO[packetno] != null)
                {
                    //log.InfoFormat("Mavlink Bad Packet (crc fail) len {0} crc {1} vs {4} pkno {2} {3}", buffer.Length, crc, packetno, MAVLINK_MESSAGE_INFO[packetno].ToString(), BitConverter.ToUInt16(buffer, buffer.Length - 2));
                    form.UpdateTextBox("Mavlink Bad Packet.");
                }
                return(new byte[0]);
            }

            try
            {
                if ((buffer[0] == 'U' || buffer[0] == 254) && buffer.Length >= buffer[1])
                {
                    if (buffer[3] == '3' && buffer[4] == 'D')
                    {
                        // Do nothing
                    }
                    else
                    {
                        byte packetSeqNo         = buffer[2];
                        int  expectedPacketSeqNo = ((MAV.recvpacketcount + 1) % 0x100);

                        if (packetSeqNo != expectedPacketSeqNo)
                        {
                            synclost++; // actualy sync loss's
                            int numLost = 0;

                            if (packetSeqNo < ((MAV.recvpacketcount + 1))) // recvpacketcount = 255 then   10 < 256 = true if was % 0x100 this would fail
                            {
                                numLost = 0x100 - expectedPacketSeqNo + packetSeqNo;
                            }
                            else
                            {
                                numLost = packetSeqNo - MAV.recvpacketcount;
                            }
                            packetslost += numLost;
                            WhenPacketLost.OnNext(numLost);

                            //log.InfoFormat("lost pkts new seqno {0} pkts lost {1}", packetSeqNo, numLost);
                        }

                        packetsnotlost++;
                        MAV.recvpacketcount = packetSeqNo;
                        WhenPacketReceived.OnNext(1);
                    }

                    if (double.IsInfinity(packetspersecond[buffer[5]]))
                    {
                        packetspersecond[buffer[5]] = 0;
                    }

                    packetspersecond[buffer[5]] = (((1000 / ((DateTime.Now - packetspersecondbuild[buffer[5]]).TotalMilliseconds) + packetspersecond[buffer[5]]) / 2));

                    packetspersecondbuild[buffer[5]] = DateTime.Now;

                    lock (writelock)
                    {
                        MAV.packets[buffer[5]] = buffer;
                        MAV.packetseencount[buffer[5]]++;
                    }

                    if (buffer[5] == (byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT) // status text
                    {
                        var msg = MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT].ByteArrayToStructure <MAVLink.mavlink_statustext_t>(6);

                        byte sev = msg.severity;

                        string logdata = Encoding.ASCII.GetString(msg.text);
                        int    ind     = logdata.IndexOf('\0');
                        if (ind != -1)
                        {
                            logdata = logdata.Substring(0, ind);
                        }
                        //log.Info(DateTime.Now + " " + logdata);

                        form.UpdateTextBox(logdata);
                        //MAV.cs.messages.Add(logdata);

                        if (sev >= 3)
                        {
                        }
                    }

                    // set ap type
                    if (buffer[5] == (byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT)
                    {
                        mavlink_heartbeat_t hb = buffer.ByteArrayToStructure <mavlink_heartbeat_t>(6);

                        if (hb.type != (byte)MAVLink.MAV_TYPE.GCS)
                        {
                            mavlinkversion = hb.mavlink_version;
                            MAV.aptype     = (MAV_TYPE)hb.type;
                            MAV.apname     = (MAV_AUTOPILOT)hb.autopilot;
                            //setAPType();
                        }
                    }
                }
            }
            catch { }

            if (buffer[3] == '3' && buffer[4] == 'D')
            {
                // dont update last packet time for 3dr radio packets
            }
            else
            {
                lastvalidpacket = DateTime.Now;
            }

            return(buffer);
        }
Esempio n. 3
0
        // TODO: How to know VxD structure offset
        void Initialize()
        {
            Recognized = false;
            if (BaseStream == null)
            {
                return;
            }

            BaseExecutable = new MZ(BaseStream);
            if (!BaseExecutable.Recognized)
            {
                return;
            }

            if (BaseExecutable.Header.new_offset >= BaseStream.Length)
            {
                return;
            }

            BaseStream.Seek(BaseExecutable.Header.new_offset, SeekOrigin.Begin);
            byte[] buffer = new byte[Marshal.SizeOf(typeof(LXHeader))];
            BaseStream.Read(buffer, 0, buffer.Length);
            IntPtr hdrPtr = Marshal.AllocHGlobal(buffer.Length);

            Marshal.Copy(buffer, 0, hdrPtr, buffer.Length);
            Header = (LXHeader)Marshal.PtrToStructure(hdrPtr, typeof(LXHeader));
            Marshal.FreeHGlobal(hdrPtr);
            Recognized = Header.signature == SIGNATURE || Header.signature == SIGNATURE16;

            if (!Recognized)
            {
                return;
            }

            Type        = Header.signature == SIGNATURE16 ? "Linear Executable (LE)" : "Linear eXecutable (LX)";
            IsBigEndian = Header.byte_order == 1 || Header.word_order == 1;
            List <string> strings = new List <string>();

            OperatingSystem reqOs = new OperatingSystem();

            switch (Header.os_type)
            {
            case TargetOS.OS2:
                reqOs.Name = "OS/2";
                if (Header.module_flags.HasFlag(ModuleFlags.PMIncompatible) &&
                    !Header.module_flags.HasFlag(ModuleFlags.PMCompatible) ||
                    !Header.module_flags.HasFlag(ModuleFlags.PMIncompatible) &&
                    Header.module_flags.HasFlag(ModuleFlags.PMCompatible))
                {
                    reqOs.Subsystem = "Console";
                }
                else if (Header.module_flags.HasFlag(ModuleFlags.PMIncompatible) &&
                         Header.module_flags.HasFlag(ModuleFlags.PMCompatible))
                {
                    reqOs.Subsystem = "Presentation Manager";
                }
                break;

            case TargetOS.Windows:
            case TargetOS.Win32:
            case TargetOS.Unknown:
                reqOs.Name = "Windows";
                break;

            case TargetOS.DOS:
                reqOs.Name = "Windows";
                break;

            default:
                reqOs.Name = $"Unknown code {(ushort)Header.os_type}";
                break;
            }

            RequiredOperatingSystem = reqOs;

            if (Header.resident_names_off != 0)
            {
                ResidentNames =
                    GetResidentStrings(BaseStream, BaseExecutable.Header.new_offset, Header.resident_names_off);

                if (ResidentNames.Length >= 1)
                {
                    ModuleName = ResidentNames[0].name;

                    if (ResidentNames.Length > 1)
                    {
                        NE.ResidentName[] newResidentNames = new NE.ResidentName[ResidentNames.Length - 1];
                        Array.Copy(ResidentNames, 1, newResidentNames, 0, ResidentNames.Length - 1);
                        ResidentNames = newResidentNames;
                    }
                    else
                    {
                        ResidentNames = null;
                    }
                }
            }

            if (Header.nonresident_name_table_len > 0)
            {
                NonResidentNames = GetResidentStrings(BaseStream, 0, Header.nonresident_name_table_off);

                if (NonResidentNames.Length >= 1)
                {
                    ModuleDescription = NonResidentNames[0].name;

                    if (NonResidentNames.Length > 1)
                    {
                        NE.ResidentName[] newNonResidentNames = new NE.ResidentName[NonResidentNames.Length - 1];
                        Array.Copy(NonResidentNames, 1, newNonResidentNames, 0, NonResidentNames.Length - 1);
                        NonResidentNames = newNonResidentNames;
                    }
                    else
                    {
                        NonResidentNames = null;
                    }
                }
            }

            if (Header.import_module_table_off != 0 && Header.import_module_entries > 0)
            {
                BaseStream.Position = Header.import_module_table_off + BaseExecutable.Header.new_offset;
                ImportedNames       = new string[Header.import_module_entries];
                for (int i = 0; i < Header.import_module_entries; i++)
                {
                    int len = BaseStream.ReadByte();
                    buffer = new byte[len];
                    BaseStream.Read(buffer, 0, len);
                    ImportedNames[i] = Encoding.ASCII.GetString(buffer);
                }
            }

            if (!string.IsNullOrEmpty(ModuleName))
            {
                strings.Add(ModuleName);
            }
            if (!string.IsNullOrEmpty(ModuleDescription))
            {
                strings.Add(ModuleDescription);
            }

            objectTableEntries     = new ObjectTableEntry[Header.obj_no];
            objectPageTableEntries = new ObjectPageTableEntry[Header.module_pages_no];

            BaseStream.Position = Header.obj_table_off + BaseExecutable.Header.new_offset;
            buffer = new byte[Marshal.SizeOf(typeof(ObjectTableEntry))];
            for (int i = 0; i < Header.obj_no; i++)
            {
                BaseStream.Read(buffer, 0, buffer.Length);
                objectTableEntries[i] = BigEndianMarshal.ByteArrayToStructureLittleEndian <ObjectTableEntry>(buffer);
            }

            BaseStream.Position = Header.obj_page_table_off + BaseExecutable.Header.new_offset;

            if (Header.signature == SIGNATURE16)
            {
                buffer = new byte[Marshal.SizeOf(typeof(ObjectPageTableEntry16))];
                for (int i = 0; i < Header.module_pages_no; i++)
                {
                    BaseStream.Read(buffer, 0, buffer.Length);
                    ObjectPageTableEntry16 page16 =
                        BigEndianMarshal.ByteArrayToStructureLittleEndian <ObjectPageTableEntry16>(buffer);

                    int pageNo = (page16.High << 8) + page16.Low;

                    objectPageTableEntries[i] = new ObjectPageTableEntry
                    {
                        DataSize       = (ushort)Header.page_size,
                        Flags          = (PageTableAttributes)page16.Flags,
                        PageDataOffset = (uint)((pageNo - 1) * Header.page_size)
                    };
                }
            }
            else
            {
                buffer = new byte[Marshal.SizeOf(typeof(ObjectPageTableEntry))];
                for (int i = 0; i < Header.module_pages_no; i++)
                {
                    BaseStream.Read(buffer, 0, buffer.Length);
                    objectPageTableEntries[i] =
                        BigEndianMarshal.ByteArrayToStructureLittleEndian <ObjectPageTableEntry>(buffer);
                }
            }

            int debugSections   = 0;
            int winrsrcSections = 0;

            if (Header.debug_info_len > 0)
            {
                debugSections = 1;
            }
            if (Header.win_res_len > 0)
            {
                winrsrcSections = 1;
            }

            Segment[] sections = new Segment[objectTableEntries.Length + debugSections + winrsrcSections];
            for (int i = 0; i < objectTableEntries.Length; i++)
            {
                sections[i] = new Segment {
                    Flags = $"{objectTableEntries[i].ObjectFlags}"
                };
                if (objectTableEntries[i].ObjectFlags.HasFlag(ObjectFlags.Resource))
                {
                    sections[i].Name = ".rsrc";
                }
                else if (objectTableEntries[i].ObjectFlags.HasFlag(ObjectFlags.Executable))
                {
                    sections[i].Name = ".text";
                }
                else if (!objectTableEntries[i].ObjectFlags.HasFlag(ObjectFlags.Writable))
                {
                    sections[i].Name = ".rodata";
                }
                else if (StringHandlers.CToString(objectTableEntries[i].Name).ToLower() == "bss")
                {
                    sections[i].Name = ".bss";
                }
                else if (!string.IsNullOrWhiteSpace(StringHandlers.CToString(objectTableEntries[i].Name).Trim()))
                {
                    sections[i].Name = StringHandlers.CToString(objectTableEntries[i].Name).Trim();
                }
                else
                {
                    sections[i].Name = ".data";
                }

                if (objectTableEntries[i].PageTableEntries == 0 ||
                    objectTableEntries[i].PageTableIndex > objectPageTableEntries.Length)
                {
                    sections[i].Size = objectTableEntries[i].VirtualSize;
                    continue;
                }

                int shift = (int)(Header.signature == SIGNATURE16 ? 0 : Header.page_off_shift);

                if (objectPageTableEntries[objectTableEntries[i].PageTableIndex - 1]
                    .Flags.HasFlag(PageTableAttributes.IteratedDataPage))
                {
                    sections[i].Offset =
                        (objectPageTableEntries[objectTableEntries[i].PageTableIndex - 1].PageDataOffset << shift) +
                        Header.obj_iter_pages_off;
                }
                else if (objectPageTableEntries[objectTableEntries[i].PageTableIndex - 1]
                         .Flags.HasFlag(PageTableAttributes.LegalPhysicalPage))
                {
                    sections[i].Offset =
                        (objectPageTableEntries[objectTableEntries[i].PageTableIndex - 1].PageDataOffset << shift) +
                        Header.data_pages_off;
                }
                else
                {
                    sections[i].Offset = 0;
                }

                sections[i].Size = 0;
                for (int j = 0; j < objectTableEntries[i].PageTableEntries; j++)
                {
                    sections[i].Size += objectPageTableEntries[j + objectTableEntries[i].PageTableIndex - 1].DataSize;
                }

                if (sections[i].Offset + sections[i].Size > BaseStream.Length)
                {
                    sections[i].Size = BaseStream.Length - sections[i].Offset;
                }
            }

            if (winrsrcSections > 0)
            {
                sections[sections.Length - debugSections - winrsrcSections] = new Segment
                {
                    Name   = ".rsrc",
                    Size   = Header.win_res_len,
                    Offset = Header.win_res_off
                }
            }
            ;

            if (debugSections > 0)
            {
                sections[sections.Length - debugSections] = new Segment
                {
                    Name   = ".debug",
                    Size   = Header.debug_info_len,
                    Offset = Header.debug_info_off
                }
            }
            ;

            // It only contains a RT_VERSION resource prefixed by some 12-byte header I can't find information about, so let's just skip it.
            if (winrsrcSections > 0)
            {
                buffer = new byte[Header.win_res_len];
                BaseStream.Position = Header.win_res_off + 12;
                BaseStream.Read(buffer, 0, buffer.Length);
                WinVersion = new NE.Version(buffer);
                strings.AddRange(from s in WinVersion.StringsByLanguage from k in s.Value select k.Value);
            }

            resources           = new ResourceTableEntry[Header.resource_entries];
            BaseStream.Position = Header.resource_table_off + BaseExecutable.Header.new_offset;
            buffer = new byte[Marshal.SizeOf(typeof(ResourceTableEntry))];
            for (int i = 0; i < resources.Length; i++)
            {
                BaseStream.Read(buffer, 0, buffer.Length);
                resources[i] = BigEndianMarshal.ByteArrayToStructureLittleEndian <ResourceTableEntry>(buffer);
            }

            SortedDictionary <ResourceTypes, List <NE.Resource> > os2Resources =
                new SortedDictionary <ResourceTypes, List <NE.Resource> >();

            for (int i = 0; i < resources.Length; i++)
            {
                os2Resources.TryGetValue(resources[i].type, out List <NE.Resource> thisResourceType);

                if (thisResourceType == null)
                {
                    thisResourceType = new List <NE.Resource>();
                }

                NE.Resource thisResource = new NE.Resource
                {
                    id         = resources[i].id,
                    name       = $"{resources[i].id}",
                    flags      = 0,
                    dataOffset = (uint)(sections[resources[i].obj_no - 1].Offset + resources[i].offset),
                    length     = resources[i].size
                };

                thisResource.data   = new byte[thisResource.length];
                BaseStream.Position = thisResource.dataOffset;
                BaseStream.Read(thisResource.data, 0, thisResource.data.Length);

                thisResourceType.Add(thisResource);
                os2Resources.Remove(resources[i].type);
                os2Resources.Add(resources[i].type, thisResourceType);
            }

            if (os2Resources.Count > 0)
            {
                neFormatResourceTable = new NE.ResourceTable();
                int counter = 0;
                neFormatResourceTable.types = new NE.ResourceType[os2Resources.Count];
                foreach (KeyValuePair <ResourceTypes, List <NE.Resource> > kvp in os2Resources)
                {
                    neFormatResourceTable.types[counter].count     = (ushort)kvp.Value.Count;
                    neFormatResourceTable.types[counter].id        = (ushort)kvp.Key;
                    neFormatResourceTable.types[counter].name      = Resources.IdToName((ushort)kvp.Key);
                    neFormatResourceTable.types[counter].resources = kvp.Value.OrderBy(r => r.id).ToArray();
                    counter++;
                }

                foreach (NE.ResourceType rtype in neFormatResourceTable.types)
                {
                    if (rtype.name != "RT_STRING")
                    {
                        continue;
                    }

                    strings.AddRange(NE.GetOs2Strings(rtype));
                }
            }

            Segments = sections;
            Strings  = strings;
        }
Esempio n. 4
0
 private void FillInternalBuffer(int count)
 {
     BaseStream.Read(this.buffer, 0, count);
 }
Esempio n. 5
0
        public int Read(byte[] buffer, int offset, int count)
        {
            if (!IsOpen)
            {
                throw new EndOfStreamException("File not open");
            }

            while (true)
            {
                // check if we have credit and continue
                if (count < bytecredit)
                {
                    bytecredit -= count;
                    break;
                }

                // get the time taken since last read in seconds
                double LapsedSinceLastRead = (DateTime.Now - lastread).TotalSeconds;

                // escape if we are out of range
                if (LapsedSinceLastRead < 0 || LapsedSinceLastRead > 2)
                {
                    break;
                }

                // get our target bps for this time slice.
                int targetbps = (int)(bps * LapsedSinceLastRead) + bytecredit;

                // check if out target+count is less than our required bps
                if (count < targetbps)
                {
                    bytecredit = targetbps - count;
                    break;
                }

                System.Threading.Thread.Sleep(1);
            }

            lastread = DateTime.Now;

            if (lastsecond != DateTime.Now.Second)
            {
                Console.WriteLine("CommsFile Read bps {0}", currentbps);
                currentbps = 0;
                lastsecond = DateTime.Now.Second;
            }
            currentbps += count;
            int ret = BaseStream.Read(buffer, offset, count);

            if (buffer[0] == 254 && offset == 1)
            {
                step = buffer[1] + 5 + 2; // + header + checksum
            }
            step -= ret;

            // read the timestamp
            //if (step == 0)
            //BaseStream.Read(new byte[8], 0, 8);

            return(ret);
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            int read = 0;

            for (int i = offset; read < count; i++)
            {
                if (MaxReadPosition >= 0 && BaseStream.Position >= MaxReadPosition)
                {
                    break;
                }

                if (BaseStream.Read(_singleBuf, 0, 1) <= 0)
                {
                    break;
                }

                var b = _singleBuf[0];
                if (_bytesAfterEqualsSign == 0)
                {
                    if (b == '=')
                    {
                        _bytesAfterEqualsSign = 1;
                        continue;
                    }
                    buffer[read++] = b;
                    continue;
                }

                _triBuf[_bytesAfterEqualsSign] = b;
                _bytesAfterEqualsSign++;
                if (_bytesAfterEqualsSign < 3)
                {
                    continue;
                }
                _bytesAfterEqualsSign = 0;

                if (_triBuf[1] == '\r' || _triBuf[1] == '\n')
                {
                    if (!IgnoreErrors && _triBuf[2] != '\r' && _triBuf[2] != '\n')
                    {
                        throw new InvalidOperationException("Cannot decode sequence =" + Escape(_triBuf[1]) + Escape(_triBuf[2]));
                    }
                    continue;
                }

                int val1 = _triBuf[1];
                val1 -= (val1 < 58 ? 48 : (val1 < 97 ? 55 : 87));
                int val2 = _triBuf[2];
                val2 -= (val2 < 58 ? 48 : (val2 < 97 ? 55 : 87));
                if (val1 < 0 || val1 > 15)
                {
                    if (!IgnoreErrors)
                    {
                        throw new InvalidOperationException("Cannot decode sequence =" + Escape(_triBuf[1]) + Escape(_triBuf[2]));
                    }
                    val1 = 0;
                    val2 = 0;
                }
                if (val2 < 0 || val2 > 15)
                {
                    if (!IgnoreErrors)
                    {
                        throw new InvalidOperationException("Cannot decode sequence =" + Escape(_triBuf[1]) + Escape(_triBuf[2]));
                    }
                    val1 = 0;
                    val2 = 0;
                }
                buffer[read++] = ((byte)((val1 << 4) | val2));
            }
            return(read);
        }
Esempio n. 7
0
        /// <summary>
        /// Read a string while checking the string precursor for intern opportunities.
        /// Taken from ndp\clr\src\bcl\system\io\binaryreader.cs-ReadString()
        /// </summary>
        override public String ReadString()
        {
            char[] resultBuffer = null;
            try
            {
                MemoryStream memoryStream = this.BaseStream as MemoryStream;

                int currPos = 0;
                int n       = 0;
                int stringLength;
                int readLength;
                int charsRead = 0;

                // Length of the string in bytes, not chars
                stringLength = Read7BitEncodedInt();
                if (stringLength < 0)
                {
                    throw new IOException();
                }

                if (stringLength == 0)
                {
                    return(String.Empty);
                }

                char[] charBuffer = _buffer.CharBuffer;
                do
                {
                    readLength = ((stringLength - currPos) > MaxCharsBuffer) ? MaxCharsBuffer : (stringLength - currPos);

                    byte[] rawBuffer   = null;
                    int    rawPosition = 0;

                    if (memoryStream != null)
                    {
                        // Optimization: we can avoid reading into a byte buffer
                        // and instead read directly from the memorystream's backing buffer
                        rawBuffer   = memoryStream.GetBuffer();
                        rawPosition = (int)memoryStream.Position;
                        int length = (int)memoryStream.Length;
                        n = (rawPosition + readLength) < length ? readLength : length - rawPosition;

                        // Attempt to track down an intermittent failure -- n should not ever be negative, but
                        // we're occasionally seeing it when we do the decoder.GetChars below -- by providing
                        // a bit more information when we do hit the error, in the place where (by code inspection)
                        // the actual error seems most likely to be occurring.
                        if (n < 0)
                        {
                            ErrorUtilities.ThrowInternalError("From calculating based on the memorystream, about to read n = {0}. length = {1}, rawPosition = {2}, readLength = {3}, stringLength = {4}, currPos = {5}.", n, length, rawPosition, readLength, stringLength, currPos);
                        }

                        memoryStream.Seek(n, SeekOrigin.Current);
                    }

                    if (rawBuffer == null)
                    {
                        rawBuffer   = _buffer.ByteBuffer;
                        rawPosition = 0;
                        n           = BaseStream.Read(rawBuffer, 0, readLength);

                        // See above explanation -- the OutOfRange exception may also be coming from our setting of n here ...
                        if (n < 0)
                        {
                            ErrorUtilities.ThrowInternalError("From getting the length out of BaseStream.Read directly, about to read n = {0}. readLength = {1}, stringLength = {2}, currPos = {3}", n, readLength, stringLength, currPos);
                        }
                    }

                    if (n == 0)
                    {
                        throw new EndOfStreamException();
                    }

                    if (currPos == 0 && n == stringLength)
                    {
                        charsRead = _decoder.GetChars(rawBuffer, rawPosition, n, charBuffer, 0);
                        return(Strings.WeakIntern(charBuffer.AsSpan(0, charsRead)));
                    }
#if !CLR2COMPATIBILITY
                    resultBuffer ??= ArrayPool <char> .Shared.Rent(stringLength); // Actual string length in chars may be smaller.
#else
                    // Since NET35 is only used in rare TaskHost processes, we decided to leave it as-is.
                    resultBuffer ??= new char[stringLength]; // Actual string length in chars may be smaller.
#endif
                    charsRead += _decoder.GetChars(rawBuffer, rawPosition, n, resultBuffer, charsRead);

                    currPos += n;
                }while (currPos < stringLength);

                var retval = Strings.WeakIntern(resultBuffer.AsSpan(0, charsRead));

                return(retval);
            }
            catch (Exception e)
            {
                Debug.Assert(false, e.ToString());
                throw;
            }
#if !CLR2COMPATIBILITY
            finally
            {
                // resultBuffer shall always be either Rented or null
                if (resultBuffer != null)
                {
                    ArrayPool <char> .Shared.Return(resultBuffer);
                }
            }
#endif
        }
Esempio n. 8
0
 /// <summary>
 /// Reads a <see cref="Double"/> from the <see cref="BaseStream"/>.
 /// </summary>
 /// <returns>The <see cref="Double"/> value.</returns>
 public Double ReadDouble()
 {
     byte[] buffer = new byte[sizeof(Double)];
     BaseStream.Read(buffer, 0, buffer.Length);
     return(Binary.ReadDouble(buffer, 0, ReadsLittleEndian));
 }
Esempio n. 9
0
 /// <summary>
 /// Reads a single byte and determines whether it
 /// represents a true value or a false value.
 /// </summary>
 /// <returns>True if the byte is non-zero, otherwise false.</returns>
 public bool ReadBoolean()
 {
     byte[] buffer = new byte[1];
     BaseStream.Read(buffer, 0, buffer.Length);
     return(buffer[0] != 0x00);
 }
Esempio n. 10
0
 public override int Read(byte[] buffer, int offset, int count) => BaseStream.Read(buffer, offset, count);
Esempio n. 11
0
 /// <summary>
 /// Reads an <see cref="Int64"/> from the <see cref="BaseStream"/>.
 /// </summary>
 /// <returns>The <see cref="Int64"/> value.</returns>
 public Int64 ReadInt64()
 {
     byte[] buffer = new byte[sizeof(Int64)];
     BaseStream.Read(buffer, 0, buffer.Length);
     return(Binary.ReadInt64(buffer, 0, ReadsLittleEndian));
 }
Esempio n. 12
0
        /// <summary>
        /// Move to the next segment line in the stream
        /// </summary>
        /// <param name="delims">Delimiters so the line can be split correctlys</param>
        /// <returns>A BaseFieldValues object that can be ingested by a derived segment type in a hard coded document format</returns>
        public BaseFieldValues ReadNextLine(Delimiters delims)
        {
            var index    = _tail;
            var exitbyte = (byte)delims.Segment;
            var sb       = new MemoryStream();

            if (_head == 0 || _tail == BufferSize || _tail == _head)
            {
                _head = BaseStream.Read(_buffer, (int)0, (int)(BufferSize));
                _tail = 0;
                index = 0;
                if (_head == 0)
                {
                    EndOfFile = true;
                    return(null);
                }
            }
            while (_buffer[index] != exitbyte)
            {
                index++;
                if (index >= BufferSize || index >= _head)
                {
                    if (BaseStream.Position == BaseStream.Length)
                    {
                        EndOfFile = true;
                        return(null);
                    }
                    if ((_buffer[_tail] == 10) ||
                        (_buffer[_tail] == 13))
                    {
                        _tail++;//since some incorrectly set line ending to \r\n
                    }
                    sb.Write(_buffer, (int)_tail, (int)(BufferSize - _tail));
                    _head = BaseStream.Read(_buffer, (int)0, (int)(BufferSize));
                    index = 0;
                    _tail = 0;
                }
            }
            var oldtail = _tail;

            _tail = index + 1;
            if (index >= _head && BaseStream.Position == BaseStream.Length)
            {
                EndOfFile = true;
            }

            if (sb.Length == 0)
            {
                if ((_buffer[oldtail] == 10 && _buffer[oldtail + 1] == 13) ||
                    (_buffer[oldtail] == 13 && _buffer[oldtail + 1] == 10))
                {
                    oldtail++;//since some incorrectly set line ending to \r\n and yet someone also did \n\r
                }
                if ((int)(index - oldtail) == 0)
                {
                    return(null);
                }
                return(new BaseFieldValues(_buffer, (int)oldtail, (int)(index - oldtail), (byte)delims.Element, delims.Component.ToString()));
            }
            else
            {
                sb.Write(_buffer, 0, (int)(index));

                return(new BaseFieldValues(sb.ToArray(), (int)oldtail, (int)(sb.Length - oldtail), (byte)delims.Element, delims.Component.ToString()));
            }
        }
Esempio n. 13
0
        public unsafe int Read(Span <byte> span)
#endif
        {
            if (_mode != Mode.Decompress)
            {
                throw new NotSupportedException("Read() not supported on compression");
            }

            // Reached end of stream
            if (_decompSrcIdx == DecompressComplete)
            {
                return(0);
            }

            int readSize      = 0;
            int destSize      = span.Length;
            int destLeftBytes = span.Length;

            if (_firstRead)
            {
                // Write FrameMagicNumber into LZ4F_decompress
                UIntPtr headerSizeVal = (UIntPtr)4;
                UIntPtr destSizeVal   = (UIntPtr)destSize;

                UIntPtr ret;
                fixed(byte *header = FrameMagicNumber)
                fixed(byte *dest = span)
                {
                    ret = LZ4Init.Lib.FrameDecompress(_dctx, dest, ref destSizeVal, header, ref headerSizeVal, null);
                }
                LZ4FrameException.CheckReturnValue(ret);

                Debug.Assert(headerSizeVal.ToUInt64() <= int.MaxValue);
                Debug.Assert(destSizeVal.ToUInt64() <= int.MaxValue);

                if (headerSizeVal.ToUInt32() != 4u)
                {
                    throw new InvalidOperationException("Not enough dest buffer");
                }
                int destWritten = (int)destSizeVal.ToUInt32();

                span      = span.Slice(destWritten);
                TotalOut += destWritten;

                _firstRead = false;
            }

            while (0 < destLeftBytes)
            {
                if (_decompSrcIdx == _decompSrcCount)
                {
                    // Read from _baseStream
                    _decompSrcIdx   = 0;
                    _decompSrcCount = BaseStream.Read(_workBuf, 0, _workBuf.Length);
                    TotalIn        += _decompSrcCount;

                    // _baseStream reached its end
                    if (_decompSrcCount == 0)
                    {
                        _decompSrcIdx = DecompressComplete;
                        break;
                    }
                }

                UIntPtr srcSizeVal  = (UIntPtr)(_decompSrcCount - _decompSrcIdx);
                UIntPtr destSizeVal = (UIntPtr)(destLeftBytes);

                UIntPtr ret;
                fixed(byte *src = _workBuf.AsSpan(_decompSrcIdx))
                fixed(byte *dest = span)
                {
                    ret = LZ4Init.Lib.FrameDecompress(_dctx, dest, ref destSizeVal, src, ref srcSizeVal, null);
                }
                LZ4FrameException.CheckReturnValue(ret);

                // The number of bytes consumed from srcBuffer will be written into *srcSizePtr (necessarily <= original value).
                Debug.Assert(srcSizeVal.ToUInt64() <= int.MaxValue);
                int srcConsumed = (int)srcSizeVal.ToUInt32();
                _decompSrcIdx += srcConsumed;
                Debug.Assert(_decompSrcIdx <= _decompSrcCount);

                // The number of bytes decompressed into dstBuffer will be written into *dstSizePtr (necessarily <= original value).
                Debug.Assert(destSizeVal.ToUInt64() <= int.MaxValue);
                int destWritten = (int)destSizeVal.ToUInt32();

                span           = span.Slice(destWritten);
                destLeftBytes -= destWritten;
                TotalOut      += destWritten;
                readSize      += destWritten;
            }

            return(readSize);
        }
Esempio n. 14
0
            public void DecodeStream()
            {
                // Reset position to use same buffer
                zlibMemoryStream.Position = 0;

                // Get compressed stream length to read
                var buff = new byte[4];

                if (BaseStream.Read(buff, 0, 4) != 4)
                {
                    throw new Exception("ZRLE decoder: Invalid compressed stream size");
                }

                // BigEndian to LittleEndian conversion
                var compressedBufferSize = buff[3] | (buff[2] << 8) | (buff[1] << 16) | (buff[0] << 24);

                if (compressedBufferSize > 64 * 1024 * 1024)
                {
                    throw new Exception("ZRLE decoder: Invalid compressed data size");
                }

                #region Decode stream

                // Decode stream
                // int pos = 0;
                // while (pos++ < compressedBufferSize)
                //  zlibDecompressedStream.WriteByte(this.BaseStream.ReadByte());

                #endregion

                #region Decode stream in blocks

                // Decode stream in blocks
                var       bytesNeeded   = compressedBufferSize;
                const int maxBufferSize = 64 * 1024; // 64k buffer
                var       receiveBuffer = new byte[maxBufferSize];
                var       netStream     = (NetworkStream)BaseStream;
                netStream.ReadTimeout = 15000; // Set timeout to 15s
                do
                {
                    if (netStream.DataAvailable)
                    {
                        var bytesToRead = bytesNeeded;

                        // the byteToRead should never exceed the maxBufferSize
                        if (bytesToRead > maxBufferSize)
                        {
                            bytesToRead = maxBufferSize;
                        }

                        // try reading bytes (read in 1024 byte chunks) - improvement for slow connections
                        var toRead    = bytesToRead > 1024 ? 1024 : bytesToRead;
                        var bytesRead = 0;
                        try
                        {
                            bytesRead = netStream.Read(receiveBuffer, bytesRead, toRead);
                        }
                        catch
                        {
                        }

                        // lower the bytesNeeded with the bytesRead.
                        bytesNeeded -= bytesRead;

                        // write the readed bytes to the decompression stream.
                        zlibDecompressedStream.Write(receiveBuffer, 0, bytesRead);
                    }
                    else
                    // there isn't any data atm. let's give the processor some time.
                    {
                        Thread.Sleep(100); // increased to 100ms for slow connections
                    }
                } while (bytesNeeded > 0);

                #endregion

                zlibMemoryStream.Position = 0;
            }
Esempio n. 15
0
 public override int Read(byte[] _Buffer, int _Offset, int _Count)
 {
     return(BaseStream.Read(_Buffer, 0, _Count));
 }
Esempio n. 16
0
 /// <summary>
 /// Reads an <see cref="UInt16"/> from the <see cref="BaseStream"/>.
 /// </summary>
 /// <returns>The <see cref="UInt16"/> value.</returns>
 public UInt16 ReadUInt16()
 {
     byte[] buffer = new byte[sizeof(Int16)];
     BaseStream.Read(buffer, 0, buffer.Length);
     return(Binary.ReadUInt16(buffer, 0, ReadsLittleEndian));
 }
Esempio n. 17
0
        public unsafe int Read(Span <byte> span)
#endif
        { // For Decompress
            if (_mode != Mode.Decompress)
            {
                throw new NotSupportedException("Read() not supported on compression");
            }
            if (_workBufPos == ReadDone)
            {
                return(0);
            }

            int        readSize = 0;
            LzmaAction action   = LzmaAction.Run;

            fixed(byte *readPtr = _workBuf)
            fixed(byte *writePtr = span)
            {
                _lzmaStream.NextIn   = readPtr + _workBufPos;
                _lzmaStream.NextOut  = writePtr;
                _lzmaStream.AvailOut = (uint)span.Length;

                while (_lzmaStream.AvailOut != 0)
                {
                    if (_lzmaStream.AvailIn == 0)
                    {
                        // Read from _baseStream
                        int baseReadSize = BaseStream.Read(_workBuf, 0, _workBuf.Length);
                        TotalIn += baseReadSize;

                        _workBufPos         = 0;
                        _lzmaStream.NextIn  = readPtr;
                        _lzmaStream.AvailIn = (uint)baseReadSize;

                        if (baseReadSize == 0) // End of stream
                        {
                            action = LzmaAction.Finish;
                        }
                    }

                    ulong bakAvailIn  = _lzmaStream.AvailIn;
                    ulong bakAvailOut = _lzmaStream.AvailOut;

                    LzmaRet ret = XZInit.Lib.LzmaCode(_lzmaStream, action);

                    _workBufPos += (int)(bakAvailIn - _lzmaStream.AvailIn);
                    readSize    += (int)(bakAvailOut - _lzmaStream.AvailOut);

                    // Once everything has been decoded successfully, the return value of lzma_code() will be LZMA_STREAM_END.
                    if (ret == LzmaRet.StreamEnd)
                    {
                        _workBufPos = ReadDone;
                        break;
                    }

                    // Normally the return value of lzma_code() will be LZMA_OK until everything has been encoded.
                    XZException.CheckReturnValue(ret);
                }
            }

            TotalOut += readSize;
            return(readSize);
        }
Esempio n. 18
0
 /// <summary>
 /// Reads bytes from the current position in the virtual stream.
 /// The number of bytes to read is determined by the length of the array.
 /// </summary>
 /// <param name="buffer">Array which will contain the read bytes after successful execution.</param>
 /// <returns>The total number of bytes read into the buffer.
 /// This might be less than the length of the array if that number
 /// of bytes are not currently available, or zero if the end of the stream is reached.</returns>
 public int Read(byte[] buffer)
 {
     return(BaseStream.Read(buffer, 0, buffer.Length));
 }
Esempio n. 19
0
        /// <summary>
        /// Read a string while checking the string precursor for intern opportunities.
        /// Taken from ndp\clr\src\bcl\system\io\binaryreader.cs-ReadString()
        /// </summary>
        override public String ReadString()
        {
            try
            {
                MemoryStream memoryStream = this.BaseStream as MemoryStream;

                int currPos = 0;
                int n       = 0;
                int stringLength;
                int readLength;
                int charsRead;

                // Length of the string in bytes, not chars
                stringLength = Read7BitEncodedInt();
                if (stringLength < 0)
                {
                    throw new IOException();
                }

                if (stringLength == 0)
                {
                    return(String.Empty);
                }

                char[] charBuffer = _buffer.CharBuffer;

                StringBuilder sb = null;
                do
                {
                    readLength = ((stringLength - currPos) > MaxCharsBuffer) ? MaxCharsBuffer : (stringLength - currPos);

                    byte[] rawBuffer   = null;
                    int    rawPosition = 0;

                    if (memoryStream != null)
                    {
                        // Optimization: we can avoid reading into a byte buffer
                        // and instead read directly from the memorystream's backing buffer
#if FEATURE_MEMORYSTREAM_GETBUFFER
                        rawBuffer   = memoryStream.GetBuffer();
                        rawPosition = (int)memoryStream.Position;
                        int length = (int)memoryStream.Length;
                        n = (rawPosition + readLength) < length ? readLength : length - rawPosition;

                        // Attempt to track down an intermittent failure -- n should not ever be negative, but
                        // we're occasionally seeing it when we do the decoder.GetChars below -- by providing
                        // a bit more information when we do hit the error, in the place where (by code inspection)
                        // the actual error seems most likely to be occurring.
                        if (n < 0)
                        {
                            ErrorUtilities.ThrowInternalError("From calculating based on the memorystream, about to read n = {0}. length = {1}, rawPosition = {2}, readLength = {3}, stringLength = {4}, currPos = {5}.", n, length, rawPosition, readLength, stringLength, currPos);
                        }
#else
                        ArraySegment <byte> rawBufferSegment;
                        if (memoryStream.TryGetBuffer(out rawBufferSegment))
                        {
                            rawBuffer   = rawBufferSegment.Array;
                            rawPosition = rawBufferSegment.Offset + (int)memoryStream.Position;

                            long maxReadLength = memoryStream.Length - memoryStream.Position;
                            n = readLength > maxReadLength ? (int)maxReadLength : readLength;
                        }
#endif
                    }

                    if (rawBuffer == null)
                    {
                        rawBuffer   = _buffer.ByteBuffer;
                        rawPosition = 0;
                        n           = BaseStream.Read(rawBuffer, 0, readLength);

                        // See above explanation -- the OutOfRange exception may also be coming from our setting of n here ...
                        if (n < 0)
                        {
                            ErrorUtilities.ThrowInternalError("From getting the length out of BaseStream.Read directly, about to read n = {0}. readLength = {1}, stringLength = {2}, currPos = {3}", n, readLength, stringLength, currPos);
                        }
                    }

                    if (n == 0)
                    {
                        throw new EndOfStreamException();
                    }

                    charsRead = _decoder.GetChars(rawBuffer, rawPosition, n, charBuffer, 0);

                    if (memoryStream != null)
                    {
                        memoryStream.Seek(readLength, SeekOrigin.Current);
                    }

                    if (currPos == 0 && n == stringLength)
                    {
                        return(OpportunisticIntern.CharArrayToString(charBuffer, charsRead));
                    }

                    if (sb == null)
                    {
                        sb = new StringBuilder(stringLength); // Actual string length in chars may be smaller.
                    }

                    sb.Append(charBuffer, 0, charsRead);
                    currPos += n;
                }while (currPos < stringLength);

                return(OpportunisticIntern.StringBuilderToString(sb));
            }
            catch (Exception e)
            {
                Debug.Assert(false, e.ToString());
                throw;
            }
        }
Esempio n. 20
0
 /// <summary>
 /// Reads bytes from the current position in the virtual stream.
 /// </summary>
 /// <param name="buffer">Array which will contain the read bytes after successful execution.</param>
 /// <param name="count">Number of bytes to read.</param>
 /// <returns>The total number of bytes read into the buffer.
 /// This might be less than the number of bytes requested if that number
 /// of bytes are not currently available, or zero if the end of the stream is reached.</returns>
 public int Read(byte[] buffer, int count)
 {
     return(BaseStream.Read(buffer, 0, count));
 }
Esempio n. 21
0
 /// <summary>
 /// Return the bytes requested from the container
 /// </summary>
 public override int Read(byte[] buffer, int offset, int count)
 {
     // throw if version missing
     ReadAttempt(true);
     return(BaseStream.Read(buffer, offset, count));
 }
 /* ----------------------------------------------------------------- */
 ///
 /// Read
 ///
 /// <summary>
 /// データを読み込みます。
 /// </summary>
 ///
 /// <param name="buffer">バッファ</param>
 /// <param name="size">読み込むサイズ</param>
 ///
 /// <returns>実際に読み込まれたサイズ</returns>
 ///
 /* ----------------------------------------------------------------- */
 public int Read(byte[] buffer, uint size) => BaseStream.Read(buffer, 0, (int)size);
Esempio n. 23
0
        void Initialize()
        {
            Recognized = false;
            if (BaseStream == null)
            {
                return;
            }

            BaseStream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[Marshal.SizeOf(typeof(GeodeHeaderV2))];
            BaseStream.Read(buffer, 0, buffer.Length);
            header  = BigEndianMarshal.ByteArrayToStructureLittleEndian <GeodeHeader>(buffer);
            header2 = BigEndianMarshal.ByteArrayToStructureLittleEndian <GeodeHeaderV2>(buffer);

            Recognized = header.magic == GEOS_ID && header.type == FileType.GFT_EXECUTABLE ||
                         header2.magic == GEOS2_ID && header2.type == FileType2.GFT_EXECUTABLE;

            if (!Recognized)
            {
                return;
            }

            isNewHeader             = header2.magic == GEOS2_ID;
            RequiredOperatingSystem = new OperatingSystem {
                Name = "GEOS", MajorVersion = isNewHeader ? 2 : 1
            };

            List <string> strings = new List <string>
            {
                StringHandlers.CToString(isNewHeader ? header2.name : header.name, geosEncoding),
                StringHandlers.CToString(isNewHeader ? header2.copyright : header.copyright, geosEncoding),
                StringHandlers.CToString(isNewHeader ? header2.info : header.info, geosEncoding)
            };

            uint segmentBase = 0;

            if (isNewHeader)
            {
                BaseStream.Position = Marshal.SizeOf(typeof(GeodeHeaderV2));
                buffer      = new byte[Marshal.SizeOf(typeof(ApplicationHeaderV2))];
                segmentBase = (uint)Marshal.SizeOf(typeof(GeodeHeaderV2));
                BaseStream.Read(buffer, 0, buffer.Length);
                applicationHeader2 = BigEndianMarshal.ByteArrayToStructureLittleEndian <ApplicationHeaderV2>(buffer);
                imports            = new Import[applicationHeader2.imports];
                exports            = new Export[applicationHeader2.exports];
                segments           = new SegmentDescriptor[applicationHeader2.segments];
                strings.Add($"{StringHandlers.CToString(applicationHeader2.name, geosEncoding).Trim()}.{StringHandlers.CToString(applicationHeader2.extension, geosEncoding).Trim()}");
            }
            else
            {
                BaseStream.Position = Marshal.SizeOf(typeof(GeodeHeader));
                buffer = new byte[Marshal.SizeOf(typeof(ApplicationHeader))];
                BaseStream.Read(buffer, 0, buffer.Length);
                applicationHeader = BigEndianMarshal.ByteArrayToStructureLittleEndian <ApplicationHeader>(buffer);
                imports           = new Import[applicationHeader.imports];
                exports           = new Export[applicationHeader.exports];
                segments          = new SegmentDescriptor[applicationHeader.segments];
                strings.Add($"{StringHandlers.CToString(applicationHeader.name, geosEncoding).Trim()}.{StringHandlers.CToString(applicationHeader.extension, geosEncoding).Trim()}");
            }

            buffer = new byte[Marshal.SizeOf(typeof(Import))];
            for (int i = 0; i < imports.Length; i++)
            {
                BaseStream.Read(buffer, 0, buffer.Length);
                imports[i] = BigEndianMarshal.ByteArrayToStructureLittleEndian <Import>(buffer);
                strings.Add(StringHandlers.CToString(imports[i].name, geosEncoding).Trim());
            }

            buffer = new byte[Marshal.SizeOf(typeof(Export))];
            for (int i = 0; i < exports.Length; i++)
            {
                BaseStream.Read(buffer, 0, buffer.Length);
                exports[i] = BigEndianMarshal.ByteArrayToStructureLittleEndian <Export>(buffer);
            }

            if (segments.Length > 0)
            {
                buffer = new byte[Marshal.SizeOf(typeof(SegmentDescriptor)) * segments.Length];
                BaseStream.Read(buffer, 0, buffer.Length);
                Segment[] mySegments = new Segment[segments.Length];

                for (int i = 0; i < segments.Length; i++)
                {
                    segments[i].length = BitConverter.ToUInt16(buffer, 2 * i);
                    segments[i].offset =
                        BitConverter.ToUInt32(buffer, 2 * segments.Length + 4 * i) + segmentBase;
                    segments[i].relocs_length = BitConverter.ToUInt16(buffer, 6 * segments.Length + 2 * i);
                    segments[i].flags         =
                        (SegmentFlags)BitConverter.ToUInt16(buffer, 8 * segments.Length + 2 * i);

                    mySegments[i] = new Segment
                    {
                        Flags  = $"{segments[i].flags}",
                        Offset = segments[i].offset,
                        Size   = segments[i].length
                    };

                    if (i == 1)
                    {
                        mySegments[i].Name = ".idata";
                    }
                    else if (segments[i].flags.HasFlag(SegmentFlags.HAF_CODE))
                    {
                        mySegments[i].Name = ".text";
                    }
                    else if (segments[i].flags.HasFlag(SegmentFlags.HAF_OBJECT_RESOURCE))
                    {
                        mySegments[i].Name = ".rsrc";
                    }
                    else if (segments[i].flags.HasFlag(SegmentFlags.HAF_ZERO_INIT))
                    {
                        mySegments[i].Name = ".bss";
                    }
                    else if (segments[i].flags.HasFlag(SegmentFlags.HAF_READ_ONLY))
                    {
                        mySegments[i].Name = ".rodata";
                    }
                    else
                    {
                        mySegments[i].Name = ".data";
                    }
                }

                Segments = mySegments;
            }

            strings.Remove("");
            strings.Remove(null);
            Strings = strings;
        }
Esempio n. 24
0
 public int ReadBlock(byte[] buffer, int offset, int size)
 {
     return(BaseStream.Read(buffer, offset, size));
 }
Esempio n. 25
0
        public string ReadString(StringStyle Style, FieldInfo Info = null)
        {
            List <byte> Buffer = new List <byte>();

            switch (Style)
            {
            case StringStyle.CString:
                while (true)
                {
                    byte Byte = base.ReadByte();
                    if (Byte < 1)
                    {
                        break;
                    }
                    Buffer.Add(Byte);
                }
                return(Encoding.GetString(Buffer.ToArray()));

            case StringStyle.UCString:
                while (true)
                {
                    byte Byte1 = base.ReadByte();
                    byte Byte2 = base.ReadByte();
                    if (Byte1 == 0x00 && Byte2 == 0x00)
                    {
                        break;
                    }
                    Buffer.Add(Byte1);
                    Buffer.Add(Byte2);
                }
                return(Encoding.GetString(Buffer.ToArray()));

            case StringStyle.PString:
                if (Info != null)
                {
                    long   Len;
                    string Prefix        = Tools.GetAttributePropertyValue(Info, Const.PSTRING, "PrefixType");
                    bool   UnicodeLength = Tools.GetAttributePropertyValue(Info, Const.PSTRING, "UnicodeLength");
                    switch (Prefix)
                    {
                    case Const.INT16:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadInt16());
                        }
                        else
                        {
                            Len = ReadInt16();
                        }
                        break;

                    case Const.UINT16:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadUInt16());
                        }
                        else
                        {
                            Len = ReadUInt16();
                        }
                        break;

                    case Const.UINT8:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadByte());
                        }
                        else
                        {
                            Len = ReadByte();
                        }
                        break;

                    case Const.INT8:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadSByte());
                        }
                        else
                        {
                            Len = ReadSByte();
                        }
                        break;

                    case Const.INT32:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadInt32());
                        }
                        else
                        {
                            Len = ReadInt32();
                        }
                        break;

                    case Const.UINT32:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadUInt32());
                        }
                        else
                        {
                            Len = ReadUInt32();
                        }
                        break;

                    case Const.INT64:
                        if (BigEndian)
                        {
                            Len = Tools.Reverse(ReadInt64());
                        }
                        else
                        {
                            Len = ReadInt64();
                        }
                        break;

                    default:
                        throw new Exception("Invalid Data Type");
                    }
                    if (UnicodeLength)
                    {
                        Len *= 2;
                    }
                    if (Len > BaseStream.Length - BaseStream.Position)
                    {
                        throw new Exception("Invalid Length");
                    }
                    byte[] Buff = new byte[Len];
                    while (Len > 0)
                    {
                        Len -= BaseStream.Read(Buff, 0, Len > int.MaxValue ? int.MaxValue : (int)Len);
                    }
                    return(Encoding.GetString(Buff));
                }
                else
                {
                    return(ReadString());
                }

            default:
                throw new Exception("Unk Value Type");
            }
        }
Esempio n. 26
0
 private byte[] ReadData(int length)
 {
     byte[] data = new byte[length];
     BaseStream.Read(data, 0, length);
     return(data);
 }
Esempio n. 27
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            var bytes = new List <byte>();

            while (currentChunkSize == 0)
            {
                var b = BaseStream.ReadByte();
                if (b < 0)
                {
                    return(0);
                }
                if (b == '\r')
                {
                    b = BaseStream.ReadByte();
                    if (b < 0)
                    {
                        return(0);
                    }
                    if (b == '\n')
                    {
                        var line = System.Text.Encoding.ASCII.GetString(bytes.ToArray());
                        bytes.Clear();
                        if (line != "")
                        {
                            int len;
                            if (Int32.TryParse(
                                    line.Split(';')[0],
                                    System.Globalization.NumberStyles.AllowHexSpecifier,
                                    System.Globalization.CultureInfo.InvariantCulture.NumberFormat,
                                    out len))
                            {
                                if (len == 0)
                                {
                                    return(0);
                                }
                                else
                                {
                                    currentChunkSize = len;
                                }
                            }
                            else
                            {
                                throw new HTTPError(HttpStatusCode.BadRequest);
                            }
                        }
                    }
                    else
                    {
                        bytes.Add((byte)'\r');
                        bytes.Add((byte)b);
                    }
                }
                else
                {
                    bytes.Add((byte)b);
                }
            }
            if (currentChunkSize > 0)
            {
                int len = BaseStream.Read(buffer, offset, Math.Min(count, currentChunkSize));
                if (len >= 0)
                {
                    offset           += len;
                    count            -= len;
                    currentChunkSize -= len;
                }
                if (currentChunkSize == 0)
                {
                    BaseStream.ReadByte(); //\r
                    BaseStream.ReadByte(); //\n
                }
                return(len);
            }
            else
            {
                return(0);
            }
        }
Esempio n. 28
0
            public override int read(sbyte [] b, int off, int len)
            {
                int r = BaseStream.Read((byte [])TypeUtils.ToByteArray(b), off, len);

                return(r == 0 ? -1 : r);
            }
Esempio n. 29
0
 /// <summary>
 /// Reads a sequence of bytes from the underlying stream and advances the position within the stream by the number of bytes read.
 /// </summary>
 /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array
 /// with the values between offset and (offset + count - 1) replaced by the bytes read from the underlying source.</param>
 /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the underlying stream.</param>
 /// <param name="count">The maximum number of bytes to be read from the underlying stream. </param>
 /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that
 /// many bytes are not currently available, or zero (0) if the end of the underlying stream has been reached.</returns>
 public override int Read(byte[] buffer, int offset, int count)
 {
     return(BaseStream.Read(buffer, offset, count));
 }
Esempio n. 30
0
 public virtual int Read(byte[] buffer, int offset, int count)
 {
     return(BaseStream.Read(buffer, offset, count));
 }