void NodeJSDebugger::SetBreakpoints()
{
    // Sanity
    if(!IsConnected()) return;
    const NodeJSBreakpoint::List_t& bps = m_bptManager.GetBreakpoints();
    std::for_each(bps.begin(), bps.end(), [&](const NodeJSBreakpoint& bp) { SetBreakpoint(bp); });
}
void
CMLineIndexTable::AdjustBreakpoints
	(
	const JIndex			lineIndex,
	const JPoint&			pt,
	const JXButtonStates&	buttonStates,
	const JXKeyModifiers&	modifiers
	)
{
	JIndex bpIndex;
	if (!GetFirstBreakpointOnLine(lineIndex, &bpIndex))
		{
		SetBreakpoint(lineIndex, JI2B(
			modifiers.GetState(JXMenu::AdjustNMShortcutModifier(kJXMetaKeyIndex)) &&
			modifiers.shift()));
		}
	else if (HasMultipleBreakpointsOnLine(bpIndex))
		{
		OpenLineMenu(lineIndex, pt, buttonStates, modifiers, kJTrue, bpIndex);
		}
	else if (modifiers.shift())
		{
		(itsBPList->NthElement(bpIndex))->ToggleEnabled();
		}
	else
		{
		itsLink->RemoveBreakpoint(*(itsBPList->NthElement(bpIndex)));
		}
}
void NodeJSDebugger::OnToggleBreakpoint(clDebugEvent& event)
{
    event.Skip();
    if(NodeJSWorkspace::Get()->IsOpen()) {
        event.Skip(false);
        IEditor* editor = clGetManager()->GetActiveEditor();
        if(editor && (editor->GetFileName().GetFullPath() == event.GetFileName())) {
            // Correct editor
            // add marker
            NodeJSBreakpoint bp = m_bptManager.GetBreakpoint(event.GetFileName(), event.GetInt());
            if(bp.IsOk()) {
                if(bp.IsApplied() && IsConnected()) {
                    // Tell NodeJS to delete this breakpoint
                    DeleteBreakpoint(bp);
                }
                m_bptManager.DeleteBreakpoint(event.GetFileName(), event.GetInt());
            } else {
                // We have no breakpoint on this file/line (yet)
                m_bptManager.AddBreakpoint(event.GetFileName(), event.GetInt());
                bp = m_bptManager.GetBreakpoint(event.GetFileName(), event.GetInt());
                if(IsConnected()) {
                    SetBreakpoint(bp);
                }
            }

            // Update the UI
            m_bptManager.SetBreakpoints(editor);
            clDebugEvent event(wxEVT_NODEJS_DEBUGGER_UPDATE_BREAKPOINTS_VIEW);
            EventNotifier::Get()->AddPendingEvent(event);
        }
    }
}
Example #4
0
VOID
EFIAPI
InsertBreakPoint (
  IN  EFI_SYSTEM_CONTEXT  SystemContext,
  IN  CHAR8              *PacketData
  )
{
  UINTN Type;
  UINTN Address;
  UINTN Length;
  UINTN ErrorCode;

  ErrorCode = ParseBreakpointPacket (PacketData, &Type, &Address, &Length);
  if (ErrorCode > 0) {
    SendError ((UINT8)ErrorCode);
    return;
  }

  switch (Type) {
    case 0:   //Software breakpoint
      break;

    default  :
      DEBUG((EFI_D_ERROR, "Insert breakpoint default: %x\n", Type));
      SendError (GDB_EINVALIDBRKPOINTTYPE);
      return;
  }

  SetBreakpoint (Address);

  SendSuccess ();
}
Example #5
0
void
CMLink::SetBreakpoint
	(
	const CMLocation&	loc,
	const JBoolean		temporary
	)
{
	SetBreakpoint(loc.GetFileName(), loc.GetLineNumber(), temporary);
}
Example #6
0
void
CMLink::SetBreakpoint
	(
	const CMBreakpoint& bp
	)
{
	SetBreakpoint(bp.GetFileName(), bp.GetLineNumber(),
				  JI2B(bp.GetAction() == CMBreakpoint::kRemoveBreakpoint));
}
Example #7
0
BOOL
CmdStep(
    LPSTR             CmdBuf,
    HANDLE            hProcess,
    HANDLE            hThread,
    PEXCEPTION_RECORD ExceptionRecord
    )
{
    PPROCESS_INFO ThisProcess = GetProcessInfo( hProcess );
    if (!ThisProcess) {
        printf( "could not get process information\n" );
        return FALSE;
    }

    PTHREAD_INFO ThisThread = GetThreadInfo( hProcess, hThread );
    if (!ThisThread) {
        printf( "could not get thread information\n" );
        return FALSE;
    }

    SuspendAllThreads( ThisProcess, ThisThread );

    ULONG Address = GetNextOffset(
        ThisProcess->hProcess,
        (ULONG)ExceptionRecord->ExceptionAddress,
        TRUE
        );

    if (Address == (ULONG)-1) {
#ifdef _M_IX86
        CurrContext.EFlags |= 0x100;
        SetRegContext( ThisThread->hThread, &CurrContext );
        PBREAKPOINT_INFO bp = GetAvailBreakpoint( ThisProcess );
        if (bp) {
            bp->Flags   |= BPF_TRACE;
            bp->Address  = (ULONG)ExceptionRecord->ExceptionAddress;
            bp->Handler  = TraceBpHandler;
        }
#else
        printf( "could not trace the instruction\n" );
#endif
    } else {
        PBREAKPOINT_INFO bp = SetBreakpoint(
            ThisProcess,
            Address,
            0,
            NULL,
            TraceBpHandler
            );
        if (!bp) {
            printf( "could not trace the instruction\n" );
            return FALSE;
        }
    }

    return TRUE;
}
void
XDLink::RunUntil
	(
	const JCharacter*	fileName,
	const JIndex		lineIndex
	)
{
	SetBreakpoint(fileName, lineIndex, kJTrue);
	Continue();
}
Example #9
0
 void HostTransferFunction::SetBreakpoint(double s, const Color& c)
 {
   SetBreakpoint(s, c, c.Alpha());
 }
Example #10
0
int ProcessRunStateMessages()
{
	if (g_DebugSocket.eGetState() != CHeDbgSocket::eSOCKSTATE_CONNECTED)
	{
		dprintf("Socket connection closed - quitting\n");
		PyObject_CallMethod(g_pHeDebugger, "set_quit", NULL);
		return -1;
	}
	
	SMsgHeader MsgHdr;
	EMessageType eType = g_DebugSocket.ReadMessageHdr(&MsgHdr);
	while (eType > eMSG_INVALID)
	{
		int MsgBytes = MsgHdr.GetMsgSize();	//strtol(MsgHdr.MsgSize, NULL, 10);
		
		static TCharVector RunMsgBuffer;
		RunMsgBuffer.resize(MsgBytes);

		int nMsgSize = 0;
		if (MsgBytes > 0)
		{
			memset (&(RunMsgBuffer[0]), 0, MsgBytes);
			nMsgSize = g_DebugSocket.ReadMessageBody(&(RunMsgBuffer[0]), &MsgHdr);	
		}
		
		switch (eType)
		{
		case eMSG_SETBREAKPOINT:
			assert(nMsgSize > 0);
			SetBreakpoint(&(RunMsgBuffer[0]));
			break;

		case eMSG_BREAKNOW:
			g_bBreakNow = true;
			break;
				
		case eMSG_RELOAD:
			assert(nMsgSize > 0);
			//ReloadFile(RunMsgBuffer);
			break;
		case eMSG_STOP:
			printf("Stopping Debugger\n");
			//throw "Stopping Debugger";
			//PyObject_CallMethod(g_pHeDebugger, "set_quit", NULL);

			break;

		case eMSG_EXIT:
			g_bContinueRun = false;
			printf("Stopping Debugger\n");
			//PyObject_CallMethod(g_pHeDebugger, "set_quit", NULL);
			//throw "Stopping Debugger";
			break;

		case eMSG_PING:
			g_DebugSocket.SendMessage(eMSG_PONG, "");
			break;

		case eMSG_SETOPTION:
			SetOption(&(RunMsgBuffer[0]));
			break;

		default:
			dprintf("ProcessRunStateMessages - Invalid Message: %d\n", eType);
	
		}
		
		eType = g_DebugSocket.ReadMessageHdr(&MsgHdr);
	}
	return 0;

} // ProcessRunStateMessages
Example #11
0
bool DebugFrontend::StartProcessAndRunToEntry(LPCSTR exeFileName, LPSTR commandLine, LPCSTR directory, PROCESS_INFORMATION& processInfo)
{

    STARTUPINFO startUpInfo = { 0 };
    startUpInfo.cb = sizeof(startUpInfo);

    ExeInfo info;
    if (!GetExeInfo(exeFileName, info) || info.entryPoint == 0)
    {
        MessageEvent("Error: The entry point for the application could not be located", MessageType_Error);
        return false;
    }

    if (!info.i386)
    {
        MessageEvent("Error: Debugging 64-bit applications is not supported", MessageType_Error);
        return false;
    }

    DWORD flags = DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS;

    if (!CreateProcess(NULL, commandLine, NULL, NULL, TRUE, flags, NULL, directory, &startUpInfo, &processInfo))
    {
        OutputError(GetLastError());
        return false;
    }

    // Running to the entry point currently doesn't work for managed applications, so
    // just start it up.

    if (!info.managed)
    {

        unsigned long entryPoint = info.entryPoint;

        BYTE breakPointData;
        bool done = false;
        
        while (!done)
        {

            DEBUG_EVENT debugEvent;
            WaitForDebugEvent(&debugEvent, INFINITE);

            DWORD continueStatus = DBG_EXCEPTION_NOT_HANDLED;

            if (debugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
            {
                if (debugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP ||
                    debugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
                {

                    CONTEXT context;
                    context.ContextFlags = CONTEXT_FULL;

                    GetThreadContext(processInfo.hThread, &context);

                    if (context.Eip == entryPoint + 1)
                    {

                        // Restore the original code bytes.
                        SetBreakpoint(processInfo.hProcess, (LPVOID)entryPoint, false, &breakPointData);
                        done = true;

                        // Backup the instruction pointer so that we execute the original instruction.
                        --context.Eip;
                        SetThreadContext(processInfo.hThread, &context);

                        // Suspend the thread before we continue the debug event so that the program
                        // doesn't continue to run.
                        SuspendThread(processInfo.hThread);

                    }

                    continueStatus = DBG_CONTINUE;

                }
            }
            else if (debugEvent.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT)
            {
                done = true;
            }
            else if (debugEvent.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
            {
            
                // Offset the entry point by the load address of the process.
                entryPoint += reinterpret_cast<size_t>(debugEvent.u.CreateProcessInfo.lpBaseOfImage);

                // Write a break point at the entry point of the application so that we
                // will stop when we reach that point.
                SetBreakpoint(processInfo.hProcess, reinterpret_cast<void*>(entryPoint), true, &breakPointData);

                CloseHandle(debugEvent.u.CreateProcessInfo.hFile);

            }
            else if (debugEvent.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT)
            {
                CloseHandle(debugEvent.u.LoadDll.hFile);
            }

            ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, continueStatus);
        
        }

    }

    DebugActiveProcessStop(processInfo.dwProcessId);
    return true;

}
void
CMLineIndexTable::HandleLineMenu
	(
	const JIndex index
	)
{
	// line

	JSize offset = 0;
	if (itsIsFullLineMenuFlag)
		{
		if (index == offset + kRunUntilCmd)
			{
			RunUntil(itsLineMenuLineIndex);
			return;
			}
		else if (index == offset + kSetExecPtCmd)
			{
			SetExecutionPoint(itsLineMenuLineIndex);
			return;
			}
		offset += kLineMenuItemCount;
		}

	// all breakpoints

	if (index == offset + kSetBreakpointCmd)
		{
		SetBreakpoint(itsLineMenuLineIndex, kJFalse);
		return;
		}
	else if (index == offset + kSetTempBreakpointCmd)
		{
		SetBreakpoint(itsLineMenuLineIndex, kJTrue);
		return;
		}
	else if (index == offset + kRemoveAllBreakpointsCmd)
		{
		RemoveAllBreakpointsOnLine(itsLineMenuLineIndex);
		return;
		}
	offset += kAllBreakpointsMenuItemCount;

	// individual breakpoints

	if (!itsLineMenuBPRange.IsNothing())
		{
		for (JIndex i=itsLineMenuBPRange.first; i<=itsLineMenuBPRange.last; i++)
			{
			CMBreakpoint* bp = itsBPList->NthElement(i);
			if (index == offset + kShowBreakpointInfoCmd)
				{
				(itsDirector->GetCommandDirector()->GetBreakpointsDir()->GetBreakpointTable())->Show(bp);
				return;
				}
			else if (index == offset + kRemoveBreakpointCmd)
				{
				itsLink->RemoveBreakpoint(*bp);
				return;
				}
			else if (index == offset + kSetConditionCmd)
				{
				(itsDirector->GetCommandDirector()->GetBreakpointsDir()->GetBreakpointTable())->EditCondition(bp);
				return;
				}
			else if (index == offset + kRemoveConditionCmd)
				{
				bp->RemoveCondition();
				return;
				}
			else if (index == offset + kToggleEnableCmd)
				{
				bp->ToggleEnabled();
				return;
				}
			else if (index == offset + kIgnoreNextNCmd)
				{
				(itsDirector->GetCommandDirector()->GetBreakpointsDir()->GetBreakpointTable())->EditIgnoreCount(bp);
				return;
				}

			offset += kBreakpointMenuItemCount;
			}
		}
}
Example #13
0
BOOL
CmdBreakPoint(
    LPSTR             CmdBuf,
    HANDLE            hProcess,
    HANDLE            hThread,
    PEXCEPTION_RECORD ExceptionRecord
    )
{
    CHAR BpCmd = tolower(CmdBuf[1]);
    ULONG Address = 0;
    PBREAKPOINT_INFO bp;
    PPROCESS_INFO ThisProcess;
    ULONG Flags;
    LPSTR p;
    LPSTR SymName;
    ULONG i;
    IMAGEHLP_MODULE mi;


    ThisProcess = GetProcessInfo( hProcess );
    if (!ThisProcess) {
        printf( "could not get process information\n" );
        return FALSE;
    }

    PTHREAD_INFO ThisThread = GetThreadInfo( hProcess, hThread );
    if (!ThisThread) {
        printf( "could not get thread information\n" );
        return FALSE;
    }

    SKIP_NONWHITE( CmdBuf );
    SKIP_WHITE( CmdBuf );
    p = CmdBuf;

    switch ( BpCmd ) {
        case 'p':
            Flags = 0;
            CmdBuf = GetAddress( CmdBuf, &Address );
            SymName = (LPSTR) MemAlloc( CmdBuf - p + 16 );
            if (!SymName) {
                printf( "could not allocate memory for bp command\n" );
                break;
            }
            strncpy( SymName, p, CmdBuf - p );
            if (!Address) {
                Flags = BPF_UNINSTANCIATED;
                printf( "breakpoint not instanciated\n" );
            }
            bp = SetBreakpoint(
                ThisProcess,
                Address,
                Flags,
                SymName,
                UserBpHandler
                );
            MemFree( SymName );
            if (!bp) {
                printf( "could not set breakpoint\n" );
            }
            ThisProcess->UserBpCount += 1;
            bp->Number = ThisProcess->UserBpCount;
            SKIP_WHITE( CmdBuf );
            if (CmdBuf[0]) {
                if (CmdBuf[0] == '/') {
                    switch (tolower(CmdBuf[1])) {
                        case 'c':
                            CmdBuf += 3;
                            if (CmdBuf[0] != '\"') {
                                printf( "invalid syntax\n" );
                                return FALSE;
                            }
                            CmdBuf += 1;
                            p = strchr( CmdBuf, '\"' );
                            if (!p) {
                                printf( "invalid syntax\n" );
                                return FALSE;
                            }
                            p[0] = 0;
                            bp->Command = _strdup( CmdBuf );
                            break;

                        default:
                            break;
                    }
                }
            }
            break;

        case 'l':
            for (i=0; i<MAX_BREAKPOINTS; i++) {
                if (ThisProcess->Breakpoints[i].Number) {
                    ULONG disp = 0;
                    if (ThisProcess->Breakpoints[i].Flags & BPF_WATCH) {
                        printf( "#%d %c%c\t          \tWatch\n",
                            ThisProcess->Breakpoints[i].Number,
                            ThisProcess->Breakpoints[i].Flags & BPF_UNINSTANCIATED ? 'U' : 'I',
                            ThisProcess->Breakpoints[i].Flags & BPF_DISABLED       ? 'D' : 'E'
                            );
                    } else if ((ThisProcess->Breakpoints[i].Address != 0) &&
                        (ThisProcess->Breakpoints[i].Address != 0xffffffff)) {
                        SymGetModuleInfo(
                            ThisProcess->hProcess,
                            ThisProcess->Breakpoints[i].Address,
                            &mi
                            );
                        if (SymGetSymFromAddr(
                            ThisProcess->hProcess,
                            ThisProcess->Breakpoints[i].Address,
                            &disp,
                            sym
                            )) {
                                printf( "#%d %c%c\t0x%08x\t%s!%s\n",
                                    ThisProcess->Breakpoints[i].Number,
                                    ThisProcess->Breakpoints[i].Flags & BPF_UNINSTANCIATED ? 'U' : 'I',
                                    ThisProcess->Breakpoints[i].Flags & BPF_DISABLED       ? 'D' : 'E',
                                    ThisProcess->Breakpoints[i].Address,
                                    mi.ModuleName,
                                    sym ? sym->Name : ""
                                    );
                        }
                    } else {
                        printf( "#%d %c%c\t          \t%s\n",
                            ThisProcess->Breakpoints[i].Number,
                            ThisProcess->Breakpoints[i].Flags & BPF_UNINSTANCIATED ? 'U' : 'I',
                            ThisProcess->Breakpoints[i].Flags & BPF_DISABLED       ? 'D' : 'E',
                            ThisProcess->Breakpoints[i].SymName
                            );
                    }
                }
            }
            break;

        case 'c':
            if (!CmdBuf[0]) {
                printf( "missing breakpoint number\n" );
                return FALSE;
            }
            if (CmdBuf[0] == '*') {
                for (i=0; i<MAX_BREAKPOINTS; i++) {
                    if (ThisProcess->Breakpoints[i].Number) {
                        ClearBreakpoint( ThisProcess, &ThisProcess->Breakpoints[i] );
                    }
                }
                return TRUE;
            }
            if (isdigit(CmdBuf[0])) {
                ULONG BpNum = atoi( CmdBuf );
                for (i=0; i<MAX_BREAKPOINTS; i++) {
                    if (ThisProcess->Breakpoints[i].Number == BpNum) {
                        ClearBreakpoint( ThisProcess, &ThisProcess->Breakpoints[i] );
                        return TRUE;
                    }
                }
            }
            printf( "invalid breakpoint number\n" );
            return FALSE;

        case 'd':
            break;

        case 'e':
            break;

        case 'a':
#if defined(_M_IX86)
            CmdBuf = GetAddress( CmdBuf, &Address );

            bp = GetAvailBreakpoint( ThisProcess );
            if (!bp) {
                printf( "could not set breakpoint\n" );
                return FALSE;
            }

            bp->Address = Address;
            bp->Handler = UserBpHandler;
            bp->Flags   = BPF_WATCH;

            ThisProcess->UserBpCount += 1;
            bp->Number = ThisProcess->UserBpCount;

            CurrContext.Dr0 = Address;
            CurrContext.Dr6 = 0x000d0002;
            SetRegContext( ThisThread->hThread, &CurrContext );
#else
            printf( "only available on x86\n" );
#endif
            break;

        default:
            break;
    }

    return TRUE;
}
Example #14
0
DWORD
UserBpHandler(
    PPROCESS_INFO       ThisProcess,
    PTHREAD_INFO        ThisThread,
    PEXCEPTION_RECORD   ExceptionRecord,
    PBREAKPOINT_INFO    BreakpointInfo
    )
{
    if (BreakpointInfo->Number) {
        printf( "Breakpoint #%d hit\n", BreakpointInfo->Number );
    } else {
        printf( "Hardcoded breakpoint hit\n" );
    }

    if (PrintRegistersFlag) PrintRegisters();
    PrintOneInstruction( ThisProcess->hProcess, (ULONG)ExceptionRecord->ExceptionAddress );

    ULONG ContinueStatus = ConsoleDebugger(
        ThisThread->hProcess,
        ThisThread->hThread,
        ExceptionRecord,
        FALSE,
        BreakpointInfo->Command
        );

    if (BreakpointInfo->Address && (!Stepped)) {
        //
        // the bp is still present so we must step off it
        //
        SuspendAllThreads( ThisProcess, ThisThread );
        ULONG Address = GetNextOffset(
            ThisProcess->hProcess,
            (ULONG)ExceptionRecord->ExceptionAddress,
            TRUE
            );
        if (Address != (ULONG)-1) {
            PBREAKPOINT_INFO bp = SetBreakpoint(
                ThisProcess,
                Address,
                0,
                NULL,
                UserBpStepHandler
                );
            if (bp) {
                bp->LastBp = BreakpointInfo;
            } else {
                printf( "could not set off of the breakpoint\n" );
            }
        } else {
#ifdef _M_IX86
            CurrContext.EFlags |= 0x100;
            SetRegContext( ThisThread->hThread, &CurrContext );
            PBREAKPOINT_INFO bp = GetAvailBreakpoint( ThisProcess );
            if (bp) {
                bp->Flags   |= BPF_TRACE;
                bp->Address  = (ULONG)ExceptionRecord->ExceptionAddress;
                bp->Handler  = TraceBpHandler;
                bp->LastBp   = BreakpointInfo;
            } else {
                printf( "could not step off of the breakpoint\n" );
            }
#else
            printf( "could not step off of the breakpoint\n" );
#endif
        }
    }

    return ContinueStatus;
}
Example #15
0
int DispatchCommand(int currentsocket, unsigned char command)
{
  int r;

  switch (command)
  {
    case CMD_GETVERSION:
    {
      PCeVersion v;
      int versionsize=strlen(versionstring);
      v=(PCeVersion)malloc(sizeof(CeVersion)+versionsize);
      v->stringsize=versionsize;
      v->version=1;

      memcpy((char *)v+sizeof(CeVersion), versionstring, versionsize);

      //version request
      sendall(currentsocket, v, sizeof(CeVersion)+versionsize, 0);

      free(v);

      break;
    }

    case CMD_GETARCHITECTURE:
    {
#ifdef __i386__
      unsigned char arch=0;
#endif
#ifdef __x86_64__
      unsigned char arch=1;
#endif
#ifdef __arm__
      unsigned char arch=2;
#endif
#ifdef __aarch64__
      unsigned char arch=3;
#endif
      sendall(currentsocket, &arch, sizeof(arch), 0);
      break;
    }

    case CMD_CLOSECONNECTION:
    {
      printf("Connection %d closed properly\n", currentsocket);
      fflush(stdout);
      close(currentsocket);

      return NULL;
    }

    case CMD_TERMINATESERVER:
    {
      printf("Command to terminate the server received\n");
      fflush(stdout);
      close(currentsocket);
      exit(0);
    }

    case CMD_STARTDEBUG:
    {
      HANDLE h;
      if (recvall(currentsocket, &h, sizeof(h), MSG_WAITALL)>0)
      {
        int r;
        printf("Calling StartDebug(%d)\n", h);
        r=StartDebug(h);
        sendall(currentsocket, &r, sizeof(r), 0);

        if (r)
        {
          isDebuggerThread=1;
          debugfd=GetDebugPort(h);
        }
      }
      break;
    }

    case CMD_WAITFORDEBUGEVENT:
    {
      struct
      {
        HANDLE pHandle;
        int timeout;
      } wfd;

      if (recvall(currentsocket, &wfd, sizeof(wfd), MSG_WAITALL)>0)
      {
        int r;
        DebugEvent event;
        memset(&event, 0, sizeof(event));

        r=WaitForDebugEvent(wfd.pHandle, &event, wfd.timeout);
        sendall(currentsocket, &r, sizeof(r), r?MSG_MORE:0);

        if (r)
        {
          if (event.debugevent==SIGTRAP)
          {
            printf("!!!SIGTRAP!!!\n");
            printf("event.address=%llx\n", event.address);
          }

          sendall(currentsocket, &event, sizeof(event),0);
        }
      }
      break;
    }

    case CMD_CONTINUEFROMDEBUGEVENT:
    {
      struct
      {
        HANDLE pHandle;
        int tid;
        int ignore;
      } cfd;

      if (recvall(currentsocket, &cfd, sizeof(cfd), MSG_WAITALL)>0)
      {
        int r;
        // Calling ContinueFromDebugEvent
        r=ContinueFromDebugEvent(cfd.pHandle, cfd.tid, cfd.ignore);
        // Returned from ContinueFromDebugEvent
        sendall(currentsocket, &r, sizeof(r), 0);
      }
      break;
    }

    case CMD_SETBREAKPOINT:
    {
      CeSetBreapointInput sb;

      printf("CMD_SETBREAKPOINT. sizeof(sb)=%d\n", sizeof(sb));

      if (recvall(currentsocket, &sb, sizeof(sb), MSG_WAITALL)>0)
      {
        int r;

        printf("Calling SetBreakpoint\n");
        r=SetBreakpoint(sb.hProcess, sb.tid, sb.debugreg, (void *)sb.Address, sb.bptype, sb.bpsize);
        printf("SetBreakpoint returned %d\n",r);
        sendall(currentsocket, &r, sizeof(r), 0);
      }
      break;
    }

    case CMD_REMOVEBREAKPOINT:
    {
      CeRemoveBreapointInput rb;

      if (recvall(currentsocket, &rb, sizeof(rb), MSG_WAITALL)>0)
      {
        int r;

        printf("Calling RemoveBreakpoint\n");
        r=RemoveBreakpoint(rb.hProcess, rb.tid, rb.debugreg, rb.wasWatchpoint);
        printf("RemoveBreakpoint returned: %d\n", r);
        sendall(currentsocket, &r, sizeof(r), 0);
      }
      break;
    }

    case CMD_GETTHREADCONTEXT:
    {
#pragma pack(1)
      struct
      {
        HANDLE hProcess;
        int tid;
        int type;
      } gtc;
#pragma pack()

      CONTEXT Context;
      int result;

      printf("CMD_GETTHREADCONTEXT:\n");

      recvall(currentsocket, &gtc, sizeof(gtc), MSG_WAITALL);

      printf("Going to call GetThreadContext(%d, %d, %p, %d)\n", gtc.hProcess, gtc.tid, &Context, gtc.type);
      memset(&Context, 0, sizeof(Context));

      result=GetThreadContext(gtc.hProcess, gtc.tid, &Context, gtc.type);

      printf("result=%d\n", result);

      if (result)
      {
        uint32_t structsize=sizeof(Context);
        sendall(currentsocket, &result, sizeof(result), MSG_MORE);
        sendall(currentsocket, &structsize, sizeof(structsize), MSG_MORE);
        sendall(currentsocket, &Context, structsize, 0); //and context
      }
      else
        sendall(currentsocket, &result, sizeof(result), 0);

      break;

    }

    case CMD_SUSPENDTHREAD:
    {
      CeSuspendThreadInput st;

      if (recvall(currentsocket, &st, sizeof(st), MSG_WAITALL)>0)
      {
        int r;

        printf("Calling SuspendThread\n");
        r=SuspendThread(st.hProcess, st.tid);
        printf("SuspendThread returned\n");
        sendall(currentsocket, &r, sizeof(r), 0);
      }
      break;
    }

    case CMD_RESUMETHREAD:
    {
      CeResumeThreadInput rt;

      if (recvall(currentsocket, &rt, sizeof(rt), MSG_WAITALL)>0)
      {
        int r;

        printf("Calling ResumeThread\n");
        r=ResumeThread(rt.hProcess, rt.tid);
        printf("ResumeThread returned\n");
        sendall(currentsocket, &r, sizeof(r), 0);
      }
      break;
    }

    case CMD_CLOSEHANDLE:
    {
      HANDLE h;

      if (recvall(currentsocket, &h, sizeof(h), MSG_WAITALL)>0)
      {
        CloseHandle(h);
        int r=1;
        sendall(currentsocket, &r, sizeof(r), 0); //stupid naggle

      }
      else
      {
        printf("Error during read for CMD_CLOSEHANDLE\n");
        close(currentsocket);
        fflush(stdout);
        return 0;
      }
      break;
    }

    case CMD_CREATETOOLHELP32SNAPSHOT:
    {
      CeCreateToolhelp32Snapshot params;
      HANDLE result;

      printf("CMD_CREATETOOLHELP32SNAPSHOT\n");

      if (recvall(currentsocket, &params, sizeof(CeCreateToolhelp32Snapshot), MSG_WAITALL) > 0)
      {
        printf("Calling CreateToolhelp32Snapshot\n");
        result=CreateToolhelp32Snapshot(params.dwFlags, params.th32ProcessID);
        printf("result of CreateToolhelp32Snapshot=%d\n", result);

        fflush(stdout);

        sendall(currentsocket, &result, sizeof(HANDLE), 0);

      }
      else
      {
        printf("Error during read for CMD_CREATETOOLHELP32SNAPSHOT\n");
        fflush(stdout);
        close(currentsocket);
        return 0;
      }

      break;
    }

    case CMD_MODULE32FIRST: //slightly obsolete now
    case CMD_MODULE32NEXT:
    {
      HANDLE toolhelpsnapshot;
      if (recvall(currentsocket, &toolhelpsnapshot, sizeof(toolhelpsnapshot), MSG_WAITALL) >0)
      {
        BOOL result;
        ModuleListEntry me;
        CeModuleEntry *r;
        int size;

        if (command==CMD_MODULE32FIRST)
          result=Module32First(toolhelpsnapshot, &me);
        else
          result=Module32Next(toolhelpsnapshot, &me);

        if (result)
        {
          size=sizeof(CeModuleEntry)+ strlen(me.moduleName);
          r=(PCeModuleEntry)malloc(size);
          r->modulebase=me.baseAddress;
          r->modulesize=me.moduleSize;
          r->modulenamesize=strlen(me.moduleName);

          // Sending %s size %x\n, me.moduleName, r->modulesize
          memcpy((char *)r+sizeof(CeModuleEntry), me.moduleName, r->modulenamesize);
        }
        else
        {
          size=sizeof(CeModuleEntry);
          r=(PCeModuleEntry)malloc(size);
          r->modulebase=0;
          r->modulesize=0;
          r->modulenamesize=0;
        }

        r->result=result;

        sendall(currentsocket, r, size, 0);

        free(r);
      }
      break;
    }

    case CMD_PROCESS32FIRST: //obsolete
    case CMD_PROCESS32NEXT:
    {
      HANDLE toolhelpsnapshot;
      if (recvall(currentsocket, &toolhelpsnapshot, sizeof(toolhelpsnapshot), MSG_WAITALL) >0)
      {
        ProcessListEntry pe;
        BOOL result;
        CeProcessEntry *r;
        int size;

        if (command==CMD_PROCESS32FIRST)
          result=Process32First(toolhelpsnapshot, &pe);
        else
          result=Process32Next(toolhelpsnapshot, &pe);

        //  printf("result=%d\n", result);

        if (result)
        {
          size=sizeof(CeProcessEntry)+ strlen(pe.ProcessName);
          r=(PCeProcessEntry)malloc(size);
          r->processnamesize=strlen(pe.ProcessName);
          r->pid=pe.PID;
          memcpy((char *)r+sizeof(CeProcessEntry), pe.ProcessName, r->processnamesize);
        }
        else
        {
          size=sizeof(CeProcessEntry);
          r=(PCeProcessEntry)malloc(size);
          r->processnamesize=0;
          r->pid=0;
        }

        r->result=result;

        sendall(currentsocket, r, size, 0);

        free(r);

      }
      break;
    }

    case CMD_READPROCESSMEMORY:
    {
      CeReadProcessMemoryInput c;

      r=recvall(currentsocket, &c, sizeof(c), MSG_WAITALL);
      if (r>0)
      {
        PCeReadProcessMemoryOutput o=NULL;
        o=(PCeReadProcessMemoryOutput)malloc(sizeof(CeReadProcessMemoryOutput)+c.size);

        o->read=ReadProcessMemory(c.handle, (void *)(uintptr_t)c.address, &o[1], c.size);

        if (c.compress)
        {
          //compress the output
#define COMPRESS_BLOCKSIZE (64*1024)
          int i;
          unsigned char *uncompressed=&o[1];
          uint32_t uncompressedSize=o->read;
          uint32_t compressedSize=0;
          int maxBlocks=1+(c.size / COMPRESS_BLOCKSIZE);

          unsigned char **compressedBlocks=malloc(maxBlocks*sizeof(unsigned char *) ); //send in blocks of 64kb and reallocate the pointerblock if there's not enough space
          int currentBlock=0;

          z_stream strm;
          strm.zalloc = Z_NULL;
          strm.zfree = Z_NULL;
          strm.opaque = Z_NULL;
          deflateInit(&strm, c.compress);

          compressedBlocks[currentBlock]=malloc(COMPRESS_BLOCKSIZE);
          strm.avail_out=COMPRESS_BLOCKSIZE;
          strm.next_out=compressedBlocks[currentBlock];

          strm.next_in=uncompressed;
          strm.avail_in=uncompressedSize;

          while (strm.avail_in)
          {
            r=deflate(&strm, Z_NO_FLUSH);
            if (r!=Z_OK)
            {
              if (r==Z_STREAM_END)
                break;
              else
              {
                printf("Error while compressing\n");
                break;
              }
            }

            if (strm.avail_out==0)
            {
              //new output block
              currentBlock++;
              if (currentBlock>=maxBlocks)
              {
                //list was too short, reallocate
                printf("Need to realloc the pointerlist (p1)\n");

                maxBlocks*=2;
                compressedBlocks=realloc(compressedBlocks, maxBlocks*sizeof(unsigned char*));
              }
              compressedBlocks[currentBlock]=malloc(COMPRESS_BLOCKSIZE);
              strm.avail_out=COMPRESS_BLOCKSIZE;
              strm.next_out=compressedBlocks[currentBlock];
            }
          }
          // finishing compressiong
          while (1)
          {

            r=deflate(&strm, Z_FINISH);

            if (r==Z_STREAM_END)
              break; //done

            if (r!=Z_OK)
            {
              printf("Failure while finishing compression:%d\n", r);
              break;
            }

            if (strm.avail_out==0)
            {
              //new output block
              currentBlock++;
              if (currentBlock>=maxBlocks)
              {
                //list was too short, reallocate
                printf("Need to realloc the pointerlist (p2)\n");
                maxBlocks*=2;
                compressedBlocks=realloc(compressedBlocks, maxBlocks*sizeof(unsigned char*));
              }
              compressedBlocks[currentBlock]=malloc(COMPRESS_BLOCKSIZE);
              strm.avail_out=COMPRESS_BLOCKSIZE;
              strm.next_out=compressedBlocks[currentBlock];
            }
          }
          deflateEnd(&strm);

          compressedSize=strm.total_out;
          // Sending compressed data
          sendall(currentsocket, &uncompressedSize, sizeof(uncompressedSize), MSG_MORE); //followed by the compressed size
          sendall(currentsocket, &compressedSize, sizeof(compressedSize), MSG_MORE); //the compressed data follows
          for (i=0; i<=currentBlock; i++)
          {
            if (i!=currentBlock)
              sendall(currentsocket, compressedBlocks[i], COMPRESS_BLOCKSIZE, MSG_MORE);
            else
              sendall(currentsocket, compressedBlocks[i], COMPRESS_BLOCKSIZE-strm.avail_out, 0); //last one, flush

            free(compressedBlocks[i]);
          }
          free(compressedBlocks);
        }
        else
          sendall(currentsocket, o, sizeof(CeReadProcessMemoryOutput)+o->read, 0);

        if (o)
          free(o);
      }
      break;
    }

    case CMD_WRITEPROCESSMEMORY:
    {
      CeWriteProcessMemoryInput c;

      printf("CMD_WRITEPROCESSMEMORY:\n");

      r=recvall(currentsocket, &c, sizeof(c), MSG_WAITALL);
      if (r>0)
      {
        CeWriteProcessMemoryOutput o;
        unsigned char *buf;

        printf("recv returned %d bytes\n", r);
        printf("c.size=%d\n", c.size);

        if (c.size)
        {
          buf=(unsigned char *)malloc(c.size);

          r=recvall(currentsocket, buf, c.size, MSG_WAITALL);
          if (r>0)
          {
            printf("received %d bytes for the buffer. Wanted %d\n", r, c.size);
            o.written=WriteProcessMemory(c.handle, (void *)(uintptr_t)c.address, buf, c.size);

            r=sendall(currentsocket, &o, sizeof(CeWriteProcessMemoryOutput), 0);
            printf("wpm: returned %d bytes to caller\n", r);

          }
          else
            printf("wpm recv error while reading the data\n");

          free(buf);
        }
        else
        {
          printf("wpm with a size of 0 bytes");
          o.written=0;
          r=sendall(currentsocket, &o, sizeof(CeWriteProcessMemoryOutput), 0);
          printf("wpm: returned %d bytes to caller\n", r);
        }
      }
      else
      {
        printf("RPM: recv failed\n");
      }
      break;
    }

    case CMD_VIRTUALQUERYEXFULL:
    {
      CeVirtualQueryExFullInput c;
      CeVirtualQueryExFullOutput o;

      r=recvall(currentsocket, &c, sizeof(c), MSG_WAITALL);
      if (r>0)
      {
        RegionInfo *rinfo=NULL;
        uint32_t count=0;
        if (VirtualQueryExFull(c.handle, c.flags, &rinfo, &count))
        {
          int i;

          sendall(currentsocket, &count, sizeof(count),0);

          for (i=0; i<count; i++)
            sendall(currentsocket, &rinfo[i], sizeof(RegionInfo),0);

          if (rinfo)
            free(rinfo);
        }
      }
      break;
    }
    case CMD_GETREGIONINFO:
    case CMD_VIRTUALQUERYEX:
    {
      CeVirtualQueryExInput c;
      r=recvall(currentsocket, &c, sizeof(c), MSG_WAITALL);
      if (r>0)
      {
        RegionInfo rinfo;
        CeVirtualQueryExOutput o;

        if (sizeof(uintptr_t)==4)
        {
          if (c.baseaddress>0xFFFFFFFF)
          {
            o.result=0;
            sendall(currentsocket, &o, sizeof(o), 0);
            break;
          }
        }

        char mapsline[200];

        if (command==CMD_VIRTUALQUERYEX)
          o.result=VirtualQueryEx(c.handle, (void *)(uintptr_t)c.baseaddress, &rinfo, NULL);
        else
        if (command==CMD_GETREGIONINFO)
          o.result=VirtualQueryEx(c.handle, (void *)(uintptr_t)c.baseaddress, &rinfo, mapsline);

        o.protection=rinfo.protection;
        o.baseaddress=rinfo.baseaddress;
        o.type=rinfo.type;
        o.size=rinfo.size;

        if (command==CMD_VIRTUALQUERYEX)
          sendall(currentsocket, &o, sizeof(o), 0);
        else
        if (command==CMD_GETREGIONINFO)
        {
          sendall(currentsocket, &o, sizeof(o), MSG_MORE);
          {
            uint8_t size=strlen(mapsline);
            sendall(currentsocket, &size, sizeof(size), MSG_MORE);
            sendall(currentsocket, mapsline, size, 0);
          }
        }
      }
      break;
    }
    case CMD_OPENPROCESS:
    {
      int pid=0;

      r=recvall(currentsocket, &pid, sizeof(int), MSG_WAITALL);
      if (r>0)
      {
        int processhandle;

        printf("OpenProcess(%d)\n", pid);
        processhandle=OpenProcess(pid);

        printf("processhandle=%d\n", processhandle);
        sendall(currentsocket, &processhandle, sizeof(int), 0);
      }
      else
      {
        printf("Error\n");
        fflush(stdout);
        close(currentsocket);
        return NULL;
      }
      break;
    }

    case CMD_GETSYMBOLLISTFROMFILE:
    {
      //get the list and send it to the client
      //zip it first
      uint32_t symbolpathsize;

      printf("CMD_GETSYMBOLLISTFROMFILE\n");

      if (recvall(currentsocket, &symbolpathsize, sizeof(symbolpathsize), MSG_WAITALL)>0)
      {
        char *symbolpath=(char *)malloc(symbolpathsize+1);
        symbolpath[symbolpathsize]='\0';

        if (recvall(currentsocket, symbolpath, symbolpathsize, MSG_WAITALL)>0)
        {
          unsigned char *output=NULL;

          printf("symbolpath=%s\n", symbolpath);

          if (memcmp("/dev/", symbolpath, 5)!=0) //don't even bother if it's a /dev/ file
            GetSymbolListFromFile(symbolpath, &output);

          if (output)
          {
            printf("output is not NULL (%p)\n", output);

            fflush(stdout);

            printf("Sending %d bytes\n", *(uint32_t *)&output[4]);
            sendall(currentsocket, output, *(uint32_t *)&output[4], 0); //the output buffer contains the size itself
            free(output);
          }
          else
          {
            printf("Sending 8 bytes (fail)\n");
            uint64_t fail=0;
            sendall(currentsocket, &fail, sizeof(fail), 0); //just write 0
          }
        }
        else
        {
          printf("Failure getting symbol path\n");
          close(currentsocket);
        }
        free(symbolpath);
      }
      break;
    }

    case CMD_LOADEXTENSION:
    {
      //Load the extension if it isn't loaded yet
      //LOADEXTENSION(handle)
      uint32_t handle;
      if (recvall(currentsocket, &handle, sizeof(handle),0)>0)
      {
        int result=loadCEServerExtension(handle);

        sendall(currentsocket, &result, sizeof(result),0);
      }

      break;
    }

    case CMD_ALLOC:
    {
      //ALLOC(processhandle, preferedbase, size)
      CeAllocInput c;
      printf("CESERVER: CMD_ALLOC\n");
      if (recvall(currentsocket, &c, sizeof(c),0)>0)
      {
        printf("c.hProcess=%d\n", c.hProcess);
        printf("c.preferedBase=%llx\n", c.preferedBase);
        printf("c.size=%d\n", c.size);

        uint64_t address=ext_alloc(c.hProcess, c.preferedBase, c.size);

        sendall(currentsocket, &address, sizeof(address),0);
      }

      break;
    }

    case CMD_FREE:
    {
      CeFreeInput c;
      printf("CESERVER: CMD_FREE\n");
      if (recvall(currentsocket, &c, sizeof(c),0)>0)
      {
        uint32_t r;
        r=ext_free(c.hProcess, c.address, c.size);

        sendall(currentsocket, &r, sizeof(r),0);
      }

      break;
    }

    case CMD_CREATETHREAD:
    {
      CeCreateThreadInput c;
      printf("CESERVER: CMD_CREATETHREAD\n");
      if (recvall(currentsocket, &c, sizeof(c),0)>0)
      {
        uint64_t th;
        HANDLE h;
        th=ext_createThread(c.hProcess, c.startaddress, c.startaddress);

        printf("returned from ext_createthread\n");

        if (th) //create a handle for this object
        {
          uint64_t *threadobject=(uint64_t *)malloc(sizeof(uint64_t));

          *threadobject=th;
          h=CreateHandleFromPointer(threadobject, htNativeThreadHandle);
        }
        else
          h=0;

        sendall(currentsocket, &h, sizeof(h),0);
      }
      break;
    }

    case CMD_LOADMODULE:
    {
      CeLoadModuleInput c;

      printf("CESERVER: CMD_LOADMODULE\n");
      if (recvall(currentsocket, &c, sizeof(c),0)>0)
      {
        char modulepath[c.modulepathlength+1];

        if (recvall(currentsocket, &modulepath, sizeof(c.modulepathlength),0)>0)
        {
          uint32_t result;
          modulepath[c.modulepathlength]=0;

          result=ext_loadModule(c.hProcess, modulepath);

          sendall(currentsocket, &result, sizeof(result),0);
        }
      }
      break;
    }

    case CMD_SPEEDHACK_SETSPEED:
    {
      CeSpeedhackSetSpeedInput c;
      printf("CESERVER: CMD_SPEEDHACK_SETSPEED\n");
      if (recvall(currentsocket, &c, sizeof(c),0)>0)
      {
        uint32_t r;
        r=ext_speedhack_setSpeed(c.hProcess, c.speed);

        sendall(currentsocket, &r, sizeof(r),0);
      }

      break;
    }

  }
}