示例#1
0
        /// <summary>
        /// 一些基元类型解压缩
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="byte"></param>
        /// <param name="flag"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected bool TryDecompressTargetTypeFlag <T>(byte[] @byte, byte flag, TargetTypeFlag enumFlag, out T value)
        {
            value = default(T);

            try
            {
                switch (enumFlag)
                {
                case TargetTypeFlag.@char:
                {
                    value = (T)(dynamic)BitConverter.ToChar(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@bool:
                {
                    value = (T)(dynamic)BitConverter.ToBoolean(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@byte:
                {
                    value = (T)(dynamic)((byte)BitConverter.ToInt16(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@short:
                {
                    value = (T)(dynamic)BitConverter.ToInt16(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@ushort:
                {
                    value = (T)(dynamic)BitConverter.ToUInt16(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@int:
                {
                    value = (T)(dynamic)BitConverter.ToInt32(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@uint:
                {
                    value = (T)(dynamic)BitConverter.ToUInt32(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@long:
                {
                    value = (T)(dynamic)BitConverter.ToInt64(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@ulong:
                {
                    value = (T)(dynamic)BitConverter.ToUInt64(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@float:
                {
                    value = (T)(dynamic)BitConverter.ToSingle(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@double:
                {
                    value = (T)(dynamic)BitConverter.ToDouble(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@decimal:
                {
                    value = (T)(dynamic)((decimal)BitConverter.ToDouble(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@timespan:
                {
                    value = (T)(dynamic)TimeSpan.FromMilliseconds(BitConverter.ToDouble(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@datetime:
                {
                    value = (T)(dynamic) new DateTime(BitConverter.ToInt64(@byte, 0));
                    return(true);
                }
                }
            }
            catch
            {
            }

            return(false);
        }
示例#2
0
 public char ReadChar(IntPtr pOffset) => CheckProcess()
     ? BitConverter.ToChar(ReadByteArray(pOffset, 0x01), 0)
     : ' ';
示例#3
0
        private static void Dump()
        {
            var writer = new StreamWriter(new FileStream("dump.cs", FileMode.Create), new UTF8Encoding(false));

            Console.WriteLine("Dumping...");
            //Script
            var scriptwriter = new StreamWriter(new FileStream("script.py", FileMode.Create), new UTF8Encoding(false));

            scriptwriter.WriteLine(Resource1.ida);
            //dump image
            for (var imageIndex = 0; imageIndex < metadata.uiImageCount; imageIndex++)
            {
                var imageDef = metadata.imageDefs[imageIndex];
                writer.Write($"// Image {imageIndex}: {metadata.GetStringFromIndex(imageDef.nameIndex)} - {imageDef.typeStart}\n");
            }
            //dump type
            foreach (var imageDef in metadata.imageDefs)
            {
                try
                {
                    var typeEnd = imageDef.typeStart + imageDef.typeCount;
                    for (int idx = imageDef.typeStart; idx < typeEnd; idx++)
                    {
                        var typeDef  = metadata.typeDefs[idx];
                        var isStruct = false;
                        var isEnum   = false;
                        var extends  = new List <string>();
                        if (typeDef.parentIndex >= 0)
                        {
                            var parent     = il2cpp.types[typeDef.parentIndex];
                            var parentName = GetTypeName(parent);
                            if (parentName == "ValueType")
                            {
                                isStruct = true;
                            }
                            else if (parentName == "Enum")
                            {
                                isEnum = true;
                            }
                            else if (parentName != "object")
                            {
                                extends.Add(parentName);
                            }
                        }
                        //implementedInterfaces
                        if (typeDef.interfaces_count > 0)
                        {
                            for (int i = 0; i < typeDef.interfaces_count; i++)
                            {
                                var @interface = il2cpp.types[metadata.interfaceIndices[typeDef.interfacesStart + i]];
                                extends.Add(GetTypeName(@interface));
                            }
                        }
                        writer.Write($"\n// Namespace: {metadata.GetStringFromIndex(typeDef.namespaceIndex)}\n");
                        writer.Write(GetCustomAttribute(imageDef, typeDef.customAttributeIndex, typeDef.token));
                        if (config.DumpAttribute && (typeDef.flags & TYPE_ATTRIBUTE_SERIALIZABLE) != 0)
                        {
                            writer.Write("[Serializable]\n");
                        }
                        var visibility = typeDef.flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
                        switch (visibility)
                        {
                        case TYPE_ATTRIBUTE_PUBLIC:
                        case TYPE_ATTRIBUTE_NESTED_PUBLIC:
                            writer.Write("public ");
                            break;

                        case TYPE_ATTRIBUTE_NOT_PUBLIC:
                        case TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM:
                        case TYPE_ATTRIBUTE_NESTED_ASSEMBLY:
                            writer.Write("internal ");
                            break;

                        case TYPE_ATTRIBUTE_NESTED_PRIVATE:
                            writer.Write("private ");
                            break;

                        case TYPE_ATTRIBUTE_NESTED_FAMILY:
                            writer.Write("protected ");
                            break;

                        case TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM:
                            writer.Write("protected internal ");
                            break;
                        }
                        if ((typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0 && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0)
                        {
                            writer.Write("static ");
                        }
                        else if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) == 0 && (typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0)
                        {
                            writer.Write("abstract ");
                        }
                        else if (!isStruct && !isEnum && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0)
                        {
                            writer.Write("sealed ");
                        }
                        if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) != 0)
                        {
                            writer.Write("interface ");
                        }
                        else if (isStruct)
                        {
                            writer.Write("struct ");
                        }
                        else if (isEnum)
                        {
                            writer.Write("enum ");
                        }
                        else
                        {
                            writer.Write("class ");
                        }
                        var typeName = metadata.GetStringFromIndex(typeDef.nameIndex);
                        writer.Write($"{typeName}");
                        if (extends.Count > 0)
                        {
                            writer.Write($" : {string.Join(", ", extends)}");
                        }
                        if (config.DumpTypeDefIndex)
                        {
                            writer.Write($" // TypeDefIndex: {idx}\n{{");
                        }
                        else
                        {
                            writer.Write("\n{");
                        }
                        //dump field
                        if (config.DumpField && typeDef.field_count > 0)
                        {
                            writer.Write("\n\t// Fields\n");
                            var fieldEnd = typeDef.fieldStart + typeDef.field_count;
                            for (var i = typeDef.fieldStart; i < fieldEnd; ++i)
                            {
                                //dump_field(i, idx, i - typeDef.fieldStart);
                                var fieldDef     = metadata.fieldDefs[i];
                                var fieldType    = il2cpp.types[fieldDef.typeIndex];
                                var fieldDefault = metadata.GetFieldDefaultValueFromIndex(i);
                                writer.Write(GetCustomAttribute(imageDef, fieldDef.customAttributeIndex, fieldDef.token, "\t"));
                                writer.Write("\t");
                                var access = fieldType.attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK;
                                switch (access)
                                {
                                case FIELD_ATTRIBUTE_PRIVATE:
                                    writer.Write("private ");
                                    break;

                                case FIELD_ATTRIBUTE_PUBLIC:
                                    writer.Write("public ");
                                    break;

                                case FIELD_ATTRIBUTE_FAMILY:
                                    writer.Write("protected ");
                                    break;

                                case FIELD_ATTRIBUTE_ASSEMBLY:
                                case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
                                    writer.Write("internal ");
                                    break;

                                case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
                                    writer.Write("protected internal ");
                                    break;
                                }
                                if ((fieldType.attrs & FIELD_ATTRIBUTE_LITERAL) != 0)
                                {
                                    writer.Write("const ");
                                }
                                else
                                {
                                    if ((fieldType.attrs & FIELD_ATTRIBUTE_STATIC) != 0)
                                    {
                                        writer.Write("static ");
                                    }
                                    if ((fieldType.attrs & FIELD_ATTRIBUTE_INIT_ONLY) != 0)
                                    {
                                        writer.Write("readonly ");
                                    }
                                }
                                writer.Write($"{GetTypeName(fieldType)} {metadata.GetStringFromIndex(fieldDef.nameIndex)}");
                                if (fieldDefault != null && fieldDefault.dataIndex != -1)
                                {
                                    var pointer = metadata.GetDefaultValueFromIndex(fieldDefault.dataIndex);
                                    if (pointer > 0)
                                    {
                                        var pTypeToUse = il2cpp.types[fieldDefault.typeIndex];
                                        metadata.Position = pointer;
                                        object multi = null;
                                        switch (pTypeToUse.type)
                                        {
                                        case Il2CppTypeEnum.IL2CPP_TYPE_BOOLEAN:
                                            multi = metadata.ReadBoolean();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_U1:
                                            multi = metadata.ReadByte();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_I1:
                                            multi = metadata.ReadSByte();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_CHAR:
                                            multi = BitConverter.ToChar(metadata.ReadBytes(2), 0);
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_U2:
                                            multi = metadata.ReadUInt16();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_I2:
                                            multi = metadata.ReadInt16();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_U4:
                                            multi = metadata.ReadUInt32();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_I4:
                                            multi = metadata.ReadInt32();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_U8:
                                            multi = metadata.ReadUInt64();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_I8:
                                            multi = metadata.ReadInt64();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_R4:
                                            multi = metadata.ReadSingle();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_R8:
                                            multi = metadata.ReadDouble();
                                            break;

                                        case Il2CppTypeEnum.IL2CPP_TYPE_STRING:
                                            var uiLen = metadata.ReadInt32();
                                            multi = Encoding.UTF8.GetString(metadata.ReadBytes(uiLen));
                                            break;
                                        }
                                        if (multi is string str)
                                        {
                                            writer.Write($" = \"{ToEscapedString(str)}\"");
                                        }
                                        else if (multi is char c)
                                        {
                                            var v = (int)c;
                                            writer.Write($" = '\\x{v:x}'");
                                        }
                                        else if (multi != null)
                                        {
                                            writer.Write($" = {multi}");
                                        }
                                    }
                                }
                                if (config.DumpFieldOffset)
                                {
                                    writer.Write("; // 0x{0:X}\n", il2cpp.GetFieldOffsetFromIndex(idx, i - typeDef.fieldStart, i));
                                }
                                else
                                {
                                    writer.Write(";\n");
                                }
                            }
                        }
                        //dump property
                        if (config.DumpProperty && typeDef.property_count > 0)
                        {
                            writer.Write("\n\t// Properties\n");
                            var propertyEnd = typeDef.propertyStart + typeDef.property_count;
                            for (var i = typeDef.propertyStart; i < propertyEnd; ++i)
                            {
                                var propertyDef = metadata.propertyDefs[i];
                                writer.Write(GetCustomAttribute(imageDef, propertyDef.customAttributeIndex, propertyDef.token, "\t"));
                                writer.Write("\t");
                                if (propertyDef.get >= 0)
                                {
                                    var methodDef = metadata.methodDefs[typeDef.methodStart + propertyDef.get];
                                    writer.Write(GetModifiers(methodDef));
                                    var propertyType = il2cpp.types[methodDef.returnType];
                                    writer.Write($"{GetTypeName(propertyType)} {metadata.GetStringFromIndex(propertyDef.nameIndex)} {{ ");
                                }
                                else if (propertyDef.set > 0)
                                {
                                    var methodDef = metadata.methodDefs[typeDef.methodStart + propertyDef.set];
                                    writer.Write(GetModifiers(methodDef));
                                    var parameterDef = metadata.parameterDefs[methodDef.parameterStart];
                                    var propertyType = il2cpp.types[parameterDef.typeIndex];
                                    writer.Write($"{GetTypeName(propertyType)} {metadata.GetStringFromIndex(propertyDef.nameIndex)} {{ ");
                                }
                                if (propertyDef.get >= 0)
                                {
                                    writer.Write("get; ");
                                }
                                if (propertyDef.set >= 0)
                                {
                                    writer.Write("set; ");
                                }
                                writer.Write("}");
                                writer.Write("\n");
                            }
                        }
                        //dump method
                        if (config.DumpMethod && typeDef.method_count > 0)
                        {
                            writer.Write("\n\t// Methods\n");
                            var methodEnd = typeDef.methodStart + typeDef.method_count;
                            for (var i = typeDef.methodStart; i < methodEnd; ++i)
                            {
                                var methodDef = metadata.methodDefs[i];
                                writer.Write(GetCustomAttribute(imageDef, methodDef.customAttributeIndex, methodDef.token, "\t"));
                                writer.Write("\t");
                                writer.Write(GetModifiers(methodDef));
                                var methodReturnType = il2cpp.types[methodDef.returnType];
                                var methodName       = metadata.GetStringFromIndex(methodDef.nameIndex);
                                writer.Write($"{GetTypeName(methodReturnType)} {methodName}(");
                                var parameterStrs = new List <string>();
                                for (var j = 0; j < methodDef.parameterCount; ++j)
                                {
                                    var parameterStr      = "";
                                    var parameterDef      = metadata.parameterDefs[methodDef.parameterStart + j];
                                    var parameterName     = metadata.GetStringFromIndex(parameterDef.nameIndex);
                                    var parameterType     = il2cpp.types[parameterDef.typeIndex];
                                    var parameterTypeName = GetTypeName(parameterType);
                                    if ((parameterType.attrs & PARAM_ATTRIBUTE_OPTIONAL) != 0)
                                    {
                                        parameterStr += "optional ";
                                    }
                                    if ((parameterType.attrs & PARAM_ATTRIBUTE_OUT) != 0)
                                    {
                                        parameterStr += "out ";
                                    }
                                    parameterStr += $"{parameterTypeName} {parameterName}";
                                    parameterStrs.Add(parameterStr);
                                }
                                writer.Write(string.Join(", ", parameterStrs));
                                if (config.DumpMethodOffset)
                                {
                                    ulong methodPointer;
                                    if (methodDef.methodIndex >= 0)
                                    {
                                        methodPointer = il2cpp.methodPointers[methodDef.methodIndex];
                                    }
                                    else
                                    {
                                        il2cpp.genericMethoddDictionary.TryGetValue(i, out methodPointer);
                                    }
                                    if (methodPointer > 0)
                                    {
                                        writer.Write("); // RVA: 0x{0:X} Offset: 0x{1:X}\n", methodPointer, il2cpp.MapVATR(methodPointer));
                                        //Script - method
                                        var name = ToEscapedString(HandleSpecialCharacters(typeName + "$$" + methodName));
                                        scriptwriter.WriteLine($"SetMethod(0x{methodPointer:X}, '{name}')");
                                    }
                                    else
                                    {
                                        writer.Write("); // -1\n");
                                    }
                                }
                                else
                                {
                                    writer.Write("); \n");
                                }
                            }
                        }
                        writer.Write("}\n");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: Some errors in dumping");
                    writer.Write("/*");
                    writer.Write(e);
                    writer.Write("*/\n}\n");
                }
            }
            //Script - stringLiteral
            scriptwriter.WriteLine("print('Make method name done')");
            scriptwriter.WriteLine("print('Setting String...')");
            if (il2cpp.version > 16)
            {
                foreach (var i in metadata.stringLiteralsdic)
                {
                    scriptwriter.WriteLine($"SetString(0x{il2cpp.metadataUsages[i.Key]:X}, r'{ToEscapedString(i.Value)}')");
                }
            }
            scriptwriter.WriteLine("print('Set string done')");
            //Script - MakeFunction
            if (config.MakeFunction)
            {
                var orderedPointers = il2cpp.methodPointers.ToList();
                orderedPointers.AddRange(il2cpp.genericMethodPointers.Where(x => x > 0));
                orderedPointers.AddRange(il2cpp.invokerPointers);
                orderedPointers.AddRange(il2cpp.customAttributeGenerators);
                orderedPointers = orderedPointers.OrderBy(x => x).ToList();
                scriptwriter.WriteLine("print('Making function...')");
                for (int i = 0; i < orderedPointers.Count - 1; i++)
                {
                    scriptwriter.WriteLine($"MakeFunction(0x{orderedPointers[i]:X}, 0x{orderedPointers[i + 1]:X})");
                }
                scriptwriter.WriteLine("print('Make function done, please wait for IDA to complete the analysis')");
            }
            scriptwriter.WriteLine("print('Script finish !')");
            //writer close
            writer.Close();
            scriptwriter.Close();
            Console.WriteLine("Done !");
            //DummyDll
            if (config.DummyDll)
            {
                Console.WriteLine("Create DummyDll...");
                if (Directory.Exists("DummyDll"))
                {
                    Directory.Delete("DummyDll", true);
                }
                Directory.CreateDirectory("DummyDll");
                Directory.SetCurrentDirectory("DummyDll");
                File.WriteAllBytes("Il2CppDummyDll.dll", Resource1.Il2CppDummyDll);
                var dummy = new DummyAssemblyCreator(metadata, il2cpp);
                foreach (var assembly in dummy.Assemblies)
                {
                    var stream = new MemoryStream();
                    assembly.Write(stream);
                    File.WriteAllBytes(assembly.MainModule.Name, stream.ToArray());
                }
                Console.WriteLine("Done !");
            }
        }
        /// <summary>
        /// Unwrap object wrapped in <see cref="SerializedObjectWrapper"/>
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        object Unwrap(SerializedObjectWrapper item)
        {
            if (item.Data.Array == null)
            {
                return(null);
            }

            if (item.Flags == RawDataFlag)
            {
                ArraySegment <byte> tmp = item.Data;

                if (tmp.Count == tmp.Array.Length)
                {
                    return(tmp.Array);
                }

                // we should never arrive here, but it's better to be safe than sorry
                var retval = new byte[tmp.Count];

                Array.Copy(tmp.Array, tmp.Offset, retval, 0, tmp.Count);

                return(retval);
            }

            var code = (TypeCode)(item.Flags & 0x00ff);

            byte[] data   = item.Data.Array;
            int    offset = item.Data.Offset;
            int    count  = item.Data.Count;

            switch (code)
            {
            // incrementing a non-existing key then getting it
            // returns as a string, but the flag will be 0
            // so treat all 0 flagged items as string
            // this may help inter-client data management as well
            //
            // however we store 'null' as Empty + an empty array,
            // so this must special-cased for compatibilty with
            // earlier versions. we introduced DBNull as null marker in emc2.6
            case TypeCode.Empty:
                return((data == null || count == 0)
                                                        ? null
                                                        : Encoding.UTF8.GetString(data, offset, count));

            case TypeCode.DBNull:
                return(null);

            case TypeCode.String:
                return(Encoding.UTF8.GetString(data, offset, count));

            case TypeCode.Boolean:
                return(BitConverter.ToBoolean(data, offset));

            case TypeCode.Int16:
                return(BitConverter.ToInt16(data, offset));

            case TypeCode.Int32:
                return(BitConverter.ToInt32(data, offset));

            case TypeCode.Int64:
                return(BitConverter.ToInt64(data, offset));

            case TypeCode.UInt16:
                return(BitConverter.ToUInt16(data, offset));

            case TypeCode.UInt32:
                return(BitConverter.ToUInt32(data, offset));

            case TypeCode.UInt64:
                return(BitConverter.ToUInt64(data, offset));

            case TypeCode.Char:
                return(BitConverter.ToChar(data, offset));

            case TypeCode.DateTime:
                return(DateTime.FromBinary(BitConverter.ToInt64(data, offset)));

            case TypeCode.Double:
                return(BitConverter.ToDouble(data, offset));

            case TypeCode.Single:
                return(BitConverter.ToSingle(data, offset));

            case TypeCode.Object:
                using (var ms = new MemoryStream(data, offset, count))
                {
                    return(bf.Deserialize(ms));
                }

            default: throw new InvalidOperationException("Unknown TypeCode was returned: " + code);
            }
        }
示例#5
0
 public override char getChar()
 {
     return(BitConverter.ToChar(hb, ix(nextGetIndex(2))));
 }
示例#6
0
            /// <summary>
            /// Returns a dictionary with all the property mappings
            /// </summary>
            /// <param name="propertyIdents">List with all the named property idents, e.g 8005, 8006, 801C, etc...</param>
            /// <returns></returns>
            internal List <MapiTagMapping> GetMapping(IEnumerable <string> propertyIdents)
            {
                var result            = new List <MapiTagMapping>();
                var entryStreamBytes  = GetStreamBytes(MapiTags.EntryStream);
                var stringStreamBytes = GetStreamBytes(MapiTags.StringStream);

                if (entryStreamBytes.Length == 0)
                {
                    return(result);
                }

                foreach (var propertyIdent in propertyIdents)
                {
                    // To read the correct mapped property we need to calculate the offset in the entry stream
                    // The offset is calculated bij subtracting 32768 (8000 hex) from the named property and
                    // multiply the outcome with 8
                    var identValue  = ushort.Parse(propertyIdent, NumberStyles.HexNumber);
                    var entryOffset = (identValue - 32768) * 8;
                    if (entryOffset > entryStreamBytes.Length)
                    {
                        continue;
                    }

                    string entryIdentString;

                    // We need the first 2 bytes for the mapping, but because the nameStreamBytes is in little
                    // endian we need to swap the first 2 bytes
                    if (entryStreamBytes[entryOffset + 1] == 0)
                    {
                        var entryIdent = new[] { entryStreamBytes[entryOffset] };
                        entryIdentString = BitConverter.ToString(entryIdent).Replace("-", string.Empty);
                    }
                    else
                    {
                        var entryIdent = new[] { entryStreamBytes[entryOffset + 1], entryStreamBytes[entryOffset] };
                        entryIdentString = BitConverter.ToString(entryIdent).Replace("-", string.Empty);
                    }

                    var stringOffset = ushort.Parse(entryIdentString, NumberStyles.HexNumber);

                    if (stringOffset >= stringStreamBytes.Length)
                    {
                        result.Add(new MapiTagMapping(propertyIdent, entryIdentString));
                        continue;
                    }

                    // Read the first 4 bytes to determine the length of the string to read
                    var stringLength = BitConverter.ToInt32(stringStreamBytes, stringOffset);

                    if (stringOffset + stringLength >= stringStreamBytes.Length)
                    {
                        result.Add(new MapiTagMapping(propertyIdent, entryIdentString));
                        continue;
                    }

                    var str = string.Empty;

                    // Skip 4 bytes and start reading the string
                    stringOffset += 4;
                    for (var i = stringOffset; i < stringOffset + stringLength; i += 2)
                    {
                        var chr = BitConverter.ToChar(stringStreamBytes, i);
                        str += chr;
                    }

                    // Remove any null character
                    str = str.Replace("\0", string.Empty);
                    result.Add(new MapiTagMapping(str, propertyIdent, true));
                }

                return(result);
            }
示例#7
0
 public void TestToChar()
 {
     Assert.AssertEquals('P', BitConverter.ToChar(this.charArray, 0));
     Assert.AssertEquals('L', BitConverter.ToChar(this.charArray, 2));
 }
 public char ToChar(byte[] arr, int length) => BitConverter.ToChar(arr, length);
示例#9
0
 public char ReadChar(int pos)
 {
     return(BitConverter.ToChar(bytes, pos));
 }
示例#10
0
 public char ReadChar(Endianness endianness) => BitConverter.ToChar(ReadForEndianness(sizeof(char), endianness), 0);
示例#11
0
 public char ToChar(byte[] arr) => BitConverter.ToChar(arr, 0);
示例#12
0
        /// <summary>
        /// GetValue
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool GetValue <T>(ref T value)
        {
            bool result = false;

            if (!string.IsNullOrEmpty(Value))
            {
                switch (DataType.Type)
                {
                case TypeCode.Boolean:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)(byteArray[0] > 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.SByte:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        sbyte[] signed = Array.ConvertAll(byteArray, b => unchecked ((sbyte)b));
                        value  = (T)(object)signed[0];
                        result = true;
                    }
                }
                break;

                case TypeCode.Byte:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)byteArray[0];
                        result = true;
                    }
                }
                break;

                case TypeCode.Char:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToChar(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.Int16:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToInt16(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.Int32:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToInt32(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.Int64:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToInt64(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.UInt16:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToUInt16(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.UInt32:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToUInt32(byteArray, 0);
                        result = true;
                    }
                }
                break;

                case TypeCode.UInt64:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToUInt64(byteArray, 0);
                        result = true;
                    }
                } break;

                case TypeCode.Object:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)byteArray;
                        result = true;
                    }
                } break;

                case TypeCode.String:
                {
                    var byteArray = Convert.FromBase64String(Value);

                    if (byteArray.Length > 0)
                    {
                        value = (T)(object)Encoding.UTF8.GetString(byteArray);
                    }

                    result = true;
                } break;

                case TypeCode.Double:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        value  = (T)(object)BitConverter.ToDouble(byteArray, 0);
                        result = true;
                    }
                } break;

                case TypeCode.DateTime:
                {
                    var byteArray = Convert.FromBase64String(Value);
                    if (byteArray.Length > 0)
                    {
                        long dateData = BitConverter.ToInt64(byteArray, 0);

                        var val = DateTime.FromBinary(dateData);

                        value = (T)(object)val;

                        result = true;
                    }
                } break;
                }
            }
            else
            {
                if (DataType.Type == TypeCode.Object)
                {
                    if (DataType.SizeInBytes > 0)
                    {
                        value  = (T)(object)new byte[DataType.SizeInBytes];
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                }
            }

            return(result);
        }
示例#13
0
 public static char PeekChar(this System.IO.Stream ms, int position)
 {
     return(BitConverter.ToChar(PeekBytes(ms, position, 2), 0));
 }
示例#14
0
 public static char ReadChar(this System.IO.Stream ms)
 {
     return(BitConverter.ToChar(ReadBytes(ms, 2), 0));
 }
示例#15
0
 public char ReadChar()
 {
     char val = BitConverter.ToChar(_storage.ToArray(), _readPos); _readPos += sizeof(char); return(val);
 }
示例#16
0
 public static char ReadValueImpl(Stream stream, byte[] bytes)
 {
     stream.Read(bytes, 0, Size);
     return(BitConverter.ToChar(bytes, 0));
 }
示例#17
0
 private char ReadChar16()
 {
     return(BitConverter.ToChar(Read <ushort>(), 0));
 }
示例#18
0
        public static void StartIndexBeyondLength()
        {
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 2));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 2));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 3));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 8));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 9));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToHalf(new byte[2], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToHalf(new byte[2], 2));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToHalf(new byte[2], 3));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 2));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 3));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 4));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 5));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 8));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 9));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 4));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 5));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 2));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 3));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 4));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 5));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 8));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 9));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1, 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1, 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2, 0));

            AssertExtensions.Throws <ArgumentOutOfRangeException>("length", () => BitConverter.ToString(new byte[1], 0, -1));
        }
示例#19
0
    public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data)
    {
        MessageType mt = (MessageType)(int)data[0];

        Debug.Log("(Nebullarix), RTM received: " + mt + "len " + data.GetLength(0));
        int        objectId, sprIndex, len;
        char       g;
        float      x, y;
        string     s;
        GameObject go;

        try
        {
            switch (mt)
            {
            case MessageType.PlayerSettings:
                objectId = BitConverter.ToInt32(data, 1);
                sprIndex = BitConverter.ToInt32(data, 5);
                g        = BitConverter.ToChar(data, 9);
                go       = GameObject.Find(objectId.ToString());
                go.GetComponent <PlayerControl>().gender = g;
                go.GetComponent <PlayerControl>().SetSprite(sprIndex);
                pcs.Add(go);
                break;

            case MessageType.AddPlayer:
                objectId   = BitConverter.ToInt32(data, 1);
                len        = BitConverter.ToInt32(data, 5);
                s          = System.Text.Encoding.ASCII.GetString(data, 9, len);
                players[s] = objectId;
                Debug.Log("(Nebullarix) playeradd: " + s + " objectid: " + objectId);
                break;

            case MessageType.Talking:

                len            = BitConverter.ToInt32(data, 1);
                s              = System.Text.Encoding.UTF8.GetString(data, 5, len);
                Time.timeScale = s == "" ? 1f : 0f;
                Camera.main.GetComponent <DialControl>().SetText(s);
                Debug.Log("(Nebullarix) TalkingText: " + s);
                break;

            case MessageType.Destroy:
                objectId = BitConverter.ToInt32(data, 1);
                Debug.Log("(Nebullarix) destroyId: " + objectId);
                go = GameObject.Find(objectId.ToString());
                go.GetComponent <GPGSyncInstance>().Destroy();
                break;

            case MessageType.Instantiate:
                objectId = BitConverter.ToInt32(data, 1);
                int objectType = BitConverter.ToInt32(data, 13);
                x = BitConverter.ToSingle(data, 2);
                y = BitConverter.ToSingle(data, 6);
                Vector3 pos = new Vector3(x, y);
                Debug.Log("(Nebullarix) createId: " + objectId + " at " + pos + "type " + objectType);
                go = Instantiate(registeredPrefabs[objectType], pos, Quaternion.identity);
                go.GetComponent <GPGSyncInstance>().createMsgSent = true;
                go.name = objectId.ToString();
                break;

            case MessageType.VelocitySync:
                objectId = BitConverter.ToInt32(data, 1);
                x        = BitConverter.ToSingle(data, 5);
                y        = BitConverter.ToSingle(data, 9);
                Vector2 newVel = new Vector2(x, y);
                Debug.Log("(Nebullarix) SyncVelId: " + objectId + " newVel " + newVel);
                go = GameObject.Find(objectId.ToString());
                go.GetComponent <GPGSyncInstance>().SetVelocity(newVel);
                break;

            case MessageType.PosSync:
                objectId = BitConverter.ToInt32(data, 1);
                x        = BitConverter.ToSingle(data, 5);
                y        = BitConverter.ToSingle(data, 9);
                Vector3 newPos = new Vector3(x, y);
                go = GameObject.Find(objectId.ToString());
                go.GetComponent <GPGSyncInstance>().SetPosition(newPos);
                Debug.Log("(Nebullarix) SyncPosId: " + objectId + " newPos " + newPos);
                break;

            case MessageType.RotSync:
                objectId = BitConverter.ToInt32(data, 1);
                x        = BitConverter.ToSingle(data, 5);
                go       = GameObject.Find(objectId.ToString());
                go.GetComponent <GPGSyncInstance>().SetRot(x);
                Debug.Log("(Nebullarix) SyncRotId: " + objectId + " angle:  " + x);
                break;

            case MessageType.HPUpdate:
                objectId = BitConverter.ToInt32(data, 1);
                go       = GameObject.Find(objectId.ToString());
                sprIndex = BitConverter.ToInt32(data, 5);
                go.GetComponent <GPGSyncInstance>().SetHP(sprIndex);
                break;
            }
        }
        catch (NullReferenceException ex) {
            Debug.Log(ex.Message);
            Debug.Log(ex.Source);
            Debug.Log(ex.StackTrace);
        }
    }
示例#20
0
文件: Database.cs 项目: Vhayle/PSSE
        }                                               //...should allow PSSE to work longer without needing an update.

        #endregion Properties

        public Database()
        {
            //bin init
            MegaStone    = Properties.Resources.megaStone;
            MissionCard  = Properties.Resources.missionCard;
            MonAbility   = Properties.Resources.pokemonAbility;
            MonData      = Properties.Resources.pokemonData;
            MonLevel     = Properties.Resources.pokemonLevel;
            StagesMain   = Properties.Resources.stageData;
            StagesEvent  = Properties.Resources.stageDataEvent;
            StagesExpert = Properties.Resources.stageDataExtra;
            byte[][] files       = { MegaStone, MonData, StagesMain, StagesEvent, StagesExpert, MonLevel, MonAbility, MissionCard };
            string[] filenames   = { "megaStone.bin", "pokemonData.bin", "stageData.bin", "stageDataEvent.bin", "stageDataExtra.bin", "pokemonLevel.bin", "pokemonAbility.bin", "missionCard.bin" };
            string   resourcedir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar + "resources" + Path.DirectorySeparatorChar;

            #region old "resource" code
            //I don't want PSSE to populate the resource folder by itself anymore but it could still be handy
            //if (!Directory.Exists(resourcedir))
            //    Directory.CreateDirectory(resourcedir);
            //for (int i = 0; i < files.Length; i++)
            //{
            //    if (!File.Exists(resourcedir + filenames[i]))
            //        File.WriteAllBytes(resourcedir + filenames[i], files[i]);
            //    else
            //        files[i] = File.ReadAllBytes(resourcedir + filenames[i]);
            //}
            #endregion
            if (Directory.Exists(resourcedir))
            {
                for (int i = 0; i < files.Length; i++)
                {
                    if (File.Exists(resourcedir + filenames[i]))
                    {
                        files[i] = File.ReadAllBytes(resourcedir + filenames[i]);
                    }
                }
            }

            //txt init
            SpeciesList    = Properties.Resources.species.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
            MonsList       = Properties.Resources.mons.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
            PokathlonList  = Properties.Resources.pokathlon.Split(new[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);
            MegaStartIndex = MonsList.ToList().IndexOf("Mega Venusaur");
            MonStopIndex   = MonsList.ToList().IndexOf("---", 1);

            //megas
            int entrylen = BitConverter.ToInt32(MonData, 0x4);
            Megas = new Tuple <int, int> [BitConverter.ToUInt32(MegaStone, 0) - 1];
            for (int i = 0; i < Megas.Length; i++)
            {
                int    monIndex = BitConverter.ToUInt16(MegaStone, MegaStone[0x10] + (i + 1) * 4) & 0x3FF;
                string str      = "Mega " + MonsList[monIndex];
                if (monIndex == 6 || monIndex == 150)
                {
                    str += (monIndex != (BitConverter.ToUInt16(MegaStone, MegaStone[0x10] + i * 4) & 0x3FF)) ? " X" : " Y";
                }
                byte[] data       = MonData.Skip(0x50 + entrylen * MonsList.ToList().IndexOf(str)).Take(entrylen).ToArray();
                int    maxSpeedup = (BitConverter.ToInt32(data, 0xA) >> 7) & 0x7F;
                Megas[i] = new Tuple <int, int>(monIndex, maxSpeedup);
            }
            MegaList = new List <int>();
            for (int i = 0; i < Megas.Length; i++)
            {
                MegaList.Add(Megas[i].Item1);
            }
            HasMega = new bool[MonsList.Length][];
            for (int i = 0; i < MonsList.Length; i++)
            {
                HasMega[i] = new bool[2];
            }
            for (int i = 0; i < Megas.Length; i++)
            {
                HasMega[BitConverter.ToUInt16(MegaStone, 0x54 + i * 4) & 0x3FF][(MegaStone[0x54 + (i * 4) + 1] >> 3) & 1] = true;
            }

            //pokemons
            Forms = new int[SpeciesList.Length];
            Mons  = new Tuple <int, int, bool, int, int, int[], int, Tuple <int, int> > [BitConverter.ToUInt32(MonData, 0)];
            Rest  = new Tuple <int, int> [Mons.Length];
            for (int i = 0; i < Mons.Length; i++)
            {
                byte[] data   = MonData.Skip(0x50 + entrylen * i).Take(entrylen).ToArray();
                bool   isMega = i >= MegaStartIndex && i <= MonsList.Count() - 1;
                int    spec   = (isMega && i <= MegaStartIndex + Megas.Length - 1)
                    ? SpeciesList.ToList().IndexOf(MonsList[Megas[i - MegaStartIndex].Item1].Substring(0, (MonsList[Megas[i - MegaStartIndex].Item1].LastIndexOf(' ') <= 0) ? MonsList[Megas[i - MegaStartIndex].Item1].Length : MonsList[Megas[i - MegaStartIndex].Item1].LastIndexOf(' ')))
                    : (BitConverter.ToInt32(data, 0xE) >> 6) & 0x7FF;
                int   raiseMaxLevel = (BitConverter.ToInt16(data, 0x4)) & 0x3F;
                int   basePower = (BitConverter.ToInt16(data, 0x3)) & 0x7; //ranges 1-7 for now (30-90 BP), may need an update later on
                int[] skillsadr = new int[] { 0x02, 0x20, 0x21, 0x22, 0x23 }, skill = new int[skillsadr.Length];
                int   j = 0, skillCount = 0;
                foreach (int adr in skillsadr)
                {
                    skill[j] = data[adr] & 0x7F; //ranges 1-~130 for now, ordered list in MESSAGE_XX/message_PokedexXX.bin ("Opportunist" to "Transform" then a bunch more with a lot of placeholders)
                    if (skill[j] != 0)
                    {
                        skillCount++;
                    }
                    j++;
                }
                skillCount = Math.Max(skillCount, 1);
                int type  = (BitConverter.ToInt16(data, 0x01) >> 3) & 0x1F; //ranges 0-17 (normal - fairy) (https://gbatemp.net/threads/psse-pokemon-shuffle-save-editor.396499/page-33#post-6278446)
                int index = (BitConverter.ToInt16(data, 0)) & 0x3FF;        //ranges 1-999, it's the number you can see on the team selection menu
                Rest[i] = new Tuple <int, int>(index, skillCount);          //Mons has more than 7 arguments so 8th one and beyond must be included in another Tuple
                Mons[i] = new Tuple <int, int, bool, int, int, int[], int, Tuple <int, int> >(spec, Forms[spec], isMega, raiseMaxLevel, basePower, skill, type, Rest[i]);
                Forms[spec]++;
            }

            //pokathlon
            PokathlonRand = new int[PokathlonList.Length / 2][];
            for (int i = 0; i < PokathlonRand.Length; i++)
            {
                PokathlonRand[i] = new int[2];
                Int32.TryParse(PokathlonList[2 * i], out PokathlonRand[i][0]);
                Int32.TryParse(PokathlonList[1 + 2 * i], out PokathlonRand[i][1]);
            }

            //missions
            Missions = new bool[BitConverter.ToInt32(MissionCard, 0)][];
            for (int i = 0; i < Missions.Length; i++)
            {
                Missions[i] = new bool[10];
                int    ientrylen = BitConverter.ToInt32(MissionCard, 0x4);
                byte[] data      = MissionCard.Skip(BitConverter.ToInt32(MissionCard, 0x10) + i * ientrylen).Take(ientrylen).ToArray();
                for (int j = 0; j < Missions[i].Length; j++)
                {
                    Missions[i][j] = BitConverter.ToInt16(data, 0x8 + 2 * j) != 0;
                }
            }

            //dictionnary, this is some really bad code here
            byte[]        HexValue = Properties.Resources.messagePokedex_US;
            string        StrValue = "";
            List <string> List     = new List <string>();
            for (int i = 0; i < HexValue.Length; i += 2)
            {
                if (BitConverter.ToChar(HexValue, i) == '\0' && !(StrValue.EndsWith("\u0001ă\u0001\u0003\u0003慮敭") || StrValue.EndsWith("\u0001ă\u0001\u0003\u0005敭慧慎敭")))
                {
                    List.Add((StrValue != "") ? StrValue.Replace("\u0001ă\u0001\u0003\u0003慮敭\0", "[name]").Replace("\u0001ă\u0001\u0003\u0005敭慧慎敭\0", "[name]") : "-Placeholder-");
                    StrValue = "";
                }
                else
                {
                    StrValue += BitConverter.ToChar(HexValue, i);
                }
            }
            int      a = List.IndexOf("Opportunist"), b = List.IndexOf("Rarely, attacks can deal\ngreater damage than usual."), c = List.IndexOf("Big Wave"), d = List.IndexOf("Increases damage done by\nany Water types in a combo.");
            string[] s1  = List.Skip(a).Take(b - a).ToArray(), s2 = List.Skip(c).Take(d - c).ToArray(), Skills = new string[s1.Length + s2.Length];
            string[] st1 = List.Skip(b).Take(b - a).ToArray(), st2 = List.Skip(d).Take(d - c).ToArray(), SkillsT = new string[st1.Length + st2.Length];
            s1.CopyTo(Skills, 0);
            s2.CopyTo(Skills, s1.Length);
            SkillsList = Skills;
            st1.CopyTo(SkillsT, 0);
            st2.CopyTo(SkillsT, s1.Length);
            SkillsTextList = SkillsT;
        }
示例#21
0
        public static T GetValue <T>(byte[] array, int startIndex, out int size)
        {
            size = 0;
            object result = null;

            if (typeof(T) == typeof(byte))
            {
                size = sizeof(byte);

                var arr = GetValue(array, startIndex, size);
                result = arr.Length > 0 ? arr[0] : 0;
            }
            else if (typeof(T) == typeof(sbyte))
            {
                size = sizeof(sbyte);

                var arr = GetValue(array, startIndex, size);
                result = arr.Length > 0 ? (sbyte)arr[0] : (sbyte)0;
            }
            else if (typeof(T) == typeof(ushort))
            {
                size = sizeof(ushort);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToUInt16(arr, 0);
            }
            else if (typeof(T) == typeof(short))
            {
                size = sizeof(short);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToInt16(arr, 0);
            }
            else if (typeof(T) == typeof(uint))
            {
                size = sizeof(uint);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToUInt32(arr, 0);
            }
            else if (typeof(T) == typeof(int))
            {
                size = sizeof(int);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToInt32(arr, 0);
            }
            else if (typeof(T) == typeof(ulong))
            {
                size = sizeof(ulong);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToUInt64(arr, 0);
            }
            else if (typeof(T) == typeof(long))
            {
                size = sizeof(long);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToInt64(arr, 0);
            }
            else if (typeof(T) == typeof(float))
            {
                size = sizeof(float);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToSingle(arr, 0);
            }
            else if (typeof(T) == typeof(double))
            {
                size = sizeof(double);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToDouble(arr, 0);
            }
            else if (typeof(T) == typeof(char))
            {
                size = sizeof(char);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToChar(arr, 0);
            }
            else if (typeof(T) == typeof(bool))
            {
                size = sizeof(bool);

                var arr = GetValue(array, startIndex, size);
                result = BitConverter.ToBoolean(arr, 0);
            }
            else if (typeof(T) == typeof(Guid))
            {
                size = 16;
                var arr = GetValue(array, startIndex, size);
                result = new Guid(arr);
            }

            return((T)Convert.ChangeType(result, typeof(T)));
        }
示例#22
0
        static void Main(string[] args)
        {
            config = File.Exists("config.json") ? new JavaScriptSerializer().Deserialize <Config>(File.ReadAllText("config.json")) : new Config();
            var ofd = new OpenFileDialog();

            ofd.Filter = "ELF file or Mach-O file|*.*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                var il2cppfile = File.ReadAllBytes(ofd.FileName);
                ofd.Filter = "global-metadata|global-metadata.dat";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        metadata = new MetadataGeneric(new MemoryStream(File.ReadAllBytes(ofd.FileName)));
                        //判断il2cpp的magic
                        var il2cppmagic = BitConverter.ToUInt32(il2cppfile, 0);
                        var isElf       = false;
                        var is64bit     = false;
                        switch (il2cppmagic)
                        {
                        default:
                            throw new Exception("ERROR: il2cpp file not supported.");

                        case 0x464c457f:    //ELF
                            isElf = true;
                            goto case 0xFEEDFACE;

                        case 0xCAFEBABE:    //FAT header
                        case 0xBEBAFECA:
                            var machofat = new MachoFat(new MemoryStream(il2cppfile));
                            Console.Write("Select platform: ");
                            for (var i = 0; i < machofat.fats.Length; i++)
                            {
                                var fat = machofat.fats[i];
                                if (fat.magic == 0xFEEDFACF)    //64-bit mach object file
                                {
                                    Console.Write($"{i + 1}.64bit ");
                                }
                                else
                                {
                                    Console.Write($"{i + 1}.32bit ");
                                }
                            }
                            Console.WriteLine();
                            var key   = Console.ReadKey(true);
                            var index = int.Parse(key.KeyChar.ToString()) - 1;
                            var magic = machofat.fats[index].magic;
                            il2cppfile = machofat.GetMacho(index);
                            if (magic == 0xFEEDFACF)    // 64-bit mach object file
                            {
                                goto case 0xFEEDFACF;
                            }
                            else
                            {
                                goto case 0xFEEDFACE;
                            }

                        case 0xFEEDFACF:    // 64-bit mach object file
                            is64bit = true;
                            goto case 0xFEEDFACE;

                        case 0xFEEDFACE:    // 32-bit mach object file
                            Console.WriteLine("Select Mode: 1.Manual 2.Auto");
                            key = Console.ReadKey(true);
                            if (key.KeyChar == '2')
                            {
                                if (isElf)
                                {
                                    il2cpp = new Elf(new MemoryStream(il2cppfile), metadata.version, metadata.maxmetadataUsages);
                                }
                                else if (is64bit)
                                {
                                    il2cpp = new Macho64(new MemoryStream(il2cppfile), metadata.version, metadata.maxmetadataUsages);
                                }
                                else
                                {
                                    il2cpp = new Macho(new MemoryStream(il2cppfile), metadata.version, metadata.maxmetadataUsages);
                                }
                                try
                                {
                                    if (!il2cpp.Search())
                                    {
                                        throw new Exception();
                                    }
                                }
                                catch
                                {
                                    throw new Exception("ERROR: Unable to process file automatically, try to use manual mode.");
                                }
                            }
                            else if (key.KeyChar == '1')
                            {
                                Console.Write("Input CodeRegistration(R0): ");
                                var codeRegistration = Convert.ToUInt64(Console.ReadLine(), 16);
                                Console.Write("Input MetadataRegistration(R1): ");
                                var metadataRegistration = Convert.ToUInt64(Console.ReadLine(), 16);
                                if (isElf)
                                {
                                    il2cpp = new Elf(new MemoryStream(il2cppfile), codeRegistration, metadataRegistration, metadata.version, metadata.maxmetadataUsages);
                                }
                                else if (is64bit)
                                {
                                    il2cpp = new Macho64(new MemoryStream(il2cppfile), codeRegistration, metadataRegistration, metadata.version, metadata.maxmetadataUsages);
                                }
                                else
                                {
                                    il2cpp = new Macho(new MemoryStream(il2cppfile), codeRegistration, metadataRegistration, metadata.version, metadata.maxmetadataUsages);
                                }
                            }
                            else
                            {
                                return;
                            }
                            var writer = new StreamWriter(new FileStream("dump.cs", FileMode.Create));
                            Console.WriteLine("Dumping...");
                            //Script
                            var scriptwriter = new StreamWriter(new FileStream("script.py", FileMode.Create));
                            scriptwriter.WriteLine(Resource1.ida);
                            //
                            //dump image;
                            for (var imageIndex = 0; imageIndex < metadata.uiImageCount; imageIndex++)
                            {
                                var imageDef = metadata.imageDefs[imageIndex];
                                writer.Write($"// Image {imageIndex}: {metadata.GetString(imageDef.nameIndex)} - {imageDef.typeStart}\n");
                            }
                            //dump type;
                            for (var idx = 0; idx < metadata.uiNumTypes; ++idx)
                            {
                                try
                                {
                                    var typeDef  = metadata.typeDefs[idx];
                                    var isStruct = false;
                                    var extends  = new List <string>();
                                    if (typeDef.parentIndex >= 0)
                                    {
                                        var parent     = il2cpp.types[typeDef.parentIndex];
                                        var parentname = get_type_name(parent);
                                        if (parentname == "ValueType")
                                        {
                                            isStruct = true;
                                        }
                                        else if (parentname != "object")
                                        {
                                            extends.Add(parentname);
                                        }
                                    }
                                    //implementedInterfaces
                                    if (typeDef.interfaces_count > 0)
                                    {
                                        for (int i = 0; i < typeDef.interfaces_count; i++)
                                        {
                                            var @interface = il2cpp.types[metadata.interfaceIndices[typeDef.interfacesStart + i]];
                                            extends.Add(get_type_name(@interface));
                                        }
                                    }
                                    writer.Write($"\n// Namespace: {metadata.GetString(typeDef.namespaceIndex)}\n");
                                    writer.Write(GetCustomAttribute(typeDef.customAttributeIndex));
                                    if (config.dumpattribute && (typeDef.flags & TYPE_ATTRIBUTE_SERIALIZABLE) != 0)
                                    {
                                        writer.Write("[Serializable]\n");
                                    }
                                    var visibility = typeDef.flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
                                    if (visibility == TYPE_ATTRIBUTE_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_PUBLIC)
                                    {
                                        writer.Write("public ");
                                    }
                                    else if (visibility == TYPE_ATTRIBUTE_NOT_PUBLIC || visibility == TYPE_ATTRIBUTE_NESTED_FAM_AND_ASSEM || visibility == TYPE_ATTRIBUTE_NESTED_ASSEMBLY)
                                    {
                                        writer.Write("internal ");
                                    }
                                    else if (visibility == TYPE_ATTRIBUTE_NESTED_PRIVATE)
                                    {
                                        writer.Write("private ");
                                    }
                                    else if (visibility == TYPE_ATTRIBUTE_NESTED_FAMILY)
                                    {
                                        writer.Write("protected ");
                                    }
                                    else if (visibility == TYPE_ATTRIBUTE_NESTED_FAM_OR_ASSEM)
                                    {
                                        writer.Write("protected internal ");
                                    }
                                    if ((typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0 && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0)
                                    {
                                        writer.Write("static ");
                                    }
                                    else if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) == 0 && (typeDef.flags & TYPE_ATTRIBUTE_ABSTRACT) != 0)
                                    {
                                        writer.Write("abstract ");
                                    }
                                    else if (!isStruct && (typeDef.flags & TYPE_ATTRIBUTE_SEALED) != 0)
                                    {
                                        writer.Write("sealed ");
                                    }
                                    if ((typeDef.flags & TYPE_ATTRIBUTE_INTERFACE) != 0)
                                    {
                                        writer.Write("interface ");
                                    }
                                    else if (isStruct)
                                    {
                                        writer.Write("struct ");
                                    }
                                    else
                                    {
                                        writer.Write("class ");
                                    }
                                    writer.Write($"{metadata.GetString(typeDef.nameIndex)}");
                                    if (extends.Count > 0)
                                    {
                                        writer.Write($" : {string.Join(", ", extends)}");
                                    }
                                    writer.Write($" // TypeDefIndex: {idx}\n{{\n");
                                    //dump field
                                    if (config.dumpfield && typeDef.field_count > 0)
                                    {
                                        writer.Write("\t// Fields\n");
                                        var fieldEnd = typeDef.fieldStart + typeDef.field_count;
                                        for (var i = typeDef.fieldStart; i < fieldEnd; ++i)
                                        {
                                            //dump_field(i, idx, i - typeDef.fieldStart);
                                            var pField   = metadata.fieldDefs[i];
                                            var pType    = il2cpp.types[pField.typeIndex];
                                            var pDefault = metadata.GetFieldDefaultFromIndex(i);
                                            writer.Write(GetCustomAttribute(pField.customAttributeIndex, "\t"));
                                            writer.Write("\t");
                                            var access = pType.attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK;
                                            if (access == FIELD_ATTRIBUTE_PRIVATE)
                                            {
                                                writer.Write("private ");
                                            }
                                            else if (access == FIELD_ATTRIBUTE_PUBLIC)
                                            {
                                                writer.Write("public ");
                                            }
                                            else if (access == FIELD_ATTRIBUTE_FAMILY)
                                            {
                                                writer.Write("protected ");
                                            }
                                            else if (access == FIELD_ATTRIBUTE_ASSEMBLY || access == FIELD_ATTRIBUTE_FAM_AND_ASSEM)
                                            {
                                                writer.Write("internal ");
                                            }
                                            else if (access == FIELD_ATTRIBUTE_FAM_OR_ASSEM)
                                            {
                                                writer.Write("protected internal ");
                                            }
                                            if ((pType.attrs & FIELD_ATTRIBUTE_LITERAL) != 0)
                                            {
                                                writer.Write("const ");
                                            }
                                            else
                                            {
                                                if ((pType.attrs & FIELD_ATTRIBUTE_STATIC) != 0)
                                                {
                                                    writer.Write("static ");
                                                }
                                                if ((pType.attrs & FIELD_ATTRIBUTE_INIT_ONLY) != 0)
                                                {
                                                    writer.Write("readonly ");
                                                }
                                            }
                                            writer.Write($"{get_type_name(pType)} {metadata.GetString(pField.nameIndex)}");
                                            if (pDefault != null && pDefault.dataIndex != -1)
                                            {
                                                var pointer = metadata.GetDefaultValueFromIndex(pDefault.dataIndex);
                                                if (pointer > 0)
                                                {
                                                    var pTypeToUse = il2cpp.types[pDefault.typeIndex];
                                                    metadata.Position = pointer;
                                                    object multi = null;
                                                    switch (pTypeToUse.type)
                                                    {
                                                    case Il2CppTypeEnum.IL2CPP_TYPE_BOOLEAN:
                                                        multi = metadata.ReadBoolean();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_U1:
                                                        multi = metadata.ReadByte();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_I1:
                                                        multi = metadata.ReadSByte();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_CHAR:
                                                        //multi = metadata.ReadChar();
                                                        multi = BitConverter.ToChar(metadata.ReadBytes(2), 0);
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_U2:
                                                        multi = metadata.ReadUInt16();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_I2:
                                                        multi = metadata.ReadInt16();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_U4:
                                                        multi = metadata.ReadUInt32();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_I4:
                                                        multi = metadata.ReadInt32();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_U8:
                                                        multi = metadata.ReadUInt64();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_I8:
                                                        multi = metadata.ReadInt64();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_R4:
                                                        multi = metadata.ReadSingle();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_R8:
                                                        multi = metadata.ReadDouble();
                                                        break;

                                                    case Il2CppTypeEnum.IL2CPP_TYPE_STRING:
                                                        var uiLen = metadata.ReadInt32();
                                                        multi = Encoding.UTF8.GetString(metadata.ReadBytes(uiLen));
                                                        break;
                                                    }
                                                    if (multi is string)
                                                    {
                                                        writer.Write($" = \"{multi}\"");
                                                    }
                                                    else if (multi != null)
                                                    {
                                                        writer.Write($" = {multi}");
                                                    }
                                                }
                                            }
                                            writer.Write("; // 0x{0:x}\n", il2cpp.GetFieldOffsetFromIndex(idx, i - typeDef.fieldStart, i));
                                        }
                                        writer.Write("\n");
                                    }
                                    //dump property
                                    if (config.dumpproperty && typeDef.property_count > 0)
                                    {
                                        writer.Write("\t// Properties\n");
                                        var propertyEnd = typeDef.propertyStart + typeDef.property_count;
                                        for (var i = typeDef.propertyStart; i < propertyEnd; ++i)
                                        {
                                            var propertydef = metadata.propertyDefs[i];
                                            writer.Write(GetCustomAttribute(propertydef.customAttributeIndex, "\t"));
                                            writer.Write("\t");
                                            if (propertydef.get >= 0)
                                            {
                                                var methodDef = metadata.methodDefs[typeDef.methodStart + propertydef.get];
                                                writer.Write(GetModifiers(methodDef));
                                                var pReturnType = il2cpp.types[methodDef.returnType];
                                                writer.Write($"{get_type_name(pReturnType)} {metadata.GetString(propertydef.nameIndex)} {{ ");
                                            }
                                            else if (propertydef.set > 0)
                                            {
                                                var methodDef = metadata.methodDefs[typeDef.methodStart + propertydef.set];
                                                writer.Write(GetModifiers(methodDef));
                                                var pParam = metadata.parameterDefs[methodDef.parameterStart];
                                                var pType  = il2cpp.types[pParam.typeIndex];
                                                writer.Write($"{get_type_name(pType)} {metadata.GetString(propertydef.nameIndex)} {{ ");
                                            }
                                            if (propertydef.get >= 0)
                                            {
                                                writer.Write("get; ");
                                            }
                                            if (propertydef.set >= 0)
                                            {
                                                writer.Write("set; ");
                                            }
                                            writer.Write("}");
                                            writer.Write("\n");
                                        }
                                        writer.Write("\n");
                                    }
                                    //dump method
                                    if (config.dumpmethod && typeDef.method_count > 0)
                                    {
                                        writer.Write("\t// Methods\n");
                                        var methodEnd = typeDef.methodStart + typeDef.method_count;
                                        for (var i = typeDef.methodStart; i < methodEnd; ++i)
                                        {
                                            var methodDef = metadata.methodDefs[i];
                                            writer.Write(GetCustomAttribute(methodDef.customAttributeIndex, "\t"));
                                            writer.Write("\t");
                                            writer.Write(GetModifiers(methodDef));
                                            var pReturnType = il2cpp.types[methodDef.returnType];
                                            writer.Write($"{get_type_name(pReturnType)} {metadata.GetString(methodDef.nameIndex)}(");
                                            for (var j = 0; j < methodDef.parameterCount; ++j)
                                            {
                                                var pParam      = metadata.parameterDefs[methodDef.parameterStart + j];
                                                var szParamName = metadata.GetString(pParam.nameIndex);
                                                var pType       = il2cpp.types[pParam.typeIndex];
                                                var szTypeName  = get_type_name(pType);
                                                if ((pType.attrs & PARAM_ATTRIBUTE_OPTIONAL) != 0)
                                                {
                                                    writer.Write("optional ");
                                                }
                                                if ((pType.attrs & PARAM_ATTRIBUTE_OUT) != 0)
                                                {
                                                    writer.Write("out ");
                                                }
                                                if (j != methodDef.parameterCount - 1)
                                                {
                                                    writer.Write($"{szTypeName} {szParamName}, ");
                                                }
                                                else
                                                {
                                                    writer.Write($"{szTypeName} {szParamName}");
                                                }
                                            }
                                            if (methodDef.methodIndex >= 0)
                                            {
                                                writer.Write("); // {0:x}\n", il2cpp.methodPointers[methodDef.methodIndex]);
                                                //Script
                                                var name = ToUnicodeString(metadata.GetString(typeDef.nameIndex) + "$$" + metadata.GetString(methodDef.nameIndex));
                                                scriptwriter.WriteLine($"SetMethod(0x{il2cpp.methodPointers[methodDef.methodIndex]:x}, '{name}')");
                                                //
                                            }
                                            else
                                            {
                                                writer.Write("); // 0\n");
                                            }
                                        }
                                    }
                                    writer.Write("}\n");
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("ERROR: Some errors in dumping");
                                    writer.Write("/*");
                                    writer.Write($"{e.Message}\n{e.StackTrace}\n");
                                    writer.Write("*/\n}\n");
                                }
                            }
                            //Script
                            if (metadata.version > 16)
                            {
                                foreach (var i in metadata.stringLiteralsdic)
                                {
                                    scriptwriter.WriteLine($"SetString(0x{il2cpp.metadataUsages[i.Key]:x}, '{ToUnicodeString(i.Value)}')");
                                }
                            }
                            //
                            writer.Close();
                            scriptwriter.Close();
                            Console.WriteLine("Done !");
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"{e.Message}\r\n{e.StackTrace}");
                    }
                    Console.WriteLine("Press any key to exit...");
                    Console.ReadKey(true);
                }
            }
        }
示例#23
0
        private bool TryGetDefaultValue(int typeIndex, int dataIndex, out object value)
        {
            var pointer          = metadata.GetDefaultValueFromIndex(dataIndex);
            var defaultValueType = il2Cpp.types[typeIndex];

            metadata.Position = pointer;
            switch (defaultValueType.type)
            {
            case Il2CppTypeEnum.IL2CPP_TYPE_BOOLEAN:
                value = metadata.ReadBoolean();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_U1:
                value = metadata.ReadByte();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_I1:
                value = metadata.ReadSByte();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_CHAR:
                value = BitConverter.ToChar(metadata.ReadBytes(2), 0);
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_U2:
                value = metadata.ReadUInt16();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_I2:
                value = metadata.ReadInt16();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_U4:
                value = metadata.ReadUInt32();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_I4:
                value = metadata.ReadInt32();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_U8:
                value = metadata.ReadUInt64();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_I8:
                value = metadata.ReadInt64();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_R4:
                value = metadata.ReadSingle();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_R8:
                value = metadata.ReadDouble();
                return(true);

            case Il2CppTypeEnum.IL2CPP_TYPE_STRING:
                var len = metadata.ReadInt32();
                value = Encoding.UTF8.GetString(metadata.ReadBytes(len));
                return(true);

            default:
                value = pointer;
                return(false);
            }
        }
示例#24
0
文件: Processor.cs 项目: g1xb17/MIPS
        /// <summary>
        /// This returns a boolean which represents the failure, success, completion or advancing cycles of this mips machine.
        /// An advancing cycle causes the data to proceed a singular cycle.
        /// A completion cycle returns false at the end
        /// The Success property must by true for this Method to be used successfully.
        /// </summary>
        /// <returns></returns>
        public bool Cycle()
        {
            if (!Success)
            {
                return(false);
            }
            //FLUSHING
            FetchBuffer[0].Flush(FetchBuffer[1]);
            DecodeBuffer[0].Flush(DecodeBuffer[1]);
            ExecuteBuffer[0].Flush(ExecuteBuffer[1]);
            MEMBuffer[0].Flush(MEMBuffer[1]);
            //END FLUSHING
            //PASSING
            FetchBuffer[1].Pass(DecodeBuffer[0]);
            DecodeBuffer[1].Pass(ExecuteBuffer[0]);
            ExecuteBuffer[1].Pass(MEMBuffer[0]);
            //END PASSING
            //Writeback STAGE
            REG.WriteRegister = MEMBuffer[1].DEST;
            REG.WriteData     = MUXER <byte[]> .Select(MEMBuffer[1].ALUResult, MEMBuffer[1].ReadData, MEMBuffer[1].vector.MemToReg);

            //MEM STAGE
            BranchGate.A          = ExecuteBuffer[1].vector.Branch;
            BranchGate.B          = ExecuteBuffer[1].Zero;
            MEM.WriteAddress      = MEM.ReadAddress = BitConverter.ToUInt32(ExecuteBuffer[1].ALUResult, 0);
            MEM.WriteData         = ExecuteBuffer[1].ReadData2;
            MEM.MemRead           = ExecuteBuffer[1].vector.MemRead;
            MEM.MemWrite          = ExecuteBuffer[1].vector.MemWrite;
            MEMBuffer[0].ReadData = MEM.ReadData;

            //EXECUTE STAGE
            Add.A            = DecodeBuffer[1].PC4;
            Add.B            = BitConverter.ToInt32(DecodeBuffer[1].OFFSET, 0) << 2;
            ALControl.ALUOp0 = DecodeBuffer[1].vector.ALUOp0;
            ALControl.ALUOp1 = DecodeBuffer[1].vector.ALUOp1;
            ALControl.FUNCT  = (( byte )(BitConverter.ToChar(DecodeBuffer[1].OFFSET, 0) & 0x3F));
            ALUnit.ALU0      = DecodeBuffer[1].ReadData1;
            ALUnit.ALU1      = MUXER <byte[]> .Select(DecodeBuffer[1].ReadData2, DecodeBuffer[1].OFFSET, DecodeBuffer[1].vector.ALUSrc);

            ALUnit.Vector             = ALControl.Output;
            ExecuteBuffer[0].PCBranch = ( uint )Add.Output;
            ExecuteBuffer[0].DEST     = MUXER <byte> .Select(DecodeBuffer[1].RT, DecodeBuffer[1].RD, DecodeBuffer[1].vector.RegDst);

            ExecuteBuffer[0].ALUResult = ALUnit.ALUResult;
            ExecuteBuffer[0].Zero      = ALUnit.Zero;

            //DECODE STAGE
            REG.Input                 = FetchBuffer[1].Instr;
            REG.RegWrite              = MEMBuffer[1].vector.RegWrite;
            Control.Input             = FetchBuffer[1].Instr;
            SGNEXT.Input              = REG.Input.OFFSET;
            DecodeBuffer[0].vector    = Control.Output;
            DecodeBuffer[0].ReadData1 = REG.ReadData1;
            DecodeBuffer[0].ReadData2 = REG.ReadData2;
            DecodeBuffer[0].OFFSET    = SGNEXT.Output;
            DecodeBuffer[0].RT        = FetchBuffer[1].Instr.RT;
            DecodeBuffer[0].RD        = FetchBuffer[1].Instr.RD;

            //FETCH STAGE
            CLI.PCDisplay(this.PC);
            IR = InstrMEM[PC];
            PC = MUXER <uint> .Select(PC + 4, ExecuteBuffer[1].PCBranch, BranchGate.Output);

            FetchBuffer[0].PC4   = PC;
            FetchBuffer[0].Instr = IR.Output;
            CLI.FetchDisplay(ref this.FetchBuffer[0], BranchGate.Output, PC, ExecuteBuffer[1].PCBranch);
            CLI.DecodeDisplay(ref this.FetchBuffer[1], ref this.DecodeBuffer[0], MEMBuffer[1].vector.RegWrite);
            CLI.ExecuteDisplay(ref this.DecodeBuffer[1], ref this.ExecuteBuffer[0]);
            CLI.MEMDisplay(ref this.ExecuteBuffer[1], ref this.MEMBuffer[0], BranchGate.Output);
            CLI.WBDisplay(ref this.MEMBuffer[1]);
            CLI.FetchDecodeBufferDisplay(FetchBuffer[0], FetchBuffer[1]);
            CLI.DecodeExecuteBufferDisplay(DecodeBuffer[0], DecodeBuffer[1]);
            CLI.ExecuteMEMBufferDisplay(ExecuteBuffer[0], ExecuteBuffer[1]);
            CLI.MEMWBBufferDisplay(MEMBuffer[0], MEMBuffer[1]);
            return(PC <= MAX_PC);
        }
示例#25
0
 public override char getChar(int i)
 {
     return(BitConverter.ToChar(hb, ix(checkIndex(i, 2))));
 }
示例#26
0
 public char ReadChar()
 {
     byte[] buffer = ReadBytes(2);
     return(BitConverter.ToChar(buffer, 0));
 }
示例#27
0
 protected static char unpackChar(byte[] bytes, ref int start)
 {
     byte[] data = { bytes[start] };
     return(BitConverter.ToChar(data, 0));
 }
示例#28
0
        public object Get(long offset, int len, byte dataType)
        {
            int         read;
            Span <byte> buf = new byte[len];

            _stream.Seek(offset, SeekOrigin.Begin);

            read = _stream.Read(buf);

            if (read != len)
            {
                throw new InvalidDataException();
            }

            var typeId = Convert.ToInt32(dataType);

            if (DataType.BOOL == typeId)
            {
                return(Convert.ToBoolean(buf[0]));
            }
            else if (DataType.CHAR == typeId)
            {
                return(BitConverter.ToChar(buf));
            }
            else if (DataType.FLOAT == typeId)
            {
                return(BitConverter.ToSingle(buf));
            }
            else if (DataType.INT == typeId)
            {
                return(BitConverter.ToInt32(buf));
            }
            else if (DataType.DOUBLE == typeId)
            {
                return(BitConverter.ToDouble(buf));
            }
            else if (DataType.LONG == typeId)
            {
                return(BitConverter.ToInt64(buf));
            }
            else if (DataType.ULONG == typeId)
            {
                return(BitConverter.ToUInt64(buf));
            }
            else if (DataType.DATETIME == typeId)
            {
                return(DateTime.FromBinary(BitConverter.ToInt64(buf)));
            }
            else if (DataType.STRING == typeId)
            {
                return(new string(System.Text.Encoding.Unicode.GetChars(buf.ToArray())));
            }
            else if (DataType.BYTE == typeId)
            {
                return(buf[0]);
            }
            else
            {
                return(buf.ToArray());
            }
        }
示例#29
0
 public char PeekChar()
 {
     return(BitConverter.ToChar(_data, _position));
 }
示例#30
0
 public static char ToChar(this byte[] current)
 {
     return(BitConverter.ToChar(current, 0));
 }