3 import java.io.FileNotFoundException;
4 import java.io.PrintWriter;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.HashSet;
8 import java.util.Hashtable;
9 import java.util.Iterator;
11 import java.util.Vector;
13 import Analysis.Disjoint.*;
14 import Analysis.MLP.CodePlan;
15 import IR.TypeDescriptor;
16 import Analysis.OoOJava.OoOJavaAnalysis;
18 /* An instance of this class manages all OoOJava coarse-grained runtime conflicts
19 * by generating C-code to either rule out the conflict at runtime or resolve one.
22 * 1) Instantiate singleton object (String input is to specify output dir)
23 * 2) Call setGlobalEffects setGlobalEffects(Hashtable<Taint, Set<Effect>> ) ONCE
24 * 3) Input SESE blocks, for each block:
25 * 3a) call addToTraverseToDoList(FlatSESEEnterNode , ReachGraph , Hashtable<Taint, Set<Effect>>) for the seseBlock
26 * 3b) call String getTraverserInvocation(TempDescriptor, String, FlatSESEEnterNode) to get the name of the traverse method in C
27 * 4) Call void close()
28 * Note: All computation is done upon closing the object. Steps 1-3 only input data
30 public class RuntimeConflictResolver {
31 public static final boolean javaDebug = true;
32 public static final boolean cSideDebug = true;
34 private PrintWriter cFile;
35 private PrintWriter headerFile;
36 private static final String hashAndQueueCFileDir = "oooJava/";
37 //This keeps track of taints we've traversed to prevent printing duplicate traverse functions
38 //The Integer keeps track of the weakly connected group it's in (used in enumerateHeapRoots)
39 private Hashtable<Taint, Integer> doneTaints;
40 private Hashtable<Tuple, Integer> idMap=new Hashtable<Tuple,Integer>();
41 private Hashtable<Taint, Set<Effect>> globalEffects;
42 private Hashtable<Taint, Set<Effect>> globalConflicts;
43 private ArrayList<TraversalInfo> toTraverse;
45 public int currentID=1;
47 // initializing variables can be found in printHeader()
48 private static final String getAllocSiteInC = "->allocsite";
49 private static final String queryVistedHashtable = "hashRCRInsert";
50 private static final String addToQueueInC = "enqueueRCRQueue(";
51 private static final String dequeueFromQueueInC = "dequeueRCRQueue()";
52 private static final String clearQueue = "resetRCRQueue()";
53 // Make hashtable; hashRCRCreate(unsigned int size, double loadfactor)
54 private static final String mallocVisitedHashtable = "hashRCRCreate(128, 0.75)";
55 private static final String deallocVisitedHashTable = "hashRCRDelete()";
56 private static final String resetVisitedHashTable = "hashRCRreset()";
58 // Hashtable provides fast access to heaproot # lookups
59 private Hashtable<Taint, WeaklyConectedHRGroup> connectedHRHash;
60 private ArrayList<WeaklyConectedHRGroup> num2WeaklyConnectedHRGroup;
61 private int traverserIDCounter;
62 private int weaklyConnectedHRCounter;
63 private ArrayList<TaintAndInternalHeapStructure> pendingPrintout;
64 private EffectsTable effectsLookupTable;
65 private OoOJavaAnalysis oooa;
67 public RuntimeConflictResolver(String buildir, OoOJavaAnalysis oooa) throws FileNotFoundException {
68 String outputFile = buildir + "RuntimeConflictResolver";
71 cFile = new PrintWriter(new File(outputFile + ".c"));
72 headerFile = new PrintWriter(new File(outputFile + ".h"));
74 cFile.println("#include \"" + hashAndQueueCFileDir + "hashRCR.h\"\n#include \""
75 + hashAndQueueCFileDir + "Queue_RCR.h\"\n#include <stdlib.h>");
76 cFile.println("#include \"classdefs.h\"");
77 cFile.println("#include \"structdefs.h\"");
78 cFile.println("#include \"mlp_runtime.h\"");
79 cFile.println("#include \"RuntimeConflictResolver.h\"");
80 cFile.println("#include \"hashStructure.h\"");
82 headerFile.println("#ifndef __3_RCR_H_");
83 headerFile.println("#define __3_RCR_H_");
85 doneTaints = new Hashtable<Taint, Integer>();
86 connectedHRHash = new Hashtable<Taint, WeaklyConectedHRGroup>();
88 traverserIDCounter = 1;
89 weaklyConnectedHRCounter = 0;
90 pendingPrintout = new ArrayList<TaintAndInternalHeapStructure>();
91 toTraverse = new ArrayList<TraversalInfo>();
92 globalConflicts = new Hashtable<Taint, Set<Effect>>();
93 //Note: globalEffects is not instantiated since it'll be passed in whole while conflicts comes in chunks
96 public void setGlobalEffects(Hashtable<Taint, Set<Effect>> effects) {
97 globalEffects = effects;
100 System.out.println("============EFFECTS LIST AS PASSED IN============");
101 for(Taint t: globalEffects.keySet()) {
102 System.out.println("For Taint " + t);
103 for(Effect e: globalEffects.get(t)) {
104 System.out.println("\t" + e);
107 System.out.println("====================END LIST====================");
112 // Go through the SESE's
113 for (Iterator<FlatSESEEnterNode> seseit = oooa.getAllSESEs().iterator(); seseit.hasNext();) {
114 FlatSESEEnterNode fsen = seseit.next();
115 Analysis.OoOJava.ConflictGraph conflictGraph;
116 Hashtable<Taint, Set<Effect>> conflicts;
117 System.out.println("-------");
118 System.out.println(fsen);
119 System.out.println(fsen.getIsCallerSESEplaceholder());
120 System.out.println(fsen.getParent());
122 if (fsen.getParent() != null) {
123 conflictGraph = oooa.getConflictGraph(fsen.getParent());
124 System.out.println("CG=" + conflictGraph);
125 if (conflictGraph != null)
126 System.out.println("Conflicts=" + conflictGraph.getConflictEffectSet(fsen));
129 if (!fsen.getIsCallerSESEplaceholder() && fsen.getParent() != null
130 && (conflictGraph = oooa.getConflictGraph(fsen.getParent())) != null
131 && (conflicts = conflictGraph.getConflictEffectSet(fsen)) != null) {
132 FlatMethod fm = fsen.getfmEnclosing();
133 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(fm.getMethod());
135 rg.writeGraph("RCR_RG_SESE_DEBUG");
137 addToTraverseToDoList(fsen, rg, conflicts);
140 // Go through the stall sites
141 for (Iterator<FlatNode> codeit = oooa.getNodesWithPlans().iterator(); codeit.hasNext();) {
142 FlatNode fn = codeit.next();
143 CodePlan cp = oooa.getCodePlan(fn);
144 FlatSESEEnterNode currentSESE = cp.getCurrentSESE();
145 Analysis.OoOJava.ConflictGraph graph = oooa.getConflictGraph(currentSESE);
148 Set<Analysis.OoOJava.SESELock> seseLockSet = oooa.getLockMappings(graph);
149 Set<Analysis.OoOJava.WaitingElement> waitingElementSet =
150 graph.getStallSiteWaitingElementSet(fn, seseLockSet);
152 if (waitingElementSet.size() > 0) {
153 for (Iterator<Analysis.OoOJava.WaitingElement> iterator = waitingElementSet.iterator(); iterator.hasNext();) {
154 Analysis.OoOJava.WaitingElement waitingElement =
155 (Analysis.OoOJava.WaitingElement) iterator.next();
157 Analysis.OoOJava.ConflictGraph conflictGraph = graph;
158 Hashtable<Taint, Set<Effect>> conflicts;
159 ReachGraph rg = oooa.getDisjointAnalysis().getReachGraph(currentSESE.getmdEnclosing());
161 rg.writeGraph("RCR_RG_STALLSITE_DEBUG");
163 if ((conflictGraph != null) && (conflicts = graph.getConflictEffectSet(fn)) != null
165 addToTraverseToDoList(fn, waitingElement.getTempDesc(), rg, conflicts);
172 buildEffectsLookupStructure();
178 * 1) Get global effects and conflicts
179 * 2) Create a hash structure (EffectsTable) to manage effects (hashed by affected Allocsite, then taint, then field)
180 * 2a) Use Effects to verify we can access something (reads)
181 * 2b) Use conflicts to mark conflicts (read/write/strongupdate)
182 * 2c) At second level of hash, store Heaproots that can cause conflicts at the field
183 * 3) Walk hash structure to identify and enumerate weakly connected groups and generate waiting queue slots.
184 * 4) Build internal representation of the rgs (pruned)
185 * 5) Print c methods by walking internal representation
188 public void addToTraverseToDoList(FlatSESEEnterNode rblock, ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
190 toTraverse.add(new TraversalInfo(rblock, rg));
192 //Add to Global conflicts
193 for(Taint t: conflicts.keySet()) {
194 if(globalConflicts.containsKey(t)) {
195 globalConflicts.get(t).addAll(conflicts.get(t));
197 globalConflicts.put(t, conflicts.get(t));
203 public void addToTraverseToDoList(FlatNode fn, TempDescriptor tempDesc,
204 ReachGraph rg, Hashtable<Taint, Set<Effect>> conflicts) {
205 toTraverse.add(new TraversalInfo(fn, rg, tempDesc));
207 for(Taint t: conflicts.keySet()) {
208 if(globalConflicts.containsKey(t)) {
209 globalConflicts.get(t).addAll(conflicts.get(t));
211 globalConflicts.put(t, conflicts.get(t));
216 private void traverseSESEBlock(FlatSESEEnterNode rblock, ReachGraph rg) {
217 Collection<TempDescriptor> inVars = rblock.getInVarSet();
219 if (inVars.size() == 0)
221 System.out.println("RBLOCK:"+rblock);
222 System.out.println("["+inVars+"]");
224 // For every non-primitive variable, generate unique method
225 for (TempDescriptor invar : inVars) {
226 TypeDescriptor type = invar.getType();
227 if(type.isPrimitive()) {
230 System.out.println(invar);
231 //created stores nodes with specific alloc sites that have been traversed while building
232 //internal data structure. It is later traversed sequentially to find inset variables and
234 //NOTE: Integer stores Allocation Site ID in hashtable
235 Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
236 VariableNode varNode = rg.getVariableNodeNoMutation(invar);
237 Taint taint = getProperTaintForFlatSESEEnterNode(rblock, varNode, globalEffects);
239 printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + rblock.toPrettyString());
243 //This is to prevent duplicate traversals from being generated
244 if(doneTaints.containsKey(taint))
247 doneTaints.put(taint, traverserIDCounter++);
248 createConcreteGraph(effectsLookupTable, created, varNode, taint);
251 //This will add the taint to the printout, there will be NO duplicates (checked above)
252 if(!created.isEmpty()) {
253 for(Iterator<ConcreteRuntimeObjNode> it=created.values().iterator();it.hasNext();) {
254 ConcreteRuntimeObjNode obj=it.next();
255 if (obj.hasPrimitiveConflicts()||obj.decendantsConflict()) {
256 rblock.addInVarForDynamicCoarseConflictResolution(invar);
261 pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
266 private void traverseStallSite(FlatNode enterNode, TempDescriptor invar, ReachGraph rg) {
267 TypeDescriptor type = invar.getType();
268 if(type == null || type.isPrimitive()) {
272 Hashtable<Integer, ConcreteRuntimeObjNode> created = new Hashtable<Integer, ConcreteRuntimeObjNode>();
273 VariableNode varNode = rg.getVariableNodeNoMutation(invar);
274 Taint taint = getProperTaintForEnterNode(enterNode, varNode, globalEffects);
277 printDebug(javaDebug, "Null FOR " +varNode.getTempDescriptor().getSafeSymbol() + enterNode.toString());
281 if(doneTaints.containsKey(taint))
284 doneTaints.put(taint, traverserIDCounter++);
285 createConcreteGraph(effectsLookupTable, created, varNode, taint);
287 if (!created.isEmpty()) {
288 pendingPrintout.add(new TaintAndInternalHeapStructure(taint, created));
292 public String getTraverserInvocation(TempDescriptor invar, String varString, FlatNode fn) {
294 if(fn instanceof FlatSESEEnterNode) {
295 flatname = ((FlatSESEEnterNode) fn).getPrettyIdentifier();
297 flatname = fn.toString();
300 return "traverse___" + invar.getSafeSymbol() +
301 removeInvalidChars(flatname) + "___("+varString+");";
304 public int getTraverserID(TempDescriptor invar, FlatNode fn) {
305 Tuple t=new Tuple(invar, fn);
306 if (idMap.containsKey(t))
307 return idMap.get(t).intValue();
308 int value=currentID++;
309 idMap.put(t, new Integer(value));
313 public String removeInvalidChars(String in) {
314 StringBuilder s = new StringBuilder(in);
315 for(int i = 0; i < s.length(); i++) {
316 if(s.charAt(i) == ' ' || s.charAt(i) == '.' || s.charAt(i) == '='||s.charAt(i)=='['||s.charAt(i)==']') {
324 public void close() {
325 //prints out all generated code
326 for(TaintAndInternalHeapStructure ths: pendingPrintout) {
327 printCMethod(ths.nodesInHeap, ths.t);
330 //Prints out the master traverser Invocation that'll call all other traversers
331 //based on traverserID
332 printMasterTraverserInvocation();
333 printResumeTraverserInvocation();
335 //TODO this is only temporary, remove when thread local vars implemented.
336 createMasterHashTableArray();
338 // Adds Extra supporting methods
339 cFile.println("void initializeStructsRCR() {\n " + mallocVisitedHashtable + ";\n " + clearQueue + ";\n}");
340 cFile.println("void destroyRCR() {\n " + deallocVisitedHashTable + ";\n}");
342 headerFile.println("void initializeStructsRCR();\nvoid destroyRCR();");
343 headerFile.println("#endif\n");
349 //Builds Effects Table and runs the analysis on them to get weakly connected HRs
350 //SPECIAL NOTE: Only runs after we've taken all the conflicts and effects
351 private void buildEffectsLookupStructure(){
352 effectsLookupTable = new EffectsTable(globalEffects, globalConflicts);
353 effectsLookupTable.runAnalysis();
354 enumerateHeaproots();
357 private void runAllTraversals() {
358 for(TraversalInfo t: toTraverse) {
359 printDebug(javaDebug, "Running Traversal a traversal on " + t.f);
361 if(t.f instanceof FlatSESEEnterNode) {
362 traverseSESEBlock((FlatSESEEnterNode)t.f, t.rg);
364 if(t.invar == null) {
365 System.out.println("RCR ERROR: Attempted to run a stall site traversal with NO INVAR");
367 traverseStallSite(t.f, t.invar, t.rg);
374 //TODO: This is only temporary, remove when thread local variables are functional.
375 private void createMasterHashTableArray() {
376 headerFile.println("void createAndFillMasterHashStructureArray();");
377 cFile.println("void createAndFillMasterHashStructureArray() {\n" +
378 " rcr_createMasterHashTableArray("+weaklyConnectedHRCounter + ");");
380 for(int i = 0; i < weaklyConnectedHRCounter; i++) {
381 cFile.println(" allHashStructures["+i+"] = (HashStructure *) rcr_createHashtable("+num2WeaklyConnectedHRGroup.get(i).connectedHRs.size()+");");
386 private void printMasterTraverserInvocation() {
387 headerFile.println("\nint tasktraverse(SESEcommon * record);");
388 cFile.println("\nint tasktraverse(SESEcommon * record) {");
389 cFile.println(" if(!CAS(&record->rcrstatus,1,2)) return;");
390 cFile.println(" switch(record->classID) {");
392 for(Iterator<FlatSESEEnterNode> seseit=oooa.getAllSESEs().iterator();seseit.hasNext();) {
393 FlatSESEEnterNode fsen=seseit.next();
394 cFile.println( " /* "+fsen.getPrettyIdentifier()+" */");
395 cFile.println( " case "+fsen.getIdentifier()+": {");
396 cFile.println( " "+fsen.getSESErecordName()+" * rec=("+fsen.getSESErecordName()+" *) record;");
397 Vector<TempDescriptor> invars=fsen.getInVarsForDynamicCoarseConflictResolution();
398 for(int i=0;i<invars.size();i++) {
399 TempDescriptor tmp=invars.get(i);
400 cFile.println(" " + this.getTraverserInvocation(tmp, "rec->"+tmp+", rec", fsen));
402 cFile.println( " }");
403 cFile.println( " break;");
406 for(Taint t: doneTaints.keySet()) {
407 if (t.isStallSiteTaint()){
408 cFile.println( " case -" + getTraverserID(t.getVar(), t.getStallSite())+ ": {");
409 cFile.println( " SESEstall * rec=(SESEstall*) record;");
410 cFile.println( " " + this.getTraverserInvocation(t.getVar(), "rec->___obj___, rec", t.getStallSite())+";");
411 cFile.println( " }");
412 cFile.println(" break;");
416 cFile.println(" default:\n printf(\"Invalid SESE ID was passed in: %d.\\n\",record->classID);\n break;");
423 //This will print the traverser invocation that takes in a traverserID and starting ptr
424 private void printResumeTraverserInvocation() {
425 headerFile.println("\nint traverse(void * startingPtr, SESEcommon * record, int traverserID);");
426 cFile.println("\nint traverse(void * startingPtr, SESEcommon *record, int traverserID) {");
427 cFile.println(" switch(traverserID) {");
429 for(Taint t: doneTaints.keySet()) {
430 cFile.println(" case " + doneTaints.get(t)+ ":");
431 if(t.isRBlockTaint()) {
432 cFile.println(" " + this.getTraverserInvocation(t.getVar(), "startingPtr, ("+t.getSESE().getSESErecordName()+" *)record", t.getSESE()));
433 } else if (t.isStallSiteTaint()){
434 cFile.println("/* " + this.getTraverserInvocation(t.getVar(), "startingPtr, record", t.getStallSite())+"*/");
436 System.out.println("RuntimeConflictResolver encountered a taint that is neither SESE nor stallsite: " + t);
438 cFile.println(" break;");
441 if(RuntimeConflictResolver.cSideDebug) {
442 cFile.println(" default:\n printf(\"Invalid traverser ID %u was passed in.\\n\", traverserID);\n break;");
444 cFile.println(" default:\n break;");
451 private void createConcreteGraph(
453 Hashtable<Integer, ConcreteRuntimeObjNode> created,
454 VariableNode varNode,
457 // if table is null that means there's no conflicts, therefore we need not
458 // create a traversal
462 Iterator<RefEdge> possibleEdges = varNode.iteratorToReferencees();
463 while (possibleEdges.hasNext()) {
464 RefEdge edge = possibleEdges.next();
467 ConcreteRuntimeObjNode singleRoot = new ConcreteRuntimeObjNode(edge.getDst(), true, false);
468 int rootKey = singleRoot.allocSite.getUniqueAllocSiteID();
470 if (!created.containsKey(rootKey)) {
471 created.put(rootKey, singleRoot);
472 createHelper(singleRoot, edge.getDst().iteratorToReferencees(), created, table, t);
477 // Plan is to add stuff to the tree depth-first sort of way. That way, we can
478 // propagate up conflicts
479 private void createHelper(ConcreteRuntimeObjNode curr,
480 Iterator<RefEdge> edges,
481 Hashtable<Integer, ConcreteRuntimeObjNode> created,
484 assert table != null;
485 AllocSite parentKey = curr.allocSite;
486 EffectsGroup currEffects = table.getEffects(parentKey, taint);
488 if (currEffects == null || currEffects.isEmpty())
491 //Handle Objects (and primitives if child is new)
492 if(currEffects.hasObjectEffects()) {
493 while(edges.hasNext()) {
494 RefEdge edge = edges.next();
495 String field = edge.getField();
496 CombinedObjEffects effectsForGivenField = currEffects.getObjEffect(field);
497 //If there are no effects, then there's no point in traversing this edge
498 if(effectsForGivenField != null) {
499 HeapRegionNode childHRN = edge.getDst();
500 int childKey = childHRN.getAllocSite().getUniqueAllocSiteID();
501 boolean isNewChild = !created.containsKey(childKey);
502 ConcreteRuntimeObjNode child;
505 child = new ConcreteRuntimeObjNode(childHRN, false, curr.isObjectArray());
506 created.put(childKey, child);
508 child = created.get(childKey);
511 curr.addObjChild(field, child, effectsForGivenField);
513 if (effectsForGivenField.hasConflict()) {
514 child.hasPotentialToBeIncorrectDueToConflict |= effectsForGivenField.hasReadConflict;
515 propagateObjConflict(curr, child);
518 if(effectsForGivenField.hasReadEffect) {
519 child.addReachableParent(curr);
521 //If isNewChild, flag propagation will be handled at recursive call
523 createHelper(child, childHRN.iteratorToReferencees(), created, table, taint);
525 //This makes sure that all conflicts below the child is propagated up the referencers.
526 if(child.decendantsPrimConflict || child.hasPrimitiveConflicts()) {
527 propagatePrimConflict(child, child.enqueueToWaitingQueueUponConflict);
530 if(child.decendantsObjConflict) {
531 propagateObjConflict(child, child.enqueueToWaitingQueueUponConflict);
540 curr.primitiveConflictingFields = currEffects.primitiveConflictingFields;
541 if(currEffects.hasPrimitiveConflicts()) {
542 //Reminder: primitive conflicts are abstracted to object.
543 propagatePrimConflict(curr, curr);
547 // This will propagate the conflict up the data structure.
548 private void propagateObjConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
549 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
550 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
551 (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess))) // case where referencer has never seen possible unresolved referencee below
553 referencer.decendantsObjConflict = true;
554 propagateObjConflict(referencer, pointsOfAccess);
559 private void propagateObjConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
560 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
561 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //case where referencee has never seen referncer
562 (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess))) // case where referencer has never seen possible unresolved referencee below
564 referencer.decendantsObjConflict = true;
565 propagateObjConflict(referencer, pointOfAccess);
570 private void propagatePrimConflict(ConcreteRuntimeObjNode curr, HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
571 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
572 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
573 (pointsOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointsOfAccess)))
575 referencer.decendantsPrimConflict = true;
576 propagatePrimConflict(referencer, pointsOfAccess);
581 private void propagatePrimConflict(ConcreteRuntimeObjNode curr, ConcreteRuntimeObjNode pointOfAccess) {
582 for(ConcreteRuntimeObjNode referencer: curr.parentsWithReadToNode) {
583 if(curr.parentsThatWillLeadToConflicts.add(referencer) || //same cases as above
584 (pointOfAccess != null && referencer.addPossibleWaitingQueueEnqueue(pointOfAccess)))
586 referencer.decendantsPrimConflict = true;
587 propagatePrimConflict(referencer, pointOfAccess);
593 * This method generates a C method for every inset variable and rblock.
595 * The C method works by generating a large switch statement that will run the appropriate
596 * checking code for each object based on its allocation site. The switch statement is
597 * surrounded by a while statement which dequeues objects to be checked from a queue. An
598 * object is added to a queue only if it contains a conflict (in itself or in its referencees)
599 * and we came across it while checking through it's referencer. Because of this property,
600 * conflicts will be signaled by the referencer; the only exception is the inset variable which can
601 * signal a conflict within itself.
604 private void printCMethod(Hashtable<Integer, ConcreteRuntimeObjNode> created, Taint taint) {
605 String inVar = taint.getVar().getSafeSymbol();
608 if(taint.isStallSiteTaint()) {
609 rBlock = taint.getStallSite().toString();
610 } else if(taint.isRBlockTaint()) {
611 rBlock = taint.getSESE().getPrettyIdentifier();
613 System.out.println("RCR CRITICAL ERROR: TAINT IS NEITHER A STALLSITE NOR SESE! " + taint.toString());
617 //This hash table keeps track of all the case statements generated.
618 Hashtable<AllocSite, StringBuilder> cases = new Hashtable<AllocSite, StringBuilder>();
621 for (ConcreteRuntimeObjNode node : created.values()) {
622 printDebug(javaDebug, "Considering " + node.allocSite + " for traversal");
623 if (!cases.containsKey(node.allocSite) && qualifiesForCaseStatement(node)) {
624 printDebug(javaDebug, "+\t" + node.allocSite + " qualified for case statement");
625 addChecker(taint, node, cases, null, "ptr", 0);
632 if (taint.isStallSiteTaint()) {
633 methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, SESEstall *record)";
635 methodName= "void traverse___" + inVar + removeInvalidChars(rBlock) + "___(void * InVar, "+taint.getSESE().getSESErecordName() +" *record)";
636 FlatSESEEnterNode fsese=taint.getSESE();
637 TempDescriptor tmp=taint.getVar();
638 index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
641 cFile.println(methodName + " {");
642 headerFile.println(methodName + ";");
644 if(cases.size() == 0) {
645 cFile.println(" return;");
647 cFile.println(" int totalcount=RUNBIAS;\n");
649 if (taint.isStallSiteTaint()) {
650 cFile.println(" record->rcrRecords[0].count=RUNBIAS;\n");
652 cFile.println(" record->rcrRecords["+index+"].count=RUNBIAS;\n");
653 cFile.println(" record->rcrRecords["+index+"].index=0;\n");
656 //clears queue and hashtable that keeps track of where we've been.
657 cFile.println(clearQueue + ";\n" + resetVisitedHashTable + ";");
658 //generic cast to ___Object___ to access ptr->allocsite field.
659 cFile.println("struct ___Object___ * ptr = (struct ___Object___ *) InVar;\nif (InVar != NULL) {\n " + queryVistedHashtable + "(ptr);\n do {");
660 if (taint.isRBlockTaint()) {
661 cFile.println(" if(unlikely(record->common.doneExecuting)) {");
662 cFile.println(" record->common.rcrstatus=0;");
663 cFile.println(" return;");
666 cFile.println(" switch(ptr->allocsite) {");
668 for(AllocSite singleCase: cases.keySet()) {
669 cFile.append(cases.get(singleCase));
672 cFile.println(" default:\n break; ");
673 cFile.println(" }\n } while((ptr = " + dequeueFromQueueInC + ") != NULL);\n}");
675 if (taint.isStallSiteTaint()) {
677 cFile.println(" if(atomic_sub_and_test(RUNBIAS-totalcount,&(record->rcrRecords[0].count))) {");
678 cFile.println(" psem_give_tag(record->common.parentsStallSem, record->tag);");
679 cFile.println(" BARRIER();");
680 cFile.println(" record->common.rcrstatus=0;");
683 cFile.println(" if(atomic_sub_and_test(RUNBIAS-totalcount,&(record->rcrRecords["+index+"].count))) {");
684 cFile.println(" int flag=LOCKXCHG32(&(record->rcrRecords["+index+"].flag),0);");
685 cFile.println(" if(flag) {");
686 //we have resolved a heap root...see if this was the last dependence
687 cFile.println(" if(atomic_sub_and_test(1, &(record->common.unresolvedDependencies))) workScheduleSubmit((void *)record);");
690 cFile.println(" record->common.rcrstatus=0;");
698 * addChecker creates a case statement for every object that is an inset variable, has more
699 * than 1 parent && has conflicts, or where resumes are possible (from waiting queue).
700 * See .qualifiesForCaseStatement
702 private void addChecker(Taint taint,
703 ConcreteRuntimeObjNode node,
704 Hashtable<AllocSite,StringBuilder> cases,
705 StringBuilder possibleContinuingCase,
708 StringBuilder currCase = possibleContinuingCase;
709 if(qualifiesForCaseStatement(node)) {
710 assert prefix.equals("ptr") && !cases.containsKey(node.allocSite);
711 currCase = new StringBuilder();
712 cases.put(node.allocSite, currCase);
713 currCase.append(" case " + node.getAllocationSite() + ": {\n");
715 //either currCase is continuing off a parent case or is its own.
716 assert currCase !=null;
718 boolean primConfRead=false;
719 boolean primConfWrite=false;
720 boolean objConfRead=false;
721 boolean objConfWrite=false;
724 for(String field: node.primitiveConflictingFields.keySet()) {
725 CombinedObjEffects effect=node.primitiveConflictingFields.get(field);
726 primConfRead|=effect.hasReadConflict;
727 primConfWrite|=effect.hasWriteConflict;
730 //Object Reference Test
731 for(String field: node.objectRefs.keySet()) {
732 for(ObjRef ref: node.objectRefs.get(field)) {
733 CombinedObjEffects effect=ref.myEffects;
734 objConfRead|=effect.hasReadConflict;
735 objConfWrite|=effect.hasWriteConflict;
740 if (taint.isRBlockTaint()) {
741 FlatSESEEnterNode fsese=taint.getSESE();
742 TempDescriptor tmp=taint.getVar();
743 index=fsese.getInVarsForDynamicCoarseConflictResolution().indexOf(tmp);
746 String strrcr=taint.isRBlockTaint()?"&record->rcrRecords["+index+"], ":"NULL, ";
748 //Do call if we need it.
749 if(primConfWrite||objConfWrite) {
750 int heaprootNum = connectedHRHash.get(taint).id;
751 assert heaprootNum != -1;
752 int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
753 int traverserID = doneTaints.get(taint);
754 currCase.append(" int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
756 currCase.append(" int tmpvar"+depth+"=rcr_WTWRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
758 currCase.append(" int tmpvar"+depth+"=rcr_WRITEBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
759 } else if (primConfRead||objConfRead) {
760 int heaprootNum = connectedHRHash.get(taint).id;
761 assert heaprootNum != -1;
762 int allocSiteID = connectedHRHash.get(taint).getWaitingQueueBucketNum(node);
763 int traverserID = doneTaints.get(taint);
764 currCase.append(" int tmpkey"+depth+"=rcr_generateKey("+prefix+");\n");
766 currCase.append(" int tmpvar"+depth+"=rcr_WTREADBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
768 currCase.append(" int tmpvar"+depth+"=rcr_READBINCASE(allHashStructures["+heaprootNum+"], tmpkey"+depth+", (SESEcommon *) record, "+strrcr+index+");\n");
771 if(primConfWrite||objConfWrite||primConfRead||objConfRead) {
772 currCase.append("if (!(tmpvar"+depth+"&READYMASK)) totalcount--;\n");
776 currCase.append("{\n");
778 if(node.isObjectArray() && node.decendantsConflict()) {
779 //since each array element will get its own case statement, we just need to enqueue each item into the queue
780 //note that the ref would be the actual object and node would be of struct ArrayObject
782 ArrayList<Integer> allocSitesWithProblems = node.getReferencedAllocSites();
783 if(!allocSitesWithProblems.isEmpty()) {
784 String childPtr = "((struct ___Object___ **)(((char *) &(((struct ArrayObject *)"+ prefix+")->___length___))+sizeof(int)))[i]";
785 String currPtr = "arrayElement" + pdepth;
787 //This is done with the assumption that an array of object stores pointers.
788 currCase.append("{\n int i;\n");
789 currCase.append(" for(i = 0; i<((struct ArrayObject *) " + prefix + " )->___length___; i++ ) {\n");
790 currCase.append(" struct ___Object___ *"+currPtr+" = "+childPtr+";\n");
791 currCase.append(" if( arrayElement"+pdepth+" != NULL) {\n");
793 //There should be only one field, hence we only take the first field in the keyset.
794 assert node.objectRefs.keySet().size() <= 1;
795 ArrayList<ObjRef> refsAtParticularField = node.objectRefs.get(node.objectRefs.keySet().iterator().next());
796 printObjRefSwitchStatement(taint,cases,pdepth,currCase,refsAtParticularField,childPtr,currPtr);
797 currCase.append(" }}}\n");
801 for(String field: node.objectRefs.keySet()) {
802 ArrayList<ObjRef> refsAtParticularField = node.objectRefs.get(field);
803 String childPtr = "((struct "+node.original.getType().getSafeSymbol()+" *)"+prefix +")->___" + field + "___";
804 String currPtr = "myPtr" + pdepth;
805 currCase.append(" struct ___Object___ * "+currPtr+"= (struct ___Object___ * ) " + childPtr + ";\n");
806 currCase.append(" if (" + currPtr + " != NULL) { ");
808 printObjRefSwitchStatement(taint, cases, depth, currCase, refsAtParticularField, childPtr, currPtr);
809 currCase.append("}");
813 currCase.append("}\n"); //For particular top level case statement.
815 if(qualifiesForCaseStatement(node)) {
816 currCase.append(" }\n break;\n");
820 private void printObjRefSwitchStatement(Taint taint, Hashtable<AllocSite, StringBuilder> cases,
821 int pDepth, StringBuilder currCase, ArrayList<ObjRef> refsAtParticularField, String childPtr,
823 currCase.append(" switch(" + currPtr + getAllocSiteInC + ") {\n");
825 for(ObjRef ref: refsAtParticularField) {
826 if(ref.child.decendantsConflict() || ref.child.hasPrimitiveConflicts()) {
827 currCase.append(" case "+ref.allocSite+":\n {\n");
828 //The hash insert is here because we don't want to enqueue things unless we know it conflicts.
829 currCase.append(" if (" + queryVistedHashtable +"("+ currPtr + ")) {\n");
831 if (ref.child.getNumOfReachableParents() == 1 && !ref.child.isInsetVar) {
832 addChecker(taint, ref.child, cases, currCase, currPtr, pDepth + 1);
835 currCase.append(" " + addToQueueInC + childPtr + ");\n ");
837 currCase.append(" }\n"); //close for queryVistedHashtable
839 currCase.append("}\n"); //close for internal case statement
843 currCase.append(" default:\n" +
845 " }\n"); //internal switch.
848 private boolean qualifiesForCaseStatement(ConcreteRuntimeObjNode node) {
851 (node.isInsetVar && (node.decendantsConflict() || node.hasPrimitiveConflicts())) ||
852 //non-inline-able code cases
853 (node.getNumOfReachableParents() != 1 && node.decendantsConflict()) ||
854 //Cases where resumes are possible
855 (node.hasPotentialToBeIncorrectDueToConflict) && node.decendantsObjConflict);
858 private Taint getProperTaintForFlatSESEEnterNode(FlatSESEEnterNode rblock, VariableNode var,
859 Hashtable<Taint, Set<Effect>> effects) {
860 Set<Taint> taints = effects.keySet();
861 for (Taint t : taints) {
862 FlatSESEEnterNode sese = t.getSESE();
863 if(sese != null && sese.equals(rblock) && t.getVar().equals(var.getTempDescriptor())) {
871 private Taint getProperTaintForEnterNode(FlatNode stallSite, VariableNode var,
872 Hashtable<Taint, Set<Effect>> effects) {
873 Set<Taint> taints = effects.keySet();
874 for (Taint t : taints) {
875 FlatNode flatnode = t.getStallSite();
876 if(flatnode != null && flatnode.equals(stallSite) && t.getVar().equals(var.getTempDescriptor())) {
883 private void printDebug(boolean guard, String debugStatements) {
885 System.out.println(debugStatements);
888 private void enumerateHeaproots() {
889 weaklyConnectedHRCounter = 0;
890 num2WeaklyConnectedHRGroup = new ArrayList<WeaklyConectedHRGroup>();
892 for(Taint t: connectedHRHash.keySet()) {
893 if(connectedHRHash.get(t).id == -1) {
894 WeaklyConectedHRGroup hg = connectedHRHash.get(t);
895 hg.id = weaklyConnectedHRCounter;
896 num2WeaklyConnectedHRGroup.add(weaklyConnectedHRCounter, hg);
897 weaklyConnectedHRCounter++;
902 private void printoutTable(EffectsTable table) {
904 System.out.println("==============EFFECTS TABLE PRINTOUT==============");
905 for(AllocSite as: table.table.keySet()) {
906 System.out.println("\tFor AllocSite " + as.getUniqueAllocSiteID());
908 BucketOfEffects boe = table.table.get(as);
910 if(boe.potentiallyConflictingRoots != null && !boe.potentiallyConflictingRoots.isEmpty()) {
911 System.out.println("\t\tPotentially conflicting roots: ");
912 for(String key: boe.potentiallyConflictingRoots.keySet()) {
913 System.out.println("\t\t-Field: " + key);
914 System.out.println("\t\t\t" + boe.potentiallyConflictingRoots.get(key));
917 for(Taint t: boe.taint2EffectsGroup.keySet()) {
918 System.out.println("\t\t For Taint " + t);
919 EffectsGroup eg = boe.taint2EffectsGroup.get(t);
921 if(eg.hasPrimitiveConflicts()) {
922 System.out.print("\t\t\tPrimitive Conflicts at alloc " + as.getUniqueAllocSiteID() +" : ");
923 for(String field: eg.primitiveConflictingFields.keySet()) {
924 System.out.print(field + " ");
926 System.out.println();
928 for(String fieldKey: eg.myEffects.keySet()) {
929 CombinedObjEffects ce = eg.myEffects.get(fieldKey);
930 System.out.println("\n\t\t\tFor allocSite " + as.getUniqueAllocSiteID() + " && field " + fieldKey);
931 System.out.println("\t\t\t\tread " + ce.hasReadEffect + "/"+ce.hasReadConflict +
932 " write " + ce.hasWriteEffect + "/" + ce.hasWriteConflict +
933 " SU " + ce.hasStrongUpdateEffect + "/" + ce.hasStrongUpdateConflict);
934 for(Effect ef: ce.originalEffects) {
935 System.out.println("\t" + ef);
944 private class EffectsGroup {
945 Hashtable<String, CombinedObjEffects> myEffects;
946 Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
948 public EffectsGroup() {
949 myEffects = new Hashtable<String, CombinedObjEffects>();
950 primitiveConflictingFields = new Hashtable<String, CombinedObjEffects>();
953 public void addPrimitive(Effect e, boolean conflict) {
954 CombinedObjEffects effects;
955 if((effects = primitiveConflictingFields.get(e.getField().getSymbol())) == null) {
956 effects = new CombinedObjEffects();
957 primitiveConflictingFields.put(e.getField().getSymbol(), effects);
959 effects.add(e, conflict);
962 public void addObjEffect(Effect e, boolean conflict) {
963 CombinedObjEffects effects;
964 if((effects = myEffects.get(e.getField().getSymbol())) == null) {
965 effects = new CombinedObjEffects();
966 myEffects.put(e.getField().getSymbol(), effects);
968 effects.add(e, conflict);
971 public boolean isEmpty() {
972 return myEffects.isEmpty() && primitiveConflictingFields.isEmpty();
975 public boolean hasPrimitiveConflicts(){
976 return !primitiveConflictingFields.isEmpty();
979 public CombinedObjEffects getPrimEffect(String field) {
980 return primitiveConflictingFields.get(field);
983 public boolean hasObjectEffects() {
984 return !myEffects.isEmpty();
987 public CombinedObjEffects getObjEffect(String field) {
988 return myEffects.get(field);
992 //Is the combined effects for all effects with the same affectedAllocSite and field
993 private class CombinedObjEffects {
994 ArrayList<Effect> originalEffects;
996 public boolean hasReadEffect;
997 public boolean hasWriteEffect;
998 public boolean hasStrongUpdateEffect;
1000 public boolean hasReadConflict;
1001 public boolean hasWriteConflict;
1002 public boolean hasStrongUpdateConflict;
1005 public CombinedObjEffects() {
1006 originalEffects = new ArrayList<Effect>();
1008 hasReadEffect = false;
1009 hasWriteEffect = false;
1010 hasStrongUpdateEffect = false;
1012 hasReadConflict = false;
1013 hasWriteConflict = false;
1014 hasStrongUpdateConflict = false;
1017 public boolean add(Effect e, boolean conflict) {
1018 if(!originalEffects.add(e))
1021 switch(e.getType()) {
1023 hasReadEffect = true;
1024 hasReadConflict = conflict;
1027 hasWriteEffect = true;
1028 hasWriteConflict = conflict;
1030 case Effect.strongupdate:
1031 hasStrongUpdateEffect = true;
1032 hasStrongUpdateConflict = conflict;
1035 System.out.println("RCR ERROR: An Effect Type never seen before has been encountered");
1042 public boolean hasConflict() {
1043 return hasReadConflict || hasWriteConflict || hasStrongUpdateConflict;
1046 public void mergeWith(CombinedObjEffects other) {
1047 for(Effect e: other.originalEffects) {
1048 if(!originalEffects.contains(e)){
1049 originalEffects.add(e);
1053 hasReadEffect |= other.hasReadEffect;
1054 hasWriteEffect |= other.hasWriteEffect;
1055 hasStrongUpdateEffect |= other.hasStrongUpdateEffect;
1057 hasReadConflict |= other.hasReadConflict;
1058 hasWriteConflict |= other.hasWriteConflict;
1059 hasStrongUpdateConflict |= other.hasStrongUpdateConflict;
1063 //This will keep track of a reference
1064 private class ObjRef {
1067 CombinedObjEffects myEffects;
1069 //This keeps track of the parent that we need to pass by inorder to get
1070 //to the conflicting child (if there is one).
1071 ConcreteRuntimeObjNode child;
1073 public ObjRef(String fieldname,
1074 ConcreteRuntimeObjNode ref,
1075 CombinedObjEffects myEffects) {
1077 allocSite = ref.getAllocationSite();
1080 this.myEffects = myEffects;
1083 public boolean hasConflictsDownThisPath() {
1084 return child.decendantsObjConflict || child.decendantsPrimConflict || child.hasPrimitiveConflicts() || myEffects.hasConflict();
1087 public boolean hasDirectObjConflict() {
1088 return myEffects.hasConflict();
1091 public boolean equals(Object other) {
1092 if(other == null || !(other instanceof ObjRef))
1095 ObjRef o = (ObjRef) other;
1097 if(o.field == this.field && o.allocSite == this.allocSite && this.child.equals(o.child))
1103 public int hashCode() {
1104 return child.allocSite.hashCode() ^ field.hashCode();
1107 public void mergeWith(ObjRef ref) {
1108 myEffects.mergeWith(ref.myEffects);
1112 private class ConcreteRuntimeObjNode {
1113 Hashtable<String, ArrayList<ObjRef>> objectRefs;
1114 Hashtable<String, CombinedObjEffects> primitiveConflictingFields;
1115 HashSet<ConcreteRuntimeObjNode> parentsWithReadToNode;
1116 HashSet<ConcreteRuntimeObjNode> parentsThatWillLeadToConflicts;
1117 //this set keeps track of references down the line that need to be enqueued if traverser is "paused"
1118 HashSet<ConcreteRuntimeObjNode> enqueueToWaitingQueueUponConflict;
1119 boolean decendantsPrimConflict;
1120 boolean decendantsObjConflict;
1121 boolean hasPotentialToBeIncorrectDueToConflict;
1123 boolean isArrayElement;
1124 AllocSite allocSite;
1125 HeapRegionNode original;
1127 public ConcreteRuntimeObjNode(HeapRegionNode me, boolean isInVar, boolean isArrayElement) {
1128 objectRefs = new Hashtable<String, ArrayList<ObjRef>>(5);
1129 primitiveConflictingFields = null;
1130 parentsThatWillLeadToConflicts = new HashSet<ConcreteRuntimeObjNode>();
1131 parentsWithReadToNode = new HashSet<ConcreteRuntimeObjNode>();
1132 enqueueToWaitingQueueUponConflict = new HashSet<ConcreteRuntimeObjNode>();
1133 allocSite = me.getAllocSite();
1135 isInsetVar = isInVar;
1136 decendantsPrimConflict = false;
1137 decendantsObjConflict = false;
1138 hasPotentialToBeIncorrectDueToConflict = false;
1139 this.isArrayElement = isArrayElement;
1142 public void addReachableParent(ConcreteRuntimeObjNode curr) {
1143 parentsWithReadToNode.add(curr);
1147 public boolean equals(Object other) {
1148 if(other == null || !(other instanceof ConcreteRuntimeObjNode))
1151 return original.equals(((ConcreteRuntimeObjNode)other).original);
1154 public int getAllocationSite() {
1155 return allocSite.getUniqueAllocSiteID();
1158 public int getNumOfReachableParents() {
1159 return parentsThatWillLeadToConflicts.size();
1162 public boolean hasPrimitiveConflicts() {
1163 return primitiveConflictingFields != null && !primitiveConflictingFields.isEmpty();
1166 public boolean decendantsConflict() {
1167 return decendantsPrimConflict || decendantsObjConflict;
1171 //returns true if at least one of the objects in points of access has been added
1172 public boolean addPossibleWaitingQueueEnqueue(HashSet<ConcreteRuntimeObjNode> pointsOfAccess) {
1173 boolean addedNew = false;
1174 for(ConcreteRuntimeObjNode dec: pointsOfAccess) {
1175 if(dec != null && dec != this){
1176 addedNew = addedNew || enqueueToWaitingQueueUponConflict.add(dec);
1183 public boolean addPossibleWaitingQueueEnqueue(ConcreteRuntimeObjNode pointOfAccess) {
1184 if(pointOfAccess != null && pointOfAccess != this){
1185 return enqueueToWaitingQueueUponConflict.add(pointOfAccess);
1191 public void addObjChild(String field, ConcreteRuntimeObjNode child, CombinedObjEffects ce) {
1192 printDebug(javaDebug,this.allocSite.getUniqueAllocSiteID() + " added child at " + child.getAllocationSite());
1193 ObjRef ref = new ObjRef(field, child, ce);
1195 if(objectRefs.containsKey(field)){
1196 ArrayList<ObjRef> array = objectRefs.get(field);
1198 if(array.contains(ref)) {
1199 ObjRef other = array.get(array.indexOf(ref));
1200 other.mergeWith(ref);
1201 printDebug(javaDebug," Merged with old");
1202 printDebug(javaDebug," Old="+ other.child.original + "\n new="+ref.child.original);
1206 printDebug(javaDebug," Just added new;\n Field: " + field);
1207 printDebug(javaDebug," AllocSite: " + child.getAllocationSite());
1208 printDebug(javaDebug," Child: "+child.original);
1212 ArrayList<ObjRef> array = new ArrayList<ObjRef>(3);
1215 objectRefs.put(field, array);
1219 public boolean isObjectArray() {
1220 return original.getType().isArray() && !original.getType().isPrimitive() && !original.getType().isImmutable();
1223 public boolean canBeArrayElement() {
1224 return isArrayElement;
1227 public ArrayList<Integer> getReferencedAllocSites() {
1228 ArrayList<Integer> list = new ArrayList<Integer>();
1230 for(String key: objectRefs.keySet()) {
1231 for(ObjRef r: objectRefs.get(key)) {
1232 if(r.hasDirectObjConflict() || (r.child.parentsWithReadToNode.contains(this) && r.hasConflictsDownThisPath())) {
1233 list.add(r.allocSite);
1241 public String toString() {
1242 return "AllocSite=" + getAllocationSite() + " myConflict=" + !parentsThatWillLeadToConflicts.isEmpty() +
1243 " decCon="+decendantsObjConflict+
1244 " NumOfConParents=" + getNumOfReachableParents() + " ObjectChildren=" + objectRefs.size();
1248 private class EffectsTable {
1249 private Hashtable<AllocSite, BucketOfEffects> table;
1251 public EffectsTable(Hashtable<Taint, Set<Effect>> effects,
1252 Hashtable<Taint, Set<Effect>> conflicts) {
1253 table = new Hashtable<AllocSite, BucketOfEffects>();
1255 // rehash all effects (as a 5-tuple) by their affected allocation site
1256 for (Taint t : effects.keySet()) {
1257 Set<Effect> localConflicts = conflicts.get(t);
1258 for (Effect e : effects.get(t)) {
1259 BucketOfEffects bucket;
1260 if ((bucket = table.get(e.getAffectedAllocSite())) == null) {
1261 bucket = new BucketOfEffects();
1262 table.put(e.getAffectedAllocSite(), bucket);
1264 printDebug(javaDebug, "Added Taint" + t + " Effect " + e + "Conflict Status = " + (localConflicts!=null?localConflicts.contains(e):false)+" localConflicts = "+localConflicts);
1265 bucket.add(t, e, localConflicts!=null?localConflicts.contains(e):false);
1270 public EffectsGroup getEffects(AllocSite parentKey, Taint taint) {
1271 //This would get the proper bucket of effects and then get all the effects
1272 //for a parent for a specific taint
1274 return table.get(parentKey).taint2EffectsGroup.get(taint);
1276 catch (NullPointerException e) {
1281 // Run Analysis will walk the data structure and figure out the weakly
1282 // connected heap roots.
1283 public void runAnalysis() {
1285 printoutTable(this);
1288 for(AllocSite key: table.keySet()) {
1289 BucketOfEffects effects = table.get(key);
1290 //make sure there are actually conflicts in the bucket
1291 if(effects.potentiallyConflictingRoots != null && !effects.potentiallyConflictingRoots.isEmpty()){
1292 for(String field: effects.potentiallyConflictingRoots.keySet()){
1293 ArrayList<Taint> taints = effects.potentiallyConflictingRoots.get(field);
1294 //For simplicity, we just create a new group and add everything to it instead of
1295 //searching through all of them for the largest group and adding everyone in.
1296 WeaklyConectedHRGroup group = new WeaklyConectedHRGroup();
1297 group.add(taints); //This will automatically add the taint to the connectedHRhash
1304 private class WeaklyConectedHRGroup {
1305 HashSet<Taint> connectedHRs;
1306 //This is to keep track of unique waitingQueue positions for each allocsite.
1307 Hashtable<AllocSite, Integer> allocSiteToWaitingQueueMap;
1308 int waitingQueueCounter;
1311 public WeaklyConectedHRGroup() {
1312 connectedHRs = new HashSet<Taint>();
1313 id = -1; //this will be later modified
1314 waitingQueueCounter = 0;
1315 allocSiteToWaitingQueueMap = new Hashtable<AllocSite, Integer>();
1318 public void add(ArrayList<Taint> list) {
1319 for(Taint t: list) {
1324 public int getWaitingQueueBucketNum(ConcreteRuntimeObjNode node) {
1325 if(allocSiteToWaitingQueueMap.containsKey(node.allocSite)) {
1326 return allocSiteToWaitingQueueMap.get(node.allocSite);
1328 allocSiteToWaitingQueueMap.put(node.allocSite, waitingQueueCounter);
1329 return waitingQueueCounter++;
1333 public void add(Taint t) {
1334 connectedHRs.add(t);
1335 WeaklyConectedHRGroup oldGroup = connectedHRHash.get(t);
1336 connectedHRHash.put(t, this); //put new group into hash
1337 //If the taint was already in another group, move all its buddies over.
1338 if(oldGroup != this && oldGroup != null) {
1339 Iterator<Taint> it = oldGroup.connectedHRs.iterator();
1342 while((relatedTaint = it.next()) != null && !connectedHRs.contains(relatedTaint)) {
1343 this.add(relatedTaint);
1349 //This is a class that stores all the effects for an affected allocation site
1350 //across ALL taints. The structure is a hashtable of EffectGroups (see above) hashed
1351 //by a Taint. This way, I can keep EffectsGroups so I can reuse most to all of my old code
1352 //and allows for easier tracking of effects. In addition, a hashtable (keyed by the string
1353 //of the field access) keeps track of an ArrayList of taints of SESEblocks that conflict on that
1355 private class BucketOfEffects {
1356 // This table is used for lookup while creating the traversal.
1357 Hashtable<Taint, EffectsGroup> taint2EffectsGroup;
1359 //This table is used to help identify weakly connected groups: Contains ONLY
1360 //conflicting effects AND is only initialized when needed
1361 //String stores the field
1362 Hashtable<String, ArrayList<Taint>> potentiallyConflictingRoots;
1364 public BucketOfEffects() {
1365 taint2EffectsGroup = new Hashtable<Taint, EffectsGroup>();
1368 public void add(Taint t, Effect e, boolean conflict) {
1369 EffectsGroup effectsForGivenTaint;
1371 if ((effectsForGivenTaint = taint2EffectsGroup.get(t)) == null) {
1372 effectsForGivenTaint = new EffectsGroup();
1373 taint2EffectsGroup.put(t, effectsForGivenTaint);
1376 if (e.getField().getType().isPrimitive()) {
1378 effectsForGivenTaint.addPrimitive(e, true);
1381 effectsForGivenTaint.addObjEffect(e, conflict);
1385 if(potentiallyConflictingRoots == null) {
1386 potentiallyConflictingRoots = new Hashtable<String, ArrayList<Taint>>();
1389 ArrayList<Taint> taintsForField = potentiallyConflictingRoots.get(e.getField().getSafeSymbol());
1390 if(taintsForField == null) {
1391 taintsForField = new ArrayList<Taint>();
1392 potentiallyConflictingRoots.put(e.getField().getSafeSymbol(), taintsForField);
1395 if(!taintsForField.contains(t)) {
1396 taintsForField.add(t);
1402 private class TaintAndInternalHeapStructure {
1404 public Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap;
1406 public TaintAndInternalHeapStructure(Taint taint, Hashtable<Integer, ConcreteRuntimeObjNode> nodesInHeap) {
1408 this.nodesInHeap = nodesInHeap;
1412 private class TraversalInfo {
1414 public ReachGraph rg;
1415 public TempDescriptor invar;
1417 public TraversalInfo(FlatNode fn, ReachGraph g) {
1423 public TraversalInfo(FlatNode fn, ReachGraph rg2, TempDescriptor tempDesc) {