Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


Lua Plugin CE Marked addresses (branches)

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Extensions
View previous topic :: View next topic  
Author Message
GH*master
Expert Cheater
Reputation: 8

Joined: 10 Jan 2008
Posts: 159

PostPosted: Fri Jan 06, 2017 1:26 pm    Post subject: Lua Plugin CE Marked addresses (branches) This post has 1 review(s) Reply with quote

Hint
1. Attach process
2. Copy/pasle Lua code
3. Change address:
startAddress = 0x0056EAC0
endAddress = 0x0056EBCB
4. Run Lua code

* Maximum 8 unique branches
** 0.91 beta version/possible bugs

Repository: link
-----------------





Code:
--RasterImage OPTIONAL, x OPTIONAL, y OPTIONAL
function OnExtraLineRender(sender_disassemblerviewLine, address, aboveInstruction, selected)

   for i = 1,8 do
      temporaryMarkerTable[i] = 0
   end

   -- по умолчанию #tablePuths == 8
   for i = 1,#tablePuths do
      -- tableAddresses хранит пары адресов не прерывного пути. Все пары составляют путь
      local tableAddresses = tablePuths[i][1]
      if(tableAddresses ~= nil) then
         for j = 1, #tableAddresses do
            if (tableAddresses[j] == address) then
               temporaryMarkerTable[i] = 1
            end
         end
      end
   end

   local allNull = true
   for i = 1,8 do
      if(temporaryMarkerTable[i] == 1) then
      allNull = false
      end
   end

   if(allNull) then
      return nil, extraLineRender_X - 100, extraLineRender_Y
   end

   -- Ищем в матрице индекс растрового изображения
   for i = 1,255 do

      -- Сохранить растровое изображение bitmap и карту марекров bitTable
      local tempalteTable = matrixColorsTable[i]
      local bitTable = tempalteTable[1]
      local bitmap = tempalteTable[2]

      local isFindedIndex = true
      for j = 1,8 do
         if (temporaryMarkerTable[j] ~= bitTable[j]) then
           isFindedIndex = false
           break
         end
      end


      if (isFindedIndex) then
         if(aboveInstruction) then
            -- TODO: bug CE 6.6. Если не возвращать, то вылет
            return bitmap, extraLineRender_X - 600, extraLineRender_Y
         else
            return bitmap, extraLineRender_X, extraLineRender_Y
         end
      end
   end
end

function debugger_onBreakpoint()

      if(EIP >= startAddress and EIP <= endAddress) then
         --Breakpoint continue methods: co_run=0, co_stepinto=1, co_stepover=2
         debug_continueFromBreakpoint(co_stepover)
         
         -- Добавляет адрес во временную таблицу
         table.insert(temporaryRecordPath, EIP)
         hitsCode = hitsCode + 1
      else
         -- TODO: Паковать адреса парами (оптимизация, сделать потом)
         -- TODO: Сравнивать пары адресов с другими путями, если отличиные, то это новый путь
         
         -- По умолчанию есть отличия между текущим путем и ранее сохраненным
         anyDifference = false
         
         
------------------ Ищем полное совпадение ветки

         -- Если все ветки пустые, то проход считается новым
         
         
         -- Проверить, что нет еще ни одной созданной ветки
         local someBranch = false
         -- Проверить, есть ли хотябы одно совпадения с ветками
         local anyDiffBranch = false
         
         for i = 1,#tablePuths do
            if(tablePuths[i] ~= nil and #tablePuths[i] > 0) then
               someBranch = true
               break
            end
         end
         
         if (not someBranch) then
            anyDifference = true
            --print('J')
            goto done
         end
         ----------------------------------------------------
         
         for i = 1,#tablePuths  do
            local tableAddresses = tablePuths[i][1]
            
            if(tableAddresses ~= nil) then
               if(#tableAddresses == #temporaryRecordPath) then
                  
                  anyDiffBranch = false
                  
                  for j = 1, #tableAddresses do
                     if (tableAddresses[j] ~= temporaryRecordPath[j]) then
                        
                        -- У ветки i, есть различия. Но нужно проверить остальные пути
                        anyDiffBranch = true
                        break
                     end
                  end
                  
                  -- Ветка похожа, не добавлять
                  if(anyDiffBranch) then
                     --print(#tablePuths..'-'..i)
                     -- Если кончились пути и есть отличия, то выход
                     if (i >= #tablePuths) then
                        --print('A11')
                        anyDifference = true
                        goto done
                     end
                  else
                     --print('AA')
                     -- Это похожая ветка
                     anyDifference = false
                     goto done
                  end
               end
               
               --print(i)
               --print('N')
            end


            if (i >= #tablePuths) then
               --print('A 333')
               anyDifference = true
               goto done
            end
         end
         
         ----------------------------------------------------
         --print('KKK')
         ::done::
         
         if (anyDifference and countGlobalPath < 8) then
            -- Это отличиный путь и его нужно связать с новым цветом
            tablePuths[countGlobalPath][1] = temporaryRecordPath
            countGlobalPath = countGlobalPath + 1
            
            if(countGlobalPath >= 8) then
               print('countGlobalPath >= 8. Stop marked')
               debug_removeBreakpoint(startAddress)
               debug_removeBreakpoint(endAddress)
            end
         else
            -- Это путь уже был. Пока ничего не делать
         end
         
         -- Если создается 8 путей, то новый путь не создается. Отладка останавливается
         temporaryRecordPath = {}
         debug_continueFromBreakpoint(co_run)
      end
         
   return 1 --I handled it so dont tell the user
   -- return 0 --unexpected breakpoint, show the the user
end

function ExtraLineRender_Init()

   local widthSingleMarker = 2
   local heightSingleMarker = 20
   local deltaX_Position = 2
   
   local ClRed      = 0x0000FF
   local clOrange   = 0x00AEFF
   local ClYellow    = 0x00FFFF
   local ClGreen   = 0x008000
   local clAqua   = 0xFFFF00
   local ClBlue   = 0xFF0000
   local clPurpure   = 0xFF00B2
   local ClLightGreen = 0x00FF00

   -- Создаем 255 растровых изображений - комбинаций маркеров в ряд
   -- Связываем ряд с индексом
   for i = 1,255 do
      local bitTable = ToBits(i)
    
      local bitmap = createBitmap((widthSingleMarker+deltaX_Position)*8, heightSingleMarker)
      bitmap.Width = (widthSingleMarker + deltaX_Position) * 8
      bitmap.Height = heightSingleMarker
      -- bitmap.Canvas.clear()
      -- Обрезка
      -- Серый цвет
      bitmap.Canvas.Brush.Color = 0xC8D0D4
      bitmap.Transparent = true
      bitmap.TransparentColor = 0xC8D0D4
      
      bitmap.Canvas.clear()
      bitmap.Canvas.fillRect(0, 0, bitmap.Width, bitmap.Height)
            
      -- Рисование маркеров в ряд
      for j = 1,8 do
      
         if(bitTable[j] == 1) then
      
            if (j == 1) then bitmap.Canvas.Brush.Color = ClRed         end
            if (j == 2) then bitmap.Canvas.Brush.Color = clOrange      end
            if (j == 3) then bitmap.Canvas.Brush.Color = ClYellow      end   
            if (j == 4) then bitmap.Canvas.Brush.Color = ClGreen      end
            if (j == 5) then bitmap.Canvas.Brush.Color = clAqua         end
            if (j == 6) then bitmap.Canvas.Brush.Color = ClBlue         end
            if (j == 7) then bitmap.Canvas.Brush.Color = clPurpure      end
            if (j == 8) then bitmap.Canvas.Brush.Color = ClLightGreen   end

            local x0 = (widthSingleMarker + deltaX_Position) * (j - 1)
            local x1 = x0 + widthSingleMarker
            
            -- Закраска в ряд
            bitmap.Canvas.fillRect(x0, 0, x1, 20)
         end
         
      end
      
      -- Сохранить растровое изображение bitmap и карту марекров bitTable
      local tempalteTable = {}
      table.insert(tempalteTable, bitTable)
      table.insert(tempalteTable, bitmap)
      
      table.insert(matrixColorsTable, tempalteTable)
   end

   -- Инициализируем таблицу адресов на каждый из 8-ми возможных путей
   for i=1,8 do
      local tableAddresses = {}
      table.insert(tablePuths, tableAddresses)
   end
   
   -- Связь обработчика c OnExtraLineRender
   getMemoryViewForm().DisassemblerView.OnExtraLineRender = OnExtraLineRender
end

function ToBits(num, bits)
   local t={}
   for b=8,1,-1 do
      rest = math.fmod(num,2)
      t[b] = math.floor(rest)
      num = (num-rest)/2
   end
   if num == 0 then return t else return {'Not enough bits to represent this number'}end
end

function UpdateUIData()
 -- Сколько раз вызывается код
 setHeader(startAddress, 'Hits:'..hitsCode..', Branches: '..(countGlobalPath - 1))
end

-- Вызывать, если надо остановить
function Stop()
   debug_removeBreakpoint(startAddress)
   debug_removeBreakpoint(endAddress)
   uiTimer.Enabled = false
   destroy(timer)
   getMemoryViewForm().DisassemblerView.OnExtraLineRender = nil
end

-- Запуск
function Start()
   startAddress          = 0x0056EAC0
   endAddress             = 0x0056EBCB
   extraLineRender_X       = 65
   extraLineRender_Y       = -20

   tablePuths             = {}
   temporaryRecordPath    = {}
   countGlobalPath       = 1
   matrixColorsTable       = {}
   temporaryMarkerTable    = {}

   hitsCode = 0
   ExtraLineRender_Init()
   -- тип отладки (0=default, 1=windows debug, 2=VEHDebug, =Kerneldebug)
   local typeDebug = 13
   -- Breakpoint triggers: bptExecute=0, bptAccess=1, bptWrite=2
   debug_setBreakpoint(startAddress, vtByte, bptExecute)
   -- vtByte=0, vtWord=1, vtDword=2
   debug_setBreakpoint(endAddress, vtByte, bptExecute)
   debugProcess(typeDebug)
   
   -- UI таймер
   uiTimer = createTimer(nil, true)
   uiTimer.Interval = 1
   uiTimer.OnTimer = UpdateUIData
   
   -- Перход и наблюдение
   getMemoryViewForm().Show()
   getMemoryViewForm().DisassemblerView.TopAddress = startAddress
end

Start()


   -- TODO: кнопка - остановки отладки. Сейчас остановка возможна, если путей больше равно восьми
   -- TODO: Если путей больше 8-ми, то сообщение что лимит цветов превысел 8 и отладка будет остановлена. Отладка останавливается
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Extensions All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites