NationalSecurityAgency / ghidra

Ghidra is a software reverse engineering (SRE) framework
https://www.nsa.gov/ghidra
Apache License 2.0
50.93k stars 5.81k forks source link

Detect typical for loops #644

Open henke37 opened 5 years ago

henke37 commented 5 years ago

The decompiler takes a rather pessimistic approach and considers all loops to be while loops. For patterns known to be traditionally written using for loops, it should output the loop as a for loop instead.

teaalltr commented 5 years ago

for instance,

void __thiscall SymbolTable(SymbolTable *this,int param_1)

{
  SymbolHashNode **ppSVar1;
  int iVar2;

  this->size = param_1;
  ppSVar1 = (SymbolHashNode **)
            operator_new__(-(uint)((int)((ulonglong)(uint)param_1 * 4 >> 0x20) != 0) |
                           (uint)((ulonglong)(uint)param_1 * 4));
  this->bucket = ppSVar1;
  iVar2 = 0;
  if (0 < this->size) {
    do {
      this->bucket[iVar2] = (SymbolHashNode *)0x0;
      iVar2 = iVar2 + 1;
    } while (iVar2 < this->size);
  }
  return;
}

may be converted to

void __thiscall SymbolTable::SymbolTable(SymbolTable *this, int param_1)
{
  SymbolTable *v2; 
  int i; 
  this->size = param_1;
  this->bucket = (SymbolHashNode **)operator new[](4 * param_1); // maybe too c++ish
  for ( i = 0; i < this->size; ++i )
    this->bucket[i] = 0;
}

it could also go further by noting that i's scope is the loop and write "int i = 0". Also note the rewrite of operator new's argument

teaalltr commented 4 years ago

@ryanmkurtz Any news for this issue? Are you devs working / planning to work on this?

ryanmkurtz commented 4 years ago

No news that I am aware of, but I'll check with the right people and get back to you.

ryanmkurtz commented 4 years ago

No one is working on it yet, but it's on the list of things to do. Unfortunately at this time I can't give you a prediction of when it will be started.

teaalltr commented 4 years ago

Thanks, good to know :+1:

ccarpenter04 commented 4 years ago

I would also really like to see different types of loops be represented better by the decompiler. As you can see in the example provided by @Piruzzolo it would help clean up the code a lot, especially in larger, already complex functions.

EmperorArthur commented 3 years ago

I know some support has been added for this feature, but it does not seem to work with the executable I am working with. At the least, I wish I could manually convert a do{}while() loop into a for loop. As is, my best option is comments.

Wall-AF commented 3 months ago

Hi guys. Any chance of this bein looked into? If you need examples, I've hundreds!

It seems that as of June 2024, while loops get decompiled as for loops and vice versa!

vitecd commented 1 month ago

How do I convert whileto for, please?