TransWikia.com

Virtual functions call asm

Reverse Engineering Asked on January 24, 2021

It seems to be a virtual function call. How would this code look in a high-level language like C ++?

.text:0053A745 loc_53A745:                             ; CODE XREF: sub_53A690+CEj
.text:0053A745                 mov     ecx, [edi+esi*4]
.text:0053A748                 test    ecx, ecx
.text:0053A74A                 jz      short loc_53A751
.text:0053A74C                 mov     edx, [ecx]
.text:0053A74E                 call    dword ptr [edx+4]
.text:0053A751
.text:0053A751 loc_53A751:                             ; CODE XREF: sub_53A690+BAj
.text:0053A751                 mov     eax, dword_83C020
.text:0053A756                 test    eax, eax
.text:0053A758                 jnz     short loc_53A78D
.text:0053A75A                 inc     esi
.text:0053A75B                 cmp     esi, 25h
.text:0053A75E                 jl      short loc_53A745

One Answer

This could be a loop over 37 objects with virtual functions, the simplified version could look similar to this (written in C++)

#include <iostream>

class Animal
{
public:
    virtual void makeSound() = 0;
    virtual char* getColor() = 0;
    virtual ~Animal() = 0;
};

class Cat : public Animal
{
public:
    Cat();
    void makeSound() { std::cout << "meow" << std::endl; }
    char* getColor() { return "red"; };
    ~Cat() {};
};

Animal* animals[] = {new Cat(), new Cat(), new Cat()};
int main()
{
    for (int i = 0; i < 3; i++)
        if (animals[i])
            std::cout << animals[i]->getColor();

    for (int i = 0; i < 3; i++)
        delete animals[i];
    return 0;
}

With the core lines:

if (animals[i])
  std::cout << animals[i]->getColor();

Compiled to this by clang 8.0.0:

cmp     dword ptr [animals + eax*4], 0
je      .LBB2_4
mov     eax, dword ptr [ebp - 8]
mov     eax, dword ptr [animals + eax*4]
mov     ecx, dword ptr [eax]
mov     dword ptr [esp], eax
call    dword ptr [ecx + 4]

Additionally your code seems to follow Microsoft __thiscall calling convention, as the this pointer is stored in ecx register.

Answered by morsisko on January 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP