OllyDbgPluginAPIv1.10
LicenseAgreement(veryofficial)
Generalprinciples-readitfirst!
Compilation-readitsecond!
AlphabeticallistofallPluginAPIelements
Informationfunctions
Dataformattingfunctions
Datainputfunctions
Dataconversionfunctions
Sorteddatafunctions
Namefunctions
Searchfunctions
Disassemblyfunctions
Assemblyfunctions
Procedurefunctions
Watchandexpressionfunctions
Breakpointfunctions
Executionandsteppingfunctions
Traceandprofilingfunctions
CPU-specificfunctions
Sourcecodesupportfunctions
Windowfunctions
Threadfunctions
Memoryfunctions
Modulefunctions
Pluginfunctions
Plugincallbackfunctions
Structures
Functionprototypes
Custommessages
Sampleprogram
OllyDbg©2000-2004OlehYuschuk,AllRightsReserved.
OllyDbgPluginAPI©2001-2004OlehYuschuk,AllRightsReserved.Feelfreetoquoteanypartsofthisdocument.
AllbrandnamesandproductnamesusedinOllyDbg,accompanyingfilesorinthishelparetrademarks,registeredtrademarks,ortradenamesoftheirrespectiveholders.
Registration
OllyDbg1.10isCopyright(C)2000-2004OlehYuschuk.Tousethisprogramonapermanentbasisorforcommercialpurposes,youshouldregisterit.Theregistrationisfreeofchargeandassumesnofinancialorotherobligationsfromyourside-justbefairandletmeknowthatyoulikethissoftware.Anypersonaldataintheregistrationformisoptional(useyournicknameorpseudonymifyouwant).
IfyouuseOllyDbgtogetherwithRandallHyde'sHLA(HighLevelAssembly),youdon'tneed(butstillallowed)toregister.
Whenregistering,youcansubscribeforinformation(email)onthenewreleaseversionsofthisprogram.Inthiscaseyouagreenottotreatthisinformationasaspamaslongasnumberoflettersdoesnotexceed4eachcalendaryearandtheycontainnoadvertisementsfromthethirdparties.Ifyounolongerwanttoreceivethisinformation-well,justletmeknow,andIwillimmediatelydeleteyouraddressfrommydatabase.
IfyouarealreadyaregisteredOllyDbguser,youdon'tneedtore-registerthisversion.Ifyouarenew,pleasereadlicenseargeement,filltheregistartionform(register.txt)orcopyandfillthefollowingsectionfromthehelpandemailittoOllydbg@t-online.de.Iwillkeepyourinformationconfidentialandwillnotgiveittothirdpersons,unlessforcedbyalaw.
RegistrationformforOllyDbgv1.10
TouseOllyDbg,youmustagreewithallofthetermsand
conditionsoftheaccompanyingLicenseAgreement.Allother
answersareoptional.
Name___________________________________________________
Title___________________________________________________
Company___________________________________________________
City,state___________________________________________________
Country___________________________________________________
WheredidyoufindOllyDbg__________________________________
___________________________________________________
Areyougoingtowriteyourownplugins
(____)Yes(____)No(____)Don'tknow
Iagreewithallthetermsandconditionoftheaccompanying
LicenseAgreement(Veryimportant!Pleasemark!)
(____)Yes(____)No
Dateofregistration________________________________________
IfyouwanttoreceivenotificationswhenOllyDbg2.00and
subsequentversionswillbeready,pleaseenteryouremail
addresshere:
_____________________________________________________________
Thankyou.IfyouhaveideashowtoimproveOllyDbgandmake
iteasierinuse,orwanttohavesomenewfeatures,please
letmeknow.Youropinionhelpsmealot!
Yourfirstidea:____________________________________________
_____________________________________________________________
Yoursecondidea:___________________________________________
_____________________________________________________________
Yourthirdidea:____________________________________________
_____________________________________________________________
LicenseAgreement
Trademarkinformation
AllbrandnamesandproductnamesusedinOllyDbg,accompanyingfilesorinthishelparetrademarks,registeredtrademarks,ortradenamesoftheirrespectiveholders.Theyareusedforidentificationpurposesonly.
LicenseAgreement
ThisLicenseAgreement("Agreement")accompaniestheOllyDbgversion1.10,OllyDbgPluginDevelopmentKitversion1.10andrelatedfiles("Software").ByusingtheSoftware,youagreetobeboundbyallofthetermsandconditionsoftheAgreement.
TheSoftwareisdistributed"asis",withoutwarrantyofanykind,expressedorimplied,including,butnotlimitedtowarrantyoffitnessforanyparticularpurpose.InnoeventwilltheAuthorbeliabletoyouforanyspecial,incidental,indirect,consequentialoranyotherdamagescausedbytheuse,misuse,ortheinabilitytouseoftheSoftware,includinganylostprofitsorlostsavings,evenifAuthorhasbeenadvisedofthepossibilityofsuchdamages.
TheSoftwareisownedbyOlehYuschuk("Author")andisCopyright(c)2000-2004OlehYuschuk.TousethisSoftwareonapermanentbasisorforcommercialpurposes,youmustregisteritbyfillingthesuppliedregistrationformandsendingittotheAuthor.Youdon'tneedtoregisterSoftwareifyouuseitexclusivelywithRandallHyde'sHighLevelAssembly.IfyouarealreadyaregisteredOllyDbguser,youdon'tneedtore-registertheSoftwareagain.IftheSoftwareisregisteredtoacompanyororganization,anypersonwithinthecompanyororganizationhastherighttouseitatwork.YoumayinstalltheregisteredSoftwareonanynumberofstoragedevices,likeharddisks,floppydisksetc.andareallowedtomakeanynumberofbackupcopiesofthisSoftware.
Youarenotallowedtomodify,decompile,disassembleorreverseengineertheSoftwareexceptandonlytotheextentthatsuchactivityisexpresslypermittedbyapplicablelaw.YouarenotallowedtodistributeoruseanypartsoftheSoftwareseparately.YoumaymakeanddistributecopiesofthisSoftwareprovidedthata)thecopycontainsallfilesfromtheoriginaldistributionand
thesefilesremainunchanged;b)ifyoudistributeanyotherfiles(forexample,plugins)togetherwiththeSoftware,theymustbeclearlymarkedassuchandtheconditionsoftheirusecannotbemorerestrictivethanconditionsofthisAgreement;andc)youcollectnofee(exceptfortransportmedia,likeCDordiskette),evenifyourdistributioncontainsadditionalfiles.
Youareallowedtodevelopanddistributeyourownplugins--DynamicLinkLibrariesthatconnecttotheSoftwareandmakeuseofthefunctionsimplementedintheSoftware--freeofchargeprovidedthata)yourpluginscontainnofeaturesthatpersuadeorforceusertoregisterthem,orlimitfunctionalityofunregisteredplugins;b)youallowfreedistributionofyourpluginsontheconditionssimilartothatoftheSoftware;andc)youcollectnofee(exceptfortransportmedia,likeCDordiskette).Ifyouwanttodevelopcommercialplugin,pleasecontactAuthorforaspecialAgreement.
ThedistributionincludesfilesPSAPI.DLLandDBGHELP.DLLthataretheMicrosoft(R)Redistributablefiles.ThesefilesshouldbeinstalledonlyinthedirectorywheretheSoftwareresides.YoushouldusesuppliedPSAPI.DLLonlyonWindowsNT(R)4.0.YouarenotallowedtodistributePSAPI.DLLand/orDBGHELP.DLLseparatelyfromtheSoftware.
ThisAgreementcoversonlytheactualversion1.10oftheOllyDbgandversion1.10oftheOllyDbgPluginDevelopmentKit.AllotherversionsarecoveredbyseparateLicenseAgreements.
Fairuse
Manysoftwaremanufacturersexplicitlydisallowyouanyattemptsofdisassembling,decompilation,reverseengineeringormodificationoftheirprograms.Thisrestrictionalsocoversallthird-partydynamic-linklibrariesyourapplicationmayuse,includingsystemlibraries.Ifyouhaveanydoubts,contacttheownerofcopyright.Thesocalled„fairuse"clausecanbemisleading.Youmaywanttodiscusswhetheritappliesinyourcasewithcompetentlawyer.Pleasedon'tuseOllyDbgforillegalpurposes!
Generalprinciples
Welcome.OllyDbgv1.10isthefinalversion.Idecidedtostopitsdevelopment.ThisdoesnotmeanthatOllyDbgisdead-currentlyI'mpreparingv2.0-butnewversionwillbeincompatiblewithv1.xx,atleastwhatconcernsplugins.Sorry,butthisistheonlypossiblesolution.
ThisdocumentsdescribesOllyDbgPluginAPIv1.10.Therearenosignificantchangesininterfacesorinstructures,sopluginscompiledforOllyDbg1.06or1.08willusuallyworkwithOllyDbg1.10.Theonlychangesthatmaybenot100%backward-compatiblearelimitedto:
-Structurest_regandt_bpointareextended;
-Newoption"Alwaysontop"requiresspecialsupportfrompluginwindows;
-FunctionBrowsefilenamesupportsSaveFiledialog;
PluginisaDLLthatresidesinOllyDbgdirectoryandaddsfunctionalitytoOllyDbg.Youarefreetowriteanddistributeyourownplugins,providedthattheyarefree,too.(SeeLicenseAgreementfordetails).Onyourrequest,Iamreadytoplacesuchpluginsfordownloadonmyhomepage.Commercialpluginsarealsoallowed,butinthiscaseyouneedspeciallicense.
Toco-operate,differentpluginsrequireuniquenames,.uddtags,nametypesandsoon.Ifyouneedsomeoftheseresources,pleasecontactme.Thisserviceisabsolutelyfreeforyou!
Duringstartup,OllyDbgloadsallavailableDLLsonebyoneandlooksforentrypointsnamed_ODBG_Plugindataand_ODBG_Plugininit.Iftheseentriesarepresentandpluginreportscompatibleinterfaceversion,OllyDbgregisterspluginandaddsentryorsubmenutoPluginspopupinthemainOllyDbgmenu.
PluginscanaddmenuitemstoDisassembler,Dump,Stack,Registers,Memory,Modules,Threads,Breakpoints,Watches,References,WindowsandRuntracewindows.Theycaninterceptbothglobalshortcutsandshortcutsfromoneofthelistedwindows.TheyalsocancreateownMDIwindows.Pluginscanwriteplugin-specificdatato.uddfileswithmodule-dependentinformationandollydbg.iniandaccessdifferentdatastructuresthatdescribedebugged
application.Thereareseveral(ingeneral,optional)callbackfunctionsthatalloweasybutcloseinteractionwithOllyDbg.Additionally,pluginsmaycallmorethan170pluginAPIfunctions.
Plugininterfaceisnotobject-oriented.Perharpsthiswillcomeassurprisetoyou,butallmyexperiencetellsmethatOOPisnotasgoodasmainsoftwarevendorstrytosell.Itisreallygoodifyouwritesmallapplicationperformingstandardfunctions.Forabigweirdproject(andOllyDbgisabigweirdproject)OOPgivesnorealimprovementsindevelopmenttime,errorsincomponentsareveryhardtolocateandevenhardertocorrect.And-contrarytowhatvendorstellus-OOprogramsareusuallyslow.Stopcrying,thisisonlymyopinion,albeitprovedbyallmyexperienceinthelast15yearsorso.Anyway,trytoswallowthatyouwillgetnoready-to-useobjectshereandaredoomedtofreememorybyyourselfwhenpluginterminates.
PluginAPIisnotre-entrantanddoesnotimplementcriticalsections.Ifyourplugincreatesnewthread,don'tcallAPIfunctionsfromthisthread,otherwiseyourisktocorruptinternaldatastructuresandcrashbothprogramandOllyDbg!
SomeexportedAPIfunctionsarenotdescribedhere.TheirdirectusemaybringOllyDbginunstablestate.Ihaveaddedthemforbettercompatibilitywithfutureversionsofplugininterface.
Seealso:Compilation
Alwaysontop
OllyDbgnowsupports"alwaysontop"optionforitsMDIwinsows(calledfromtheAppearancemenu).ThisoptionmeansthatselectedMDIwindowremainsvisibleonthetopofotherwindows.
Addingthisusefuloptiontoapluginisamatterofminutes.PluginscreateMDIwindowsbycallingNewtablewindoworQuicktablewindow.Inthestructuret_table,passedasafirstparameter,youmustspecifyflagTABLE_ONTOP,asinthesampleprogram.Tosupportthisoption,pluginmustpassmessageWM_WINDOWPOSCHANGEDtodefaultpluginfunction(seehere).
That'sall!Easy,isn'tit?
Compilation
Compilation
Tocompileyourownplugin,youneedsomeCorC++compiler(togetherwithlinkerandrun-timelibraries).Plugininterface(fileplugin.h)iscompatibleatleastwithfollowingcompilers:
·Borland'sC++5.5-commandlinecompiler,availableforfreefromwww.borland.com(requiresregistration);
·Borland'sC++Builder5-basedonthesameC++5.5;
·Microsoft'sVisualC++5.0-ratheroldbutsolidandstable.
Ihaven'ttriedanyothercompilers.Pleaseletmeknowifyoufindanyincompatibilitiesand,ifpossible,sendmecorrectedversionoffileplugin.h.
PluginDevelopmentKitincludessourcecodefortwofullyfunctionalsampleplugins:bookmark,thatallowstosetupto10bookmarksindebuggedapplication,andcommandline,thatimplementscommandlineinterface.Pluginsarewelldocumented.Youcanusethemasatemplateforyourownplugins.Theyarefreeware,i.e.yourrightstomodifyandre-usetheirsourcecodearenotlimitedinanyway.
FollowingcompilersettingsarerequiredforcorrectcommunicationbetweenpluginandOllyDbg.Forcompilerslistedabove,plugin.hforcesorcheckssomeoftheserules:
·Exportallcallbackfunctionsbyname,NOTbyordinal;
·IfyouuseC++compiler,disablenamemanglingonallcallbackfunctions(declarethemasextern"C");
·ForcestandardC-stylepassingofparameterstoallAPIandcallbackfunctions(declarethemascdecl);
·ForceBYTEalignmentofallstructuresdeclaredinplugin.h;
·SetdefaultcharactertypetoUNSIGNED.
KeepinmindthatallpointersyougetfromOllyDbgmaybeNULL.Thisisaverycommonerrortoassumeopposite.
Usestaticrun-timelibrarieslinkeddirectlyintoyourplugin,otherwisedifferencesbetweenversionsofrun-timeDLLswillmakeOllyDbgunstable.DonotsplityourpluginunnecessarilyintoseveralDLLs.Ifyouneeddatafilesthatarenotmodifiablebyuser,trytoplacethisdatadirectlyintoyourpluginasaresource.
TolinkyourplugintoOllyDbg,youalsoneedimportlibraryollydbg.lib.Somecompilers(Borland)includeutilitycalledimplibthatscansexecutablefile(inourcase,ollydbg.exe)andproducesaspecialkindoflibrarywithalistofallexportedfunctions.Someotherproducts,likeMSVC,cangenerateimportlibraryfromthedefinitionfile(ollydbg.def).Similarproductsfromothervendorsarealsoavailable.Fordetails,pleaseconsultdocumentation.
And,lastbutnotleast,don'twasteresources!Don'texportunusedcallbackfunctionsandmakeyourprogramfast!OllyDbgincurrentversionsupportsupto32plugins.Ifeachofthemwilltakeonly50mstorejectaglobalshortcut,then50msforwindow-specificshortcut...youDOunderstandwhatImean,don'tyou?
Contentsofplug110.zip
Pluginkitarchivecontainsfollowingfiles:
Rootdirectory:
bookmark.c-sourceofbookmarkplugin
cmdexec.c-sourceofcommandlineplugin
command.c-sourceofcommandlineplugin
cmdline.rtf-RTFsourceofhelp(.hlp)fileforcommandlineplugin
ollydbg.def-OllyDbgdefinitionfile,somecompilersneedittoproduceimportlibraryollydbg.lib
plugin.h-headerwithdefinitionsofplugininterface
plugins.hlp-thishelpfile
DirectoryBC55:
sample.bpr-projectfileforBCB5,producessample.dll(sameasbookmark.dll)
sample.cpp-mainfileforsample.bpr
bookmark.mak-makefileforBC5.5,producesbookmark.dll
cmdline.bpr-projectfileforBCB5,producescmdline.dll
cmdline.cpp-mainfileforcmdline.bpr
cmdline.mak-makefileforBC5.5,producescmdline.dll
ollydbg.lib-OllyDbgimportlibraryinOMFformat
DirectoryVC50:
bookmark.dsp-projectfileforVisualStudio97,producesbookmark.dll
bookmark.dsw-projectfileforVisualStudio97,producesbookmark.dll
bookmark.mak-makefileforVC5.0,producesbookmark.dll
cmdline.dsp-projectfileforVisualStudio97,producescmdline.dll
cmdline.dsw-projectfileforVisualStudio97,producescmdline.dll
cmdline.mak-makefileforVC5.0,producescmdline.dll
ollydbg.lib-OllyDbgimportlibraryinCOFFformat
MakingsamplepluginswithBC5.5
TobuildsampleDLLswithBC5.5,pleasedothefollowing:
1.Copyfilesbookmark.c,cmdexec.c,command.c,plugin.h,bc55\bookmark.mak,bc55\cmdline.mak,bc55\ollydbg.libtosamedirectory;
2.AssumingthatyourBC5.5compilerisinstalledtoc:\bc55,issuefollowingcommands:
c:\bc55\bin\make-fbookmark.mak
c:\bc55\bin\make-fcmdline.mak
3.Supposethatyouwriteyourownplugin,myplug,consistingofsourcefilesa.c,b.candresourcec.rc.Allyouneedistorenamebookmark.maktomyplug.makandmodifythreelinesnearthetopofthefileinafollowingway:
PROJECT=myplug.dll
OBJFILES=a.objb.obj
RESFILES=c.rc
andthencommand
c:\bc55\bin\make-fmyplug.mak
MakingsamplepluginswithBCB5
BCBprojectsmustcontainmainC++programwiththesamenameasprojectandextention.cpp.Forthisreason,bookmarkplugincreatedwithBuilderiscalledsample.dll.Ofcourse,thishasnoinfluenceonitsfunctionality.
Tobuildsample.dll,pleasedothefollowing:
1.Copyfilesbookmark.c,plugin.h,bc55\sample.bpr,bc55\sample.cppandbc55\ollydbg.libtothesamedirectory;
2.Opensample.bprinBuilderandmakeproject.
Tobuildcmdline.dll,pleasedothefollowing:
1.Copyfilescmdexec.c,command.c,plugin.h,bc55\cmdline.bpr,bc55\cmdline.cppandbc55\ollydbg.libtothesamedirectory;
2.Opencmdline.bprinBuilderandmakeproject.
MakingsamplepluginswithVC5.0fromthecommandline
TobuildsampleDLLswithVC5.0,pleasedothefollowing:
1.Copyfilesbookmark.c,cmdexec.c,command.c,plugin.h,vc50\bookmark.mak,vc50\cmdline.makandvc50\ollydbg.libtothesamedirectory;
2.In.makfiles,editlines
INCLUDE=c:\vc\include
LIBPATH=c:\vc\lib
sothattheypointtoyourincludeandlibrarydirectories;
3.AssumingthatyourVCcompiler,cl.exe,andmakeutility,nmake.exe,resideinc:\vc\bin,executefollowingcommands:
c:\vc\bin\nmake-fbookmark.mak
c:\vc\bin\nmake-fcmdline.mak
MakingsamplepluginsfromtheVisualStudio
Tobuildbookmark.dll:
1.Copyfilesbookmark.c,plugin.h,vc50\bookmark.dsp,vc50\bookmark.dswandvc50\ollydbg.libtothesamedirectory;
2.OpenprojectbookmarkinVisualStudioandmakeit.
Tobuildcmdline.dll:
1.Copyfilescmdexec.c,command.c,plugin.h,vc50\cmdline.dsp,vc50\cmdline.dswandvc50\ollydbg.libtothesamedirectory;
2.OpenprojectcmdlineinVisualStudioandmakeit.
PluginAPI-alphabeticallist
APIfunctions
ThislistcontainsallfunctionsexportedbyOllyDbg.Someofthemarereservedforthefutureuseandarenotdescribedhere.DirectcallstosomeundescribedfunctionsmayimpairOllyDbg'sstability.Ifyouneedsomeundescribedfunction,pleasecontactOlehYuschuk.Functionsthatwereaddedorchangedsinceversion1.08aremarkedwithanasterisk(*).
Addsorteddata
Addtolist
Analysecode
Animate
Assemble
Attachtoactiveprocess*
Broadcast
Browsefilename*
Checkcondition
Compress
Createdumpwindow
Createlistwindow
Createpatchwindow*
Createprofilewindow
Creatertracewindow
Createsorteddata
Createthreadwindow
Createwatchwindow
Createwinwindow
Decodeaddress
Decodeascii
Decodecharacter
Decodefullvarname
Decodeknownargument
Decodename
Decoderange
Decoderelativeoffset
Decodethreadname
Decodeunicode
Decompress
Defaultbar
Deletebreakpoints
Deletehardwarebreakbyaddr
Deletehardwarebreakpoint
Deletenamerange
Deletenonconfirmedsorteddata
Deleteruntrace
Deletesorteddata
Deletesorteddatarange
Deletewatch
Demanglename
Destroysorteddata
Disasm
Disassembleback
Disassembleforward
Discardquicknames
Dumpbackup
Error
Expression
Findallcommands
Findalldllcalls
Findallsequences
Finddecode
Findfileoffset
Findfixup
Findhittrace
Findimportbyname
Findknownfunction
Findlabel
Findlabelbyname
Findmemory
Findmodule
Findname
Findnextname
Findnextproc
Findnextruntraceip
Findprevproc
Findprevruntraceip
Findprocbegin
Findprocend
Findreferences
Findsorteddata
Findsorteddataindex
Findsorteddatarange
Findstrings
Findsymbolicname
Findthread
Findunknownfunction
Flash
Followcall
Get3dnow
Get3dnowxy
Getaddressfromline
Getasmfindmodel
Getasmfindmodelxy
Getbprelname
Getbreakpointtype
Getbreakpointtypecount*
Getcputhreadid
Getdisassemblerrange
Getfloat
Getfloatxy
Getfloat10
Getfloat10xy
Gethexstring
Gethexstringxy
Getline
Getlinexy
Getlinefromaddress
Getlong
Getlongxy
Getmmx
Getmmxxy
Getnextbreakpoint
Getoriginaldatasize
Getproclimits
Getregxy
Getresourcestring
Getruntraceregisters
Getruntraceprofile
Getsortedbyselection
Getsourcefilelimits
Getstatus
Gettableselectionxy
Gettext
Gettextxy
Getwatch
Go
Guardmemory
Hardbreakpoints
Havecopyofmemory
Infoline
Injectcode
Insertname
Insertwatch
Isfilling
Isprefix
Isretaddr
Issuspicious
IstextA
IstextW
Listmemory*
Manualbreakpoint
Mergequicknames
Message
Modifyhittrace
Newtablewindow
OpenEXEfile
Painttable
Plugingetvalue
Pluginreadintfromini
Pluginreadstringfromini
Pluginsaverecord
Pluginwriteinttoini
Pluginwritestringtoini
Print3dnow
Printfloat10
Printfloat4
Printfloat8
Printsse
Progress
Quickinsertname
Quicktablewindow
Readcommand
Readmemory
Redrawdisassembler
Registerpluginclass
Restoreallthreads
Runsinglethread
Runtracesize
Scrollruntracewindow
Selectandscroll
Sendshortcut
Setbreakpoint*
Setbreakpointext*
Setcpu
Setdisasm
Setdumptype
Sethardwarebreakpoint
Setmembreakpoint
Settracecondition
Settracecount*
Showsourcefromaddress
Sortsorteddata
Startruntrace
Stringtotext
Suspendprocess
Tablefunction
Tempbreakpoint
Unregisterpluginclass
Updatelist
Walkreference
Walkreferenceex
Writememory
Callbackfunctions
ODBG_Paused*
ODBG_Pausedex*
ODBG_Pluginaction
ODBG_Pluginclose
ODBG_Plugincmd*
ODBG_Plugindata
ODBG_Plugindestroy
ODBG_Plugininit
ODBG_Pluginmainloop
ODBG_Pluginmenu
ODBG_Pluginreset
ODBG_Pluginsaveudd
ODBG_Pluginshortcut
ODBG_Pluginuddrecord
Structures
t_asmmodel
t_bpoint*
t_disasm
t_dump
t_extmodel
t_hexstr
t_memory
t_module
t_operand
t_ref
t_reg*
t_result
t_sorted
t_sortheader
t_table
t_thread
t_window
Functionprototypes
SORTFUNC
DESTFUNC
DRAWFUNC
Custommessages
WM_USER_BAR
WM_USER_CHALL
WM_USER_CHGS
WM_USER_CHMEM
WM_USER_CHREG
WM_USER_CNTS
WM_USER_DBLCLK
WM_USER_MENU
WM_USER_SCR
WM_USER_STS
WM_USER_VABS
WM_USER_VBYTE
WM_USER_VREL
Informationfunctions
Thisgroupoffunctionsdisplayserrorandinformationmessages,addsmessagestologwindow,showsscrollbarandflash:
voidAddtolist(longaddr,inthighlight,char*format,...);
voidUpdatelist(void);
HWNDCreatelistwindow(void);
voidError(char*format,...);
voidMessage(ulongaddr,char*format,...);
voidInfoline(char*format,...);
voidProgress(intpromille,char*format,...);
voidFlash(char*format,...);
Addtolist
TheAddtolistfunctionaddssinglelineofASCIItext,uptoTEXTLENcharacterslong,tothelogwindow.
voidAddtolist(longaddr,inthighlight,char*format,...);
Parameters:
addr-memoryaddressassociatedwithlogline.Bydoubleclickingthelineinlogwindow,onecaninstantlyjumptothecorrespondingcodeordatainCPU;
highlight-coloroftext:
0 standardcolor(blackinblackonwhitecolorscheme);1 highlighted(red);-1 grayed(gray);
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Updatelist,Createlistwindow,Message
Updatelist
Iflogwindowispresent,calltothisfunctionforcesimmediateupdateofthelogwindow.Callitifsomeoperationtakesplentyoftimeandyouwanttomakenewmessagesimmediatelyavailableforuser.
voidUpdatelist(void);
Seealso:Addtolist,Createlistwindow,Message
Createlistwindow
Createsorrestoreslogwindow(windowthatdisplayscontentsoflogbuffer)onthescreen.Notethatwritingtobufferdoesn'tdependonwhetherlogwindowispresent;closinglogwindowdoesn'tdestroythecontentsofbuffer.
HWNDCreatelistwindow(void);
Seealso:Addtolist,Updatelist,Message
Error
Displaysmessageboxwithinformationabouterror.Tocontinue,usermustclickOKbutton,pressEnterorEsc.Usethiscallforcriticalerrorsonly;iferrorisnotveryimportant,Flash,MessageorInfolinearebetteralternatives.
voidError(char*format,...);
Parameters:
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Flash,Message,Infoline
Message
DisplaysmessageonthebottomofmainOllyDbgwindowandaddsittothelogwindow.IfformatisNULL,messagewillberemovedfromthebottomlinebutnotaddedtothelog.Formattedmessagemaycontaindollarsign'$'.Thissymbolisreplacedbydash'-'onthebottomlineandterminateslineaddedtothelog.Forexample,ifyoucallMessage(0,"Criticalerror$pressSPACEtocontinue"),bottomlinewilldisplay"Criticalerror-pressSPACEtocontinue"andlogwindow"Criticalerror".Calltothisfunctionremovesflashandprogressbarfromthebottomline.
voidMessage(ulongaddr,char*format,...);
Parameters:
addr-memoryaddressassociatedwithlogline.Bydoubleclickingthelineinlogwindow,onecaninstantlyjumptothecorrespondingcodeordatainCPU.addrisnotdisplayedinthebottomline;
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Addtolist,Updatelist,Createlistwindow,Infoline,Progress,Flash
Infoline
DisplaysmessageonthebottomofmainOllyDbgwindow.IfformatisNULL,currentlydisplayedmessagewillberemoved.CalltoInfolineremovesflashandprogressbarfromthebottomline.
voidInfoline(char*format,...);
Parameters:
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Addtolist,Updatelist,Createlistwindow,Message,Progress,Flash
Progress
DisplaysprogressbaronthebottomofmainOllyDbgwindow.Barwillcontainformattedtextwithattachedpercentofexecution.Formattedtextmaycontaindollarsign'$',inthiscasepersentofexecution,enclosedindashes,isinsertedinsteadofdollrasign.Ifpromilleis0,functionclosesprogressbarrestorespreviouslydisplayedmessage.CallstoMessage,InfolineandFlashalsowillcloseprogressbar.
voidProgress(intpromille,char*format,...);
Parameters:
promille-progress,in1/1000th;
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Message,Infoline,Flash
Flash
DisplayshighlightedmessageonthebottomofmainOllyDbgwindow.Thismessageautomaticallydisappearsin500milliseconds.
voidFlash(char*format,...);
Parameters:
format-formatstring(asincalltoprintf),followedbyoptionalarguments.
Seealso:Message,Infoline,Progress
Dataformattingfunctions
Thisgroupoffunctionsconvertsbinarydata,likeaddress,floatingnumberorcharactertoASCIItext.FunctionsIstextAandIstextWcheckwhetherASCIIorUNICODEcharactercanbeapartofstring.Isretaddrcheckswhetheraddressisapossiblereturnaddress.
intDecodeaddress(ulongaddr,ulongbase,intaddrmode,char*symb,intnsymb,char*comment);
intDecoderelativeoffset(ulongaddr,intaddrmode,char*symb,intnsymb);
intDecoderange(ulongaddr,ulongsize,char*s);
intDecodecharacter(char*s,uintc);
intDecodeascii(ulongaddr,char*s,intlen,intmode);
intDecodeunicode(ulongaddr,char*s,intlen);
intPrintfloat4(char*s,floatf);
intPrintfloat8(char*s,doubled);
intPrintfloat10(char*s,longdoubleext);
intPrintsse(char*s,char*f);
intPrint3dnow(char*s,char*f);
intIstextA(charc);
intIstextW(wchar_tw);
ulongIsretaddr(ulongretaddr,ulong*procaddr);
intStringtotext(char*data,intndata,char*text,intntext);
Decodeaddress
Decodesmemoryaddresstotextstringandoptionallycommentsit.Returnslengthofdecodedstring(notincludingterminal0),or0onerror.Thedecodingisstronglyinfluencedbyaddrmodeandmayvaryfromsimple01234567toconstructslike<JMP.&USER32.GetSystemMetrics>.Ifaddresshasbothmodule-anduser-definednames,user-definednamehaspriorityandmodule-definednameisplacedincomment.
intDecodeaddress(ulongaddr,ulongbase,intaddrmode,char*symb,intnsymb,char*comment);
Parameters:
addr-addresstodecodeinaddressspaceofdebuggedprogram;
base-addressbelongingtothemoduleselectedascurrentor0ifthereisnocurrentmodule.NecessaryifyousetbitsADC_SAMEMODorADC_DIFFMOD;
addrmode-combinationofADC_xxxbitslistedbelow,determineshowtodecodeaddr.NotethatDecodeaddressdoesnotsupportsomeofADC_xxxdeclaredinplugin.h:
ADC_VALID decodeaddressonlyifitpointstoallocatedmemoryorhasassociatedsymbolicname;
ADC_INMODULE
decodeaddressonlyifitpointstosomemoduleorhasassociatedsymbolicname.Ifyouwanttoavoidcaseswhensomeaddresspointstogapbetweentwomemoryblocksbelongingtoamodule,specifybothADC_VALIDandADC_INMODULEflags;
ADC_SAMEMOD
decodeaddressonlyifitpointstomoduledefinedbyparameterbaseorhasassociatedsymbolicname(constantornamebelongingtodifferentmnodule).ConditionADC_INMODULEisautomaticallytrueandflagneednottobeexplicitelyspecified.
ADC_SYMBOL decodeaddressonlyifithassymbolicnameorifADC_JUMPbitissetandaddresspointstoJMPtosymbolicname;
ADC_JUMPcheckwhetheraddrpointstoJMPtoaddressplacedonsomeimportaddressanddecodeitas<JMP.&MODULE.ImportName>;
ADC_DIFFMODdisplaymodulenameonlyifaddrbelongstomodulewhichdiffersfromthecurrent(specifiedbybase);
ADC_NOMODNAME
neverdisplaymodulename.IfneitherADC_DIFFMODnorADC_NOMODNAMEbitsspecified,modulenameisdisplayedwhenaddressbelongstosomemodule;
ADC_OFFSETifaddresshasasymbolicnameandpointstodatasection,addwordOFFSETbeforethisname(forex.,OFFSETMODULE.DataName);
ADC_STRING decodetocommentthecasewhenaddresspointstoASCIIorUNICODEstring;
ADC_ENTRYdecodetocommentthecasewhenaddressisanentrypointofsomesubroutinewithoutsymbolicname;
symb-pointertobufferoflengthatleastnsymbbyteswhereDecodeaddressplacesdecodedstring;
nsymb-length,incharacters,ofbuffersymb;
comment-pointertostringoflengthatleastTEXTLENbytesorNULL,receivescommentasociatedwithaddr.
Seealso:Decoderelativeoffset,Disasm,Decodeascii,Decodeunicode
Decoderelativeoffset
Ifaddresspointstoavalidcommandwithinthenamedprocedure,decodesaddressinform"module.procedure+offset"or"procedure+offset".Returnslengthofdecodedstringor0onerrororwhenprocedureisnotnamed.
intDecoderelativeoffset(ulongaddr,intaddrmode,char*symb,intnsymb);
Parameters:
addr-absoluteaddresstodecode;
addrmode-combinationofADC_xxxbitslistedbelow,determineshowtodecodeaddr.NotethatDecodeaddressdoesnotsupportsomeofADC_xxxdeclaredinplugin.h:
ADC_NOMODNAME ifbitiscleared,prependnameofprocedurewithmodulename,otherwisemodulenameisomittedADC_NONTRIVIAL ifoffsetis0,donotdecoderelativeoffset
symb-pointertobufferoflengthatleastnsymbbyteswhereDecoderelativeoffsetplacesdecodedstring;
nsymb-length,incharacters,ofbuffersymb.
Seealso:Decodeaddress,Decoderange
Decoderange
Decodesaddressrange,eitherinform"module:section"or"firstaddr..lastaddr".Returnslengthofresultingstring.
intDecoderange(ulongaddr,ulongsize,char*s);
Parameters:
addr-startofaddressrange;
size-sizeofaddressrange;
s-pointertobufferoflengthatleastTEXTLENbytesthatreceivesresultingstring.
Seealso:Decodeaddress,Decoderelativeoffset
Decodecharacter
DecodesASCIIcharacterctostringsandcommentssomecharacterswithspecialmeaning,likeTAB,CRorLF.Returnslengthofdecodedstringor0onerror.
intDecodecharacter(char*s,uintc);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswhereDecodecharacterplacesdecodedstring;
c-charactertodecode.
Seealso:IstextA,IstextW
Decodeascii
DecodesASCIIstringthatstartsataddressaddrinthememoryofdebuggedprocessintostringsoflengthlen.IfmodeisDASC_TESTorDASC_NOHEX,checkswhetherthisreallylookslikeastring,ifDASC_ASCII-decodesasASCIIstring,ifDASC_PASCAL-decodesasPascalstring(notzero-terminated,precededwithbytelength).IfmodeisDASC_NOHEXandvaluepointstoastring,precedesdecodedstringwith"ASCII".Returnslengthofresultingtext,notincludingterminal'\0'.
intDecodeascii(ulongaddr,char*s,intlen,intmode);
Parameters:
addr-addressinthememoryofdebuggedprocesswhereASCIIstringstarts;
s-pointertobufferoflengthatleastTEXTLENbyteswhereDecodeasciiplacesdecodedstring;
len-lengthofstringsinbytes;
mode-decodingmode,oneofthefollowing:
DASC_TEST TestwhetherpointeddatareallylookslikeanASCIIstring.Ifnot,printhexadecimaladdressinsteadofstring
DASC_NOHEX TestwhetherpointeddatareallylookslikeanASCIIstring.Ifnot,return0.
DASC_ASCII ForceASCIIstringDASC_PASCAL ForcePascalstring
Seealso:Decodeunicode,Decodeaddress,Decodecharacter
Decodeunicode
//DecodesUNICODEstringthatstartsataddressaddrinthememoryofdebuggedprocessintoASCIIstringsoflengthlen.Returnslengthofresultingtext,notincludingterminal'\0'.
intDecodeunicode(ulongaddr,char*s,intlen);
Parameters:
addr-addressinthememoryofdebuggedprocesswhereUNICODEstringstarts;
s-pointertobufferoflengthatleastTEXTLENbyteswhereDecodeunicodeplacesdecodedstring;
len-lengthofstringsinbytes.
Seealso:Decodeascii,Decodeaddress,Decodecharacter
Printfloat4
Decodes32-bit(4-byte)floatingpointnumbertoASCIIstring.IfnumberisINForNAN,addshexadecimaldump.Returnslengthofdecodedstring.
intPrintfloat4(char*s,floatf);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswherePrintfloat4placesdecodedstring;
f-32-bitfloatingnumbertodecode.
Seealso:Printfloat8,Printfloat10,Print3dnow,Printsse
Printfloat8
Decodes64-bit(8-byte,double)floatingpointnumbertoASCIIstring.IfnumberisINForNAN,addshexadecimaldump.Returnslengthofdecodedstring.Notethatthisprocedureissaferthanprintf,becausesomeprintfimplementationsgenerateexceptionwhenprocessingINForNAN.
intPrintfloat8(char*s,doubled);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswherePrintfloat8placesdecodedstring;
d-64-bit(double)floatingnumbertodecode.
Seealso:Printfloat4,Printfloat10,Print3dnow,Printsse
Printfloat10
Decodes80-bit(10-byte,longdouble)floatingpointnumbertoASCIIstring.IfnumberisINForNAN,addshexadecimaldump.Returnslengthofdecodedstring.Notethatthisprocedureissaferthanprintf,becausesomeprintfimplementationsgenerateexceptionwhenprocessingINForNAN.
intPrintfloat10(char*s,longdoubleext);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswherePrintfloat10placesdecodedstring;
ext-80-bit(longdouble)floatingnumbertodecode.
Seealso:Printfloat4,Printfloat8,Print3dnow,Printsse
Printsse
Decodes128-bitSSEconsistingof432-bitfloatingpointnumberstoASCIIstring.IfanycomponentisINForNAN,displaysitasahexadecimaldump.Returnslengthofdecodedstring.Notethatthisprocedureissaferthanprintf,becausesomeprintfimplementationsgenerateexceptionwhenprocessingINForNAN.
intPrintsse(char*s,char*f);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswherePrintfsseplacesdecodedstring;
f-pointerto16-bytearraycontainingSSEtodecode.
Seealso:Printfloat4,Printfloat8,Print3dnow
Print3dnow
Decodes64-bit3Dnow!number(consistingoftwo32-bitfloatingnumbers)toASCIIstring.Returnslengthofdecodedstring.
intPrint3dnow(char*s,char*f);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbyteswherePrint3dnowplacesdecodedstring;
f-pointerto8-bytebuffercontaining3Dnow!number.
Seealso:Printfloat4,Printfloat8,Printfloat10,Printsse
IstextA
ReturnsPLAINASCII,DIACRITICALortheircombinationifsymbolcanbepartofvalidASCIItext,and0otherwise.Resultisinfluencedbyoption"Allowdiacriticalsymbolsinstrings".
intIstextA(charc);
Parameters:
c-charactertoanalyze.
Seealso:IstextW,Decodecharacter
IstextW
Returnsnon-zeroifwide(UNICODE)charactercanbepartofvalid(fromtheOllyDbg'spointofview)UNICODEstringand0otherwise.Resultisinfluencedbyoption"Allowdiacriticalsymbolsinstrings".
intIstextW(wchar_tw);
Parameters:
w-widecharactertoanalyze.
Seealso:IstextA,Decodecharacter
Isretaddr
Functioncheckswhetherretaddrisapossiblereturnaddress,thatis,pointstothecommandthatimmediatelyfollowsCALLcommand.IfprocaddrisnotNULL,setsprocaddrtodestinationofCALLorto0ifdestinationisnotconstant.ReturnsaddressofCALLcommandifretaddrisapossiblereturnaddressand0otherwise.
ulongcdeclIsretaddr(ulongretaddr,ulong*procaddr);
Parameters:
retaddr-questionedaddressinmemoryspaceofdebuggedapplication;
procaddr-pointertovariablethatreceivesstartaddressofcalledfunctionorNULL.
Stringtotext
DecodesASCIIdataoflengthndata(notnecessarilyNULL-terminated)intothestringoflengthatleastntextbytesaccordingtothemodeofstringdecodingsetinStringoptions.Decodingstopseitherwhenndatasymbolsareprocessed,orcharacter'\0'isemcountered,orwhenoutputstringisfull.Returnslengthofresultingstringor0onerror.
Note:TherearethreedecodingmodescurrentlysupportedbyOllyDbg:
plain "abcdef"Assembler "abc",LF,"def"C "abc\ndef"
intStringtotext(char*data,intndata,char*text,intntext);
Parameters:
data-pointertoinputASCIIdataoflengthndata;
ndata-lengthofinputdatainbytes;
text-pointertothebufferoflengthatleastntextthatreceivesformatedtext;
ntext-sizeofoutputbufferinbytes.
Datainputfunctions
Thesefunctionsinvokedialogwindowallowingusertoenternumberorstringandspecifyrelatedoptions:
intGetlong(char*title,ulong*data,intdatasize,charletter,intmode);
intGetline(char*title,ulong*data);
intGetfloat10(char*title,longdouble*fdata,char*tag,charletter,intmode);
intGetfloat(char*title,void*fdata,intsize,charletter,intmode);
voidGetasmfindmodel(t_asmmodelmodel[NMODELS],charletter,intsearchall);
intGettext(char*title,char*text,charletter,inttype,intfontindex);
intGethexstring(char*title,t_hexstr*hs,intmode,intfontindex,charletter);
intGetmmx(char*title,char*data,intmode);
intGet3dnow(char*title,char*data,intmode);
intBrowsefilename(char*title,char*name,char*defext,intgetarguments);
Mostofthedatainputfunctionshave...xycounterpartallowingtospecifythepositionofthedialogonthescreen.Internally,non-xyfunctionsjustcallxy-enabledfunctionswithx=-1andy=-1.FunctionGetregxyexistsonlyin...xyform:
intGetlongxy(char*title,ulong*data,intdatasize,charletter,intmode,intx,inty);
intGetlinexy(char*title,ulong*data,intx,inty);
intGetfloat10xy(char*title,longdouble*fdata,char*tag,charletter,intmode,intx,inty);
intGetfloatxy(char*title,void*fdata,intsize,charletter,intmode,intx,inty);
voidGetasmfindmodelxy(t_asmmodelmodel[NMODELS],charletter,intsearchall,intx,inty);
intGettextxy(char*title,char*text,charletter,inttype,intfontindex,intx,inty);
intGethexstringxy(char*title,t_hexstr*hs,intmode,intfontindex,charletter,intx,inty);
intGetregxy(char*title,ulong*data,charletter,intx,inty);
intGetmmxxy(char*title,char*data,intmode,intx,inty);
intGet3dnowxy(char*title,char*data,intmode,intx,inty);
FunctionGettableselectionxyallowstocalculatescreenX-Ycoordinatesforstandard(notuser-drawn)tablewindows:
intGettableselectionxy(t_table*pt,intcolumn,int*px,int*py);
Getlong,Getlongxy
Functionsdisplaydialogallowingusertoenter8-,16-or32-bitintegernumberinanyof3formats:hexadecimal,decimalunsignedordecimalsigned,or(ifbitDIA_HEXONLYisset)inhexadecimalformatonly.Optionalcheckboxes"Entireblock"and"Alignedsearch"arecontrolledbybitsDIA_ASKGLOBALandDIA_ALIGNEDandcontrolglobalflagsglobalsearchandalignedsearch.Return0onsuccessand-1iferroroccuredorusercancelledaction.FunctionGetlongxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGetlong(char*title,ulong*data,intdatasize,charletter,intmode);
intGetlongxy(char*title,ulong*data,intdatasize,charletter,intmode,intx,inty);
Parameters:
title-titleofdialogbox;
data-pointerto32-bitbuffercontaininginitialvalueofintegernumber.Onreturn,buffercontainsenteredvalue.Ifusercancelsaction,valueremainsunchanged;
datasize-sizeofintegernumberinbytes(1,2or4).Notethatdependlessondatasize,bufferpointedtobydatanustbe32bits(4bytes)long;
letter-firstcharactertobeenteredindefaultcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononacharacterenteredbyuser;
mode-combinationofDIA_xxxbitsspecifyingadditionalGetlongfeatures:
DIA_HEXONLY hidedecimalinputwindows
DIA_ASKGLOBALdisplaycheckbox"Entireblock"thatcontrolsglobalsearchflag.ActualstateofthisflagisreturnedbycalltoPlugingetvalue(VAL_GLOBALSEARCH)
DIA_ALIGNED
displaycheckbox"Alignedsearch"thatcontrolsalignedsearchflag.Actualstateofthisflagisreturnedbycallto
Plugingetvalue(VAL_ALIGNEDSEARCH)
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getregxy,Getline,Getfloat,Getfloat10,Getmmx,Get3dnow,Gettableselectionxy
Getline,Getlinexy
Functionsdisplaydialogaskingusertoentersourcelinenumberinunsigneddecimalformat.Return0onsuccessand-1iferroroccuredorusercancelledaction.FunctionGetlinexyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGetline(char*title,ulong*data);
intGetlinexy(char*title,ulong*data,intx,inty);
Parameters:
title-titleofdialogbox;
data-pointerto32-bitbuffercontaininginitialvalueoflinenumber.Onreturn,buffercontainsenteredvalue.Ifusercancelsaction,valueremainsunchanged;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getlong,Getregxy,Getfloat,Getfloat10,Getmmx,Get3dnow,Gettableselectionxy
Getfloat10,Getfloat10xy
Displaydialogaskingusertoenter80-bitfloatingpointnumber,eitherasfloatorashexadecimalcode.PrimarilyorientedoneditingofcontentsofFPUstack.IftagisnotNULL,functionsaskwhethertochangetheassociatedFPUtag.IftagisNULLandbitDIA_ASKGLOBALisset,askwhethertouseglobalsearch.BitDIA_ALIGNEDenablesboxes"Alignedsearch"and"Allow0.1%errormargin".FunctionGetfloat10additionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGetfloat10(char*title,longdouble*fdata,char*tag,charletter,intmode);
intGetfloat10xy(char*title,longdouble*fdata,char*tag,charletter,intmode,intx,inty);
Parameters:
title-titleofdialogbox;
fdata-pointerto80-bitfloatingpointnumber.Onreturn,buffercontainsenteredvalue.Ifusercancelsaction,valueremainsunchanged;
tag-pointertotagassociatedwithFPUregister.Ifuserrequestedchangeofassociatedtag,Getfloat10willsetthistagtovalid,zeroorbaddependingonthecontentsof*fdata;
letter-firstcharactertobeenteredineditcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononanumerickeypressedbyuser;
mode-combinationofDIA_xxxbitsspecifyingadditionalGetfloat10features:
DIA_ASKGLOBALdisplaycheckbox"Entireblock"thatcontrolsglobalsearchflag.ActualstateofthisflagisreturnedbycalltoPlugingetvalue(VAL_GLOBALSEARCH)
DIA_ALIGNED
displaycheckboxes"Alignedsearch"and"Allow0.1%errormargin"thatcontrolalignedsearchandinexactsearchflags.ActualstateoftheseflagsisreturnedbycallstoPlugingetvalue(VAL_ALIGNEDSEARCH)and
Plugingetvalue(VAL_SEARCHMARGIN)
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getlong,Getregxy,Getline,Getfloat,Getmmx,Get3dnow,Gettableselectionxy
Getfloat,Getfloatxy
Displaydialogaskingusertoenterfloatingpointnumberofspecifiedprecision(4,8or10bytes),eitherasfloatorashexadecimalcode.IfbitDIA_ASKGLOBALisset,askwhethertouseglobalsearch.BitDIA_ALIGNEDenablesboxes"Alignedsearch"and"Allow0.1%errormargin".FunctionGetfloatxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGetfloat(char*title,void*fdata,intsize,charletter,intmode);
intGetfloatxy(char*title,void*fdata,intsize,charletter,intmode,intx,inty);
Parameters:
title-titleofdialogbox;
fdata-pointertofloatingpointnumber.Onreturn,buffercontainsenteredvalue.Ifusercancelsaction,valueremainsunchanged;
size-sizeoffloatingpointnumberinbytes(4,8or10);
letter-firstcharactertobeenteredineditcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononakeypressedbyuser;
mode-combinationofDIA_xxxbitsspecifyingadditionalGetfloatfeatures:
DIA_ASKGLOBALdisplaycheckbox"Entireblock"thatcontrolsglobalsearchflag.ActualstateofthisflagisreturnedbycalltoPlugingetvalue(VAL_GLOBALSEARCH)
DIA_ALIGNED
displaycheckboxes"Alignedsearch"and"Allow0.1%errormargin"thatcontrolalignedsearchandinexactsearchflags.ActualstateoftheseflagsisreturnedbycallstoPlugingetvalue(VAL_ALIGNEDSEARCH)andPlugingetvalue(VAL_SEARCHMARGIN)
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatit
remainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getfloat10,Getlong,Getregxy,Getline,Getmmx,Get3dnow,Gettableselectionxy
Getasmfindmodel,Getasmfindmodelxy
Displaydialogboxallowingusertoenterassemblercommand(imprecisecommandsarealsoaccepted)andcreatesetofsearchmodels.Ifusercancelsinput,model[0].lengthis0.FunctionGetasmfindmodelxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
voidGetasmfindmodel(t_asmmodelmodel[NMODELS],charletter,intsearchall);
voidGetasmfindmodelxy(t_asmmodelmodel[NMODELS],charletter,intsearchall,intx,inty);
Parameters:
model-pointerofarrayofNMODELSt_asmmodelstructuresthatreceivessetofmodelscreatedbyGetasmfindmodelonsuccess;
letter-firstcharactertobeenteredineditcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononakeypressedbyuser;
searchall-ifnonzero,hidescheckbox"Entireblock"thatcontrolsglobalsearchflag.ActualstateofthisflagisreturnedbycalltoPlugingetvalue(VAL_GLOBALSEARCH);
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Gettext,Gethexstring,Getlong,t_asmmodel,Gettableselectionxy
MAXCMDSIZE
Constantthatdeterminesmaximalpossiblelengthofthevalid80x86command(16bytes).Youmayarguethatmaximalallowedlengthis15;that'scorrect,but16isapowerof2andsoseemsmorepreferrableinacomputerprogram.
#defineMAXCMDSIZE16//Maximallengthof80x86command
TEXTLEN
Constantthatdeterminesmaximalpossiblelengthofnames,textstringsandmessagesinOllyDbg.Asageneralrule,iffunctionreturnsstringanddoesnotcontainitsmaximallengthasaninputparameter,thesizeofstringbuffermustbeatleastTEXTLENcharacters(or2*TEXTLENbytesforUNICODEstrings).Filenamesareanexception,theyarealwaysMAXPATHbyteslong.Allotherexceptionsfromthisruleareclearlydocumentedhere.
#defineTEXTLEN256//Maximallengthoftextstring
t_asmmodel
Typeofstructurethatkeepsassemblersearchmodel.
typedefstructt_asmmodel{//Modeltosearchforassemblercommand
charcode[MAXCMDSIZE];//Binarycode
charmask[MAXCMDSIZE];//Maskforbinarycode(0:bitignored)
intlength;//Lengthofcode,bytes(0:empty)
intjmpsize;//Offsetsizeifrelativejump
intjmpoffset;//OffsetrelativetoIP
intjmppos;//Positionofjumpoffsetincommand
}t_asmmodel;
Members:
code-binarycodeofthecommand.Onlybitsthathave1'ssetincorrespondingmaskbitsaresignificant;
mask-comparisonmask.Searchroutineignoresallcodebitswheremaskissetto0;
length-lengthofcodeandmask,bytes.Iflengthis0,searchmodelisemptyorinvalid;
jmpsize-ifnonzero,commandisarelativejumpandjmpsizeisasizeofoffsetinbytes;
jmpoffset-ifjmpsizeisnonzero,jumpoffsetrelativetoaddressofthefollowingcommand,otherwiseundefined;
jmppos-ifjmpsizeisnonzero,positionofthefirstbyteoftheoffsetincode,otherwiseundefined.
Seealso:Getasmfindmodel
Gettext,Gettextxy
DisplaydialogboxallowingusertoenteroreditASCIItextstring.Thisdialogcontainscomboboxwithseverallastenteredstringsofspecifiedtype.Forsomepredefinedstringtypes,thesestringsaresavedtothe.uddfile.Returnlengthofenteredstringor-1onerrororwhenusercancelledinput.FunctionGettextxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGettext(char*title,char*text,charletter,inttype,intfontindex);
intGettextxy(char*title,char*text,charletter,inttype,intfontindex,intx,inty);
Parameters:
title-titleofdialogbox;
text-pointertobufferatleastTEXTLENbyteslongthatreceivesenteredstring;
letter-firstcharactertobeenteredineditcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononakeypressedbyuser;
type-typeofsavedstrings(0..255).Somestringtypes(NM_xxxorNM_xxx|NMHISTORY)arepredefined.Ingeneral,itissafetousetypesinrange192..254,ofcourse,iftheyarenotusedbyotherplugins.Contactmeifyouneeduniquetypethatisautomaticallysavedto.uddfile;
fontindex-indexofOllyDbgfontusedineditcontrolandcombobox.UseeitherFIXEDFONTor,ifPlugingetvalue(VAL_WINDOWFONT)returnsnon-zero,indexoffontusedinparentwindow;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Plugingetvalue,Gethexstring,Browsefilename,Gettableselectionxy
Gethexstring,Gethexstringxy
DisplaydialogboxallowingusertoenteroreditmaskedASCII,UNICODEorhexadecimalstring.Return0onsuccessand-1onerrororwhenusercancelledinput.FunctionGethextsringxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGethexstring(char*title,t_hexstr*hs,intmode,intfontindex,charletter);
intGethexstringxy(char*title,t_hexstr*hs,intmode,intfontindex,charletter,intx,inty);
Parameters:
title-titleofdialogbox;
hs-pointertostringdescriptorthatcontainsinitialdatatobedisplayedinthedialogandonexitcontainsmaskedstringenteredbyuser;
mode-combinationofDIA_xxxbitsspecifyingadditionaloptions.OptionsDIA_DEFHEX,DIA_DEFASCIIandDIA_DEFUNICODEaremutuallyexclusive:
DIA_ASKGLOBAL
ifthisbitiscleared,dialogcontains"Keepsize"checkbox;ifbitisset,dialogcontainscheckboxes"Entireblock"thatcontrolsglobalsearchflagand"Casesensitive"thatcontrolscaseignoringflag.ActualstateofthesethreeflagsisreturnedbycallstoPlugingetvalue(VAL_KEEPSELSIZE),Plugingetvalue(VAL_GLOBALSEARCH)andPlugingetvalue(VAL_IGNORECASE)
DIA_DEFHEX defaultdatatypeishexadecimalDIA_DEFASCII defaultdatatypeisASCIIDIA_DEFUNICODE defaultdatatypeisUNICODE
fontindex-indexofOllyDbgfontusedineditcontrolsandcomboboxes.UseeitherFIXEDFONTor,ifPlugingetvalue(VAL_WINDOWFONT)returnsnon-zero,indexoffontusedinparentwindow;
letter-firstcharactertobeenteredinactiveeditcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononakeypressedbyuser;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Plugingetvalue,Gettext,Browsefilename,t_hexstr,Gettableselectionxy
t_hexstr
Typeofstructurethatkeepsmaskedbinarystring.
typedefstructt_hexstr{//Stringusedforhex/textsearch
intn;//Stringlength
chardata[TEXTLEN];//Data
charmask[TEXTLEN];//Mask,0bitsaremasked
}t_hexstr;
Members:
n-lengthofthestringinbytes;
data-arraywithstringdata.Onlythosedatabitsaresignificantwhichhas1incorrespondingbitsofmask;
mask-arraywithmaskdata.
Seealso:Gethexstring
Getregxy
SimilartoGetlongxy,displaydialogallowingusertoenter32-bitintegernumberinanyof4formats:hexadecimal,decimalunsigned,decimalsignedorasasetof4characters.Intendedprimarilytoeditcontentsofgeneral-purposeregistersEAX,EBX,CXandEDX.Returns0onsuccessand-1iferroroccuredorusercancelledaction.
intGetregxy(char*title,ulong*data,charletter,intx,inty);
Parameters:
title-titleofdialogbox;
data-pointerto32-bitbuffercontaininginitialvalueofintegernumber.Onreturn,buffercontainsenteredvalue.Ifusercancelsaction,valueremainsunchanged;
letter-firsthexadecimalcharactertobeenteredinhexcontrol,or0ifthereisnocharacter.Usefuliffunctioniscalledasareactiononacharacterenteredbyuser;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getlongxy,Getline,Getfloat,Getfloat10,Getmmx,Get3dnow,Gettableselectionxy
Getmmx,Getmmxxy
Displaydialogboxallowingusertoenteroredit64-bitMMXnumberasacombinationof8-,16-or32-bitintegersinsigneddecimal,unsigneddecimalorhexadecimalformats.Return0onsuccessand-1onerrororwhenusercancelledinput.FunctionGetmmxxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGetmmx(char*title,char*data,intmode);
intGetmmxxy(char*title,char*data,intmode,intx,inty);
Parameters:
title-titleofdialogbox;
data-pointerto64-bit(8-byte)memoryareacontaininginitialvalueofMMXnumber.Onexit,containsnumbermodifiedbyuser;
mode-reserved,mustbe0;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getlong,Getregxy,Getfloat,Getfloat10,Get3dnow,Gettableselectionxy
Get3dnow,Get3dnowxy
Displaydialogboxallowingusertoenteroredit64-bit3DNow!numberasacombinationoftwofloating-pointorhexadecimal32-bitnumbers.Return0onsuccessand-1onerrororwhenusercancelledinput.FunctionGet3dnowxyadditionallycontainsthepreferredscreencoordinatesofthebottomleftpointofthedialogwindow.
intGet3dnow(char*title,char*data,intmode);
intGet3dnowxy(char*title,char*data,intmode,intx,inty);
Parameters:
title-titleofdialogbox;
data-pointerto64-bit(8-byte)memoryareacontaininginitialvalueof3DNow!number.Onexit,containsnumbermodifiedbyuser;
mode-reserved,mustbe0;
x-absoluteXscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.Ifnecessary,dialogwillautomaticallyadjustitspositionsothatitremainsvisible;
y-absoluteYscreencoordinate,inpixels,ofthebottomleftcornerofthedialogwindow.
Seealso:Getlong,Getregxy,Getfloat,Getfloat10,Getmmx,Gettableselectionxy
Gettableselectionxy
Calculatesscreencoordinatesofthelefttopcornerofthefirstvisibleselectedlineinthespecifiedcolumnoftablewindow.Returns0onsuccessand-1ifcoordinatescannotbecomputedortableisuser-defined.
Note:thisfunctionfailsiftableisuser-defined!
intGettableselectionxy(t_table*pt,intcolumn,int*px,int*py);
Parameters:
pt-pointertodescriptoroftablewindow;
column-columnintable;
px-pointertovariablethatreceivesXcoordinate(inpixelsofthescreen).Eitherpxorpy(butnotboth)canbeNULL;
py-pointertovariablethatreceivesYcoordinate(inpixelsofthescreen).
Seealso:Datainputfunctions
Browsefilename
Opensdialogboxallowingusertoselectfilenameandadditionalfile-relatedoptions,accordingtospecifiedmode.Inmodes0,1and2returnsTRUEifvalidfilewasselectedandFALSEinanyothercase.
intBrowsefilename(char*title,char*name,char*defext,intmode);
Parameters:
title-titleofdialogbox;
name-pointertobuffercontaininginitialfilename,atleastMAXPATHbyteslong.Onexit,containsnameoffileselectedbyuser;
defext-pointertostringcontainingsetofoneorseveraldefaultextentions.Firstextentionmuststartwithpoint('.').Tospecifyseveralextentions,separatethemwithverticalline('|').Tospecifyseveralextentionsasasingleselection,separatethemwith";*"(like".exe;*.dll").Browsefilenameknowsseveraltypesofextentionsandtheircombinationsandautomaticallycommentsthem;
mode-modeofoperation.Modes3to8arenotintendedforuseinpluginsandarenotdescribedhere:
0 standarddialogwithoutadditionalelements1 dialogwithcombobox"Arguments"2 dialogwithcheckbox"Appendtoexistingfile"
Newinversion1.10:ifmodeisORedwith0x80,BrowsefilenameopensSaveFiledialoginsteadofOpenFile.
Sorteddatafunctions
ManykindsofinternalOllyDbgdataconsistofhomogenouselementsthathasstartandfinaladdressanddonotoverlapwitheachother.Goodexampleisthetableofmemoryblocks.Breakpointsmaybetreatedaselementsoccupying1byteinmemoryspaceofdebuggedprogram.Threadsexistintheaddressspaceofthreadidentifiersandalsooccupy1addressofthisspace.Elementsusuallycanbedisplayedinsomewindowandsortedusingsomecriterium.Setofsuchelementsiscalledsorteddata.
OllyDbgimplementsapowerfulsetoffunctionsthatalloweasyoperationswithsorteddata,likeinitilaization,addingorreplacingofelements,removingofelementsoraddressranges,sorting,searchandsoon.OllyDbgautomaticallyallocatesnewmemoryforsorteddataifnecessary.
Elementsofsorteddataarealwayskeptsortedbyaddressinacontiguousbuffer.Thisallowsforsimpleandextremelyfastbinarysearch.Addingnewdatais,ofcourse,notsoeasyandcantakesignificanttime.Weightedbinarytreesmaylookasabettersolution,butinourcasedataisreadmuchmorefrequentlythanaddedtothetable.Ifyousortdatabymethodotherthanincreasingaddresses,OllyDbgsimplycreatesadditionalarrayofindexespointingtodataelements.
Allelementsofsorteddatabeginwithastandard12-byteheader:
typedefstructt_sortheader{//Headerofsorteddatafield
ulongaddr;//Baseaddressoftheelement
ulongsize;//Sizeoccupiedbyelementinaddressspace
ulongtype;//Typeofdataelement,TY_xxx
}t_sortheader;
Pleasedon'tmixthesizespecifiedinthisheaderandphysicalsizeoftheelement.Theybelongtodifferentaddressspaces!Sizeinheaderisthesizeofpieceofvirtualaddressspacedescribedbysorteddataandusuallybelongstodebuggedprogram.PhysicalsizeofelementisthesizeofmemoryocuppiedbyelementintheOllyDbg'smemory.Allelementshavesamephysicalsize
necessarytofitallthecharacteristicsanddescriptionsofthedescribedobject;sizeinheaderissimplyone(albeitmostimportant)oftheobject'scharacteristicsandmaybedifferentforeachobject.
Inmostcasessorteddatafunctionsignoretypeandyoumayuseitasyouwant.OnlyDeletenonconfirmedsorteddatachecksforbitTY_CONFIRMEDandremovesatonceallelementswherethisbitisnotset(averyfastwaytogetridofunnecessaryelements).Standardheadercanbefollowedbyanyadditionalfields.OllyDbgdoesnotalignsdataelements;toassureeffectivememoryaccess,makephysicalsizeofelementamultipleof4bytes.
Thereisaspecialkindofsorteddatacalledautoarrangeable.Autoarrangeabledataassumesthataddressoftheelementissimplyits0-basedordinalnumberinthedataarrayandsizeoccupiedbyelementinaddressspaceisalways1.Eveninthiscase,elementsmustbeginwithvalidheader.Addsorteddataalwaysinsertsnewitemstoautoarrangeabledataandneverreplacesexisting.
Tocreateyourowntableofsorteddata,firstofallyoumustallocatetabledescriptor(structureoftypet_sorted)andinitializeallitsfieldsto0.ThenyoucallCreatesorteddatatoinitializetableandallocatedatabuffers.Afterinitialization,youcanuseallsorteddatafunctionstochangeorretrievedata.Donotmodifyitemsoftabledescriptordirectly,thismayleadtoseveredataintegrityproblems!
Indexarrayisallocatedonlyifvalidsortfuncisspecified.Toassurethatsorteddataisvalidandcorrectlyinitialized,checkthatdatapointerisnotNULL.Ifnis0,tableisempty(butisnotnecessarilyinitialized).
Tableversionincrementsby1eachtimetableofsorteddatachanges.Thisallowsforeasyimplementationofsmallcache:ifversionisnotchanged,previouslyfetcheddataisstillvalid.Inanyimaginableapplication,wraparoundof32-bitvariableisimpossible.Createsorteddatainitializesversionto1,sosetcacheversionto0toindicatethatcacheisinvalid.
Ifsortedis0,indextablewasnotupdatedafterlastmodificationofthedata.Toforcesorting,callSortsorteddata.Ifdataisalreadysorted,Sortsorteddatareturnsimmediately.
intCreatesorteddata(t_sorted*sd,char*name,intitemsize,intnmax,SORTFUNC*sortfunc,DESTFUNC*destfunc);
voidDestroysorteddata(t_sorted*sd);
void*Addsorteddata(t_sorted*sd,void*item);
voidDeletesorteddata(t_sorted*sd,ulongaddr);
voidDeletesorteddatarange(t_sorted*sd,ulongaddr0,ulongaddr1);
intDeletenonconfirmedsorteddata(t_sorted*sd);
void*Findsorteddata(t_sorted*sd,ulongaddr);
void*Findsorteddatarange(t_sorted*sd,ulongaddr0,ulongaddr1);
intFindsorteddataindex(t_sorted*sd,ulongaddr0,ulongaddr1);
intSortsorteddata(t_sorted*sd,intsort);
void*Getsortedbyselection(t_sorted*sd,intindex);
t_sorted
Typeofdescriptorofsorteddata.
typedefstructt_sorted{//Descriptorofsortedtable
charname[MAXPATH];//Nameoftable,asappearsinerrormessages
intn;//Actualnumberofentries
intnmax;//Maximalnumberofentries
intselected;//Indexofselectedentryor-1
ulongseladdr;//Baseaddressofselectedentry
intitemsize;//Sizeofsingleentry
ulongversion;//Uniqueversionoftable
void*data;//Elements,sortedbyaddress
SORTFUNC*sortfunc;//FunctionwhichsortsdataorNULL
DESTFUNC*destfunc;//DestructorfunctionorNULL
intsort;//Sortingcriterium(column)
intsorted;//Whetherindexesaresorted
int*index;//Indexes,sortedbycriterium
intsuppresserr;//Suppressmultipleoverflowerrors
}t_sorted;
Members:
name-nameofthesorteddata,ofnorealimportance.Youcansetittoemptystringoruseforyourownpurposes;
n-actualnumberofelementsinsorteddata;
nmax-maximalnumberofelementsthatfitinallocatedmemory.Ifnecessary,sorteddatafunctionsallocateadditionalmemorytofitnewelements;
selected-indexofselectedentryindatasortedbyspecifiedcriterium.Onlywhent_sorted.sortedisNULLordataissortedbyaddress,thisindexcoincideswithindexint_sorted.data;
seladdr-baseaddressofselectedelement;
itemsize-sizeofelementofsorteddatainbytes;
version-variablethatincrementsby1eachtimethecontentsofsorteddataischanged.Onecanuseversiontoavoidunnecessarysearchesinsorteddata:aslongasversionremainsunchanged,pointerstoelementsofsorteddataarevalid.Createsorteddatainitializesversionto1;
data-pointertocontiguousbufferthatcontainselementsofsorteddatasortedbyaddress.IfdataisNULL,sorteddataisnotinitialized;
sortfunc-pointertofunctionthatsortsdatabygivencriterium,orNULLifdataisnotsortable.SeeSORTFUNC;
destfunc-pointertodestructorfunctionthatfreesresourcesallocatedbyelementofsorteddata,canbeNULLifelementdoesn'tallocateresources.SeeDESTFUNC;
sort-actualsortingcriterium.OllyDbgpassesthisparametertosortfunc;
sorted-flagindicatingwhetherindexarrayisactual;
index-arraycontainingindexesofelementssortedbyspecifiedcriterium.NULLifdataisnotinitializedorsortfuncisNULL;
suppresserr-flagpreventingfrommultipleerrorreports.
Seealso:Sorteddatafunctions
Createsorteddata
Initializesdescriptorofsorteddata(structuret_sorted).Ifdescriptoralseadycontainsdata,thisdataisdestroyed.Returns0onsuccessand-1onerror.
intCreatesorteddata(t_sorted*sd,char*name,intitemsize,intnmax,SORTFUNC*sortfunc,DESTFUNC*destfunc);
Parameters:
sd-pointertodescriptorofsorteddata;
name-optionalnameofsorteddata,canbeNULL.OllyDbgusesthisnameonlyinsomerarecases;
itemsize-size,inbytes,oftheelementofsorteddata(includingstandardheader);
nmax-initialnumberofdataelementsthatallocatedbuffercankeep.Ifnecessary,OllyDbgwillautomaticallyallocateadditionalmemory;
sortfunc-pointertofunctionthatcomparestwodataelementsaccordingtosortingcriterium,orNULLifdatacannotbesorted.Thiscriteriumisusuallytheindexofcolumnintablewindow.IfyouspecifyAUTOARRANGE,dataisautoarrangeable,thatis,assumesthataddressoftheelementissimplyits(0-based)ordinalnumberinthedataandsizeofelementisalways1.Eveninthiscase,elementmustbeginwithvalidheader.Addsorteddataalwaysinsertsnewitemstoautoarrangeabledataandneverreplacesexisting;
destfunc-pointertofunctionthatiscalledforeachelementbeingremovedfromthetable,orNULLifdestructorisnotnecessary.Youneeddestfunc,forexample,ifelementsofsorteddataallocateadditionalmemorythatmustbefreedbeforeelementisdeleted.
Seealso:Destroysorteddata,SORTFUNC,DESTFUNC
SORTFUNC
TypeofoptionalcallbackfunctionusedbyOllyDbgtosortelementsofsorteddataaccordingtosomecriterium.Thisfunctionreceivestwopointerstoelementsofsorteddataandsortcriterium(whichisusuallytheindexofcolumninthewindowdisplayingsorteddata).Functionmustreturn0ifelementsareequal,1iffirstelementisgreater(comeslater)and-1iffirstelementislessthanthesecond(comesearlier).
AspecialpredefinedsortpseudofunctionAUTOARRANGEmakessorteddataautoarrangeable.SeeCreatesorteddatafordetails.
typedefintSORTFUNC(constt_sortheader*p1,constt_sortheader*p2,constintsort);
Parameters:
p1-pointertothefirstelement;
p2-pointertothesecondelement;
sort-sortcriterium.Irecommendthatyouuse0tosortdatabyaddress.
Seealso:Createsorteddata,Sortsorteddata
DESTFUNC
TypeofoptionalcallbackfunctionusedbyOllyDbgtofreeresourcesallocatedbyelementofsorteddatawhenelementisremoved.CorrespondstodestructorinC++objects.
typedefvoidDESTFUNC(t_sortheader*pe);
Parameters:
pe-pointertotheelementofsorteddatatoberemoved.
Seealso:Createsorteddata
Destroysorteddata
Removesallelementsfromthesorteddataanddeallocatesdatamemory.Ifsorteddatahasdestructorfunction,thisdestructorwillbecalledforeachdeletedelement.
voidDestroysorteddata(t_sorted*sd);
Parameters:
sd-pointertodescriptorofsorteddata.
Seealso:Createsorteddata
Addsorteddata
Addsorreplaceselementininitializedsorteddata.ReturnspointertoiteminthedataifitemiscorrectlyaddedorreplacedandNULLifeitherinputparametersareinvalid,databufferisfullandOllyDbgisunabletoallocatemorememory,newelementcannotreplaceoldbecauseitisneithersubsetnorsupersetoftheolditem,oritoverlapswithtwoormoreexistingelements.Thispointerisvalidtillthenextoperationthataddsorremovesdata.Donotchangeaddressorsizeofelementafteritisaddedtosorteddata,thismayleadtoseveredataintegrityproblems.
void*Addsorteddata(t_sorted*sd,void*item);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata;
item-pointertonewelement.
Seealso:Deletesorteddata,Deletesorteddatarange,Findsorteddata,Findsorteddatarange,Findsorteddataindex
Deletesorteddata
Deleteselementwhichbeginsexactlyatspecifiedaddressfromsorteddata.
voidDeletesorteddata(t_sorted*sd,ulongaddr);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata;
addr-addressofelement.
Seealso:Deletesorteddatarange,Addsorteddata,Findsorteddata,Findsorteddatarange,Findsorteddataindex
Deletesorteddatarange
Deletesallelementswhichcontainatleast1addresswithinthespecifiedrangefromthetableofsorteddata.
voidDeletesorteddatarange(t_sorted*sd,ulongaddr0,ulongaddr1);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata;
addr0-startofaddressrange(included);
addr1-endofaddressrange(notincluded).
Seealso:Deletesorteddata,Addsorteddata,Findsorteddata,Findsorteddatarange,Findsorteddataindex
Deletenonconfirmedsorteddata
DeletesallelementswithtypebitTY_CONFIRMEDresetto0fromsorteddataandresetsthisbitinallremainingelements.Returnsnumberofdeleteditems.Thisisusuallythefastestwaytodeletemultiplenon-adjacentelementsfromthesorteddata.Autoarrangeabledatacannotbedeletedinthisway.
intDeletenonconfirmedsorteddata(t_sorted*sd);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata.
Seealso:Deletesorteddata,Deletesorteddatarange
Findsorteddata
Searchesforelementcontainingspecifiedaddressinsorteddata.ReturnspointertofounditemonsuccessandNULLonerrororwhenthereisnosuchitem.Returnedpointerisvalidtillthenextoperationthataddsorremovesdata.Donotchangeaddressorsizeofelement,thismayleadtoseveredataintegrityproblems.
void*Findsorteddata(t_sorted*sd,ulongaddr);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata;
addr-addressintheaddressspaceofspecifiedsorteddata.
Seealso:Findsorteddatarange,Findsorteddataindex,Getsortedbyselection
Findsorteddatarange
Searchesforthefirstelementofsorteddatacontainingaddresswithinthespecifiedrange.ReturnspointertofounditemonsuccessandNULLonerrororwhenthereisnosuchitem.Returnedpointerisvalidtillthenextoperationthataddsorremovesdata.Donotchangeaddressorsizeofelement,thismayleadtoseveredataintegrityproblems.
void*Findsorteddatarange(t_sorted*sd,ulongaddr0,ulongaddr1);
Parameters:
sd-pointertoinitializeddescriptorofsorteddata;
addr0-startofaddressrangeintheaddressspaceofspecifiedsorteddata(included);
addr1-endofaddressrangeintheaddressspaceofspecifiedsorteddata(notincluded).
Seealso:Findsorteddata,Findsorteddataindex,Getsortedbyselection
Findsorteddataindex
Searchesforthefirstelementofsorteddatacontainingaddresswithinthespecifiedrange.Returnsindexoffounditemonsuccessand-1onerrororwhenthereisnosuchitem.Indexisvalidtillthenextoperationthataddsorremovesdata.
intFindsorteddataindex(t_sorted*sd,ulongaddr0,ulongaddr1);
Parameters:
sd-pointertodescriptorofsorteddata;
addr0-startofaddressrangeintheaddressspaceofspecifiedsorteddata(included);
addr1-endofaddressrangeintheaddressspaceofspecifiedsorteddata(notincluded).
Seealso:Findsorteddata,Findsorteddatarange,Getsortedbyselection
Sortsorteddata
Sortssorteddataaccordingtothespecifiedsortcriteriumandsavesresultstotheindexarrayassociatedwithsorteddata.Returns1ifdatawasupdatedand0otherwise.
intSortsorteddata(t_sorted*sd,intsort);
Parameters:
sd-pointertodescriptorofsorteddata;
sort-sortcriterium.
Seealso:Createsorteddata,Getsortedbyselection,SORTFUNC
Getsortedbyselection
Returnspointertoelementwithspecifiedindexinsorteddatasortedbyactualcriterium,orNULLonerror.Ifnecessary,functionactualizesassociatedindextable,sopreliminarycalltoSortsorteddataisnotnecessary.Functionisveryusefulforextractionofselectedelementintablewindows.
void*Getsortedbyselection(t_sorted*sd,intselection);
Parameters:
sd-pointertodescriptorofsorteddata;
selection-zero-basedindexindatasortedbyselectedsortcriterium.
Seealso:Sortsorteddata,Findsorteddata,Findsorteddatarange
Windowfunctions
AllMDIwindowsinOllyDbgarethesocalledtablewindows.Theyhaveupto17resizablecolumns,unlimitednumberofrowsandhideablebarwhichcanactasastringofbuttons.OllyDbgsupportsresizingofcolumnsandscrollingoftablewindows.Forsimpletablewindows,itautomaticallyaddspossibilitytocopywholetable,roworsingleelementtoclipboardwithoutextracode.TablewindowssupportUNICODE,highlightingandselectionandseveralpseudographicalsymbols.Usercanselectfontandcolourscheme,andsoon.
Ordinarytablewindowsdisplaycontentsofsorteddata.OllyDbgmakesitespeciallyeasyfortheprogrammer,oneonlyneedstosupplyseveralrelativelysimplefunctions.Forexample,functionthatimplementsWM_PAINTfunctionalitysimplyreturnstexttobedrawninspecifiedcell,andfunctionthatallowstosortcontentsofwindowjustcomparestwoelementsofsorteddata.
Custom(user-defined)tablewindowsmaydisplayanydata.DisassemblerandDumparegoodexamplesofcustomwindows.TheyalsoobtainplentyofsupportfromOllyDbg,butrequiresignificantlymoreprogramming.
Tablewindowsaredescribedbystructuret_table.Itisontheresponsibilityoftheprogrammertomaintaindataincustomwindows.Registerpluginclassallocates8additionallongwordsaccessiblebySetWindowLongandGetWindowLong.Firsttwolongwords(withoffsets0and4)arereservedforinternaluse.Youcanfreelyuseremainingoffsets8,12,...,28.
typedefintDRAWFUNC(char*s,char*mask,int*select,t_sortheader*ps,intcolumn);
voidDefaultbar(t_bar*pb);
intTablefunction(t_table*pt,HWNDhw,UINTmsg,WPARAMwp,LPARAMlp);
voidPainttable(HWNDhw,t_table*pt,DRAWFUNCgetline);
voidSelectandscroll(t_table*pt,intindex,intmode);
voidSendshortcut(intwhere,ulongaddr,intmsg,intctrl,intshift,intvkcode);
HWNDNewtablewindow(t_table*pt,intnlines,intmaxcolumns,char*winclass,char*wintitle);
HWNDQuicktablewindow(t_table*pt,intnlines,intmaxcolumns,char*winclass,char*wintitle);
intBroadcast(UINTmsg,WPARAMwp,LPARAMlp);
HWNDCreatedumpwindow(char*name,ulongbase,ulongsize,ulongaddr,inttype,SPECFUNC*specdump);
voidSetdumptype(t_dump*pd,inttype);
voidDumpbackup(t_dump*pd,intaction);
HWNDCreatewatchwindow(void);
HWNDCreatewinwindow(void);
HWNDCreatertracewindow(void);
HWNDCreatethreadwindow(void);
HWNDCreatepatchwindow(void);
Createwatchwindow
Createsneworbringstotopexistingwindowthatcontainswatches.Onlyonesuchwindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.
HWNDCreatewatchwindow(void);
Createwinwindow
Createsneworbringstotopexistingwindowthatlistsallwindows(includingchilds)createdbydebuggedapplication.Onlyonesuchwindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.
HWNDCreatewinwindow(void);
Createthreadwindow
Createsneworbringstotopexistingwindowthatlistsallthreadsofdebuggedapplication.Onlyonesuchwindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.
HWNDCreatethreadwindow(void);
Createpatchwindow
Createsneworbringstotopexistingwindowthatlistspatchesappliedtodebuggedapplicationincurrentandprevioussessions.Onlyonesuchwindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.
HWNDCreatepatchwindow(void);
t_table
Typeofdescriptoroftableofsorteddata.Startingfromtheversion1.08,thisstructurecontainstwonewelements:colselandhilite.Tokeepitbackwardcompatiblewithpreviousversions,Ihavesplittedhscrollandschemeintotwoshort16-bitvariableseach.
typedefstructt_table{//Windowwithsorteddataandbar
HWNDhw;//HandleofwindoworNULL
t_sorteddata;//Sorteddata
t_barbar;//Bar
intshowbar;//Bar:1-displayed,0-hidden,-1-absent
shorthscroll;//Horiz.scroll:1-displayed,0-hidden
shortcolsel;//ActivecolumninTABLE_COLSELwindow
intmode;//CombinationofbitsTABLE_xxx
intfont;//Fontusedbywindow
shortscheme;//Colourschemeusedbywindow
shorthilite;//Codehighlightingschemeusedbywindow
intoffset;//Firstdisplayedrow
intxshift;//ShiftinXdirection,pixels
DRAWFUNC*drawfunc;//Functionwhichdecodestablefields
}t_table;
Members:
hw-handleofwindowthatdisplayscontentsofthetable,orNULLifthereisno
associatedwindow;
data-descriptorofsorteddata;
bar-descriptorofcolumnsandbarbuttonsinthewindow;
showbar-statusofthebarinwindow:1-barvisible,0-hidden,-1-barispermanentlyhidden;
hscroll-flagindicatingpresenceofthehorizontalscrollinthewindow;
colsel-columnwithselectioninTABLE_COLSELwindow.Ordinarysorteddatawindowsselectcompleterow;TABLE_COLSELwindowsselectsinglecellinthetable;
mode-combinationofbitsTABLE_xxxdescribingadditionaltableproperties.Pluginscanusefollowingbits:
TABLE_DIRBottom-to-toptablewithreversedorderoflines.Logwindowisanexampleofthebottom-to-toptable
TABLE_COPYMENUAttachcopymenuitemTABLE_SORTMENU AttachsortmenuTABLE_APPMENU AttachappearancemenuTABLE_WIDECOL AttachwidecolumnsmenuitemTABLE_USERDEF User-drawntableTABLE_NOHSCR Tablecontainsnohorizontalscroll
TABLE_SAVEPOS Savepositionofwindowtothe.inifile
TABLE_FASTSEL UpdatewhelselectionchangesTABLE_HILMENU AttachhighlightingmenuTABLE_ONTOP AttachAlwaysontopmenu
font-indexoffontusedtopaintwindow;
scheme-colourschemeusedtopaintwindow;
hilite-codehighlightingschemeusedtodisplaydisassembledcode,or0if
highlightingisdisabledornotapplicable;
offset-indexoffirstrowvisibleinthewindow;
xshift-horizontalshiftinpixels;
drawfunc-functionthatpreparesdatausedtopaintwindow,seeDRAWFUNC.
DRAWFUNC
Typeofpointertocallbackfunctionthatpreparesdataforpaintingintablewindows.Givenlineandcolumn,functionmustprepareASCIIorUNICODEstringthatwillbedisplayedontheirintersection.Ifstringcontainsgraphicalsymbols,orwhenitusesdifferentcolors,functionmustfillmaskwithindividualgraphicalattributesforeachcharacter.Functionreturnsnumberofcharacters(UNICODE:widecharacters)inpreparedstring.Stringisnotnecessarilynull-terminated.
Forstandardtablewindows(bitTABLE_USERDEFint_table.modeiscleared),parameterpspointsdirectlytotheelementofsorteddata.
Foruser-definedtablewindow(TABLE_USERDEFisset),psisapointertothestructuret_tablethatdescribesthiswindow.BeforeOllyDbgcallsDRAWFUNC,itsetst_table.offsettotheindexofcurrentlyprocessedlineintablewindow(topmostdisplayedlinehasindex0)andsetstable.data.ntothetotalnumberofcompletelyorpartiallyvisiblelines.Drawingfunctioniscalledonceforeverycrossingofvisiblerowwithvisiblecolumn.Individualdecodingofeachitemmayimposesevereoverheadandmakedrawingslow.SoOllyDbgsetstable.data.netonlyonceatthebeginningofthesequence.Drawingfunctionmayuseitasacommandtopreparetheentireblockofrequesteddatainsomestaticbufferandthenresetnto0.ItisguaranteedthatsequenceofcallstoDRAWFUNCwillnotbeinterruptedbycallwithdifferentt_table.
Toimplementscrollingincustomwindow,itswindowproceduremustprocessseveralcustommessages.
typedefintDRAWFUNC(char*s,char*mask,int*select,t_sortheader*ps,intcolumn);
Parameters:
s-pointertobufferforoutputstringofsizeatleast2*TEXTLENcharacters.LengthofreturnedstringmustnotexceedTEXTLENASCIIorUNICODEcharacters.IffunctionreturnsUNICODEstring,itmustsetbitDRAW_UNICODEin*select.Stringisnotnecessarilynull-terminated;
mask-arrayofindividualgraphicalattributesforeverycharacterinoutput
string.OllyDbgusesmaskonlyifDRAWFUNCsetsbitDRAW_MASKin*select.EachbyteofthemaskisacombinationofbitsDRAW_xxx,seedetaileddescriptionbelow;
select-pointertographicalattributescommontoallcharactersinoutputstring.*selectisacombinationofbitsDRAW_xxx,seedetaileddescriptionbelow;
ps-forstandardtablewindows(withoutattributeTABLE_USERDEF),pointertotheelementofsorteddatatobedecoded.Forcustom(user-defined)windows,castpstopointertostructuret_tablethatdescribescustomwindow,seedetaileddescriptionabove;
column-zero-basedindexoftheprocessedcolumn.Notethatifcolumnisnotvisibleatall,OllyDbgdoesnotcallDRAWFUNC.
MeaningofbitsDRAW_xxx
MaskandselectconsistofcombinationofbitsDRAW_xxx.Theyaresummarizedinthetablebelow.Notethatbitswhicharenotallowedinthemaskmayhavevaluesthatdon'tfitintobyte:
Bitallowedin: select mask DRAW_NORMAL * * normalplaintextDRAW_GRAY * * grayedtextDRAW_HILITE * * highlightedtextDRAW_UL * underlinedtextDRAW_SELECT * * selectedbackgroundDRAW_EIP * * invertednormaltext/backgroundDRAW_BREAK * * breakpointbackgroundDRAW_GRAPH * graphicalsymbol,seebelow
DRAW_DIRECT * directtextandbackgroundcolourindices
DRAW_MASK * useindividualmaskattributesforeachsymbol
DRAW_EXTSEL * extendselectionfromlastmasktillendofcolumn
DRAW_UNICODE * textisinUNICODE
DRAW_TOP * drawtophalfofthetextshifted1/2rowdown
DRAW_BOTTOM * drawbottomhalfofthetextshifted1/2rowup
Ifentirestringhassamehighlightandselectionattributes,don'tsetDRAW_MASK.OllyDbgignoresmaskandusesonlyattributesfrom*select.AttributesDRAW_NORMAL,DRAW_GRAYandDRAW_HILITEaremutuallyexclusive.YoucannotsetDRAW_EIPtogetherwitheitherDRAW_SELECTorDRAW_BREAK.IfbitsDRAW_BREAKandDRAW_SELECTaresetsimultaneously,backgroundcorrespondstothatofconditionalbreakpoint.
Tohighlightandselecteachcharacterindividually,setDRAW_MASKin*selectandfillinthemaskwithcombinationofbitsdescribingcorrespondingcharacterinoutputstring.BitDRAW_HILITEinthemaskhaspriorityover*select.BitsDRAW_GRAY,DRAW_SELECT,DRAW_EIPandDRAW_BREAKin*selecthavepriorityoverremainingbitsinmask.Maskalsoallowstodrawpseudographicalcharacters.IfDRAW_GRAPHbitisset,characterisdecodedinaspecialway:
Symbol Char MeaningD_SPACE 'N' spaceD_SEP '' thinverticalseparatinglineD_POINT '.' pointD_BEGIN 'B' beginofprocedure,looporstackscopeD_BODY 'I' bodyofprocedure,looporstackscopeD_ENTRY 'J' loopentrypointD_LEAF 'K' IntermediateleafonatreeD_END 'E' endofprocedure,looporstackscopeD_SINGLE 'S' scopeconsistingofsinglelineD_ENDBEG 'T' beginandendofstackscopeD_JMPUP 'U' smallthinarrowupstairs(jumpupstairs)D_JMPOUT '<' shortdash(jumptodifferentmodule)
D_JMPDN 'D' smallthinarrowdownstairs(jumpdownstairs)
D_PATHUP 'u' startofhighlightedjumppathupstairsD_GRAYUP 'v' startofgrayedjumppathupstairsD_PATHDN 'd' startofhighlightedjumppathdownstairsD_GRAYDN 'e' startofgrayedjumppathdownstairsD_PATH 'i' bodyofhighlightedjumppathD_GRAYPATH 'j' bodyofgrayedjumppathD_PATHUPEND 'r' endofhighlightedjumppathupstairsD_GRAYUPEND 's' endofgrayedjumppathupstairsD_PATHDNEND 'f' endofhighlightedjumppathdownstairsD_GRAYDNEND 'g' endofgrayedjumppathdownstairsD_PATHPTUP 'a' jumpentryupstairs(highlighted)D_PATHPTDN 'h' jumpentrydownstairs(highlighted)D_PATHEND 'z' two-sidedendofjump(highlighted)D_SWTOP 't' startofswitchD_SWBODY 'b' switchbodyD_CASE 'c' intermediateswitchcaseD_LASTCASE 'l' lastswitchcase
Anyothercharacterisdisplayedasspace.
OllyDbgallowsdirectsettingofforegroundandbackgroundcolourforeachcharacterinthestring.Tousethisfeature,allowmaskin*selectandfillcorrespondingmaskbyteswiththefollowingdata:
DRAW_DIRECTORedwithbackgroundcolourORedwithforegroundcolour,
wherebackgrondcolourisoneofBKxxxconstantsdefinedinplugin.h(BKTRANSPfordefaultbackground),andforegroundcolourisanycolourinrange0..15.Colours16to19arenotsupported.Youcan'tcombineDRAW_DIRECTwithanyotherDRAW_xxxflagsinthemask.
IfbitBAR_SHIFTSELissetfortheactualcolumn,backgroundwillbeshifted1/2charactertotheleft.Thisisanicetrickallowingbetterhighlighting.Inthiscaseassurethatlasthighlightedcharacterisaspace.
OllyDbg'sRegisterwindowisalsoacustomtablewindow.PleasehaveacloselookonEIPandEFL:theyareshifteddownby1/2line!Howisitpossible?Well,hereIuseanothertrick:Idrawtheselinestwice,firsttimewithbitDRAW_TOPandsecondtimewithbitDRAW_BOTTOM.However,thistrickisrelativelytime-consuming,andmousewillselectwithineachcompleteline.Idonotrecommendeditforthefuture.
Defaultbar
Setsdefaultwidthsofthecolumnsintablewindowinaccordancewithcurrentlyselectedfont.Youmustredrawwindowtomakeeffectofthisfunctionvisible.
voidDefaultbar(t_bar*pb);
Parameters:
pb-pointertobardescriptor.
Tablefunction
Defaultwindowfunctionforalltablewindows,implementsmostoftheirfunctionality.CallitonlyasareactiononreceivedWM_xxxmessage.Returnvaluedependsonthemessage,itissafetopassthisvaluetotheoperatingsystem.Forstandardtablewindows,alwayspassfollowingmessagestoTablefunction:
WM_DESTROY
WM_MOUSEMOVE
WM_LBUTTONDOWN
WM_LBUTTONDBLCLK
WM_LBUTTONUP
WM_RBUTTONDOWN
WM_RBUTTONDBLCLK
WM_HSCROLL
WM_VSCROLL
WM_TIMER(unprocessedmessagesonly)
WM_KEYDOWN(unprocessedmessagesonly)
WM_SYSKEYDOWN(unprocessedmessagesonly)
WM_WINDOWPOSCHANGED(tosupportAlwaysontopoption)
TablefunctionalsoprocessesmostofcustomOllyDbgmessagesfromstandardtablewindows.Customwindowsusuallymustprocessthesemessagesbyitself.
intTablefunction(t_table*pt,HWNDhw,UINTmsg,WPARAMwParam,LPARAMlParam);
Parameters:
pt-pointertodescriptoroftablewindow;
hw,msg,wParam,lParam-messageparametersasreceivedfromWindows.
Seealso:Custommessages
Custommessages
OllyDbgdefinesfollowingcustommessagesthatmustbeprocessedbytablewindows:
WM_USER_MENU activatecontext-sensitivemenuWM_USER_SCR (*) redrawscroll(s)WM_USER_VABS (*) scrollcontentsofwindowbylines
WM_USER_VREL (*) scrollcontentsofwindowbypercent
WM_USER_VBYTE (*) scrollcontentsofwindowbybytesWM_USER_STS (*) startselectioninwindowWM_USER_CNTS (*) continueselectioninwindowWM_USER_CHGS (*) movesingle-lineselection
WM_USER_BAR messagefrombarsegmentactingasbutton
WM_USER_DBLCLK doubleclickincolumnWM_USER_CHALL redraw(almost)everything
WM_USER_CHMEM rangeofdebuggee'smemorychanged
WM_USER_CHREG debuggee'sregister(s)changed
Standardtablewindowsusuallyredirectmessagesmarkedwithasterisk(*)toTablefunction.
Seealso:Tablefunction
WM_USER_MENU
CustommessagesenttotablewindowwhenuserpressesrightmousebuttonorshortcutAlt+F10.Windowshouldcreateandfillpop-upmenuandpassthismessagetoTablefunctionwithmenuhandleinparameterlp.Windowcanuseidentifiersfrom1toMENU_SORT-1(0x27F)andfromMENU_APPMAX+1(0x300)toMENU_PLUGIN-1.ItcanpassNULLifonlystandardmenusarerequired.
Tablefunctionchecksforattributeslistedint_table.modeandperformsfollowingactions:
Attribute Action
TABLE_COPYMENU
Ifsomelineisselected,addsmenuitem"Copy".ThisattributealsoaddsprocessingofkeyboardshortcutsCtrl+CandCtrl+Ins
TABLE_SORTMENU
Addssubmenu"Sortby"withalistofallbarsegmentswithoutBAR_NOSORT.Tohidepartofthesegmenttitleinmenu,separateitwith'$'
TABLE_APPMENUAddssubmenu"Appearance"thatincludesbar,column,fontandcolouroptions
TABLE_WIDECOL
WhensetsimultaneouslywithTABLE_APPMENU,addsmenuitem"Widecolumns",allowingtodoubledefaultwidths
TABLE_HILMENU
WhensetsimultaneouslywithTABLE_APPMENU,addsmenuitem"Highlighting",allowingtoselectoneofcodehighlightingschemes
TABLE_ONTOPAddsmenuitem"Alwaysontop"thatallowstokeeponeMDIwindowalwaysvisible
OnreturnfromTablefunction,windowgetsidofselecteditem.IfselectionisprocessedinternallybyTablefunction,orwhenthereisnoselection,itgets0.Windowthenmustdestroyallnewlycreatedmenus,processselectionandreturntocaller.
Seealso:Tablefunction
WM_USER_SCR
Askswindowtoupdatehorizontalandverticalscrollbars.SimplypassthismessagetoTablefunction.
WM_USER_VABS
Thismessagerequeststablewindowtoscrollverticallyby(signed)numberoflinesspecifiedinlParam.PositivelParammeansscrollingforwardindata(contentsofwindowmovesup),negative-backward.wParamcontainsnumberofdatalinescompletelyvisibleinthewindow(1ifdataareaissmallerthan1line).IflParamis0,messagerequeststocalculatenewpositionofverticalscrollbar.
StandardtablewindowshouldsimplypassthismessagetoTablefunction.
Owner-drawnwindowmustmodifytabledatabutneitherredrawnorinvalidatethewindow.Ifwindow'sappearanceremainsunchangedandlParamisnot0,windowfunctionmustreturn-1.Ifwindowsupportsbytescrolling,itmustreturn(indexoftopmostline)*MAXTRACK/(totalnumberoflines).IftotalnumberoflinesislessthanorequaltowParam,itreturns0.Otherwise,itmustreturn(indexoftopmostline)*MAXTRACK/(totalnumberoflines-wParam).AsconstantMAXTRACKisrelativelybig,useMulDivtocalculatereturnvalue.
WM_USER_VREL
Thismessagerequestsverticalscrollingtothepositionrelativetothetotalsizeofthetable.wParamcontainsnumberofcompletelyvisiblelinesinthewindow(1ifdataareaissmallerthan1line).lParamcontainsnewscrollingpositionin1.0/MAXTRACKpartsofthetotalheightofthetable.
StandardtablewindowshouldsimplypassthismessagetoTablefunction.
Ifcustomtablewindowsupportsbytescrolling,itmustmakelinewithindex(totalnumberoflines)*lParam/MAXTRACKtopmostvisibleinthewindow.Ifbytescrollingisnotsupported,itmustbeline(totalnumberoflines-wParam)*lParam/MAXTRACK.Windowisnotallowedtoeitherredraworinvalidatethewindow.Ifwindow'sappearanceremainsunchanged,windowfunctionmustreturn-1.Ifwindowsupportsbytescrolling,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines).IftotalnumberoflinesislessthanorequaltowParam,itreturns0.Otherwise,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines-wParam).AsconstantMAXTRACKisrelativelybig,useMulDivtocalculatereturnvalue.
WM_USER_VBYTE
ThismessagerequeststablewindowtoscrollupordownlParambytes.wParamcontainsnumberofcompletelyvisiblelinesinthewindow(1ifdataareaissmallerthan1line).
StandardtablewindowshouldsimplypassthismessagetoTablefunctionwhereitisinterpretedasWM_USER_VABS.
Customtablewindowmustmodifydatabutneitherredrawnorinvalidatethewindow.Ifpositionofdataremainsunchanged,window'sfunctionmustreturn-1.Ifwindowsupportsbytescrolling,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines).IftotalnumberoflinesislessthanorequaltowParam,itreturns0.Otherwise,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines-wParam).AsconstantMAXTRACKisrelativelybig,useMulDivtocalculatereturnvalue.
WM_USER_STS
Messagerequeststablewindowtostartselection.HIWORD(wParam)containscolumnwhereselectionbegins,LOWORD(wParam)-Xoffsetwithinthecolumnincharacterwidths,lParam-Yoffsetwithinthewindowincharacterheigths.
StandardtablewindowshouldsimplypassthismessagetoTablefunction.
Customtablewindowmustmodifydatatoreflectstartofselectionbutneitherredrawnorinvalidatethewindow.Itmustreturn1ifscreenappearanceischanged,0ifnotand-1ifstartofselectionatthispointisnotpossible.
WM_USER_CNTS
MessageissenttotablewindowtocontinueselectionstartedbyWM_USER_STS.HIWORD(wParam)containscolumnwithcurrentendofselection,LOWORD(wParam)-Xoffsetwithinthecolumnincharacterwidths,lParam-Yoffsetwithinthewindowincharacterheigths.
StandardtablewindowshouldsimplypassthismessagetoTablefunction.
Customtablewindowmustmodifydatatoreflectchangeofselectionbutmustneitherredrawnorinvalidatethewindow.Itreturns1ifscreenappearanceischangedand0ifnot.
WM_USER_CHGS
Messagerequeststablewindowtochangeselectiontosingle-line,moveselectionupordownbylParamlinesandscrollwindowsothatselectionisstillvisible.SpeciallParamvaluesofMOVETOPandMOVEBOTTOMmoveselectiondirectlytofirstorlastlineinthetable.wParamcontainsnumberofcompletelyvisiblelinesinthewindow(1ifdataareaissmallerthan1line).
Ifwindowdoesnotsupportsingle-lineselection,itmustscrollbyspecifiednumberoflines.
Standardtablewindow(whichanywaydoesnotallowmultilineselection)shouldsimplypassthismessagetoTablefunction.
Customtablewindowmustmodifydatabutneitherredrawnorinvalidatethewindow.Ifpositionofdataremainsunchanged,window'sfunctionmustreturn-1.Ifwindowsupportsbytescrolling,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines).IftotalnumberoflinesislessthanorequaltowParam,itreturns0.Otherwise,itmustreturn(topmostline)*MAXTRACK/(totalnumberoflines-wParam).AsconstantMAXTRACKisrelativelybig,useMulDivtocalculatereturnvalue.
WM_USER_BAR
BarsegmentwithmodebitBAR_BUTTONworksasabuttonand,whenpressed,sendsthismessagetothewindowwhichownsbar.wParamcontainscolumn,lParamis0.OllyDbgignoresvaluereturnedbythismessage.
WM_USER_DBLCLK
Whenuserdoubleclicksleftmousebuttonwithinthedataarea(butneitherinbarnoroverthedividingline),tablewindowreceivesthismessage.HIWORD(wParam)containscolumn,LOWORD(wParam)-Xoffsetwithinthecolumnincharacterwidths,lParam-Yoffsetwithinthewindowinrows.Ifwindowprocessesthismessage,itmustreturn1,otherwisedoubleclickistreatedassimpleclick.
WM_USER_CHALL
Duetochangesindebuggedapplicationordisplayoptions,windowmustbeupdated.Window'sprocedureisexpectedtopostponeredrawingusingactualdataandreturnCONT_BROADCAST.
WM_USER_CHMEM
MemoryofdebuggedprocessinrangefromwParam(included)tolParam(notincluded)ispossiblychanged.UpdatewindowifnecessaryandreturnCONT_BROADCAST.
WM_USER_CHREG
Someregistersofdebuggedprocess(general-purpose,FPU,MMXetc.)arechanged.UpdatewindowifnecessaryandreturnCONT_BROADCAST.
Painttable
ImplementsprocessingofWM_PAINTmessageforalltablewindows.CallthisfunctiononlywhenprocessingWM_PAINT.
voidPainttable(HWNDhw,t_table*pt,DRAWFUNCgetline);
Parameters:
hw-handleofwindowtoberedrawn;
pt-pointertodescriptoroftablewindow;
getline-pointertocustomfunctionthatpreparesdatatobedrawninspecifiedcelloftablewindow.
Seealso:DRAWFUNC
Selectandscroll
Selectselementofsorteddatawithspecifiedindexaccordingtocurrentsortmodeandscrollswindowsothatselectionisvisible.Thisfunctionneitherredrawsnorinvalidatesnorcreateswindowandhasnoeffectonowner-drawntablewindows.
voidSelectandscroll(t_table*pt,intindex,intmode);
Parameters:
pt-pointertodescriptoroftablewindow;
index-indexofelementofsorteddataaccordingtocurrentsortmode;
mode-requestforpositionofselectedlineinwindow.Ifmodeis0,thisisalwaysthetopmostline,if1-lineinthemiddleofthedataarea,2-selectedautomatically(recommendedwhencallingfunctionwalksthroughalltableentries).
Sendshortcut
EmulateseitherglobalkeyboardshortcutorshortcutinsomeCPUsubwindow.Designedprimarilyforuseincommandlineplugin.
voidSendshortcut(intwhere,ulongaddr,intmsg,intctrl,intshift,intvkcode);
Parameters:
where-addresseeoftheemulatedkeyboardshortcut:
PM_MAIN Mainwindow(globalshortcut)
PM_DISASM CPUDisassemblerPM_CPUDUMP CPUDumpPM_CPUSTACK CPUStackPM_CPUREGS CPURegisters
addr-forallCPUsubwindowsexceptPM_CPUREGS,addresstowhichshortcutisapplied.IgnoredifwhereisPM_CPUREGSorPM_MAIN;
msg-keyboardmessagetoemulate:WM_KEYDOWN,WM_SYSKEYDOWNorWM_CHAR;
ctrl-emulatedstateofControlkeyonthekeyboard(0-released,1-pressed);
shift-emulatedstateofShiftkeyonthekeyboard(0-released,1-pressed);
vkcode-keytoemulate,characteroroneofVK_xxx(forexample,VK_F1toemulateF1key).
Quicktablewindow
Ifwindowalreadyexists,restoresitandbringstothetop.Otherwise,setsdefaultappearanceparametersandcreatesnewwindow.Ifrecordwithwindow'stitlealreadyexistsinollydbg.ini,tablehasTABLE_SAVEPOSattributeandoption"Restorewindowspositionandappearance"isselected,restoresoldposition,sizeandappearance.ReturnspointertowindoworNULLonerror.Notethatalternativefunction,Newtablewindow,neitherrestoreswindownorchangesitsappearance.
HWNDQuicktablewindow(t_table*pt,intnlines,intmaxcolumns,char*winclass,char*wintitle);
Parameters:
pt-pointertodescriptoroftablewindow;
nlines-preferrednumberofvisiblelines;
maxcolumns-preferrednumberofvisiblecolumns;
winclass-nameofregisteredwindowclass(forexample,obtainedfromcalltoRegisterpluginclass);
wintitle-window'stitle.IftablehasTABLE_SAVEPOSattribute,OllyDbgusestitletosaveandrestorewindow'spositionandappearance.
Seealso:Registerpluginclass,Newtablewindow
Newtablewindow
Createsnewtablewindow.Ifrecordwithwindow'stitlealreadyexistsinollydbg.ini,tablehasTABLE_SAVEPOSattributeandoption"Restorewindowspositionandappearance"isselected,restoresoldposition,sizeandappearanceofthetablewindow.ReturnspointertowindoworNULLonerror.Notethatalternativefunction,Quicktablewindow,restoreswindowifitalreadyexistsandsetsdefaultappearanceparameters.
HWNDNewtablewindow(t_table*pt,intnlines,intmaxcolumns,char*winclass,char*wintitle);
Parameters:
pt-pointertodescriptoroftablewindow;
nlines-preferrednumberofvisiblelines;
maxcolumns-preferrednumberofvisiblecolumns;
winclass-nameofregisteredwindowclass(forexample,obtainedfromcalltoRegisterpluginclass);
wintitle-window'stitle.IftablehasTABLE_SAVEPOSattribute,OllyDbgusestitletosaveandrestorewindow'spositionandappearance.
Seealso:Registerpluginclass,Quicktablewindow
Createdumpwindow
Createsnewdumpwindowthatcanshoweithercontextoffileormemoryrangeofdebuggedprograminoneofpredefineddumpformats.ReturnshandleofcreatedwindoworNULLonerror.Numberofsimultaneouslydisplayeddumpwindowsis(theoretically)unlimited.
HWNDCreatedumpwindow(char*name,ulongbase,ulongsize,ulongaddr,inttype,SPECFUNC*specdump);
Parameters:
name-ifparametersizeis0,nameoffiletodisplay,otherwisewindow'stitleorNULL,inthislastcaseOllyDbggeneratestitleautomatically;
base-ifsizeis0,baseisignored,otherwisethisisthebaseaddressofdisplayedmemoryrange;
size-0ifwindowshoulddumpcontentsoffile,orsizeofdisplayedmemoryrangeotherwise;
addr-addressoroffsetofthefirstelementdisplayedafterwindowiscreated;
type-combinationofdumptype(oneofDU_xxx),numberofitemsperline((n<<8)&DU_COUNT)andsizeofsingleitem(l&DU_SIZE).Forvariable-lengthtypessizeis1.Seetablebelowforalistofcommonlyuseddumptypes;
specdump-functionthatperformsspecialdatadecoding,settoNULL.
Commonlyuseddumptypes:
0x01101 Hex/ASCII(16bytes)0x01081 Hex/ASCII(8bytes)0x0A101 Hex/UNICODE(16bytes)0x0A081 Hex/UNICODE(8bytes)0x02401 ASCII(64chars)0x02201 ASCII(32chars)0x03402 UNICODE(64chars)
0x03202 UNICODE(32chars)0x04082 Signedshortdecimal0x05082 Unsignedshortdecimal0x06082 Shorthex0x04044 Signedlongdecimal0x05044 Unsignedlongdecimal0x06044 Longhex0x08014 Address0x0B041 AddresswithASCIIdump0x0C041 AddresswithUNICODEdump0x07044 32-bitfloat0x07028 64-bitdouble0x0701A 80-bitlongdouble0x09011 Disassemble0x0D001 PEheader
Seealso:Setdumptype,Dumpbackup
Setdumptype
Setsorchangestypeofinformationdisplayedindumpwindow.Windowassociatedwithpdisnotupdated,youmustinvalidateittovisualizethischange.
voidSetdumptype(t_dump*pd,inttype);
Parameters:
pd-pointertodumpdescriptor;
type-combinationofdumptype(oneofDU_xxx),numberofitemsperline((n<<8)&DU_COUNT)andsizeofsingleitem(l&DU_SIZE).Forvariable-lengthtypessizeis1.Seetablehereforalistofcommonlyuseddumptypes.
Seealso:Createdumpwindow,Dumpbackup
Dumpbackup
Functionperformsspecifiedbackupaction(likecreatingorupdatingbackup,readingbackupfromfile,destroyingbackupetc.)onthedump.Ifactioninvolvesfileoperations(readdatafromfile,savedataorbackuptofile),userispromptedtoselectfilename.Functionneitherredrawsnorinvalidatesbackupwindow.
voidDumpbackup(t_dump*pd,intaction);
Parameters:
pd-pointertodumpdescriptor;
action-constantthatspecifiesrequestedbackupaction:
BKUP_CREATE CreateorupdatebackupcopyBKUP_VIEWDATA VieworiginaldataBKUP_VIEWCOPY ViewbackupcopyBKUP_LOADCOPY ReadbackupcopyfromfileBKUP_SAVEDATA SaveoriginaldatatofileBKUP_SAVECOPY SavebackupcopytofileBKUP_DELETE Deletebackupcopy
Seealso:Createdumpwindow,Setdumptype
Broadcast
FunctionsendsmessagetoallopenMDIwindows.StopseitheraftermessageissenttoallwindowsorwhensomewindowreturnsSTOP_BROADCAST.UsuallyusedtobroadcastcustommessagesWM_USER_CHALL,WM_USER_CHMEMandWM_USER_CHREG.Notethatyoudon'tneedtobroadcastWM_USER_CHMEMaftercalltoWritememorywithmodeflagMM_RESTORE.
intBroadcast(UINTmsg,WPARAMwParam,LPARAMlParam);
Parameters:
msg-messagetobebroadcasted;
wParam-firstmessageparameter;
lParam-secondmessageparameter.
Seealso:Writememory,WM_USER_CHALL,WM_USER_CHMEM,WM_USER_CHREG
Namefunctions
Anyzero-terminatedASCIIstringthatisshorterthanTEXTLENcharacterscanbeanamefromtheOllyDbg'spointofview.Everynamehasassociated32-bitaddressand8-bittype.OllyDbgstoresallnamesinahugecentralizeddynamicalbufferthatcankeepupto10,000,000names,providedofcoursethatyouhaveenoughmemory.Whenusedcorrectly,namefunctionsareveryfast.
Severalnametypesarepredefined:
NM_NONAME UndefinednameNM_ANYNAME Nameofanytype
Namesthatarestoredinthe.uddfileofmodulewheretheyappear:
NM_LABEL User-definedlabelNM_EXPORT Exported(global)nameNM_IMPORT Importedname
NM_LIBRARY Nameextractedfromlibrary,objectfileordebugdata
NM_CONST User-definedconstant(currentlynotimplemented)
NM_COMMENT User-definedcomment
NM_LIBCOMM Automaticallygeneratedcommentfromlibraryorobjectfile
NM_BREAK ConditionrelatedwithbreakpointNM_ARG ArgumentsdecodedbyanalyserNM_ANALYSE CommentaddedbyanalyserNM_BREAKEXPR ExpressionrelatedwithbreakpointNM_BREAKEXPL ExplanationrelatedwithbreakpointNM_ASSUME AssumefunctionwithknownargumentsNM_STRUCT CodestructuredecodedbyanalyzerNM_CASE Casedescriptiondecodedbyanalyzer
NM_PLUGCMD Plugincommandstoexecuteatbreakpoint
Namesthatarestoredinthe.uddfileofmainmodule:
NM_INSPECT Severallastenteredinspectexpressions
NM_WATCH Watchexpressions
NM_ASM Severallastenteredassembledstrings
NM_FINDASM Severallastenteredassemblersearchstrings
NM_LASTWATCH Severallastenteredwatchexpressions
NM_SOURCE Severallastenteredsourcesearchstrings
NM_REFTXT Severallastenteredreferencetextsearchstrings
NM_GOTO SeverallastexpressionstofollowinDisassembler
NM_GOTODUMP SeverallastexpressionstofollowinDump
NM_TRPAUSE Severallastexpresionstopauseruntrace
NM_LABEL|NMHISTORY Severallastentereduser-definedlabels
NM_COMMENT|NMHISTORY Severallastentereduser-definedcomments
NM_BREAK|NMHISTORY Severallastenteredbreakpointconditions
NM_BREAKEXPR|NMHISTORY Severallastenteredbreakpointexpressions
NM_BREAKEXPL|NMHISTORY Severallastenteredbreakpointexplanations
Ifyouneeduniquenametypeforyourplugin,pleasecontacttheauthorof
OllyDbg.
Tofindnamebyitsaddress,OllyDbgusesbinarysearchoncontiguoussortedindexarray.Forthisreason,searchisextermelyfast,butaddingnewnamestothetablemaytakesignificanttime.Ifyouneedtoaddmultiplenamesatonce,useQuickinsertname.NamesaddedinthiswayareunaccessibleuntilyoucallMergequicknames.Asaruleofthumb,thismethodispreferrableifnumberofnamesexceeds10-15.
intInsertname(ulongaddr,inttype,char*name);
intQuickinsertname(ulongaddr,inttype,char*name);
voidMergequicknames(void);
voidDiscardquicknames(void);
intFindname(ulongaddr,inttype,char*name);
intDecodename(ulongaddr,inttype,char*name);
ulongFindnextname(char*name);
intFindlabel(ulongaddr,char*name);
voidDeletenamerange(ulongaddr0,ulongaddr1,inttype);
intFindlabelbyname(char*name,ulong*addr,ulongaddr0,ulongaddr1);
ulongFindimportbyname(char*name,ulongaddr0,ulongaddr1);
intDemanglename(char*name,inttype,char*undecorated);
intFindsymbolicname(ulongaddr,char*fname);
Insertname
Insertsneworreplacesexistingnameofgiventypeinthenametable.IfnameisNULLorempty,entryisdeleted.Returns0onsuccessand-1onerror.Note:donotcallthisfunctionbetweencallstoQuickinsertnameandMergequicknames!
intInsertname(ulongaddr,inttype,char*name);
Parameters:
addr-nameaddress;
type-nametype(NM_xxxforpredefinedtypes);
name-nametoinsert.IfnameisNULLorempty,entryisremovedfromthenametable.
Seealso:Quickinsertname,Mergequicknames,Discardquicknames,Findname,Deletenamerange
Quickinsertname
Insertsneworreplacesexistingnameofgiventypeinthenametable.NULLoremptynamesarenotallowed.Returns0onsuccessand-1onerror.NamesaddedbythisfunctionareunavailableuntilyoucallMergequicknames.Ifyouaddmultiplenames,QuickinsertnameismuchfasterthanInsertname.Note:donotcallInsertnamebetweencallstoQuickinsertnameandMergequicknames!
intQuickinsertname(ulongaddr,inttype,char*name);
Parameters:
addr-nameaddress;
type-nametype(NM_xxxforpredefinedtypes);
name-nametoinsert.IfnameisNULLorempty,entryisremovedfromthenametable.
Seealso:Insertname,Mergequicknames,Discardquicknames,Findname,Deletenamerange
Mergequicknames
FunctionaddsnamespostedbyQuickinsertnametothenametable.NotethatpostednamesarenotavailableuntilyoucallMergequicknames.
voidMergequicknames(void);
Seealso:Quickinsertname,Insertname,Discardquicknames
Discardquicknames
DiscardsallnamespostedbyQuickinsertnameafterlastcalltoMergequicknames.
voidDiscardquicknames(void);
Seealso:Quickinsertname,Mergequicknames
Findname
Searchesfornamewithgivenaddressandtype.Returnslengthofthenameor0ifnameisabsent.Asasideeffect,setsglobalargumentsforFindnextname.
intFindname(ulongaddr,inttype,char*name);
Parameters:
addr-nameaddress;
type-nametype(NM_xxxforpredefinedtypes);
name-pointertobufferoflengthatleastTEXTLENcharactersorNULL.Ifnameisfound,functioncopiesittothisbuffer.
Sealso:Findnextname,Decodename,Findlabel,Findlabelbyname,Findimportbyname
Decodename
Searchesfornamewithgivenaddressandtype.Ifnameisfound,scansitforcombinations<+XXXXXXXX>,whereXXXXXXXXisahexadecimalnumber,andsubstitutesthembysumofbaseandXXXXXXXXinhexadecimalformat.Returnslengthofresultingstringor0ifnameisabsent.OllyDbgusesthisfunctiontocorrectautomaticallygeneratedcommentsinrelocatablemodules.
intDecodename(ulongaddr,inttype,char*name);
Parameters:
addr-nameaddress;
type-nametype(NM_xxxforpredefinedtypes);
name-pointertooutputbufferoflengthatleastTEXTLENcharacters.
Seealso:Findname,Findlabel,Findlabelbyname,Findimportbyname
Findnextname
SearchesfornamewithtypespecifiedinlastcalltoFindnameandaddressexceedingthatinFindnameorreturnedbylastcalltoFindnextname.Returnsaddressor0iftherearenomorecompatibleentries.IfnameisNULL,nameitselfisnotfetched.
ulongFindnextname(char*name);
Parameters:
name-pointertooutputbufferoflengthatleastTEXTLENcharacters.
Seealso:Findname,Findlabel,Findlabelbyname,Findimportbyname
Findlabel
SearchesfornameoftypesNM_LABEL,NM_EXPORT,NM_IMPORT,NM_LIBRARY,NM_CONST(inthelistedorder).Ifsomenameisfound,getsnameandreturnsitstype,otherwisereturnsNM_NONAME.
intFindlabel(ulongaddr,char*name);
Parameters:
addr-nameaddress;
name-pointertooutputbufferoflengthatleastTEXTLENcharactersorNULL.
Seealso:Findname,Findlabelbyname,Findimportbyname
Deletenamerange
Deletesallnamesofspecifiedtype(orallnamesiftypeisNM_ANYNAME)inthespecifiedrange.
voidDeletenamerange(ulongaddr0,ulongaddr1,inttype);
Parameters:
addr0-startofaddressrange(included);
addr1-endofaddressrange(notincluded);
type-typeofnamestodelete(NM_ANYNAMEtodeleteallnamesintherange).
Seealso:Insertname,Quickinsertname
Findlabelbyname
SearchesfornameoftypesNM_LABEL,NM_EXPORT,NM_IMPORT,NM_LIBRARYorNM_CONSTinthespecifiedrange.Ifnameisfound,copiesitsaddressto*addrandreturnstypeoflabel,otherwisereturnsNM_NONAME.Attention,thisfunctionisveryslow,itsearchesnametablesequentially!
intFindlabelbyname(char*name,ulong*addr,ulongaddr0,ulongaddr1);
Parameters:
name-pointertooutputbufferoflengthatleastTEXTLENcharacters;
addr-pointertovariablethatreceivesaddressoffoundname;
addr0-startofaddressrange(included);
addr1-endofaddressrange(notincluded).
Seealso:Findname,Findlabel,Findimportbyname
Findimportbyname
SearchesfornameoftypeNM_IMPORTinthespecifiedrange.Ifnameisfound,returnsitsaddress,otherwisereturns0.Ifnamecontainsnomoduleprefix,routinesearchesforimportnamewithanymoduleprefix.Attention,thisfunctionisveryslow,itsearchesnametablesequentially!
ulongFindimportbyname(char*name,ulongaddr0,ulongaddr1);
Parameters:
name-pointertooutputbufferoflengthatleastTEXTLENcharacters;
addr0-startofaddressrange(included);
addr1-endofaddressrange(notincluded).
Seealso:Findname,Findlabel,Findlabelbyname
Findsymbolicname
Checksthatthereisasymbolicnameassociatedwithaddress.Returns0ifthereisnosymbolicname.Returns1ifnameexistsbuffnameisNULL.Extractsnametofnameandreturnsitssizeotherwise.
intFindsymbolicname(ulongaddr,char*fname);
Parameters:
addr-address;
fname-pointertooutputbufferoflengthatleastTEXTLENcharactersthatreceivesfoundname.
Seealso:Findname,Findlabel,Findlabelbyname
Disassemblyfunctions
DisasmisthemostimportantOllyDbgfunction,andoneofthemostcomplicated.Inversion1.06,itsCcodetogetherwithdeclarations,servicesubroutinesandtablesis4291lines(210Kbytes)long!AlmosteverypartofOllyDbgcallsDisasm,directlyorindirectly.
Disasmrequiresthatyousupplybinarycodeofthecommandtodisassemble.Readcommandallowsyoutoeasilyreadcommandfromthememoryofdebuggedprocess.
Twootherdisassemblyfunctions,DisassembleforwardandDisassembleback,allowwalkingthroughthebinarycode,commandbycommand.Notethat80x86commandshavevariablelength.Disassemblebackuseheuristicalmethodstoseparatecommandsandinsome(astoundinglyrare!)casesmayreturninvalidanswer.Toavoidrisksofinvalingbackwardwalking,useanalysisdata.
FunctionsIssuspiciousandIsfillingcandeterminewhethercommandispotentiallyinvalidorequivalenttoNOP.
ulongDisasm(char*src,ulongsrcsize,ulongsrcip,char*srcdec,t_disasm*disasm,intdisasmmode,ulongthreadid);
ulongReadcommand(ulongip,char*cmd);
ulongDisassembleback(char*block,ulongbase,ulongsize,ulongip,intn,intusedec);
ulongDisassembleforward(char*block,ulongbase,ulongsize,ulongip,intn,intusedec);
ulongFollowcall(ulongaddr);
intIssuspicious(char*cmd,ulongsize,ulongip,ulongthreadid,t_reg*preg,char*s);
intIsfilling(ulongoffset,char*data,ulongsize,ulongalign);
intIsprefix(intc);
t_disasm
Disasmusesthisstructuretoreportdisassemblyresults.Whichfieldsofthestructurearefilleddependsonthedisassemblingmode:
DISASM_SIZE Onlyerrorisvalid
DISASM_DATA Onlymembersoft_disasmmarkedwithasterisk(*)arevalid
DISASM_TRACE Onlymembersmarkedwithasterisk(*)andminus(-)arevalid
DISASM_FILE
Completedisassembly,butDisasmassumesthatregistersareundefinedanddoesnotdecodesymbolicnames.Membersmarkedwithminus(-)areinvalid
DISASM_CODECompletedisassembly,butDisasmassumesthatregistersareundefined.Membersmarkedwithminus(-)areinvalid
DISASM_ALL Completedisassembly.Membersmarkedwithminus(-)areinvalid
typedefstructt_disasm{//Resultsofdisassembling
ulongip;//(*)Instrucionpointer
chardump[TEXTLEN];//Hexadecimaldumpofthecommand
charresult[TEXTLEN];//Disassembledcommand
charcomment[TEXTLEN];//Briefcomment
charopinfo[3][TEXTLEN];//Commentstocommand'soperands
intcmdtype;//(*)OneofC_xxx
intmemtype;//(*)Typeofaddressedvariableinmemory
intnprefix;//(*)Numberofprefixes
intindexed;//Addresscontainsregister(s)
ulongjmpconst;//(*)Constantjumpaddress
ulongjmptable;//(*)Possibleaddressofswitchtable
ulongadrconst;//(*)Constantpartofaddress
ulongimmconst;//(*)Immediateconstant
intzeroconst;//(*)Whethercontainszeroconstant
intfixupoffset;//(*)Possibleoffsetof32-bitfixups
intfixupsize;//(*)Possibletotalsizeoffixupsor0
ulongjmpaddr;//Destinationofjump/call/return
intcondition;//0xFF:unconditional,0:false,1:true
interror;//(*)Errorwhiledisassemblingcommand
intwarnings;//(*)CombinationofDAW_xxx
intoptype[3];//Typeofoperand(extendedsetDEC_xxx)
intopsize[3];//Sizeofoperand,bytes
intopgood[3];//Whetheraddressanddatavalid
ulongopaddr[3];//Addressifmemory,indexifregister
ulongopdata[3];//Actualvalue(onlyintegeroperands)
t_operandop[3];//Fulldescriptionofoperand
ulongregdata[8];//Registersaftercommandisexecuted
intregstatus[8];//Statusofregisters,oneofRST_xxx
ulongaddrdata;//Tracedmemoryaddress
intaddrstatus;//Statusofaddrdata,oneofRST_xxx
ulongregstack[NREGSTACK];//Stacktracingbuffer
intrststatus[NREGSTACK];//Statusofstackitems
intnregstack;//Numberofitemsinstacktracebuffer
ulongreserved[29];//Reservedforplugincompatibility
}t_disasm;
Members:
ip-addressofthedisassembledcommand;
dump-ASCIIstring,formattedhexadecimaldumpofthecommand;
result-ASCIIstring,disassembledcommanditself;
comment-ASCIIstring,briefcommentthatappliestothewholecommand;
opinfo-arrayofASCIIstrings,commentstoindividualoperands(explicitorimplicit,likeESP,EBPandECXinMOVSB);
cmdtype-typeofthedisassembledcommand,oneofC_xxxpossiblyORedwithC_RAREtoindicatethatcommandisseldominordinaryWin32applications.CommandsoftypeC_MMXadditionallycontainsizeofMMXdatainthe3leastsignificantbits(0means8-byteoperands).Non-MMXcommandsmayhaveC_EXPLbitsetwhichmeansthatsomememoryoperandhassizewhichisnotconformwithstandard80x86rules;
memtype-typeofmemoryoperand,oneofDEC_xxx,orDEC_UNKNOWNifoperandisnon-standardorcommanddoesnotaccessmemory;
nprefix-numberofprefixesthatthiscommandcontains;
indexed-ifmemoryaddresscontainsindexregister,settoscale,otherwise0;
jmpconst-addressofjumpdestinationifthisaddressisaconstant,and0otherwise;
jmptable-ifindirectjumpcanbeinterpretedasswitch,baseaddressofswitchtableand0otherwise;
adrconst-constantpartofmemoryaddress;
immconst-immediateconstantor0ifcommandcontainsnoimmediateconstant.TheonlycommandthatcontainstwoimmediateconstantsisENTER.Disasmignoressecondconstantwhichisanyway0inmostcases;
zeroconst-nonzeroifcommandcontainsimmediatezeroconstant;
fixupoffset-possiblestartof32-bitfixupwithinthecommand,or0ifcommandcan'tcontainfixups;
fixupsize-possibletotalsizeoffixups(0,4or8).Ifcommandcontainsbothimmediateconstantandimmediateaddress,theyarealwaysadjacenton80x86processors;
jmpaddr-destinationofjump,callorreturn.Ifjumpaddresscontainsundefinedregister,jmpaddris0;
condition-whetherconditionincommandismet:0-conditionisfalse,1-true,-1-commandisunconditionalorEFLisundefined;
error-Disasmwasunabletodisassemblecommand(forexample,commanddoesnotexistorcrossesendofmemoryblock),oneofDAE_xxx;
warnings-commandissuspiciousormeaningless(forexample,farjumporMOVEAX,EAXprecededwithsegmentprefix),combinationofDAW_xxxbits;
optype-arrayofoperandtypes,DEC_xxxorDECR_xxx;
opsize-arrayofoperandsizesinbytes;
opgood-arrayofflagsindicatingopaddrandopdataarevalid;
opaddr-arraycontainingmemoryaddressesofmemoryoperandsandregisterindexesforregisteroperands.Validonlyifcorrespondingopgoodisset;
opdata-arrayofactualoperand'svalues(integeroperandsonly),validonlyif
correspondingopgoodisset;
op-fulldescriptionsofoperands.
Registertracingisstillrelativelyrawandisnotdescribed.
Disasm
Disassemblescommand,determinesitssizeanddecodesoperands.Returnssizeofthecommand.Disasmfunctionalitydependsontheselectedmodeandglobaldisassembling/analysisoptions.Seedescriptionoft_disasmformoredetails:
Mode ActionsDISASM_SIZE Fastestmode,onlycalculatescommandsizeDISASM_DATA Extractsmostimportantdata,notextualinformation
DISASM_TRACE Extractsmostimportantdataandtracescontentsofintegerregisters,notextualinformation
DISASM_FILEDisassemblescommandinassumptionthatregistersareundefinedandsymbolicnamesareinvalid.Usuallyusedtodisassemblecontentsoffile
DISASM_CODE Disassemblescommandassumingthatregistersareundefined
DISASM_ALL Completeandrelativelyslowdisassembly
ulongDisasm(char*src,ulongsrcsize,ulongsrcip,char*srcdec,t_disasm*disasm,intdisasmmode,ulongthreadid);
Parameters:
src-pointertobinarycommandthatmustbedisassembled;
srcsize-sizeofsrc.Lengthof80x86commandsislimitedtoMAXCMDSIZEbytes;
srcip-addressofthecommand;
srcdec-pointertodecodingdataproducedbyAnalyzerorNULLifdecodingdataisabsent.Youmustsupplysrcdecifyouwanttodecodeswitchtables,constantsandstrings;
disasm-pointertot_disasmstructurethatreceivesresultsofdisassembling;
disasmmode-disassemblymode,oneofDISASM_xxx.Seedesctiptionoft_disasmandtableabove;
threadid-identifierofthreadcontainingregisters,orNULLifregistersareundefined.
Seealso:Readmemory,Finddecode,t_disasm,MAXCMDSIZE
Disassembleback
Calculatesaddressofassemblerinstructionwhichisninstructions(maximally127)backfrominstructionatspecifiedaddress.Returnsaddressoffoundinstruction.Incaseoferror,itmaybelessthanninstructionsapart.
80x86commandshavevariablelength.Disassemblebackuseheuristicalmethodstoseparatecommandsandinsome(astoundinglyrare!)casesmayreturninvalidanswer.Toavoidrisksofinvalingbackwardwalking,orcorrectlywalkthroughconstantsandstrings,useresultsofcodeanalysis.
ulongDisassembleback(char*block,ulongbase,ulongsize,ulongip,intn,intusedec);
Parameters:
block-pointertocopyofcode.IfblockisNULL,Disassemblebackassumesmemoryofdebuggedprocessandifnecessaryreadsit;
base-addressoffirstbyteofcodeblock;
size-sizeofcodeblock;
ip-addressofcurrentinstruction;
n-numberofinstructionstowalkback;
usedec-flagindicatingwhetherDisassemblebackshouldtrytousedecodingdata.
Seealso:Disassembleforward,Followcall,Findmemory,Readmemory
Disassembleforward
Calculatesaddressofassemblerinstructionwhichisninstructionsforwardfrominstructionatspecifiedaddress.Ifcopyofcodeisnotsupplied,Disassembleforwardguaranteescorrectresultsupton=127(typically300).Returnsaddressoffoundinstruction.Incaseoferror,itmaybelessthanninstructionsapart.
Ifyouwanttocorrectlywalkthroughconstantsandstrings,useresultsofcodeanalysis.
ulongDisassembleforward(char*block,ulongbase,ulongsize,ulongip,intn,intusedec);
Parameters:
block-pointertocopyofcode.IfblockisNULL,Disassembleforwardassumesmemoryofdebuggedprocessandifnecessaryreadsit;
base-addressoffirstbyteofcodeblock;
size-sizeofcodeblock;
ip-addressofcurrentinstruction;
n-numberofinstructionstowalkforward;
usedec-flagindicatingwhetherDisassembleforwardshouldtrytousedecodingdata.
Seealso:Disassembleback,Followcall,Findmemory,Readmemory
Followcall
Followssequenceofjumps(directorindirect)andWin95thunksthatstartsatspecifiedaddress.Stopsif:
-nextcommandisneitherjumpnorthunk,or
-nextcommandisexportedentryindifefrentmodule,or
-lengthofsequenceexceeds10jumps.
Returnsaddressoffinaldestination,or0onerror.ParameteraddrisusuallythedestinationofCALLcommand,hencethename.Asanyaccesstothedebuggee'smemorytakessignificanttime,thisfunctionmaybeslow.
ulongFollowcall(ulongaddr);
Parameters:
addr-addressoffirstcommandinjumpchain.
Seealso:Disassembleforward,Disassembleback,Disasm
Issuspicious
Checkswhethercommandissomehowsuspicious.Returns-1onerror,0ifcommandisnotsuspiciousand1ifcommandissuspicious.Useonlywithprograminmemory,donotapplytofile!Commandisconsideredsuspiciouswhen:
·thiscommandiserroneousorunknown,or
·itispotentiallyinvalidaccordingtoactiveanalysisoptions,or
·itsetssingle-steptrap,or
·itaccessesmemoryoperandinunusedpartofstack(i.e.addr>ESP),or
·itiscommandCLI,or
·memoryoperandcontainsINT3breakpointsetbyOllyDbg.
intIssuspicious(char*cmd,ulongsize,ulongip,ulongthreadid,t_reg*preg,char*comment);
Parameters:
cmd-pointertothebinarycommandcode;
size-sizeofcmdinbytes;
ip-addressofthecommandinthememoryofdebuggedprocess;
threadid-identifierofthethreadinwhichcontextthiscommandwillbeexecuted;
preg-pointertoregistersatthemomentofexecution;
comment-buffer,atleastTEXTLENbyteslong,thatreceivesexplanationwhythiscommandissuspicious,orNULL.
Seealso:Disasm,Isfilling,Isprefix,Readcommand
Isfilling
Functioncheckswhethercommandwhichbinarycodestartsatdata[offset]isavalidfillingcommand(usuallysomekindofNOP)usedtoaligncodetoaspecifiedborder.Returnslengthofcommandifthisisrecognizedasfillingand0otherwise.Checksinclude:
·NOP
·INT3
·XCHGRA,RA
·MOVRA,RA
·LEARA,[RA](withorwithoutSIBbyte)
·LEARA,[RA+00000000]
Thislistisfarfromcompletenessbutincludescommandsmostfrequentlyusedasfillingbyactualcompilers.
intIsfilling(ulongoffset,char*data,ulongsize,ulongalign);
Parameters:
offset-offsetofbinarycommandindata;
data-buffercontainingcopyofexecutablecode;
size-sizeofvalidcodeindata(ifsize<offset+sizeoftestedcommand,functionreturns0);
align-expectedcodealignment,mustbeeitherpowerof2(1,2,4,8...)or0thatmeansnoalignment.
Seealso:Disasm,Issuspicious,Isprefix,Readcommand
Isprefix
Veryquickandstraightforwardfunction,returns1ifbytecisa80x86commandprefix(ES:,CS:,SS:,DS:,FS:,GS:,DATASIZE,ADDRSIZE,LOCK,REPNE,REP)and0otherwise.Attention,itdoesn'tdistinguishthecaseswhenbyteispartoftheSSE/SSE2command!
intIsprefix(intc);
Parameters:
c-bytetoverify.
Seealso:Issuspicious,Isfilling
Readcommand
Readscommandfromthememoryofdebuggedprocessandrestoredbreakpoints.Returnslengthofthereadcode(atmostMAXCMDSIZEbytes)or0ifmemorycan'tberead.
Note:Anyaccesstothememoryindifferentprocessisextremelytime-expensive.AsinmanycasesdifferentpartsofOllyDbgaccesssamecommandseveraltimes,Readcommandmaintainssmall1-commandcachesignificantlyimprovesthewholesaveproductivityofOllyDbg.Ifyouneedtoaccessseveralcompactlyplacedcommands,Readmemoryisusuallymuchfaster.
ulongReadcommand(ulongip,char*cmd);
Parameters:
ip-addressofthecommandinthememoryspaceofdebuggedprocess.Ifipis0,functioninvalidatescacheandreturns0;
cmd-bufferoflengthatleastMAXCMDSIZEbytesthatreceivescommand.
Seealso:Disasm,Readmemory
Assemblyfunctions
intAssemble(char*cmd,ulongip,t_asmmodel*model,intattempt,intconstsize,char*errtext);
intCheckcondition(intcode,ulongflags);
Assemble
FunctionAssemble,asexpected,convertscommandinASCIIformtobinary32-bitcode.ItsharescommandtablewithDisasm,soifsomecommandcanbedisassembled,itcanbeassembledbacktoo,withoneexception:Assembledoesn'tsupport16-bitaddresses.Somecommandshavemorethanoneencoding.BycallingAssemblewithparameterattempt=0,1...andconstsize=0,1,2,3onecangetalternativevariantsandthenselecttheshortestpossibleform(thisishowOllyDbgimplementsassembling).However,onlyoneaddressformisgeneratedineachcase([EAX*2]butnot[EAX+EAX];[EBX+EAX]butnot[EAX+EBX];[EAX]willnotuseSIBbyte;noDS:prefixandsoon).
Assemblecompilesimprecisecommands(where,forexample,R32replacesanygeneral-purpose32-bitregister).Thisallowstogenerateimprecisesearchpatterns,wheremaskcontainszerosatthepositionoccupiedincodebyregister).Returnsnumberofbytesinassembledcodeornon-positivenumberincaseofdetectederrororwhenvariantselectedbycombinationofattemptandconstsizedoesn'texist.Thisnumberisthenegativepositionoferrorintheinputcommand.
intAssemble(char*cmd,ulongip,t_asmmodel*model,intattempt,intconstsize,char*errtext);
Parameters:
cmd-pointertozero-terminatedASCIIcommand;
ip-addressofthegeneratedbinarycodeinmemory;
model-pointertostructurethatreceivesmachinecodeandmask;
attempt-indexofalternativeverisonofthecommand.CallAssemblewithattempt=0,1,2...toobtainallpossibleversionsofthecommand.StopthissequencewhenAssemblereportserror;
constsize-requestedsizeofaddressconstantandimmediatedata.CallAssemblewithconstsize=0,1,2,3toobtainallpossiblevariantsoftheversionselectedbyattempt;
errtext-pointertotextbufferoflengthatleastTEXTLENthatreceivesdescriptionofdetectederror.
Seealso:Disasm
Checkcondition
Checkswhether80x86flagsmeetconditionsetinthecommand.Returns1ifconditionismetand0ifnot.
intCheckcondition(intcode,ulongflags);
Parameters:
code-firstbyteofconditionalcommand;
flags-contentsofregisterEFL.
Watchandexpressionfunctions
Forsomeobscurereasons,watchesinOllyDbgare1-based.Thatmeansthattoaccessthefirstavailablewatch,youmustsetindexinwatchfunctionsto1.Internally,OllyDbgkeepswatchexpressionsasnamesoftypeNM_WATCH,wherefirstwatchhasaddress1,next-address2andsoon.Accesstowatchexpressionsusingnamefunctionsisnotrecommended,directdeletionorinsertionofnewwatcheswillbringwatchwindowoutofsynchronization.Instead,usefunctionslistedbelow.
intInsertwatch(intindexone,char*text);
intDeletewatch(intindexone);
intGetwatch(intindexone,char*text);
intExpression(t_result*result,char*expression,inta,intb,char*data,ulongdatabase,ulongdatasize,ulongthreadid);
Insertwatch
Insertsnewwatchbeforethewatchwithspecified1-basedindexandupdateswatchwindow.Returnsnumberofwatchesafternewwatchisinserted,or-1onerror.
intInsertwatch(intindexone,char*text);
Parameters:
indexone-1-basedindexofexistingwatch.Ifthisindexexceedstotalnumberofexistingwatches,newwatchwillbeaddedtotheendofthewatchtable;
text-newwatchexpressiontoinsert.
Seealso:Deletewatch,Getwatch
Deletewatch
Deleteswatchwithspecified1-basedindexandupdateswatchwindow.Returnsnumberofremainingwatches,or-1onerror.
intDeletewatch(intindexone);
Parameters:
indexone-1-basedindexofexistingwatch.
Seealso:Insertwatch,Getwatch
Getwatch
Getscurrentexpressionofwatchwithgiven1-basedindex.Returnslengthofexpressionor0incaseoferror.
intGetwatch(intindexone,char*text);
Parameters:
indexone-1-basedindexofexistingwatchtoretrieve;
text-bufferoflengthatleastTEXTLENbytesthatreceiveswatchexpression.
Seealso:Insertwatch,Deletewatch
Expression
Expressioncalculatesvalueand,ifavailable,addressofarithmeticalexpression.Expressioncanincludeconstants,registers,memoryaddressesandtosomelimitedextentsymbolicnames,allstandardarithmeticaloperations,parenthesesandtwoparameters%Aand%B.Youcanfindbothintuitiveandformaldescriptionsofallowedexpressionsinfileollydbg.hlp.Onsuccess,Expressionfillsinstructuret_resultandreturnslengthofvalidexpression.Onerror(result->type==DEC_UNKNOWN)itreturnspositionoferrorinexpressionstringanderrormessageinresult->value.
Noticethatstartingfromversion1.08,Expression()doesn'treporterror"Extracharactersonline".Unrecognizedsymbolsremainunprocessed.
intExpression(t_result*result,char*expression,inta,intb,char*data,ulongdatabase,ulongdatasize,ulongthreadid);
Parameters:
result-pointertostructuret_resultthatreceivesresultsofevaluation;
expression-inputstringcontainingexpressiontoevaluate;
a-valueofparameter%A;
b-valueofparameter%B;
data-optionalpointertothecopyofmemoryofdebuggedprocess.IfdataisnotNULLandexpressionaccessesvariableinmemoryinrangefromdatabasetodatabase+datasize,Expressiontakescontentsofmemoryfromdata,otherwiseitreadsmemoryofdebuggedprocess.Thissparestime,especiallyifyouestimatesmultipleexpressions.
database-addressofdatainmemoryspaceofdebuggedprocess;
datasize-sizeofdata;
threadid-identifierofthreadwhoseregisterswillbeusedinevaluationofexpression.Ifthreadidis0andexpressionincludesregister,Expressionreports
erorr.
Seealso:Checkcondition,t_result
t_result
Typeofstructurethatcontainsresultofexpressionevaluation.
typedefstructt_result{//Resultofexpression'sevaluation
inttype;//Typeofexpression,DEC(R)_xxx
intdtype;//Typeofdata,DEC_xxx
union{
chardata[10];//Binaryformofexpression'svalue
ulongu;//Valueasunsignedinteger
longl;//Valueassignedinteger
longdoublef;};//Valueas80-bitfloat
union{
charvalue[TEXTLEN];//ASCIIformofexpression'svalue
wchar_twvalue[TEXTLEN/2];};//UNICODEformofexpression'svalue
ulonglvaddr;//AddressorindexoflvalueorNULL
}t_result;
Members:
type-exacttypeofexpression,oneofDEC_xxxorDECR_xxxpossiblyORedwithDEC_SIGNEDifresultshouldbeinterpretedassignednumber.typeisDEC_UNKNOWNifexpressionisinvalid.Expressionislvalue(canbeassignedto)ifeithertypeisDEC_xxxandlvaddrisnot0,oriftypeisoneofDECR_xxx.Allpossibletypesarelistedinthetablebelow:
type&DECR_TYPEMASK Meaning
DEC_UNKNOWN ErrorinexpressionDEC_BYTE ByteDEC_WORD ShortintegerDEC_DWORD LongintegerDEC_FLOAT4 32-bitfloatDEC_FWORD 48-bitdescriptororlongpointerDEC_FLOAT8 64-bitdoubleDEC_QWORD QuadwordDEC_FLOAT10 80-bitlongdoubleDEC_STRING Zero-terminatedASCIIstringDEC_UNICODE Zero-terminatedUNICODEstringDECR_BYTE ByteregisterDECR_WORD ShortintegerregisterDECR_DWORD LongintegerregisterDECR_QWORD MMXregisterDECR_FLOAT10 Floating-pointregisterDECR_SEG Segmentregister
dtype-simplifiedtypeofdata,possiblyORedwithDEC_SIGNED,describesvaluestoredint_result.data.IfbitDEC_SIGNEDisset,resultmustbeinterpretedassigned,otherwiseasunsigned:
dtype Interpretationoft_result.data
DEC_UNKNOWN Errorinexpressionorresultdoesn'tfitintodata
DEC_DWORD 32-bitunsignedintegerint_result.u
DEC_DWORD|DEC_SIGNED 32-bitsignedintegerstoredint_result.l
DEC_QWORD 64-bitintegerindata[0..7]
DEC_FLOAT10 80-bitlongdoublestoredint_result.f
data,u,l,f-resultofexpressionifthiscanberepresentedasintegerorfloat.
Whichfieldtoselectdependsondtype;
value-resultofexpressionoftypeDEC_STRING(truncatedtoTEXTLENcharacters)orerrormessageiftypeisDEC_UNKNOWN;
wvalue-resultofexpressionoftypeDEC_UNICODE(truncatedtoTEXTLEN/2characters);
lvaddr-addressofexpressioniftypeisoneofDEC_xxx,orindexofregisteriftypeisDECR_xxx.
Seealso:Expression
Threadfunctions
OllyDbgkeepslistofactivethreadinasorteddataconsistingofelementsoftypet_thread.YoucanreceivepointertotableofthreadsbycallingPlugingetvalue(VAL_THREADS)andcastingresultto(t_table*).Ifyouknowthread'sidentifier,Findthreadwillreturnpointertothreaddescriptor.Plugingetvalue(VAL_MAINTHREADID)givesidentifierofmainthreadofdebuggedprocess.
OllyDbgfunctionsusethreadidentifiers,butsomeWindowsfunctionsrequirehandles.Followingcodeconvertsidentifiertohandle:
t_thread*pthread;
HANDLEhthread;
pthread=Findthread(threadid);
if(pthread!=NULL)
hthread=pthread->handle;
else
hthread=NULL;
NotethatafterapplicationstartedandbeforeOllyDbgreceivedCREATE_PROCESS_DEBUG_EVENTevent,thread'shandleisunknown.
t_thread*Findthread(ulongthreadid);
intDecodethreadname(char*s,ulongthreadid,intmode);
ulongGetcputhreadid(void);
HWNDCreatethreadwindow(void);
t_thread
Typeofthreaddescriptor.
typedefstructt_thread{//Informationaboutactivethreads
ulongthreadid;//Threadidentifier
ulongdummy;//Always1
ulongtype;//Serviceinformation,TY_xxx
HANDLEthread;//Threadhandle
ulongdatablock;//Per-threaddatablock
ulongentry;//Threadentrypoint
ulongstacktop;//WorkingvariableofListmemory()
ulongstackbottom;//WorkingvariableofListmemory()
CONTEXTcontext;//Actualcontextofthethread
t_regreg;//Actualcontentsofregisters
intregvalid;//Whetherregisvalid
t_regoldreg;//Previouscontentsofregisters
intoldregvalid;//Whetheroldregisvalid
intsuspendcount;//Suspensioncount(maybenegative)
longusertime;//Timeinusermode,1/10thms,or-1
longsystime;//Timeinsystemmode,1/10thms,or-1
ulongreserved[16];//Reservedforfuturecompatibility
}t_thread;
Members:
threadid-threadidentifier;
dummy-sizeofthreadinspaceofthreadidentifiers,mustbe1.SeeSorteddatafunctionsforexplanation;
type-typeofthread,combinationofbitsTY_xxx.IfbitTY_MAINisset,thisisthemainthread;
thread-threadhandle.AfterapplicationstartedandbeforeOllyDbgreceivedCREATE_PROCESS_DEBUG_EVENTevent,thread'shandleisunavailable;
datablock-baseaddressofper-threaddatablock;
entry-addressofthreadentrypoint;
context-actualcontextofthethread.Donotmodifycontextdirectly,oryourisktocrashdebuggedapplication!
reg-excerptfromcontextthatcontainsCPUregisterssortedinanaturalway.Validonlywhenregvalidisnon-zero.Ifyouneedtomodifyregister,stopapplicationifnecessary,checkthatregvalidisnon-zero,applyyourchangesandsetreg.modifiedto1.DonotchangesinglestepflagordebuggingregisterDR6;
regvalid-flagindicatingthatregcontainsactualcontentsofthread'sregisters;
oldreg-previouscontentsofregisters,don'tmodify.Ifreg.modifiedbyuseris0,thisisacopyofregistersonapreviousstep,otherwisecopyoforiginalregisters;
oldregvalid-flagindicatingthatcontentsofoldregisvalid;
suspendcount-numberoftimesthisthreadwassuspendedbyOllyDbg.MaybenegativeincasewhenthreadwassuspendedbyuserorprogramandresumedbyOllyDbg.Donotmodifydirectly!
usertime-timethethreadspentinusermode,in100-microsecondunits,or-1ifunavailable;
systime-timethethreadspentinsystemmode,in100-microsecondunits,or-1ifunavailable;
reserved-reservedforfutureuseexclusivelybyOllyDbg.
Seealso:Findthread,Plugingetvalue
Findthread
Giventhread'sidentifier,returnspointertodescriptorofspecifiedthread,orNULLifthreaddoesnotexist.
t_thread*Findthread(ulongthreadid);
Parameters:
threadid-identifier(nothandle!)oftherequestedthread.
Seealso:Getcputhreadid,t_thread
Decodethreadname
DecodesnameofthreadwithspecifiedthreadidentifiertoASCIIstring,like"Mainthread"or"thread12345678".Returnslengthofnameor0onerror.
intDecodethreadname(char*s,ulongthreadid,intmode);
Parameters:
s-pointertobufferoflengthatleastTEXTLENbytesthatreceivesdecodedname;
threadid-threadidentifier;
mode-combinationofbitsADC_xxxthattellhowtodecodenameofthread:
ADC_VALID decodenameofthreadonlyifthreadidisavalidthreadidentifier
ADC_SYMBOL decodenameofthreadonlyifithassymbolicname
ADC_UPPERCASE forcefirstcharacterofnametobeinuppercase
ADC_WIDEFORM includeword"thread"intodecodedname
Getcputhreadid
ReturnsidentifierofthreadthatiscurrentlyselectedinCPUwindow.
ulongGetcputhreadid(void);
Memoryfunctions
OllyDbgkeepslistofmemoryblocksallocatedbydebuggedapplicationinatableofsorteddataconsistingofelementsoftypet_memory.YoucanreceivepointertomemorytablebycallingPlugingetvalue(VAL_MEMORY)andcastingresultto(t_table*).
t_memory*Findmemory(ulongaddr);
voidHavecopyofmemory(char*copy,ulongbase,ulongsize);
ulongReadmemory(void*buf,ulongaddr,ulongsize,intmode);
ulongWritememory(void*buf,ulongaddr,ulongsize,intmode);
intListmemory(void);
t_memory
Typeofmemorydescriptor,donotmodifydirectly!
typedefstructt_memory{//Memoryblockdescriptor
ulongbase;//Baseaddressofmemoryblock
ulongsize;//Sizeofblock
ulongtype;//Serviceinformation,TY_xxx
ulongowner;//Addressofownerofthememory
ulonginitaccess;//Initialread/writeaccess
ulongaccess;//Actualstatusandread/writeaccess
ulongthreadid;//Blockbelongstothisthreador0
charsect[SHORTLEN];//Nameofmodulesection
char*copy;//CopyusedinCPUwindoworNULL
ulongreserved[8];//Reservedforplugincompatibility
}t_memory;
Members:
base-baseaddressofmemoryblockinthememoryspaceofdebuggedprocess;
size-sizeofmemoryblock;
type-memorycharacteristics,combinationofbitsTY_xxx:
TY_CODE Memoryblockcontainsimageofcodesection
TY_DATA ContainsimageofdatasectionTY_IMPDATA Includesimportdata
TY_EXPDATA IncludesexportdataTY_RSRC ContainsresourcesTY_RELOC Includesrelocationdata
TY_STACK Containsstackofthreadwithidentifierthreadid
TY_THREAD Containsdatablockofthreadwithidentifierthreadid
TY_HEADER ContainsCOFFheaderTY_DEFHEAP ContainsdefaultheapTY_HEAP Containsnon-defaultheapTY_SFX Containsself-extractorTY_GUARDED NTonly:guardedmemoryblock
owner-addressofmemoryblockthatownsthisblock;
initaccess-typeofallowedmemoryaccesswhenblockwasallocated,oneofPAGE_xxx(seedescriptionofWindowsfunctionVirtualQueryExfordetails);
access-actualtypeofallowedmemoryaccess,oneofPAGE_xxx
threadid-ifmemorycontainsstackofthreaddatablock,identifierofowningthread,otherwiseundefined;
sect-nameofsection(notnecessarilynull-terinated!)ifblockisanimageofsectioninexecutablefile,otherwiseemptystring;
copy-ifmemoryblockwasbackupedinCPUwindow,pointertobackupcopy,orNULLotherwise;
reserved-reservedforfutureuseexclusivelybyOllyDbg.
Seealso:Findmemory
Findmemory
Givenaddressofmemory,returnspointertodescriptorofmemoryblockthatthisaddressbelongsto,orNULLifthereisnoallocatedmemory.
t_memory*Findmemory(ulongaddr);
Parameters:
addr-addressofmemoryinthememoryspaceofdebuggedapplication.
Seealso:t_memory
Havecopyofmemory
Optimizesaccesstomemoryofdebuggedprocess.FunctionReadmemoryisslow.Ifyouexpectmultiplereadsfromthesameblock,readrequestedpieceofmemorytosomeinternalbufferandreportittoOllyDbg.AllsubsequentcallstoReadmemorywill,wheneverpossible,usethiscopy.Don'tforgettocallHavecopyofmemory(NULL,0,0)whenyounolongerneedthiscopy,orOllyDbgwillcrash!NotethatWritememorywillnotupdatethiscopy.
voidHavecopyofmemory(char*copy,ulongbase,ulongsize);
Parameters:
copy-pointertocopyofmemoryofdebuggedprocess;
base-baseaddressofmemory;
size-sizeofmemory.
Seealso:Readmemory
Readmemory
ReadsmemoryofdebuggedprocessoptionallyremovingINT3breakpoints.Youcanreadmemory"onthefly":ifnecessary,Readmemorytemporailypausesdebuggedapplicationandenablesreadaccess.Returnssizeofmemoryactuallyread.Currently,thisiseithersizeor0ifmemorycannotbereadatonce.
Importantnote:Anyaccesstothememoryofdebuggedapplicationistime-consuming.Tooptimizeaccess,consideruseofHavecopyofmemory.
ulongReadmemory(void*buf,ulongaddr,ulongsize,intmode);
Parameters:
buf-pointertobufferofsizeatleastsizethatreceivescopyofmemory;
addr-addressofmemoryinthememoryspaceofdebuggedapplication;
size-sizeofrequestedmemoryblock;
mode-modeofoperation,combinationoffollowingbits:
MM_RESTORE RestoreINT3breakpointsMM_SILENT Onerror,don'tdisplayerrormessagebox
NotethatheaderdeclaresMM_RESILENTasacombinationof(MM_RESTORE|MM_SILENT).
Seealso:Writememory,Havecopyofmemory
Writememory
Modifiesmemoryofdebuggedprocess,optionallyremovingINT3breakpoints,broadcastingmemorychangesandremovinganalysisdata.Returnssizeofactuallymodifiedmemory.Currently,thisiseithersizeor0ifmemorycannotbewrittenatonce.
ulongWritememory(void*buf,ulongaddr,ulongsize,intmode);
Parameters:
buf-pointertobufferwithnewcontentsofmemory;
addr-addressofmemoryinthememoryspaceofdebuggedapplication;
size-sizeofnewcontents;
mode-modeofoperation,combinationoffollowingbits:
MM_RESTORE RemoveINT3breakpointsinthemodifiedareaandbroadcastmemorychanges
MM_DELANALWipeoffanalysisinthemodifiedareaMM_SILENT Onerror,don'tdisplayerrormessagebox
Seealso:Readmemory
Listmemory
Functionactualizeslistofmemoryblocksand(incaseifWindows95)listofheapsallocatedbyDebuggee.Ifmemoryand/orheapwindowsareopen,alsoupdateswindows.Returns0iftablesareactualizedand-1ifsomeorallofentriesmaybeinvalid.
Asthisoperationistime-consuming,OllyDbgusuallyupdatesmemorytablesonlyifapplicationispaused.Ifpluginaccessesmemorytables"onthefly",itmayneedtocallthisfunction.Notethatreadingorwritingtothememorydoesnotrequireactualizationofmemorytables.
intListmemory(void);
Modulefunctions
Moduleisanexecutablefile(ususllyEXEorDLL)loadedintomemory.OllyDbgkeepslistofloadedmodulesinatableofsorteddataconsistingofelementsoftypet_module.YoucanreceivepointertotableofmodulesbycallingPlugingetvalue(VAL_MODULES)andcastingresultto(t_table*).
t_module*Findmodule(ulongaddr);
t_fixup*Findfixup(t_module*pmod,ulongaddr);
char*Finddecode(ulongaddr,ulong*psize);
ulongFindfileoffset(t_module*pmod,ulongaddr);
intAnalysecode(t_module*pmod);
t_module
Typeofmoduledescriptor.Thisisaverysensitivestructure,donotmodifydirectly!
typedefstructt_module{//Executablemoduledescriptor
ulongbase;//Baseaddressofmodule
ulongsize;//Sizeoccupiedbymodule
ulongtype;//Serviceinformation,TY_xxx
ulongcodebase;//Baseaddressofmodulecodeblock
ulongcodesize;//Sizeofmodulecodeblock
ulongresbase;//Baseaddressofresources
ulongressize;//Sizeofresources
t_stringtable*stringtable;//PointerstostringresourcesorNULL
intnstringtable;//Actualnumberofusedstringtable
intmaxstringtable;//Actualnumberofallocatedstringtable
ulongentry;//Addressof<ModuleEntryPoint>orNULL
ulongdatabase;//Baseaddressofmoduledatablock
ulongidatatable;//Baseaddressofimportdatatable
ulongidatabase;//Baseaddressofimportdatablock
ulongedatatable;//Baseaddressofexportdatatable
ulongedatasize;//Sizeofexportdatatable
ulongreloctable;//Baseaddressofrelocationtable
ulongrelocsize;//Sizeofrelocationtable
charname[SHORTLEN];//Shortnameofthemodule
charpath[MAXPATH];//Fullnameofthemodule
intnsect;//Numberofsectionsinthemodule
IMAGE_SECTION_HEADER*sect;//Copyofsectionheadersfromfile
ulongheadersize;//Totalsizeofheadersinexecutable
ulongfixupbase;//Baseofimageinexecutablefile
intnfixup;//Numberoffixupsinexecutable
t_fixup*fixup;//ExtractedfixupsorNULL
char*codedec;//DecodedcodefeaturesorNULL
ulongcodecrc;//CodeCRCforactualdecoding
char*hittrace;//HittracingdataorNULL
char*hittracecopy;//CopyofINT3-substitutedcode
char*datadec;//DecodeddatafeaturesorNULL
t_tablenamelist;//Listofmodulenames
t_symvar*symvar;//Descriptionsofsymbolicvariables
intnsymvar;//Actualnumberofelementsinsymvar
intmaxsymvar;//Maximalnumberofelementsinsymvar
char*globaltypes;//Globaltypesfromdebuginfo
ulongmainentry;//AddressofWinMain()etc.indbgdata
ulongrealsfxentry;//EntryofpackedcodeorNULL
intupdatenamelist;//Requesttoupdatenamelist
ulongorigcodesize;//Originalsizeofmodulecodeblock
ulongsfxbase;//BaseofmemoryblockwithSFX
ulongsfxsize;//SizeofmemoryblockwithSFX
intissystemdll;//WhethersystemDLL
intprocessed;//0:notprocessed,1:good,-1:bad
intdbghelpsym;//1:symbolsloadedbydbghelp.dll
charversion[NVERS];//Versionofexecutablefile
t_jdest*jddata;//Recognizedjumpswithinthemodule
intnjddata;//Numberofrecognizedjumps
ulongreserved[15];//Reservedforplugincompatibility
}t_module;
Members(membersthatintendedstriclyforinternalusearenotexplained):
base-baseaddressofmoduleinthememoryspaceofdebuggedprocess;
size-totalsizeoccupiedbymodule,notnecessarilycontiguousmemory;
type-serviceinformation,combinationofbitsTY_xxx;
codebase-baseaddressofexecutablecode,asstaysinCOFFheader.Insomecases,OllyDbgmaycorrectdefinitelyinvalidcodebase;
codesize-sizeofexecutablecode,asstaysinCOFFheader.Insomecases,OllyDbgmaycorrectdefinitelyinvalidcodesize;
resbase-baseaddressofresources;
ressize-sizeofresources;
entry-addressofmodule'sentrypoint,asstaysinCOFFheader;
database-baseaddressofmodule'sdatablock.OllyDbgusesheuristicstolocatedata;
idatatable-baseaddressofimportdatatable,asstaysinCOFFheader;
idatabase-baseaddressofimportdatablock,asstaysinCOFFheader;
edatatable-baseaddressofexportdatatable,asstaysinCOFFheader;
edatasize-sizeofexportdatatable,asstaysinCOFFheader;
reloctable-baseaddressofrelocationtable,asstaysinCOFFheader;
relocsize-sizeofrelocationtable,asstaysinCOFFheader;
name-shortnameofthemodule,notnecessarilyNULL-terminated;
path-fullnameofexecutablefile;
nsect-numberofsectionsinthemodule;
sect-pointertocopyofsectionheadersfromtheCOFFheader;
headersize-totalsizeofheadersinexecutablefile;
fixupbase-baseofimageinexecutablefile;
nfixup-numberoffixupsinexecutablefile;
fixup-pointertolistofextractedfixupsorNULL;
mainentry-addressofWinMainorDllEntryPointfromdebuggingdataor0;
realsfxentry-realentryofunpackedSFXcodeor0;
updatenamelist-requesttoupdatenamelist;
issystemdll-1ifmoduleissystemDLL(i.e.DLLresidinginWindows'systemdirectory)and0otherwise;
dbghelpsym-1ifdebugginginformationinoneofMicrosoftformatsisavailableand0otherwise;
version-zero-terminatedASCIIstringcontainingversionofexecutablefile,NVERS-1byteslong;
reserved-reservedforfutureuseexclusivelybyOllyDbg.
Seealso:Findmodule,Findfileoffset
Findmodule
Givenaddressofmemoryindebuggedapplication,returnspointertomoduledescriptorthatthisaddressbelongsto,orNULLifaddressisoutsideanymodule.
t_module*Findmodule(ulongaddr);
Parameters:
addr-addressofmemoryinthememoryspaceofdebuggedapplication.
Seealso:Findfixup,Finddecode,Findfileoffset,t_module
Findfixup
Ifsuppliedaddressbelongstosomemodule,functioncheckswhethertherearefixupsincludingorexceedingthisaddressandreturnspointertofirstsuchfixup.Otherwise,itreturnsNULL.Fixupsaresortedinascendingorderandterminatedbyelement(0,0),socallingproceduremayusereturnedpointertowalkthroughallsubsequentfixups.
t_fixup*Findfixup(t_module*pmod,ulongaddr);
Parameters:
pmod-optionalpointertomoduledescriptor.IfpmodisNULL,Findfixuplooksformoduledescriptorbyitself;
addr-addressinmemoryspaceofdebuggedapplicationwheresearchforfixupswillstart.
Seealso:Findmodule,Finddecode,Findfileoffset,t_module
Analysecode
Analyzesexecutablecodeofspecifiedmodule.Amongothertasks,analysisincludes:
·Recognitionofcommandsandembeddeddata;
·Recognitionof1-and2-stageswitches;
·Recognitionofproceduresandloops;
·Decodingofargumentsofknownfunctions;
·Predictionofcontentsofregisters;
·Formingofcalltree.
Oneveryimportantassumption:codeisvalidandisnotcounterfeit:knowinghowthisanalysisworks,onemaywriteaprogramthatwillbeanalyzedtotallyincorrectly.Functionishighlyheuristical,soneverassumethatresultsare100%reliable.Returns0onsuccessand-1onerror.
intAnalysecode(t_module*pmod);
Parameters:
pmod-pointertomoduledescriptor.
Finddecode
Searchesfordecodingdatathatstartsonspecifiedaddress.Onsuccess,sets*psizetosizeoflocateddataandreturnspointertodecodinginformation.Ifthereisnodecodinginformation,sets*psizeto0andreturnsNULL.Foreachbyteofanalysedcode,correspondingbyteofdecodingdatacontainscombinationoftype,procedureandanalysisfields:
Typefield,useDEC_TYPEMASKtoextractitfromdecodingdata:
DEC_UNKNOWN UnknowntypeDEC_BYTE ByteDEC_WORD Firstbyteof16-bitintegerDEC_NEXTDATA SubsequentbyteofdataDEC_DWORD Firstbyteof32-bitintegerDEC_FLOAT4 Firstbyteof32-bitfloatDEC_FWORD FirstbyteofdescriptororlongpointerDEC_FLOAT8 Firstbyteof64-bitdoubleDEC_QWORD Firstbyteof64-bitintegerDEC_FLOAT10 Firstbyteof80-bitlongdoubleDEC_TBYTE Firstbyteof10-byteBCDintegerDEC_STRING FirstbyteofASCIIstringDEC_UNICODE FirstbyteofUNICODEstringDEC_3DNOW Firstbyteof3DNow!operandDEC_SSE FirstbyteofSSEoperandDEC_BYTESW Bytewhichisasecond-levelswitchindexDEC_NEXTCODE SubsequentbyteofcommandDEC_COMMAND Firstbyteofcommand
DEC_JMPDEST Firstbyteofcommandthatisjumpdestination
DEC_CALLDEST Firstbyteofcommandthatiscall(andmaybejump)destination
Procedurefield,useDEC_PROCMASKtoextractitfromdecodingdata:
DEC_PROC StartofprocedureDEC_PBODY BodyofprocedureDEC_PEND Endofprocedure
BitDEC_CHECKED,ifset,reportsthatbytewasanalyzed.
char*Finddecode(ulongaddr,ulong*psize);
Parameters:
addr-addressofthefirstbyteinthememoryspaceofdebuggedprocessforwhichdecodinginformationisrequested;
psize-pointertovariablethatwillreceivesizeoffounddecodingdataorNULL.
Seealso:Findmodule,Findfixup,Findfileoffset
Findfileoffset
Convertsaddressbelongingtosomemoduleintooffsetinexecutablefile.Returnsoffsetor0ifoffsetcannotbecalculated(forexample,addressbelongstothegapbetweentwosections).
ulongFindfileoffset(t_module*pmod,ulongaddr);
Parameters:
mod-optionalpointertomoduledescriptor.IfpmodisNULL,Findfileoffsetlooksformoduledescriptorbyitself;
addr-addressinmemoryspaceofdebuggedapplicationwheresearchforfixupswillstart.
Seealso:Findmodule,Findfixup,Finddecode,t_module
Dataconversionfunctions
ulongCompress(char*bufin,ulongnbufin,char*bufout,ulongnbufout);
ulongDecompress(char*bufin,ulongnbufin,char*bufout,ulongnbufout);
ulongGetoriginaldatasize(char*bufin,ulongnbufin);
Compress
Compressesbinarydata.Thisfunctionusespatent-freeformofLempel-Zivcompressionalgorithm.Returnslengthofcompresseddataor0ifsomeerrorwasdetectedduringcompression.Firstlongwordintheoutputbufferistheidentifierofcompresseddataandsecondisthelengthoforiginaldata.
ulongCompress(char*bufin,ulongnbufin,char*bufout,ulongnbufout);
Parameters:
bufin-pointertouncompresseddata;
nbufin-sizeofuncompresseddata;
bufout-pointertobufferthatwillreceivecompresseddata;
nbufout-sizeofbufout.
Seealso:Decompress
Decompress
UnpacksdatacompressedbyCompress.Returnslengthofunpackeddataor0ifsomeerrorwasdetectedduringdecompression.
ulongDecompress(char*bufin,ulongnbufin,char*bufout,ulongnbufout);
Parameters:
bufin-pointertocompresseddata;
nbufin-sizeofcompresseddata;
bufout-pointertobufferthatwillreceiveunpackeddata;
nbufout-sizeofbufout.
Seealso:Compress,Getoriginaldatasize
Getoriginaldatasize
ForthedatacompressedbyCompress,returnssizeoftheoriginaldata.Returns0onerror.
ulongGetoriginaldatasize(char*bufin,ulongnbufin);
Parameters:
bufin-pointertocompresseddata;
nbufin-sizeofcompresseddata;
Seealso:Decompress
Pluginfunctions
intRegisterpluginclass(char*classname,char*iconname,HINSTANCEdllinst,WNDPROCclassproc);
voidUnregisterpluginclass(char*classname);
intPluginwriteinttoini(HINSTANCEdllinst,char*key,intvalue);
intPluginwritestringtoini(HINSTANCEdllinst,char*key,char*s);
intPluginreadintfromini(HINSTANCEdllinst,char*key,intdef);
intPluginreadstringfromini(HINSTANCEdllinst,char*key,char*s,char*def);
intPluginsaverecord(ulongtag,ulongsize,void*data);
intPlugingetvalue(inttype);
t_statusGetstatus(void);
Registerpluginclass
Generatesuniqueclassnameandregistersnewclassofpluginwindows.IficonnameisNULL,usesstandardpluginicon(letter'P').Onsuccess,returns0andfillsclassname(atleast32byteslong)withuniqueclassname.Ifregistrationfailed,returns-1.Windowsbelongingtoregisteredclasshas8longwordsofextramemory,pluginisfreetouselongwords2..7(offsets8..28incallstoGetWindowLongandSetWindowLong).ODBG_Plugininitisthebestplacetocallthisfunction.
intRegisterpluginclass(char*classname,char*iconname,HINSTANCEdllinst,WNDPROCclassproc);
Parameters:
classname-pointertobufferoflengthatleast32charactersthatwillreceiveuniqueclassname;
iconname-nameoficonresourceinpluginDLL;
dllinst-plugin'sinstance;
classproc-pointertowindowprocedureofnewclass.
Seealso:Unregisterpluginclass
Unregisterpluginclass
UnregisterswindowclasspreviouslyregisteredbyRegisterpluginclass.CallthisfunctionforeachregisteredclassfromODBG_Plugindestroy.
voidUnregisterpluginclass(char*classname);
Parameters:
classname-classnamereturnedbycalltoRegisterpluginclass.
Seealso:Registerpluginclass
Pluginwriteinttoini
Storesanintegerassociatedwithakeyintheplugin'spersonalsectionoftheollydbg.ini.Returns1onsuccessand0onerror.
intPluginwriteinttoini(HINSTANCEdllinst,char*key,intvalue);
Parameters:
dllinst-plugin'sinstance;
key-nameofthekeytobeassociatedwithaninteger;
value-integertobewrittentoollydbg.ini.
Seealso:Pluginreadintfromini,Pluginwritestringtoini,Pluginreadstringfromini
Pluginreadintfromini
Readsintegerassociatedwithakeyfromtheplugin'spersonalsectionoftheollydbg.ini.Onsuccess,returnsintegerfromtheinitializationsfile.Onerror,returnsspecifieddefaultvalue.
intPluginreadintfromini(HINSTANCEdllinst,char*key,intdef);
Parameters:
dllinst-plugin'sinstance;
key-nameofthekeyassociatedwithaninteger;
def-defaultvalue.
Seealso:Pluginwriteinttoini,Pluginwritestringtoini,Pluginreadstringfromini
Pluginwritestringtoini
StoresASCIIstringassociatedwithakeyintheplugin'spersonalsectionoftheollydbg.ini.Returns1onsuccessand0onerror.
intPluginwritestringtoini(HINSTANCEdllinst,char*key,char*s);
Parameters:
dllinst-plugin'sinstance;
key-nameofthekeytobeassociatedwithastring;
s-stringtobestoredinollydbg.ini.
Seealso:Pluginreadstringfromini,Pluginwriteinttoini,Pluginreadintfromini
Pluginreadstringfromini
Readsstringassociatedwithakeyfromtheplugin'spersonalsectionoftheollydbg.ini.Onsuccess,returnsstringfromtheinitializationsfile.Onerror,returnsspecifieddefaultstring.
intPluginreadstringfromini(HINSTANCEdllinst,char*key,char*s,char*def);
Parameters:
dllinst-plugin'sinstance;
key-nameofthekeyassociatedwiththestring;
s-pointertobufferthatreceivesstring;
def-pointertoanull-terminateddefaultstring.
Seealso:Pluginwritestringtoini,Pluginwriteinttoini,Pluginreadintfromini,
Pluginsaverecord
Writessinglerecordto.uddfile.Returns1onsuccessand0onerror.CallthisfunctiononlyfromODBG_Pluginsaveudd,anyothercallwillfail.
intPluginsaverecord(ulongtag,ulongsize,void*data);
Parameters:
tag-uniqueplugin-specifictag;
size-sizeofdatatobewrittento.uddfile,maximallyUSERLEN;
data-pointertodataofspecifiedsizetobewrittento.uddfile.
Seealso:ODBG_Pluginsaveudd,ODBG_Pluginuddrecord
Plugingetvalue
RetrievesvariousOllyDbgsettingsandvariables.
intPlugingetvalue(inttype);
Parameters:
type-settingorvariabletoretrieve:
type Castto ExplanationVAL_HINST (HINST) CurrentOllyDbginstance
VAL_HWMAIN (HWND) HandleofthemainOllyDbgwindow
VAL_HWCLIENT (HWND) HandleoftheMDIclientwindow
VAL_NCOLORS Numberofcommoncolors
VAL_COLORS (COLORREF*)
RGBvaluesofcommoncolors
VAL_BRUSHES (HBRUSH*) Handlesofcommoncolorbrushes
VAL_PENS (PEN*) Handlesofcommoncolorpens
VAL_NFONTS NumberofcommonfontsVAL_FONTS (HFONT*) HandlesofcommonfontsVAL_FONTNAMES (char**) Internalfontnames
VAL_FONTWIDTHS (int*) Averagewidthsofcommonfonts
VAL_FONTHEIGHTS (int*) Averageheigthsofcommonfonts
VAL_NFIXFONTS Actualnumberoffixed-pitchfonts
VAL_DEFFONT IndexofdefaultfontVAL_NSCHEMES NumberofcolorschemesVAL_SCHEMES (t_scheme*) Colourschemes
VAL_DEFSCHEME Indexofdefaultcolourscheme
VAL_DEFHSCROLL Defaulthorizontalscroll
VAL_RESTOREWINDOWPOS Restorewindowpositionsfrom.ini
VAL_HPROCESS (HANDLE) Handleofdebuggedprocess
VAL_PROCESSID ProcessIDofdebuggedprocess
VAL_HMAINTHREAD (HANDLE) Handleofmainthreadofdebuggedprocess
VAL_MAINTHREADID ThreadIDofmainthreadofdebuggedprocess
VAL_MAINBASE Baseofmainmoduleinthedebuggedprocess
VAL_PROCESSNAME (char*) Nameofthedebuggedprocess
VAL_EXEFILENAME (char*) Nameofthemaindebuggedfile
VAL_CURRENTDIR (char*) Currentdirectoryfordebuggedprocess
VAL_SYSTEMDIR (char*) Windowssystemdirectory
VAL_DECODEANYIP DecoderegistersdependlessonEIP
VAL_PASCALSTRINGS DecodePascal-stylestringconstants
VAL_ONLYASCII OnlyprintableASCIIcharsindump
VAL_DIACRITICALS Allowdiacriticalsymbolsinstrings
VAL_GLOBALSEARCH Searchfromthebeginningofblock
VAL_ALIGNEDSEARCH Searchalignedtoitem'ssize
VAL_SEARCHMARGIN Floatingsearchallowserrormargin
VAL_KEEPSELSIZE Keepsizeofhexeditselection
VAL_MMXDISPLAY MMXdisplaymodeindialog(0:hex,1:signed,2:unsignedMMX)
VAL_WINDOWFONT Usecallingwindow'sfontindialog
VAL_TABSTOPS Distancebetweentabstops
VAL_MODULES (t_table*) Tableofmodules(.EXEand.DLL)
VAL_MEMORY (t_table*) Tableofallocatedmemoryblocks
VAL_THREADS (t_table*) TableofactivethreadsVAL_BREAKPOINTS (t_table*) Tableofactivebreakpoints
VAL_REFERENCES (t_table*) Tablewithfoundreferences
VAL_SOURCELIST (t_table*) TableofsourcefilesVAL_WATCHES (t_table*) Tableofwatches
VAL_CPUFEATURES CPUfeaturebitsasreturnedbyCPUID
VAL_TRACEFILE (FILE*) HandleofruntracelogfileVAL_ALIGNDIALOGS Aligndialogs
VAL_CPUDASM (t_dump*) DumpdescriptorofCPUDisassemblerpane
VAL_CPUDDUMP (t_dump*) DumpdescriptorofCPUDumppane
VAL_CPUDSTACK (t_dump*) DumpdescriptorofCPUStackpane
VAL_APIHELP (char*) NameofselectedAPIhelpfile
VAL_HARDBP Whetherhardwarebreakpointsareenabled
VAL_PATCHES (t_table*) Tableofpatches
VAL_HINTS (t_sorted*) Sorteddatawithanalysishints
Getstatus
Returnscurrentstatusofdebuggedprocess(oneofSTAT_xxx):
STAT_NONE NoprocesstodebugSTAT_STOPPED ProcesssuspendedSTAT_EVENT Processingdebugevent,processtemporarilypausedSTAT_RUNNING ProcessisrunningSTAT_FINISHED ProcessterminatedSTAT_CLOSING TerminateProcess()called,waitingforconfirmation
t_statusGetstatus(void);
Seealso:Plugingetvalue
Sourcecodesupportfunctions
Sourcedebuggingisstillindevelopmentphase.IdecidednottodescribeitinactualversionofPluginAPI.
CPU-specificfunctions
voidSetcpu(ulongthreadid,ulongasmaddr,ulongdumpaddr,ulongstackaddr,intmode);
voidSetdisasm(ulongasmaddr,ulongselsize,intmode);
voidRedrawdisassembler(void);
voidGetdisassemblerrange(ulong*pbase,ulong*psize);
ulongGetcputhreadid(void);
Setcpu
UpdatesstateofpanesinCPUwindow.Ifnecessary,createsorrestoresCPUwindowandmovesittotop.
voidSetcpu(ulongthreadid,ulongasmaddr,ulongdumpaddr,ulongstackaddr,intmode);
Parameters:
threadid-identifiedofthreadtodisplayinCPU,or0ifthreadremainsunchanged.Ifthreadididnon-zero,parametersasmaddrandstackaddrareignoredandsettocontentsofEIPandESPofthespecifiedthread.Ifthreadidis0andactualthreadisinvalid,Setcpuautomaticallyreswitchestomainthread;
asmaddr-addresstodisplayinDisassembler,or0ifthisaddressremainsunchanged.Ignoredifthreadidisnot0;
dumpaddr-addresstodisplayinCPUDump,or0ifthisaddressremainsunchanged;
stackaddr-addresstodisplayinStack,or0ifthisaddressremainsunchanged.Ignoredifthreadidisnot0;
mode-combinationofCPU_xxxflagsthatselectupdatemode:
CPU_ASMHIST AddchangetoDisassemblerhistory
CPU_ASMCENTER PositionaddressinthemiddleofDisassemblerwindow
CPU_ASMFOCUS MovefocustoDisassembler
CPU_DUMPHIST AddchangetoDumphistory(currentlynotavailable)
CPU_DUMPFIRST MakedumpaddrthefirstbyteinCPUDumpCPU_DUMPFOCUS MovefocustoCPUDump
CPU_REGAUTO AutomaticallychangeRegistersmodetoFPU/MMX/3DNow!
CPU_RUNTRACE Showruntracedataatoffsetasmaddr
CPU_NOCREATE Don'tcreateCPUwindowifabsentCPU_REDRAW RedrawCPUwindowimmediatelyCPU_NOFOCUS Don'tforcefocustomainwindow
Seealso:Setdisasm,Redrawdisassembler,Getcputhreadid
Setdisasm
PresetsCPUDisassemblersothatitdisplayscodeataddressasmaddr.Ifselsizeisgreaterthan1,selectsselsizebytes,otherwise1assemblercommand.ThenitcreatesCPUwindow(ifabsent),restoresandmoveswindowtothetop.
voidSetdisasm(ulongasmaddr,ulongselsize,intmode);
Parameters:
asmaddr-addresstodisplayinDisassembler,or0ifthisaddressremainsunchanged.Ignoredifthreadidisnot0;
selsize-ifgreaterthan1,sizeofselectioninbytes,otherwiseSetdisasmselects1command;
mode-combinationofCPU_xxxflagsthatselectupdatemode:
CPU_ASMHIST AddchangetoDisassemblerhistory
CPU_ASMCENTER PositionaddressinthemiddleofDisassemblerwindow
CPU_ASMFOCUS MovefocustoDisassembler
CPU_REGAUTO AutomaticallychangeRegistersmodetoFPU/MMX/3DNow!
Seealso:Setcpu,Redrawdisassembler,Getcputhreadid
Redrawdisassembler
RedrawsDisassemblerbycallingUpdateWindow,sothatallmodificationsareimmediatelyvisible.
voidRedrawdisassembler(void);
Seealso:Setcpu
Getdisassemblerrange
GetsaddressrangeofmemoryblockthatiscurrentlydisplayedinDisassemblerwindow.
voidGetdisassemblerrange(ulong*pbase,ulong*psize);
Parameters:
pbase-pointertovariablethatreceivesbaseaddressofmemoryblockinaddressspaceofdebuggedapplication;
psize-pointertovariablethatreceivessizeofmemoryblock.
Seealso:Getcputhreadid
t_dump
Typeofdumpdescriptor.
typedefstructt_dump{//Currentstatusofdumpwindow
t_tabletable;//Treatdumpwindowascustomtable
intdimmed;//Drawinlowcolorifnonzero
ulongthreadid;//Usedecodingandregistersifnot0
intdumptype;//Currentdumptype,DU_xxx+count+size
SPECFUNC*specdump;//DecoderofDU_SPECdumptypes
intmenutype;//Standardmenus,MT_xxx
intitemwidth;//Lengthofdisplayeditem,characters
intshowstackframes;//Showstackframesinaddressdump
intshowstacklocals;//Shownamesoflocalsinstack
intshowsource;//Showsourceascommentindisassembler
charfilename[MAXPATH];//Nameofdisplayedorbackupfile
ulongbase;//Startofmemoryblockorfile
ulongsize;//Sizeofmemoryblockorfile
ulongaddr;//Addressoffirstdisplayedbyte
ulonglastaddr;//Addressoflastdisplayedbyte+1
ulongsel0;//Addressoffirstselectedbyte
ulongsel1;//Lastselectedbyte(notincluded!)
ulongstartsel;//Startoflastselection
intcaptured;//Mouseiscapturedbydump
ulongreladdr;//Addressesrelativetothis
charrelname[SHORTLEN];//Symbolforrelativezeroaddressbase
char*filecopy;//CopyofthefileorNULL
char*backup;//Oldbackupofmemory/fileorNULL
intruntraceoffset;//Offsetbackinruntrace
ulongreserved[8];//Reservedforthefutureextentions
}t_dump;
Members:
table-structurethatdescribesdumpwindowasacustomtable;
threadid-ifnon-zero,windowbelongstoCPUandshuldusethread'sregisterswhendisassemblingdata;
dumptype-currentdumptype,combinationofdumptype(oneofDU_xxx),numberofitemsperline((n<<8)&DU_COUNT)andsizeofsingleitem(l&DU_SIZE).AdditionallycanbeORedwithonbeofthefollowingbits:
DU_ESCAPABLE DumpwindowwillcloseonESCkey
DU_BACKUP Dumpwindowdisplaysbackupdata
Forvariable-lengthtypesthesizeis1.SeedescriptionofCreatedumpwindowforalistofcommonlyuseddumptypes;
base-baseaddressofdisplayedmemoryinthememorysizeofdebuggedprocess,usually0forfiledump;
size-sizeofdisplayedfileormemoryarea;
addr-addressoroffsetofthefirstdisplayedbyte;
sel0-addressoroffsetofthefirstselectedbyte(included);
sel1-addressoroffsetofthelastselectedbyte(notincluded);
filecopy-pointertocopyofdisplayedfile,orNULLifthisismemorydump;
backup-pointertolocalbackupofdumpdata,orNULLifbackupisabsent;
runtraceoffset-stepbackinruntrace,or0ifinactive.
Seealso:Createdumpwindow,ODBG_Pluginuddrecord,ODBG_Pluginmenu,ODBG_Pluginaction
t_window
Typeofwindowdescriptor-structuredescribingwindoworcontrolcreatedbydebuggedapplication.
typedefstructt_window{//Descriptionofwindow
ulonghwnd;//Window'shandle
ulongdummy;//Mustbe1
ulongtype;//Typeofwindow,TY_xxx
ulongparenthw;//Handleofparentor0
ulongwinproc;//AddressofWinProcor0
ulongthreadid;//IDoftheowningthread
ulongexstyle;//Extendedwindowstyle
ulongstyle;//Windowstyle
ulongid;//Identifierormenuhandle
ulongclassproc;//Addressofdefault(class)WinProc
intchild;//Indexofnextchild
intlevel;//Levelingenealogy(0:topmost)
intsibling;//Indexofnextsibling
intbyparent;//Indexwhensortedbyparent
chartitle[TEXTLEN];//Window'stitle
charclassname[TEXTLEN];//Classname
chartree[MAXNEST];//ForinternalusebyOllyDbg
}t_window;
Members:
hwnd-handleofwindow(control)createdbydebuggedapplication,casttoHWNDtouseasahandleincallstoWindowsAPIroutines;
dummy-ustbe1toobeytherulesofsorteddata;
type-typeofwindow.TheonlyimportantflaghereisTY_NEW;
parenthw-handleofparentwindoworNULL.Insomecasethismaybethehandleofdesktop(obtainablebycalltoGetDesktopWindow();
winproc-addressofwindowprocedureassociatedwithwindowinmemorycontextofdebuggedapplication.OnNT-basedsystems,GetWindowLong(hwnd,GWL_WNDPROC)returns0andOllyDbgusescodeinjectiontoobtainthisaddress;
threadid-identifierofthreadthatownswindow;
exstyle-extendedstyleofwindow,setofWS_EX_xxxandsimilarflags;
style-styleofwindow,setofWS_xxxandsimilarflags;
id-control'sidentifier;
classproc-addressofwindow'sclassprocedure.Ifclassprocdiffersfromwinproc,windowissubclassed;
title-ASCIIstringwithwindow'stitleortext;
classname-ASCIIstringwithwindow'sclassname.
t_ref
Typeofreferencedescriptor.
typedefstructt_ref{//Descriptionofreference
ulongaddr;//Addressofreference
ulongsize;//1:singlecommand,otherwisesize
ulongtype;//Typeofreference,TY_xxx
ulongdest;//Destinationofcall
}t_ref;
Members:
addr-addressofreferencingcommandordata;
size-1ifsinglecommandisreferenced,ortotalsize,bytes,ofselectedcommandsotherwise;
type-typeofreference,combinationofTY_xxxflags:
TY_REFERENCE ItemisarealreferenceTY_ORIGIN Itemisasearchorigin
dest-destinationofintermodularcall,0foranyotherreference.
Plugincallbackfunctions
Plugininterfaceincludesseveralcallbackfunctions.OllyDbgcallsthemtoinstallorremovepluginandonimportantevents,likeselectedmenuitemorpressedshortcutkey.Onlytwocallbackaremandatory:ODBG_PlugindataandODBG_Plugininit,allotherareoptional.Don'tforgettoexportyourcallbacks!
intODBG_Plugindata(char*shortname);
intODBG_Plugininit(intollydbgversion,HWNDhw,ulong*features);
voidODBG_Pluginmainloop(DEBUG_EVENT*debugevent);
voidODBG_Pluginsaveudd(t_module*pmod,intismainmodule);
intODBG_Pluginuddrecord(t_module*pmod,intismainmodule,ulongtag,ulongsize,void*data);
intODBG_Pluginmenu(intorigin,chardata[4096],void*item);
voidODBG_Pluginaction(intorigin,intaction,void*item);
intODBG_Pluginshortcut(intorigin,intctrl,intalt,intshift,intkey,void*item);
voidODBG_Pluginreset(void);
voidODBG_Pluginclose(void);
voidODBG_Plugindestroy(void);
intODBG_Paused(intreason,t_reg*reg);
intODBG_Pausedex(intreason,intextdata,t_reg*reg,DEBUG_EVENT*debugevent);
intODBG_Plugincmd(intreason,t_reg*reg,char*cmd);
ODBG_Paused
Optionalcallbackfunction.Ifpresent,OllyDbgwillcalliteachtimethedebuggedapplicationispausedandafterallinternalprocessingisfinished.Pluginmay,forexample,makesomemodificationsandimmediatelycontinueexecutionbycalingGo.Inthiscaseitmayreturn1,disablingtime-consumingredrawingofwindows.Inanyothercaseitmustreturn0.
NotethatifpluginexportsbothODBG_PausedandODBG_Pausedex,onlythesecondfunctionwillbecalled.
intODBG_Paused(intreason,t_reg*reg);
Parameters:
reason-reasonwhyapplicationwaspaused:
PP_EVENT PausedondebuggingeventPP_PAUSE Pausedonuser'srequestPP_TERMINATEDApplicationterminated
reg-pointertoregistersofthreadthatcausedapplicationtopause,maybeNULL.
Seealso:ODBG_Pausedex
ODBG_Pausedex
Optionalcallbackfunction.Ifpresent,OllyDbgwillcalliteachtimethedebuggedapplicationispausedandafterallinternalprocessingisfinished.Pluginmay,forexample,makesomemodificationsandimmediatelycontinueexecutionbycalingGo.Inthiscaseitmayreturn1,disablingtime-consumingredrawingofwindows.Inanyothercaseitmustreturn0.
NotethatifpluginexportsbothODBG_PausedexandODBG_Paused,thesecondfunctionwillnotbecalled.
intODBG_Pausedex(intreason,intextdata,t_reg*reg,DEBUG_EVENT*debugevent);
Parameters:
reason-reasonwhyapplicationwaspaused,usePP_MAINtoextract:
PP_EVENT PausedondebuggingeventPP_PAUSE Pausedonuser'srequestPP_TERMINATEDApplicationterminated
ThereasonmaybeORedwithoneorseveralofthefollowingclarifiers:
PP_BYPROGRAMDebuggingeventcausedbyprogram
PP_INT3BREAK INT3breakpointPP_MEMBREAK MemorybreakpointPP_HWBREAK HardwarebreakpointPP_SINGLESTEP Single-steptrapPP_EXCEPTION Exception,likedivisionby0
PP_ACCESS Accessviolation,likewritingtoNULLpointer
PP_GUARDED Guardedpage
extdata-reserved,currentlyalways0;
reg-pointertoregistersofthreadthatcausedapplicationtopause,maybeNULL;
debugevent-pointertodebugeventthatcausedpause,orNULLiftherewasnoevent.
Seealso:ODBG_Paused
ODBG_Plugincmd
Optionalcallbackfunction.Ifpresent,OllyDbgwillcalliteachtimethedebuggedapplicationpausesonconditionalloggingbreakpointthatspecifiescommandstobepassedtoplugins.EachcommandispassedtoeverypluginthatexportsODBG_Plugincmd,sopluginmustdecidebyitselfwhetheritshouldexecutecommandornot.Forexample,samplecommandlinepluginacceptsallcommandsthatbeginwithapoint.Ifpluginrecognizescommand,itmustreturn1tostopOllyDbgfrompassingittoremainingplugins.Otherwise,itmustreturn0.
intODBG_Plugincmd(intreason,t_reg*reg,char*cmd);
Parameters:
reason-reasonwhyprogramwaspaused,currentlyalwaysPP_EVENT;
reg-pointertoregistersofthreadthatcausedapplicationtopause,maybeNULL;
cmd-null-terminatedcommandtoplugin.
ODBG_Plugindata
MandatorycallbackfunctionthatmustbepresentinanyvalidOllyDbgplugin.Itmustfillinpluginnameandreturnversionofplugininterface(constantPLUGIN_VERSION).Iffunctionisabsent,orversionisnotcompatible,pluginwillbenotinstalled.ShortnameidentifiesplugininOllyDbg.Thisnameislimitedto31alphanumericalcharactersorspacesfollowedbyterminatingnullcharacter.Tokeeplifeeasyforusers,nameshouldbedescriptiveandcorrelatewiththenameofDLL.
intODBG_Plugindata(char*shortname);
Parameters:
shortname-pointertobufferoflengthatleast32charactersthatreceivesnameofplugin.Thisnamemayincludespacesandpunctuatorsbutnospecialsymbols.
ODBG_Plugininit
MandatorycallbackfunctionthatmustbepresentinanyvalidOllyDbgplugin.Hereyoucanplaceallstartupinitializationsandallocateresources.Ifstartupwassuccessfull,functionmustreturn0.Onerror,itmustfreeallocatedresourcesandreturn-1,inthiscasepluginwillberemoved.ParameterollydbgversionistheversionofOllyDbg,useittoassurethatOllyDbgiscompatiblewithyourplugin.
intODBG_Plugininit(intollydbgversion,HWNDhw,ulong*features);
Parameters:
ollydbgversion-versionofOllyDbg.Checkthatyourpluginiscompatiblewiththisversion.IwilltrytoavoidincompatiblechangesinthefutureversionsofOllyDbg;
hw-handleofmainOllyDbgwindow,keepitifnecessary;
features-reservedforfutureextentions.
Seealso:ODBG_Pluginreset,ODBG_Pluginclose,ODBG_Plugindestroy
ODBG_Pluginmainloop
Optionalcallbackfunction.Ifpresent,OllyDbgwillcallitoneachpassofmainloop.Hereyoucandoallyourperiodicaltasks.Don'tassumethatcallsareequidistant;theyaren't.Donotexportthisfunctionunnecessarily,asthismaynegativelyinfluencetheoverallspeed!
voidODBG_Pluginmainloop(DEBUG_EVENT*debugevent);
Parameters:
debugevent-pointertodebugeventreceivedbycalltoWindowsAPIfunctionWaitForDebugEvent,orNULLiftherewasnoevent.
ODBG_Pluginsaveudd
Optionalcallbackfunction.Ifpresent,OllyDbgcallsitwhensomemodulerequeststosavemodule-orapplication-relateddatato.uddfile.Tosavedatato.uddfile,callPluginsaverecordforeachdataitemthatmustbesaved.Global,appliction-orienteddatamustbesavedintehmain.uddfile;module-relevantdatamustbesavedinmodule.uddfiles.Savealladdressesrelativetothebaseofmodulesothatdatawillberestoredcorrectlyevenwhenmoduleisrelocated.
voidODBG_Pluginsaveudd(t_module*pmod,intismainmodule);
Parameters:
pmod-pointertomoduledescriptor;
ismainmodule-flagindicatingwhetherthisismainmoduleofdebuggedapplication(.exe).
Seealso:Pluginsaverecord,t_module
ODBG_Pluginuddrecord
Optionalcallbackfunction.Ifpresent,OllyDbgcallsODBG_Pluginuddrecordwhenitreads.uddfileandencountersunrecognizedrecord.Ifrecordbelongstoplugin,itmustprocessrecordandreturn1,otherwiseitmustreturn0topassrecordtootherplugins.Notethatmoduledescriptorpointedtobypmodcanbeincomplete,i.e.doesnotnecessarilycontaininformationstoredinprocessed.uddfile,likedecodingdataorhittracebufer.
intODBG_Pluginuddrecord(t_module*pmod,intismainmodule,ulongtag,ulongsize,void*data);
Parameters:
pmod-pointertomoduledescriptor;
ismainmodule-flagindicatingwhetherthisismainmoduleofdebuggedapplication(.exe);
tag-tagthatidentifiesrecord;
size-sizeofdata;
data-pointertobinaryrecorddata.
Seealso:Pluginsaverecord,t_module
ODBG_Pluginmenu
Optionalcallbackfunction.Ifpresent,OllyDbgcallsittogivepluginthepossibilitytoaddmenuitemseithertomainOllyDbgmenu(origin=PM_MAIN)ortopopupmenuinoneofstandardOllyDbgwindows.Toaddmenuitems,pluginmustpreparestringthatdescribesmenustructureandreturn1,otherwiseitmustreturn0.AsageneralOllyDbgrule,donotaddinactiveitemstomenu.
intODBG_Pluginmenu(intorigin,chardata[4096],void*item);
Parameters:
origin-codeofwindowthatcallsODBG_Pluginmenu.OllyDbgsupportsfollowingcodes:
Code Castitemto WhocallsODBG_Pluginmenu
PM_MAINitemisalwaysNULL
Mainwindow
PM_DUMP (t_dump*) AnyDumpwindowPM_MODULES (t_module*) ModuleswindowPM_MEMORY (t_memory*) MemorywindowPM_THREADS (t_thread*) ThreadswindowPM_BREAKPOINTS (t_bpoint*) BreakpointswindowPM_REFERENCES (t_ref*) ReferenceswindowPM_RTRACE (int*) Runtracewindow
PM_WATCHES (1-basedindex) Watcheswindow
PM_WINDOWS (t_window*) WindowswindowPM_DISASM (t_dump*) CPUDisassemblerPM_CPUDUMP (t_dump*) CPUDumpPM_CPUSTACK (t_dump*) CPUStackPM_CPUREGS (t_reg*) CPURegisters
data-pointertobuffer4Kbyteslongthatreceivesdescriptionofmenustructure.
Ordinarymenuitemconsistsofdecimalidentificator(0to63)followedbyname.Whenuserselectssomemenuitem,Pluginactionreceivesidentifierofthisitem.Duplicatedidentifiersareallowed.Usecomma(,)toseparatemenuitems.Verticalline(|)placeshorizontaldividinglineinmenu.Tocreatesubmenu,additsnamefollowedbycontentsofsubmenuenclosedintobraces.OllyDbgautomaticallyremovesunnecessaryorduplicatedseparatorsandemptysubmenus.Toforcehorizontaldividingline,use#symbol.Someexamples:
0&Aaa,2&Bbb|3&Ccc|,,
Linearmenuwith3items:Aaa,BbbandCcc,relativeIDs0,2and3,menushortcutsA,BandC.Separatorbetweensecondandthirditem,lastseparatorandcommasareignored
#A{0Aaa,B{1Bbb|2Ccc}}
Unconditionalseparator,followedbypopupmenuAwithtwoelements,secondofthemispopupBwithtwoelementsandseparatorinbetween
item-pointereithertoselectedelementofsorteddatadisplayedinwindowor,incaseofdumpwindows,pointertodumpdescriptor.CanbeNULL.Youmayneedthiselementtofindoutwhichmenuitemsapplytoselecetditem.
Seealso:ODBG_Pluginaction,Pluginaction,Plugingetvalue
ODBG_Pluginaction
Optionalcallbackfunction.Ifpresent,OllyDbgcallsiteachtimetheuserselectedmenuitemaddedtomenubyODBG_Pluginmenu.
voidODBG_Pluginaction(intorigin,intaction,void*item);
Parameters:
origin-codeofwindowthatcallsODBG_Pluginaction.OllyDbgsupportsfollowingcodes:
Code Castitemto WhocallsODBG_Pluginmenu
PM_MAINitemisalwaysNULL
Mainwindow
PM_DUMP (t_dump*) AnyDumpwindowPM_MODULES (t_module*) ModuleswindowPM_MEMORY (t_memory*) MemorywindowPM_THREADS (t_thread*) ThreadswindowPM_BREAKPOINTS (t_bpoint*) BreakpointswindowPM_REFERENCES (t_ref*) ReferenceswindowPM_RTRACE (int*) Runtracewindow
PM_WATCHES (1-basedindex) Watcheswindow
PM_WINDOWS (t_window*) WindowswindowPM_DISASM (t_dump*) CPUDisassemblerPM_CPUDUMP (t_dump*) CPUDumpPM_CPUSTACK (t_dump*) CPUStackPM_CPUREGS (t_reg*) CPURegisters
action-identifierofmenuitem(0..63),assetbyODBG_Pluginmenu;
item-pointereithertoselectedelementofsorteddatadisplayedinwindowor,incaseofdumpwindows,pointertodumpdescriptor,orNULL.Youmayneedthis
elementtocarryoutrequestedaction.
Seealso:ODBG_Pluginmenu,Pluginaction,Plugingetvalue,Custommessages
ODBG_Pluginshortcut
Optionalcallbackfunction.Ifpresent,OllyDbgcallsiteachtimewhenuserpressescombinationofkeysthatisnotrecognizedbystandardOllyDbgwindow.Thisfunctionisusuallycalledtwice:firsttimewithorigin=PM_MAINindicatingglobalshortcut,andsecondtimewithoriginidentifierofwindowthathaskeyboardfocus.ShortcutsarescarceresourceandIwillconstantlyaddnewtoOllyDbg,sousethisfeaturewithcareandalwaysimplementalternativepossibilities.
intODBG_Pluginshortcut(intorigin,intctrl,intalt,intshift,intkey,void*item);
Parameters:
origin-codeofwindowthatcallsODBG_Pluginshortcut.OllyDbgsupportsfollowingcodes:
Code Castitemto WhocallsODBG_Pluginmenu
PM_MAINitemisalwaysNULL
Mainwindow
PM_DUMP (t_dump*) AnyDumpwindowPM_MODULES (t_module*) ModuleswindowPM_MEMORY (t_memory*) MemorywindowPM_THREADS (t_thread*) ThreadswindowPM_BREAKPOINTS (t_bpoint*) BreakpointswindowPM_REFERENCES (t_ref*) ReferenceswindowPM_RTRACE (int*) Runtracewindow
PM_WATCHES (1-basedindex) Watcheswindow
PM_WINDOWS (t_window*) WindowswindowPM_DISASM (t_dump*) CPUDisassemblerPM_CPUDUMP (t_dump*) CPUDumpPM_CPUSTACK (t_dump*) CPUStack
PM_CPUREGS (t_reg*) CPURegisters
ctrl-stateofCtrlkey:0-released,1-pressed;
alt-stateofAltkey:0-released,1-pressed;
shift-stateofShiftkey:0-released,1-pressed;
key-codeofpressedvirtualkey(VK_xxx).See"VirtualKeyCodes"inWindowsAPIhelpforacompletelistofvirtualkeycodes;
item-pointereithertoselectedelementofsorteddatadisplayedinwindowor,incaseofdumpwindows,pointertodumpdescriptor,orNULL.Youmayneedthiselementtocarryoutrequestedaction.
ODBG_Pluginreset
Optionalcallbackfunction.Ifpresent,OllyDbgcallsODBG_Pluginresetwhenuseropensneworrestartscurrentapplication.Pluginshouldresetinternalvariablesanddatastructurestoinitialstate.
voidODBG_Pluginreset(void);
ODBG_Pluginclose
OllyDbgcallsthisoptionalfunctionwhenuserwantstoterminateOllyDbg.AllMDIwindowscreatedbypluginstillexist.Thisisthebestpossibilitytosavepluginparametersto.inifile.Functionmustreturn0ifitissafetoterminateOllyDbg.Anynon-zeroreturnwillstopclosingsequence.Donotmisusethispossibility!Alwaysinformuseraboutthereasonswhyterminationisnotgoodandaskforhisdecision!
voidODBG_Pluginclose(void);
Seealso:ODBG_Plugindestroy,Pluginwriteinttoini,Pluginwritestringtoini
ODBG_Plugindestroy
OllyDbgcallsthisoptionalfunctiononceonexit.Atthismoment,allMDIwindowscreatedbypluginarealreadydestroyed(receivedWM_DESTROYmessages).Functionmustfreeallinternallyallocatedresources,likewindowclasses,files,memoryandsoon.
voidODBG_Plugindestroy(void);
Breakpointfunctions
INT3breakpointsarebrieflyexplainedhere.
intManualbreakpoint(ulongaddr,intkey,intshiftkey,ulongnametype,intfont);
voidTempbreakpoint(ulongaddr,intmode);
intSetbreakpoint(ulongaddr,ulongtype,ucharcmd);
intSetbreakpointext(ulongaddr,ulongtype,ucharcmd,ulongpasscount);
ulongGetbreakpointtypecount(ulongaddr,ulong*passcount);
intSetmembreakpoint(inttype,ulongaddr,ulongsize);
NotethathardwarebreakpointsarenotsupportedbyWindows95andWindows98.Toassurethatyoucanusefunctionslistedbelow,callPlugingetvalue(VAL_HARDBP):
intSethardwarebreakpoint(ulongaddr,intsize,inttype);
intHardbreakpoints(intcloseondelete);
intDeletehardwarebreakpoint(intindex);
intDeletehardwarebreakbyaddr(ulongaddr);
Setbreakpoint
Simplified(old)versionofSetbreakpointext,keptforcompatibilityreasons.EquivalenttocallSetbreakpointext(addr,type,cmd,0).
intSetbreakpoint(ulongaddr,ulongtype,ucharcmd);
Parameters:
addr-addressofbreakpoint.Ifaddresspointstodataorinthemiddleofthecommand,OllyDbgwillaskyouforconfirmation;
type-combinationofbitsTY_xxxthatspecifyrequestedactionsandtypeofbreakpoint,seedescriptionofSetbreakpointext;
cmd-originalcommandthatwillbesavedtodescriptorifbitTY_KEEPCODEisset.Otherwise,thisparameterisignoredandcommandisreadfromthememory.
Setbreakpointext
SetsnewINT3breakpointorchangestypeofexistingbreakpointatspecifiedaddress.Returns0onsuccessand-1onerror(i.e.breakpointwasneithersetnorrestored).IfbitTY_KEEPCONDintypeisset,condition,explanationandexpressionassociatedwithbreakpoint(explainedhere)remainunchanged,otherwisetheyareremoved.IfbitTY_SETCOUNTissetorbreakpointisabsent,setsspecifiedpasscount,otherwisepasscountremainsunchanged.
intSetbreakpointext(ulongaddr,ulongtype,ucharcmd,ulongpasscount);
Parameters:
addr-addressofbreakpoint.Ifaddresspointstodataorinthemiddleofthecommand,OllyDbgwillaskyouforconfirmation;
type-combinationofbitsTY_xxxthatspecifyrequestedactionsandtypeofbreakpoint:
Flag Meaning
TY_ACTIVE Setpermanent(user)breakpointorrestoredisabled
TY_DISABLEDTemporarilydeactivatepermanentbreakpoint.IfTY_ACTIVEandTY_DISABLEDaresetsimultaneously,TY_DISABLEDisignored
TY_ONESHOTSetone-shotbreakpointthatwillbeautomaticallyremovedwhenhit.Doesn'tinterferewithactivebreakpoint
TY_TEMP
Settemporarybreakpointthatwillbeautomaticallyremovedwhenhit.Executioncontinuesautomatically.TY_TEMPdoesnotinterferewithactivebreakpoint
TY_STOPAN StopanimationifbreakpointishitTY_KEEPCODE Forceoriginalcommand(parametercmd)
TY_SETCOUNT ForcepasscountevenifbreakpointalreadyexistsLeaveassociatednamesoftypesNM_BREAK,
TY_KEEPCOND NM_BREAKEXPR,NM_BREAKEXPLandNM_PLUGCMDunchanged.Ifthisbitisnotset,breakpointsoftypesTY_ACTIVEandTY_DISABLEDclearthesenames
cmd-originalcommandthatwillbesavedtodescriptorifbitTY_KEEPCODEisset.Otherwise,thisparameterisignoredandcommandisreadfromthememory;
passcount-passcount,i.e.thenumberoftimesthisbreakpointshouldbeskipped.IfbreakpointalreadyexistsandflagTY_SETCOUNTisnotset,thisparameterisignoredandpasscountremainsunchanged.
Tosetconditionalbreakpoint,consideruseofManualbreakpoint.Ifbreakpointmustbesetautomatically(i.e.withoutuser'sinterference),pleasedothefollowing:
·Ifdebuggedprogramisstillrunning,callSuspendprocesstomakefollowingoperationsatomic;
·CallSetbreakpointext(addr,TY_ACTIVE,0,passcount),thussettingINT3breakpointandrelatedpasscount.Thisisenoughforordinary(unconditional)breakpoint;
·Ifnecessary,setconditionbycalltoInsertname(addr,NM_BREAK,condition).Thisisenoughforconditionalbreakpoint;
·Tosetconditionalloggingbreakpoint,youmustadditionallypreparecontrolbyte,expressionandexplanationandsetthemcallingInsertname(NM_BREAKEXPR)andInsertname(NM_BREAKEXPL);
·Ifnecessary,resumeexecution(Go).
Seealso:Breakpointfunctions,Manualbreakpoint,Setbreakpoint,Getbreakpointtypecount.
Howbreakpointworks
OllyDbgsupportsmanykindsofINT3breakpoints:ordinary,conditionalandconditionallogging.Ofcourse,internallythisisthesamebreakpointwithdifferentoptionsactivated.Atthefirstglance,itlooksovercomplicatedandillogical;butitisreallyso.Version2.0shouldmakebreakpointsbetter,butnowyoumustlivewithwhatyouhave.
Breakpointconsistsofsingle-bytecommandINT3thatreplacesfirstbyteofthebreakpointedcommand,descriptoroftypet_bpointintableofactivebreakpointsandseveralnamesassociatedwiththesameaddressthatspecifyexpressionsandnecessaryactions:
Nametype Meaning
NM_BREAKConditionassociatedwithbreakpoint.Ifconditionisabsentorinvalid,OllyDbgassumesthatitistrue;
NM_BREAKEXPL
Explanation-anytextthatidentifiesbreakpointtouser.Usuallyhasnospecialmeaning.Messagebreakpointsusespecialname"<WinProc>";
NM_BREAKEXPR
Expressionthatshouldbeestimatedandlogged.Firstbyteofexpressioncontainsflags(setofCOND_xxx,explainedbelow)thatcontrolbehaviourofbreakpoint;
NM_PLUGCMD
Commandsthatwillbepassed,onebyone,topluginsifbreakpointistaken.CommandareseparatedbyCR,LForCRLF.
Ordinarybreakpoint(toggledifyoupressF2)hasnoassociatednamesandzeropasscount.Programpauseswheneverthisbreakpointishit.
Conditionalbreakpoint(shortcutShift+F2)hasassociatednameoftypeNM_BREAK.Ifbreakpointishit,OllyDbgestimatesvalueofexpression.Ifresultisnot0,orexpressionisinvalid,programpauses.Otherwise,OllyDbg
continuesexecution.
Conditionalloggingbreakpoint(Shift+F4)hasatleastassociatednameoftypeNM_BREAKEXPR.FirstbyteofthisnameisasetofflagsCOND_xxxthatspecifyadditionaloptions.StrangesettingsofbitsCOND_NOBREAKandCOND_BRKALWAYSareforbackwardcompatibilitywithversion1.00.Asyousee,sodeepcompatibilityisnotalwaysgood:
Bit Meaning Equivalentindialog
COND_NOBREAK
Don'tpauseexecutionifbreakpointishit.HashigherprioritythanCOND_BRKALWAYS
Pauseprogram:Never
COND_BRKALWAYS
Alwayspauseifbreakpointishit.IfbothCOND_NOBREAKandCOND_BRKALWAYSarezero,pauseoncondition
Pauseprogram:Always
COND_LOGTRUE
EstimatevalueofexpressionNM_BREAKEXPRandlogittogetherwithNM_BREAKEXPLifconditionistrue
Logvalue:Oncondition
COND_LOGALWAYS Alwayslogvalueofexpression Logvalue:Always
COND_ARGTRUEDecodeandlogargumentsofknownfunctionifexpressionistrue
Logarguments:Oncondition
COND_ARGALWAYS AlwayslogargumentsofknownfunctionLogarguments:Always
COND_FILLING Alwayssettoassurethatresultingbyteisnot0
Descriptorofbreakpointcontainspasscount.ThisfeatureisnewtoOllyDbg1.10.Ifbreakpointishitandconditions(ortheirabsence)indicatethatprogramshouldbepaused,OllyDbgcomparespasscountwith0.Ifcountis0,programpauses.Otherwise,OllyDbgdecrementscounterandcontinuesexecution.Passcountdoesnotrestoreautomatically,thatis,afteritisdecrementedtozero,it
remainszerountiluserorpluginwillsetitagain.
Seealso:Breakpointfunctions,Manualbreakpoint,Setbreakpoint,Setbreakpointext,Getbreakpointtypecount.
Getbreakpointtypecount
Returnstype(combinationofbitsTY_xxx)andassociatedpasscountofINT3breakpointatspecifiedaddress.Ifbreakpointdoesn'texist,returnsTY_INVALID.
ulongGetbreakpointtypecount(ulongaddr,ulong*passcount);
Parameters:
addr-addressofbreakpoint;
passcount-pointertovariablethatwillreceivepasscount,canbeNULL.
Seealso:Breakpointfunctions,Howbreakpointworks,Manualbreakpoint,Setbreakpoint,Setbreakpointext.
t_bpoint
TypeofINT3breakpointdescriptor:
typedefstructt_bpoint{//DescriptionofINT3breakpoint
ulongaddr;//Addressofbreakpoint
ulongdummy;//Always1
ulongtype;//Typeofbreakpoint,TY_xxx
charcmd;//Oldvalueofcommand
ulongpasscount;//Actualpasscount
}t_bpoint;
Members(membersthatintendedstriclyforinternalusearenotexplained):
addr-addressofbreakpoint;
dummy-lengthofbreakpoint,mustbe1;
type-typeofbreakpoint,combinationofbitsTY_xxx.Avoiddirectmodification.Pleasedonotchangeflagsthatarenotdescribedhere:
Flag MeaningTY_SET CodeINT3isinmemory.Neverchange!TY_ACTIVE Permanent(user)breakpointTY_DISABLED Temporarilydeactivatedpermanentbreakpoint
TY_ONESHOT One-shotbreakpointsetbyOllyDbg,automaticallyremovedifbreakpointishit
TY_TEMP
Temporarybreakpoint,usedinternallybyOllyDbg,forexampletostepoverpermanentbreakpoint.Automaticallyremovedwhenhit,executioncontinues
cmd-originalcommandatspecifiedaddress.Ifbreakpointisactive,thiscommandisreplacedinmemorybyINT3;
passcount-counterthatindicateshowmanytimesthisbreakpointmustbeskipped.IfOllyDbgdecidesthatprogramshouldpauseatbreakpointandpasscountisnot0,itdecrementspasscountandcontinuesexecution.NotethatthisitemisnewtoOllyDbg1.10.
Togetbreakpointdescriptor,youmayusethefollowingcode:
t_table*bptable;
t_bpoint*bpoint;
bptable=(t_table*)Plugingetvalue(VAL_BREAKPOINTS);
if(bptable!=NULL){
bpoint=(t_bpoint*)Findsorteddata(&(bptable->data),addr);
if(bpoint!=NULL){
.....anynecessaryactions.....
}
}
Seealso:Breakpointfunctions,Setbreakpoint,Setbreakpointext,Tempbreakpoint
Manualbreakpoint
FacilitatesmanualINT3breakpointsetting,eitherfrommenuorkeyboardshortcut.SupportsstandardOllyDbg"lookandfeel".Returns0ifsomeactiontookplaceand-1otherwise.Followingcombinationsaresupported:
key shiftkey ActionVK_F2 0 Toggleunconditionalbreakpoint
VK_F2 Pressed(not0) Setconditionalbreakpoint
VK_F4 Pressed(not0) Setloggingbreakpoint
intManualbreakpoint(ulongaddr,intkey,intshiftkey,ulongnametype,intfont);
Parameters:
addr-memoryaddressintheaddressspaceofdebuggedapplicationwhereINT3breakpointmustbeset;
key-VK_F2orVK_F4(seeabove);
shiftkey-stateofshiftkey(seeabove);
nametype-setto0whencallingManualbreakpointfromplugin;
font-indexofpredefinedfonttobeusedininvokeddialogs.Ifnotsure,useFIXEDFONT.
Tempbreakpoint
Setstemporaryorone-shotbreakpointonexecution.Ifpossible,setshardwarebreakpoint,otherwiseINT3.OllyDbgautomaticallyremovestemporaryandone-shotbreakpoints.
voidTempbreakpoint(ulongaddr,intmode);
Parameters:
addr-codeaddresswheretemporarybreakpointshouldbeset;
mode-typeofbreakpointtoset:
TY_ONESHOT|TY_KEEPCOND
Setone-shotbreakpoint.OllyDbgautomaticallyremovesone-shotbreakpointwhenhitandpausesdebuggedapplication
TY_ONESHOT|TY_KEEPCOND|TY_STOPAN
Sameasabove,additionallystopsanykindoftraceoranimationwhenhit
TY_TEMP|TY_KEEPCOND
Settemporarybreakpoint.OllyDbgautomaticallyremovestemporarybreakpointwhenhitandimmediatelycontinues
execution
AnyothercombinationSetsINT3breakpointofspecifiedtype
Setmembreakpoint
Modifiesorremovesmemorybreakpoint.OllyDbgsupportsonlyonememorybreakpointatatime.Returns0onsuccessand-1onerror.CallSetmembreakpoint(0,0,0)todisablememorybreakpoint.
intSetmembreakpoint(inttype,ulongaddr,ulongsize);
Parameters:
type-typeofmemorybreakpoint.UseeitherMEMBP_READorMEMBP_READ|MEMBP_WRITE;
addr-startofmemorybreakpointintheaddressspaceofdebuggedapplication;
size-sizeofmemorybreakpoint,bytes.
Sethardwarebreakpoint
Setshardwarebreakpointandactivatesit.80x86compatibleprocessorssupport4hardwarebreakpoints.Ifallavailableslotsareinuse,functionasksusertodeleteoneofactivebreakpoints.Returns0onsuccessand-1onerrororifusercancelledaction.ItisallowedtocallSethardwarebreakpoint"onthefly",i.e.whendebuggedapplicationisrunning.
NotethathardwarebreakpointsarenotsupportedbyWindows95andWindows98.Toassurethatyoucanusethisfunction,callPlugingetvalue(VAL_HARDBP).
intSethardwarebreakpoint(ulongaddr,intsize,inttype);
Parameters:
addr-addressofbreakpoint;
size-sizeofmemorycoveredbyhardwarebreakpoint(1,2or4bytes).addrmustbealignedonthecorrespondingboundary.Thisparametermustbe1incaseofbreakpointonexecution;
type-typeofhardwarebreakpoint:
HB_CODE ActiveoncommandexecutionHB_ACCESS Activeonread/writeaccessHB_WRITE Activeonwriteaccess
Seealso:Hardbreakpoints,Deletehardwarebreakpoint,Deletehardwarebreakbyaddr
Hardbreakpoints
Createsdialogenablingusertoview,followanddeleteexistinghardwarebreakpoints.Ifcloseondeleteis1,dialogclosesaftersomebreakpointisdeleted.Returns-1onerrororifusercancelledactionand0otherwise.
NotethathardwarebreakpointsarenotsupportedbyWindows95andWindows98.Toassurethatyoucanusethisfunction,callPlugingetvalue(VAL_HARDBP).
intHardbreakpoints(intcloseondelete);
Parameters:
closeondelete-if1,asksusertodeletesomeexistingbreakpointandclosesdialogwindowaftersomehardwarebreakpointisdeleted.
Seealso:Sethardwarebreakpoint,Deletehardwarebreakpoint,Deletehardwarebreakbyaddr
Deletehardwarebreakpoint
80x86processorssupportupto4hardwarebreakpoints.ThisfunctionremoveshardwarebreakpointwithspecifiedindexpreviouslysetbyOllyDbg.Returns0onsuccessand-1onerror.OllyDbgmayusehardwarebreakpointstobypassactualcommand,sousethisfunctionwithcare!FunctionDeletehardwarebreakbyaddriseasiertouse.
NotethathardwarebreakpointsarenotsupportedbyWindows95andWindows98.Toassurethatyoucanusethisfunction,callPlugingetvalue(VAL_HARDBP).
intDeletehardwarebreakpoint(intindex);
Parameters:
index-indexofhardwarebreakpointtodelete(0..3).
Seealso:Sethardwarebreakpoint,Hardbreakpoints,Deletehardwarebreakbyaddr
Deletehardwarebreakbyaddr
Deleteshardwarebreakpointbyaddress.Ifthereareseveralbreakpointsembracingsameaddres,deletesallsuchbreakpoints.Returnsnumberofdeletedbreakpointsor0onerror.
NotethathardwarebreakpointsarenotsupportedbyWindows95andWindows98.Toassurethatyoucanusethisfunction,callPlugingetvalue(VAL_HARDBP).
intDeletehardwarebreakbyaddr(ulongaddr);
Parameters:
addr-addressofhardwarebreakpoint.Everyhardwarebreakpointthatcoversthisaddresswillberemoved.Forexample,ifhardwarebreakpointhasaddress0x00123450andsize4,itcoversaddressrangefrom0x00123450to0x00123453inclusive.
Seealso:Sethardwarebreakpoint,Hardbreakpoints,Deletehardwarebreakpoint
Executionandsteppingfunctions
Executionandsteppingfunctionslistedinthissectioncheckforrougherrorsbut,whenimproperlyused,maybringOllyDbginunstablestate.Pleaseusethemwithcare!Forsimpletasks,consideruseofSendshortcut.
intOpenEXEfile(char*path,intdropped);
intAttachtoactiveprocess(intprocessid);
intGo(ulongthreadid,ulongtilladdr,intstepmode,intgivechance,intbackupregs);
voidAnimate(intanimation);
intSuspendprocess(intprocessevents);
ulongRunsinglethread(ulongthreadid);
voidRestoreallthreads(void);
Go
Continuesexecutionofthedebuggedprogram.Returns-1ifcontinuationisimpossibleand0onsuccess.ImproperuseofthisfunctionmaybringOllyDbginunstableorundefinedstate.Forsimpletasks,consideruseofSendshortcut.
intGo(ulongthreadid,ulongtilladdr,intstepmode,intgivechance,intbackupregs);
Parameters:
threadid-threadIDtocontinue.Ifthreadidis0,functionassumesthreadwherelastdebuggingeventoccured;
tilladdr-ifstepmodeisSTEP_SKIP,functionrequestsskippingofallcommandsuptotilladdratonce.Callingroutinemustguaranteethattilladdristhefirstbyteofsomecommandandthatsequenceinbetweenhasnojumps/returnstooutside.Otherwise,setstemporarybreakpointontilladdrsothatprogramwillpauseatthispoint(like"Runtolselection"inDisassembler).
stepmode-steppingmode,oneofthefollowing:
STEP_SAME SameactionasonpreviouscalltoGoSTEP_RUN RunprogramSTEP_OVER Stepover(executecallsatonce)STEP_IN Stepin(entersubroutines)STEP_SKIP Skipsequencetillspecifiedaddress
givechance-ifdebuggedapplicationwaspausedonexceptionandthisparameterisnot0,passesexceptiontoexceptionhandlerinstalledbyapplication;
backupregs-ifnot0,updatesoldthreadregisters(elementoldregofstructuret_thread).Disassemblerusesbackuptohighlightmodifiedregisters.
Seealso:OpenEXEfile,Animate,Suspendprocess,Runsinglethread,Restoreallthreads
Animate
Setsanimationmodeand,ifrequestedindebugoptions,setshigherprioritytodebuggedprocess.Noticethatthisfunctiondoesn'tstartsteppingoranimation,youmustexplicitelycallGoafterwards.ImproperuseofAnimatemaybringOllyDbginunstablestate.Forsimpletasks,consideruseofSendshortcut.
voidAnimate(intanimation);
Parameters:
animation-animationmode:
ANIMATE_OFF NoanimationANIMATE_IN AnimateintoANIMATE_OVER AnimateoverANIMATE_RET ExecutetillRET
ANIMATE_SKPRET ExecutetillRET,thenskipRETinstruction
ANIMATE_USER ExecutetillusercodeANIMATE_TRIN RuntraceinANIMATE_TROVER RuntraceoverANIMATE_STOP Gracefullystopanimation
Seealso:OpenEXEfile,Go,Suspendprocess,Runsinglethread,Restoreallthreads
Suspendprocess
Suspendsallthreadsoftheprocessbeingdebugged.Itmayhappen(especiallywhenloggingbreakpointsaresetorhittraceisactive)thatthreadswillbesuspendedaftersomebreakpointisexecutedbutcorrespondingdebugeventisnotprocessed.IfyouwantOllyDbgtoprocesseventsbeforereturningfromSuspendprocess,callitwithprocessevents=1.Returns0onsuccessand-1incaseofanyerror.Toresumeexecution,callGo.ThisfunctionisslowonWin95-basessystems.
intSuspendprocess(intprocessevents);
Parameters:
processevents-processpendingdebuggingeventsbeforereturn.
Seealso:OpenEXEfile,Go,Animate,Runsinglethread,Restoreallthreads
Runsinglethread
Suspendsallthreadsexceptforspecified,andresumesspecifiedthreadevenifitwassuspended.Ifthreadidis0orinvalid,suspendsallthreads.ReturnsthreadIDofthethreadthatwastheonlyonerunning,threadIDofthemainthreadiftherewerenone/morethan1activethreads,and0onerror.Toreverseeffectofthisfunction,callRestoreallthreads.ImproperuseofthisfunctionmaybringOllyDbginunstableorundefinedstate.
ulongRunsinglethread(ulongthreadid);
Parameters:
threadid-identifier(nothandle!)ofthreadtorun,or0tosuspendallthreads.
Seealso:OpenEXEfile,Go,Animate,Suspendprocess,Restoreallthreads
OpenEXEfile
Closesactuallprocessandstartsnewexecutableorlinkspecifiedinpath.Returns0ifexecutablefileissuccessfullystarted.Displayserrormessageandreturns-1iffileisnota32-bitPortableExecutableorOllyDbgwasunabletocreatenewprocess.
intOpenEXEfile(char*path,intdropped);
Parameters:
path-pointertoASCIIstringwithnameofexecutablefile(.exe)orExplorerlinkfile(.lnk);
dropped-setto1ifexecutablefilewasdrag-and-droppedtoOllyDbgorplugin,otherwisesetitto0.Currently,theonlyactionofthisflagistoclearcommandline.
Seealso:Go,Animate,Suspendprocess,Runsinglethread,Restoreallthreads
Restoreallthreads
Restoresoriginalthreadstates(asbeforethesequenceofcallstoRunsinglethread).Warnsifallthreadsaresuspended.
voidRestoreallthreads(void);
Seealso:OpenEXEfile,Go,Animate,Suspendprocess,Runsinglethread
Traceandprofilingfunctions
char*Findhittrace(ulongaddr,char**ptracecopy,ulong*psize);
intModifyhittrace(ulongaddr0,ulongaddr1,intmode);
intRuntracesize(void);
intFindprevruntraceip(ulongip,intstartback);
intFindnextruntraceip(ulongip,intstartback);
intStartruntrace(t_reg*preg);
voidDeleteruntrace(void);
voidSettracecondition(char*cond,intonsuspicious,ulongin0,ulongin1,ulongout0,ulongout1);
voidSettracecount(ulongcount);
intGetruntraceregisters(intnback,t_reg*preg,t_reg*pold,char*cmd,char*comment);
intGetruntraceprofile(ulongaddr,ulongsize,ulong*profile);
HWNDCreatertracewindow(void);
voidScrollruntracewindow(intback);
HWNDCreateprofilewindow(ulongbase,ulongsize);
Settracecount
Setsnumberofcommandstotrace.Afterspecifiednumberofcommandsisloggedtotracebuffer,tracepauses.UsuallyyoumaycallthisfunctionafterSettracecondition.
voidSettracecount(ulongcount);
Parameters:
count-numberofcommandstoexecutebeforeruntracepauses.
Seealso:Settracecondition
Findhittrace
Lookswhetherhittraceinformationisavailablestartingfromspecifiedaddress.Returnspointertohittraceinformationcorrespondingtogivenaddressandoptionallysets*ptracecopytocopyoforiginalcodeand*psizetosizeofremainingdata.ReturnsNULLandsets*psizeto0ifthereisnodecodinginformation.HittraceinformationisanarrayofbytesthatarethecombinationofbitsTR_xxx.
char*Findhittrace(ulongaddr,char**ptracecopy,ulong*psize);
Parameters:
addr-addressoffirstbyteofthecodeintheaddressspaceofdebuggedapplication;
ptracecopy-pointertovariablethatreceivespointertostaticalcopyoforiginalcode,maybeNULL;
psize-pointertovariablethatreceivessizeofhittraceandcopydata,maybeNULL.
Seealso:Modifyhittrace,Runtracesize
Modifyhittrace
Functionadds,resets,removesorrestoresspecifiedrangeinthecombinedhit/runtracedatabuffer.Thisbuffercontainsflagsspecifyingwhichactionsshouldbeundertakenwhencorrespondingcommandisreached,don'tmixitwiththeruntracelogbufferthatcontainsresultsofruntrace.Ifnecessary,bufferiscreated.Returns0onsuccess(evenpartial)and-1onerror.
Warning:Settinghittraceorforcedruntraceondatamayhavedisastrouseffectsonyourprogram!
intModifyhittrace(ulongaddr0,ulongaddr1,intmode);
Parameters:
addr0-addressofthefirstbyteofthecoderangeintheaddressspaceofdebuggedapplication;
addr1-addressofthelastbyteofthecoderangeintheaddressspaceofdebuggedapplication(notincluded);
mode-actiontoperform,oneofthefollowing:
ATR_ADD Hittracespecifiedrange
ATR_ADDPROC Hittraceonlyrecognizedproceduresintherange
ATR_RESET MarkrangeasnottracedATR_REMOVE RemoverangeandbreakpointsATR_REMOVEALLDestroyrangeandbreakpointsATR_RESTORE RestorebreakpointsinmemoryATR_RTRADD HittracerangeandforceruntraceATR_RTRJUMPS HittraceandruntracejumpsonlyATR_RTRENTRY HittraceandruntraceentriesonlyATR_RTREMOVE RemovetracefromrangeATR_RTSKIP Skiprangefromruntrace
Seealso:Findhittrace,Runtracesize
Runtracesize
Returnsnumberofrecordsinruntracedata,includingrecordaddedduringinitialization,or0ifruntracedataisabsent.Thisfunctionisveryfast.
intRuntracesize(void);
Findprevruntraceip
Searchesfortheprevious(older)appearanceofcommandwithspecifiedEIPintheruntracebuffer,startingfromthespecifiedbackwardstep(notincludedinsearch).Returnsbackwardstepor-1ifcommandisnotintraceorifruntraceisinactive.
intFindprevruntraceip(ulongip,intstartback);
Parameters:
ip-addressofthecommandtosearch;
startback-backwardstepwherethesearchstarts.Thisstepisnotincludedinsearch.Usestartback=0tosearchfortheyoungestappearance.
Seealso:Findhittrace,Runtracesize,Findnextruntraceip,Getruntraceregisters
Findnextruntraceip
Searchesforthenext(younger)appearanceofcommandwithspecifiedEIPintheruntracebuffer,startingfromthespecifiedbackwardstep(notincludedinsearch).Returnsbackwardstepor-1ifcommandisnotintraceorifruntraceisinactive.
intFindnextruntraceip(ulongip,intstartback);
ip-addressofthecommandtosearch;
startback-backwardstepwherethesearchstarts.Thisstepisnotincludedinsearch.
Seealso:Findhittrace,Runtracesize,Findprevruntraceip,Getruntraceregisters
Getruntraceregisters
Extractsregistersthatarenbackstepsbackintheruntracedata(nback=0meansactualregisters)andoptionallyregistersonthepreviousstep(soonecancheckformodifications).Optionallyextractsoriginalcommandandcomment.Returns-1oferror,lengthofcommandifcmd!=NULLandoriginalcommandisavailableand0iforiginalcommandisabsent.Ifrecordcontainsskippedsequence,returns0andsetscmd[0]to0x01.
intGetruntraceregisters(intnback,t_reg*preg,t_reg*pold,char*cmd,char*comment);
Parameters:
nback-backwardstepinruntracebuffer,0meansactualstep;
preg-pointertot_regstructurethatreceivesregistersrestoredtothestateafterthiscommandwasexecuted;
pold-pointertot_regstructurethatreceivesregistersrestoredtothestatebeforethiscommandwasexecuted,canbeNULL;
cmd-bufferatleastMAXCMDSIZEbyteslongthatreceivesoriginalcommand,orNULL.IfrecordcontainsskippedsequenceandcmdisnotNULL,functionsetscmd[0]to0x01andreturns0;
comment-bufferatleastTEXTLENbyteslongthatreceivescommentfromtheruntracebuffer,canbeNULL.
Seealso:Runtracesize,Findprevruntraceip,Findnextruntraceip
Getruntraceprofile
Calculatesnumberoftimesthateachaddressinrangefromaddrtoaddr+size(notincluded)appearsintheruntracedata.Parameterprofilepointstoarrayofsizeelementsthatreceivesprofiledata.Returns0onsuccessorwhenruntracedataisunavailable,and-1onerror.Functioncanberatherslowifruntracedataislong.
intGetruntraceprofile(ulongaddr,ulongsize,ulong*profile);
Parameters:
addr-baseaddressoftheprofiledcode;
size-sizeoftheprofiledcode;
profile-pointertoarrayofsizedoublewordsthatreceivesprofiledata.
Seealso:Findhittrace,Runtracesize,Findprevruntraceip,Findnextruntraceip,Getruntraceregisters
Scrollruntracewindow
Selectsspecifiedlineandscrollsruntracewindowsothatselectionisvisible.Ifoption"SynchronizeCPUandRuntrace"isactive,Disassembleralsoscrollstothiscommand.
voidScrollruntracewindow(intback);
Parameters:
back-backwardstepinruntracebuffer,0meansactualstep.
Seealso:Runtracesize,Findprevruntraceip,Findnextruntraceip,Getruntraceregisters
Startruntrace
Reinitializestracedataandreallocatestracebuffer.Previoustraceisdeleted.Returns0onsuccessand-1onerror.
intStartruntrace(t_reg*preg);
Parameters:
preg-pointertoactualregistersthatwillbeusedastheoldestrecordintheruntracebuffer.FunctionfailsifpregisNULL.
Seealso:Runtracesize,Findprevruntraceip,Findnextruntraceip,Getruntraceregisters,Settracecondition
Deleteruntrace
Closesruntraceanddestroystracedata.
voidDeleteruntrace(void);
Seealso:Startruntrace,Runtracesize,Findprevruntraceip,Findnextruntraceip,Getruntraceregisters
Settracecondition
OllyDbgcanpauseruntraceonasetofconditions.Thisfunctionquicklysetspauseonexpression,onsuspiciouscommandand/oronEIPrangeanddeactivatespauseoncommand.
voidSettracecondition(char*cond,intonsuspicious,ulongin0,ulongin1,ulongout0,ulongout1);
Parameters:
cond-pointertocharacterstringcontainingexpression.Runtracewillpauseifexpressionisinvalidorestimatestonon-zerovalue;
onsuspicious-activates(1)ordeactivates(0)pauseonsuspiciouscommand;
in0,in1-'inrange'request.RuntracewillpauseifEIPisinthisrange(in1notincluded).Todisablepauseon'inrange',setbothin0andin1to0;
out0,out1-'outofrange'request.RuntracewillpauseifEIPisoutsidethisrangeorequalstoout1.Todisablepauseon'outofrange',setbothout0andout1to0.
Seealso:Startruntrace,Issuspicious
Createprofilewindow
Createsneworbringstotopexistingprofilewindowanddisplaysactualprofileforthespecifiedpieceofcode.Onlyoneprofilewindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.Notethatinordertoactualizeprofile,thisfunctionattemptstoallocatetemporarybufferofsize4*sizebytes,andwillfailifyouspecifytoolargeornon-contiguouscodeblock.
HWNDCreateprofilewindow(ulongbase,ulongsize);
base-baseaddressoftheprofiledcode;
size-sizeoftheprofiledcode.
Seealso:Startruntrace,Getruntraceprofile
t_reg
Structurethatkeepsthevaluesofallrelevant80x86registers.Notethatlengthofthisstructureinversion1.10isincreasedby4bytes.Thismayleadtoincompatibilitieswithpreviousversions.
typedefstructt_reg{//Excerptfromcontext
intmodified;//Someregsmodified,updatecontext
intmodifiedbyuser;//Amongmodified,somemodifiedbyuser
intsinglestep;//Typeofsinglestep,SS_xxx
ulongr[8];//EAX,ECX,EDX,EBX,ESP,EBP,ESI,EDI
ulongip;//Instructionpointer(EIP)
ulongflags;//Flags
inttop;//Indexoftop-of-stack
longdoublef[8];//Floatregisters,f[top]-topofstack
uchartag[8];//Floattags(0x3-emptyregister)
ulongfst;//FPUstatusword
ulongfcw;//FPUcontrolword
ulongs[6];//SegmentregistersES,CS,SS,DS,FS,GS
ulongbase[6];//Segmentbases
ulonglimit[6];//Segmentlimits
ucharbig[6];//Defaultsize(0-16,1-32bit)
ulongdr6;//DebugregisterDR6
ulongthreadid;//IDofthreadthatownsregisters
ulonglasterror;//Lastthreaderroror0xFFFFFFFF
intssevalid;//WhetherSSEregistersvalid
intssemodified;//WhetherSSEregistersmodified
charssereg[8][16];//SSEregisters
ulongmxcsr;//SSEcontrolandstatusregister
intselected;//Reportsselectedregistertoplugin
ulongdrlin[4];//DebugregistersDR0..DR3
ulongdr7;//DebugregisterDR7
}t_reg;
Members:
modified-non-zerovalueindicatesthatsomeregistersweremodifiedandOllyDbgshouldupdateCONTEXTstructureofthecorrespondingthreadbeforecontinuingexecution;
modifiedbyuser-amongmodifiedregisters,someregistersweremodifiedbyuser;
singlestep-usedinternallybyOllyDbg,donotmodifydirectly!
r-32-bitgeneral-purposeregistersEAX,ECX,EDX,EBX,ESP,EBP,ESI,EDI(inthelistedorder,useconstantsREG_xxxtoaccess);
ip-32-bitInstructionPointer(EIPregister);
flags-32-bitEFLAGSregister,donotmodifysingle-steptrapbit!
top-indexoftheregisterthatisthetopoftheFPUstack;
f-80-bitfloating-point/MMX/3DNow!registers;
tag-two-bittagsassociatedwithfloatingpointregisters;
fst-16-bitFPUstatusword;
fcw-16-bitFPUcontrolword;
s-segmentregistersES,CS,SS,DS,FS,GS(inthelistedorder,useconstantsSEG_xxxtoaccess);
base-baseaddressesofsegmentdescroptors;
limit-limitsofsegmentdescriptors;
big-defaultsegmentsize(0-16-bitsegment,seldominflatmode;1-32-bitsegment);
dr6-debugregisterdr6,pleasedonotmodify!
threadid-identifierofthethreadthatownsregisters;
lasterror-lasterrorinthethreadasreturnedbycalltoGetlastError,or-1(0xFFFFFFFF)ifexactvalueoftheerrorisunknown;
ssevalid-non-zeroifsseregcontainvaliddata;
ssereg-16-byteSSEregisters;
mxcsr-SSEcontrolandstatusregister;
selected-currentlyselectedregister,definedonlyift_regispassedtooneofODBG_Plugin...callbackfunctions,otherwiseundefined.ANDthisvaluewithRS_GROUPtoobtainthegroupofregistersRS_xxx;togetindexofregisterwithinthegroup,ANDitwithRS_INDEX.Forexample,code0013isageneral-purposeregisterEBX(0013&RS_GROUP=RS_INT,0013&RS_INDEX=REG_EBX);
drlin-debugregistersdr0..dr3,pleasedonotmodify!
dr7-debugregisterdr7,pleasedonotmodify!
Procedurefunctions
GroupoffunctionsthatfacilitatehandlingofproceduresrecognizedbyAnalyzer.
ulongFindprocbegin(ulongaddr);
ulongFindprocend(ulongaddr);
ulongFindprevproc(ulongaddr);
ulongFindnextproc(ulongaddr);
intGetproclimits(ulongaddr,ulong*start,ulong*end);
Findprocbegin
Returnsstartaddressoftheprocedurethatenclosesaddr,or0onerror,forexample,whenmoduleisnotanalyzedoraddresspointstonoprocedure.
ulongFindprocbegin(ulongaddr);
Parameters:
addr-addressofanycommandwithintheprocedure.
Seealso:Findprocend,Findprevproc,Findnextproc,Getproclimits
Findprocend
Returnsaddressofthelastcommandoftheprocedurethatenclosesaddr,or0onerror,forexample,whenmoduleisnotanalyzedoraddresspointstonoprocedure.
ulongFindprocend(ulongaddr);
Parameters:
addr-addressofanycommandwithintheprocedure.
Seealso:Findprocbegin,Findprevproc,Findnextproc,Getproclimits
Findprevproc
Returnsstartaddressoftheprocedurethatprecedesorenclosesaddr,or0onerror,forexample,whenmoduleisnotanalyzedoraddressdoesn'tpointtoexecutablecode.
ulongFindprevproc(ulongaddr);
Parameters:
addr-addressofreferencecommand.
Seealso:Findprocbegin,Findprocend,Findnextproc,Getproclimits
Findnextproc
Returnsstartaddressoftheprocedurethatisnexttoaddr,or0onerror,forexample,whenmoduleisnotanalyzedoraddressdoesn'tpointtoexecutablecode.
ulongFindnextproc(ulongaddr);
Parameters:
addr-addressofreferencecommand.
Seealso:Findprocbegin,Findprocend,Findprevproc,Getproclimits
Getproclimits
Calculateslimitsoftheprocedurethatincludesspecifiedaddress.Returns0onsuccessand-1onerror,forexample,whenmoduleisnotanalyzedoraddresspointstonoprocedure.
intGetproclimits(ulongaddr,ulong*start,ulong*end);
Parameters:
addr-addressofanycommandwithintheprocedure;
start-pointertovariablethatreceivesstartaddressoftheprocedure;
end-pointertovariablethatreceivesaddressofthelastcommandintheprocedure.
Seealso:Findprocbegin,Findprocend,Findprevproc,Findnextproc
Searchfunctions
Thefunctionsdescribedinthissectionhavelittlevalueforplugindeveloperandexportedmainlyforuseincommandlineplugin.Theysearchforspecifiedsortofdataanddisplayresultsinthereferencewindow.
intFindallcommands(t_dump*pd,t_asmmodel*model,ulongorigin,char*title);
intFindalldllcalls(t_dump*pd,ulongorigin,char*title);
intFindallsequences(t_dump*pd,t_extmodelmodel[NSEQ][NMODELS],ulongorigin,char*title);
intFindreferences(ulongbase,ulongsize,ulongaddr0,ulongaddr1,ulongorigin,intrecurseonjump,char*title);
intFindstrings(ulongbase,ulongsize,ulongorigin,char*title);
Findalldllcalls
Searchesforallcalls(includingindirect)todifferentmodulesfromthecodesectiondescribedbydumpstructure,placesthemintothereferencetableasasetoft_refrecordsanddisplaysinreferencewindow.Addressoforigin,ifnot0,isalsoincludedintothetable(markedasTY_ORIGIN).Returnsnumberoffoundreferencesor-1onerror.Noticethatthisfunctiondoesn'tworkonfiledump.
intFindalldllcalls(t_dump*pd,ulongorigin,char*title);
Parameters:
pd-pointertodumpdescriptorofcodesection;
origin-addressofsearchoriginor0ifnone.Searchorigingiveseasywaytoreturntoinitialpointafterbrowsingthroughthefounditems;
title-titleofreferencewindow.
Noteconcerningfunctionsthataccess.inifile
Ihateregistry!ManytimesIwasforcedtoreinstallsoftwarethatwasstillonmyharddiskonlybecauseregistrycrashedaftersomehazardousexperimentswithhardware,orbecauseIreinstalledWindowstogetridoftrashfromremovedinstallations.DoYOUknowwhichofyourpersonaldataresidesinregistry?Canyoucheckit?Canyoueasilybackupsettingsofsomeprogramandeasilyrestorethem?Oredit?Inmyopinion,theovercomplicationofthesoftwareinthelasttimeeithercomesfromthefactthatprogrammersfirstwriteandthenthink,orisa(rathersuccessfull)waytomakeproductinaccessibleforaconcurrent.Dixi.
Sampleprogram
Thisistheannotatedcodeofsamplebookmarkplugin.Iplaceitheresothatyoucangetquickhelponallreferencedfunctions.
////////////////////////////////////////////////////////////////////////////////
////
//SAMPLEPLUGINFOROLLYDBG//
////
//Thispluginallowstosetupto10codebookmarksusingkeyboardshortcuts//
//orpopupmenusinDisassemblerandthenquicklyreturntooneofthe//
//bookmarksusingshortcuts,popupmenuorBookmarkwindow.Bookmarks//
//arekeptbetweensessionsin.uddfile.//
////
////////////////////////////////////////////////////////////////////////////////
//VERYIMPORTANTNOTICE:COMPILETHISDLLWITHBYTEALIGNMENTOFSTRUCTURES
//ANDUNSIGNEDCHAR!
#include<windows.h>
#include<stdio.h>
#include<string.h>
#include<dir.h>
#include"plugin.h"
HINSTANCEhinst;//DLLinstance
HWNDhwmain;//HandleofmainOllyDbgwindow
charbookmarkwinclass[32];//Nameofbookmarkwindowclass
//OllyDbgsupportsandmakesextensiveuseofspecialkindofdatacollections
//calledsortedtables.Atableconsistsofdescriptor(t_table)anddata.All
//dataelementshassamesizeandbeginwitha3-dwordheader:address,size
//andtype.Tableautomaticallysortsitemsbyaddress,overlappingisnot
//allowed.Ourbookmarktableconsistsofelementsoftypet_bookmark.
typedefstructt_bookmark{
ulongindex;//Bookmarkindex(0..9)
ulongsize;//Sizeofindex,always1inourcase
ulongtype;//Typeofentry,always0
ulongaddr;//Addressofbookmark
}t_bookmark;
t_tablebookmark;//Bookmarktable
//Functionsinthisfileareplacedinmoreorless"chronological"order,
//i.e.orderinwhichtheywillbecalledbyOllyDbg.Thisrequiresforward
//referencing.
intBookmarksortfunc(t_bookmark*b1,t_bookmark*b2,intsort);
LRESULTCALLBACKBookmarkwinproc(HWNDhw,UINTmsg,WPARAMwp,LPARAMlp);
intBookmarkgettext(char*s,char*mask,int*select,t_sortheader*ph,intcolumn);
voidCreatebookmarkwindow(void);
//EntrypointintoapluginDLL.ManysystemcallsrequireDLLinstance
//whichispassedtoDllEntryPoint()asoneofparameters.Rememberit.
//PreferrablewayistoplaceinitializationsintoODBG_Plugininit()and
//cleanupinODBG_Plugindestroy().
BOOLWINAPIDllEntryPoint(HINSTANCEhi,DWORDreason,LPVOIDreserved){
if(reason==DLL_PROCESS_ATTACH)
hinst=hi;//Markplugininstance
return1;//Reportsuccess
};
//ODBG_Plugindata()isa"must"forvalidOllyDbgplugin.Itmustfillin
//pluginnameandreturnversionofplugininterface.Iffunctionisabsent,
//orversionisnotcompatible,pluginwillbenotinstalled.Shortname
//identifiesitinthePluginsmenu.Thisnameismax.31alphanumerical
//charactersorspaces+terminating'\0'long.Tokeeplifeeasyforusers,
//thisnameshouldbedescriptiveandcorrelatewiththenameofDLL.
extcint_exportcdeclODBG_Plugindata(charshortname[32]){
strcpy(shortname,"Bookmarks");//Nameofplugin
returnPLUGIN_VERSION;
};
//OllyDbgcallsthisobligatoryfunctiononceduringstartup.Placeall
//one-timeinitializationshere.Ifallresourcesaresuccessfullyallocated,
//functionmustreturn0.Onerror,itmustfreepartiallyallocatedresources
//andreturn-1,inthiscasepluginwillberemoved.Parameterollydbgversion
//istheversionofOllyDbg,useittoassurethatitiscompatiblewithyour
//plugin;hwisthehandleofmainOllyDbgwindow,keepitifnecessary.
//Parameterfeaturesisreservedforfutureextentions,donotuseit.
extcint_exportcdeclODBG_Plugininit(
intollydbgversion,HWNDhw,ulong*features){
//CheckthatversionofOllyDbgiscorrect.
if(ollydbgversion<PLUGIN_VERSION)
return-1;
//KeephandleofmainOllyDbgwindow.Thishandleisnecessary,forexample,
//todisplaymessagebox.
hwmain=hw;
//Initializebookmarkdata.Dataconsistsofelementsoftypet_bookmark,
//wereservespacefor10elements.Ifnecessary,tablewillallocatemore
//space,butinourcasemaximalnumberofbookmarksis10.Elementsdonot
//allocatememoryorotherresources,sodestructorisnotnecessary.
if(Createsorteddata(&(bookmark.data),"Bookmarks",
sizeof(t_bookmark),10,(SORTFUNC*)Bookmarksortfunc,NULL)!=0)
return-1;//Unabletoallocatebookmarkdata
//RegisterwindowclassforMDIwindowthatwilldisplayplugins.Please
//notethatformallythisclassbelongstoinstanceofmainOllyDbgprogram,
//notapluginDLL.Stringbookmarkwinclassgetsuniquenameofnewclass.
//Keepittocreatewindowandunregisteronshutdown.
if(Registerpluginclass(bookmarkwinclass,NULL,hinst,Bookmarkwinproc)<0){
//Failure!Destroysorteddataandexit.
Destroysorteddata(&(bookmark.data));
return-1;};
//Pluginsuccessfullyinitialized.Nowisthebesttimetoreportthisfact
//tothelogwindow.ToconformOllyDbglookandfeel,pleaseusetwolines.
//Thefirst,inblack,shoulddescribeplugin,thesecond,grayandindented
//bytwocharacters,bearscopyrightnotice.
Addtolist(0,0,"Bookmarkssamplepluginv1.10(plugindemo)");
Addtolist(0,-1,"Copyright(C)2001-2004OlehYuschuk");
//OllyDbgsavespositionsofpluginwindowswithattributeTABLE_SAVEPOSto
//the.inifilebutdoesnotautomaticallyrestorethem.Letusaddthis
//functionalityhere.Ikeepinformationwhetherwindowwasopenwhen
//OllyDbgterminatedalsoinollydbg.ini.Thisinformationissavedin
//ODBG_Pluginclose.ToconformtoOllyDbgnorms,windowisrestoredonly
//ifcorrespondingoptionisenabled.
if(Plugingetvalue(VAL_RESTOREWINDOWPOS)!=0&&
Pluginreadintfromini(hinst,"Restorebookmarkswindow",0)!=0)
Createbookmarkwindow();
return0;
};
//Tosortsorteddatabysomecriterium,onemustsupplysortfunctionthat
//returns-1iffirstelementislessthansecond,1iffirstelementis
//greaterand0ifelementsareequalaccordingtocriteriumsort.Usually
//thiscriteriumisthezero-basedindexofthecolumninwindow.
intBookmarksortfunc(t_bookmark*b1,t_bookmark*b2,intsort){
inti=0;
if(sort==1){//Sortbyaddressofbookmark
if(b1->addr<b2->addr)i=-1;
elseif(b1->addr>b2->addr)i=1;};
//Ifelementsareequalorsortingisbythefirstcolumn,sortbyindex.
if(i==0){
if(b1->index<b2->index)i=-1;
elseif(b1->index>b2->index)i=1;};
returni;
};
//Eachwindowclassneedsitsownwindowprocedure.Bothstandardandcustom
//OllyDbgwindowsmustpasssomesystemandOllyDbg-definedmessagesto
//Tablefunction().SeedescriptionofTablefunction()formoredetails.
LRESULTCALLBACKBookmarkwinproc(HWNDhw,UINTmsg,WPARAMwp,LPARAMlp){
inti,shiftkey,controlkey;
HMENUmenu;
t_bookmark*pb;
switch(msg){
//Standardmessages.Youcanprocessthem,but-unlessabsolutelysure-
//alwayspassthemtoTablefunction().
caseWM_DESTROY:
caseWM_MOUSEMOVE:
caseWM_LBUTTONDOWN:
caseWM_LBUTTONDBLCLK:
caseWM_LBUTTONUP:
caseWM_RBUTTONDOWN:
caseWM_RBUTTONDBLCLK:
caseWM_HSCROLL:
caseWM_VSCROLL:
caseWM_TIMER:
caseWM_SYSKEYDOWN:
Tablefunction(&bookmark,hw,msg,wp,lp);
break;//PassmessagetoDefMDIChildProc()
//Custommessagesresponsibleforscrollingandselection.User-drawn
//windowsmustprocessthem,standardOllyDbgwindowswithoutextra
//functionalitypassthemtoTablefunction().
caseWM_USER_SCR:
caseWM_USER_VABS:
caseWM_USER_VREL:
caseWM_USER_VBYTE:
caseWM_USER_STS:
caseWM_USER_CNTS:
caseWM_USER_CHGS:
returnTablefunction(&bookmark,hw,msg,wp,lp);
//IfwindowshouldsupportTABLE_ONTOP("Alwaysontop"mode),itmustpass
//WM_WINDOWPOSCHANGEDtoTablefunction().
caseWM_WINDOWPOSCHANGED:
returnTablefunction(&bookmark,hw,msg,wp,lp);
caseWM_USER_MENU:
menu=CreatePopupMenu();
//Findselectedbookmark.Anyoperationswithbookmarksmakesenseonly
//ifatleastonebookmarkexistsandisselected.Notethatsorteddata
//hasspecialsortindextablewhichisupdatedonlywhennecessary.
//Getsortedbyselection()doesthis;someothersorteddatafunctions
//don'tandyoumustcallSortsorteddata().Readdocumentation!
pb=(t_bookmark*)Getsortedbyselection(
&(bookmark.data),bookmark.data.selected);
if(menu!=NULL&&pb!=NULL){
AppendMenu(menu,MF_STRING,1,"&Follow\tEnter");
AppendMenu(menu,MF_STRING,2,"&Delete\tDel");};
//EvenwhenmenuisNULL,calltoTablefunctionisstillmeaningful.
i=Tablefunction(&bookmark,hw,WM_USER_MENU,0,(LPARAM)menu);
if(menu!=NULL)DestroyMenu(menu);
if(i==1)//FollowbookmarkinDisassembler
Setcpu(0,pb->addr,0,0,CPU_ASMHIST|CPU_ASMCENTER|CPU_ASMFOCUS);
elseif(i==2){//Deletebookmark
Deletesorteddata(&(bookmark.data),pb->index);
//Thereisnoautomaticalwindowupdate,doityourself.
InvalidateRect(hw,NULL,FALSE);};
return0;
caseWM_KEYDOWN:
//ProcessingofWM_KEYDOWNmessagesis-surprise,surprise-very
//similartothatofcorrespondingmenuentries.
shiftkey=GetKeyState(VK_SHIFT)&0x8000;
controlkey=GetKeyState(VK_CONTROL)&0x8000;
if(wp==VK_RETURN&&shiftkey==0&&controlkey==0){
//ReturnkeyfollowsbookmarkinDisassembler.
pb=(t_bookmark*)Getsortedbyselection(
&(bookmark.data),bookmark.data.selected);
if(pb!=NULL)
Setcpu(0,pb->addr,0,0,CPU_ASMHIST|CPU_ASMCENTER|CPU_ASMFOCUS);
;}
elseif(wp==VK_DELETE&&shiftkey==0&&controlkey==0){
//DELkeydeletesbookmark.
pb=(t_bookmark*)Getsortedbyselection(
&(bookmark.data),bookmark.data.selected);
if(pb!=NULL){
Deletesorteddata(&(bookmark.data),pb->index);
InvalidateRect(hw,NULL,FALSE);
};}
else
//Addallthisarrow,homeandpageupfunctionality.
Tablefunction(&bookmark,hw,msg,wp,lp);
break;
caseWM_USER_DBLCLK:
//DoubleclickingrowfollowsbookmarkinDisassembler.
pb=(t_bookmark*)Getsortedbyselection(
&(bookmark.data),bookmark.data.selected);
if(pb!=NULL)
Setcpu(0,pb->addr,0,0,CPU_ASMHIST|CPU_ASMCENTER|CPU_ASMFOCUS);
return1;//Doubleclickprocessed
caseWM_USER_CHALL:
caseWM_USER_CHMEM:
//Somethingischanged,redrawwindow.
InvalidateRect(hw,NULL,FALSE);
return0;
caseWM_PAINT:
//PaintingofallOllyDbgwindowsisdonebyPainttable().Makecustom
//drawingonlyifyouhaveimportantreasonstodothis.
Painttable(hw,&bookmark,Bookmarkgettext);
return0;
default:break;
};
returnDefMDIChildProc(hw,msg,wp,lp);
};
//IfyoudefineODBG_Pluginmainloop,thisfunctionwillbecalledeachtime
//fromthemainWindowsloopinOllyDbg.Ifthereissomedebugeventfrom
//thedebuggedapplication,debugeventpointstoit,otherwiseitisNULL.Do
//notdeclarethisfunctionunnecessarily,asthismaynegativelyinfluence
//theoverallspeed!
extcvoid_exportcdeclODBG_Pluginmainloop(DEBUG_EVENT*debugevent){
};
//RecordtypesmustbeuniqueamongOllyDbgandallplugins.Thebestwayto
//assurethisistoregisterrecordtypebyOllDbg(OlehYuschuk).Registration
//isabsolutelyfreeofcharge,exceptforemailcosts:)
#defineTAG_BOOKMARK0x236D420AL//Bookmarkrecordtypein.uddfile
//Timetosavedatato.uddfile!ThisisdonebycallingPluginsaverecord()
//foreachdataitemthatmustbesaved.Global,process-orienteddatamust
//besavedinmain.uddfile(namedby.exe);module-relevantdatamustbe
//savedinmodulefiles.Don'tforgettosavealladdressesrelativeto
//module'sbase,sothatdatawillberestoredcorrectlyevenwhenmoduleis
//relocated.
extcvoid_exportcdeclODBG_Pluginsaveudd(t_module*pmod,intismainmodule){
inti;
ulongdata[2];
t_bookmark*pb;
if(ismainmodule==0)
return;//Savebookmarkstomainfileonly
pb=(t_bookmark*)bookmark.data.data;
for(i=0;i<bookmark.data.n;i++,pb++){
data[0]=pb->index;
data[1]=pb->addr;
Pluginsaverecord(TAG_BOOKMARK,2*sizeof(ulong),data);
};
};
//OllyDbgrestoresdatafrom.uddfile.Ifrecordbelongstoplugin,itmust
//processrecordandreturn1,otherwiseitmustreturn0topassrecordto
//otherplugins.Notethatmoduledescriptorpointedtobypmodcanbe
//incomplete,i.e.doesnotnecessarilycontainallinformations,especially
//thatfrom.uddfile.
extcint_exportcdeclODBG_Pluginuddrecord(t_module*pmod,intismainmodule,
ulongtag,ulongsize,void*data){
t_bookmarkmark;
if(ismainmodule==0)
return0;//Bookmarkssavedinmainfileonly
if(tag!=TAG_BOOKMARK)
return0;//Tagisnotrecognized
mark.index=((ulong*)data)[0];
mark.size=1;
mark.type=0;
mark.addr=((ulong*)data)[1];
Addsorteddata(&(bookmark.data),&mark);
return1;//Recordprocessed
};
//FunctionaddsitemseithertomainOllyDbgmenu(origin=PM_MAIN)ortopopup
//menuinoneofstandardOllyDbgwindows.Whenpluginwantstoaddownmenu
//items,itgathersmenupatternindataandreturns1,otherwiseitmust
//return0.Exceptforstaticmainmenu,pluginmustnotaddinactiveitems.
//Itemindicesmustrangein0..63.Duplicatedindicesareexplicitlyallowed.
extcint_exportcdeclODBG_Pluginmenu(intorigin,chardata[4096],void*item){
inti,n;
t_bookmark*pb;
t_dump*pd;
switch(origin){
//Menucreationisverysimple.Youjustfillindatawithmenupattern.
//Someexamples:
//0Aaa,2Bbb|3Ccc|,,-linearmenuwith3items,relativeIDs0,2and
//3,separatorbetweensecondandthirditem,last
//separatorandcommasareignored;
//#A{0Aaa,B{1Bbb|2Ccc}}-unconditionalseparator,followedbypopupmenu
//Awithtwoelements,secondispopupwithtwo
//elementsandseparatorinbetween.
casePM_MAIN://Pluginmenuinmainwindow
strcpy(data,"0&Bookmarks|1&About");
//Ifyourpluginismorethantrivial,IalsorecommendtoincludeHelp.
return1;
casePM_DISASM://PopupmenuinDisassembler
//Firstcheckthatmenuapplies.
pd=(t_dump*)item;
if(pd==NULL||pd->size==0)
return0;//Windowempty,don'tadd
//Startsecond-levelpopupmenu.
n=sprintf(data,"Bookmark{");
//Additem"Insertbookmarkn"iftherearefreebookmarksandsomepart
//ofDisassemblerisselected.NotethatOllyDbgcorrectlyinterpretes
//superfluoscommas,separatorsand,tosomeextent,missedbraces.
pb=(t_bookmark*)bookmark.data.data;
for(i=0;i<bookmark.data.n;i++)
if(pb[i].index!=(ulong)i)break;
if(i<10&&pd->sel1>pd->sel0)
n+=sprintf(data+n,"%i&Insertbookmark%i\tAlt+Shift+%i,",i,i,i);
//Additem"Deletebookmarkn"foreachavailablebookmark.Menu
//identifiersarenotnecessarilyconsecutive.
for(i=0;i<bookmark.data.n;i++){
n+=sprintf(data+n,"%iDeletebookmark%i,",pb[i].index+10,pb[i].index);
};
//Addseparatortomenu.
data[n++]='|';
//Additem"Gotobookmarkn"foreachavailablebookmark.Bookmarks
//setatselectedcommandarenotshown.
for(i=0;i<bookmark.data.n;i++){
if(pb[i].addr==pd->sel0)continue;
n+=sprintf(data+n,"%iGotobookmark%i\tAlt+%i,",
pb[i].index+20,pb[i].index,pb[i].index);
;
};
//Closepopup.Ifyouforgettodothis,OllyDbgwilltrytocorrect
//yourerror.
sprintf(data+n,"}");
return1;
default:break;//Anyotherwindow
};
return0;//Windownotsupportedbyplugin
};
//Thisoptionalfunctionreceivescommandsfrompluginmenuinwindowoftype
//origin.ArgumentactionismenuidentifierfromODBG_Pluginmenu().Ifuser
//activatesautomaticallycreatedentryinmainmenu,actionis0.
extcvoid_exportcdeclODBG_Pluginaction(intorigin,intaction,void*item){
t_bookmarkmark,*pb;
t_dump*pd;
if(origin==PM_MAIN){
switch(action){
case0:
//Menuitem"Bookmarks",createsbookmarkwindow.
Createbookmarkwindow();
break;
case1:
//Menuitem"About",displaysplugininfo.
MessageBox(hwmain,
"Bookmarkpluginv1.10\n"
"(demonstrationofplugincapabilities)\n"
"Copyright(C)2001-2004OlehYuschuk",
"Bookmarkplugin",MB_OK|MB_ICONINFORMATION);
break;
default:break;
};}
elseif(origin==PM_DISASM){
pd=(t_dump*)item;
if(action>=0&&action<10){//Insertbookmark
mark.index=action;
mark.size=1;
mark.type=0;
mark.addr=pd->sel0;
Addsorteddata(&(bookmark.data),&mark);
if(bookmark.hw!=NULL)InvalidateRect(bookmark.hw,NULL,FALSE);}
elseif(action>=10&&action<20){//Deletebookmark
pb=(t_bookmark*)Findsorteddata(&(bookmark.data),action-10);
if(pb!=NULL){
Deletesorteddata(&(bookmark.data),action-10);
if(bookmark.hw!=NULL)InvalidateRect(bookmark.hw,NULL,FALSE);
};}
elseif(action>=20&&action<30){//Gotobookmark
pb=(t_bookmark*)Findsorteddata(&(bookmark.data),action-20);
if(pb!=NULL){
Setcpu(0,pb->addr,0,0,CPU_ASMHIST|CPU_ASMCENTER|CPU_ASMFOCUS);
};
};
};
};
//StandardfunctionPainttable()makesmostofOllyDbgwindowsredrawing.You
//onlyneedtosupplyanotherfunctionthatpreparestextstringsand
//optionallycoloursthem.Caseofcustomwindowsisabitmorecomplicated,
//pleasereaddocumentation.
intBookmarkgettext(char*s,char*mask,int*select,
t_sortheader*ph,intcolumn){
intn;
ulongcmdsize,decodesize;
charcmd[MAXCMDSIZE],*pdecode;
t_memory*pmem;
t_disasmda;
t_bookmark*pb=(t_bookmark*)ph;
if(column==0){//Nameofbookmark
//Column0containsnameofbookmarkinform"Alt+n",wherenisthe
//digitfrom0to9.Mainlyfordemonstrationpurposes,Idisplayprefix
//"Alt+"ingrayedanddigitinnormaltext.Standardtablewindowsdo
//notneedtobotheraboutselection.
n=sprintf(s,"Alt+%i",pb->index);
*select=DRAW_MASK;
memset(mask,DRAW_GRAY,4);
mask[4]=DRAW_NORMAL;}
elseif(column==1)//Addressofbookmark
n=sprintf(s,"%08X",pb->addr);
elseif(column==2){//Disassembledcommand
//FunctionDisasm()requiresthatcallingroutinesuppliescodetobe
//disassembled.Readthiscodefrommemory.Firstdeterminepossible
//codesize.
pmem=Findmemory(pb->addr);//Findmemoryblockcontainingcode
if(pmem==NULL){
*select=DRAW_GRAY;returnsprintf(s,"???");};
cmdsize=pmem->base+pmem->size-pb->addr;
if(cmdsize>MAXCMDSIZE)
cmdsize=MAXCMDSIZE;
if(Readmemory(cmd,pb->addr,cmdsize,MM_RESTORE|MM_SILENT)!=cmdsize){
*select=DRAW_GRAY;returnsprintf(s,"???");};
pdecode=Finddecode(pb->addr,&decodesize);
if(decodesize<cmdsize)pdecode=NULL;
Disasm(cmd,cmdsize,pb->addr,pdecode,&da,DISASM_CODE,0);
strcpy(s,da.result);
n=strlen(s);}
elseif(column==3)//Comment
//Onlyuser-definedcommentsaredisplayedhere.
n=Findname(pb->addr,NM_COMMENT,s);
elsen=0;//sisnotnecessarily0-terminated
returnn;
};
//OllyDbgmakesmostofworkwhencreatingstandardMDIwindow.Pluginmust
//onlydescribenumberofcolumns,theirpropertiesandpropertiesofwindow
//asawhole.
voidCreatebookmarkwindow(void){
//Describetablecolumns.Notethatcolumnnamesarepointers,sostrings
//mustexistaslongastableitself.
if(bookmark.bar.nbar==0){
//Barstilluninitialized.
bookmark.bar.name[0]="Bookmark";//Nameofbookmark
bookmark.bar.defdx[0]=9;
bookmark.bar.mode[0]=0;
bookmark.bar.name[1]="Address";//Bookmarkaddress
bookmark.bar.defdx[1]=9;
bookmark.bar.mode[1]=0;
bookmark.bar.name[2]="Disassembly";//Disassembledcommand
bookmark.bar.defdx[2]=32;
bookmark.bar.mode[2]=BAR_NOSORT;
bookmark.bar.name[3]="Comment";//Comment
bookmark.bar.defdx[3]=256;
bookmark.bar.mode[3]=BAR_NOSORT;
bookmark.bar.nbar=4;
bookmark.mode=//Note:newoptionTABLE_ONTOP
TABLE_COPYMENU|TABLE_SORTMENU|TABLE_APPMENU|TABLE_SAVEPOS|TABLE_ONTOP;
bookmark.drawfunc=Bookmarkgettext;};
//Ifwindowalreadyexists,Quicktablewindow()doesnotcreatenewwindow,
//butrestoresandbringstotopexisting.Thisisthesimplestway,
//Newtablewindow()ismoreflexiblebutmorecomplicated.Idonotrecommend
//custom(plugin-drawn)windowswithoutveryimportantreasonstodothis.
Quicktablewindow(&bookmark,15,4,bookmarkwinclass,"Bookmarks");
};
//ThisfunctionreceivespossiblekeyboardshortcutsfromstandardOllyDbg
//windows.Ifitrecognizesshortcut,itmustprocessitandreturn1,
//otherwiseitreturns0.
extcint_exportcdeclODBG_Pluginshortcut(
intorigin,intctrl,intalt,intshift,intkey,void*item){
t_dump*pd;
t_bookmarkmark,*pm;
//PluginacceptsshortcutsinformAlt+xorShift+Alt+x,wherexisakey
//'0'..'9'.Shiftedshortcutsetsbookmark(onlyinDisassembler),
//non-shiftedjumpstobookmarkfromeverywhere.
if(ctrl==0&&alt!=0&&key>='0'&&key<='9'){
if(shift!=0&&origin==PM_DISASM&&item!=NULL){
//Setneworreplaceexistingbookmark.
pd=(t_dump*)item;
mark.index=key-'0';
mark.size=1;
mark.type=0;
mark.addr=pd->sel0;
Addsorteddata(&(bookmark.data),&mark);
if(bookmark.hw!=NULL)InvalidateRect(bookmark.hw,NULL,FALSE);
return1;}//Shortcutrecognized
elseif(shift==0){
//Jumptoexistingbookmark(fromanywindow).
pm=Findsorteddata(&(bookmark.data),key-'0');
if(pm==NULL)
Flash("Undefinedbookmark");
else
Setcpu(0,pm->addr,0,0,CPU_ASMHIST|CPU_ASMCENTER|CPU_ASMFOCUS);
return1;//Shortcutrecognized
};
};
return0;//Shortcutnotrecognized
};
//Functioniscalledwhenuseropensneworrestartscurrentapplication.
//Pluginshouldresetinternalvariablesanddatastructurestoinitialstate.
extcvoid_exportcdeclODBG_Pluginreset(void){
Deletesorteddatarange(&(bookmark.data),0,0xFFFFFFFF);
};
//OllyDbgcallsthisoptionalfunctionwhenuserwantstoterminateOllyDbg.
//AllMDIwindowscreatedbypluginsstillexist.Functionmustreturn0if
//itissafetoterminate.Anynon-zeroreturnwillstopclosingsequence.Do
//notmisusethispossibility!Alwaysinformuseraboutthereasonswhy
//terminationisnotgoodandaskforhisdecision!
extcint_exportcdeclODBG_Pluginclose(void){
//Forautomaticalrestoringofopenwindows,markin.inifilewhether
//Bookmarkswindowisstillopen.
Pluginwriteinttoini(hinst,"Restorebookmarkswindow",bookmark.hw!=NULL);
return0;
};
//OllyDbgcallsthisoptionalfunctiononceonexit.Atthismoment,allMDI
//windowscreatedbypluginarealreadydestroyed(andreceivedWM_DESTROY
//messages).Functionmustfreeallinternallyallocatedresources,like
//windowclasses,files,memoryandsoon.
extcvoid_exportcdeclODBG_Plugindestroy(void){
Unregisterpluginclass(bookmarkwinclass);
Destroysorteddata(&(bookmark.data));
};
Attachtoactiveprocess
AttachesOllyDbgtoactive(running)processwithknownprocessidentifier.Ifanotherprocessisdebugged,asksforpermissiontocloseit.Returns0onsuccessand-1onerror.
intAttachtoactiveprocess(intprocessid);
Parameters:
processid-identifierofrunningprocess.
Seealso:OpenEXEfile
Creatertracewindow
Createsneworbringstotopexistingwindowdisplayingruntracehistory.Onlyonesuchwindowmayexistatatime.ReturnshandleofthewindoworNULLonerror.
HWNDCreatertracewindow(void);
Demanglename
Demanglesorundecoratesname.CurrentlysupportsBorlandandMicrosoftmanglingschemes.Returns0ifnameisnotmangled(inthiscasebufferpointedtobyundecoratedisinvalidandprobablymodified)andlengthofunmanglednameonsuccess.Attention,noguaranteethatdemanglednameisunique!
intDemanglename(char*name,inttype,char*undecorated);
Parameters:
name-pointertomangledname;
type-typeofname.FunctiontreatsnamesoftypesNM_IMPORTandNM_IMPNAMEinaspecialway;
undecorated-pointertooutputbufferoflengthatleastTEXTLENcharacters.