Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [cdt-dev] Reg: Array subscript of a C program using Eclipse CDT

> I want to implement the buffer overrun problem of C program using java  
> with the help of Eclipse CDT. 
>  
> I used the following code to get the value of the array-subscript. 
>  
>  
>      CASTArraySubscriptExpression exprn =  
> (CASTArraySubscriptExpression)astName.getParent().getParent(); 
>  
>   String size = exprn.getSubscriptExpression().toString(); 
>  
>    System.out.println("Size : " + size); 
>  
>  
> If I give the constant value as array-subscript[like in Eg:1], I am  
> able to get this value using the above code. 
>  
> But if I set the variable as array-subscript [like in Eg:2], the code  
> does not return the value. 
>  
>  
> How can I  detect the array-Index using CDT? Is CDT provide any API  
> regarding this? 

This is not public API, but you can do something like:

  import org.eclipse.cdt.core.dom.ast.IValue;
  import org.eclipse.cdt.internal.core.dom.parser.Value;

  IValue value = Value.create(exprn.getSubscriptExpression(), Value.MAX_RECURSION_DEPTH);
  if (value == Value.UNKNOWN || value.numericalValue() == null)
      System.out.println("cannot determine value of subscript");
  else
      System.out.println("value of subscript is " + value.numericalValue().longValue());

It's also possible to do using just public API but then you have to
recurse over the structure of the expression yourself. If you only
care about id-expressions (expressions that name a variable), it 
would be  something like:

  IASTExpression subscript = exprn.getSubscriptExpression();
  if (subscript instanceof IASTIdExpression)
  {
      IASTName name = ((IASTIdExpression) subscript).getName();
      IBinding binding = name.resolveBinding();
      if (binding instanceof IVariable)
      {
          IValue value = ((IVariable) binding).getInitialValue();
          // use the value
      }
  }

(This probably goes without saying but keep in mind that any value 
you get from CDT will just be the _initial_ value of a variable.
If the variable is not const then the value of the index may be
different at runtime.)

Regards,
Nate 		 	   		  

Back to the top