X-Git-Url: https://git.proxmox.com/?p=mirror_edk2.git;a=blobdiff_plain;f=SourceLevelDebugPkg%2FLibrary%2FDebugAgent%2FDebugAgentCommon%2FDebugAgent.c;h=f156fe24db2d3578e2766d96cc147b84a01ef80e;hp=f4039f49952cc051e27d06f6849db5259783a460;hb=9e981317be20ab85bb68a670e79735f9685a3348;hpb=b422b62c01a490e7892864c04280d430a2566e3f diff --git a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c index f4039f4995..f156fe24db 100644 --- a/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c +++ b/SourceLevelDebugPkg/Library/DebugAgent/DebugAgentCommon/DebugAgent.c @@ -4,7 +4,7 @@ read/write debug packet to communication with HOST based on transfer protocol. - Copyright (c) 2010 - 2013, Intel Corporation. All rights reserved.
+ Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at @@ -18,11 +18,119 @@ #include "DebugAgent.h" #include "Ia32/DebugException.h" -CHAR8 mErrorMsgVersionAlert[] = "\rThe SourceLevelDebugPkg you are using requires a newer version of the Intel(R) UDK Debugger Tool.\r\n"; -CHAR8 mErrorMsgSendInitPacket[] = "\rSend INIT break packet and try to connect the HOST (Intel(R) UDK Debugger Tool v1.3) ...\r\n"; -CHAR8 mErrorMsgConnectOK[] = "HOST connection is successful!\r\n"; -CHAR8 mErrorMsgConnectFail[] = "HOST connection is failed!\r\n"; -CHAR8 mWarningMsgIngoreBreakpoint[] = "Ignore break point in SMM for SMI issued during DXE debugging!\r\n"; +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 mErrorMsgVersionAlert[] = "\rThe SourceLevelDebugPkg you are using requires a newer version of the Intel(R) UDK Debugger Tool.\r\n"; +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 mErrorMsgSendInitPacket[] = "\rSend INIT break packet and try to connect the HOST (Intel(R) UDK Debugger Tool v1.5) ...\r\n"; +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 mErrorMsgConnectOK[] = "HOST connection is successful!\r\n"; +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 mErrorMsgConnectFail[] = "HOST connection is failed!\r\n"; +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 mWarningMsgIngoreBreakpoint[] = "Ignore break point in SMM for SMI issued during DXE debugging!\r\n"; + +// +// Vector Handoff Info list used by Debug Agent for persist +// +GLOBAL_REMOVE_IF_UNREFERENCED EFI_VECTOR_HANDOFF_INFO mVectorHandoffInfoDebugAgent[] = { + { + DEBUG_EXCEPT_DIVIDE_ERROR, // Vector 0 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_DEBUG, // Vector 1 + EFI_VECTOR_HANDOFF_DO_NOT_HOOK, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_NMI, // Vector 2 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_BREAKPOINT, // Vector 3 + EFI_VECTOR_HANDOFF_DO_NOT_HOOK, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_OVERFLOW, // Vector 4 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_BOUND, // Vector 5 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_INVALID_OPCODE, // Vector 6 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_DOUBLE_FAULT, // Vector 8 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_INVALID_TSS, // Vector 10 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_SEG_NOT_PRESENT, // Vector 11 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_STACK_FAULT, // Vector 12 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_GP_FAULT, // Vector 13 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_PAGE_FAULT, // Vector 14 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_FP_ERROR, // Vector 16 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_ALIGNMENT_CHECK, // Vector 17 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_MACHINE_CHECK, // Vector 18 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_EXCEPT_SIMD, // Vector 19 + EFI_VECTOR_HANDOFF_HOOK_BEFORE, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_TIMER_VECTOR, // Vector 32 + EFI_VECTOR_HANDOFF_DO_NOT_HOOK, + EFI_DEBUG_AGENT_GUID + }, + { + DEBUG_MAILBOX_VECTOR, // Vector 33 + EFI_VECTOR_HANDOFF_DO_NOT_HOOK, + EFI_DEBUG_AGENT_GUID + }, + { + 0, + EFI_VECTOR_HANDOFF_LAST_ENTRY, + { 0 } + } +}; + +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mVectorHandoffInfoCount = sizeof (mVectorHandoffInfoDebugAgent) / sizeof (EFI_VECTOR_HANDOFF_INFO); /** Calculate CRC16 for target data. @@ -45,7 +153,7 @@ CalculateCrc16 ( UINTN BitIndex; for (Index = 0; Index < DataSize; Index++) { - Crc ^= Data[Index]; + Crc ^= (UINT16)Data[Index]; for (BitIndex = 0; BitIndex < 8; BitIndex++) { if ((Crc & 0x8000) != 0) { Crc <<= 1; @@ -66,7 +174,7 @@ CalculateCrc16 ( @retval FALSE IDT entries were not setup by Debug Agent. **/ -BOOLEAN +BOOLEAN IsDebugAgentInitialzed ( VOID ) @@ -83,63 +191,27 @@ IsDebugAgentInitialzed ( /** Find and report module image info to HOST. - + @param[in] AlignSize Image aligned size. - + **/ -VOID +VOID FindAndReportModuleImageInfo ( - IN UINTN AlignSize + IN UINTN AlignSize ) { UINTN Pe32Data; - EFI_IMAGE_DOS_HEADER *DosHdr; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; // // Find Image Base // - Pe32Data = ((UINTN)mErrorMsgVersionAlert) & ~(AlignSize - 1); - while (Pe32Data != 0) { - DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data; - if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { - // - // DOS image header is present, so read the PE header after the DOS image header. - // Check if address overflow firstly. - // - if ((MAX_ADDRESS - (UINTN)DosHdr->e_lfanew) > Pe32Data) { - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)(Pe32Data + (UINTN)(DosHdr->e_lfanew)); - if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { - // - // It's PE image. - // - break; - } - } - } else { - // - // DOS image header is not present, TE header is at the image base. - // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data; - if ((Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) && - ((Hdr.Te->Machine == IMAGE_FILE_MACHINE_I386) || Hdr.Te->Machine == IMAGE_FILE_MACHINE_X64)) { - // - // It's TE image, it TE header and Machine type match - // - break; - } - } - - // - // Not found the image base, check the previous aligned address - // - Pe32Data -= AlignSize; + Pe32Data = PeCoffSearchImageBase ((UINTN) mErrorMsgVersionAlert); + if (Pe32Data != 0) { + ImageContext.ImageAddress = Pe32Data; + ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageContext.ImageAddress); + PeCoffLoaderRelocateImageExtraAction (&ImageContext); } - - ImageContext.ImageAddress = Pe32Data; - ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageContext.ImageAddress); - PeCoffLoaderRelocateImageExtraAction (&ImageContext); } /** @@ -183,7 +255,7 @@ TriggerSoftInterrupt ( } /** - Caculate Mailbox checksum and update the checksum field. + Calculate Mailbox checksum and update the checksum field. @param[in] Mailbox Debug Agent Mailbox pointer. @@ -193,7 +265,7 @@ UpdateMailboxChecksum ( IN DEBUG_AGENT_MAILBOX *Mailbox ) { - Mailbox->CheckSum = CalculateCheckSum8 ((UINT8 *)Mailbox, sizeof (DEBUG_AGENT_MAILBOX) - 2); + Mailbox->CheckSum = CalculateCheckSum8 ((UINT8 *)Mailbox, sizeof (DEBUG_AGENT_MAILBOX) - 2); } /** @@ -204,16 +276,16 @@ UpdateMailboxChecksum ( @param[in] Mailbox Debug Agent Mailbox pointer. **/ -VOID +VOID VerifyMailboxChecksum ( IN DEBUG_AGENT_MAILBOX *Mailbox ) { UINT8 CheckSum; - + CheckSum = CalculateCheckSum8 ((UINT8 *) Mailbox, sizeof (DEBUG_AGENT_MAILBOX) - 2); // - // The checksum updating process may be disturbed by hardware SMI, we need to check CheckSum field + // The checksum updating process may be disturbed by hardware SMI, we need to check CheckSum field // and ToBeCheckSum field to validate the mail box. // if (CheckSum != Mailbox->CheckSum && CheckSum != Mailbox->ToBeCheckSum) { @@ -229,10 +301,10 @@ VerifyMailboxChecksum ( @param[in] Mailbox Debug Agent Mailbox pointer. @param[in] Index Mailbox content index. @param[in] Value Value to be set into Mailbox. - + **/ VOID -UpdateMailboxContent ( +UpdateMailboxContent ( IN DEBUG_AGENT_MAILBOX *Mailbox, IN UINTN Index, IN UINT64 Value @@ -241,7 +313,7 @@ UpdateMailboxContent ( AcquireMpSpinLock (&mDebugMpContext.MailboxSpinLock); switch (Index) { case DEBUG_MAILBOX_DEBUG_FLAG_INDEX: - Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->DebugFlag.Uint64, sizeof(UINT64)) + Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->DebugFlag.Uint64, sizeof(UINT64)) - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT64)); Mailbox->DebugFlag.Uint64 = Value; break; @@ -270,10 +342,92 @@ UpdateMailboxContent ( - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT8)); Mailbox->HostSequenceNo = (UINT8) Value; break; + case DEBUG_MAILBOX_DEBUG_TIMER_FREQUENCY: + Mailbox->ToBeCheckSum = Mailbox->CheckSum + CalculateSum8 ((UINT8 *)&Mailbox->DebugTimerFrequency, sizeof(UINT32)) + - CalculateSum8 ((UINT8 *)&Value, sizeof(UINT32)); + Mailbox->DebugTimerFrequency = (UINT32) Value; + break; } UpdateMailboxChecksum (Mailbox); ReleaseMpSpinLock (&mDebugMpContext.MailboxSpinLock); } + +/** + Read data from debug device and save the data in buffer. + + Reads NumberOfBytes data bytes from a debug device into the buffer + specified by Buffer. The number of bytes actually read is returned. + If the return value is less than NumberOfBytes, then the rest operation failed. + If NumberOfBytes is zero, then return 0. + + @param Handle Debug port handle. + @param Buffer Pointer to the data buffer to store the data read from the debug device. + @param NumberOfBytes Number of bytes which will be read. + @param Timeout Timeout value for reading from debug device. It unit is Microsecond. + + @retval 0 Read data failed, no data is to be read. + @retval >0 Actual number of bytes read from debug device. + +**/ +UINTN +DebugAgentReadBuffer ( + IN DEBUG_PORT_HANDLE Handle, + IN UINT8 *Buffer, + IN UINTN NumberOfBytes, + IN UINTN Timeout + ) +{ + UINTN Index; + UINT32 Begin; + UINT32 TimeoutTicker; + UINT32 TimerRound; + UINT32 TimerFrequency; + UINT32 TimerCycle; + + Begin = 0; + TimeoutTicker = 0; + TimerRound = 0; + TimerFrequency = GetMailboxPointer()->DebugTimerFrequency; + TimerCycle = GetApicTimerInitCount (); + + if (Timeout != 0) { + Begin = GetApicTimerCurrentCount (); + TimeoutTicker = (UINT32) DivU64x32 ( + MultU64x64 ( + TimerFrequency, + Timeout + ), + 1000000u + ); + TimerRound = (UINT32) DivU64x32Remainder (TimeoutTicker, TimerCycle / 2, &TimeoutTicker); + } + Index = 0; + while (Index < NumberOfBytes) { + if (DebugPortPollBuffer (Handle)) { + DebugPortReadBuffer (Handle, Buffer + Index, 1, 0); + Index ++; + continue; + } + if (Timeout != 0) { + if (TimerRound == 0) { + if (IsDebugTimerTimeout (TimerCycle, Begin, TimeoutTicker)) { + // + // If time out occurs. + // + return 0; + } + } else { + if (IsDebugTimerTimeout (TimerCycle, Begin, TimerCycle / 2)) { + TimerRound --; + Begin = GetApicTimerCurrentCount (); + } + } + } + } + + return Index; +} + /** Set debug flag in mailbox. @@ -281,10 +435,10 @@ UpdateMailboxContent ( @param[in] FlagValue Debug flag value. **/ -VOID +VOID SetDebugFlag ( IN UINT64 FlagMask, - IN UINT32 FlagValue + IN UINT32 FlagValue ) { DEBUG_AGENT_MAILBOX *Mailbox; @@ -300,7 +454,7 @@ SetDebugFlag ( Get debug flag in mailbox. @param[in] FlagMask Debug flag mask value. - + @return Debug flag value. **/ @@ -328,12 +482,12 @@ GetDebugFlag ( VOID SendDebugMsgPacket ( IN CHAR8 *Buffer, - IN UINTN Length + IN UINTN Length ) { DEBUG_PACKET_HEADER DebugHeader; DEBUG_PORT_HANDLE Handle; - + Handle = GetDebugPortHandle(); DebugHeader.StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL; @@ -358,7 +512,7 @@ SendDebugMsgPacket ( @param[in] ErrorLevel The error level of the debug message. @param[in] Format Format string for the debug message to print. - @param[in] ... Variable argument list whose contents are accessed + @param[in] ... Variable argument list whose contents are accessed based on the format string specified by Format. **/ @@ -393,15 +547,15 @@ DebugAgentMsgPrint ( /** Prints a debug message to the debug output device if the specified error level is enabled. - If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function - GetDebugPrintErrorLevel (), then print the message specified by Format and the + If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function + GetDebugPrintErrorLevel (), then print the message specified by Format and the associated variable argument list to the debug output device. If Format is NULL, then ASSERT(). @param[in] ErrorLevel The error level of the debug message. @param[in] IsSend Flag of debug message to declare that the data is being sent or being received. - @param[in] Data Variable argument list whose contents are accessed + @param[in] Data Variable argument list whose contents are accessed @param[in] Length based on the format string specified by Format. **/ @@ -411,7 +565,7 @@ DebugAgentDataMsgPrint ( IN UINT8 ErrorLevel, IN BOOLEAN IsSend, IN UINT8 *Data, - IN UINT8 Length + IN UINT8 Length ) { CHAR8 Buffer[DEBUG_DATA_MAXIMUM_REAL_DATA]; @@ -436,7 +590,7 @@ DebugAgentDataMsgPrint ( while (TRUE) { if (DestBuffer - Buffer > DEBUG_DATA_MAXIMUM_REAL_DATA - 6) { // - // If there was no enough space in buffer, send out the debug message, + // If there was no enough space in buffer, send out the debug message, // reserving 6 bytes is for the last data and end characters "]\n". // SendDebugMsgPacket (Buffer, DestBuffer - Buffer); @@ -464,6 +618,7 @@ DebugAgentDataMsgPrint ( @retval EFI_SUCCESS Read the symbol in BreakSymbol. @retval EFI_CRC_ERROR CRC check fail. @retval EFI_TIMEOUT Timeout occurs when reading debug packet. + @retval EFI_DEVICE_ERROR Receive the old or responsed packet. **/ EFI_STATUS @@ -473,10 +628,12 @@ ReadRemainingBreakPacket ( ) { UINT16 Crc; + DEBUG_AGENT_MAILBOX *Mailbox; + // // Has received start symbol, try to read the rest part // - if (DebugPortReadBuffer (Handle, &DebugHeader->Command, sizeof (DEBUG_PACKET_HEADER) - 1, READ_PACKET_TIMEOUT) == 0) { + if (DebugAgentReadBuffer (Handle, (UINT8 *)DebugHeader + OFFSET_OF (DEBUG_PACKET_HEADER, Command), sizeof (DEBUG_PACKET_HEADER) - OFFSET_OF (DEBUG_PACKET_HEADER, Command), READ_PACKET_TIMEOUT) == 0) { // // Timeout occur, exit // @@ -491,9 +648,21 @@ ReadRemainingBreakPacket ( DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *)DebugHeader, DebugHeader->Length); return EFI_CRC_ERROR; } + Mailbox = GetMailboxPointer(); + if (IS_REQUEST (DebugHeader)) { + if (DebugHeader->SequenceNo == (UINT8) (Mailbox->HostSequenceNo + 1)) { + // + // Only updagte HostSequenceNo for new command packet + // + UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, DebugHeader->SequenceNo); + return EFI_SUCCESS; + } + if (DebugHeader->SequenceNo == Mailbox->HostSequenceNo) { + return EFI_SUCCESS; + } + } - UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, DebugHeader->SequenceNo); - return EFI_SUCCESS; + return EFI_DEVICE_ERROR; } /** @@ -515,7 +684,7 @@ IsHostAttached ( Set HOST connect flag in Mailbox. @param[in] Attached Attach status. - + **/ VOID SetHostAttached ( @@ -530,14 +699,14 @@ SetHostAttached ( Set debug setting of Debug Agent in Mailbox. @param DebugSetting Pointer to Debug Setting defined by transfer protocol. - + @retval RETURN_SUCCESS The setting is set successfully. @retval RETURN_UNSUPPORTED The Key value is not supported. **/ RETURN_STATUS SetDebugSetting ( - IN DEBUG_DATA_SET_DEBUG_SETTING *DebugSetting + IN DEBUG_DATA_SET_DEBUG_SETTING *DebugSetting ) { RETURN_STATUS Status; @@ -578,7 +747,7 @@ CommandGo ( } /** - Exectue Stepping command. + Execute Stepping command. @param[in] CpuContext Pointer to saved CPU context. @@ -593,6 +762,39 @@ CommandStepping ( Eflags = (IA32_EFLAGS32 *) &CpuContext->Eflags; Eflags->Bits.TF = 1; Eflags->Bits.RF = 1; + // + // Save and clear EFLAGS.IF to avoid interrupt happen when executing Stepping + // + SetDebugFlag (DEBUG_AGENT_FLAG_INTERRUPT_FLAG, Eflags->Bits.IF); + Eflags->Bits.IF = 0; + // + // Set Stepping Flag + // + SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 1); +} + +/** + Do some cleanup after Stepping command done. + + @param[in] CpuContext Pointer to saved CPU context. + +**/ +VOID +CommandSteppingCleanup ( + IN DEBUG_CPU_CONTEXT *CpuContext + ) +{ + IA32_EFLAGS32 *Eflags; + + Eflags = (IA32_EFLAGS32 *) &CpuContext->Eflags; + // + // Restore EFLAGS.IF + // + Eflags->Bits.IF = GetDebugFlag (DEBUG_AGENT_FLAG_INTERRUPT_FLAG); + // + // Clear Stepping flag + // + SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 0); } /** @@ -623,11 +825,11 @@ SetDebugRegister ( // // Enable Gx, Lx // - Dr7Value |= 0x3 << (RegisterIndex * 2); + Dr7Value |= (UINTN) (0x3 << (RegisterIndex * 2)); // // Set RWx and Lenx // - Dr7Value &= ~(0xf << (16 + RegisterIndex * 4)); + Dr7Value &= (UINTN) (~(0xf << (16 + RegisterIndex * 4))); Dr7Value |= (UINTN) ((SetHwBreakpoint->Type.Length << 2) | SetHwBreakpoint->Type.Access) << (16 + RegisterIndex * 4); // // Enable GE, LE @@ -652,19 +854,19 @@ ClearDebugRegister ( { if ((ClearHwBreakpoint->IndexMask & BIT0) != 0) { CpuContext->Dr0 = 0; - CpuContext->Dr7 &= ~(0x3 << 0); + CpuContext->Dr7 &= (UINTN)(~(0x3 << 0)); } if ((ClearHwBreakpoint->IndexMask & BIT1) != 0) { CpuContext->Dr1 = 0; - CpuContext->Dr7 &= ~(0x3 << 2); + CpuContext->Dr7 &= (UINTN)(~(0x3 << 2)); } if ((ClearHwBreakpoint->IndexMask & BIT2) != 0) { CpuContext->Dr2 = 0; - CpuContext->Dr7 &= ~(0x3 << 4); + CpuContext->Dr7 &= (UINTN)(~(0x3 << 4)); } if ((ClearHwBreakpoint->IndexMask & BIT3) != 0) { CpuContext->Dr3 = 0; - CpuContext->Dr7 &= ~(0x3 << 6); + CpuContext->Dr7 &= (UINTN)(~(0x3 << 6)); } } @@ -831,6 +1033,51 @@ SendAckPacket ( UpdateMailboxContent (Mailbox, DEBUG_MAILBOX_LAST_ACK, AckCommand); } +/** + Decompress the Data in place. + + @param[in, out] Data The compressed data buffer. + The buffer is assumed large enough to hold the uncompressed data. + @param[in] Length The length of the compressed data buffer. + + @return The length of the uncompressed data buffer. +**/ +UINT8 +DecompressDataInPlace ( + IN OUT UINT8 *Data, + IN UINTN Length + ) +{ + UINTN Index; + UINT16 LastChar; + UINTN LastCharCount; + UINT8 CurrentChar; + + LastChar = (UINT16) -1; + LastCharCount = 0; + for (Index = 0; Index < Length; Index++) { + CurrentChar = Data[Index]; + if (LastCharCount == 2) { + LastCharCount = 0; + CopyMem (&Data[Index + CurrentChar], &Data[Index + 1], Length - Index - 1); + SetMem (&Data[Index], CurrentChar, (UINT8) LastChar); + LastChar = (UINT16) -1; + Index += CurrentChar - 1; + Length += CurrentChar - 1; + } else { + if (LastChar != CurrentChar) { + LastCharCount = 0; + } + LastCharCount++; + LastChar = CurrentChar; + } + } + + ASSERT (Length <= DEBUG_DATA_MAXIMUM_REAL_DATA); + + return (UINT8) Length; +} + /** Receive valid packet from HOST. @@ -870,19 +1117,19 @@ ReceivePacket ( } else { TimeoutForStartSymbol = Timeout; } - + DebugHeader = (DEBUG_PACKET_HEADER *) InputPacket; while (TRUE) { // // Find the valid start symbol // - Received = DebugPortReadBuffer (Handle, &DebugHeader->StartSymbol, sizeof (DebugHeader->StartSymbol), TimeoutForStartSymbol); + Received = DebugAgentReadBuffer (Handle, &DebugHeader->StartSymbol, sizeof (DebugHeader->StartSymbol), TimeoutForStartSymbol); if (Received < sizeof (DebugHeader->StartSymbol)) { - DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "DebugPortReadBuffer(StartSymbol) timeout\n"); + DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "DebugAgentReadBuffer(StartSymbol) timeout\n"); return RETURN_TIMEOUT; } - if (DebugHeader->StartSymbol != DEBUG_STARTING_SYMBOL_NORMAL) { + if ((DebugHeader->StartSymbol != DEBUG_STARTING_SYMBOL_NORMAL) && (DebugHeader->StartSymbol != DEBUG_STARTING_SYMBOL_COMPRESS)) { DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "Invalid start symbol received [%02x]\n", DebugHeader->StartSymbol); continue; } @@ -890,14 +1137,14 @@ ReceivePacket ( // // Read Package header till field Length // - Received = DebugPortReadBuffer ( + Received = DebugAgentReadBuffer ( Handle, - &DebugHeader->Command, + (UINT8 *) DebugHeader + OFFSET_OF (DEBUG_PACKET_HEADER, Command), OFFSET_OF (DEBUG_PACKET_HEADER, Length) + sizeof (DebugHeader->Length) - sizeof (DebugHeader->StartSymbol), Timeout ); if (Received == 0) { - DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugPortReadBuffer(Command) timeout\n"); + DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugAgentReadBuffer(Command) timeout\n"); return RETURN_TIMEOUT; } if (DebugHeader->Length < sizeof (DEBUG_PACKET_HEADER)) { @@ -916,9 +1163,9 @@ ReceivePacket ( // // Read the payload data include the CRC field // - Received = DebugPortReadBuffer (Handle, &DebugHeader->SequenceNo, (UINT8) (DebugHeader->Length - OFFSET_OF (DEBUG_PACKET_HEADER, SequenceNo)), Timeout); + Received = DebugAgentReadBuffer (Handle, &DebugHeader->SequenceNo, (UINT8) (DebugHeader->Length - OFFSET_OF (DEBUG_PACKET_HEADER, SequenceNo)), Timeout); if (Received == 0) { - DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugPortReadBuffer(SequenceNo) timeout\n"); + DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "DebugAgentReadBuffer(SequenceNo) timeout\n"); return RETURN_TIMEOUT; } // @@ -936,6 +1183,12 @@ ReceivePacket ( DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, FALSE, (UINT8 *) DebugHeader, DebugHeader->Length); + if (DebugHeader->StartSymbol == DEBUG_STARTING_SYMBOL_COMPRESS) { + DebugHeader->StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL; + DebugHeader->Length = DecompressDataInPlace ( + (UINT8 *) (DebugHeader + 1), DebugHeader->Length - sizeof (DEBUG_PACKET_HEADER) + ) + sizeof (DEBUG_PACKET_HEADER); + } return RETURN_SUCCESS; } @@ -1044,8 +1297,12 @@ GetBreakCause ( if ((CpuContext->Dr6 & BIT14) != 0) { Cause = DEBUG_DATA_BREAK_CAUSE_STEPPING; // - // If it's single step, no need to check DR0, to ensure single step work in PeCoffExtraActionLib - // (right after triggering a breakpoint to report image load/unload). + // DR6.BIT14 Indicates (when set) that the debug exception was + // triggered by the single step execution mode. + // The single-step mode is the highest priority debug exception. + // This is single step, no need to check DR0, to ensure single step + // work in PeCoffExtraActionLib (right after triggering a breakpoint + // to report image load/unload). // return Cause; @@ -1065,13 +1322,13 @@ GetBreakCause ( if (CpuContext->Dr3 == IO_PORT_BREAKPOINT_ADDRESS) { - Cause = (UINT8) ((CpuContext->Dr0 == IMAGE_LOAD_SIGNATURE) ? + Cause = (UINT8) ((CpuContext->Dr0 == IMAGE_LOAD_SIGNATURE) ? DEBUG_DATA_BREAK_CAUSE_IMAGE_LOAD : DEBUG_DATA_BREAK_CAUSE_IMAGE_UNLOAD); } break; case SOFT_INTERRUPT_SIGNATURE: - + if (CpuContext->Dr1 == MEMORY_READY_SIGNATURE) { Cause = DEBUG_DATA_BREAK_CAUSE_MEMORY_READY; CpuContext->Dr0 = 0; @@ -1110,88 +1367,282 @@ GetBreakCause ( } /** - Send packet with response data to HOST. + Copy memory from source to destination with specified width. + + @param[out] Dest A pointer to the destination buffer of the memory copy. + @param[in] Src A pointer to the source buffer of the memory copy. + @param[in] Count The number of data with specified width to copy from source to destination. + @param[in] Width Data width in byte. + +**/ +VOID +CopyMemByWidth ( + OUT UINT8 *Dest, + IN UINT8 *Src, + IN UINT16 Count, + IN UINT8 Width + ) +{ + UINT8 *Destination; + UINT8 *Source; + INT8 Step; + + if (Src > Dest) { + Destination = Dest; + Source = Src; + Step = Width; + } else { + // + // Copy memory from tail to avoid memory overlap + // + Destination = Dest + (Count - 1) * Width; + Source = Src + (Count - 1) * Width; + Step = -Width; + } + + while (Count-- != 0) { + switch (Width) { + case 1: + *(UINT8 *) Destination = MmioRead8 ((UINTN) Source); + break; + case 2: + *(UINT16 *) Destination = MmioRead16 ((UINTN) Source); + break; + case 4: + *(UINT32 *) Destination = MmioRead32 ((UINTN) Source); + break; + case 8: + *(UINT64 *) Destination = MmioRead64 ((UINTN) Source); + break; + default: + ASSERT (FALSE); + } + Source += Step; + Destination += Step; + } +} + +/** + Compress the data buffer but do not modify the original buffer. + + The compressed data is directly send to the debug channel. + Compressing in place doesn't work because the data may become larger + during compressing phase. ("3 3 ..." --> "3 3 0 ...") + The routine is expected to be called three times: + 1. Compute the length of the compressed data buffer; + 2. Compute the CRC of the compressed data buffer; + 3. Compress the data and send to the debug channel. + + @param[in] Handle The debug channel handle to send the compressed data buffer. + @param[in] Data The data buffer. + @param[in] Length The length of the data buffer. + @param[in] Send TRUE to send the compressed data buffer. + @param[out] CompressedLength Return the length of the compressed data buffer. + It may be larger than the Length in some cases. + @param[out] CompressedCrc Return the CRC of the compressed data buffer. +**/ +VOID +CompressData ( + IN DEBUG_PORT_HANDLE Handle, + IN UINT8 *Data, + IN UINT8 Length, + IN BOOLEAN Send, + OUT UINTN *CompressedLength, OPTIONAL + OUT UINT16 *CompressedCrc OPTIONAL + ) +{ + UINTN Index; + UINT8 LastChar; + UINT8 LastCharCount; + UINT8 CurrentChar; + UINTN CompressedIndex; + + ASSERT (Length > 0); + LastChar = Data[0] + 1; // Just ensure it's different from the first byte. + LastCharCount = 0; + + for (Index = 0, CompressedIndex = 0; Index <= Length; Index++) { + if (Index < Length) { + CurrentChar = Data[Index]; + } else { + CurrentChar = (UINT8) LastChar + 1; // just ensure it's different from LastChar + } + if (LastChar != CurrentChar) { + if (LastCharCount == 1) { + CompressedIndex++; + if (CompressedCrc != NULL) { + *CompressedCrc = CalculateCrc16 (&LastChar, 1, *CompressedCrc); + } + if (Send) { + DebugPortWriteBuffer (Handle, &LastChar, 1); + } + + } else if (LastCharCount >= 2) { + CompressedIndex += 3; + LastCharCount -= 2; + if (CompressedCrc != NULL) { + *CompressedCrc = CalculateCrc16 (&LastChar, 1, *CompressedCrc); + *CompressedCrc = CalculateCrc16 (&LastChar, 1, *CompressedCrc); + *CompressedCrc = CalculateCrc16 (&LastCharCount, 1, *CompressedCrc); + } + if (Send) { + DebugPortWriteBuffer (Handle, &LastChar, 1); + DebugPortWriteBuffer (Handle, &LastChar, 1); + DebugPortWriteBuffer (Handle, &LastCharCount, 1); + } + } + LastCharCount = 0; + } + LastCharCount++; + LastChar = CurrentChar; + } + + if (CompressedLength != NULL) { + *CompressedLength = CompressedIndex; + } +} + +/** + Read memory with speicifed width and send packet with response data to HOST. @param[in] Data Pointer to response data buffer. - @param[in] DataSize Size of response data in byte. + @param[in] Count The number of data with specified Width. + @param[in] Width Data width in byte. + @param[in] DebugHeader Pointer to a buffer for creating response packet and receiving ACK packet, + to minimize the stack usage. @retval RETURN_SUCCESS Response data was sent successfully. **/ RETURN_STATUS -SendDataResponsePacket ( - IN UINT8 *Data, - IN UINT16 DataSize +ReadMemoryAndSendResponsePacket ( + IN UINT8 *Data, + IN UINT16 Count, + IN UINT8 Width, + IN DEBUG_PACKET_HEADER *DebugHeader ) { RETURN_STATUS Status; - DEBUG_PACKET_HEADER *DebugHeader; BOOLEAN LastPacket; - DEBUG_PACKET_HEADER *AckDebugHeader; - UINT8 DebugPacket[DEBUG_DATA_UPPER_LIMIT]; - UINT8 InputPacketBuffer[DEBUG_DATA_UPPER_LIMIT]; DEBUG_PORT_HANDLE Handle; UINT8 SequenceNo; + UINTN RemainingDataSize; + UINT8 CurrentDataSize; + UINTN CompressedDataSize; Handle = GetDebugPortHandle(); - DebugHeader = (DEBUG_PACKET_HEADER *) &DebugPacket; - DebugHeader->StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL; - + RemainingDataSize = Count * Width; while (TRUE) { SequenceNo = GetMailboxPointer()->HostSequenceNo; - if (DataSize <= DEBUG_DATA_MAXIMUM_REAL_DATA) { + if (RemainingDataSize <= DEBUG_DATA_MAXIMUM_REAL_DATA) { + // + // If the remaining data is less one real packet size, this is the last data packet + // + CurrentDataSize = (UINT8) RemainingDataSize; LastPacket = TRUE; - DebugHeader->Command = DEBUG_COMMAND_OK; - DebugHeader->Length = (UINT8) (DataSize + sizeof (DEBUG_PACKET_HEADER)); - DebugHeader->SequenceNo = SequenceNo; - DebugHeader->Crc = 0; - CopyMem (DebugHeader + 1, Data, DataSize); - + DebugHeader->Command = DEBUG_COMMAND_OK; } else { + // + // Data is too larger to be sent in one packet, calculate the actual data size could + // be sent in one Maximum data packet + // + CurrentDataSize = (DEBUG_DATA_MAXIMUM_REAL_DATA / Width) * Width; LastPacket = FALSE; - DebugHeader->Command = DEBUG_COMMAND_IN_PROGRESS; - DebugHeader->Length = DEBUG_DATA_MAXIMUM_REAL_DATA + sizeof (DEBUG_PACKET_HEADER); - DebugHeader->SequenceNo = SequenceNo; - DebugHeader->Crc = 0; - CopyMem (DebugHeader + 1, Data, DEBUG_DATA_MAXIMUM_REAL_DATA); + DebugHeader->Command = DEBUG_COMMAND_IN_PROGRESS; } + // + // Construct the rest Debug header + // + DebugHeader->StartSymbol = DEBUG_STARTING_SYMBOL_NORMAL; + DebugHeader->Length = CurrentDataSize + sizeof (DEBUG_PACKET_HEADER); + DebugHeader->SequenceNo = SequenceNo; + DebugHeader->Crc = 0; + CopyMemByWidth ((UINT8 *) (DebugHeader + 1), Data, CurrentDataSize / Width, Width); // - // Calculate and fill the checksum + // Compression/decompression support was added since revision 0.4. + // Revision 0.3 shouldn't compress the packet. // - DebugHeader->Crc = CalculateCrc16 ((UINT8 *) DebugHeader, DebugHeader->Length, 0); + if (DEBUG_AGENT_REVISION >= DEBUG_AGENT_REVISION_04) { + // + // Get the compressed data size without modifying the packet. + // + CompressData ( + Handle, + (UINT8 *) (DebugHeader + 1), + CurrentDataSize, + FALSE, + &CompressedDataSize, + NULL + ); + } else { + CompressedDataSize = CurrentDataSize; + } + if (CompressedDataSize < CurrentDataSize) { + DebugHeader->Length = (UINT8) CompressedDataSize + sizeof (DEBUG_PACKET_HEADER); + DebugHeader->StartSymbol = DEBUG_STARTING_SYMBOL_COMPRESS; + // + // Compute the CRC of the packet head without modifying the packet. + // + DebugHeader->Crc = CalculateCrc16 ((UINT8 *) DebugHeader, sizeof (DEBUG_PACKET_HEADER), 0); + CompressData ( + Handle, + (UINT8 *) (DebugHeader + 1), + CurrentDataSize, + FALSE, + NULL, + &DebugHeader->Crc + ); + // + // Send out the packet head. + // + DebugPortWriteBuffer (Handle, (UINT8 *) DebugHeader, sizeof (DEBUG_PACKET_HEADER)); + // + // Compress and send out the packet data. + // + CompressData ( + Handle, + (UINT8 *) (DebugHeader + 1), + CurrentDataSize, + TRUE, + NULL, + NULL + ); + } else { + + // + // Calculate and fill the checksum, DebugHeader->Crc should be 0 before invoking CalculateCrc16 () + // + DebugHeader->Crc = CalculateCrc16 ((UINT8 *) DebugHeader, DebugHeader->Length, 0); + + DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, TRUE, (UINT8 *) DebugHeader, DebugHeader->Length); - DebugAgentDataMsgPrint (DEBUG_AGENT_VERBOSE, TRUE, (UINT8 *) DebugHeader, DebugHeader->Length); - - DebugPortWriteBuffer (Handle, (UINT8 *) DebugHeader, DebugHeader->Length); + DebugPortWriteBuffer (Handle, (UINT8 *) DebugHeader, DebugHeader->Length); + } while (TRUE) { - Status = ReceivePacket (InputPacketBuffer, NULL, NULL, READ_PACKET_TIMEOUT, FALSE); + Status = ReceivePacket ((UINT8 *) DebugHeader, NULL, NULL, READ_PACKET_TIMEOUT, FALSE); if (Status == RETURN_TIMEOUT) { DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Timeout in SendDataResponsePacket()\n"); break; } - AckDebugHeader = (DEBUG_PACKET_HEADER *) InputPacketBuffer; - SequenceNo = AckDebugHeader->SequenceNo; - if (AckDebugHeader->Command == DEBUG_COMMAND_OK && - SequenceNo == DebugHeader->SequenceNo && - LastPacket) { + if ((DebugHeader->Command == DEBUG_COMMAND_OK) && (DebugHeader->SequenceNo == SequenceNo) && LastPacket) { // // If this is the last packet, return RETURN_SUCCESS. // return RETURN_SUCCESS; } - if ((SequenceNo == (UINT8) (DebugHeader->SequenceNo + 1)) && (AckDebugHeader->Command == DEBUG_COMMAND_CONTINUE)) { + if ((DebugHeader->Command == DEBUG_COMMAND_CONTINUE) && (DebugHeader->SequenceNo == (UINT8) (SequenceNo + 1))) { // - // Send the rest packet + // Calculate the rest data size // - Data += DEBUG_DATA_MAXIMUM_REAL_DATA; - DataSize -= DEBUG_DATA_MAXIMUM_REAL_DATA; - UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, (UINT8) SequenceNo); + Data += CurrentDataSize; + RemainingDataSize -= CurrentDataSize; + UpdateMailboxContent (GetMailboxPointer(), DEBUG_MAILBOX_HOST_SEQUENCE_NO_INDEX, DebugHeader->SequenceNo); break; } - if (SequenceNo >= DebugHeader->SequenceNo) { + if (DebugHeader->SequenceNo >= SequenceNo) { DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Received one old or new command(SequenceNo is %x, last SequenceNo is %x)\n", SequenceNo, DebugHeader->SequenceNo); break; } @@ -1200,37 +1651,34 @@ SendDataResponsePacket ( } /** - Send break cause packet to HOST. + Send packet with response data to HOST. - @param[in] Vector Vector value of exception or interrutp. - @param[in] CpuContext Pointer to save CPU context. + @param[in] Data Pointer to response data buffer. + @param[in] DataSize Size of response data in byte. + @param[in, out] DebugHeader Pointer to a buffer for creating response packet and receiving ACK packet, + to minimize the stack usage. @retval RETURN_SUCCESS Response data was sent successfully. - @retval RETURN_DEVICE_ERROR Cannot receive DEBUG_COMMAND_OK from HOST. **/ RETURN_STATUS -SendBreakCausePacket ( - IN UINTN Vector, - IN DEBUG_CPU_CONTEXT *CpuContext +SendDataResponsePacket ( + IN UINT8 *Data, + IN UINT16 DataSize, + IN OUT DEBUG_PACKET_HEADER *DebugHeader ) { - DEBUG_DATA_RESPONSE_BREAK_CAUSE DebugDataBreakCause; - - DebugDataBreakCause.StopAddress = CpuContext->Eip; - DebugDataBreakCause.Cause = GetBreakCause (Vector, CpuContext); - - return SendDataResponsePacket ((UINT8 *) &DebugDataBreakCause, (UINT16) sizeof (DEBUG_DATA_RESPONSE_BREAK_CAUSE)); + return ReadMemoryAndSendResponsePacket (Data, DataSize, 1, DebugHeader); } /** Try to attach the HOST. - + Send init break packet to HOST: - If no acknowlege received in specified Timeout, return RETURN_TIMEOUT. - If received acknowlege, check the revision of HOST. - Set Attach Flag if attach successfully. - + If no acknowlege received in specified Timeout, return RETURN_TIMEOUT. + If received acknowlege, check the revision of HOST. + Set Attach Flag if attach successfully. + @param[in] BreakCause Break cause of this break event. @param[in] Timeout Time out value to wait for acknowlege from HOST. The unit is microsecond. @@ -1251,7 +1699,7 @@ AttachHost ( IncompatibilityFlag = FALSE; Handle = GetDebugPortHandle(); - + // // Send init break and wait ack in Timeout // @@ -1269,7 +1717,7 @@ AttachHost ( DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgVersionAlert, AsciiStrLen (mErrorMsgVersionAlert)); CpuDeadLoop (); } - + if (RETURN_ERROR (Status)) { DebugPortWriteBuffer (Handle, (UINT8 *) mErrorMsgConnectFail, AsciiStrLen (mErrorMsgConnectFail)); } else { @@ -1283,8 +1731,8 @@ AttachHost ( } /** - Send Break point packet to HOST. - + Send Break point packet to HOST. + Only the first breaking processor could sent BREAK_POINT packet. @param[in] BreakCause Break cause of this break event. @@ -1292,7 +1740,7 @@ AttachHost ( @param[out] BreakReceived If BreakReceived is not NULL, TRUE is retured if break-in symbol received. FALSE is retured if break-in symbol not received. - + **/ VOID SendBreakPacketToHost ( @@ -1303,9 +1751,9 @@ SendBreakPacketToHost ( { UINT8 InputCharacter; DEBUG_PORT_HANDLE Handle; - + Handle = GetDebugPortHandle(); - + if (IsHostAttached ()) { DebugAgentMsgPrint (DEBUG_AGENT_INFO, "processor[%x]:Send Break Packet to HOST.\n", ProcessorIndex); SendCommandAndWaitForAckOK (DEBUG_COMMAND_BREAK_POINT, READ_PACKET_TIMEOUT, BreakReceived, NULL); @@ -1316,17 +1764,17 @@ SendBreakPacketToHost ( // // // Poll Attach symbols from HOST and ack OK - // + // do { - DebugPortReadBuffer (Handle, &InputCharacter, 1, 0); + DebugAgentReadBuffer (Handle, &InputCharacter, 1, 0); } while (InputCharacter != DEBUG_STARTING_SYMBOL_ATTACH); SendAckPacket (DEBUG_COMMAND_OK); - + // // Try to attach HOST // while (AttachHost (BreakCause, 0, NULL) != RETURN_SUCCESS); - + } } @@ -1349,7 +1797,7 @@ CommandCommunication ( ) { RETURN_STATUS Status; - UINT8 InputPacketBuffer[DEBUG_DATA_UPPER_LIMIT]; + UINT8 InputPacketBuffer[DEBUG_DATA_UPPER_LIMIT + sizeof (UINT64) - 1]; DEBUG_PACKET_HEADER *DebugHeader; UINT8 Width; UINT8 Data8; @@ -1365,6 +1813,7 @@ CommandCommunication ( DEBUG_DATA_READ_MSR *MsrRegisterRead; DEBUG_DATA_WRITE_MSR *MsrRegisterWrite; DEBUG_DATA_CPUID *Cpuid; + DEBUG_DATA_RESPONSE_BREAK_CAUSE BreakCause; DEBUG_DATA_RESPONSE_CPUID CpuidResponse; DEBUG_DATA_SEARCH_SIGNATURE *SearchSignature; DEBUG_DATA_RESPONSE_GET_EXCEPTION Exception; @@ -1372,10 +1821,10 @@ CommandCommunication ( DEBUG_DATA_SET_VIEWPOINT *SetViewPoint; BOOLEAN HaltDeferred; UINT32 ProcessorIndex; - DEBUG_PORT_HANDLE Handle; DEBUG_AGENT_EXCEPTION_BUFFER AgentExceptionBuffer; UINT32 IssuedViewPoint; DEBUG_AGENT_MAILBOX *Mailbox; + UINT8 *AlignedDataPtr; ProcessorIndex = 0; IssuedViewPoint = 0; @@ -1386,7 +1835,7 @@ CommandCommunication ( SetCpuStopFlagByIndex (ProcessorIndex, TRUE); if (mDebugMpContext.ViewPointIndex == ProcessorIndex) { // - // Only the current view processor could set AgentInProgress Flag. + // Only the current view processor could set AgentInProgress Flag. // IssuedViewPoint = ProcessorIndex; } @@ -1397,9 +1846,7 @@ CommandCommunication ( // Set AgentInProgress Flag. // SetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS, 1); - } - - Handle = GetDebugPortHandle(); + } while (TRUE) { @@ -1430,8 +1877,8 @@ CommandCommunication ( DebugHeader =(DEBUG_PACKET_HEADER *) InputPacketBuffer; DebugAgentMsgPrint (DEBUG_AGENT_INFO, "TARGET: Try to get command from HOST...\n"); - Status = ReceivePacket ((UINT8 *)DebugHeader, &BreakReceived, NULL, READ_PACKET_TIMEOUT, TRUE); - if (Status != RETURN_SUCCESS || (DebugHeader->Command & DEBUG_COMMAND_RESPONSE) != 0) { + Status = ReceivePacket ((UINT8 *) DebugHeader, &BreakReceived, NULL, READ_PACKET_TIMEOUT, TRUE); + if (Status != RETURN_SUCCESS || !IS_REQUEST (DebugHeader)) { DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Get command[%x] sequenceno[%x] returned status is [%x] \n", DebugHeader->Command, DebugHeader->SequenceNo, Status); DebugAgentMsgPrint (DEBUG_AGENT_WARNING, "TARGET: Get command failed or it's response packet not expected! \n"); ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock); @@ -1451,7 +1898,7 @@ CommandCommunication ( ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock); continue; } - + // // Save CPU content before executing HOST commond // @@ -1467,7 +1914,7 @@ CommandCommunication ( } DebugAgentMsgPrint (DEBUG_AGENT_INFO, "Processor[%x]:Received one command(%x)\n", mDebugMpContext.ViewPointIndex, DebugHeader->Command); - + switch (DebugHeader->Command) { case DEBUG_COMMAND_HALT: @@ -1505,11 +1952,7 @@ CommandCommunication ( if (Data8 == DEBUG_DATA_BREAK_CAUSE_IMAGE_LOAD || Data8 == DEBUG_DATA_BREAK_CAUSE_IMAGE_UNLOAD) { CpuContext->Dr0 = 0; } - // - // Clear Stepping Flag - // - SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 0); - + if (!HaltDeferred) { // // If no HALT command received when being in-active mode @@ -1518,7 +1961,7 @@ CommandCommunication ( Data32 = FindNextPendingBreakCpu (); if (Data32 != -1) { // - // If there are still others processors being in break state, + // If there are still others processors being in break state, // send OK packet to HOST to finish this go command // SendAckPacket (DEBUG_COMMAND_OK); @@ -1548,7 +1991,7 @@ CommandCommunication ( SetCpuRunningFlag (TRUE); CpuPause (); // - // Wait for all processors are in running state + // Wait for all processors are in running state // while (TRUE) { if (IsAllCpuRunning ()) { @@ -1592,14 +2035,13 @@ CommandCommunication ( break; case DEBUG_COMMAND_BREAK_CAUSE: - + BreakCause.StopAddress = CpuContext->Eip; if (MultiProcessorDebugSupport() && ProcessorIndex != mDebugMpContext.BreakAtCpuIndex) { - Status = SendBreakCausePacket (DEBUG_TIMER_VECTOR, CpuContext); - + BreakCause.Cause = GetBreakCause (DEBUG_TIMER_VECTOR, CpuContext); } else { - Status = SendBreakCausePacket (Vector, CpuContext); + BreakCause.Cause = GetBreakCause (Vector, CpuContext); } - + SendDataResponsePacket ((UINT8 *) &BreakCause, (UINT16) sizeof (DEBUG_DATA_RESPONSE_BREAK_CAUSE), DebugHeader); break; case DEBUG_COMMAND_SET_HW_BREAKPOINT: @@ -1624,10 +2066,6 @@ CommandCommunication ( } mDebugMpContext.BreakAtCpuIndex = (UINT32) (-1); - // - // Set Stepping Flag - // - SetDebugFlag (DEBUG_AGENT_FLAG_STEPPING, 1); ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock); // // Executing stepping command directly without sending ACK packet, @@ -1639,17 +2077,24 @@ CommandCommunication ( Data64 = (UINTN) (((DEBUG_DATA_SET_SW_BREAKPOINT *) (DebugHeader + 1))->Address); Data8 = *(UINT8 *) (UINTN) Data64; *(UINT8 *) (UINTN) Data64 = DEBUG_SW_BREAKPOINT_SYMBOL; - Status = SendDataResponsePacket ((UINT8 *) &Data8, (UINT16) sizeof (UINT8)); + Status = SendDataResponsePacket ((UINT8 *) &Data8, (UINT16) sizeof (UINT8), DebugHeader); break; case DEBUG_COMMAND_READ_MEMORY: MemoryRead = (DEBUG_DATA_READ_MEMORY *) (DebugHeader + 1); - Status = SendDataResponsePacket ((UINT8 *) (UINTN) MemoryRead->Address, (UINT16) (MemoryRead->Count * MemoryRead->Width)); + Status = ReadMemoryAndSendResponsePacket ((UINT8 *) (UINTN) MemoryRead->Address, MemoryRead->Count, MemoryRead->Width, DebugHeader); break; case DEBUG_COMMAND_WRITE_MEMORY: MemoryWrite = (DEBUG_DATA_WRITE_MEMORY *) (DebugHeader + 1); - CopyMem ((VOID *) (UINTN) MemoryWrite->Address, &MemoryWrite->Data, MemoryWrite->Count * MemoryWrite->Width); + // + // Copy data into one memory with 8-byte alignment address + // + AlignedDataPtr = ALIGN_POINTER ((UINT8 *) &MemoryWrite->Data, sizeof (UINT64)); + if (AlignedDataPtr != (UINT8 *) &MemoryWrite->Data) { + CopyMem (AlignedDataPtr, (UINT8 *) &MemoryWrite->Data, MemoryWrite->Count * MemoryWrite->Width); + } + CopyMemByWidth ((UINT8 *) (UINTN) MemoryWrite->Address, AlignedDataPtr, MemoryWrite->Count, MemoryWrite->Width); SendAckPacket (DEBUG_COMMAND_OK); break; @@ -1671,7 +2116,7 @@ CommandCommunication ( default: Data64 = (UINT64) -1; } - Status = SendDataResponsePacket ((UINT8 *) &Data64, IoRead->Width); + Status = SendDataResponsePacket ((UINT8 *) &Data64, IoRead->Width, DebugHeader); break; case DEBUG_COMMAND_WRITE_IO: @@ -1696,7 +2141,7 @@ CommandCommunication ( break; case DEBUG_COMMAND_READ_ALL_REGISTERS: - Status = SendDataResponsePacket ((UINT8 *) CpuContext, sizeof (*CpuContext)); + Status = SendDataResponsePacket ((UINT8 *) CpuContext, sizeof (*CpuContext), DebugHeader); break; case DEBUG_COMMAND_READ_REGISTER: @@ -1704,7 +2149,7 @@ CommandCommunication ( if (RegisterRead->Index <= SOFT_DEBUGGER_REGISTER_MAX) { RegisterBuffer = ArchReadRegisterBuffer (CpuContext, RegisterRead->Index, &Width); - Status = SendDataResponsePacket (RegisterBuffer, Width); + Status = SendDataResponsePacket (RegisterBuffer, Width, DebugHeader); } else { Status = RETURN_UNSUPPORTED; } @@ -1724,13 +2169,13 @@ CommandCommunication ( case DEBUG_COMMAND_ARCH_MODE: Data8 = DEBUG_ARCH_SYMBOL; - Status = SendDataResponsePacket ((UINT8 *) &Data8, (UINT16) sizeof (UINT8)); + Status = SendDataResponsePacket ((UINT8 *) &Data8, (UINT16) sizeof (UINT8), DebugHeader); break; case DEBUG_COMMAND_READ_MSR: MsrRegisterRead = (DEBUG_DATA_READ_MSR *) (DebugHeader + 1); Data64 = AsmReadMsr64 (MsrRegisterRead->Index); - Status = SendDataResponsePacket ((UINT8 *) &Data64, (UINT16) sizeof (UINT64)); + Status = SendDataResponsePacket ((UINT8 *) &Data64, (UINT16) sizeof (UINT64), DebugHeader); break; case DEBUG_COMMAND_WRITE_MSR: @@ -1749,13 +2194,13 @@ CommandCommunication ( case DEBUG_COMMAND_GET_REVISION: DebugAgentRevision.Revision = DEBUG_AGENT_REVISION; DebugAgentRevision.Capabilities = DEBUG_AGENT_CAPABILITIES; - Status = SendDataResponsePacket ((UINT8 *) &DebugAgentRevision, (UINT16) sizeof (DEBUG_DATA_RESPONSE_GET_REVISION)); + Status = SendDataResponsePacket ((UINT8 *) &DebugAgentRevision, (UINT16) sizeof (DEBUG_DATA_RESPONSE_GET_REVISION), DebugHeader); break; case DEBUG_COMMAND_GET_EXCEPTION: Exception.ExceptionNum = (UINT8) Vector; Exception.ExceptionData = (UINT32) CpuContext->ExceptionData; - Status = SendDataResponsePacket ((UINT8 *) &Exception, (UINT16) sizeof (DEBUG_DATA_RESPONSE_GET_EXCEPTION)); + Status = SendDataResponsePacket ((UINT8 *) &Exception, (UINT16) sizeof (DEBUG_DATA_RESPONSE_GET_EXCEPTION), DebugHeader); break; case DEBUG_COMMAND_SET_VIEWPOINT: @@ -1781,12 +2226,12 @@ CommandCommunication ( case DEBUG_COMMAND_GET_VIEWPOINT: Data32 = mDebugMpContext.ViewPointIndex; - SendDataResponsePacket((UINT8 *) &Data32, (UINT16) sizeof (UINT32)); + SendDataResponsePacket((UINT8 *) &Data32, (UINT16) sizeof (UINT32), DebugHeader); break; case DEBUG_COMMAND_MEMORY_READY: Data8 = (UINT8) GetDebugFlag (DEBUG_AGENT_FLAG_MEMORY_READY); - SendDataResponsePacket (&Data8, (UINT16) sizeof (UINT8)); + SendDataResponsePacket (&Data8, (UINT16) sizeof (UINT8), DebugHeader); break; case DEBUG_COMMAND_DETACH: @@ -1797,16 +2242,16 @@ CommandCommunication ( case DEBUG_COMMAND_CPUID: Cpuid = (DEBUG_DATA_CPUID *) (DebugHeader + 1); AsmCpuidEx ( - Cpuid->Eax, Cpuid->Ecx, + Cpuid->Eax, Cpuid->Ecx, &CpuidResponse.Eax, &CpuidResponse.Ebx, &CpuidResponse.Ecx, &CpuidResponse.Edx ); - SendDataResponsePacket ((UINT8 *) &CpuidResponse, (UINT16) sizeof (CpuidResponse)); + SendDataResponsePacket ((UINT8 *) &CpuidResponse, (UINT16) sizeof (CpuidResponse), DebugHeader); break; case DEBUG_COMMAND_SEARCH_SIGNATURE: SearchSignature = (DEBUG_DATA_SEARCH_SIGNATURE *) (DebugHeader + 1); - if ((SearchSignature->Alignment != 0) && + if ((SearchSignature->Alignment != 0) && (SearchSignature->Alignment == GetPowerOfTwo32 (SearchSignature->Alignment)) ) { if (SearchSignature->Positive) { @@ -1836,7 +2281,7 @@ CommandCommunication ( Data64 = (UINT64) -1; } } - SendDataResponsePacket ((UINT8 *) &Data64, (UINT16) sizeof (Data64)); + SendDataResponsePacket ((UINT8 *) &Data64, (UINT16) sizeof (Data64), DebugHeader); } else { Status = RETURN_UNSUPPORTED; } @@ -1884,6 +2329,7 @@ InterruptProcess ( UINT32 IssuedViewPoint; DEBUG_AGENT_EXCEPTION_BUFFER *ExceptionBuffer; + InputCharacter = 0; ProcessorIndex = 0; IssuedViewPoint = 0; BreakReceived = FALSE; @@ -1913,9 +2359,16 @@ InterruptProcess ( // Check if this exception is issued by Debug Agent itself // If yes, fill the debug agent exception buffer and LongJump() back to // the saved CPU content in CommandCommunication() + // If exception is issued when executing Stepping, will be handled in + // exception handle procedure. // if (GetDebugFlag (DEBUG_AGENT_FLAG_AGENT_IN_PROGRESS) == 1) { - DebugAgentMsgPrint (DEBUG_AGENT_ERROR, "Debug agent meet one Exception, ExceptionNum is %d.\n", Vector); + DebugAgentMsgPrint ( + DEBUG_AGENT_ERROR, + "Debug agent meet one Exception, ExceptionNum is %d, EIP = 0x%x.\n", + Vector, + (UINTN)CpuContext->Eip + ); ExceptionBuffer = (DEBUG_AGENT_EXCEPTION_BUFFER *) (UINTN) GetMailboxPointer()->ExceptionBufferPointer; ExceptionBuffer->ExceptionContent.ExceptionNum = (UINT8) Vector; ExceptionBuffer->ExceptionContent.ExceptionData = (UINT32) CpuContext->ExceptionData; @@ -1925,7 +2378,7 @@ InterruptProcess ( if (MultiProcessorDebugSupport()) { // - // If RUN commmand is executing, wait for it done. + // If RUN commmand is executing, wait for it done. // while (mDebugMpContext.RunCommandSet) { CpuPause (); @@ -1955,6 +2408,10 @@ InterruptProcess ( if (MultiProcessorDebugSupport()) { mDebugMpContext.BreakAtCpuIndex = ProcessorIndex; } + // + // Clear Stepping Flag and restore EFLAGS.IF + // + CommandSteppingCleanup (CpuContext); SendAckPacket (DEBUG_COMMAND_OK); CommandCommunication (Vector, CpuContext, BreakReceived); break; @@ -1984,7 +2441,7 @@ InterruptProcess ( // // Continue to run the following common code // - + case DEBUG_DATA_BREAK_CAUSE_HW_BREAKPOINT: case DEBUG_DATA_BREAK_CAUSE_SW_BREAKPOINT: default: @@ -1994,12 +2451,12 @@ InterruptProcess ( AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock); // // Only the first breaking processor could send BREAK_POINT to HOST - // + // if (IsFirstBreakProcessor (ProcessorIndex)) { SendBreakPacketToHost (BreakCause, ProcessorIndex, &BreakReceived); } ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock); - + if (Vector == DEBUG_INT3_VECTOR) { // // go back address located "0xCC" @@ -2036,7 +2493,8 @@ InterruptProcess ( // CurrentDebugTimerInitCount = GetApicTimerInitCount (); if (mDebugMpContext.DebugTimerInitCount != CurrentDebugTimerInitCount) { - InitializeDebugTimer (); + InitializeDebugTimer (NULL, FALSE); + SaveAndSetDebugTimerInterrupt (TRUE); } } @@ -2121,13 +2579,24 @@ InterruptProcess ( default: if (Vector <= DEBUG_EXCEPT_SIMD) { + DebugAgentMsgPrint ( + DEBUG_AGENT_ERROR, + "Exception happened, ExceptionNum is %d, EIP = 0x%x.\n", + Vector, + (UINTN) CpuContext->Eip + ); if (BreakCause == DEBUG_DATA_BREAK_CAUSE_STEPPING) { // - // Stepping is finished, send Ack package. + // If exception happened when executing Stepping, send Ack package. + // HOST consider Stepping command was finished. // if (MultiProcessorDebugSupport()) { mDebugMpContext.BreakAtCpuIndex = ProcessorIndex; } + // + // Clear Stepping flag and restore EFLAGS.IF + // + CommandSteppingCleanup (CpuContext); SendAckPacket (DEBUG_COMMAND_OK); } else { // @@ -2136,13 +2605,13 @@ InterruptProcess ( AcquireMpSpinLock (&mDebugMpContext.DebugPortSpinLock); // // Only the first breaking processor could send BREAK_POINT to HOST - // + // if (IsFirstBreakProcessor (ProcessorIndex)) { SendBreakPacketToHost (BreakCause, ProcessorIndex, &BreakReceived); } ReleaseMpSpinLock (&mDebugMpContext.DebugPortSpinLock); } - + CommandCommunication (Vector, CpuContext, BreakReceived); } break;