Главная » Просмотр файлов » Volume 2 System Programming

Volume 2 System Programming (794096), страница 86

Файл №794096 Volume 2 System Programming (Intel and AMD manuals) 86 страницаVolume 2 System Programming (794096) страница 862019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 86)

When single stepping isenabled, a #DB exception occurs after every instruction is executed until it is disabled by clearingrFLAGS.TF to 0. However, the instruction that sets the TF bit, and the instruction that follows it, is notsingle stepped.When a #DB exception occurs due to single stepping, the processor clears rFLAGS.TF to 0 beforeentering the debug handler, so that the debug handler itself is not single stepped. The processor alsosets DR6.BS to 1, which indicates that the #DB exception occurred as a result of single stepping.

TherFLAGS image pushed onto the debug-handler stack has the TF bit set, and single stepping resumeswhen a subsequent IRET pops the stack image into the rFLAGS register.Debug and Performance Resources337AMD64 Technology24593—Rev. 3.13—July 2007Single-step breakpoints have a higher priority than external interrupts. If an external interrupt occursduring single stepping, control is transferred to the #DB handler first, causing the rFLAGS.TF bit to becleared to 0. Next, before the first instruction in the debug handler is executed, the processor transferscontrol to the pending-interrupt handler.

This allows external interrupts to be handled outside ofsingle-step mode.The INTn, INT3, and INTO instructions clear the rFLAGS.TF bit to 0 when they are executed. If adebugger is used to single-step software that contains these instructions, it must emulate them insteadof executing them.The single-step mechanism can also be set to single step only control transfers, rather than single stepevery instruction. See “Single Stepping Control Transfers” on page 339 for additional information.13.2.4 Breakpoint Instruction (INT3)The INT3 instruction, or the INTn instruction with an operand of 3, can be used to set breakpoints thattransfer control to the breakpoint-exception (#BP) handler rather than the debug-exception handler.When a debugger uses the breakpoint instructions to set breakpoints, it does so by replacing the firstbytes of an instruction with the breakpoint instruction.

The debugger replaces the breakpointinstructions with the original-instruction bytes to clear the breakpoint.INT3 is a single-byte instruction while INTn with an operand of 3 is a two-byte instruction. Theinstructions have slightly different effects on the breakpoint exception-handler stack. See “#BP—Breakpoint Exception (Vector 3)” on page 210 for additional information on this exception.13.2.5 Control-Transfer Breakpoint FeaturesA control transfers is accomplished by using one of following instructions:•••••••JMP, CALL, RETJcc, JrCXZ, LOOPccJMPF, CALLF, RETFINTn, INT 3, INTO, ICEBPExceptions, IRETSYSCALL, SYSRET, SYSENTER, SYSEXITINTR, NMI, SMI, RSMRecording Control Transfers.

S o f t w a r e e n a b l e s c o n t r o l - t r a n s f e r r e c o r d i n g by s e t t i n gDebugCtlMSR.LBR to 1. When this bit is set, the processor updates the recording MSR'sautomatically when control transfers occur:•LastBranchFromIP and LastBranchToIP Registers—On branch instructions, theLastBranchFromIP register is loaded with the segment offset of the branch instruction, and theLastBranchToIP register is loaded with the first instruction to be executed after the branch. Oninterrupts and exceptions, the LastBranchFromIP register is loaded with the segment offset of the338Debug and Performance Resources24593—Rev. 3.13—July 2007•AMD64 Technologyinterrupted instruction, and the LastBranchToIP register is loaded with the offset of the interrupt orexception handler.LastExceptionFromIP and LastExceptionToIP Registers—The processor loads these from theLastBranchFromIP register and the LastBranchToIP register, respectively, when most interruptsand exceptions are taken.

These two registers are not updated, however, when #DB or #MCexceptions are taken, or the ICEBP instruction is executed.The processor automatically disables control-transfer recording when a debug exception (#DB) occursby clearing DebugCtlMSR.LBR to 0. The contents of the control-transfer recording MSRs are notaltered by the processor when the #DB occurs. Before exiting the debug-exception handler, softwarecan set DebugCtlMSR.LBR to 1 to re-enable the recording mechanism.Debuggers can trace a control transfer backward from a bug to its source using the recording MSRsand the breakpoint-address registers. The debug handler does this by updating the breakpoint registersfrom the recording MSRs after a #DB exception occurs, and restarting the program. The program takesa #DB exception on the previous control transfer, and this process can be repeated.

The debug handlercannot simply copy the contents of the recording MSR into the breakpoint-address register. Therecording MSRs hold segment offsets, while the debug registers hold virtual (linear) addresses. Thedebug handler must calculate the virtual address by reading the code-segment selector (CS) from theinterrupt-handler stack, then reading the segment-base address from the CS descriptor, and adding thatbase address to the offset in the recording MSR. The calculated virtual-address can then be used as abreakpoint address.Single Stepping Control Transfers. Software can enable control-transfer single stepping by settingDebugCtlMSR.BTF to 1 and rFLAGS.TF to 1.

The processor automatically disables control-transfersingle stepping when a debug exception (#DB) occurs by clearing DebugCtlMSR.BTF to 0.rFLAGS.TF is also cleared when a #DB exception occurs. Before exiting the debug-exception handler,software must set both DebugCtlMSR.BTF and rFLAGS.TF to 1 to restart single stepping.When enabled, this single-step mechanism causes a #DB exception to occur on every branchinstruction, interrupt, or exception. Debuggers can use this capability to perform a “coarse” single stepacross blocks of code (bound by control transfers), and then, as the problem search is narrowed, switchinto a “fine” single-step mode on every instruction (DebugCtlMSR.BTF=0, rFLAGS.TF=1).Debuggers can use both the single-step mechanism and recording mechanism to support full backwardand forward tracing of control transfers.13.3Performance OptimizationThe AMD64 architecture supports the performance-monitoring features introduced in earlierprocessor implementations.

These features allow the selection of events to be monitored, and include aset of corresponding counter registers that track the frequency of monitored events. Software tools canuse these features to identify performance bottlenecks, such as sections of code that have high cachemiss rates or frequently mis-predicted branches. This information can then be used as a guide forDebug and Performance Resources339AMD64 Technology24593—Rev. 3.13—July 2007improving or eliminating performance problems through software optimizations or hardware-designimprovements.The performance-monitoring features include:•••••A set of performance-counter registers that count the frequency or duration of specific processorevents.A set of performance-event-select registers used to specify the events that are be tracked by theperformance-counter registers.A time-stamp counter that can be used to count processor-clock cycles over time.A set of instruction-based sampling registers to profile instruction fetch performance.A set of instruction-based sampling registers to profile instruction execution performance.Implementations are not required to support the performance counters and the event-select registers,the time-stamp counter, nor the instruction-based sampling registers for instruction fetch or instructionexecution sampling.

The presence of these features can be determined by executing the CPUIDinstruction, and checking the returned feature bits to determine their availability. See “ProcessorFeature Identification” on page 61 for more information on using the CPUID instruction.The registers used in support of performance monitoring are model-specific registers (MSRs). See“Performance-Monitoring MSRs” on page 461 for a listing of the performance-monitoring MSRnumbers and their reset values.Each feature, and its use, is described in the following sections.13.3.1 Performance CountersPerformance counters are used to count specific processor events, such as data-cache misses, or theduration of events, such as the number of clocks it takes to return data from memory after a cache miss.During event counting, the processor increments the counter when it detects an occurrence of theevent. During duration measurement, the processor counts the number of processor clocks it takes tocomplete an event.

Each performance counter can be used to count one event, or measure the durationof one event, at a time.Implementations of the AMD64 architecture can support any number of performance counters,PerfCtrn. The length, in bits, of the performance counters is also implementation dependent, but themaximum length supported is 64 bits. Figure 13-6 shows the format of the PerfCtrn register.630PerfCtrnFigure 13-6.340Performance Counter (PerfCtrn)Debug and Performance Resources24593—Rev. 3.13—July 2007AMD64 TechnologyThe PerfCtrn registers are model-specific registers that can be read using a special read performancemonitoring counter instruction, RDPMC.

The RDPMC instruction loads the contents of the PerfCtrnregister specified by the ECX register, into the EDX register and the EAX register. The high 32 bits areloaded into EDX, and the low 32 bits are loaded into EAX. RDPMC can be executed only at CPL=0,unless system software enables use of the instruction at all privilege levels. RDPMC can be enabled foruse at all privilege levels by setting CR4.PCE (the performance-monitor counter-enable bit) to 1.When CR4.PCE = 0 and CPL > 0, attempts to execute RDPMC result in a general-protectionexception (#GP).The performance counters can also be read and written by system software running at CPL=0 using theRDMSR and WRMSR instructions, respectively.

Характеристики

Тип файла
PDF-файл
Размер
3,37 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6510
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее