Inheritance: MonoBehaviour
示例#1
0
        public void FreeLeft()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            mm.Free(p1);

            var freePages = mm.FreePages.ToArray();
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[1].Offset, Is.EqualTo(6));

            mm.Free(p3);

            freePages = mm.FreePages.ToArray();
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[1].Offset, Is.EqualTo(3));

            mm.Free(p2);

            freePages = mm.FreePages.ToArray();
            Assert.That(freePages.Length, Is.EqualTo(1));
            Assert.That(freePages[0].Offset, Is.EqualTo(0));
            Assert.That(freePages[0].Size, Is.EqualTo(10));
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of the in-game player.
        /// </summary>
        /// <param name="memoryManager">The Memory Manager for reading and writing in-game values.</param>
        /// <param name="baseAddress">The players base address.</param>
        /// <param name="baseOffsets">The players base offsets.</param>
        /// <param name="xCoordinateOffset">The players X-coordinate offset.</param>
        /// <param name="yCoordinateOffset">The players Y-coordinate offset.</param>
        /// <param name="zCoordinateOffset">The players Z-coordinate offset.</param>
        /// <param name="xSpeedOffset">The players X-speed offset.</param>
        /// <param name="ySpeedOffset">The players Y-speed offset.</param>
        /// <param name="zSpeedOffset">The players Z-speed offset.</param>
        /// <param name="vectorX1Offset">The players X1-vector offset.</param>
        /// <param name="vectorY1Offset">The players Y1-vector offset.</param>
        /// <param name="vectorZ1Offset">The players Z1-vector offset.</param>
        /// <param name="vectorX2Offset">The players X2-vector offset.</param>
        /// <param name="vectorY2Offset">The players Y2-vector offset.</param>
        /// <param name="vectorZ2Offset">The players Z2-vector offset.</param>
        /// <param name="powerUpTypeOffset">The players Power-up type offset.</param>
        /// <param name="powerUpWhiteBricksOffset">The players Power-up White bricks amount offset.</param>
        /// <param name="powerUpRed">The players Red Power-up address.</param>
        /// <param name="powerUpBlue">The players Blue Power-up address.</param>
        /// <param name="powerUpGreen">The players Green Power-up address.</param>
        /// <param name="powerUpYellow">The players Yellow Power-up address.</param>
        public Player(MemoryManager memoryManager, int baseAddress, int[] baseOffsets, int xCoordinateOffset, int yCoordinateOffset, int zCoordinateOffset, int xSpeedOffset, int ySpeedOffset, int zSpeedOffset, int vectorX1Offset, int vectorY1Offset, int vectorZ1Offset, int vectorX2Offset, int vectorY2Offset, int vectorZ2Offset, int powerUpTypeOffset, int powerUpWhiteBricksOffset, int powerUpRed, int powerUpBlue, int powerUpGreen, int powerUpYellow)
        {
            this.memoryManager = memoryManager;
            this.baseAddress = baseAddress;
            this.baseOffsets = baseOffsets;
            this.memoryBase = memoryManager.CalculatePointer(memoryManager.ReadInt(baseAddress), baseOffsets);
            this.xCoordinateOffset = xCoordinateOffset;
            this.yCoordinateOffset = yCoordinateOffset;
            this.zCoordinateOffset = zCoordinateOffset;
            this.xSpeedOffset = xSpeedOffset;
            this.ySpeedOffset = ySpeedOffset;
            this.zSpeedOffset = zSpeedOffset;
            this.vectorX1Offset = vectorX1Offset;
            this.vectorY1Offset = vectorY1Offset;
            this.vectorZ1Offset = vectorZ1Offset;
            this.vectorX2Offset = vectorX2Offset;
            this.vectorY2Offset = vectorY2Offset;
            this.vectorZ2Offset = vectorZ2Offset;
            this.powerUpTypeOffset = powerUpTypeOffset;
            this.powerUpwhiteBricksOffset = powerUpWhiteBricksOffset;
            this.powerUpRed = powerUpRed;
            this.powerUpBlue = powerUpBlue;
            this.powerUpGreen = powerUpGreen;
            this.powerUpYellow = powerUpYellow;

            Initialize();
        }
示例#3
0
 public static void PrintBeforeExit(int ip , MemoryManager memoryManager)
 {
     var sb = new StringBuilder("Memory:\n");
     sb.Append(memoryManager);
     sb.AppendFormat("\nIP : {0}\n", ip);
     sb.AppendFormat("RON : {0:x2}\n", Ron.Sum);
     sb.AppendFormat("IR : {0:x2}\n", Ir.IR);
     Console.WriteLine(sb);
 }
示例#4
0
        public void Free()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            var freeBlock = mm.FreePages.Single();
            Assert.That(freeBlock.Offset, Is.EqualTo(6));
            Assert.That(freeBlock.Size, Is.EqualTo(4));
        }
示例#5
0
        public void Allocate()
        {
            var mm = new MemoryManager(new Ram(10, 1));

            var p1 = mm.Allocate(_pcb);
            var p2 = mm.Allocate(_pcb);
            var p3 = mm.Allocate(_pcb);

            var allocated = mm.AllocatedPages.ToArray();
            Assert.That(allocated.Length, Is.EqualTo(3));
            Assert.That(new PageInfo(p1), Is.EqualTo(allocated[0]));
            Assert.That(new PageInfo(p2), Is.EqualTo(allocated[1]));
            Assert.That(new PageInfo(p3), Is.EqualTo(allocated[2]));
        }
        public BassMediaPlayer([NotNull] IEventAggregator aggregator)
        {
            _visualHelper = new VisualHelper();
            _memoryManager = new MemoryManager();
            _equalizer = new Equalizer();

            _play = aggregator.GetEvent<RadioPlayerPlay, EventArgs>();
            _stop = aggregator.GetEvent<RadioPlayerStop, EventArgs>();
            _titleRecived = aggregator.GetEvent<RadioPlayerTitleRecived, string>();

            _memoryManager.Init();

            BassNet.Registration("*****@*****.**", "2X1533726322323");
        }
示例#7
0
 private static void Main()
 {
     if (!SettingsManager.TryInitializeSignals())
     {
         Console.WriteLine(
             "You should set all signals [pusk|vzap1|zam1|zam2|chist|op|vib|zapp|pereh] in app.config (1 is ok , 0 is broken)");
         return;
     }
     var pathToMemory = SettingsManager.MemoryPath();
     if (String.IsNullOrEmpty(pathToMemory)) return;
     var memoryManager = new MemoryManager(pathToMemory);
     if (!memoryManager.TryInitFromFile())
     {
         Console.WriteLine("Can't init from memory file , exit");
         return;
     }
     var ip = 0;
     while (true)
     {
         byte addrByte;
         byte operationByte;
         if (!(memoryManager.TryGetByte(ip, out operationByte) && memoryManager.TryGetByte(ip + 1, out addrByte)))
             break;
         Deccom.GenerateControlSignals(operationByte);
         if (!ControlSignals.Pusk)
             break;
         var ia = addrByte + Ir.IR;
         byte sp;
         if (!memoryManager.TryGetByte(ia, out sp))
             throw new Exception(string.Format("Process error , no data by offset {0}", ia));
         var res = M.Calculate(sp, ia, Rvv.RVV);
         var aluRes = Alu.Calculate(operationByte, Ron.Sum, res);
         var mRes = M.Calculate(aluRes);
         if (ControlSignals.Zam2)
             Ir.IR = mRes;
         if (ControlSignals.Zam1)
             Ron.Set(aluRes, Alu.Pr, operationByte);
         if (ControlSignals.Zapp)
             memoryManager.TryWrite((byte) aluRes, ia);
         if (!ControlSignals.Pusk)
             break;
         ip = M.NextOffset(ia, ip, operationByte);
     }
     PrintBeforeExit(ip, memoryManager);
 }
示例#8
0
 public static MemoryManager get()
 {
     if (_instance == null)
     {
         Logger.Log("MemoryManager::get was badly initialized", Logger.Level.WARN);
         _instance = GameObject.Find(gameObjectName).GetComponent<MemoryManager>();
         if (null != _instance)
         {
             DontDestroyOnLoad(_instance.gameObject);
             _instance.initializeIfNecessary();
         }
         else
         {
             Logger.Log("MemoryManager::get couldn't find game object", Logger.Level.ERROR);
         }
     }
     return _instance;
 }
 public DesktopMemoryCharacterImpl(MemoryManager manager)
 {
     this.MemoryManager = manager;
     this.Position      = new PositionImpl(this);
 }
示例#10
0
            /// <summary>
            /// Gets pixel data in normalized form (8 or 16-bit grayscale, or ARGB).
            /// </summary>
            /// <returns></returns>
            /// <remarks>
            /// <i>Normalized</i> pixel data means that:
            /// <list type="Bullet">
            /// <item>
            /// <description>Grayscale pixel data has embedded overlays removed and each pixel value
            /// is padded so that it can be cast directly to the appropriate type (e.g. byte, sbyte, ushort, short).</description>
            /// </item>
            /// <item>
            /// <description>Colour pixel data is always converted into ARGB format.</description>
            /// </item>
            /// <item>
            /// <description>Pixel data is always uncompressed.</description>
            /// </item>
            /// </list>
            /// <para>
            /// Ensuring that the pixel data always meets the above criteria
            /// allows clients to easily consume pixel data without having
            /// to worry about the the multitude of DICOM photometric interpretations
            /// and transfer syntaxes.
            /// </para>
            /// <para>
            /// Pixel data is reloaded when this method is called after a
            /// call to <see cref="ISopFrameData.Unload"/>.
            /// </para>
            /// </remarks>
            public override byte[] GetNormalizedPixelData()
            {
                _largeObjectContainerData.UpdateLastAccessTime();

                var pixelData = _pixelData;

                if (pixelData == null && !_isLoading)
                {
                    lock (SyncLock)
                    {
                        // if an asynchronous exception was thrown, throw it now and reset the field
                        if (_lastAsyncException != null)
                        {
                            var ex = _lastAsyncException;
                            _lastAsyncException = null;
                            throw new AsyncSopDataSourceException(ex);
                        }

                        pixelData = _pixelData;
                        if (pixelData == null && !_isLoading)
                        {
                            LockSource();
                            try
                            {
                                if (IsReadySynchronously())
                                {
                                    _pixelData = pixelData = SyncCreateNormalizedPixelData();
                                    _largeObjectContainerData.UpdateLastAccessTime();

                                    UpdateLargeObjectInfo();
                                    MemoryManager.Add(this);

                                    Diagnostics.OnLargeObjectAllocated(pixelData.Length);
                                    UpdateProgress(100, true, pixelData, null, false);

                                    return(pixelData);
                                }

                                _isLoading      = true;
                                ProgressPercent = 0;
                                IsLoaded        = false;

                                AsyncCreateNormalizedPixelData((pd, e) =>
                                {
                                    try
                                    {
                                        _largeObjectContainerData.UpdateLastAccessTime();

                                        if (pd != null)
                                        {
                                            lock (SyncLock)
                                            {
                                                Monitor.Pulse(SyncLock);
                                                _pixelData = pd;
                                                UpdateLargeObjectInfo();
                                                MemoryManager.Add(this);
                                            }

                                            Diagnostics.OnLargeObjectAllocated(pd.Length);
                                        }

                                        // we have to update progress no matter how it finished (success/failed)
                                        UpdateProgress(100, true, pd, e, true);
                                    }
                                    catch (Exception ex)
                                    {
                                        UpdateProgress(100, true, pd, ex, true);
                                        Platform.Log(LogLevel.Error, ex, "Encountered error while asynchronously loading SOP frame data.");
                                    }
                                    finally
                                    {
                                        _isLoading = false;
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                Platform.Log(LogLevel.Error, ex, "Encountered error while asynchronously loading SOP frame data.");
                            }
                            finally
                            {
                                UnlockSource();
                            }
                            pixelData = _pixelData;
                        }
                    }
                }

                return(pixelData);
            }
示例#11
0
        public KernelResult Initialize(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.PersonalMmHeapPagesCount, memRegion);

            ulong codePagesCount = (ulong)creationInfo.CodePagesCount;

            ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize;

            if (neededSizeForProcess != 0 && resourceLimit != null)
            {
                if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (neededSizeForProcess != 0 && resourceLimit != null)
                {
                    resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)creationInfo.PersonalMmHeapPagesCount;

            KMemoryBlockAllocator memoryBlockAllocator;

            if (PersonalMmHeapPagesCount != 0)
            {
                memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
            }
            else
            {
                memoryBlockAllocator = (MmuFlags & 0x40) != 0
                    ? System.LargeMemoryBlockAllocator
                    : System.SmallMemoryBlockAllocator;
            }

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = codePagesCount * KMemoryManager.PageSize;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapNewProcessCode(
                codeAddress,
                codePagesCount,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = Capabilities.InitializeForUser(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            Pid = System.GetProcessId();

            if (Pid == -1 || (ulong)Pid < Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            if (result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(result);
        }
示例#12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="total_samples"></param>
        /// <param name="mode_infinite"></param>
        /// <param name="sample_rate"></param>
        /// <param name="runner">このドライバを駆動しているRenderingRunnerのオブジェクト</param>
        /// <returns></returns>
        public int startRendering( long total_samples, boolean mode_infinite, int sample_rate, IWaveIncoming runner, WorkerState state )
        {
#if DEBUG
            sout.println( "VocaloidDriver#startRendering; entry; total_samples=" + total_samples + "; sample_rate=" + sample_rate );
#endif
            lock ( locker ) {
                rendering = true;
                //g_cancelRequired = false;
                g_progress = 0.0;
                sampleRate = sample_rate;

                Vector<MidiEvent> lpEvents = merge_events( s_track_events.get( 0 ), s_track_events.get( 1 ) );
                int current_count = -1;
                MidiEvent current = new MidiEvent();// = lpEvents;

                MemoryManager mman = null;
                float* left_ch;
                float* right_ch;
                float** out_buffer;
                try {
                    mman = new MemoryManager();
                    left_ch = (float*)mman.malloc( sizeof( float ) * sampleRate ).ToPointer();
                    right_ch = (float*)mman.malloc( sizeof( float ) * sampleRate ).ToPointer();
                    out_buffer = (float**)mman.malloc( sizeof( float* ) * 2 ).ToPointer();
                    out_buffer[0] = left_ch;
                    out_buffer[1] = right_ch;

                    double[] buffer_l = new double[sampleRate];
                    double[] buffer_r = new double[sampleRate];

#if TEST
                    org.kbinani.debug.push_log( "    calling initial dispatch..." );
#endif
#if DEBUG
                    sout.println( "VocaloidDriver#startRendering; sampleRate=" + sampleRate );
#endif
                    aEffect.Dispatch( AEffectOpcodes.effSetSampleRate, 0, 0, IntPtr.Zero, (float)sampleRate );
                    aEffect.Dispatch( AEffectOpcodes.effMainsChanged, 0, 1, IntPtr.Zero, 0 );

                    // ここではブロックサイズ=サンプリングレートということにする
                    aEffect.Dispatch( AEffectOpcodes.effSetBlockSize, 0, sampleRate, IntPtr.Zero, 0 );

                    // レンダリングの途中で停止した場合,ここでProcessする部分が無音でない場合がある
                    for ( int i = 0; i < 3; i++ ) {
                        aEffect.ProcessReplacing( IntPtr.Zero, new IntPtr( out_buffer ), sampleRate );
                    }
#if TEST
                    org.kbinani.debug.push_log( "    ...done" );
#endif

                    int delay = 0;
                    int duration = 0;
                    int dwNow = 0;
                    int dwPrev = 0;
                    int dwDelta;
                    int dwDelay = 0;
                    int dwDeltaDelay = 0;

                    int addr_msb = 0, addr_lsb = 0;
                    int data_msb = 0, data_lsb = 0;

                    int total_processed = 0;
                    int total_processed2 = 0;
#if TEST
                    org.kbinani.debug.push_log( "    getting dwDelay..." );
#endif
                    dwDelay = 0;
                    Vector<MidiEvent> list = s_track_events.get( 1 );
                    int list_size = list.size();
                    for ( int i = 0; i < list_size; i++ ) {
                        MidiEvent work = list.get( i );
                        if ( (work.firstByte & 0xf0) == 0xb0 ) {
                            switch ( work.data[0] ) {
                                case 0x63:
                                addr_msb = work.data[1];
                                addr_lsb = 0;
                                break;
                                case 0x62:
                                addr_lsb = work.data[1];
                                break;
                                case 0x06:
                                data_msb = work.data[1];
                                break;
                                case 0x26:
                                data_lsb = work.data[1];
                                if ( addr_msb == 0x50 && addr_lsb == 0x01 ) {
                                    dwDelay = (data_msb & 0xff) << 7 | (data_lsb & 0x7f);
                                }
                                break;
                            }
                        }
                        if ( dwDelay > 0 ) {
                            break;
                        }
                    }
#if TEST
                    org.kbinani.debug.push_log( "    ...done; dwDelay=" + dwDelay );
#endif

                    while ( !state.isCancelRequested() ) {
                        int process_event_count = current_count;
                        int nEvents = 0;

#if TEST
                        org.kbinani.debug.push_log( "lpEvents.Count=" + lpEvents.size() );
#endif
                        if ( current_count < 0 ) {
                            current_count = 0;
                            current = lpEvents.get( current_count );
                            process_event_count = current_count;
                        }
                        while ( current.clock == dwNow ) {
                            // durationを取得
                            if ( (current.firstByte & 0xf0) == 0xb0 ) {
                                switch ( current.data[0] ) {
                                    case 0x63:
                                    addr_msb = current.data[1];
                                    addr_lsb = 0;
                                    break;
                                    case 0x62:
                                    addr_lsb = current.data[1];
                                    break;
                                    case 0x06:
                                    data_msb = current.data[1];
                                    break;
                                    case 0x26:
                                    data_lsb = current.data[1];
                                    // Note Duration in millisec
                                    if ( addr_msb == 0x50 && addr_lsb == 0x4 ) {
                                        duration = data_msb << 7 | data_lsb;
                                    }
                                    break;
                                }
                            }

                            nEvents++;
                            if ( current_count + 1 < lpEvents.size() ) {
                                current_count++;
                                current = lpEvents.get( current_count );
                            } else {
                                break;
                            }
                        }

                        if ( current_count + 1 >= lpEvents.size() ) {
                            break;
                        }

                        double msNow = msec_from_clock( dwNow );
                        dwDelta = (int)(msNow / 1000.0 * sampleRate) - total_processed;
#if TEST
                    org.kbinani.debug.push_log( "dwNow=" + dwNow );
                    org.kbinani.debug.push_log( "dwPrev=" + dwPrev );
                    org.kbinani.debug.push_log( "dwDelta=" + dwDelta );
#endif
                        VstEvents* pVSTEvents = (VstEvents*)mman.malloc( sizeof( VstEvent ) + nEvents * sizeof( VstEvent* ) ).ToPointer();
                        pVSTEvents->numEvents = 0;
                        pVSTEvents->reserved = (VstIntPtr)0;

                        for ( int i = 0; i < nEvents; i++ ) {
                            MidiEvent pProcessEvent = lpEvents.get( process_event_count );
                            int event_code = pProcessEvent.firstByte;
                            VstEvent* pVSTEvent = (VstEvent*)0;
                            VstMidiEvent* pMidiEvent;

                            switch ( event_code ) {
                                case 0xf0:
                                case 0xf7:
                                case 0xff:
                                break;
                                default:
                                pMidiEvent = (VstMidiEvent*)mman.malloc( (int)(sizeof( VstMidiEvent ) + (pProcessEvent.data.Length + 1) * sizeof( byte )) ).ToPointer();
                                pMidiEvent->byteSize = sizeof( VstMidiEvent );
                                pMidiEvent->deltaFrames = dwDelta;
                                pMidiEvent->detune = 0;
                                pMidiEvent->flags = 1;
                                pMidiEvent->noteLength = 0;
                                pMidiEvent->noteOffset = 0;
                                pMidiEvent->noteOffVelocity = 0;
                                pMidiEvent->reserved1 = 0;
                                pMidiEvent->reserved2 = 0;
                                pMidiEvent->type = VstEventTypes.kVstMidiType;
                                pMidiEvent->midiData[0] = (byte)(0xff & pProcessEvent.firstByte);
                                for ( int j = 0; j < pProcessEvent.data.Length; j++ ) {
                                    pMidiEvent->midiData[j + 1] = (byte)(0xff & pProcessEvent.data[j]);
                                }
                                pVSTEvents->events[pVSTEvents->numEvents++] = (int)(VstEvent*)pMidiEvent;
                                break;
                            }
                            process_event_count++;
                            //pProcessEvent = lpEvents[process_event_count];
                        }
#if TEST
                        org.kbinani.debug.push_log( "calling Dispatch with effProcessEvents..." );
#endif
                        aEffect.Dispatch( AEffectXOpcodes.effProcessEvents, 0, 0, new IntPtr( pVSTEvents ), 0 );
#if TEST
                        org.kbinani.debug.push_log( "...done" );
#endif

                        while ( dwDelta > 0 && !state.isCancelRequested() ) {
                            int dwFrames = dwDelta > sampleRate ? sampleRate : dwDelta;
#if TEST
                            org.kbinani.debug.push_log( "calling ProcessReplacing..." );
#endif
                            aEffect.ProcessReplacing( IntPtr.Zero, new IntPtr( out_buffer ), dwFrames );
#if TEST
                            org.kbinani.debug.push_log( "...done" );
#endif

                            int iOffset = dwDelay - dwDeltaDelay;
                            if ( iOffset > (int)dwFrames ) {
                                iOffset = (int)dwFrames;
                            }

                            if ( iOffset == 0 ) {
                                for ( int i = 0; i < (int)dwFrames; i++ ) {
                                    buffer_l[i] = out_buffer[0][i];
                                    buffer_r[i] = out_buffer[1][i];
                                }
                                total_processed2 += dwFrames;
                                runner.waveIncomingImpl( buffer_l, buffer_r, dwFrames, state );
                            } else {
                                dwDeltaDelay += iOffset;
                            }
                            dwDelta -= dwFrames;
                            total_processed += dwFrames;
                        }

                        dwPrev = dwNow;
                        dwNow = (int)current.clock;
                        g_progress = total_processed / (double)total_samples * 100.0;
                    }

                    double msLast = msec_from_clock( dwNow );
                    dwDelta = (int)(sampleRate * ((double)duration + (double)delay) / 1000.0 + dwDeltaDelay);
                    if ( total_samples - total_processed2 > dwDelta ) {
                        dwDelta = (int)total_samples - total_processed2;
                    }
                    while ( dwDelta > 0 && !state.isCancelRequested() ) {
                        int dwFrames = dwDelta > sampleRate ? sampleRate : dwDelta;
#if TEST
                        org.kbinani.debug.push_log( "calling ProcessReplacing..." );
#endif
                        aEffect.ProcessReplacing( IntPtr.Zero, new IntPtr( out_buffer ), dwFrames );
#if TEST
                        org.kbinani.debug.push_log( "...done" );
#endif

                        for ( int i = 0; i < (int)dwFrames; i++ ) {
                            buffer_l[i] = out_buffer[0][i];
                            buffer_r[i] = out_buffer[1][i];
                        }
                        total_processed2 += dwFrames;
                        runner.waveIncomingImpl( buffer_l, buffer_r, dwFrames, state );

                        dwDelta -= dwFrames;
                        total_processed += dwFrames;
                    }

#if TEST
                    sout.println( "vstidrv::StartRendering; total_processed=" + total_processed );
#endif

                    if ( mode_infinite ) {
                        for ( int i = 0; i < sampleRate; i++ ) {
                            buffer_l[i] = 0.0;
                            buffer_r[i] = 0.0;
                        }
                        while ( !state.isCancelRequested() ) {
                            total_processed2 += sampleRate;
                            runner.waveIncomingImpl( buffer_l, buffer_r, sampleRate, state );
                        }
                    }

                    aEffect.Dispatch( AEffectOpcodes.effMainsChanged, 0, 0, IntPtr.Zero, 0 );
                    lpEvents.clear();
#if DEBUG
                    sout.println( "VocaloidDriver#startRendering; done; total_processed=" + total_processed + "; total_processed2=" + total_processed2 );
#endif
                } catch ( Exception ex ) {
                    serr.println( "VocaloidDriver#startRendering; ex=" + ex );
                } finally {
                    if ( mman != null ) {
                        try {
                            mman.dispose();
                        } catch ( Exception ex2 ) {
                            serr.println( "VocaloidDriver#startRendering; ex2=" + ex2 );
                        }
                    }
                }
                rendering = false;
                g_saProcessed = 0;
                for ( int i = 0; i < s_track_events.size(); i++ ) {
                    s_track_events.get( i ).clear();
                }
                g_tempoList.clear();
                //g_cancelRequired = false;
            }
            return 1;
        }
示例#13
0
 /// <summary>
 /// Checks if compute shader code in memory is equal to the cached shader.
 /// </summary>
 /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
 /// <param name="cpShader">Cached compute shader</param>
 /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
 /// <returns>True if the code is different, false otherwise</returns>
 private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle cpShader, ulong gpuVa)
 {
     return(IsShaderEqual(memoryManager, cpShader.Shaders[0], gpuVa));
 }
示例#14
0
 public ulong GetMemoryUsage()
 {
     return(_imageSize + _mainThreadStackSize + MemoryManager.GetTotalHeapSize() + GetPersonalMmHeapSize());
 }
示例#15
0
        public Executable(IExecutable Exe, KMemoryManager MemoryManager, MemoryManager Memory, long ImageBase)
        {
            Dynamic = new List <ElfDyn>();

            FilePath = Exe.FilePath;

            if (FilePath != null)
            {
                Name = Path.GetFileNameWithoutExtension(FilePath.Replace(Homebrew.TemporaryNroSuffix, ""));
            }

            this.Memory        = Memory;
            this.MemoryManager = MemoryManager;
            this.ImageBase     = ImageBase;
            this.ImageEnd      = ImageBase;

            long TextPosition = ImageBase + (uint)Exe.TextOffset;
            long ROPosition   = ImageBase + (uint)Exe.ROOffset;
            long DataPosition = ImageBase + (uint)Exe.DataOffset;

            long TextSize = (uint)IntUtils.AlignUp(Exe.Text.Length, KMemoryManager.PageSize);
            long ROSize   = (uint)IntUtils.AlignUp(Exe.RO.Length, KMemoryManager.PageSize);
            long DataSize = (uint)IntUtils.AlignUp(Exe.Data.Length, KMemoryManager.PageSize);
            long BssSize  = (uint)IntUtils.AlignUp(Exe.BssSize, KMemoryManager.PageSize);

            long DataAndBssSize = BssSize + DataSize;

            ImageEnd = DataPosition + DataAndBssSize;

            if (Exe.SourceAddress == 0)
            {
                MemoryManager.HleMapProcessCode(TextPosition, TextSize + ROSize + DataAndBssSize);

                MemoryManager.SetProcessMemoryPermission(ROPosition, ROSize, MemoryPermission.Read);
                MemoryManager.SetProcessMemoryPermission(DataPosition, DataAndBssSize, MemoryPermission.ReadAndWrite);

                Memory.WriteBytes(TextPosition, Exe.Text);
                Memory.WriteBytes(ROPosition, Exe.RO);
                Memory.WriteBytes(DataPosition, Exe.Data);
            }
            else
            {
                long Result = MemoryManager.MapProcessCodeMemory(TextPosition, Exe.SourceAddress, TextSize + ROSize + DataSize);

                if (Result != 0)
                {
                    throw new InvalidOperationException();
                }

                MemoryManager.SetProcessMemoryPermission(ROPosition, ROSize, MemoryPermission.Read);
                MemoryManager.SetProcessMemoryPermission(DataPosition, DataSize, MemoryPermission.ReadAndWrite);

                if (Exe.BssAddress != 0 && Exe.BssSize != 0)
                {
                    Result = MemoryManager.MapProcessCodeMemory(DataPosition + DataSize, Exe.BssAddress, BssSize);

                    if (Result != 0)
                    {
                        throw new InvalidOperationException();
                    }

                    MemoryManager.SetProcessMemoryPermission(DataPosition + DataSize, BssSize, MemoryPermission.ReadAndWrite);
                }
            }

            if (Exe.Mod0Offset == 0)
            {
                return;
            }

            long Mod0Offset = ImageBase + Exe.Mod0Offset;

            int  Mod0Magic        = Memory.ReadInt32(Mod0Offset + 0x0);
            long DynamicOffset    = Memory.ReadInt32(Mod0Offset + 0x4) + Mod0Offset;
            long BssStartOffset   = Memory.ReadInt32(Mod0Offset + 0x8) + Mod0Offset;
            long BssEndOffset     = Memory.ReadInt32(Mod0Offset + 0xc) + Mod0Offset;
            long EhHdrStartOffset = Memory.ReadInt32(Mod0Offset + 0x10) + Mod0Offset;
            long EhHdrEndOffset   = Memory.ReadInt32(Mod0Offset + 0x14) + Mod0Offset;
            long ModObjOffset     = Memory.ReadInt32(Mod0Offset + 0x18) + Mod0Offset;

            while (true)
            {
                long TagVal = Memory.ReadInt64(DynamicOffset + 0);
                long Value  = Memory.ReadInt64(DynamicOffset + 8);

                DynamicOffset += 0x10;

                ElfDynTag Tag = (ElfDynTag)TagVal;

                if (Tag == ElfDynTag.DT_NULL)
                {
                    break;
                }

                Dynamic.Add(new ElfDyn(Tag, Value));
            }

            long StrTblAddr = ImageBase + GetFirstValue(ElfDynTag.DT_STRTAB);
            long SymTblAddr = ImageBase + GetFirstValue(ElfDynTag.DT_SYMTAB);

            long SymEntSize = GetFirstValue(ElfDynTag.DT_SYMENT);

            List <ElfSym> Symbols = new List <ElfSym>();

            while ((ulong)SymTblAddr < (ulong)StrTblAddr)
            {
                ElfSym Sym = GetSymbol(SymTblAddr, StrTblAddr);

                Symbols.Add(Sym);

                SymTblAddr += SymEntSize;
            }

            SymbolTable = Array.AsReadOnly(Symbols.OrderBy(x => x.Value).ToArray());
        }
 public void UnTarget()
 {
     MemoryManager?.WriteToMemory((uint)0);
 }
示例#17
0
 public static void InitSigScan()
 {
     hMemory = new MemoryManager(Process.GetCurrentProcess().ProcessName);
 }
示例#18
0
        private void _window_DrawGraphics(object sender, DrawGraphicsEventArgs e)
        {
            var gfx = e.Graphics;

            if (!Checks.IsIngame())
            {
                gfx.ClearScene(_transparent);                 // set the background of the scene (can be transparent)
            }
            else
            {
                // you do not need to call BeginScene() or EndScene()
                gfx.ClearScene(_transparent);                 // set the background of the scene (can be transparent)

                if (Settings.ESP.DebugMode)
                {
                    var startX = 275f;
                    var startY = 50f;

                    var increaseAmount = 0f;

                    for (var strIdx = 0; strIdx < Settings.ESP.DebugStrings.Count; strIdx++)
                    {
                        gfx.DrawText(_font, _debugFontSize, _red, startX, startY + increaseAmount, Settings.ESP.DebugStrings[strIdx]);
                        increaseAmount += _debugFontSize + 5f;
                    }
                }

                if (Settings.ESP.DebugMode)
                {
                    return;
                }

                var maxPlayers = Structs.ClientState.BaseStruct.MaxPlayers;
                var entities   = MemoryManager.ReadMemory((int)Structs.Base.Client + Offsets.dwEntityList, maxPlayers * 0x10);

                for (var i = 0; i < maxPlayers; i++)
                {
                    var _viewMatrix = Structs.Base.ViewMatrix;
                    if (_viewMatrix == null)
                    {
                        continue;
                    }

                    var cEntity = Math.GetInt(entities, i * 0x10);

                    var entityStruct = MemoryManager.ReadMemory <Structs.Enemy_t>(cEntity);

                    if (!entityStruct.Team.HasTeam() ||
                        entityStruct.Team.IsMyTeam() ||
                        !entityStruct.Health.IsAlive() ||
                        entityStruct.Dormant
                        /*&& (!entityStruct.Spotted || !entityStruct.SpottedByMask)*/)
                    {
                        continue;
                    }

                    if (entityStruct.Position == Vector3.Zero)
                    {
                        continue;
                    }
                    var bonePosition = Extensions.Other.GetBonePos(cEntity, Settings.Aimbot.Bone);
                    if (bonePosition == Vector3.Zero)
                    {
                        continue;
                    }

                    if (bonePosition.ToScreen(out var _worldToScreenPos))
                    {
                        var boneX = _worldToScreenPos.X;
                        var boneY = _worldToScreenPos.Y;

                        //float flDist = Externalio.Other.Math.GetDistance3D(Structs.LocalPlayer.BaseStruct.Position, entityStruct.Position) * Externalio.Other.Math.METERS_PER_INCH;
                        //float flDist = Externalio.Other.Math.GetDistance3D(Structs.LocalPlayer.BaseStruct.Position, entityStruct.Position);

                        gfx.DrawCrosshair(_red, boneX, boneY, 9f, 5f, CrosshairStyle.Dot);
                    }

                    #region old code

                    /*
                     * if (entityStruct.Position.ToScreen(booleanVector, out Vector2 _worldToScreenPos))
                     * {
                     *      var posX = _worldToScreenPos.X;
                     *      var posY = _worldToScreenPos.Y;
                     *
                     *      if (bonePosition.ToScreen(booleanVector, out _worldToScreenPos))
                     *      {
                     *              float boneX = _worldToScreenPos.X;
                     *              //float boneY = _worldToScreenPos.Y - _worldToScreenPos.Y / 64;
                     *              float boneY = _worldToScreenPos.Y;
                     *
                     *              float height = posY - boneY;
                     *              float width = height / 2;
                     *
                     *              float flDist = Externalio.Other.Math.GetDistance3D(Structs.LocalPlayer.BaseStruct.Position, entityStruct.Position);
                     *              //gfx.DrawText(_font, (100f / flDist) < 13f ? 13f : (100f / flDist), _red, boneX / flDist , boneY / flDist, "XD");
                     *
                     *              gfx.DrawCrosshair(_red, boneX, boneY, 9f, 5f, CrosshairStyle.Plus);
                     *
                     *              //gfx.DrawLine(_red, new Point(posX - width / 2, posY), new Point(posX - width / 2, boneY), 0.5f);
                     *              //gfx.DrawLine(_red, new Point(posX - width / 2, boneY), new Point(boneX + width / 2, boneY), 0.5f);
                     *              //gfx.DrawLine(_red, new Point(boneX + width / 2, boneY), new Point(posX + width / 2, posY), 0.5f);
                     *              //gfx.DrawLine(_red, new Point(posX + width / 2, posY), new Point(posX - width / 2, posY), 0.5f);
                     *      }
                     * }
                     */

                    #endregion
                }
            }
        }
示例#19
0
 public void Assign(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager)
 {
     lock (_sendLock)
     {
         lock (_receiveLock)
         {
             this.channelId     = channelId;
             this.connection    = connection;
             this.config        = config;
             this.memoryManager = memoryManager;
         }
     }
 }
示例#20
0
        internal ReliableFragmentedChannel(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager)
        {
            this.channelId     = channelId;
            this.connection    = connection;
            this.config        = config;
            this.memoryManager = memoryManager;

            // Alloc the in flight windows for receive and send
            _receiveSequencer = new HeapableFixedDictionary <PendingIncomingPacketFragmented>(config.ReliabilityWindowSize, memoryManager);
            _sendSequencer    = new HeapableFixedDictionary <PendingOutgoingPacketFragmented>(config.ReliabilityWindowSize, memoryManager);
        }
示例#21
0
        public KernelResult Start(int MainThreadPriority, ulong StackSize)
        {
            lock (ProcessLock)
            {
                if (State > ProcessState.CreatedAttached)
                {
                    return(KernelResult.InvalidState);
                }

                if (ResourceLimit != null && !ResourceLimit.Reserve(LimitableResource.Thread, 1))
                {
                    return(KernelResult.ResLimitExceeded);
                }

                KResourceLimit ThreadResourceLimit = ResourceLimit;
                KResourceLimit MemoryResourceLimit = null;

                if (MainThreadStackSize != 0)
                {
                    throw new InvalidOperationException("Trying to start a process with a invalid state!");
                }

                ulong StackSizeRounded = BitUtils.AlignUp(StackSize, KMemoryManager.PageSize);

                ulong NeededSize = StackSizeRounded + ImageSize;

                //Check if the needed size for the code and the stack will fit on the
                //memory usage capacity of this Process. Also check for possible overflow
                //on the above addition.
                if (NeededSize > MemoryUsageCapacity ||
                    NeededSize < StackSizeRounded)
                {
                    ThreadResourceLimit?.Release(LimitableResource.Thread, 1);

                    return(KernelResult.OutOfMemory);
                }

                if (StackSizeRounded != 0 && ResourceLimit != null)
                {
                    MemoryResourceLimit = ResourceLimit;

                    if (!MemoryResourceLimit.Reserve(LimitableResource.Memory, StackSizeRounded))
                    {
                        ThreadResourceLimit?.Release(LimitableResource.Thread, 1);

                        return(KernelResult.ResLimitExceeded);
                    }
                }

                KernelResult Result;

                KThread MainThread = null;

                ulong StackTop = 0;

                void CleanUpForError()
                {
                    MainThread?.Terminate();
                    HandleTable.Destroy();

                    if (MainThreadStackSize != 0)
                    {
                        ulong StackBottom = StackTop - MainThreadStackSize;

                        ulong StackPagesCount = MainThreadStackSize / KMemoryManager.PageSize;

                        MemoryManager.UnmapForKernel(StackBottom, StackPagesCount, MemoryState.Stack);
                    }

                    MemoryResourceLimit?.Release(LimitableResource.Memory, StackSizeRounded);
                    ThreadResourceLimit?.Release(LimitableResource.Thread, 1);
                }

                if (StackSizeRounded != 0)
                {
                    ulong StackPagesCount = StackSizeRounded / KMemoryManager.PageSize;

                    ulong RegionStart = MemoryManager.StackRegionStart;
                    ulong RegionSize  = MemoryManager.StackRegionEnd - RegionStart;

                    ulong RegionPagesCount = RegionSize / KMemoryManager.PageSize;

                    Result = MemoryManager.AllocateOrMapPa(
                        StackPagesCount,
                        KMemoryManager.PageSize,
                        0,
                        false,
                        RegionStart,
                        RegionPagesCount,
                        MemoryState.Stack,
                        MemoryPermission.ReadAndWrite,
                        out ulong StackBottom);

                    if (Result != KernelResult.Success)
                    {
                        CleanUpForError();

                        return(Result);
                    }

                    MainThreadStackSize += StackSizeRounded;

                    StackTop = StackBottom + StackSizeRounded;
                }

                ulong HeapCapacity = MemoryUsageCapacity - MainThreadStackSize - ImageSize;

                Result = MemoryManager.SetHeapCapacity(HeapCapacity);

                if (Result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(Result);
                }

                HandleTable = new KHandleTable(System);

                Result = HandleTable.Initialize(Capabilities.HandleTableSize);

                if (Result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(Result);
                }

                MainThread = new KThread(System);

                Result = MainThread.Initialize(
                    Entrypoint,
                    0,
                    StackTop,
                    MainThreadPriority,
                    DefaultCpuCore,
                    this);

                if (Result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(Result);
                }

                Result = HandleTable.GenerateHandle(MainThread, out int MainThreadHandle);

                if (Result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(Result);
                }

                MainThread.SetEntryArguments(0, MainThreadHandle);

                ProcessState OldState = State;
                ProcessState NewState = State != ProcessState.Created
                    ? ProcessState.Attached
                    : ProcessState.Started;

                SetState(NewState);

                //TODO: We can't call KThread.Start from a non-guest thread.
                //We will need to make some changes to allow the creation of
                //dummy threads that will be used to initialize the current
                //thread on KCoreContext so that GetCurrentThread doesn't fail.

                /* Result = MainThread.Start();
                 *
                 * if (Result != KernelResult.Success)
                 * {
                 *  SetState(OldState);
                 *
                 *  CleanUpForError();
                 * } */

                MainThread.Reschedule(ThreadSchedState.Running);

                return(Result);
            }
        }
示例#22
0
        public KernelResult Initialize(
            ProcessCreationInfo CreationInfo,
            int[]               Caps,
            KResourceLimit ResourceLimit,
            MemoryRegion MemRegion)
        {
            this.ResourceLimit = ResourceLimit;
            this.MemRegion     = MemRegion;

            ulong PersonalMmHeapSize = GetPersonalMmHeapSize((ulong)CreationInfo.PersonalMmHeapPagesCount, MemRegion);

            ulong CodePagesCount = (ulong)CreationInfo.CodePagesCount;

            ulong NeededSizeForProcess = PersonalMmHeapSize + CodePagesCount * KMemoryManager.PageSize;

            if (NeededSizeForProcess != 0 && ResourceLimit != null)
            {
                if (!ResourceLimit.Reserve(LimitableResource.Memory, NeededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (NeededSizeForProcess != 0 && ResourceLimit != null)
                {
                    ResourceLimit.Release(LimitableResource.Memory, NeededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)CreationInfo.PersonalMmHeapPagesCount;

            KMemoryBlockAllocator MemoryBlockAllocator;

            if (PersonalMmHeapPagesCount != 0)
            {
                MemoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
            }
            else
            {
                MemoryBlockAllocator = (MmuFlags & 0x40) != 0
                    ? System.LargeMemoryBlockAllocator
                    : System.SmallMemoryBlockAllocator;
            }

            AddressSpaceType AddrSpaceType = (AddressSpaceType)((CreationInfo.MmuFlags >> 1) & 7);

            bool AslrEnabled = ((CreationInfo.MmuFlags >> 5) & 1) != 0;

            ulong CodeAddress = CreationInfo.CodeAddress;

            ulong CodeSize = CodePagesCount * KMemoryManager.PageSize;

            KernelResult Result = MemoryManager.InitializeForProcess(
                AddrSpaceType,
                AslrEnabled,
                !AslrEnabled,
                MemRegion,
                CodeAddress,
                CodeSize,
                MemoryBlockAllocator);

            if (Result != KernelResult.Success)
            {
                CleanUpForError();

                return(Result);
            }

            if (!ValidateCodeAddressAndSize(CodeAddress, CodeSize))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            Result = MemoryManager.MapNewProcessCode(
                CodeAddress,
                CodePagesCount,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (Result != KernelResult.Success)
            {
                CleanUpForError();

                return(Result);
            }

            Result = Capabilities.InitializeForUser(Caps, MemoryManager);

            if (Result != KernelResult.Success)
            {
                CleanUpForError();

                return(Result);
            }

            Pid = System.GetProcessId();

            if (Pid == -1 || (ulong)Pid < Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            Result = ParseProcessInfo(CreationInfo);

            if (Result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(Result);
        }
示例#23
0
            private RetrievePixelDataResult TryClientRetrievePixelData(out Exception lastRetrieveException)
            {
                // retry parameters
                const int retryTimeout = 1500;
                int       retryDelay   = 50;
                int       retryCounter = 0;

                //Second parameter true to use bulk loading, false to load images one by one
                MINTStreamingClient     client = new MINTStreamingClient(this.BaseUrl, UseBulkLoading, BinaryStream);
                RetrievePixelDataResult result = null;

                lastRetrieveException = null;

                CodeClock timeoutClock = new CodeClock();

                timeoutClock.Start();

                while (true)
                {
                    try
                    {
                        if (retryCounter > 0)
                        {
                            Platform.Log(LogLevel.Info, "Retrying retrieve pixel data for Sop '{0}' (Attempt #{1})", this.SopInstanceUid, retryCounter);
                        }

                        CodeClock statsClock = new CodeClock();
                        statsClock.Start();

                        result = client.RetrievePixelData();

                        statsClock.Stop();

                        Platform.Log(LogLevel.Debug, "[Retrieve Info] Sop/Frame: {0}/{1}, Transfer Syntax: {2}, Bytes transferred: {3}, Elapsed (s): {4}, Retries: {5}",
                                     this.SopInstanceUid, this.FrameNumber, this.TransferSyntaxUid,
                                     result.MetaData.ContentLength, statsClock.Seconds, retryCounter);

                        break;
                    }
                    catch (Exception ex)
                    {
                        lastRetrieveException = ex;

                        timeoutClock.Stop();
                        if (timeoutClock.Seconds * 1000 >= retryTimeout)
                        {
                            // log an alert that we are aborting (exception trace at debug level only)
                            int elapsed = (int)(1000 * timeoutClock.Seconds);
                            Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Aborting after {1} attempts in {2} ms", this.SopInstanceUid, retryCounter, elapsed);
                            Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Abort] Sop/Frame: {0}/{1}, Retry Attempts: {2}, Elapsed: {3} ms", this.SopInstanceUid, this.FrameNumber - 1, retryCounter, elapsed);
                            break;
                        }
                        timeoutClock.Start();

                        retryCounter++;

                        // log the retry (exception trace at debug level only)
                        Platform.Log(LogLevel.Warn, "Failed to retrieve pixel data for Sop '{0}'; Retrying in {1} ms", this.SopInstanceUid, retryDelay);
                        Platform.Log(LogLevel.Debug, ex, "[Retrieve Fail-Retry] Sop/Frame: {0}/{1}, Retry in: {2} ms", this.SopInstanceUid, this.FrameNumber - 1, retryDelay);
                        MemoryManager.Collect(retryDelay);
                        retryDelay *= 2;
                    }
                }

                return(result);
            }
示例#24
0
        internal static void HandleIncomingMessage(ArraySegment <byte> payload, Connection connection, SocketConfig activeConfig)
        {
            // This is where all data packets arrive after passing the connection handling.

            // TODO:
            // 1. Fragmentation
            // 2. Delay to pack messages

            byte channelId = payload.Array[payload.Offset];

            if (channelId < 0 || channelId >= connection.Channels.Length)
            {
                // ChannelId out of range
                return;
            }

            ArraySegment <byte>?incomingMessage = connection.Channels[channelId].HandleIncomingMessagePoll(new ArraySegment <byte>(payload.Array, payload.Offset + 1, payload.Count - 1), out bool hasMore);

            if (incomingMessage != null)
            {
                // Alloc memory that can be borrowed to userspace
                HeapMemory memory = MemoryManager.Alloc((uint)incomingMessage.Value.Count);

                // Copy payload to borrowed memory
                Buffer.BlockCopy(incomingMessage.Value.Array, incomingMessage.Value.Offset, memory.Buffer, 0, incomingMessage.Value.Count);

                // Send to userspace
                connection.Socket.UserEventQueue.Enqueue(new NetworkEvent()
                {
                    Connection        = connection,
                    Socket            = connection.Socket,
                    Type              = NetworkEventType.Data,
                    AllowUserRecycle  = true,
                    Data              = new ArraySegment <byte>(memory.Buffer, (int)memory.VirtualOffset, (int)memory.VirtualCount),
                    InternalMemory    = memory,
                    SocketReceiveTime = DateTime.Now,
                    ChannelId         = channelId
                });
            }

            if (hasMore)
            {
                HeapMemory messageMemory = null;

                do
                {
                    messageMemory = connection.Channels[channelId].HandlePoll();

                    if (messageMemory != null)
                    {
                        // Send to userspace
                        connection.Socket.UserEventQueue.Enqueue(new NetworkEvent()
                        {
                            Connection        = connection,
                            Socket            = connection.Socket,
                            Type              = NetworkEventType.Data,
                            AllowUserRecycle  = true,
                            Data              = new ArraySegment <byte>(messageMemory.Buffer, (int)messageMemory.VirtualOffset, (int)messageMemory.VirtualCount),
                            InternalMemory    = messageMemory,
                            SocketReceiveTime = DateTime.Now,
                            ChannelId         = channelId
                        });
                    }
                }while (messageMemory != null);
            }
        }
示例#25
0
        public static unsafe int MemoryUsageInfo(
            ulong *totalMemoryFree,
            ulong *totalMemoryInUse,
            ulong *kernelHeapInUse,
            ulong *kernelStackInUse,
            ulong *totalSIPHeapInUse,
            ulong *totalSIPStackInUse,
            ulong *kernelStackReservation,
            ulong *kernelHeapReservation
            )
        {
            ulong allocatedCount = 0;
            ulong allocatedBytes = 0;
            ulong freedCount     = 0;
            ulong freedBytes     = 0;

            ulong userAllocatedCount         = 0;
            ulong userAllocatedBytes         = 0;
            ulong userFreedCount             = 0;
            ulong userFreedBytes             = 0;
            ulong kernelHeapReservationLocal = 0;

            *totalMemoryFree  = MemoryManager.GetFreePhysicalMemory();
            *totalMemoryInUse = MemoryManager.GetUsedPhysicalMemory();

            //
            // Get general memory info
            //
            MemoryManager.GetUsageStatistics(
                out allocatedCount,
                out allocatedBytes,
                out freedCount,
                out freedBytes,
                out kernelHeapReservationLocal
                );

            //
            // Get SIP (user) memory usage
            //
            MemoryManager.GetUserStatistics(
                out userAllocatedCount,
                out userAllocatedBytes,
                out userFreedCount,
                out userFreedBytes
                );

            // Kernel heap is total heap in use - SIP heap in use
            *kernelHeapInUse       = (allocatedBytes - freedBytes) - (userAllocatedBytes - userFreedBytes);
            *kernelHeapReservation = kernelHeapReservationLocal;

            *totalSIPHeapInUse = userAllocatedBytes - userFreedBytes;

            // Stack Information
            ulong kernelStackCount            = 0;
            ulong kernelStackReturnCount      = 0;
            ulong kernelStackBytes            = 0;
            ulong kernelStackReturnBytes      = 0;
            ulong kernelStackReservationLocal = 0;
            ulong SIPStackCount       = 0;
            ulong SIPStackReturnCount = 0;
            ulong SIPStackBytes       = 0;
            ulong SIPStackReturnBytes = 0;
            ulong SIPStackReservation = 0;

            MemoryManager.GetStackUsage(
                out kernelStackCount,
                out kernelStackReturnCount,
                out kernelStackBytes,
                out kernelStackReturnBytes,
                out kernelStackReservationLocal,
                out SIPStackCount,
                out SIPStackReturnCount,
                out SIPStackBytes,
                out SIPStackReturnBytes,
                out SIPStackReservation
                );

            *totalSIPStackInUse     = SIPStackBytes - SIPStackReturnBytes;
            *kernelStackInUse       = kernelStackBytes - kernelStackReturnBytes;
            *kernelStackReservation = kernelStackReservationLocal;

            return(0);
        }
 public void Target()
 {
     MemoryManager?.WriteCurrentTargetToGameMemory();
 }
示例#27
0
 private static byte[] AllocatePixelData(int rows, int columns, int bitsPerPixel)
 {
     return(MemoryManager.Allocate <byte>(rows * columns * bitsPerPixel / 8));
 }
示例#28
0
        private void UpdateBuffer(MemoryManager memory)
        {
            //TODO: Implement conversion for formats other
            //than interleaved stereo (2 channels).
            //As of now, it assumes that HostChannelsCount == 2.
            WaveBuffer wb = WaveBuffers[_bufferIndex];

            if (wb.Position == 0)
            {
                _samples = new int[0];

                return;
            }

            if (SampleFormat == SampleFormat.PcmInt16)
            {
                int samplesCount = (int)(wb.Size / (sizeof(short) * ChannelsCount));

                _samples = new int[samplesCount * AudioConsts.HostChannelsCount];

                if (ChannelsCount == 1)
                {
                    for (int index = 0; index < samplesCount; index++)
                    {
                        short sample = memory.ReadInt16(wb.Position + index * 2);

                        _samples[index * 2 + 0] = sample;
                        _samples[index * 2 + 1] = sample;
                    }
                }
                else
                {
                    for (int index = 0; index < samplesCount * 2; index++)
                    {
                        _samples[index] = memory.ReadInt16(wb.Position + index * 2);
                    }
                }
            }
            else if (SampleFormat == SampleFormat.Adpcm)
            {
                byte[] buffer = memory.ReadBytes(wb.Position, wb.Size);

                _samples = AdpcmDecoder.Decode(buffer, AdpcmCtx);
            }
            else
            {
                throw new InvalidOperationException();
            }

            if (SampleRate != AudioConsts.HostSampleRate)
            {
                //TODO: We should keep the frames being discarded (see the 4 below)
                //on a buffer and include it on the next samples buffer, to allow
                //the resampler to do seamless interpolation between wave buffers.
                int samplesCount = _samples.Length / AudioConsts.HostChannelsCount;

                samplesCount = Math.Max(samplesCount - 4, 0);

                _samples = Resampler.Resample2Ch(
                    _samples,
                    SampleRate,
                    AudioConsts.HostSampleRate,
                    samplesCount,
                    ref _resamplerFracPart);
            }
        }
示例#29
0
        public static void Init()
        {
            try
            {
                ColorConsole.WriteLine(ConsoleColor.Cyan, "Classic Shell v1.1");
                commands : ColorConsole.Write(ConsoleColor.Cyan, Reference.UserAccount.GetUsername());
                ColorConsole.Write(ConsoleColor.White, Reference.UserAccess);
                ColorConsole.Write(ConsoleColor.Yellow, Reference.CurrentDir);
                ColorConsole.Write(ConsoleColor.White, " => ");
                string cmd = Console.ReadLine();

                if (cmd == Reference.Commands[0])
                {
                    string all = string.Empty;
                    foreach (string comnd in Reference.Commands)
                    {
                        all += $"{comnd} - ";
                    }
                    ColorConsole.WriteLine(ConsoleColor.White, all.Remove(all.Length - 3));
                    goto commands;
                }
                else if (cmd == Reference.Commands[1])
                {
                    SimpleGui.Init();
                }
                else if (cmd == Reference.Commands[2])
                {
                    ColorConsole.WriteLine(ConsoleColor.White, $"{UnixTime.Now()} (day/month/year hour:minute:second)");
                    goto commands;
                }
                else if (cmd == Reference.Commands[3])
                {
                    ColorConsole.WriteLine(ConsoleColor.White, $"{MemoryManager.UsedMemory()} MB / {MemoryManager.TotalMemory()} MB (used / total)");
                    goto commands;
                }
                else if (cmd == Reference.Commands[4])
                {
                    Textpad.Run();
                    Console.ReadKey();
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[4]} "))
                {
                    Textpad.Run(cmd.Split(" ")[1]);
                    Console.ReadKey();
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[5]} "))
                {
                    string lang    = cmd.Split(" ")[1];
                    string setName = "keyboard_layout";
                    if (lang == "fr")
                    {
                        Sys.KeyboardManager.SetKeyLayout(new Sys.ScanMaps.FR_Standard());
                        SettingsMan.Add(setName, "fr");
                    }
                    else if (lang == "us")
                    {
                        Sys.KeyboardManager.SetKeyLayout(new Sys.ScanMaps.US_Standard());
                        SettingsMan.Add(setName, "en");
                    }
                    else if (lang == "de")
                    {
                        Sys.KeyboardManager.SetKeyLayout(new Sys.ScanMaps.DE_Standard());
                        SettingsMan.Add(setName, "de");
                    }
                    else
                    {
                        ColorConsole.WriteLine(ConsoleColor.Red, "Unknown keyboard layout.");
                    }
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[6]} "))
                {
                    string newDir = cmd.Split(" ")[1];
                    if (Directory.Exists(newDir))
                    {
                        if (newDir.Contains(Reference.RootPath))
                        {
                            Reference.CurrentDir = newDir;
                        }
                        else
                        {
                            Reference.CurrentDir += newDir;
                        }
                    }
                    else
                    {
                        ColorConsole.WriteLine(ConsoleColor.Red, "Directory not found.");
                    }
                    goto commands;
                }
                else if (cmd == Reference.Commands[7])
                {
                    List <string[]> fad = new List <string[]>
                    {
                        Directory.GetDirectories(Reference.CurrentDir),
                        Directory.GetFiles(Reference.CurrentDir)
                    };

                    for (int i = 0; i < fad.Count; i++)
                    {
                        string[] list = fad[i];
                        for (int y = 0; y < list.Length; y++)
                        {
                            ColorConsole.WriteLine(ConsoleColor.Cyan, list[y]);
                        }
                    }
                    goto commands;
                }
                else if (cmd == Reference.Commands[8])
                {
                    Console.Clear();
                    LoginMan.Init();
                }
                else if (cmd == Reference.Commands[9])
                {
                    Console.Clear();
                    goto commands;
                }
                else if (cmd == Reference.Commands[10])
                {
                    ColorConsole.WriteLine(ConsoleColor.White, $"Sartox OS ver {Reference.Version}, kernel ver {Reference.KernelVersion} made by ShiningLea.\n\nSartox OS is an operating system made in C# with the COSMOS kit. The goal here is to provide a minimal but working operating system for any purpose. Currently made by only one developer, it's highly maintained and will continue to be as long as the dev wants to (oh wait, I'm literally writing this message...)");
                    goto commands;
                }
                else if (cmd == Reference.Commands[11])
                {
                    Power.Shutdown();
                }
                else if (cmd.StartsWith($"{Reference.Commands[12]} "))
                {
                    Directory.CreateDirectory(cmd.Split(" ")[1]);
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[13]} "))
                {
                    File.Create(cmd.Split(" ")[1]);
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[14]} "))
                {
                    File.WriteAllText(cmd.Split(" ")[1], string.Empty);
                    goto commands;
                }
                else if (cmd == Reference.Commands[14])
                {
                    ColorConsole.WriteLine(ConsoleColor.White, "Touch what?");
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[15]} "))
                {
                    File.WriteAllText(cmd.Split(" ")[1], cmd.Split(" ")[2]);
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[16]} "))
                {
                    string file = cmd.Split(" ")[1];
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                    else
                    {
                        ColorConsole.WriteLine(ConsoleColor.Red, "The specified file doesn't exist.");
                    }
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[17]} "))
                {
                    string dir = cmd.Split(" ")[1];
                    if (Directory.Exists(dir))
                    {
                        Directory.Delete(dir, true);
                    }
                    else
                    {
                        ColorConsole.WriteLine(ConsoleColor.Red, "The specified directory doesn't exist.");
                    }
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[18]} "))
                {
                    string move = cmd.Split(" ")[1];
                    if (Directory.Exists(move) || File.Exists(move))
                    {
                        Directory.Move(move, cmd.Split(" ")[2]);
                    }
                    else
                    {
                        ColorConsole.WriteLine(ConsoleColor.Red, "The source directory/file doesn't exist.");
                    }
                    goto commands;
                }
                else if (cmd.StartsWith($"{Reference.Commands[19]} "))
                {
                    File.Copy(cmd.Split(" ")[1], cmd.Split(" ")[2], true);
                    goto commands;
                }
                else if (cmd == Reference.Commands[20])
                {
                    Power.Restart();
                }
                else if (cmd == Reference.Commands[21])
                {
                    throw new Exception("Crash initialized by user.");
                }
                else if (cmd == Reference.Commands[22])
                {
                    SartoxShell.Init();
                }
                else
                {
                    ColorConsole.WriteLine(ConsoleColor.Red, "Invalid command.");
                    goto commands;
                }
            }
            catch (Exception e)
            {
                Global.mDebugger.Send("ERROR : " + e.Message + e.HResult.ToString());
                ErrorScreen.Init(e.Message, e.HResult);
            }
        }
示例#30
0
        public KernelResult InitializeKip(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KPageList pageList,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;

            KMemoryBlockAllocator memoryBlockAllocator = (MmuFlags & 0x40) != 0
                ? System.LargeMemoryBlockAllocator
                : System.SmallMemoryBlockAllocator;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(
                codeAddress,
                pageList,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            result = Capabilities.InitializeForKernel(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            Pid = System.GetKipId();

            if (Pid == 0 || (ulong)Pid >= Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            return(result);
        }
示例#31
0
 public string getName()
 {
     MemoryManager x = new MemoryManager();
     x.Attach("League of Legends");
     var name = x.ReadString(LeagueAdressesOffsets.PlayerObject.Name, 16);
     x.Disconnect();
     return name;
 }
示例#32
0
        public KernelResult Start(int mainThreadPriority, ulong stackSize)
        {
            lock (_processLock)
            {
                if (_state > ProcessState.CreatedAttached)
                {
                    return(KernelResult.InvalidState);
                }

                if (ResourceLimit != null && !ResourceLimit.Reserve(LimitableResource.Thread, 1))
                {
                    return(KernelResult.ResLimitExceeded);
                }

                KResourceLimit threadResourceLimit = ResourceLimit;
                KResourceLimit memoryResourceLimit = null;

                if (_mainThreadStackSize != 0)
                {
                    throw new InvalidOperationException("Trying to start a process with a invalid state!");
                }

                ulong stackSizeRounded = BitUtils.AlignUp(stackSize, KMemoryManager.PageSize);

                ulong neededSize = stackSizeRounded + _imageSize;

                // Check if the needed size for the code and the stack will fit on the
                // memory usage capacity of this Process. Also check for possible overflow
                // on the above addition.
                if (neededSize > _memoryUsageCapacity ||
                    neededSize < stackSizeRounded)
                {
                    threadResourceLimit?.Release(LimitableResource.Thread, 1);

                    return(KernelResult.OutOfMemory);
                }

                if (stackSizeRounded != 0 && ResourceLimit != null)
                {
                    memoryResourceLimit = ResourceLimit;

                    if (!memoryResourceLimit.Reserve(LimitableResource.Memory, stackSizeRounded))
                    {
                        threadResourceLimit?.Release(LimitableResource.Thread, 1);

                        return(KernelResult.ResLimitExceeded);
                    }
                }

                KernelResult result;

                KThread mainThread = null;

                ulong stackTop = 0;

                void CleanUpForError()
                {
                    HandleTable.Destroy();

                    mainThread?.DecrementReferenceCount();

                    if (_mainThreadStackSize != 0)
                    {
                        ulong stackBottom = stackTop - _mainThreadStackSize;

                        ulong stackPagesCount = _mainThreadStackSize / KMemoryManager.PageSize;

                        MemoryManager.UnmapForKernel(stackBottom, stackPagesCount, MemoryState.Stack);

                        _mainThreadStackSize = 0;
                    }

                    memoryResourceLimit?.Release(LimitableResource.Memory, stackSizeRounded);
                    threadResourceLimit?.Release(LimitableResource.Thread, 1);
                }

                if (stackSizeRounded != 0)
                {
                    ulong stackPagesCount = stackSizeRounded / KMemoryManager.PageSize;

                    ulong regionStart = MemoryManager.StackRegionStart;
                    ulong regionSize  = MemoryManager.StackRegionEnd - regionStart;

                    ulong regionPagesCount = regionSize / KMemoryManager.PageSize;

                    result = MemoryManager.AllocateOrMapPa(
                        stackPagesCount,
                        KMemoryManager.PageSize,
                        0,
                        false,
                        regionStart,
                        regionPagesCount,
                        MemoryState.Stack,
                        MemoryPermission.ReadAndWrite,
                        out ulong stackBottom);

                    if (result != KernelResult.Success)
                    {
                        CleanUpForError();

                        return(result);
                    }

                    _mainThreadStackSize += stackSizeRounded;

                    stackTop = stackBottom + stackSizeRounded;
                }

                ulong heapCapacity = _memoryUsageCapacity - _mainThreadStackSize - _imageSize;

                result = MemoryManager.SetHeapCapacity(heapCapacity);

                if (result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(result);
                }

                HandleTable = new KHandleTable(System);

                result = HandleTable.Initialize(Capabilities.HandleTableSize);

                if (result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(result);
                }

                mainThread = new KThread(System);

                result = mainThread.Initialize(
                    _entrypoint,
                    0,
                    stackTop,
                    mainThreadPriority,
                    DefaultCpuCore,
                    this);

                if (result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(result);
                }

                result = HandleTable.GenerateHandle(mainThread, out int mainThreadHandle);

                if (result != KernelResult.Success)
                {
                    CleanUpForError();

                    return(result);
                }

                mainThread.SetEntryArguments(0, mainThreadHandle);

                ProcessState oldState = _state;
                ProcessState newState = _state != ProcessState.Created
                    ? ProcessState.Attached
                    : ProcessState.Started;

                SetState(newState);

                // TODO: We can't call KThread.Start from a non-guest thread.
                // We will need to make some changes to allow the creation of
                // dummy threads that will be used to initialize the current
                // thread on KCoreContext so that GetCurrentThread doesn't fail.

                /* Result = MainThread.Start();
                 *
                 * if (Result != KernelResult.Success)
                 * {
                 *  SetState(OldState);
                 *
                 *  CleanUpForError();
                 * } */

                mainThread.Reschedule(ThreadSchedState.Running);

                if (result == KernelResult.Success)
                {
                    mainThread.IncrementReferenceCount();
                }

                mainThread.DecrementReferenceCount();

                return(result);
            }
        }
示例#33
0
 private int getMoveSpeed()
 {
     MemoryManager x = new MemoryManager();
     x.Attach("League of Legends");
     var GoldLv1Adress = (IntPtr)(x.ReadInteger(LeagueAdressesOffsets.PlayerObject.BaseAdress) + LeagueAdressesOffsets.PlayerObject.Attributes.Offset);
     var GoldAdress = (IntPtr)(x.ReadInteger(GoldLv1Adress.ToInt32()) + LeagueAdressesOffsets.PlayerObject.Attributes.MoveSpeed.Offset);
     var gold = x.ReadFloat(GoldAdress.ToInt32());
     x.Disconnect();
     return Convert.ToInt32(Math.Round(gold));
 }
示例#34
0
        public virtual void send( MidiEvent[] events )
        {
            unsafe {
                MemoryManager mman = null;
                try {
                    mman = new MemoryManager();
                    int nEvents = events.Length;
                    VstEvents* pVSTEvents = (VstEvents*)mman.malloc( sizeof( VstEvent ) + nEvents * sizeof( VstEvent* ) ).ToPointer();
                    pVSTEvents->numEvents = 0;
                    pVSTEvents->reserved = (VstIntPtr)0;

                    for ( int i = 0; i < nEvents; i++ ) {
                        MidiEvent pProcessEvent = events[i];
                        //byte event_code = (byte)pProcessEvent.firstByte;
                        VstEvent* pVSTEvent = (VstEvent*)0;
                        VstMidiEvent* pMidiEvent;
                        pMidiEvent = (VstMidiEvent*)mman.malloc( (int)(sizeof( VstMidiEvent ) + (pProcessEvent.data.Length + 1) * sizeof( byte )) ).ToPointer();
                        pMidiEvent->byteSize = sizeof( VstMidiEvent );
                        pMidiEvent->deltaFrames = 0;
                        pMidiEvent->detune = 0;
                        pMidiEvent->flags = 1;
                        pMidiEvent->noteLength = 0;
                        pMidiEvent->noteOffset = 0;
                        pMidiEvent->noteOffVelocity = 0;
                        pMidiEvent->reserved1 = 0;
                        pMidiEvent->reserved2 = 0;
                        pMidiEvent->type = VstEventTypes.kVstMidiType;
                        pMidiEvent->midiData[0] = (byte)(0xff & pProcessEvent.firstByte);
                        for ( int j = 0; j < pProcessEvent.data.Length; j++ ) {
                            pMidiEvent->midiData[j + 1] = (byte)(0xff & pProcessEvent.data[j]);
                        }
                        pVSTEvents->events[pVSTEvents->numEvents++] = (int)(VstEvent*)pMidiEvent;
                    }
                    aEffect.Dispatch( AEffectXOpcodes.effProcessEvents, 0, 0, new IntPtr( pVSTEvents ), 0 );
                } catch ( Exception ex ) {
                    serr.println( "vstidrv#send; ex=" + ex );
                } finally {
                    if ( mman != null ) {
                        try {
                            mman.dispose();
                        } catch ( Exception ex2 ) {
                            serr.println( "vstidrv#send; ex2=" + ex2 );
                        }
                    }
                }
            }
        }
示例#35
0
        static void Main(string[] args)
        {
            Console.Title = $"Externalio - Build ({ Extensions.AssemblyCreationDate() })";

            Globals.Proc.Process = Extensions.Proc.WaitForProcess(Globals.Proc.Name);

            Extensions.Proc.WaitForModules(Globals.Proc.Modules, Globals.Proc.Name);

            MemoryManager.Initialize(Globals.Proc.Process.Id);

            List <string> outdatedSignatures = Offsets.ScanPatterns();

            if (outdatedSignatures.Count > 0)
            {
                foreach (string sig in outdatedSignatures)
                {
                    Extensions.Error($"> Outdated Signature: { sig }", 0, false);
                }

                Console.ReadKey();

                Environment.Exit(0);
            }

            Config.Load();

            /* Temp */
            Extensions.Information("---------------------------------------------]", true);
            Extensions.Information("[TempMessage] Config Save:     F4", true);
            Extensions.Information("[TempMessage] Config Load:     F5", true);
            Extensions.Information("---------------------------------------------]", true);
            Extensions.Information("[TempMessage] Toggle Bunnyhop: F6", true);
            Extensions.Information("[TempMessage] Toggle Trigger:  F7", true);
            Extensions.Information("[TempMessage] Toggle Glow:     F8", true);
            Extensions.Information("[TempMessage] Toggle Radar:    F9", true);
            Extensions.Information("[TempMessage] Toggle Aimbot:   F10", true);
            Extensions.Information("[TempMessage] Toggle Chams:    F11", true);
            Extensions.Information("---------------------------------------------]", true);

            ThreadManager.Add("Watcher", Watcher.Run);
            ThreadManager.Add("Reader", Reader.Run);

            ThreadManager.Add("Bunnyhop", Bunnyhop.Run);
            ThreadManager.Add("Trigger", Trigger.Run);
            ThreadManager.Add("Glow", Glow.Run);
            ThreadManager.Add("Radar", Radar.Run);
            ThreadManager.Add("Aimbot", Aimbot.Run);
            ThreadManager.Add("Chams", Chams.Run);

            ThreadManager.ToggleThread("Watcher");
            ThreadManager.ToggleThread("Reader");

            if (Settings.Bunnyhop.Enabled)
            {
                ThreadManager.ToggleThread("Bunnyhop");
            }
            if (Settings.Trigger.Enabled)
            {
                ThreadManager.ToggleThread("Trigger");
            }
            if (Settings.Glow.Enabled)
            {
                ThreadManager.ToggleThread("Glow");
            }
            if (Settings.Radar.Enabled)
            {
                ThreadManager.ToggleThread("Radar");
            }
            if (Settings.Aimbot.Enabled)
            {
                ThreadManager.ToggleThread("Aimbot");
            }
            if (Settings.Chams.Enabled)
            {
                ThreadManager.ToggleThread("Chams");
            }
        }
示例#36
0
 public MemoryInjector(MemoryManager mngr, int size)
 {
     Mngr = mngr;
     Address = mngr.AllocateMemory(size, Imports.AllocationType.Commit, Imports.MemoryProtection.ExecuteReadWrite);
 }
示例#37
0
 public static T DeviceRead <T>(this MemoryManager gmm, uint offset) where T : unmanaged
 {
     return(gmm.Read <T>((ulong)offset << 8));
 }
示例#38
0
 public ElementWithMemoryManager(SendPacketsElement element, MemoryManager <byte> memoryManager)
 {
     Element       = element;
     MemoryManager = memoryManager;
 }
示例#39
0
        public KernelResult InitializeKip(
            ProcessCreationInfo CreationInfo,
            int[]               Caps,
            KPageList PageList,
            KResourceLimit ResourceLimit,
            MemoryRegion MemRegion)
        {
            this.ResourceLimit = ResourceLimit;
            this.MemRegion     = MemRegion;

            AddressSpaceType AddrSpaceType = (AddressSpaceType)((CreationInfo.MmuFlags >> 1) & 7);

            bool AslrEnabled = ((CreationInfo.MmuFlags >> 5) & 1) != 0;

            ulong CodeAddress = CreationInfo.CodeAddress;

            ulong CodeSize = (ulong)CreationInfo.CodePagesCount * KMemoryManager.PageSize;

            KMemoryBlockAllocator MemoryBlockAllocator = (MmuFlags & 0x40) != 0
                ? System.LargeMemoryBlockAllocator
                : System.SmallMemoryBlockAllocator;

            KernelResult Result = MemoryManager.InitializeForProcess(
                AddrSpaceType,
                AslrEnabled,
                !AslrEnabled,
                MemRegion,
                CodeAddress,
                CodeSize,
                MemoryBlockAllocator);

            if (Result != KernelResult.Success)
            {
                return(Result);
            }

            if (!ValidateCodeAddressAndSize(CodeAddress, CodeSize))
            {
                return(KernelResult.InvalidMemRange);
            }

            Result = MemoryManager.MapPages(
                CodeAddress,
                PageList,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (Result != KernelResult.Success)
            {
                return(Result);
            }

            Result = Capabilities.InitializeForKernel(Caps, MemoryManager);

            if (Result != KernelResult.Success)
            {
                return(Result);
            }

            Pid = System.GetKipId();

            if (Pid == 0 || (ulong)Pid >= Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            Result = ParseProcessInfo(CreationInfo);

            return(Result);
        }
示例#40
0
 public virtual Message copy(MemoryManager memManager)
 {
     return(copy(true, memManager));
 }
示例#41
0
 public static ReadOnlySpan <byte> DeviceGetSpan(this MemoryManager gmm, uint offset, int size)
 {
     return(gmm.GetSpan((ulong)offset << 8, size));
 }
示例#42
0
 private int getMaximumHealth()
 {
     MemoryManager x = new MemoryManager();
         x.Attach("League of Legends");
         var GoldLv1Adress = (IntPtr)(x.ReadInteger(LeagueAdressesOffsets.PlayerObject.BaseAdress) + LeagueAdressesOffsets.PlayerObject.Stats.Offset);
         var GoldAdress = (IntPtr)(x.ReadInteger(GoldLv1Adress.ToInt32()) + LeagueAdressesOffsets.PlayerObject.Stats.MaxHealth.Offset);
         var gold = x.ReadInteger(GoldAdress.ToInt32());
         x.Disconnect();
         return gold;
 }
示例#43
0
 public static void DeviceWrite(this MemoryManager gmm, uint offset, ReadOnlySpan <byte> data)
 {
     gmm.Write((ulong)offset << 8, data);
 }
示例#44
0
 private int getUserGold()
 {
     MemoryManager x = new MemoryManager();
         x.Attach("League of Legends");
         var GoldLv1Adress = (IntPtr)(x.ReadInteger(LeagueAdressesOffsets.PlayerObject.BaseAdress) + LeagueAdressesOffsets.PlayerObject.Attributes.Offset);
         var GoldAdress = (IntPtr)(x.ReadInteger(GoldLv1Adress.ToInt32()) + LeagueAdressesOffsets.PlayerObject.Attributes.Gold.Offset);
         var gold = x.ReadInteger(GoldAdress.ToInt32());
         x.Disconnect();
         return gold;
 }
示例#45
0
 public ResourceManager(MemoryManager gmm, BufferPool <Pixel> surfacePool, BufferPool <byte> bufferPool)
 {
     Gmm         = gmm;
     SurfacePool = surfacePool;
     BufferPool  = bufferPool;
 }