//
    // Memcard Functions
    //

    /// <summary>
    /// Writes an entire memcard's contents
    /// </summary>
    /// <param name="inCard">0/1</param>
    public static bool Command_MemcardUpload(UInt32 inCard, byte[] inFile)
    {
        if (!TransferLogic.ChallengeResponse(CommandMode.MCUP))
        {
            return(Error("No response from Unirom. Are you using 8.0.E or higher?"));
        }

        Console.WriteLine("Uploading card data...");

        // send the card number
        activeSerial.Write(BitConverter.GetBytes(inCard), 0, 4);
        // file size in bytes, let unirom handle it
        activeSerial.Write(BitConverter.GetBytes(inFile.Length), 0, 4);
        activeSerial.Write(BitConverter.GetBytes(CalculateChecksum(inFile)), 0, 4);

        if (TransferLogic.WriteBytes(inFile, false))
        {
            Console.WriteLine("File uploaded, check your screen...");
        }
        else
        {
            return(Error("Couldn't upload to unirom - no write attempt will be made", false));
        }

        return(true);
    }
Example #2
0
    public static void DebugInit(UInt32 localPort)
    {
        Console.WriteLine("Checking if Unirom is in debug mode...");

        // if it returns true, we might enter /m (monitor) mode, etc
        if (
            !TransferLogic.ChallengeResponse(CommandMode.DEBUG)
            )
        {
            Console.WriteLine("Couldn't determine if Unirom is in debug mode.");
            return;
        }

        Console.WriteLine("Grabbing initial state...");

        TransferLogic.Command_DumpRegs();

        Console.WriteLine("Monitoring sio...");

        Console.WriteLine("********************** WARNING ***************************");
        Console.WriteLine("THE TCP BRIDGE DOES NOT CURRENTLY ACCEPT COMMANDS FROM GDB");
        Console.WriteLine("********************** ******* ***************************");

        Init(localPort);
    }
        #pragma warning restore CS0162

    /*
     * /// <summary>
     * /// Leaves the serial connection open
     * /// Will attempt to detect /HALT notifications from Unirom
     * /// and catch crash/exception events
     * /// </summary>
     * public static void DoMonitor(){
     *
     * // Note:
     * // Mono hasn't implemented the activeSerial.ReceivedBytesThreshold methods yet
     * // so we can't really use events. Instead the max we'll wait is 1ms to enter the
     * // tight inner loop. Should be fine if you're not filling a ~2kb buffer in 1ms
     *
     *      // a rolling buffer of the last 4 things recieved
     *      string lastMonitorBytes = "";
     *
     *      while (true)
     *      {
     *
     *              while (activeSerial.BytesToRead > 0)
     *              {
     *
     *                      // echo things to the screen
     *
     *                      int responseByte = activeSerial.ReadByte();
     *                      Console.Write((char)(responseByte));
     *
     *                      // check if the PSX has crashed
     *
     *      // TODO: use a more appropriate data collection, lol
     *                      lastMonitorBytes += (char)responseByte;
     *                      while ( lastMonitorBytes.Length > 4 )
     *                              lastMonitorBytes = lastMonitorBytes.Remove( 0, 1 );
     *
     *                      if ( lastMonitorBytes == "HLTD" ){
     *
     *                              while ( true ){
     *
     *                                      Console.WriteLine( "\nThe PSX may have crashed, enter debug mode? (y/n)" );
     *              Console.WriteLine( "(Also starts a TCP/SIO bridge on port 3333." );
     *                                      ConsoleKeyInfo c = Console.ReadKey();
     *                                      if ( c.KeyChar.ToString().ToLowerInvariant() == "y" ){
     *                  GDB.GetRegs();
     *                  GDB.DumpRegs();
     *                                              GDB.Init( 3333 );
     *                                              return;
     *                                      } else {
     *                                              Console.WriteLine( "\nReturned to monitor mode." );
     *                                              break;
     *                                      }
     *
     *                              }
     *
     *
     *                      }
     *
     *              }
     *
     *  Thread.Sleep( 1 );
     *
     *      }
     *
     *
     * }
     */

    /// <summary>
    /// Puts Unirom into /debug mode and wipes everything from the end of the kernel
    /// to the stack, where it will crash.
    //  0x80010000 -> 0x801FFF??
    /// </summary>
    /// <param name="wipeValue">32 bit value to fill ram with</param>
    /// <returns></returns>
    public static bool Command_WipeMem(UInt32 wipeAddress, UInt32 wipeValue)
    {
        // if it returns true, we might enter /m (monitor) mode, etc
        if (
            !TransferLogic.ChallengeResponse(CommandMode.DEBUG)
            )
        {
            Console.WriteLine("Couldn't determine if Unirom is in debug mode.");
            return(false);
        }

        Thread.Sleep(200);

        byte[] buffer = new byte[0x80200000 - wipeAddress];           // just shy of 2MB

        for (int i = 0; i < buffer.Length / 4; i++)
        {
            BitConverter.GetBytes(wipeValue).CopyTo(buffer, i * 4);
        }

        Command_SendBin(wipeAddress, buffer);

        // It won't return.
        return(true);
    }
    /// <summary>
    /// Reads and dumps a memcard to disc
    /// </summary>
    /// <param name="inCard">0/1</param>
    public static bool Command_MemcardDownload(UInt32 inCard, string fileName)
    {
        if (!TransferLogic.ChallengeResponse(CommandMode.MCDOWN))
        {
            return(Error("No response from Unirom. Are you using 8.0.E or higher?"));
        }

        // send the card number
        activeSerial.Write(BitConverter.GetBytes(inCard), 0, 4);

        Console.WriteLine("Reading card to ram...");

        // it'll send this when it's done dumping to ram
        if (!TransferLogic.WaitResponse("MCRD", false))
        {
            return(Error("Please see screen or SIO for error!"));
        }

        Console.WriteLine("Ready, reading....");

        UInt32 addr = TransferLogic.read32();

        Console.WriteLine("Data is 0x" + addr.ToString("x"));

        UInt32 size = TransferLogic.read32();

        Console.WriteLine("Size is 0x" + size.ToString("x"));


        Console.WriteLine("Dumping...");

        byte[] lastReadBytes = new byte[size];
        TransferLogic.ReadBytes(addr, size, lastReadBytes);


        if (System.IO.File.Exists(fileName))
        {
            string newFilename = fileName + GetSpan().TotalSeconds.ToString();

            Console.Write("\n\nWARNING: Filename " + fileName + " already exists! - Dumping to " + newFilename + " instead!\n\n");

            fileName = newFilename;
        }

        try
        {
            File.WriteAllBytes(fileName, lastReadBytes);
        }
        catch (Exception e)
        {
            return(Error("Couldn't write to the output file + " + fileName + " !\nThe error returned was: " + e, false));
        }

        Console.WriteLine("File written to: " + fileName);
        Console.WriteLine("It is raw .mcd format used by PCSX-redux, no$psx, etc");
        return(true);
    }
Example #5
0
    public static void Init()
    {
        Console.WriteLine("Checking if Unirom is in debug mode...");

        // if it returns true, we might enter /m (monitor) mode, etc
        if (
            !TransferLogic.ChallengeResponse(CommandMode.DEBUG)
            )
        {
            Console.WriteLine("Couldn't determine if Unirom is in debug mode.");
            return;
        }

        Console.WriteLine("Grabbing initial state...");

        TransferLogic.Command_DumpRegs();

        Console.WriteLine("Monitoring sio...");

        InitSocket();

        MonitorSIOAndSocket();
    }
    /// <summary>
    /// We've parsed everything from stdin, let's start processing it.
    /// </summary>
    /// <returns>success?</returns>
    private static bool DoStuff()
    {
        PrintUsage(true);

        //
        // Process the secondary/standalone commands
        // /fast, /slow, /m, etc
        //

        if (enterFastMode)
        {
            // start in normal mode and send a "FAST" command
            // unirom doesn't have to respond, so if it's already in fast mode, no biggie
            if (!NewSIO(SIOSPEED.SLOW))
            {
                return(false);
            }

            // The bytes "FAST" with no null terminator
            activeSerial.Write(BitConverter.GetBytes(0x54534146), 0, 4);
            Thread.Sleep(100);

            // Switch to fast
            if (!NewSIO(SIOSPEED.FAST))
            {
                return(false);
            }
        }
        else if (enterSlowMode)
        {
            // As above, but returns to 115200 so you don't have to 'nops /fast' all the time

            // going to assume Unirom's in fast mode.. so start there and negotiate back down
            if (!NewSIO(SIOSPEED.FAST))
            {
                return(false);
            }

            // The bytes "FAST" with no null terminator
            activeSerial.Write(BitConverter.GetBytes(0x574F4C53), 0, 4);
            Thread.Sleep(100);

            // Now switch back
            if (!NewSIO(SIOSPEED.SLOW))
            {
                return(false);
            }
        }
        else
        {
            if (!NewSIO(SIOSPEED.SLOW))
            {
                return(false);
            }
        }


        // If we got /m on its own
        if (monitorComms && argCommand == CommandMode.NOT_SET)
        {
            GDB.MonitorSerialToSocket();
            return(true);
        }

        // we just did 'nops /fast /m' or something
        if (allArgsAreSecondary)
        {
            return(true);
        }


        //
        // A little cleanup...
        //

        if (usingCachedComPort)
        {
            Console.WriteLine("Using port " + argComPort + " from comport.txt\n");
        }

        // Clear the SIO buffer incase the last program has been spamming

        Console.WriteLine("Emptying buffer... ");
        while (activeSerial.BytesToRead != 0)
        {
            Console.Write("" + (char)activeSerial.ReadByte());
        }
        Console.WriteLine("...done!\n\n");


        //
        // Process the primary commands
        //

        // Upload

        if (argCommand == CommandMode.SEND_EXE)
        {
            TransferLogic.Command_SendEXE(inFile);
        }

        if (argCommand == CommandMode.SEND_BIN)
        {
            TransferLogic.Command_SendBin(argAddr, inFile);
        }

        if (argCommand == CommandMode.SEND_ROM)
        {
            TransferLogic.Command_SendROM(argAddr, inFile);
        }

        // Program flow

        if (argCommand == CommandMode.JUMP_JMP)
        {
            TransferLogic.Command_JumpAddr(argAddr);
        }

        if (argCommand == CommandMode.JUMP_CALL)
        {
            TransferLogic.Command_CallAddr(argAddr);
        }

        // Pokeypoke

        if (argCommand == CommandMode.POKE8)
        {
            byte[] bytes = { (byte)(argValue & 0xFF) };
            TransferLogic.Command_SendBin(argAddr, bytes);
        }

        if (argCommand == CommandMode.POKE16)
        {
            short  shorty = (byte)(argValue & 0xFFFF);
            byte[] bytes  = BitConverter.GetBytes(shorty);
            TransferLogic.Command_SendBin(argAddr, bytes);
        }

        if (argCommand == CommandMode.POKE32)
        {
            byte[] bytes = BitConverter.GetBytes(argValue);
            TransferLogic.Command_SendBin(argAddr, bytes);
        }

        // Utility

        if (argCommand == CommandMode.PING)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.RESET)
        {
            TransferLogic.WriteChallenge(argCommand.challenge());
        }

        // Debug functions

        if (argCommand == CommandMode.DEBUG)
        {
            // if it returns true, we might enter /m (monitor) mode, etc
            if (
                !TransferLogic.ChallengeResponse(argCommand)
                )
            {
                return(false);
            }
        }

        if (argCommand == CommandMode.HALT)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.CONT)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.REGS)
        {
            TransferLogic.Command_DumpRegs();
        }

        if (argCommand == CommandMode.SETREG)
        {
            if (!TransferLogic.Command_SetReg(argRegister, argValue))
            {
                return(Error("Couldn't set reg " + argRegister + " to " + argValue, false));
            }
        }


        // Hook functions

        if (
            argCommand == CommandMode.HOOKREAD ||
            argCommand == CommandMode.HOOKWRITE ||
            argCommand == CommandMode.HOOKEXEC
            )
        {
            if (TransferLogic.ChallengeResponse(argCommand))
            {
                activeSerial.Write(BitConverter.GetBytes(argAddr), 0, 4);
            }
        }

        // Memory card

        if (argCommand == CommandMode.MCUP)
        {
            if (!TransferLogic.Command_MemcardUpload(argCard, inFile))
            {
                return(false);
            }
        }

        if (argCommand == CommandMode.WIPEMEM)
        {
            if (!TransferLogic.Command_WipeMem(argAddr, argValue))
            {
                return(false);
            }
        }

        if (argCommand == CommandMode.MCDOWN)
        {
            if (!TransferLogic.Command_MemcardDownload(argCard, argFileName))
            {
                return(false);
            }
        }

        // Peek / Read functions

        if (argCommand == CommandMode.DUMP)
        {
            if (!TransferLogic.Command_Dump(argAddr, argSize))
            {
                return(false);
            }
        }

        if (argCommand == CommandMode.WATCH)
        {
            TransferLogic.Watch(argAddr, argSize);
            return(true);
        }


        //
        // Major work in progress
        //

        if (argCommand == CommandMode.GDB)
        {
            GDB.DebugInit(argPort);
        }

        if (argCommand == CommandMode.BRIDGE)
        {
            GDB.Init(argPort);
        }

        //
        // All done, are we leaving the comms monitor open?
        //

        if (monitorComms)
        {
            GDB.MonitorSerialToSocket();
        }
        else
        {
            Console.WriteLine("\n Bye!");
            activeSerial.Close();
        }

        return(true);
    }     // void Transfer
Example #7
0
    private static bool Transfer()
    {
        PrintUsage(true);


        activeSerial = new SerialPort(argComPort, 115200, Parity.None, 8, StopBits.Two);
        // Required for e.g. SharkLink & Yaroze cable compat. Doesn't interfere with the 3-wire setups
        activeSerial.Handshake = Handshake.None;
        activeSerial.DtrEnable = true;
        activeSerial.RtsEnable = true;

        if (fastMode)
        {
            activeSerial.ReadTimeout  = TIMEOUT;
            activeSerial.WriteTimeout = TIMEOUT;

            try {
                activeSerial.Open();
            } catch (Exception exception) {
                Console.WriteLine("Error opening temporary serial port on " + argComPort + "!");
                Console.WriteLine(exception.Message);

                return(false);
            }

            // The bytes "FAST" with no null terminator
            activeSerial.Write(BitConverter.GetBytes(0x54534146), 0, 4);


            Thread.Sleep(100);


            activeSerial.Close();

            // We need to find a suitable overlap in frequencies which can be divided
            // from the Playstation's clock and from the FTDI/clone, with some wiggle room.
            //
            // PSX/libs uses whole integer divisions of 2073600 for anything over 115200
            // giving us 518400 close to the half-megabyte mark.
            //
            // Most FTDI/clones seem to operate in 2xinteger divisions of 48mhz
            // giving us 510000 or 521000 close to the half-megabyte mark. e.g. (48m/47/2) or (48m/46/2)
            //
            // 5210000 (and even 518400) is a little fast, but the lower end
            // of things (510000 to 518300) seems pretty stable.
            //
            // note: psx @ 518400, pc @ 510000
            //
            activeSerial = new SerialPort(argComPort, 510000, Parity.None, 8, StopBits.Two);
            // Required for e.g. SharkLink & Yaroze cable compat. Doesn't interfere with the 3-wire setups
            activeSerial.Handshake = Handshake.None;
            activeSerial.DtrEnable = true;
            activeSerial.RtsEnable = true;
        }

        // Now the main serial port

        activeSerial.ReadTimeout  = TIMEOUT;
        activeSerial.WriteTimeout = TIMEOUT;

        try {
            activeSerial.Open();
        } catch (Exception exception) {
            Console.WriteLine("Error opening the serial port on " + argComPort + "!");
            Console.WriteLine(exception.Message);

            return(false);
        }



        // just lets us skip a ton of ifs
        if (monitorComms && argCommand == CommandMode.NOT_SET)
        {
            TransferLogic.DoMonitor();
            return(true);
        }


        if (usingCachedComPort)
        {
            Console.WriteLine("Using port " + argComPort + " from comport.txt\n");
        }

        // Clear the SIO buffer incase the last program has been spamming

        Console.WriteLine("Emptying buffer... ");
        while (activeSerial.BytesToRead != 0)
        {
            Console.Write("" + (char)activeSerial.ReadByte());
        }
        Console.WriteLine("...done!\n\n");


        if (argCommand == CommandMode.SEND_EXE)
        {
            TransferLogic.Command_SendEXE(argAddr, inFile, CalculateChecksum(inFile, true));
        }

        if (argCommand == CommandMode.SEND_BIN)
        {
            TransferLogic.Command_SendBin(argAddr, inFile, CalculateChecksum(inFile));
        }

        // Unirom 8 mode - requires a response after checking that
        // things will fit on the cart.
        if (argCommand == CommandMode.SEND_ROM)
        {
            TransferLogic.Command_SendROM(argAddr, inFile, CalculateChecksum(inFile));
        }


        if (argCommand == CommandMode.RESET)
        {
            TransferLogic.WriteChallenge(argCommand.challenge());
        }

        // Unirom 8.0.4 and up, enables kernel-resident SIO
        if (argCommand == CommandMode.DEBUG)
        {
            // if it returns true, we might enter /m (monitor) mode, etc
            if (
                !TransferLogic.ChallengeResponse(argCommand)
                )
            {
                return(false);
            }
        }


        if (argCommand == CommandMode.DUMP)
        {
            lastReadBytes = new byte[argSize];

            TransferLogic.Command_DumpBytes(argAddr, argSize, lastReadBytes);

            string fileName = "DUMP_" + argAddr.ToString("X8") + "_to_" + argSize.ToString("X8") + ".bin";

            if (System.IO.File.Exists(fileName))
            {
                string newFilename = fileName + GetSpan().TotalSeconds.ToString();

                Console.Write("\n\nWARNING: Filename " + fileName + " already exists! - Dumping to " + newFilename + " instead!\n\n");

                fileName = newFilename;
            }

            try{
                File.WriteAllBytes(fileName, lastReadBytes);
            } catch (Exception e) {
                Error("Couldn't write to the output file + " + fileName + " !\nThe error returned was: " + e, false);
                return(false);
            }
        }         // DUMP

        if (argCommand == CommandMode.PING)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.GDB)
        {
            GDB.Init();
        }

        if (argCommand == CommandMode.JUMP_JMP)
        {
            TransferLogic.Command_JumpAddr(argAddr);
        }

        if (argCommand == CommandMode.JUMP_CALL)
        {
            TransferLogic.Command_CallAddr(argAddr);
        }

        if (argCommand == CommandMode.HALT)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.CONT)
        {
            TransferLogic.ChallengeResponse(argCommand);
        }

        if (argCommand == CommandMode.REGS)
        {
            TransferLogic.Command_DumpRegs();
        }

        if (argCommand == CommandMode.SETREG)
        {
            TransferLogic.Command_SetReg(argRegister, argAddr);
        }

        if (argCommand == CommandMode.WATCH)
        {
            TransferLogic.Watch(argAddr, argSize);
            return(true);
        }         // WATCH

        if (monitorComms)
        {
            TransferLogic.DoMonitor();
        }
        else
        {
            Console.WriteLine("\n This is where we part ways!");
            activeSerial.Close();
        }

        return(true);
    }     // void Transfer