开发者

Is it possible to bring GCC into an infinite loop?

Is it possible to bring GCC into an开发者_如何转开发 infinite loop by inputting strange source code? And if yes, how? Maybe one could do something with Template Metaprogramming?


Yes.

Almost every computer program has loop termination problems. I'm thinking that GCC, however, would run out of RAM before an infinite loop ever becomes obvious. There aren't many "free" operations in its design.

The parser & preprocessor wouldn't create problems. I'm willing to bet that you could target the optimizer, which would likely have more implementation faults. It would be less about the language and more about exploiting a flaw you could discover from the source code. i.e. the exploit would be non-obvious.

UPDATE

In this particular case, my theory seems correct. The compiler keeps allocating RAM and the optimizer does seem to be vulnerable. The answer is yes. Yes you can.


Bugs are particularly transient, for example @Pestilence's answer was found in GCC 4.4.0 and fixed in 4.4.1. For a list of current ways to bring GCC to an infinite loop, check their Bugzilla.

EDIT: I just found a new way, which also crashes Comeau. This is a more satisfying answer, for now. Of course, it should also be fixed soon.

template< int n >
struct a { 
    a< n+1 > operator->() { return a< n+1 >(); }
};

int main() {
    a<0>()->x;
}


Since C++ template metaprogramming is in fact Turing complete you can make a never ending compilation.

For example:

template<typename T>
struct Loop {
   typedef typename Loop<Loop<T> >::Temp Temp;
};

int main(int, char**) {
   Loop<int> n;
   return 0;
}

However, like the answer before me. gcc has a flag to stop this from continuing endlessly (Much like a stack overflow in an infinite recursion).


Bentley writes in his book "Programming Pearls" that the following code resulted in an infinite loop during optimized compilation:

void traverse(node* p) {
  traverse(p->left);
  traverse(p->right);
}

He says "the optimizer tried to convert the tail recursion into a loop, and died when it could find a test to terminated the loop." (p.139) He doesn't report the exact compiler version where that happened. I assume newer compilers detect the case.


It may be possible. But most compilers (and most standardised languages) have limits on things like recursion depths in templates or include files, at which point the compiler should bail out with a diagnostic. Compilers that don't do this are not normally popular with users.


Don't know about gcc, but old pcc used to go into an infinite loop compiling some kinds of infinite loops (the ones that compiled down to _x: jmp _x).


I think you could do it with #include

Just #include "file1.c" into file2.c and #include "file2.c" in file1

suggestion causes compiler to loop a lot then fail, not loop infinitely

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜