Changeset 199
- Timestamp:
- 11/04/09 10:07:34 (3 weeks ago)
- Location:
- trunk/cpp_analysis/src/xtc/lang/c4
- Files:
-
- 3 added
- 8 modified
-
C4.java (modified) (5 diffs)
-
C4Callable.java (added)
-
C4Core.rats (modified) (1 diff)
-
C4Extractable.java (added)
-
C4ParserState.java (modified) (2 diffs)
-
C4Wrapper.java (added)
-
CPPAnalyzer.java (modified) (43 diffs)
-
ConvertibleLogger.java (modified) (1 diff)
-
DBHandler.java (modified) (24 diffs)
-
Makefile (modified) (2 diffs)
-
TreeLogger.java (modified) (7 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/cpp_analysis/src/xtc/lang/c4/C4.java
r193 r199 33 33 /** A shared parser state. */ 34 34 private C4ParserState parserState = null; 35 36 static C4State preState = null; 35 37 36 38 /** */ … … 49 51 return "C4 Tool"; 50 52 } 51 52 public void init() { 53 public void init() { 53 54 super.init(); 54 55 runtime.bool("transform", "optionTransformC4", … … 82 83 ; 83 84 85 84 86 macrosManager = new C4MacrosManager(); 85 parserState = new C4ParserState(macrosManager); 87 parserState = new C4ParserState(preState, macrosManager); 88 86 89 cmdLineHeaders = new ArrayList<Node>(); 87 90 } … … 544 547 * Between each iteration, we need to reset the State 545 548 */ 546 public static void resetPreState() { 547 C4ParserState.resetPreState(); 548 } 549 549 550 public static C4State getPreState() { 551 return preState; 552 } 553 554 /*public void setPreState(C4State preState) { 555 this.preState = preState; 556 }*/ 557 550 558 /** 551 559 * Run the tool with the specified command line arguments. … … 554 562 * The command line arguments. 555 563 */ 556 public static void main(String[] args) {557 564 public static void entry(String[] args) { 565 try { 558 566 C4 c4tool = new C4(); 559 567 if(0 != args.length) 560 568 c4tool.fileProcessed = args[args.length - 1]; 561 569 c4tool.run(args); 562 570 c4tool = null; 571 } catch(Exception e) { 572 System.exit(-1); 573 } 563 574 } 564 575 } -
trunk/cpp_analysis/src/xtc/lang/c4/C4Core.rats
r198 r199 350 350 <PElse> void:"else":Keyword Statement? 351 351 / <FuncMacroCompoundStmt> funcMacroCall:FunctionMacroCallStatement 352 { yyValue = GNode.create("FunctionMacroCompoundSt mt", funcMacroCall, yyState.getMacro(yyState.getRegisteredMacroId())); }352 { yyValue = GNode.create("FunctionMacroCompoundStatement", funcMacroCall, yyState.getMacro(yyState.getRegisteredMacroId())); } 353 353 / <ObjectMacroStmt> id:Identifier &{ yyState.isMacro(toText(id)) && !(yyState.isBlockBeginning(toText(id)) || yyState.isBlockEnding(toText(id)))} 354 354 { yyValue = GNode.create("MacroReference",id,yyState.getMacro(toText(id)));} -
trunk/cpp_analysis/src/xtc/lang/c4/C4ParserState.java
r198 r199 1 /* 2 * xtc - The eXTensible Compiler 3 * Copyright (C) 2005-2006 Princeton University 4 * 5 * This program is free software; you can redistribute it and/or 6 * modify it under the terms of the GNU General Public License 7 * version 2 as published by the Free Software Foundation. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 17 * USA. 18 */ 19 package xtc.lang.c4; 20 21 import java.util.ArrayList; 22 import java.util.HashMap; 23 import java.util.Iterator; 24 25 import xtc.lang.c4.C4State.Context; 26 import xtc.tree.GNode; 27 import xtc.tree.LineMarker; 28 import xtc.tree.Location; 29 import xtc.tree.Node; 30 import xtc.tree.Pragma; 31 import xtc.tree.SourceIdentity; 32 import xtc.tree.Visitor; 33 import xtc.util.State; 34 35 36 /** 37 * State for parsing C4. 38 * 39 * @author Laurent Burgy 40 * @version $Revision: 1.3 $ 41 */ 42 public class C4ParserState implements State { 43 44 private class MacroUndefException extends RuntimeException { 45 /** 46 * 47 */ 48 private static final long serialVersionUID = -4091350260433333109L; 49 private String macroName; 50 51 MacroUndefException(String name) { 52 super(); 53 macroName = name; 54 } 55 56 MacroUndefException() { 57 super(); 58 } 59 60 public void printStackTrace() { 61 System.out.println("Undefined Macro " + macroName); 62 super.printStackTrace(); 63 } 64 65 public String getMessage() { 66 return ("Undefined Macro" + macroName + " " + super.getMessage()); 67 } 68 69 public String getMacroName() { 70 if(null != macroName) 71 return macroName; 72 return ""; 73 } 74 75 } 76 77 78 // ========================================================================== 79 80 /** 81 * Add the specified number of fresh contexts to the pool. 82 * 83 * @param n The number to add. 84 */ 85 protected void fillPool(int n) { 86 preState.fillPool(n); 87 } 88 89 /** 90 * Take a context from the pool, refilling the pool if necessary. 91 * 92 * @return A fresh context. 93 */ 94 protected Context takeFromPool() { 95 return preState.takeFromPool(); 96 } 97 98 /** 99 * Return the specified context to the pool, clearing it along the 100 * way. 101 * 102 * @param c The context to return. 103 */ 104 protected void addToPool(Context c) { 105 preState.addToPool(c); 106 } 107 108 // ========================================================================== 109 110 /** 111 * Push the specified context onto the context stack. 112 * 113 * @param c The context to push. 114 */ 115 protected void push(Context c) { 116 preState.push(c); 117 } 118 119 /** 120 * Pop a context from the context stack. 121 * 122 * @return The top-most context. 123 */ 124 protected Context pop() { 125 return preState.pop(); 126 } 127 128 public void start() { 129 preState.start(); 130 } 131 132 public void commit() { 133 preState.commit(); 134 } 135 136 public void abort() { 137 preState.abort(); 138 } 139 140 // ========================================================================== 141 142 /** Record a typedef storage class specifier. */ 143 public void typedef() { 144 preState.typedef(); 145 } 146 147 /** Record a function parameter list. */ 148 public void parameters() { 149 preState.parameters(); 150 } 151 152 /** Record a function declarator. */ 153 public void functionDeclarator() { 154 preState.functionDeclarator(); 155 } 156 157 /** Enter a new scope. */ 158 public void pushScope() { 159 preState.pushScope(); 160 } 161 162 /** Exit the last scope. */ 163 public void popScope() { 164 preState.popScope(); 165 } 166 167 /** Enter a structure declaration list. */ 168 public void enterStructure() { 169 preState.enterStructure(); 170 } 171 172 /** Exit a structure declaration list. */ 173 public void exitStructure() { 174 preState.exitStructure(); 175 } 176 177 178 179 /** 180 * Determine whether a declaration actually is a declaration. This 181 * method determines whether the sequence 182 * <pre> 183 * DeclarationSpecifiers l:InitializedDeclaratorList? 184 * </pre> 185 * can actually represent a declaration. It assumes that any type 186 * specifier encountered while parsing 187 * <code>DeclarationSpecifiers</code> has been marked through {@link 188 * #typeSpecifier()}. 189 * 190 * @param idl The result of parsing the optional initialized 191 * declarator list. 192 * @return <code>true</code> if the declaration is a declaration. 193 */ 194 public boolean isValid(Node idl) { 195 return preState.isValid(idl); 196 } 197 198 // ========================================================================== 199 200 /** 201 * Record a line marker. Note that string values for the four flags 202 * are interpreted as follows: Any non-null string counts for 203 * <code>true</code>, while null counts for <code>false</code>. 204 * 205 * @see LineMarker 206 * 207 * @param file The file name (without quotes). 208 * @param line The line number. 209 * @param isStartFile The start file flag. 210 * @param isReturnToFile The return to file flag. 211 * @param isSystemHeader The system header flag. 212 * @param isExternC The extern C flag. 213 * @param location The line marker's source location. 214 */ 215 public void lineMarker(String file, int line, String isStartFile, 216 String isReturnToFile, String isSystemHeader, 217 String isExternC, Location location) { 218 preState.lineMarker(file, line, isStartFile, isReturnToFile, isSystemHeader, isExternC, location); 219 } 220 221 /** 222 * Record a pragma. 223 * 224 * @see Pragma 225 * 226 * @param directive The actual directive. 227 * @param location The pragma's source location. 228 */ 229 public void pragma(String directive, Location location) { 230 preState.pragma(directive, location); 231 } 232 233 /** 234 * Record an ident directive. 235 * 236 * @see SourceIdentity 237 * 238 * @param ident The actual identity marker. 239 * @param location The ident directive's source location. 240 */ 241 public void ident(String ident, Location location) { 242 preState.ident(ident, location); 243 } 244 245 /** 246 * Mark the current annotation. This method must be called before 247 * recognizing the nonterminals to be annotated. Furthermore, it 248 * must be called within the context of a stateful production. 249 */ 250 public void mark() { 251 preState.mark(); 252 } 253 254 /** 255 * Annotate the specified node. If any annotations have been 256 * recorded and {@link #mark() marked}, the specified node is 257 * wrapped by those annotations and the outer-most annotation is 258 * returned. Otherwise, the specified node is returned. 259 * 260 * @param node The node. 261 * @return The annotated node. 262 */ 263 public Node annotate(Node node) { 264 return preState.annotate(node); 265 } 266 267 //=========================================================================== 268 /** The C4 State to manage everything 269 * before everything was collecting using C4ParserState 270 * but it's no longer possible 271 * I've added a static field that manages all the state 272 */ 273 static C4State preState = new C4State(); 274 275 /** The current Object MacroId */ 276 String omId ; 277 278 /** 279 * Expression Evaluator 280 */ 281 /** Left Value for a If directive */ 282 String leftValue ; 283 284 boolean leftValueSet; 285 286 boolean isLeft = false; 287 288 boolean isRight = false; 289 290 /** Right Value for a If directive */ 291 String rightValue; 292 293 /** To check if the macro currently defined is an attribute */ 294 boolean isAttribute = false; 295 296 /** 297 * Variable that stores the temp value of the IfSection Conditional (if arithmetic included) 298 */ 299 long tmpCondValue = 0; 300 301 boolean tmpCondValueSet = false; 302 303 /* 304 * Variable that contains the name of the macro currently used inside a declaration 305 * only used as a temporary storage for the parser 306 */ 307 private String registeredMacroId; 308 309 /* 310 * Sets the id of the registered macro 1 /* 2 * xtc - The eXTensible Compiler 3 * Copyright (C) 2005-2006 Princeton University 4 * 5 * This program is free software; you can redistribute it and/or 6 * modify it under the terms of the GNU General Public License 7 * version 2 as published by the Free Software Foundation. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 17 * USA. 18 */ 19 package xtc.lang.c4; 20 21 import java.util.ArrayList; 22 import java.util.HashMap; 23 import java.util.Iterator; 24 25 import xtc.lang.c4.C4State.Context; 26 import xtc.tree.GNode; 27 import xtc.tree.LineMarker; 28 import xtc.tree.Location; 29 import xtc.tree.Node; 30 import xtc.tree.Pragma; 31 import xtc.tree.SourceIdentity; 32 import xtc.tree.Visitor; 33 import xtc.util.State; 34 35 36 /** 37 * State for parsing C4. 38 * 39 * @author Laurent Burgy 40 * @version $Revision: 1.3 $ 41 */ 42 public class C4ParserState implements State { 43 44 private class MacroUndefException extends RuntimeException { 45 /** 311 46 * 312 47 */ 313 public String getRegisteredMacroId() { 314 return registeredMacroId; 315 } 316 317 public void setRegisteredMacroId(String registeredMacroId) { 318 this.registeredMacroId = registeredMacroId; 319 } 320 321 /** 322 * Default constructor. 323 */ 324 public C4ParserState() { 48 private static final long serialVersionUID = -4091350260433333109L; 49 private String macroName; 50 51 MacroUndefException(String name) { 325 52 super(); 326 } 327 328 /** 329 * Constructor with a macro manager. 330 * 331 * @param macrosManager An instance of the C4MacrosManager. 332 */ 333 public C4ParserState(C4MacrosManager macrosManager) { 334 this(); 335 if(preState == null) //If we do not use the wrapper 336 resetPreState(); // we need to instantiate the preState 337 338 preState.setMacrosManager(macrosManager); 339 } 340 341 /** 342 * Sets the include path manager. 343 * 344 * @param manager 345 * An instance of the include path manager. 346 */ 347 public void setIncludePathManager(C4IncludePathManager manager) { 348 preState.setIncludePathManager(manager); 349 } 350 351 /** 352 * Sets the parseTree flag 353 * @param parseTreeFlag 354 * A boolean 355 */ 356 public void setParseTree(boolean parseTree) { 357 preState.setParseTree(parseTree); 358 } 359 360 /** 361 * Sets the parseTree flag 362 * @param parseTreeFlag 363 * A boolean 364 */ 365 public boolean getParseTree() { 366 return preState.getParseTree(); 367 } 368 369 /** 370 * Returns the include path manager. 371 * 372 * @return The include path manager. 373 */ 374 public C4IncludePathManager getIncludePathManager() { 375 return preState.getIncludePathManager(); 376 } 377 378 /** 379 * Increments the include level. 380 */ 381 public void incIncludeLevel() { 382 preState.incIncludeLevel(); 383 } 384 385 /** 386 * Decrements the include level. 387 */ 388 public void decIncludeLevel() { 389 preState.decIncludeLevel(); 390 } 391 392 public void reset(String file) { 53 macroName = name; 54 } 55 56 MacroUndefException() { 57 super(); 58 } 59 60 public void printStackTrace() { 61 System.out.println("Undefined Macro " + macroName); 62 super.printStackTrace(); 63 } 64 65 public String getMessage() { 66 return ("Undefined Macro" + macroName + " " + super.getMessage()); 67 } 68 69 public String getMacroName() { 70 if(null != macroName) 71 return macroName; 72 return ""; 73 } 74 75 } 76 77 78 // ========================================================================== 79 80 /** 81 * Add the specified number of fresh contexts to the pool. 82 * 83 * @param n The number to add. 84 */ 85 protected void fillPool(int n) { 86 preState.fillPool(n); 87 } 88 89 /** 90 * Take a context from the pool, refilling the pool if necessary. 91 * 92 * @return A fresh context. 93 */ 94 protected Context takeFromPool() { 95 return preState.takeFromPool(); 96 } 97 98 /** 99 * Return the specified context to the pool, clearing it along the 100 * way. 101 * 102 * @param c The context to return. 103 */ 104 protected void addToPool(Context c) { 105 preState.addToPool(c); 106 } 107 108 // ========================================================================== 109 110 /** 111 * Push the specified context onto the context stack. 112 * 113 * @param c The context to push. 114 */ 115 protected void push(Context c) { 116 preState.push(c); 117 } 118 119 /** 120 * Pop a context from the context stack. 121 * 122 * @return The top-most context. 123 */ 124 protected Context pop() { 125 return preState.pop(); 126 } 127 128 public void start() { 129 preState.start(); 130 } 131 132 public void commit() { 133 preState.commit(); 134 } 135 136 public void abort() { 137 preState.abort(); 138 } 139 140 // ========================================================================== 141 142 /** Record a typedef storage class specifier. */ 143 public void typedef() { 144 preState.typedef(); 145 } 146 147 /** Record a function parameter list. */ 148 public void parameters() { 149 preState.parameters(); 150 } 151 152 /** Record a function declarator. */ 153 public void functionDeclarator() { 154 preState.functionDeclarator(); 155 } 156 157 /** Enter a new scope. */ 158 public void pushScope() { 159 preState.pushScope(); 160 } 161 162 /** Exit the last scope. */ 163 public void popScope() { 164 preState.popScope(); 165 } 166 167 /** Enter a structure declaration list. */ 168 public void enterStructure() { 169 preState.enterStructure(); 170 } 171 172 /** Exit a structure declaration list. */ 173 public void exitStructure() { 174 preState.exitStructure(); 175 } 176 177 178 179 /** 180 * Determine whether a declaration actually is a declaration. This 181 * method determines whether the sequence 182 * <pre> 183 * DeclarationSpecifiers l:InitializedDeclaratorList? 184 * </pre> 185 * can actually represent a declaration. It assumes that any type 186 * specifier encountered while parsing 187 * <code>DeclarationSpecifiers</code> has been marked through {@link 188 * #typeSpecifier()}. 189 * 190 * @param idl The result of parsing the optional initialized 191 * declarator list. 192 * @return <code>true</code> if the declaration is a declaration. 193 */ 194 public boolean isValid(Node idl) { 195 return preState.isValid(idl); 196 } 197 198 // ========================================================================== 199 200 /** 201 * Record a line marker. Note that string values for the four flags 202 * are interpreted as follows: Any non-null string counts for 203 * <code>true</code>, while null counts for <code>false</code>. 204 * 205 * @see LineMarker 206 * 207 * @param file The file name (without quotes). 208 * @param line The line number. 209 * @param isStartFile The start file flag. 210 * @param isReturnToFile The return to file flag. 211 * @param isSystemHeader The system header flag. 212 * @param isExternC The extern C flag. 213 * @param location The line marker's source location. 214 */ 215 public void lineMarker(String file, int line, String isStartFile, 216 String isReturnToFile, String isSystemHeader, 217 String isExternC, Location location) { 218 preState.lineMarker(file, line, isStartFile, isReturnToFile, isSystemHeader, isExternC, location); 219 } 220 221 /** 222 * Record a pragma. 223 * 224 * @see Pragma 225 * 226 * @param directive The actual directive. 227 * @param location The pragma's source location. 228 */ 229 public void pragma(String directive, Location location) { 230 preState.pragma(directive, location); 231 } 232 233 /** 234 * Record an ident directive. 235 * 236 * @see SourceIdentity 237 * 238 * @param ident The actual identity marker. 239 * @param location The ident directive's source location. 240 */ 241 public void ident(String ident, Location location) { 242 preState.ident(ident, location); 243 } 244 245 /** 246 * Mark the current annotation. This method must be called before 247 * recognizing the nonterminals to be annotated. Furthermore, it 248 * must be called within the context of a stateful production. 249 */ 250 public void mark() { 251 preState.mark(); 252 } 253 254 /** 255 * Annotate the specified node. If any annotations have been 256 * recorded and {@link #mark() marked}, the specified node is 257 * wrapped by those annotations and the outer-most annotation is 258 * returned. Otherwise, the specified node is returned. 259 * 260 * @param node The node. 261 * @return The annotated node. 262 */ 263 public Node annotate(Node node) { 264 return preState.annotate(node); 265 } 266 267 //=========================================================================== 268 /** The C4 State to manage everything 269 * before everything was collecting using C4ParserState 270 * but it's no longer possible 271 * I've added a static field that manages all the state 272 */ 273 C4State preState; 274 275 /** The current Object MacroId */ 276 String omId ; 277 278 /** 279 * Expression Evaluator 280 */ 281 /** Left Value for a If directive */ 282 String leftValue ; 283 284 boolean leftValueSet; 285 286 boolean isLeft = false; 287 288 boolean isRight = false; 289 290 /** Right Value for a If directive */ 291 String rightValue; 292 293 /** To check if the macro currently defined is an attribute */ 294 boolean isAttribute = false; 295 296 /** 297 * Variable that stores the temp value of the IfSection Conditional (if arithmetic included) 298 */ 299 long tmpCondValue = 0; 300 301 boolean tmpCondValueSet = false; 302 303 /* 304 * Variable that contains the name of the macro currently used inside a declaration 305 * only used as a temporary storage for the parser 306 */ 307 private String registeredMacroId; 308 309 /* 310 * Sets the id of the registered macro 311 * 312 */ 313 public String getRegisteredMacroId() { 314 return registeredMacroId; 315 } 316 317 public void setRegisteredMacroId(String registeredMacroId) { 318 this.registeredMacroId = registeredMacroId; 319 } 320 321 /** 322 * Default constructor. 323 */ 324 public C4ParserState() { 325 super(); 326 327 this.preState = C4.getPreState(); 328 } 329 330 /** 331 * Constructor with a macro manager. 332 * 333 * @param macrosManager An instance of the C4MacrosManager. 334 */ 335 public C4ParserState(C4State preState, C4MacrosManager macrosManager) { 336 this(); 337 this.preState = preState; 338 this.preState.setMacrosManager(macrosManager); 339 } 340 341 /** 342 * Sets the include path manager. 343 * 344 * @param manager 345 * An instance of the include path manager. 346 */ 347 public void setIncludePathManager(C4IncludePathManager manager) { 348 preState.setIncludePathManager(manager); 349 } 350 351 /** 352 * Sets the parseTree flag 353 * @param parseTreeFlag 354 * A boolean 355 */ 356 public void setParseTree(boolean parseTree) { 357 preState.setParseTree(parseTree); 358 } 359 360 /** 361 * Sets the parseTree flag 362 * @param parseTreeFlag 363 * A boolean 364 */ 365 public boolean getParseTree() { 366 return preState.getParseTree(); 367 } 368 369 /** 370 * Returns the include path manager. 371 * 372 * @return The include path manager. 373 */ 374 public C4IncludePathManager getIncludePathManager() { 375 return preState.getIncludePathManager(); 376 } 377 378 /** 379 * Increments the include level. 380 */ 381 public void incIncludeLevel() { 382 preState.incIncludeLevel(); 383 } 384 385 /** 386 * Decrements the include level. 387 */ 388 public void decIncludeLevel() { 389 preState.decIncludeLevel(); 390 } 391 392 public void reset(String file) { 393 if(preState == null) { 394 System.out.println("preState is null"); 395 System.exit(-1); 396 397 } 398 393 399 preState.reset(file); 394 400 } … … 2402 2408 } 2403 2409 2404 /** 2405 * Resets the PreState shared by all the C4ParserState 2406 * Required because of the wrapper 2407 */ 2408 public static void resetPreState() { 2409 preState = new C4State(); 2410 } 2410 2411 2411 } 2412 2412 // vim: set sts=2 sw=2 ts=2 et : -
trunk/cpp_analysis/src/xtc/lang/c4/CPPAnalyzer.java
r198 r199 907 907 908 908 /** 909 * Check that the tag declaration is not located within a parameter910 * list. If the declaration is located within a parameter list, this911 * method prints the appropriate warning.912 *913 * @param node914 * The node.915 * @param kind916 * The kind of tag.917 */918 // private void checkNotParameter(Node node, String kind) {919 // if (TMP_SCOPE.equals(table.current().getName())) {920 // final String tag = node.getString(1);921 // final String msg;922 // if (null == tag) {923 // msg = "anonymous " + kind924 // + " declared inside parameter list";925 // } else {926 // msg = "'" + kind + " " + tag927 // + "' declared inside parameter list";928 // }929 //930 // // runtime.warning(msg, node);931 // }932 // }933 934 /**935 909 * Determine whether the specifiers contain the specified attribute. 936 910 * … … 2094 2068 public ArrayList<String> currentPrimaryId; 2095 2069 2096 // public ArrayList<String> primaryIdsBlock;2097 2070 /** 2098 2071 * List of all the symbols used in the whole function … … 2100 2073 public ArrayList<String> primaryIdsGlobal; 2101 2074 2102 // public ArrayList<ArrayList<String>> primaryIdentifiersAfter;2103 2075 /** Mapping of the current arguments with prototype. */ 2104 2076 public Map<String, ArrayList<String>> functionParameters; … … 2174 2146 2175 2147 /** The flag to know whether we are in a Right-Hand Side context */ 2176 private boolean inside Test;2148 private boolean insideString; 2177 2149 2178 2150 /** The flag to know whether we are in a leftHandSide context */ … … 2208 2180 ArrayList<GNode> loopsNode; 2209 2181 2182 /** Stack of the currently nested parameters (function and macro parameters) */ 2183 ArrayList<GNode> parameterNode; 2184 2210 2185 /** Total Number of Macros */ 2211 2186 int macroNumber; … … 2739 2714 // Dispatching the top level 2740 2715 dispatch(unit); 2741 2742 2716 2743 2717 // Extraction 2744 2718 if (null != extract && atTopLevelFile()) { 2745 2719 ArrayList<String> headersToExtract = new ArrayList<String>(); 2746 2720 2747 2721 //We look if headers are only referred inside what is extracted 2748 2722 for(String header: insideExtractedHeaders) { … … 2756 2730 2757 2731 tmpExtractor.extract(); 2758 2759 System.out.println("INSIDE " + insideExtractedHeaders); 2732 2760 2733 } 2761 2734 … … 3843 3816 ifsNode = new ArrayList<GNode>(); 3844 3817 loopsNode = new ArrayList<GNode>(); 3818 parameterNode = new ArrayList<GNode>(); 3845 3819 toExtract = new ArrayList<C4Extractable>(); 3846 3820 functionDefinitions = new HashMap<String, GNode>(); … … 4103 4077 4104 4078 @SuppressWarnings( { "unused", "unchecked" }) 4105 private HashMap<String, Boolean> isMovableAfter Conditionally(4079 private HashMap<String, Boolean> isMovableAfterFuncCall( 4106 4080 final GNode functionCall, String condFuncName, 4107 4081 final GNode functionDefinition, final Node args, … … 4204 4178 dispatch(n.getGeneric(5)); 4205 4179 isMovableTmpMap.put("FunctionDefinition:" + n.getLocation(), 4206 new Boolean(isMovable && inFuncBody));4180 new Boolean(isMovable && shouldBeReportedAfter())); 4207 4181 return isMovableTmpMap; 4208 4182 … … 4230 4204 // after this return 4231 4205 isMovableTmpMap.put("Return:" + n.getLocation(), new Boolean( 4232 isMovable && inFuncBody));4206 isMovable && shouldBeReportedAfter())); 4233 4207 } 4234 4208 … … 4246 4220 4247 4221 /** 4248 * Analysis to know whether a Node is modified after a MacroBased4 4249 * 4222 * Analysis to know whether a Node is modified after a MacroReference 4250 4223 */ 4251 4224 @SuppressWarnings( { "unused", "unchecked" }) … … 4261 4234 10); 4262 4235 // To know whether we are in the right context 4263 4264 4236 boolean flag = false; 4265 4237 … … 4300 4272 isMovableTmpMap.put( 4301 4273 "FunctionDefinition:" + n.getLocation(), 4302 new Boolean(isMovable && inFuncBody));4274 new Boolean(isMovable && shouldBeReportedAfter())); 4303 4275 4304 4276 return isMovableTmpMap; 4305 4277 4306 4278 } 4279 4280 //We define these methods to avoid dispatching the definition of the macro 4281 public void visitMacroFunctionExpressionWrapper(GNode n) { 4282 dispatch(n.getGeneric(0)); 4283 } 4284 4285 public void visitMacroBasedDeclaration(GNode n) { 4286 dispatch(n.getGeneric(0)); 4287 } 4288 4289 public void visitFunctionMacroCompoundStatement(GNode n) { 4290 dispatch(n.getGeneric(0)); 4291 } 4292 4293 // 4307 4294 4308 4295 public void visitIfDef(GNode n) { … … 4314 4301 flag = true; 4315 4302 } 4303 dispatch(n.getGeneric(2)); 4316 4304 } 4317 4305 … … 4320 4308 flag = true; 4321 4309 } 4310 dispatch(n.getGeneric(3)); 4322 4311 } 4323 4312 … … 4326 4315 flag = true; 4327 4316 } 4317 dispatch(n.getGeneric(4)); 4328 4318 } 4329 4319 … … 4332 4322 flag = true; 4333 4323 } 4324 dispatch(n.getGeneric(1)); 4325 //Remember that this node may have a compound statement 4326 //in the last position 4327 if(null != n.getGeneric(n.size()-1)) { 4328 dispatch(n.getGeneric(n.size()-1)); 4329 } 4330 4331 4334 4332 } 4335 4333 … … 4338 4336 flag = true; 4339 4337 } 4338 4339 dispatch(n.getGeneric(n.size()-1)); 4340 4340 } 4341 4341 … … 4369 4369 // this return 4370 4370 isMovableTmpMap.put("Return:" + n.getLocation(), 4371 new Boolean(isMovable && inFuncBody));4371 new Boolean(isMovable && shouldBeReportedAfter())); 4372 4372 } 4373 4373 … … 4400 4400 } 4401 4401 4402 4402 4403 public void visitBranchStatements(GNode n) { 4403 4404 final int size = n.size(); … … 4416 4417 dispatch(n.getGeneric(5)); 4417 4418 isMovableTmpMap.put("FunctionDefinition:" + n.getLocation(), 4418 new Boolean(isMovable ));4419 new Boolean(isMovable && shouldBeReportedAfter())); 4419 4420 return isMovableTmpMap; 4420 4421 … … 4450 4451 // this return 4451 4452 isMovableTmpMap.put("Return:" + n.getLocation(), new Boolean( 4452 isMovable ));4453 isMovable && shouldBeReportedAfter())); 4453 4454 } 4454 4455 … … 4482 4483 */ 4483 4484 @SuppressWarnings("unused") 4484 private boolean isMovableBefore Conditionally(String condFuncName,4485 private boolean isMovableBeforeFuncCall(String condFuncName, 4485 4486 final GNode functionDefinition, final Node args) { 4486 4487 setCondMovable(true); … … 4585 4586 isMovable = (!primaryIdsGlobal.contains(id)) 4586 4587 && (!pointedParams.contains(id)); // 4587 if (1 <= DEBUG) { 4588 System.out.println("Primary Ids Global " + primaryIdsGlobal); 4589 System.out.println("Pointed Parmas " + pointedParams); 4590 System.out.println("Checking this Id " + id); 4591 System.out.println("Is definedlocally " + id + " " 4592 + table.current().lookup(id)); 4593 System.out.println("TABLE " + table.current().getName() 4594 + " parent " + table.current().getParent().getName()); 4595 System.out.println("ID: " + id + " is Movable ? " + isMovable 4596 + " " + primaryIdsGlobal); 4597 } 4598 if (!isMovable) 4588 4589 if (!isMovable || !shouldBeReportedBefore()) 4599 4590 break; 4600 4591 } … … 8166 8157 8167 8158 /** 8168 * Visit the specified function call. MacroFunction Calls are considered as 8169 * Function Calls 8159 * Visit the specified function call. 8170 8160 * */ 8171 8161 public Type visitFunctionCall(GNode n) { 8172 8162 functionCall = true; 8173 8163 final Node n1 = n.getGeneric(0); 8174 // The second child obtained by n.getGeneric(2) is an optional if 8164 8165 // The second child obtained by n.getGeneric(1) is an optional if 8175 8166 // section... 8176 8167 final Node n2 = n.getGeneric(2); … … 8183 8174 boolean convertibleAfter; 8184 8175 boolean inside = false; 8185 8176 8186 8177 Type t1; 8187 8178 … … 8265 8256 } 8266 8257 } else { 8258 8267 8259 t1 = (Type) dispatch(n1); 8268 8260 } 8269 8261 8270 8262 Type result; 8271 if (!GNode.cast(n1).hasName("FunctionMacro")) { // Regular Processing 8272 if (t1 == null) 8273 return ErrorT.TYPE; 8274 8275 final Type r1 = c().pointerize(t1); 8276 @SuppressWarnings("unchecked") 8277 final List<Type> args = (List<Type>) dispatch(n2); 8278 if (r1.isError()) { 8279 result = ErrorT.TYPE; 8280 8281 } else if (r1.isPointer() 8282 && r1.toPointer().getType().hasTag(Tag.FUNCTION)) { 8283 8284 final FunctionT function = r1.toPointer().getType().resolve() 8285 .toFunction(); 8286 8287 final List<Type> parameters = function.getParameters(); 8288 8289 // PARAMETERs recording 8290 if (1 <= DEBUG) { 8291 System.out.println("#######################" 8292 + "\nFUNCTION " 8293 + function 8294 + " name " 8295 + ((FunctionT) r1.toPointer().getType()) 8296 .getParameters() + "\nARGS " + args 8297 + " N2 " + n2 + "\nTABLE " 8298 + table.current().symbols + "\nPARAMETERS " 8299 + parameters + "\n#######################\n"); 8300 } 8301 8302 // If the function has a prototype, check the types. 8303 if (!function.hasAttribute(Constants.ATT_STYLE_OLD)) { 8304 final int size1 = parameters.size(); 8305 final int size2 = (null == args) ? 0 : args.size(); 8306 final int min = Math.min(size1, size2); 8307 final String name = toFunctionName(n1); 8308 8309 for (int i = 0; i < min; i++) { 8310 String desc = "passing argument " + (i + 1); 8311 if (null != name) 8312 desc = desc + " to '" + name + "'"; 8313 processAssignment(false, desc, n, parameters.get(i), 8314 args.get(i)); 8315 } 8316 8317 } 8318 for (Type parameter : parameters) { 8319 if (parameter.isPointer()) { 8320 pointedParams.add(parameter.getName()); 8321 } 8322 } 8323 result = function.getResult(); 8324 8325 } else { 8326 result = ErrorT.TYPE; 8327 } 8263 //if (!GNode.cast(n1).hasName("FunctionMacro")) { // Regular Processing 8264 if (t1 == null) 8265 return ErrorT.TYPE; 8266 8267 final Type r1 = c().pointerize(t1); 8268 //Dispatch of the parameters 8269 parameterNode.add((GNode) n2); 8270 8271 @SuppressWarnings("unchecked") 8272 final List<Type> args = (List<Type>) dispatch(n2); 8273 8274 parameterNode.remove(parameterNode.size()-1); 8275 8276 8277 8278 if (r1.isError()) { 8279 result = ErrorT.TYPE; 8280 8281 } else if (r1.isPointer() 8282 && r1.toPointer().getType().hasTag(Tag.FUNCTION)) { 8283 8284 final FunctionT function = r1.toPointer().getType().resolve() 8285 .toFunction(); 8286 8287 final List<Type> parameters = function.getParameters(); 8288 8289 // PARAMETERs recording 8290 if (1 <= DEBUG) { 8291 System.out.println("#######################" 8292 + "\nFUNCTION " 8293 + function 8294 + " name " 8295 + ((FunctionT) r1.toPointer().getType()) 8296 .getParameters() + "\nARGS " + args 8297 + " N2 " + n2 + "\nTABLE " 8298 + table.current().symbols + "\nPARAMETERS " 8299 + parameters + "\n#######################\n"); 8300 } 8301 8302 // If the function has a prototype, check the types. 8303 if (!function.hasAttribute(Constants.ATT_STYLE_OLD)) { 8304 final int size1 = parameters.size(); 8305 final int size2 = (null == args) ? 0 : args.size(); 8306 final int min = Math.min(size1, size2); 8307 final String name = toFunctionName(n1); 8308 8309 for (int i = 0; i < min; i++) { 8310 String desc = "passing argument " + (i + 1); 8311 if (null != name) 8312 desc = desc + " to '" + name + "'"; 8313 processAssignment(false, desc, n, parameters.get(i), 8314 args.get(i)); 8315 } 8316 8317 } 8318 8319 for (Type parameter : parameters) { 8320 if (parameter.isPointer()) { 8321 pointedParams.add(parameter.getName()); 8322 } 8323 } 8324 result = function.getResult(); 8325 8328 8326 } else { 8327 result = ErrorT.TYPE; 8328 } 8329 /*} else { 8329 8330 // Function MACRO 8330 8331 result = VoidT.TYPE; 8331 } 8332 }*/ 8332 8333 8333 8334 // Analysis 8334 8335 8335 8336 // We log only if the function is conditionally defined. 8336 String name = toFunctionName(n1);8337 String functionName = toFunctionName(n1); 8337 8338 8338 8339 //We may not be able to have the definition of the function called 8339 8340 //when a gcc builtin_ function is called 8340 8341 //like builtin_constant_p 8341 if(functionDefinitions.containsKey( name))8342 funcDefLoc = ((GNode) functionDefinitions.get( name)).getLocation();8342 if(functionDefinitions.containsKey(functionName)) 8343 funcDefLoc = ((GNode) functionDefinitions.get(functionName)).getLocation(); 8343 8344 else 8344 8345 funcDefLoc = null; … … 8347 8348 8348 8349 8349 8350 if (conditionalDefs.containsKey(name)) { 8351 // This Function is conditionally defined 8352 if (1 <= DEBUG) 8353 System.out.println("Function " + name 8354 + " is conditionally defined with " 8355 + conditionalDefs.get(name)); 8356 8357 8358 // Location Logging 8359 if (logLocation) { 8360 loclogger.insertNewLocation(conditionalDefs.get(name), loc, 8361 isInFunction(), isInFunctionBody()); 8362 8363 } 8364 // 8365 8366 // Extraction 8367 if (null != extract && atTopLevelFile()) { 8368 //We look if the function is defined according to the 8369 //configuration option we are currently looking 8370 if (conditionalDefs.get(name).contains(extract)) { 8371 8372 //TODO change to be defined before or after according to the real nature of the extraction 8373 toExtract.add(new C4Extractable(functionDefinitionName, 8374 funcDef, n, "before")); 8375 8376 //For the extraction of header, we look from where stems the 8377 //function 8378 8379 if(inHeaderFile(((GNode) functionDefinitions.get(name)))) { 8380 if (!insideExtractedHeaders.contains(funcDefLoc.file)) 8381 inside = true; 8382 } 8383 8384 8385 } 8386 } 8387 8388 // Logging 8389 // if(!alreadyConsideredFunctionCall() &&) { 8390 // CONVERTIBLE BEFORE 8391 convertibleBefore = isConvertibleBefore(n); 8392 // CONVERTIBLE AFTER 8393 convertibleAfter = isConvertibleAfter(n); 8394 // MOVABLE BEFORE 8395 if ((!isInFunctionBody()) || (returnSeen || rightHandSide) 8396 || (ifsNode.size() > 0) || (loopsNode.size() > 0)) { 8397 movableBefore = false; 8398 } else { 8399 movableBefore = isMovableBeforeConditionally(name, 8400 (GNode) functionDefinitions.get(name), n2); 8401 } 8402 // MOVABLE AFTER 8403 movableAfter = isMovableAfterConditionally(n, name, 8404 (GNode) functionDefinitions.get(name), n2, 8405 isInFunctionBody()); 8406 8407 ArrayList<String> condDefs = conditionalDefs.get(name); 8408 8409 8410 8411 if (conditionalDefs.containsKey(name)) { 8412 8413 c4log.logWrapper("Function", name, funcDefLoc, loc, 8414 conditionStack, markedConfigOptionsStack, condDefs, 8415 movableBefore, movableAfter, convertibleBefore, 8416 convertibleAfter); 8417 clogger.setConvertibleBeforeFuncCall(conditionalDefs.get(name), 8418 loc, convertibleBefore); 8419 clogger.setConvertibleAfterFuncCall(conditionalDefs.get(name), 8420 loc, convertibleAfter); 8421 8422 } 8423 // END OF LOGGING 8424 // END OF ANALYSIS REPORT 8425 8426 8427 8428 8429 } 8430 8350 //We look if we have already considered exactly the same function call 8351 //In order to avoid recounting several times the same call in different 8352 //contexts that is exactly the same 8353 if ((!atTopLevelFile()) && (logger.alreadyConsideredFuncCall(funcDef, functionName, loc.toString()))) { 8354 //System.out.println("Name of the functionAlreadyConsidered " + functionName + " Loc: " + loc.toString()); 8355 ////System.out.println("KIND " + n.getName() + " N1 " + n1); 8356 ; 8357 } else { 8358 8359 if (conditionalDefs.containsKey(functionName)) { 8360 // This Function is conditionally defined 8361 if (1 <= DEBUG) 8362 System.out.println("Function " + functionName 8363 + " is conditionally defined with " 8364 + conditionalDefs.get(functionName)); 8365 8366 8367 // Location Logging 8368 if (logLocation) { 8369 loclogger.insertNewLocation(conditionalDefs.get(functionName), loc, 8370 isInFunction(), isInFunctionBody()); 8371 8372 } 8373 // 8374 8375 // Extraction 8376 if (null != extract && atTopLevelFile()) { 8377 //We look if the function is defined according to the 8378 //configuration option we are currently looking 8379 if (conditionalDefs.get(functionName).contains(extract)) { 8380 8381 //TODO change to be defined before or after according to the real nature of the extraction 8382 toExtract.add(new C4Extractable(functionDefinitionName, 8383 funcDef, n, "before")); 8384 8385 //For the extraction of header, we look from where stems the 8386 //function 8387 8388 if(inHeaderFile(((GNode) functionDefinitions.get(functionName)))) { 8389 if (!insideExtractedHeaders.contains(funcDefLoc.file)) 8390 inside = true; 8391 } 8392 8393 8394 } 8395 } 8396 8397 // Logging 8398 // if(!alreadyConsideredFunctionCall() &&) { 8399 // CONVERTIBLE BEFORE 8400 convertibleBefore = isConvertibleBefore(n); 8401 // CONVERTIBLE AFTER 8402 convertibleAfter = isConvertibleAfter(n); 8403 // MOVABLE BEFORE 8404 if (!shouldBeReportedBefore()) { 8405 movableBefore = false; 8406 } else { 8407 movableBefore = isMovableBeforeFuncCall(functionName, 8408 (GNode) functionDefinitions.get(functionName), n2); 8409 } 8410 // MOVABLE AFTER 8411 movableAfter = isMovableAfterFuncCall(n, functionName, 8412 (GNode) functionDefinitions.get(functionName), n2, 8413 isInFunctionBody()); 8414 8415 ArrayList<String> condDefs = conditionalDefs.get(functionName); 8416 8417 8418 8419 if (conditionalDefs.containsKey(functionName)) { 8420 8421 c4log.logWrapper("Function", functionName, funcDefLoc, loc, 8422 conditionStack, markedConfigOptionsStack, condDefs, 8423 movableBefore, movableAfter, convertibleBefore, 8424 convertibleAfter); 8425 clogger.setConvertibleBeforeFuncCall(conditionalDefs.get(functionName), 8426 loc, convertibleBefore); 8427 clogger.setConvertibleAfterFuncCall(conditionalDefs.get(functionName), 8428 loc, convertibleAfter); 8429 8430 } 8431 // END OF LOGGING 8432 // END OF ANALYSIS REPORT 8433 8434 8435 8436 8437 } 8438 } 8431 8439 functionCall = false; 8432 8440 8433 8441 //Header extraction 8434 if(functionDefinitions.containsKey(name)){ 8435 if(inHeaderFile(functionDefinitions.get(name))) 8436 if(null != extract) { 8437 if(funcDefLoc != null) 8438 insertExtractHeader(funcDefLoc.file, inside); 8439 } 8440 } 8442 if(functionDefinitions.containsKey(functionName)){ 8443 if(inHeaderFile(functionDefinitions.get(functionName))) 8444 if(null != extract) { 8445 if(funcDefLoc != null) 8446 insertExtractHeader(funcDefLoc.file, inside); 8447 } 8448 } 8449 8441 8450 mark(n, result); 8442 8451 return result; … … 8639 8648 /** Visit the specified if else statement. */ 8640 8649 public void visitIfElseStatement(GNode n) { 8641 final Node n1 = n.getGeneric(0); 8642 Type t1 = (Type) dispatch(n1); 8650 final Node n1; 8651 Type t1 ; 8652 8653 ifsNode.add(n); 8654 8655 n1 = n.getGeneric(0); 8656 t1 = (Type) dispatch(n1); 8643 8657 8644 8658 if (t1 != null) // MACRO 8645 8659 ensureScalar(n1, c().pointerize(t1)); 8646 8660 8647 ifsNode.add(n);8648 8661 dispatch(n.getGeneric(1)); 8649 8662 dispatch(n.getGeneric(2)); … … 8934 8947 /** Visit the specified if else statement. */ 8935 8948 public void visitIfStatement(GNode n) { 8936 final Node n1 = n.getGeneric(0); 8937 8938 insideTest = true; 8939 Type t1 = (Type) dispatch(n1); 8940 insideTest = false; 8949 final Node n1; 8950 Type t1; 8951 8952 // we increment the if counter for the analysis 8953 ifsNode.add(n); 8954 8955 n1 = n.getGeneric(0); 8956 t1 = (Type) dispatch(n1); 8941 8957 8942 8958 if (t1 != null) // Macro 8943 8959 ensureScalar(n1, c().pointerize(t1)); 8944 8960 8945 // we increment the if counter for the analysis8946 ifsNode.add(n);8947 8961 dispatch(n.getGeneric(1)); 8948 8962 ifsNode.remove(ifsNode.size() - 1); … … 9160 9174 public void macroFunctionVisitor(GNode n, int parameterPosition, 9161 9175 int macroNamePosition, GNode macroDefinition) { 9162 Node parameters = n.getGeneric(parameterPosition) != null ? n9176 GNode parameters = n.getGeneric(parameterPosition) != null ? n 9163 9177 .getGeneric(parameterPosition) : null; // FunctionMacroCallParametersList 9164 9178 String macroName = n.getString(macroNamePosition); 9165 9179 9166 9180 // Node macroDefinition = retrieveMacroAnalysis(macroName); 9167 9168 9181 Location macroDefLoc = macroDefinition.getLocation(); 9169 9182 … … 9177 9190 parameters); 9178 9191 9192 //We're dispatching the parameters, because macros can be given as parameters 9193 9194 //If we're inside a macro the parameters must be reported 9195 // MACRO_FUNC(MACRO_OBJ) 9196 // If MACRO_OBJ is defined under the same condition as MACRO_FUNC, 9197 // we do not want to pollute the result for the call to MACRO_FUNC that can remain movable 9198 // in the general case 9199 9200 parameterNode.add(parameters); 9201 9202 dispatch(parameters); 9203 9204 parameterNode.remove(parameterNode.size()-1); 9205 9206 9179 9207 // Incrementing the total number of Macros 9180 9208 macroNumber++; … … 9190 9218 } 9191 9219 9220 } 9221 9222 /** 9223 * Actual implementation of the visitor for macro function calls 9224 * In particular cases, the macro reference can contain a compound statement (a block). 9225 * This is generally the case when the macro replaces the first line of an if or a loop 9226 * @param n The node to visit 9227 * @param parameterPosition The position of the parameters among the children 9228 * @param macroNamePosition The position of the name of the macro called in the children 9229 * @param macroDefinition The definition of the referenced macro 9230 * @param n The compound statement following that must be dispatched 9231 */ 9232 public void macroFunctionVisitor(GNode n, int parameterPosition, 9233 int macroNamePosition, GNode macroDefinition, GNode compound) { 9234 //We call the regular macroFunction Visitor 9235 macroFunctionVisitor(n, parameterPosition, macroNamePosition, macroDefinition); 9236 //and then we dispatch the following Compound statement 9237 if(null != compound) {//Should not happen but we test anyway 9238 dispatch(compound); 9239 } 9192 9240 } 9193 9241 … … 9200 9248 * The node visited 9201 9249 */ 9250 @SuppressWarnings("unused") 9202 9251 public void visitFunctionMacroCompoundStatement(GNode n) { 9203 9252 final GNode macroDefinition = n.getGeneric(1); … … 9205 9254 new Visitor() { 9206 9255 public void visitFunctionMacroCallStatement(GNode n) { 9207 macroFunctionVisitor(n, 1, 0, macroDefinition );9256 macroFunctionVisitor(n, 1, 0, macroDefinition, n.getGeneric(n.size()-1)); 9208 9257 } 9209 9258 }.dispatch(n.getGeneric(0)); … … 9213 9262 * MacroBased6 are only declarations, not sure we should consider them. 9214 9263 */ 9215 9264 @SuppressWarnings("unused") 9216 9265 public void visitMacroBasedDeclaration(GNode n) { 9217 9266 final GNode macroDef = n.getGeneric(1); … … 9235 9284 9236 9285 }.dispatch(n.getGeneric(0)); 9237 }9238 9239 /**9240 * Visiting a MacroBased4 declaration. MacroFunctions called are considered9241 * as MacroBased49242 *9243 * @param n9244 * The node actually visited9245 */9246 public void visitMacroBased4(GNode n) {9247 System.out.println("SHOULD NOT HAPPEN " + n.getLocation());9248 // macroFunctionVisitor(n,2,1);9249 9286 } 9250 9287 … … 9254 9291 * @param n 9255 9292 */ 9293 @SuppressWarnings("unused") 9256 9294 public void visitMacroFunctionExpressionWrapper(GNode n) { 9257 9295 final GNode macroDefinition = n.getGeneric(1); … … 9315 9353 // Or this is in the right hand side of an assignement 9316 9354 9317 if ((returnSeen || rightHandSide) || (ifsNode.size() > 0) 9318 || (loopsNode.size() > 0) || !inFuncBody) { 9355 if (!shouldBeReportedBefore()) { 9319 9356 // if((returnSeen) || (rightHandSide)){ 9320 9357 movableBefore = false; … … 9967 10004 boolean wide = false; 9968 10005 for (Object o : n) { 9969 10006 Node tmpNode = null; 9970 10007 // TODO Look at that 9971 10008 if (o instanceof Node) { 9972 o = ((Node) o).strip(); 9973 } 9974 9975 if (o.toString().startsWith("MacroIdentifierConstant")) { 9976 buf.append("MacroParameter"); 9977 } else if (o.toString().startsWith("MacroReference")) { 9978 buf.append("MacroReference"); 9979 dispatch((Node) o); 9980 } else { 10009 tmpNode = ((Node) o).strip(); 10010 } 10011 if(null != tmpNode) { 10012 if (o.toString().startsWith("MacroIdentifierConstant")) { 10013 buf.append("MacroParameter"); 10014 } else if (o.toString().startsWith("MacroReference")) { 10015 buf.append("MacroReference"); 10016 10017 insideString = true; 10018 dispatch((Node) o); 10019 insideString = false; 10020 10021 } 10022 } 10023 else { 9981 10024 String s = Token.cast(o); 9982 10025 … … 10231 10274 /** Visit the specified while statement. */ 10232 10275 public void visitWhileStatement(GNode n) { 10233 final Node n1 = n.getGeneric(0); 10234 10235 insideTest = true; 10236 final Type t1 = (Type) dispatch(n1); 10237 insideTest = false; 10276 final Node n1; 10277 final Type t1 ; 10278 10279 loopsNode.add(n); 10280 loops.add(Boolean.TRUE); 10281 10282 n1 = n.getGeneric(0); 10283 t1 = (Type) dispatch(n1); 10238 10284 10239 10285 if (t1 != null) 10240 10286 ensureScalar(n1, c().pointerize(t1)); 10241 10287 10242 loopsNode.add(n); 10243 loops.add(Boolean.TRUE); 10288 10244 10289 dispatch(n.getGeneric(1)); 10245 10290 loops.remove(loops.size() - 1); … … 10247 10292 } 10248 10293 10294 /** 10295 * Tells whether or not the result of the BEFORE analysis should be reported 10296 * or not (if not, <code>false</code> should be reported) 10297 */ 10298 private boolean shouldBeReportedBefore() { 10299 boolean result = false; 10300 10301 result = (!((returnSeen || rightHandSide || insideString) || (ifsNode.size() > 0) 10302 || (loopsNode.size() > 0) || !isInFunctionBody())) || (parameterNode.size() > 0); 10303 10304 //Right now if we're inside parameterNode, we report 10305 10306 return result; 10307 } 10308 10309 10310 /** 10311 * Tells whether or not the result of the AFTER analysis should be reported 10312 * or not (if not, <code>false</code> should be reported) 10313 */ 10314 private boolean shouldBeReportedAfter() { 10315 boolean result = false; 10316 10317 result = (!((rightHandSide || insideString) || (ifsNode.size() > 0) 10318 || (loopsNode.size() > 0) || !isInFunctionBody())) || (parameterNode.size() > 0); 10319 10320 //Right now if we're inside parameterNode, we report 10321 10322 return result; 10323 } 10324 10249 10325 } -
trunk/cpp_analysis/src/xtc/lang/c4/ConvertibleLogger.java
r160 r199 109 109 */ 110 110 public void initConvertible(ArrayList<String> configOptions) { 111 dbHandler.initConvertible(configOptions);111 DBHandler.initConvertible(configOptions); 112 112 } 113 113 -
trunk/cpp_analysis/src/xtc/lang/c4/DBHandler.java
r197 r199 13 13 import java.util.Iterator; 14 14 15 import java.util.concurrent.locks.Lock; 16 import java.util.concurrent.locks.ReentrantLock; 17 15 18 import com.sun.tools.javac.util.Pair; 16 19 … … 26 29 */ 27 30 public class DBHandler { 28 private class DBHandlerException extends Exception { 29 30 /** 31 * 32 */ 33 private static final long serialVersionUID = 2012470201229606208L; 34 35 public DBHandlerException() { 36 super(); 37 } 38 39 public DBHandlerException(String reason) { 40 super(reason); 41 } 42 43 } 44 45 /** 46 * Constants that are used to specify which column of the table to update 47 */ 48 public static final int BIFSECTION = 0; 49 public static final int BMACROREF = 1; 50 public static final int BFUNCCALL = 2; 51 public static final int AIFSECTION = 3; 52 public static final int AMACROREF = 4; 53 public static final int AFUNCCALL = 5; 54 55 /** Connection to the current database **/ 56 Connection conn; 57 /** A PreparedStatement to insert new trees in the database **/ 58 PreparedStatement newTree; 59 /** A Prepared to select nodes with the same hash signature **/ 60 PreparedStatement query; 61 /** A PreparedStatement to insert new trees in the database **/ 62 PreparedStatement newMacro; 63 /** A Prepared to find whether the macrodefinition associated with a particular location remains the same 64 * with the same hash signature **/ 65 PreparedStatement queryMacro; 66 /** A PreparedStatement to insert new funcCall in the database **/ 67 PreparedStatement newFuncCall; 68 /** A Prepared to find whether the function definition associated with a particular location remains the same 69 * with the same hash signature **/ 70 PreparedStatement queryFuncCall; 71 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 72 PreparedStatement convUpdateBeforeSection; 73 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 74 PreparedStatement convUpdateBeforeMacroRef; 75 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 76 PreparedStatement convUpdateBeforeFuncCall; 77 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 78 PreparedStatement convUpdateAfterSection; 79 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 80 PreparedStatement convUpdateAfterMacroRef; 81 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 82 PreparedStatement convUpdateAfterFuncCall; 83 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 84 PreparedStatement convSelectBeforeSection; 85 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 86 PreparedStatement convSelectBeforeMacroRef; 87 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 88 PreparedStatement convSelectBeforeFuncCall; 89 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 90 PreparedStatement convSelectAfterSection; 91 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 92 PreparedStatement convSelectAfterMacroRef; 93 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 94 PreparedStatement convSelectAfterFuncCall; 95 /** A Prepared to insert the value of the convertibility of a config option **/ 96 PreparedStatement convIns; 97 /** A Prepared to insert the value of the convertibility of a config option **/ 98 PreparedStatement convLocIns; 99 /** A Prepared to request the value of the convertibility of a config option **/ 100 PreparedStatement convLocSel; 101 /** A Prepared to test whether a config option for IfSections has already been included **/ 102 PreparedStatement convTest; 103 /** A Prepared to insert a new location for one particular configuration option **/ 104 PreparedStatement locIns; 105 /** A Prepared to insert a new record with the location of an IfSection and whether or not there is a return 106 * inside this IfSection 107 */ 108 PreparedStatement returnInIfSection; 109 /** An anonymous Statement to execute arbitrary queries **/ 110 Statement stmt; 111 112 private String buildUpdateRequest(String column) { 113 return "UPDATE convertibleConfigOptions SET " + column +"=? WHERE configOption=?;"; 114 } 115 116 private String buildSelectQuery(String column) { 117 return "SELECT * FROM convertibleConfigOptions WHERE " + column + "=? AND configOption=?;"; 118 } 119 120 public DBHandler() { 121 conn = this.connect(); 122 123 try{ 124 stmt = conn.createStatement(); 125 //We set the pragma synchronous OFF 126 //The Database may be corrupted if the computer loses power or if the system crashes 127 //We don't really care 128 stmt.execute("PRAGMA synchronous = OFF;"); 129 130 //Table to avoid recounting the same header twice when analyzing 131 stmt.executeUpdate("create table if not exists treesMD5 (id INTEGER PRIMARY KEY ASC, hash BINARY[16], node TEXT); "); 132 newTree = conn.prepareStatement( 133 "insert into treesMD5(hash, node) values(?, ?);"); 134 query = conn.prepareStatement("select node from treesMD5 where hash==? ;"); 135 136 //Table to avoid recounting the same macro twice when analyzing 137 //Keeps track of the macroDefinition signature associated with one refLocation 138 stmt.executeUpdate("create table if not exists macrosMD5 (id INTEGER PRIMARY KEY ASC, " + 139 "hashDef BINARY[16], macroName TEXT, refLocation TEXT); "); 140 newMacro = conn.prepareStatement( 141 "insert into macrosMD5(hashDef, macroName, refLocation) values(?, ?, ?);"); 142 queryMacro = conn.prepareStatement("select macroName from macrosMD5 where (hashDef==? AND refLocation==?) ;"); 143 144 //Table to avoid recounting the same funcCall twice when analyzing 145 //Keeps track of the macroDefinition signature associated with one refLocation 146 stmt.executeUpdate("create table if not exists funcCallMD5 (id INTEGER PRIMARY KEY ASC, " + 147 "hashDef BINARY[16], funcName TEXT, callLocation TEXT); "); 148 newFuncCall = conn.prepareStatement( 149 "insert into funcCallMD5 (hashDef, funcName, callLocation) values(?, ?, ?);"); 150 queryFuncCall= conn.prepareStatement("select funcName from funcCallMD5 where (hashDef==? AND callLocation==?) ;"); 151 152 153 //Table to collect convertible information per location with CONFIG_OPTION 154 stmt.executeUpdate("create table if not exists convertibleLocation (id INTEGER PRIMARY KEY ASC, configOption TEXT, kind TEXT " + 155 ", location TEXT, convertible BOOLEAN);"); 156 157 //CONVERTIBLE LOCATION 158 convLocIns = conn.prepareStatement("INSERT INTO convertibleLocation(configOption, kind, location, convertible) VALUES (?, ?, ?, ?);"); 159 160 //CONVERTIBLE LOCATION REQUEST 161 convLocSel = conn.prepareStatement("SELECT * FROM convertibleLocation WHERE (configOption=?) AND (kind=?) AND (location=?) and (convertible=?)"); 162 163 164 //Table to collect convertible information per config option 165 stmt.executeUpdate("create table if not exists convertibleConfigOptions (configOption TEXT, convertibleBeforeSection SHORT INTEGER, " + 166 "convertibleBeforeMacroRef SHORT INTEGER, convertibleBeforeFuncCall SHORT INTEGER, " + 167 "convertibleAfterSection SHORT INTEGER, convertibleAfterMacroRef SHORT INTEGER, convertibleAfterFuncCall SHORT INTEGER);"); 168 169 convIns = conn.prepareStatement("INSERT INTO convertibleConfigOptions VALUES (?, ?, ?, ?, ?, ?, ?);"); 170 171 //BEFORE 172 convUpdateBeforeSection = conn.prepareStatement(buildUpdateRequest("convertibleBeforeSection")); 173 convUpdateBeforeMacroRef = conn.prepareStatement(buildUpdateRequest("convertibleBeforeMacroRef")); 174 convUpdateBeforeFuncCall = conn.prepareStatement(buildUpdateRequest("convertibleBeforeFuncCall")); 175 176 //AFTER 177 convUpdateAfterSection = conn.prepareStatement(buildUpdateRequest("convertibleAfterSection")); 178 convUpdateAfterMacroRef = conn.prepareStatement(buildUpdateRequest("convertibleAfterMacroRef")); 179 convUpdateAfterFuncCall = conn.prepareStatement(buildUpdateRequest("convertibleAfterFuncCall")); 180 181 //BEFORE REQ 182 convSelectBeforeSection = conn.prepareStatement(buildSelectQuery("convertibleBeforeSection")); 183 convSelectBeforeMacroRef = conn.prepareStatement(buildSelectQuery("convertibleBeforeMacroRef")); 184 convSelectBeforeFuncCall = conn.prepareStatement(buildSelectQuery("convertibleBeforeFuncCall")); 185 186 //AFTER 187 convSelectAfterSection = conn.prepareStatement(buildSelectQuery("convertibleAfterSection")); 188 convSelectAfterMacroRef = conn.prepareStatement(buildSelectQuery("convertibleAfterMacroRef")); 189 convSelectAfterFuncCall = conn.prepareStatement(buildSelectQuery("convertibleAfterFuncCall")); 190 191 convTest = conn.prepareStatement("SELECT * FROM convertibleConfigOptions WHERE configOption=?;"); 192 193 //LOCATION 194 //Table that keeps track of everything referencing a configuration option 195 stmt.executeUpdate("create table if not exists locationConfigOptions (id INTEGER PRIMARY KEY ASC, configOption TEXT, location TEXT, inFunction BOOLEAN, inFunctionBody BOOLEAN);"); 196 locIns = conn.prepareStatement("INSERT INTO locationConfigOptions(configOption, location, inFunction, inFunctionBody) VALUES (?, ?, ?, ?);"); 197 198 //RETURN in If Section 199 //Table that keeps track of the presence of returns inside IfSection that occur inside functions 200 stmt.executeUpdate("create table if not exists returnIfSection (id INTEGER PRIMARY KEY ASC, location TEXT, hasReturn BOOLEAN );"); 201 returnInIfSection = conn.prepareStatement("INSERT INTO returnIfSection(location, hasReturn) VALUES (?, ? );"); 202 203 } 204 catch (Exception e) { 205 System.err.println("Statement Creation Problem"); 206 e.printStackTrace(); 207 System.exit(-1); 208 } 209 210 } 211 212 213 /** 214 * Connects to the Database. 215 * @return The connection associated. 216 */ 217 public Connection connect() { 218 try{ 219 Class.forName("org.sqlite.JDBC"); 220 conn = DriverManager.getConnection("jdbc:sqlite:test.db"); 221 }catch (ClassNotFoundException c) { 222 System.err.println("Class Not Found"); 223 c.printStackTrace(); 224 } 225 catch (SQLException sql) { 226 System.err.println("SQL Exception when connecting to sqlite"); 227 sql.printStackTrace(); 228 } 229 return conn; 230 } 231 232 233 /** 234 * Translates a Node into a ByteArrayInputStream to include into the database 235 * @param n the node to convert 236 * @return a ByteArrayInputStream to insert into the database. nulll if there's an exception 237 */ 238 private Pair<ByteArrayInputStream, Integer> nodeToBinaryStream(Node n) { 239 try{ 240 ByteArrayOutputStream nodeOut = new ByteArrayOutputStream(); 241 ObjectOutputStream objectOut = new ObjectOutputStream(nodeOut); 242 objectOut.writeObject(n); 243 byte[] nodeAsBytes = nodeOut.toByteArray(); 244 ByteArrayInputStream nodeStream = new ByteArrayInputStream(nodeAsBytes); 245 return new Pair<ByteArrayInputStream, Integer>(nodeStream, nodeAsBytes.length); 246 } 247 catch(NotSerializableException ex) { 248 System.err.println("ex cause " + ex.getMessage()); 249 return null; 250 } 251 catch(IOException ioe) { 252 ioe.printStackTrace(); 253 return null; 254 } 255 256 } 257 258 /** 259 * Adding a header file in the table 260 * @param headerRoot The node representing the root of the header file to add. 261 * @param hName The name of the header file to add. 262 * @param includingName The name of the file including this header file. 263 */ 264 public void addHeaderTree(Node headerRoot, String hName, byte[] hash) { 265 Pair<FileLock, RandomAccessFile> dbLock; 266 try { 267 //newTree.clearBatch(); 268 conn.setAutoCommit(false); 31 class DBHandlerException extends Exception { 32 33 /** 34 * 35 */ 36 private static final long serialVersionUID = 2012470201229606208L; 37 38 public DBHandlerException() { 39 super(); 40 } 41 42 public DBHandlerException(String reason) { 43 super(reason); 44 } 45 46 } 47 48 /** 49 * Constants that are used to specify which column of the table to update 50 */ 51 public static final int BIFSECTION = 0; 52 public static final int BMACROREF = 1; 53 public static final int BFUNCCALL = 2; 54 public static final int AIFSECTION = 3; 55 public static final int AMACROREF = 4; 56 public static final int AFUNCCALL = 5; 57 58 static Lock dbLock = new ReentrantLock(); 59 /** Connection to the current database **/ 60 static Connection conn; 61 /** A PreparedStatement to insert new trees in the database **/ 62 static PreparedStatement newTree; 63 /** A Prepared to select nodes with the same hash signature **/ 64 static PreparedStatement query; 65 /** A PreparedStatement to insert new trees in the database **/ 66 static PreparedStatement newMacro; 67 /** A Prepared to find whether the macrodefinition associated with a particular location remains the same 68 * with the same hash signature **/ 69 static PreparedStatement queryMacro; 70 /** A PreparedStatement to insert new funcCall in the database **/ 71 static PreparedStatement newFuncCall; 72 /** A Prepared to find whether the function definition associated with a particular location remains the same 73 * with the same hash signature **/ 74 static PreparedStatement queryFuncCall; 75 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 76 static PreparedStatement convUpdateBeforeSection; 77 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 78 static PreparedStatement convUpdateBeforeMacroRef; 79 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 80 static PreparedStatement convUpdateBeforeFuncCall; 81 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 82 static PreparedStatement convUpdateAfterSection; 83 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 84 static PreparedStatement convUpdateAfterMacroRef; 85 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 86 static PreparedStatement convUpdateAfterFuncCall; 87 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 88 static PreparedStatement convSelectBeforeSection; 89 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 90 static PreparedStatement convSelectBeforeMacroRef; 91 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 92 static PreparedStatement convSelectBeforeFuncCall; 93 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 94 static PreparedStatement convSelectAfterSection; 95 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 96 static PreparedStatement convSelectAfterMacroRef; 97 /** A Prepared to update the value of the convertibility for IfSections defined with of a config option **/ 98 static PreparedStatement convSelectAfterFuncCall; 99 /** A Prepared to insert the value of the convertibility of a config option **/ 100 static PreparedStatement convIns; 101 /** A Prepared to insert the value of the convertibility of a config option **/ 102 static PreparedStatement convLocIns; 103 /** A Prepared to request the value of the convertibility of a config option **/ 104 static PreparedStatement convLocSel; 105 /** A Prepared to test whether a config option for IfSections has already been included **/ 106 static PreparedStatement convTest; 107 /** A Prepared to insert a new location for one particular configuration option **/ 108 static PreparedStatement locIns; 109 /** A Prepared to insert a new record with the location of an IfSection and whether or not there is a return 110 * inside this IfSection 111 */ 112 static PreparedStatement returnInIfSection; 113 /** An anonymous Statement to execute arbitrary queries **/ 114 static Statement stmt; 115 116 private String buildUpdateRequest(String column) { 117 return "UPDATE convertibleConfigOptions SET " + column +"=? WHERE configOption=?;"; 118 } 119 120 private String buildSelectQuery(String column) { 121 return "SELECT * FROM convertibleConfigOptions WHERE " + column + "=? AND configOption=?;"; 122 } 123 124 private synchronized void init() { 125 try{ 126 stmt = conn.createStatement(); 127 //We set the pragma synchronous OFF 128 //The Database may be corrupted if the computer loses power or if the system crashes 129 //We don't really care 130 stmt.execute("PRAGMA synchronous = OFF;"); 131 132 //Table to avoid recounting the same header twice when analyzing 133 stmt.executeUpdate("create table if not exists treesMD5 (id INTEGER PRIMARY KEY ASC, hash BINARY[16], node TEXT); "); 134 newTree = conn.prepareStatement( 135 "insert into treesMD5(hash, node) values(?, ?);"); 136 query = conn.prepareStatement("select node from treesMD5 where hash==? ;"); 137 138 //Table to avoid recounting the same macro twice when analyzing 139 //Keeps track of the macroDefinition signature associated with one refLocation 140 stmt.executeUpdate("create table if not exists macrosMD5 (id INTEGER PRIMARY KEY ASC, " + 141 "hashDef BINARY[16], macroName TEXT, refLocation TEXT); "); 142 newMacro = conn.prepareStatement( 143 "insert into macrosMD5(hashDef, macroName, refLocation) values(?, ?, ?);"); 144 queryMacro = conn.prepareStatement("select macroName from macrosMD5 where (hashDef==? AND refLocation==?) ;"); 145 146 //Table to avoid recounting the same funcCall twice when analyzing 147 //Keeps track of the macroDefinition signature associated with one refLocation 148 stmt.executeUpdate("create table if not exists funcCallMD5 (id INTEGER PRIMARY KEY ASC, " + 149 "hashDef BINARY[16], funcName TEXT, callLocation TEXT); "); 150 newFuncCall = conn.prepareStatement( 151 "insert into funcCallMD5 (hashDef, funcName, callLocation) values(?, ?, ?);"); 152 queryFuncCall= conn.prepareStatement("select funcName from funcCallMD5 where (hashDef==? AND callLocation==?) ;"); 153 154 155 //Table to collect convertible information per location with CONFIG_OPTION 156 stmt.executeUpdate("create table if not exists convertibleLocation (id INTEGER PRIMARY KEY ASC, configOption TEXT, kind TEXT " + 157 ", location TEXT, convertible BOOLEAN);"); 158 159 //CONVERTIBLE LOCATION 160 convLocIns = conn.prepareStatement("INSERT INTO convertibleLocation(configOption, kind, location, convertible) VALUES (?, ?, ?, ?);"); 161 162 //CONVERTIBLE LOCATION REQUEST 163 convLocSel = conn.prepareStatement("SELECT * FROM convertibleLocation WHERE (configOption=?) AND (kind=?) AND (location=?) and (convertible=?)"); 164 165 166 //Table to collect convertible information per config option 167 stmt.executeUpdate("create table if not exists convertibleConfigOptions (configOption TEXT, convertibleBeforeSection SHORT INTEGER, " + 168 "convertibleBeforeMacroRef SHORT INTEGER, convertibleBeforeFuncCall SHORT INTEGER, " + 169 "convertibleAfterSection SHORT INTEGER, convertibleAfterMacroRef SHORT INTEGER, convertibleAfterFuncCall SHORT INTEGER);"); 170 171 convIns = conn.prepareStatement("INSERT INTO convertibleConfigOptions VALUES (?, ?, ?, ?, ?, ?, ?);"); 172 173 //BEFORE 174 convUpdateBeforeSection = conn.prepareStatement(buildUpdateRequest("convertibleBeforeSection")); 175 convUpdateBeforeMacroRef = conn.prepareStatement(buildUpdateRequest("convertibleBeforeMacroRef")); 176 convUpdateBeforeFuncCall = conn.prepareStatement(buildUpdateRequest("convertibleBeforeFuncCall")); 177 178 //AFTER 179 convUpdateAfterSection = conn.prepareStatement(buildUpdateRequest("convertibleAfterSection")); 180 convUpdateAfterMacroRef = conn.prepareStatement(buildUpdateRequest("convertibleAfterMacroRef")); 181 convUpdateAfterFuncCall = conn.prepareStatement(buildUpdateRequest("convertibleAfterFuncCall")); 182 183 //BEFORE REQ 184 convSelectBeforeSection = conn.prepareStatement(buildSelectQuery("convertibleBeforeSection")); 185 convSelectBeforeMacroRef = conn.prepareStatement(buildSelectQuery("convertibleBeforeMacroRef")); 186 convSelectBeforeFuncCall = conn.prepareStatement(buildSelectQuery("convertibleBeforeFuncCall")); 187 188 //AFTER 189 convSelectAfterSection = conn.prepareStatement(buildSelectQuery("convertibleAfterSection")); 190 convSelectAfterMacroRef = conn.prepareStatement(buildSelectQuery("convertibleAfterMacroRef")); 191 convSelectAfterFuncCall = conn.prepareStatement(buildSelectQuery("convertibleAfterFuncCall")); 192 193 convTest = conn.prepareStatement("SELECT * FROM convertibleConfigOptions WHERE configOption=?;"); 194 195 //LOCATION 196 //Table that keeps track of everything referencing a configuration option 197 stmt.executeUpdate("create table if not exists locationConfigOptions (id INTEGER PRIMARY KEY ASC, configOption TEXT, location TEXT, inFunction BOOLEAN, inFunctionBody BOOLEAN);"); 198 locIns = conn.prepareStatement("INSERT INTO locationConfigOptions(configOption, location, inFunction, inFunctionBody) VALUES (?, ?, ?, ?);"); 199 200 //RETURN in If Section 201 //Table that keeps track of the presence of returns inside IfSection that occur inside functions 202 stmt.executeUpdate("create table if not exists returnIfSection (id INTEGER PRIMARY KEY ASC, location TEXT, hasReturn BOOLEAN );"); 203 returnInIfSection = conn.prepareStatement("INSERT INTO returnIfSection(location, hasReturn) VALUES (?, ? );"); 204 205 } 206 catch (Exception e) { 207 System.err.println("Statement Creation Problem"); 208 e.printStackTrace(); 209 System.exit(-1); 210 } 211 212 213 } 214 215 216 public DBHandler() { 217 conn = this.connect(); 218 init(); 219 } 220 221 222 /** 223 * Connects to the Database. 224 * @return The connection associated. 225 */ 226 public Connection connect() { 227 try{ 228 Class.forName("org.sqlite.JDBC"); 229 conn = DriverManager.getConnection("jdbc:sqlite:test.db"); 230 }catch (ClassNotFoundException c) { 231 System.err.println("Class Not Found"); 232 c.printStackTrace(); 233 } 234 catch (SQLException sql) { 235 System.err.println("SQL Exception when connecting to sqlite"); 236 sql.printStackTrace(); 237 } 238 return conn; 239 } 240 241 242 /** 243 * Translates a Node into a ByteArrayInputStream to include into the database 244 * @param n the node to convert 245 * @return a ByteArrayInputStream to insert into the database. nulll if there's an exception 246 */ 247 private Pair<ByteArrayInputStream, Integer> nodeToBinaryStream(Node n) { 248 try{ 249 ByteArrayOutputStream nodeOut = new ByteArrayOutputStream(); 250 ObjectOutputStream objectOut = new ObjectOutputStream(nodeOut); 251 objectOut.writeObject(n); 252 byte[] nodeAsBytes = nodeOut.toByteArray(); 253 ByteArrayInputStream nodeStream = new ByteArrayInputStream(nodeAsBytes); 254 return new Pair<ByteArrayInputStream, Integer>(nodeStream, nodeAsBytes.length); 255 } 256 catch(NotSerializableException ex) { 257 System.err.println("ex cause " + ex.getMessage()); 258 return null; 259 } 260 catch(IOException ioe) { 261 ioe.printStackTrace(); 262 return null; 263 } 264 265 } 266 267 /** 268 * Adding a header file in the table 269 * @param headerRoot The node representing the root of the header file to add. 270 * @param hName The name of the header file to add. 271 * @param includingName The name of the file including this header file. 272 */ 273 public static synchronized void addHeaderTree(Node headerRoot, String hName, byte[] hash) { 274 try { 275 //newTree.clearBatch(); 276 //conn.setAutoCommit(false); 269 277 if(16 == hash.length ) { 270 278 newTree.setBytes(1, hash); … … 277 285 newTree.setString(2,hName); 278 286 279 //dbLock = lock_db();287 280 288 newTree.executeUpdate(); 281 //release_db(dbLock);289 282 290 283 291 //squery.setBytes(1, hash); 284 conn.commit(); 285 } catch (SQLException e) { 292 dbLock.lock(); 293 //conn.commit(); 294 dbLock.unlock(); 295 296 } catch (SQLException e) { 286 297 System.err.println("Updating error: " + hName + " not inserted in the table"); 287 298 e.printStackTrace(); … … 296 307 private Pair<FileLock, RandomAccessFile> lock_db() { 297 308 try { 298 RandomAccessFile raf = new RandomAccessFile("test.db", "rw");309 RandomAccessFile raf = new RandomAccessFile("test.db", "rw"); 299 310 FileLock dbLock = raf.getChannel().lock(); 300 return new Pair<FileLock, RandomAccessFile>(dbLock, raf);311 return new Pair<FileLock, RandomAccessFile>(dbLock, raf); 301 312 } catch (FileNotFoundException e) { 302 313 e.printStackTrace(); … … 331 342 * @param includingName The name of the file including this header file. 332 343 */ 333 public void addFuncCallTree(byte[] hash, String funcName, String callLocation) { 334 Pair<FileLock, RandomAccessFile> dbLock; 344 public static synchronized void addFuncCallTree(byte[] hash, String funcName, String callLocation) { 335 345 try { 336 346 //newTree.clearBatch(); 337 conn.setAutoCommit(false);347 //conn.setAutoCommit(false); 338 348 if(16 == hash.length ) { 339 349 newFuncCall.setBytes(1, hash); … … 350 360 //System.out.println("NEW MACRO " + newMacro); 351 361 352 //dbLock = lock_db();362 353 363 newFuncCall.executeUpdate(); 354 //release_db(dbLock); 355 356 conn.commit(); 357 } catch (SQLException e) { 364 dbLock.lock(); 365 //conn.commit(); 366 dbLock.unlock(); 367 368 } catch (SQLException e) { 358 369 System.err.println("Updating error: " + funcName + " at "+ callLocation + " not inserted in the table"); 359 370 e.printStackTrace(); … … 367 378 * @param includingName The name of the file including this header file. 368 379 */ 369 public void addMacroReferenceTree(byte[] hash, String macroName, String refLocation) { 370 Pair<FileLock, RandomAccessFile> dbLock; 380 public static synchronized void addMacroReferenceTree(byte[] hash, String macroName, String refLocation) { 371 381 try { 372 382 //newTree.clearBatch(); 373 conn.setAutoCommit(false);383 //conn.setAutoCommit(false); 374 384 if(16 == hash.length ) { 375 385 newMacro.setBytes(1, hash); … … 386 396 //System.out.println("NEW MACRO " + newMacro); 387 397 388 //dbLock = lock_db(); 398 389 399 newMacro.executeUpdate(); 390 //release_db(dbLock); 391 392 conn.commit(); 393 } catch (SQLException e) { 400 401 dbLock.lock(); 402 //conn.commit(); 403 dbLock.unlock(); 404 405 406 } catch (SQLException e) { 394 407 System.err.println("Updating error: " + macroName + " at "+ refLocation + " not inserted in the table"); 395 408 e.printStackTrace(); … … 403 416 * @return An ArrayList representing all the GNodes associated with this hash value 404 417 */ 405 public boolean isThereMacroWithSameHash(byte[] hash, String refLocation) {418 public static synchronized boolean isThereMacroWithSameHash(byte[] hash, String refLocation) { 406 419 boolean result = false; 407 420 try { … … 430 443 * @return An ArrayList representing all the GNodes associated with this hash value 431 444 */ 432 public boolean isThereFuncCallWithSameHash(byte[] hash, String callLocation) {445 public static synchronized boolean isThereFuncCallWithSameHash(byte[] hash, String callLocation) { 433 446 boolean result = false; 434 447 try { … … 456 469 * @return An ArrayList representing all the GNodes associated with this hash value 457 470 */ 458 public ArrayList<String> getNodeWithSameHash(byte[] hash) {471 public static synchronized ArrayList<String> getNodeWithSameHash(byte[] hash) { 459 472 ArrayList<String> matchingTrees = new ArrayList<String>(); 460 473 String tmp; … … 478 491 * @return An ArrayList representing all the GNodes associated with this hash value 479 492 */ 480 public ArrayList<GNode> getNodeWithSameHash(int hash) {493 public static synchronized ArrayList<GNode> getNodeWithSameHash(int hash) { 481 494 ArrayList<GNode> matchingTrees = new ArrayList<GNode>(); 482 495 … … 499 512 * @param convertible The new convertibility 500 513 */ 501 public void setConvertible(int column, String configOption, Location loc, boolean convertible) { 502 Pair<FileLock, RandomAccessFile> dbLock; 514 public static synchronized void setConvertible(int column, String configOption, Location loc, boolean convertible) { 503 515 boolean empty = false; 504 516 PreparedStatement tmpUpdate, tmpSelect; … … 511 523 convTest.setString(1, configOption); 512 524 513 //dbLock = lock_db();514 525 ResultSet rs = convTest.executeQuery(); 515 //release_db(dbLock);516 526 517 527 if (rs.next()) { … … 553 563 break; 554 564 default: 555 try { 556 throw new DBHandlerException("DBHandler Error: no column number provided"); 557 } catch (DBHandlerException dbe) { 558 System.err.println(dbe.getMessage()); 565 System.err.println("PROBLEMO " ); 559 566 return; 560 }561 567 } 562 568 … … 569 575 convLocSel.setBoolean(4, convertible); 570 576 571 //dbLock = lock_db();572 577 rs = convLocSel.executeQuery(); 573 //release_db(dbLock);574 578 if(!rs.next()) 575 579 empty = true; … … 584 588 convLocIns.setString(3, loc.toString()); 585 589 convLocIns.setBoolean(4, convertible); 586 conn.setAutoCommit(false);587 //dbLock = lock_db();590 //conn.setAutoCommit(false); 591 588 592 convLocIns.executeUpdate(); 589 //release_db(dbLock); 590 conn.commit(); 593 dbLock.lock(); 594 //conn.commit(); 595 dbLock.unlock(); 591 596 } 592 597 … … 594 599 tmpSelect.setString(2, configOption); 595 600 596 //dbLock = lock_db();597 601 rs = tmpSelect.executeQuery(); 598 //release_db(dbLock);599 602 600 603 if(!rs.next()) … … 609 612 tmpUpdate.setString(2, configOption); 610 613 611 conn.setAutoCommit(false);612 //dbLock = lock_db(); 614 //conn.setAutoCommit(false); 615 613 616 tmpUpdate.executeUpdate(); 614 //release_db(dbLock); 615 conn.commit(); 617 dbLock.lock(); 618 //conn.commit(); 619 dbLock.unlock(); 616 620 } 617 621 … … 629 633 * @param configOptions The list containing all the configuration options 630 634 */ 631 public void initConvertible(ArrayList<String> configOptions) { 632 Pair<FileLock, RandomAccessFile> dbLock; 635 public static synchronized void initConvertible(ArrayList<String> configOptions) { 633 636 boolean empty = true; 634 637 try { 635 conn.setAutoCommit(false);636 //dbLock = lock_db(); 637 ResultSet rs = stmt.executeQuery("SELECT * FROM convertibleConfigOptions;");638 //conn.setAutoCommit(false); 639 640 ResultSet rs = stmt.executeQuery("SELECT * FROM convertibleConfigOptions;"); 638 641 //release_db(dbLock); 639 642 … … 662 665 } 663 666 664 conn.commit(); 665 } catch (Exception e) { 667 668 669 670 671 672 673 dbLock.lock(); 674 //conn.commit(); 675 dbLock.unlock(); 676 } catch (Exception e) { 666 677 System.err.println("Error when initializing"); 667 678 e.printStackTrace(); … … 674 685 * @param loc The new location to add 675 686 */ 676 public void insertNewLocation(String configOption, Location loc, boolean inFunction, boolean inFunctionBody) { 677 try { 678 Pair<FileLock, RandomAccessFile> dbLock; 679 conn.setAutoCommit(false); 687 public static synchronized void insertNewLocation(String configOption, Location loc, boolean inFunction, boolean inFunctionBody) { 688 try { 689 //conn.setAutoCommit(false); 680 690 locIns.setString(1, configOption); 681 691 locIns.setString(2, loc.toString()); … … 683 693 locIns.setBoolean(4, inFunctionBody); 684 694 685 //dbLock = lock_db();695 686 696 locIns.execute(); 687 //release_db(dbLock);688 conn.commit();697 698 //conn.commit(); 689 699 } catch (Exception e) { 690 700 e.printStackTrace(); … … 698 708 * @param hasReturn True if this IfSection contains a return statement 699 709 */ 700 public void insertNewReturnInIfSection(Location loc, boolean hasReturn) { 701 try { 702 Pair<FileLock, RandomAccessFile> dbLock; 703 conn.setAutoCommit(false); 710 public static synchronized void insertNewReturnInIfSection(Location loc, boolean hasReturn) { 711 try { 712 //conn.setAutoCommit(false); 704 713 returnInIfSection.setString(1, loc.toString()); 705 714 returnInIfSection.setBoolean(2, hasReturn); 706 715 707 //dbLock= lock_db();716 708 717 returnInIfSection.execute(); 709 //release_db(dbLock);710 conn.commit();718 719 //conn.commit(); 711 720 } catch (Exception e) { 712 721 e.printStackTrace(); -
trunk/cpp_analysis/src/xtc/lang/c4/Makefile
r193 r199 62 62 C4PrettyPrinter.java \ 63 63 C4Extractable.java \ 64 C4Wrapper.java \ 64 65 C4Driver.java \ 65 66 DBHandler.java \ … … 67 68 C4MacrosManager.java \ 68 69 C4IncludePathManager.java 70 69 71 CFACTORY = C4CFactory 70 72 -
trunk/cpp_analysis/src/xtc/lang/c4/TreeLogger.java
r196 r199 63 63 64 64 //We look for the same hash value in the DB 65 if( dbHandler.isThereMacroWithSameHash(md5key, refLocation)) {65 if(DBHandler.isThereMacroWithSameHash(md5key, refLocation)) { 66 66 //We look for potential collisions by comparing the whole trees 67 67 //We've already considered that macro... … … 77 77 //At this point, we know that the tree has been already considered 78 78 //We insert it into the DB 79 dbHandler.addMacroReferenceTree(md5key, macroName, refLocation);79 DBHandler.addMacroReferenceTree(md5key, macroName, refLocation); 80 80 return false; 81 81 } … … 94 94 */ 95 95 public boolean alreadyConsideredFuncCall( GNode funcDef, String funcName, String callLocation) { 96 97 if(null == funcDef) { 98 System.out.println("FuncDef is Null at this call location " + callLocation); 99 return false; 100 } 101 96 102 //First we compute the new hash value 97 103 //int newHash = hashFunction(rootNode); … … 100 106 101 107 //We look for the same hash value in the DB 102 if( dbHandler.isThereFuncCallWithSameHash(md5key, callLocation)) {108 if(DBHandler.isThereFuncCallWithSameHash(md5key, callLocation)) { 103 109 //We look for potential collisions by comparing the whole trees 104 110 //We've already considered that macro... … … 112 118 //At this point, we know that the tree has been already considered 113 119 //We insert it into the DB 114 &n
