001// Main routine for Daikon invariant detector 002// For documentation, see file doc/daikon.html in the distribution. 003 004package daikon; 005 006import static java.util.logging.Level.FINE; 007import static java.util.logging.Level.FINER; 008import static java.util.logging.Level.INFO; 009 010import daikon.config.Configuration; 011import daikon.derive.Derivation; 012import daikon.inv.Equality; 013import daikon.inv.Invariant; 014import daikon.inv.OutputFormat; 015import daikon.inv.binary.sequenceScalar.Member; 016import daikon.inv.binary.sequenceScalar.MemberFloat; 017import daikon.inv.binary.sequenceScalar.SeqFloatEqual; 018import daikon.inv.binary.sequenceScalar.SeqFloatGreaterEqual; 019import daikon.inv.binary.sequenceScalar.SeqFloatGreaterThan; 020import daikon.inv.binary.sequenceScalar.SeqFloatLessEqual; 021import daikon.inv.binary.sequenceScalar.SeqFloatLessThan; 022import daikon.inv.binary.sequenceScalar.SeqIntEqual; 023import daikon.inv.binary.sequenceScalar.SeqIntGreaterEqual; 024import daikon.inv.binary.sequenceScalar.SeqIntGreaterThan; 025import daikon.inv.binary.sequenceScalar.SeqIntLessEqual; 026import daikon.inv.binary.sequenceScalar.SeqIntLessThan; 027import daikon.inv.binary.sequenceString.MemberString; 028import daikon.inv.binary.twoScalar.FloatEqual; 029import daikon.inv.binary.twoScalar.FloatGreaterEqual; 030import daikon.inv.binary.twoScalar.FloatGreaterThan; 031import daikon.inv.binary.twoScalar.FloatLessEqual; 032import daikon.inv.binary.twoScalar.FloatLessThan; 033import daikon.inv.binary.twoScalar.FloatNonEqual; 034import daikon.inv.binary.twoScalar.IntEqual; 035import daikon.inv.binary.twoScalar.IntGreaterEqual; 036import daikon.inv.binary.twoScalar.IntGreaterThan; 037import daikon.inv.binary.twoScalar.IntLessEqual; 038import daikon.inv.binary.twoScalar.IntLessThan; 039import daikon.inv.binary.twoScalar.IntNonEqual; 040import daikon.inv.binary.twoScalar.LinearBinary; 041import daikon.inv.binary.twoScalar.LinearBinaryFloat; 042import daikon.inv.binary.twoScalar.NumericFloat; 043import daikon.inv.binary.twoScalar.NumericInt; 044import daikon.inv.binary.twoSequence.PairwiseFloatEqual; 045import daikon.inv.binary.twoSequence.PairwiseFloatGreaterEqual; 046import daikon.inv.binary.twoSequence.PairwiseFloatGreaterThan; 047import daikon.inv.binary.twoSequence.PairwiseFloatLessEqual; 048import daikon.inv.binary.twoSequence.PairwiseFloatLessThan; 049import daikon.inv.binary.twoSequence.PairwiseIntEqual; 050import daikon.inv.binary.twoSequence.PairwiseIntGreaterEqual; 051import daikon.inv.binary.twoSequence.PairwiseIntGreaterThan; 052import daikon.inv.binary.twoSequence.PairwiseIntLessEqual; 053import daikon.inv.binary.twoSequence.PairwiseIntLessThan; 054import daikon.inv.binary.twoSequence.PairwiseLinearBinary; 055import daikon.inv.binary.twoSequence.PairwiseLinearBinaryFloat; 056import daikon.inv.binary.twoSequence.PairwiseNumericFloat; 057import daikon.inv.binary.twoSequence.PairwiseNumericInt; 058import daikon.inv.binary.twoSequence.PairwiseString; 059import daikon.inv.binary.twoSequence.PairwiseStringEqual; 060import daikon.inv.binary.twoSequence.PairwiseStringGreaterEqual; 061import daikon.inv.binary.twoSequence.PairwiseStringGreaterThan; 062import daikon.inv.binary.twoSequence.PairwiseStringLessEqual; 063import daikon.inv.binary.twoSequence.PairwiseStringLessThan; 064import daikon.inv.binary.twoSequence.Reverse; 065import daikon.inv.binary.twoSequence.ReverseFloat; 066import daikon.inv.binary.twoSequence.SeqSeqFloatEqual; 067import daikon.inv.binary.twoSequence.SeqSeqFloatGreaterEqual; 068import daikon.inv.binary.twoSequence.SeqSeqFloatGreaterThan; 069import daikon.inv.binary.twoSequence.SeqSeqFloatLessEqual; 070import daikon.inv.binary.twoSequence.SeqSeqFloatLessThan; 071import daikon.inv.binary.twoSequence.SeqSeqIntEqual; 072import daikon.inv.binary.twoSequence.SeqSeqIntGreaterEqual; 073import daikon.inv.binary.twoSequence.SeqSeqIntGreaterThan; 074import daikon.inv.binary.twoSequence.SeqSeqIntLessEqual; 075import daikon.inv.binary.twoSequence.SeqSeqIntLessThan; 076import daikon.inv.binary.twoSequence.SeqSeqStringEqual; 077import daikon.inv.binary.twoSequence.SeqSeqStringGreaterEqual; 078import daikon.inv.binary.twoSequence.SeqSeqStringGreaterThan; 079import daikon.inv.binary.twoSequence.SeqSeqStringLessEqual; 080import daikon.inv.binary.twoSequence.SeqSeqStringLessThan; 081import daikon.inv.binary.twoSequence.SubSequence; 082import daikon.inv.binary.twoSequence.SubSequenceFloat; 083import daikon.inv.binary.twoSequence.SubSet; 084import daikon.inv.binary.twoSequence.SubSetFloat; 085import daikon.inv.binary.twoSequence.SuperSequence; 086import daikon.inv.binary.twoSequence.SuperSequenceFloat; 087import daikon.inv.binary.twoSequence.SuperSet; 088import daikon.inv.binary.twoSequence.SuperSetFloat; 089import daikon.inv.binary.twoString.StdString; 090import daikon.inv.binary.twoString.StringEqual; 091import daikon.inv.binary.twoString.StringGreaterEqual; 092import daikon.inv.binary.twoString.StringGreaterThan; 093import daikon.inv.binary.twoString.StringLessEqual; 094import daikon.inv.binary.twoString.StringLessThan; 095import daikon.inv.binary.twoString.StringNonEqual; 096import daikon.inv.ternary.threeScalar.FunctionBinary; 097import daikon.inv.ternary.threeScalar.FunctionBinaryFloat; 098import daikon.inv.ternary.threeScalar.LinearTernary; 099import daikon.inv.ternary.threeScalar.LinearTernaryFloat; 100import daikon.inv.unary.scalar.CompleteOneOfScalar; 101import daikon.inv.unary.scalar.IsPointer; 102import daikon.inv.unary.scalar.LowerBound; 103import daikon.inv.unary.scalar.LowerBoundFloat; 104import daikon.inv.unary.scalar.Modulus; 105import daikon.inv.unary.scalar.NonModulus; 106import daikon.inv.unary.scalar.NonZero; 107import daikon.inv.unary.scalar.NonZeroFloat; 108import daikon.inv.unary.scalar.OneOfFloat; 109import daikon.inv.unary.scalar.OneOfScalar; 110import daikon.inv.unary.scalar.RangeFloat; 111import daikon.inv.unary.scalar.RangeInt; 112import daikon.inv.unary.scalar.UpperBound; 113import daikon.inv.unary.scalar.UpperBoundFloat; 114import daikon.inv.unary.sequence.CommonFloatSequence; 115import daikon.inv.unary.sequence.CommonSequence; 116import daikon.inv.unary.sequence.EltLowerBound; 117import daikon.inv.unary.sequence.EltLowerBoundFloat; 118import daikon.inv.unary.sequence.EltNonZero; 119import daikon.inv.unary.sequence.EltNonZeroFloat; 120import daikon.inv.unary.sequence.EltOneOf; 121import daikon.inv.unary.sequence.EltOneOfFloat; 122import daikon.inv.unary.sequence.EltRangeFloat; 123import daikon.inv.unary.sequence.EltRangeInt; 124import daikon.inv.unary.sequence.EltUpperBound; 125import daikon.inv.unary.sequence.EltUpperBoundFloat; 126import daikon.inv.unary.sequence.EltwiseFloatEqual; 127import daikon.inv.unary.sequence.EltwiseFloatGreaterEqual; 128import daikon.inv.unary.sequence.EltwiseFloatGreaterThan; 129import daikon.inv.unary.sequence.EltwiseFloatLessEqual; 130import daikon.inv.unary.sequence.EltwiseFloatLessThan; 131import daikon.inv.unary.sequence.EltwiseIntEqual; 132import daikon.inv.unary.sequence.EltwiseIntGreaterEqual; 133import daikon.inv.unary.sequence.EltwiseIntGreaterThan; 134import daikon.inv.unary.sequence.EltwiseIntLessEqual; 135import daikon.inv.unary.sequence.EltwiseIntLessThan; 136import daikon.inv.unary.sequence.NoDuplicates; 137import daikon.inv.unary.sequence.NoDuplicatesFloat; 138import daikon.inv.unary.sequence.OneOfFloatSequence; 139import daikon.inv.unary.sequence.OneOfSequence; 140import daikon.inv.unary.sequence.SeqIndexFloatEqual; 141import daikon.inv.unary.sequence.SeqIndexFloatGreaterEqual; 142import daikon.inv.unary.sequence.SeqIndexFloatGreaterThan; 143import daikon.inv.unary.sequence.SeqIndexFloatLessEqual; 144import daikon.inv.unary.sequence.SeqIndexFloatLessThan; 145import daikon.inv.unary.sequence.SeqIndexFloatNonEqual; 146import daikon.inv.unary.sequence.SeqIndexIntEqual; 147import daikon.inv.unary.sequence.SeqIndexIntGreaterEqual; 148import daikon.inv.unary.sequence.SeqIndexIntGreaterThan; 149import daikon.inv.unary.sequence.SeqIndexIntLessEqual; 150import daikon.inv.unary.sequence.SeqIndexIntLessThan; 151import daikon.inv.unary.sequence.SeqIndexIntNonEqual; 152import daikon.inv.unary.string.CompleteOneOfString; 153import daikon.inv.unary.string.OneOfString; 154import daikon.inv.unary.string.PrintableString; 155import daikon.inv.unary.stringsequence.CommonStringSequence; 156import daikon.inv.unary.stringsequence.EltOneOfString; 157import daikon.inv.unary.stringsequence.OneOfStringSequence; 158import daikon.simplify.LemmaStack; 159import daikon.split.ContextSplitterFactory; 160import daikon.split.PptSplitter; 161import daikon.split.SpinfoFile; 162import daikon.split.Splitter; 163import daikon.split.SplitterFactory; 164import daikon.split.SplitterList; 165import daikon.suppress.NIS; 166import daikon.suppress.NIS.SuppressionProcessor; 167import gnu.getopt.Getopt; 168import gnu.getopt.LongOpt; 169import java.io.File; 170import java.io.FileInputStream; 171import java.io.IOException; 172import java.io.InputStream; 173import java.io.LineNumberReader; 174import java.lang.reflect.Field; 175import java.lang.reflect.Method; 176import java.time.LocalDateTime; 177import java.time.ZoneId; 178import java.util.ArrayList; 179import java.util.Collection; 180import java.util.ConcurrentModificationException; 181import java.util.HashSet; 182import java.util.Iterator; 183import java.util.LinkedHashMap; 184import java.util.LinkedHashSet; 185import java.util.List; 186import java.util.Map; 187import java.util.Set; 188import java.util.TreeSet; 189import java.util.concurrent.TimeUnit; 190import java.util.logging.Logger; 191import java.util.regex.Matcher; 192import java.util.regex.Pattern; 193import java.util.regex.PatternSyntaxException; 194import org.checkerframework.checker.interning.qual.Interned; 195import org.checkerframework.checker.nullness.qual.EnsuresNonNull; 196import org.checkerframework.checker.nullness.qual.KeyFor; 197import org.checkerframework.checker.nullness.qual.MonotonicNonNull; 198import org.checkerframework.checker.nullness.qual.NonNull; 199import org.checkerframework.checker.nullness.qual.Nullable; 200import org.checkerframework.checker.nullness.qual.RequiresNonNull; 201import org.checkerframework.checker.signature.qual.ClassGetName; 202import org.checkerframework.dataflow.qual.Pure; 203import org.plumelib.util.EntryReader; 204import org.plumelib.util.FilesPlume; 205import org.plumelib.util.RegexUtil; 206import org.plumelib.util.StringsPlume; 207import typequals.prototype.qual.Prototype; 208 209/** 210 * The {@link #main} method is the main entry point for the Daikon invariant detector. The {@link 211 * #mainHelper} method is the entry point, when called programmatically. 212 */ 213public final class Daikon { 214 215 private Daikon() { 216 throw new UnsupportedOperationException("do not instantiate"); 217 } 218 219 /** 220 * The amount of time to wait between updates of the progress display, measured in milliseconds. A 221 * value of -1 means do not print the progress display at all. 222 */ 223 public static int dkconfig_progress_delay = 1000; 224 225 /** The current version of Daikon. */ 226 public static final String release_version = "5.9.2"; 227 228 /** The date for the current version of Daikon. */ 229 public static final String release_date = "December 1, 2026"; 230 231 /** A description of the Daikon release (version number, date, and URL). */ 232 public static final String release_string = 233 "Daikon version " 234 + release_version 235 + ", released " 236 + release_date 237 + "; https://plse.cs.washington.edu/daikon."; 238 239 // Variables starting with dkconfig_ should only be set via the 240 // daikon.config.Configuration interface. 241 /** Boolean. Controls whether conditional program points are displayed. */ 242 public static boolean dkconfig_output_conditionals = true; 243 244 // Variables starting with dkconfig_ should only be set via the 245 // daikon.config.Configuration interface. 246 /** Boolean. Just print the total number of possible invariants and exit. */ 247 public static boolean dkconfig_calc_possible_invs; 248 249 /** 250 * Integer. Percentage of program points to process. All program points are sorted by name, and 251 * all samples for the first {@code ppt_perc} program points are processed. A percentage of 100 252 * matches all program points. 253 */ 254 public static int dkconfig_ppt_perc = 100; 255 256 /** 257 * Boolean. Controls whether or not the total samples read and processed are printed at the end of 258 * processing. 259 */ 260 public static boolean dkconfig_print_sample_totals = false; 261 262 // All these variables really need to be organized better. 263 264 public static final String lineSep = Global.lineSep; 265 266 /** 267 * Boolean. Controls whether or not processing information is printed out. Setting this variable 268 * to true also automatically sets {@code progress_delay} to -1. 269 */ 270 public static boolean dkconfig_quiet = false; 271 272 // Change this at your peril; high costs in time and space for "false", 273 // because so many more invariants get instantiated. 274 public static final boolean check_program_types = true; 275 276 // Problem with setting this to true: 277 // get no invariants over any value that can ever be missing 278 // Problem with setting this to false: 279 // due to different number of samples, isEqualityComparison is 280 // non-transitive (that is specially handled in the code) 281 public static final boolean invariants_check_canBeMissing = false; 282 283 // Specialized version for array elements; only examined if 284 // invariants_check_canBeMissing is false 285 public static final boolean invariants_check_canBeMissing_arrayelt = true; 286 287 public static final boolean disable_modbit_check_message = false; 288 289 /** 290 * Not a good idea to set this to true, as it is too easy to ignore the warnings and the modbit 291 * problem can cause an error later. 292 */ 293 public static final boolean disable_modbit_check_error = false; 294 295 /** When true, don't print textual output. */ 296 public static boolean no_text_output = false; 297 298 /** 299 * When true, show how much time each Daikon phase took. Has no effect if System.console() is not 300 * connected to a terminal. If option show-detail-progress was used, also show how much time each 301 * program point took. 302 */ 303 public static boolean show_progress = false; 304 305 /** 306 * If true, use the "new" equality set mechanism for handling equality, using canonicals to have 307 * instantiation of invariants only over equality sets. 308 */ 309 public static boolean use_equality_optimization = true; 310 311 /** 312 * Boolean. Controls whether the Daikon optimizations (equality sets, suppressions) are undone at 313 * the end to create a more complete set of invariants. Output does not include conditional 314 * program points, implications, reflexive and partially reflexive invariants. 315 */ 316 public static boolean dkconfig_undo_opts = false; 317 318 /** 319 * Boolean. Indicates to Daikon classes and methods that the methods calls should be compatible to 320 * DaikonSimple because Daikon and DaikonSimple share methods. Default value is 'false'. 321 */ 322 public static boolean using_DaikonSimple = false; 323 324 /** 325 * If "always", then invariants are always guarded. If "never", then invariants are never guarded. 326 * If "missing", then invariants are guarded only for variables that were missing ("can be 327 * missing") in the dtrace (the observed executions). If "default", then use "missing" mode for 328 * Java output and "never" mode otherwise. 329 * 330 * <p>Guarding means adding predicates that ensure that variables can be dereferenced. For 331 * instance, if {@code a} can be null --- that is, if {@code a.b} can be nonsensical --- then the 332 * guarded version of 333 * 334 * <pre>a.b == 5</pre> 335 * 336 * is 337 * 338 * <pre>(a != null) ⇒ (a.b == 5)</pre> 339 * 340 * . 341 * 342 * <p>(To do: Some configuration option (maybe this one) should add guards for other reasons that 343 * lead to nonsensical values (@pxref{Variable names}).) <br> 344 * @cindex nonsensical values for variables, guarding 345 */ 346 // Perhaps a better default would be "missing". 347 public static @Interned String dkconfig_guardNulls = "default"; 348 349 /** 350 * If true, associate the program points in a dataflow hierarchy, as via Nimmer's thesis. 351 * Deactivate only for languages and analyses where flow relation is nonsensical. 352 */ 353 public static boolean use_dataflow_hierarchy = true; 354 355 /** 356 * If true, use the bottom up implementation of the dataflow hierarchy. This mechanism builds 357 * invariants initially only at the leaves of the partial order. Upper points are calculated by 358 * joining the invariants from each of their children points. 359 */ 360 // public static boolean dkconfig_df_bottom_up = true; 361 362 // When true, use the Simplify theorem prover (not part of Daikon) 363 // to locate logically redundant invariants, and flag them as 364 // redundant, so that they are removed from the printed output. 365 public static boolean suppress_redundant_invariants_with_simplify = false; 366 367 public static OutputFormat output_format = OutputFormat.DAIKON; 368 369 // When true, output numbers of values and samples (also names of variables) 370 public static boolean output_num_samples = false; 371 372 public static boolean ignore_comparability = false; 373 374 // Controls which program points/variables are used/ignored. 375 public static @Nullable Pattern ppt_regexp; 376 public static @Nullable Pattern ppt_omit_regexp; 377 public static @Nullable Pattern var_regexp; 378 public static @Nullable Pattern var_omit_regexp; 379 380 /** 381 * If set, only ppts less than ppt_max_name are included. Used by the configuration option 382 * dkconfig_ppt_percent to only work on a specified percent of the ppts. 383 */ 384 public static @Nullable String ppt_max_name = null; 385 386 // The invariants detected will be serialized and written to this 387 // file. 388 public static @Nullable File inv_file; 389 390 // Whether we want the memory monitor activated 391 private static boolean use_mem_monitor = false; 392 393 /** True if Daikon should print its version number and date. */ 394 public static boolean noversion_output = false; 395 396 /** True if Daikon is in its inferencing loop. Used only for assertion checks. */ 397 public static boolean isInferencing = false; 398 399 /** 400 * When true, omit certain invariants from the output {@code .inv} file. Generally these are 401 * invariants that wouldn't be printed in any case; but by default, they're retained in the {@code 402 * .inv} file in case they would be useful for later processing. (For instance, we might at some 403 * point in the future support resuming processing with more data from an {@code .inv} file). 404 * These invariants can increase the size of the {@code .inv} file, though, so when only limited 405 * further processing is needed, it can save space to omit them. 406 */ 407 public static boolean omit_from_output = false; 408 409 /** 410 * An array of flags, indexed by characters, in which a true entry means that invariants of that 411 * sort should be omitted from the output {@code .inv} file. 412 */ 413 public static boolean[] omit_types = new boolean[256]; 414 415 // Command-line options / command-line arguments 416 // These variables are public so other programs can reuse the same 417 // command-line options. 418 419 /** option help. */ 420 public static final String help_SWITCH = "help"; 421 422 // "-o" switch: file to which serialized output is written 423 /** option no-text-output. */ 424 public static final String no_text_output_SWITCH = "no_text_output"; 425 426 /** option format. */ 427 public static final String format_SWITCH = "format"; 428 429 /** option show-progress. */ 430 public static final String show_progress_SWITCH = "show_progress"; 431 432 /** option show-detail-progress. */ 433 public static final String show_detail_progress_SWITCH = "show_detail_progress"; 434 435 /** option no-show-progress. */ 436 public static final String no_show_progress_SWITCH = "no_show_progress"; 437 438 /** option noversion. */ 439 public static final String noversion_SWITCH = "noversion"; 440 441 public static final String output_num_samples_SWITCH = "output_num_samples"; 442 public static final String files_from_SWITCH = "files_from"; 443 public static final String omit_from_output_SWITCH = "omit_from_output"; 444 // Control invariant detection 445 public static final String conf_limit_SWITCH = "conf_limit"; 446 public static final String list_type_SWITCH = "list_type"; 447 public static final String user_defined_invariant_SWITCH = "user-defined-invariant"; 448 public static final String disable_all_invariants_SWITCH = "disable-all-invariants"; 449 public static final String no_dataflow_hierarchy_SWITCH = "nohierarchy"; 450 public static final String suppress_redundant_SWITCH = "suppress_redundant"; 451 // Process only part of the trace file 452 public static final String ppt_regexp_SWITCH = "ppt-select-pattern"; 453 public static final String ppt_omit_regexp_SWITCH = "ppt-omit-pattern"; 454 public static final String var_regexp_SWITCH = "var-select-pattern"; 455 public static final String var_omit_regexp_SWITCH = "var-omit-pattern"; 456 // Configuration options 457 public static final String server_SWITCH = 458 "server"; // YOAV: server mode for Daikon: reads dtrace files as they appear 459 public static final String config_SWITCH = "config"; 460 public static final String config_option_SWITCH = "config_option"; 461 // Debugging 462 public static final String debugAll_SWITCH = "debug"; 463 public static final String debug_SWITCH = "dbg"; 464 public static final String track_SWITCH = "track"; 465 public static final String disc_reason_SWITCH = "disc_reason"; 466 public static final String mem_stat_SWITCH = "mem_stat"; 467 public static final String wrap_xml_SWITCH = "wrap_xml"; 468 469 /** 470 * Regular expression that matches class names in the format expected by {@link 471 * Class#forName(String)}. 472 */ 473 // This regular expression is taken from 474 // checker-framework/checker/src/org/checkerframework/checker/signature/qual/ClassGetName.java 475 // . It's a bit too lenient since we don't need to permit arrays and 476 // primitives. 477 private static final String classGetNameRegex = 478 "(^[A-Za-z_][A-Za-z_0-9]*(\\.[A-Za-z_][A-Za-z_0-9]*)*(\\$[A-Za-z_0-9]+)*$)|^\\[+([BCDFIJSZ]|L[A-Za-z_][A-Za-z_0-9]*(\\.[A-Za-z_][A-Za-z_0-9]*)*(\\$[A-Za-z_0-9]+)*;)$"; 479 480 private static final Pattern classGetNamePattern; 481 482 static { 483 try { 484 classGetNamePattern = Pattern.compile(classGetNameRegex); 485 } catch (PatternSyntaxException e) { 486 // This shouldn't happen because classGetNameRegex is a legal regex 487 throw new Error(e); 488 } 489 } 490 491 public static @MonotonicNonNull File server_dir = 492 null; // YOAV: the directory from which we read the dtrace files 493 494 /** 495 * A PptMap (mapping from String to PptTopLevel) that contains all the program points. Set in 496 * mainHelper(). 497 */ 498 @SuppressWarnings("nullness:initialization.static.field.uninitialized") // set in mainHelper() 499 public static PptMap all_ppts; 500 501 /** current invariant (used for debugging) */ 502 public static @Nullable Invariant current_inv = null; 503 504 /* List of prototype invariants (one for each type of invariant) */ 505 public static ArrayList<@Prototype Invariant> proto_invs = new ArrayList<>(); 506 507 /** Debug tracer. */ 508 public static final Logger debugTrace = Logger.getLogger("daikon.Daikon"); 509 510 public static final Logger debugProgress = Logger.getLogger("daikon.Progress"); 511 512 public static final Logger debugEquality = Logger.getLogger("daikon.Equality"); 513 514 /** Debug tracer for ppt initialization. */ 515 public static final Logger debugInit = Logger.getLogger("daikon.init"); 516 517 /** Prints out statistics concerning equality sets, suppressions, etc. */ 518 public static final Logger debugStats = Logger.getLogger("daikon.stats"); 519 520 /** The usage message for this program. */ 521 public static final String usage = 522 StringsPlume.joinLines( 523 release_string, 524 // "Uses the Java port of GNU getopt, copyright (c) 1998 Aaron M. Renn", 525 // "For licensing information, see the License section of the manual.", 526 "Usage:", 527 " java daikon.Daikon [flags...] files...", 528 " Each file is a declaration file or a data trace file; the file type", 529 " is determined by the file name (containing \".decls\" or \".dtrace\").", 530 " For a list of flags, see the Daikon manual, which appears in the ", 531 " Daikon distribution and also at https://plse.cs.washington.edu/daikon/."); 532 533 /** Indicates the need for Daikon to terminate. */ 534 public abstract static class DaikonTerminationException extends RuntimeException { 535 static final long serialVersionUID = 20180729L; 536 537 protected DaikonTerminationException() { 538 super(); 539 } 540 541 protected DaikonTerminationException(String message) { 542 super(message); 543 } 544 545 protected DaikonTerminationException(Throwable e) { 546 super(e); 547 } 548 549 protected DaikonTerminationException(String message, Throwable e) { 550 super(message, e); 551 } 552 } 553 554 /** Indicates that Daikon has terminated normally. */ 555 public static class NormalTermination extends DaikonTerminationException { 556 static final long serialVersionUID = 20180729L; 557 558 public NormalTermination(String message) { 559 super(message); 560 } 561 562 public NormalTermination() { 563 super(); 564 } 565 } 566 567 /** 568 * Indicates that Daikon has terminated abnormally, indicating a bug in Daikon. Also used to 569 * indicate a situation that should not happen. 570 */ 571 public static class BugInDaikon extends DaikonTerminationException { 572 static final long serialVersionUID = 20180729L; 573 574 public BugInDaikon(String message) { 575 super(message); 576 } 577 578 public BugInDaikon(Throwable e) { 579 super(e); 580 } 581 582 public BugInDaikon(String message, Throwable e) { 583 super(message, e); 584 } 585 } 586 587 /** 588 * Indicates a user error. Thrown to indicate that main should not print a stack trace, but only 589 * print the message itself to the user. 590 * 591 * <p>Code in Daikon should throw other exceptions such as BugInDaikon in cases of a Daikon bug or 592 * a system problem (like unpredictable IOExceptions). If the string is null, then this is normal 593 * termination, not an error; no message is printed. 594 */ 595 public static class UserError extends DaikonTerminationException { 596 static final long serialVersionUID = 20050923L; 597 598 public static String error_at_line_file(LineNumberReader reader, String filename, Throwable e) { 599 String msg = e.getMessage(); 600 if (msg == null) { 601 msg = " of type " + e.getClass() + " with no detail message"; 602 } 603 return error_at_line_file(reader, filename, msg); 604 } 605 606 public static String error_at_line_file(LineNumberReader reader, String filename, String msg) { 607 if (msg == null) { 608 throw new Error("Null message supplied to error_at_line_file()"); 609 } 610 return "Error at line " + reader.getLineNumber() + " in file " + filename + ": " + msg; 611 } 612 613 // Constructors that take a Throwable 614 615 // Requires that e.getMessage() != null. 616 public UserError(Throwable e) { 617 super(e.getMessage() == null ? e.toString() : e.getMessage(), e); 618 } 619 620 public UserError(Throwable e, String msg) { 621 super( 622 ((e.getMessage() != null && msg.contains(e.getMessage())) 623 ? msg 624 : msg + ": " + e.getMessage()), 625 e); 626 } 627 628 public UserError(Throwable e, FileIO.ParseState state) { 629 this(e, error_at_line_file(state.reader, state.filename, e)); 630 } 631 632 public UserError(Throwable e, LineNumberReader reader, String filename) { 633 this(e, error_at_line_file(reader, filename, e)); 634 } 635 636 public UserError(Throwable e, String msg, LineNumberReader reader, String filename) { 637 this(e, error_at_line_file(reader, filename, msg)); 638 } 639 640 // Constructors that do not take a Throwable 641 642 /** Creates a UserError with no details. */ 643 public UserError() { 644 super(""); 645 } 646 647 public UserError(String s) { 648 super(s); 649 } 650 651 public UserError(String msg, FileIO.ParseState state) { 652 super(error_at_line_file(state.reader, state.filename, msg)); 653 } 654 655 public UserError(String msg, LineNumberReader reader, String filename) { 656 super(error_at_line_file(reader, filename, msg)); 657 } 658 // This constructor is too error-prone: it leads to throwing away 659 // subsequent args if there are not enough % directives in the string. 660 // public UserError(String format, @Nullable Object... args) { 661 // super (String.format (format, args)); 662 // } 663 } 664 665 /** A parser error that should be reported, with better context, by the caller. */ 666 public static class ParseError extends Exception { 667 static final long serialVersionUID = 20181021L; 668 669 ParseError(String s) { 670 super(s); 671 } 672 } 673 674 /** 675 * The arguments to daikon.Daikon are file names. Declaration file names end in ".decls", and data 676 * trace file names end in ".dtrace". 677 */ 678 public static void main(final String[] args) { 679 try { 680 mainHelper(args); 681 } catch (DaikonTerminationException e) { 682 handleDaikonTerminationException(e); 683 } 684 } 685 686 /** 687 * Handle DaikonTerminationExceptions. Others are left to be handled by the default handler, which 688 * prints a more informative stack trace. 689 */ 690 public static void handleDaikonTerminationException(DaikonTerminationException e) { 691 if (e instanceof NormalTermination) { 692 System.out.println(); 693 if (e.getMessage() != null) { 694 System.out.println(e.getMessage()); 695 } 696 System.exit(0); 697 } else if (e instanceof UserError) { 698 System.err.println(); 699 System.err.println(e.getMessage()); 700 if (Debug.dkconfig_show_stack_trace) { 701 e.printStackTrace(); 702 } 703 System.exit(1); 704 } else if (e instanceof BugInDaikon) { 705 System.err.println(); 706 System.err.println("Bug in Daikon. Please report."); 707 e.printStackTrace(System.err); 708 System.err.println("Bug in Daikon. Please report."); 709 System.exit(2); 710 } else { 711 // This case should never be executed. 712 System.err.println(); 713 System.err.println("Unknown problem in Daikon. Please report."); 714 e.printStackTrace(System.err); 715 System.err.println("Unknown problem in Daikon. Please report."); 716 System.exit(2); 717 } 718 } 719 720 /** 721 * This does the work of {@link #main}, but it never calls System.exit, so it is appropriate to be 722 * called programmatically. 723 * 724 * @param args the command-line arguments 725 */ 726 @SuppressWarnings("SystemConsoleNull") // https://errorprone.info/bugpattern/SystemConsoleNull 727 public static void mainHelper(final String[] args) { 728 long startTime = System.nanoTime(); 729 long duration; 730 731 // Cleanup from any previous runs 732 cleanup(); 733 734 // Read command line options 735 FileOptions files = read_options(args, usage); 736 Set<File> decls_files = files.decls; 737 Set<String> dtrace_files = files.dtrace; 738 Set<File> spinfo_files = files.spinfo; 739 Set<File> map_files = files.map; 740 if (server_dir == null && decls_files.isEmpty() && dtrace_files.isEmpty()) { 741 System.out.println("No .decls or .dtrace files specified"); 742 throw new Daikon.UserError("No .decls or .dtrace files specified"); 743 } 744 745 // Never disable splitting for csharp format. 746 if (Daikon.dkconfig_undo_opts && Daikon.output_format != OutputFormat.CSHARPCONTRACT) { 747 PptSplitter.dkconfig_disable_splitting = true; 748 } 749 750 if (Daikon.dkconfig_quiet) { 751 Daikon.dkconfig_progress_delay = -1; 752 } 753 if (System.console() == null && !show_progress) { 754 // not connected to a terminal 755 Daikon.dkconfig_progress_delay = -1; 756 } 757 758 // Set up debug traces; note this comes after reading command line options. 759 LogHelper.setupLogs(Global.debugAll ? FINE : INFO); 760 761 if (!noversion_output) { 762 if (!Daikon.dkconfig_quiet) { 763 System.out.println(release_string); 764 } 765 } 766 767 // figure out which algorithm to use in NIS to process suppressions 768 if (NIS.dkconfig_suppression_processor == SuppressionProcessor.HYBRID) { 769 NIS.hybrid_method = true; 770 } else { 771 if (NIS.dkconfig_suppression_processor == SuppressionProcessor.ANTECEDENT) { 772 NIS.antecedent_method = true; 773 NIS.hybrid_method = false; 774 } else { 775 assert (NIS.dkconfig_suppression_processor == SuppressionProcessor.FALSIFIED); 776 NIS.antecedent_method = false; 777 NIS.hybrid_method = false; 778 } 779 } 780 781 // Create the list of all invariant types 782 setup_proto_invs(); 783 784 if (PrintInvariants.print_discarded_invariants) { 785 DiscReasonMap.initialize(); 786 } 787 788 fileio_progress = new FileIOProgress(); 789 fileio_progress.start(); 790 791 // Load declarations and splitters 792 load_spinfo_files(spinfo_files); 793 all_ppts = load_decls_files(decls_files); 794 load_map_files(map_files); 795 796 all_ppts.trimToSize(); 797 798 // Only for assertion checks 799 isInferencing = true; 800 801 // Infer invariants 802 process_data(all_ppts, dtrace_files); 803 isInferencing = false; 804 if (Debug.logOn()) { 805 Debug.check(all_ppts, "After process data"); 806 } 807 808 // If requested, just calculate the total number of invariants possible 809 if (dkconfig_calc_possible_invs) { 810 fileio_progress.shouldStop = true; 811 int total_invs = 0; 812 // Can't use new for syntax because the default iterator for all_ppts 813 // is not the one I want here. 814 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 815 System.out.printf("Processing %s with %d variables", ppt.name(), ppt.var_infos.length); 816 int inv_cnt = 0; 817 if (ppt.var_infos.length > 1600) { 818 System.out.println("Skipping, too many variables!"); 819 } else { 820 inv_cnt = ppt.getInvariants().size(); 821 System.out.println(" " + inv_cnt + " invariants"); 822 total_invs += inv_cnt; 823 } 824 } 825 System.out.println(total_invs + " invariants total"); 826 return; 827 } 828 829 if (suppress_redundant_invariants_with_simplify) { 830 suppressWithSimplify(all_ppts); 831 } 832 833 // Check that PptMap created was correct 834 all_ppts.repCheck(); 835 836 // Remove undesired invariants, if requested 837 if (omit_from_output) { 838 processOmissions(all_ppts); 839 } 840 841 debugProgress.fine(" Writing Serialized Pptmap ... "); 842 long startWriteTime = System.nanoTime(); 843 // Write serialized output - must be done before guarding invariants 844 if (inv_file != null) { 845 try { 846 FileIO.write_serialized_pptmap(all_ppts, inv_file); 847 } catch (IOException e) { 848 throw new RuntimeException("Error while writing .inv file: " + inv_file, e); 849 } 850 } 851 duration = System.nanoTime() - startWriteTime; 852 debugProgress.fine( 853 " Writing Serialized Pptmap ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 854 855 // if ((Daikon.dkconfig_guardNulls == "always") // interned 856 // || (Daikon.dkconfig_guardNulls == "missing")) { // interned 857 // // This side-effects the PptMap, but it has already been saved 858 // // to disk and is now being used only for printing. 859 // guardInvariants(all_ppts); 860 // } 861 862 // Debug print information about the variables 863 if (false) { 864 for (PptTopLevel ppt : all_ppts.all_ppts()) { 865 System.out.printf("Dumping variables for ppt %s%n", ppt.name()); 866 for (VarInfo vi : ppt.var_infos) { 867 System.out.printf(" vi %s%n", vi); 868 System.out.printf(" file_rep_type = %s%n", vi.file_rep_type); 869 System.out.printf(" type = %s%n", vi.type); 870 } 871 } 872 } 873 874 // print out the invariants for each program point 875 if (Daikon.dkconfig_undo_opts) { 876 // Print out the invariants for each program point (sort first) 877 for (PptTopLevel ppt : all_ppts.pptIterable()) { 878 879 // We do not need to print out program points that have not seen 880 // any samples. 881 if (ppt.num_samples() == 0) { 882 continue; 883 } 884 List<Invariant> invs = PrintInvariants.sort_invariant_list(ppt.invariants_vector()); 885 List<Invariant> filtered_invs = filter_invs(invs); 886 887 // Debugging output. Sometimes the program points actually differ in number of samples seen 888 // due to differences in how Daikon and DaikonSimple see the variable hierarchy. 889 if (false) { 890 System.out.println("===================================================="); 891 System.out.println(ppt.name()); 892 System.out.println(ppt.num_samples()); 893 894 for (Invariant inv : filtered_invs) { 895 System.out.println(inv.getClass()); 896 System.out.println(inv); 897 } 898 } 899 } 900 901 // exit the program 902 if (false) { 903 return; 904 } 905 } 906 907 // Display invariants 908 if (output_num_samples) { 909 System.out.println("The --output_num_samples debugging flag is on."); 910 System.out.println("Some of the debugging output may only make sense to Daikon programmers."); 911 } 912 913 // If they want to see discarded invariants, they probably don't 914 // want to see the true ones. 915 if (!PrintInvariants.print_discarded_invariants) { 916 PrintInvariants.print_invariants(all_ppts); 917 } else { 918 PrintInvariants.print_reasons(all_ppts); 919 } 920 921 if (output_num_samples) { 922 Global.output_statistics(); 923 } 924 if (dkconfig_print_sample_totals) { 925 System.out.println(FileIO.samples_processed + " samples processed"); 926 } 927 928 // print statistics concerning what invariants are printed 929 if (debugStats.isLoggable(FINE)) { 930 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 931 PrintInvariants.print_filter_stats(debugStats, ppt, all_ppts); 932 } 933 } 934 935 duration = System.nanoTime() - startTime; 936 debugProgress.fine(" Total time spent in Daikon: " + TimeUnit.NANOSECONDS.toSeconds(duration)); 937 938 // Done 939 if (!Daikon.dkconfig_quiet) { 940 System.out.println("Exiting Daikon."); 941 } 942 } 943 944 /** Cleans up static variables so that mainHelper can be called more than once. */ 945 @SuppressWarnings("nullness") // reinitialization 946 public static void cleanup() { 947 948 // Stop the thread that prints out progress information 949 if ((fileio_progress != null) && (fileio_progress.getState() != Thread.State.NEW)) { 950 fileio_progress.shouldStop = true; 951 try { 952 fileio_progress.join(2000); 953 } catch (InterruptedException e) { 954 // It's OK for a wait operation to be interrupted. 955 } 956 if (fileio_progress.getState() != Thread.State.TERMINATED) { 957 throw new BugInDaikon("Can't stop fileio_progress thead"); 958 } 959 } 960 fileio_progress = null; 961 progress = ""; 962 963 // Reset statics. Unfortunately, these must match the settings where 964 // these are declared and I don't know how to do that automatically. 965 inv_file = null; 966 no_text_output = false; 967 show_progress = false; 968 output_format = OutputFormat.DAIKON; 969 noversion_output = false; 970 output_num_samples = false; 971 omit_from_output = false; 972 omit_types = new boolean[256]; 973 use_dataflow_hierarchy = true; 974 suppress_redundant_invariants_with_simplify = false; 975 ppt_regexp = null; 976 ppt_omit_regexp = null; 977 var_regexp = null; 978 var_omit_regexp = null; 979 ppt_max_name = null; 980 server_dir = null; 981 use_mem_monitor = false; 982 userDefinedInvariants.clear(); 983 spinfoFiles.clear(); 984 // The input language affects how SplitterList matches program point names. 985 FileIO.input_language = null; 986 // Sample counts are per-invocation; e.g., the "No samples found" check uses samples_used. 987 FileIO.samples_processed = 0; 988 FileIO.samples_used = 0; 989 // Unmatched procedure entries are per-invocation; they affect the unmatched-entry report and 990 // which zero-sample program points are pruned. Within one invocation they persist across 991 // trace files, so an entry and its exit might be in different files. 992 FileIO.call_stack.clear(); 993 FileIO.call_hashmap.clear(); 994 // The count of omitted declarations is reported at the end of each invocation. 995 FileIO.omitted_declarations = 0; 996 FileIO.ppt_to_value_reps.clear(); 997 998 proto_invs.clear(); 999 } 1000 1001 // Structure for return value of read_options. 1002 // Return an array of {decls, dtrace, spinfo, map} files. 1003 public static class FileOptions { 1004 public Set<File> decls; 1005 public Set<String> dtrace; 1006 public Set<File> spinfo; 1007 public Set<File> map; 1008 1009 public FileOptions(Set<File> decls, Set<String> dtrace, Set<File> spinfo, Set<File> map) { 1010 this.decls = decls; 1011 this.dtrace = dtrace; 1012 this.spinfo = spinfo; 1013 this.map = map; 1014 } 1015 } 1016 1017 // /////////////////////////////////////////////////////////////////////////// 1018 // Read in the command line options 1019 1020 /** 1021 * Reads the command-line options, setting the corresponding static fields of Daikon and other 1022 * classes. 1023 * 1024 * @param args the command-line arguments 1025 * @param usage the usage message to print for {@code -h} and {@code --help} 1026 * @return the {decls, dtrace, spinfo, map} files 1027 * @throws Daikon.NormalTermination after printing the usage message, if an argument requests it 1028 * @throws Daikon.UserError if an argument is malformed or names a nonexistent file 1029 */ 1030 public static FileOptions read_options(String[] args, String usage) { 1031 if (args.length == 0) { 1032 System.out.println("Error: no files supplied on command line."); 1033 System.out.println(usage); 1034 throw new Daikon.UserError(); 1035 } 1036 1037 // LinkedHashSet because it can be confusing to users if files (of the 1038 // same type) are gratuitously processed in a different order than they 1039 // were supplied on the command line. 1040 HashSet<File> decl_files = new LinkedHashSet<>(); 1041 HashSet<String> dtrace_files = new LinkedHashSet<>(); // file names or "-" or "+" 1042 HashSet<File> spinfo_files = new LinkedHashSet<>(); 1043 HashSet<File> map_files = new LinkedHashSet<>(); 1044 1045 LongOpt[] longopts = 1046 new LongOpt[] { 1047 // Control output 1048 new LongOpt(no_text_output_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1049 new LongOpt(format_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1050 new LongOpt(show_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1051 new LongOpt(show_detail_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1052 new LongOpt(no_show_progress_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1053 new LongOpt(noversion_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1054 new LongOpt(output_num_samples_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1055 new LongOpt(files_from_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1056 new LongOpt(omit_from_output_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1057 // Control invariant detection 1058 new LongOpt(conf_limit_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1059 new LongOpt(list_type_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1060 new LongOpt(user_defined_invariant_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1061 new LongOpt(disable_all_invariants_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1062 new LongOpt(no_dataflow_hierarchy_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1063 new LongOpt(suppress_redundant_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1064 // Process only part of the trace file 1065 new LongOpt(ppt_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1066 new LongOpt(ppt_omit_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1067 new LongOpt(var_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1068 new LongOpt(var_omit_regexp_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1069 // Configuration options 1070 new LongOpt(server_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1071 new LongOpt(config_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1072 new LongOpt(config_option_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1073 // Debugging 1074 new LongOpt(debugAll_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1075 new LongOpt(debug_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1076 new LongOpt(track_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1077 new LongOpt(disc_reason_SWITCH, LongOpt.REQUIRED_ARGUMENT, null, 0), 1078 new LongOpt(mem_stat_SWITCH, LongOpt.NO_ARGUMENT, null, 0), 1079 }; 1080 DaikonGetopt g = new DaikonGetopt(args, "o:", longopts, usage); 1081 int c; 1082 1083 while ((c = g.getopt()) != -1) { 1084 switch (c) { 1085 case 0: 1086 // got a long option 1087 String option_name = longopts[g.getLongind()].getName(); 1088 1089 // Control output 1090 if (no_text_output_SWITCH.equals(option_name)) { 1091 no_text_output = true; 1092 } else if (format_SWITCH.equals(option_name)) { 1093 String format_name = getOptarg(g); 1094 Daikon.output_format = OutputFormat.get(format_name); 1095 if (Daikon.output_format == null) { 1096 throw new Daikon.UserError("Unknown output format: --format " + format_name); 1097 } 1098 } else if (show_progress_SWITCH.equals(option_name)) { 1099 show_progress = true; 1100 LogHelper.setLevel("daikon.Progress", FINE); 1101 } else if (show_detail_progress_SWITCH.equals(option_name)) { 1102 show_progress = true; 1103 LogHelper.setLevel("daikon.Progress", FINER); 1104 } else if (no_show_progress_SWITCH.equals(option_name)) { 1105 show_progress = false; 1106 } else if (noversion_SWITCH.equals(option_name)) { 1107 noversion_output = true; 1108 } else if (output_num_samples_SWITCH.equals(option_name)) { 1109 output_num_samples = true; 1110 } else if (files_from_SWITCH.equals(option_name)) { 1111 String files_from_filename = getOptarg(g); 1112 try (EntryReader entryReader = new EntryReader(files_from_filename)) { 1113 for (String filename : entryReader) { 1114 // Ignore blank lines in file. 1115 if (filename.equals("")) { 1116 continue; 1117 } 1118 // This code is duplicated below outside the options loop. 1119 // These aren't "endsWith()" because there might be a suffix 1120 // on the end (eg, a date, or ".gz"). 1121 File file = new File(filename); 1122 if (!file.exists()) { 1123 throw new Daikon.UserError("File " + filename + " not found."); 1124 } 1125 if (filename.indexOf(".decls") != -1) { 1126 decl_files.add(file); 1127 } else if (filename.indexOf(".dtrace") != -1) { 1128 dtrace_files.add(filename); 1129 } else if (filename.indexOf(".spinfo") != -1) { 1130 spinfo_files.add(file); 1131 } else if (filename.indexOf(".map") != -1) { 1132 map_files.add(file); 1133 } else { 1134 throw new Daikon.UserError("Unrecognized file extension: " + filename); 1135 } 1136 } 1137 } catch (IOException e) { 1138 throw new RuntimeException( 1139 String.format("Error reading --files_from file: %s", files_from_filename)); 1140 } 1141 break; 1142 } else if (omit_from_output_SWITCH.equals(option_name)) { 1143 String f = getOptarg(g); 1144 for (int i = 0; i < f.length(); i++) { 1145 if ("0rs".indexOf(f.charAt(i)) == -1) { 1146 throw new Daikon.UserError( 1147 "omit_from_output flag letter '" + f.charAt(i) + "' is unknown"); 1148 } 1149 omit_types[f.charAt(i)] = true; 1150 } 1151 omit_from_output = true; 1152 } 1153 // Control invariant detection 1154 else if (conf_limit_SWITCH.equals(option_name)) { 1155 double limit = Double.parseDouble(getOptarg(g)); 1156 if ((limit < 0.0) || (limit > 1.0)) { 1157 throw new Daikon.UserError(conf_limit_SWITCH + " must be between [0..1]"); 1158 } 1159 Configuration.getInstance() 1160 .apply("daikon.inv.Invariant.confidence_limit", String.valueOf(limit)); 1161 } else if (list_type_SWITCH.equals(option_name)) { 1162 try { 1163 String list_type_string = getOptarg(g); 1164 ProglangType.list_implementors.add(list_type_string); 1165 } catch (Exception e) { 1166 throw new Daikon.UserError("Problem parsing " + list_type_SWITCH + " option: " + e); 1167 } 1168 break; 1169 } else if (user_defined_invariant_SWITCH.equals(option_name)) { 1170 try { 1171 String user_defined_invariant_string = getOptarg(g); 1172 Matcher m = classGetNamePattern.matcher(user_defined_invariant_string); 1173 if (!m.matches()) { 1174 throw new Daikon.UserError( 1175 "Bad argument " 1176 + user_defined_invariant_string 1177 + " for " 1178 + ppt_regexp_SWITCH 1179 + ": not in the format required by Class.getName(String)"); 1180 } 1181 @SuppressWarnings("signature") // Regex match guarantees the format of Class.getName() 1182 @ClassGetName String cname = user_defined_invariant_string; 1183 userDefinedInvariants.add(cname); 1184 } catch (Exception e) { 1185 throw new Daikon.UserError( 1186 "Problem parsing " + user_defined_invariant_SWITCH + " option: " + e); 1187 } 1188 break; 1189 } else if (disable_all_invariants_SWITCH.equals(option_name)) { 1190 // There are two possibilities: 1191 // * a given invariant class is not yet loaded, in which case 1192 // we set the default value for its dkconfig_enabled field. 1193 // * a given invariant class is already loaded, in which case 1194 // we reflectively set its dkconfig_enabled to false. 1195 1196 // Set the default for not-yet-loaded invariants. 1197 Invariant.invariantEnabledDefault = false; 1198 1199 // Get all loaded classes. This solution is from 1200 // https://stackoverflow.com/a/10261850/173852 . Alternate approach: 1201 // https://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm 1202 Field f; 1203 try { 1204 f = ClassLoader.class.getDeclaredField("classes"); 1205 } catch (NoSuchFieldException e) { 1206 throw new Daikon.BugInDaikon("Didn't find field ClassLoader.classes"); 1207 } 1208 f.setAccessible(true); 1209 Object classesAsObject; 1210 { 1211 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 1212 if (cl == null) { 1213 throw new Daikon.BugInDaikon( 1214 "Need to handle when getContextClassLoader returns null"); 1215 } 1216 try { 1217 classesAsObject = f.get(cl); 1218 } catch (IllegalAccessException e) { 1219 throw new Daikon.BugInDaikon("Field ClassLoader.classes was not made accessible"); 1220 } 1221 } 1222 @SuppressWarnings({ 1223 "unchecked", // type of ClassLoader.classes field is known 1224 "nullness" // ClassLoader.classes is non-null 1225 }) 1226 @NonNull List<Class<?>> classes = (List<Class<?>>) classesAsObject; 1227 for (int i = 0; i < classes.size(); i++) { 1228 Class<?> loadedClass = classes.get(i); 1229 if (Invariant.class.isAssignableFrom(loadedClass)) { 1230 @SuppressWarnings("unchecked") // loadedClass is a subclass of Invariant 1231 Class<? extends Invariant> invType = (Class<? extends Invariant>) loadedClass; 1232 try { 1233 Field field = invType.getField("dkconfig_enabled"); 1234 if (field.getType() != Boolean.TYPE) { 1235 throw new Daikon.BugInDaikon( 1236 "Field " 1237 + invType 1238 + ".dkconfig_enabled has type " 1239 + field.getType() 1240 + " instead of boolean"); 1241 } else { 1242 setStaticField(field, false); 1243 // System.out.println( 1244 // "Set field " 1245 // + invType 1246 // + ".dkconfig_enabled to false"); 1247 } 1248 } catch (NoSuchFieldException e) { 1249 // System.out.println( 1250 // "Class " + invType + " does not have a dkconfig_enabled field"); 1251 } catch (IllegalAccessException e) { 1252 throw new Daikon.BugInDaikon( 1253 "IllegalAccessException for field " + invType + ".dkconfig_enabled"); 1254 } 1255 } 1256 } 1257 } else if (no_dataflow_hierarchy_SWITCH.equals(option_name)) { 1258 use_dataflow_hierarchy = false; 1259 } else if (suppress_redundant_SWITCH.equals(option_name)) { 1260 suppress_redundant_invariants_with_simplify = true; 1261 } 1262 1263 // Process only part of the trace file 1264 else if (ppt_regexp_SWITCH.equals(option_name)) { 1265 if (ppt_regexp != null) { 1266 throw new Daikon.UserError( 1267 "multiple --" 1268 + ppt_regexp_SWITCH 1269 + " regular expressions supplied on command line"); 1270 } 1271 String regexp_string = getOptarg(g); 1272 if (!RegexUtil.isRegex(regexp_string)) { 1273 throw new Daikon.UserError( 1274 "Bad regexp " 1275 + regexp_string 1276 + " for " 1277 + ppt_regexp_SWITCH 1278 + ": " 1279 + RegexUtil.regexError(regexp_string)); 1280 } 1281 ppt_regexp = Pattern.compile(regexp_string); 1282 break; 1283 } else if (ppt_omit_regexp_SWITCH.equals(option_name)) { 1284 if (ppt_omit_regexp != null) { 1285 throw new Daikon.UserError( 1286 "multiple --" 1287 + ppt_omit_regexp_SWITCH 1288 + " regular expressions supplied on command line"); 1289 } 1290 String regexp_string = getOptarg(g); 1291 if (!RegexUtil.isRegex(regexp_string)) { 1292 throw new Daikon.UserError( 1293 "Bad regexp " 1294 + regexp_string 1295 + " for " 1296 + ppt_omit_regexp_SWITCH 1297 + ": " 1298 + RegexUtil.regexError(regexp_string)); 1299 } 1300 ppt_omit_regexp = Pattern.compile(regexp_string); 1301 break; 1302 } else if (var_regexp_SWITCH.equals(option_name)) { 1303 if (var_regexp != null) { 1304 throw new Daikon.UserError( 1305 "multiple --" 1306 + var_regexp_SWITCH 1307 + " regular expressions supplied on command line"); 1308 } 1309 String regexp_string = getOptarg(g); 1310 if (!RegexUtil.isRegex(regexp_string)) { 1311 throw new Daikon.UserError( 1312 "Bad regexp " 1313 + regexp_string 1314 + " for " 1315 + var_regexp_SWITCH 1316 + ": " 1317 + RegexUtil.regexError(regexp_string)); 1318 } 1319 var_regexp = Pattern.compile(regexp_string); 1320 break; 1321 } else if (var_omit_regexp_SWITCH.equals(option_name)) { 1322 if (var_omit_regexp != null) { 1323 throw new Daikon.UserError( 1324 "multiple --" 1325 + var_omit_regexp_SWITCH 1326 + " regular expressions supplied on command line"); 1327 } 1328 String regexp_string = getOptarg(g); 1329 if (!RegexUtil.isRegex(regexp_string)) { 1330 throw new Daikon.UserError( 1331 "Bad regexp " 1332 + regexp_string 1333 + " for " 1334 + var_omit_regexp_SWITCH 1335 + ": " 1336 + RegexUtil.regexError(regexp_string)); 1337 } 1338 var_omit_regexp = Pattern.compile(regexp_string); 1339 break; 1340 } else if (server_SWITCH.equals(option_name)) { 1341 String input_dir = getOptarg(g); 1342 server_dir = new File(input_dir); 1343 if (!server_dir.isDirectory() || !server_dir.canRead() || !server_dir.canWrite()) { 1344 throw new RuntimeException( 1345 "Could not open config file in server directory " + server_dir); 1346 } 1347 break; 1348 1349 // Configuration options 1350 1351 } else if (config_SWITCH.equals(option_name)) { 1352 String config_file = getOptarg(g); 1353 try (InputStream stream = new FileInputStream(config_file)) { 1354 Configuration.getInstance().apply(stream); 1355 } catch (IOException e) { 1356 throw new Daikon.UserError( 1357 // Is this the only possible reason for an IOException? 1358 "Could not open config file " + config_file); 1359 } 1360 break; 1361 } else if (config_option_SWITCH.equals(option_name)) { 1362 String item = getOptarg(g); 1363 try { 1364 Configuration.getInstance().apply(item); 1365 } catch (daikon.config.Configuration.ConfigException e) { 1366 throw new Daikon.UserError(e); 1367 } 1368 break; 1369 } else if (debugAll_SWITCH.equals(option_name)) { 1370 Global.debugAll = true; 1371 } else if (debug_SWITCH.equals(option_name)) { 1372 LogHelper.setLevel(getOptarg(g), FINE); 1373 } else if (track_SWITCH.equals(option_name)) { 1374 LogHelper.setLevel("daikon.Debug", FINE); 1375 String error = Debug.add_track(getOptarg(g)); 1376 if (error != null) { 1377 throw new Daikon.UserError( 1378 "Error parsing track argument '" + getOptarg(g) + "' - " + error); 1379 } 1380 } else if (disc_reason_SWITCH.equals(option_name)) { 1381 try { 1382 PrintInvariants.discReasonSetup(getOptarg(g)); 1383 } catch (IllegalArgumentException e) { 1384 throw new Daikon.UserError(e); 1385 } 1386 } else if (mem_stat_SWITCH.equals(option_name)) { 1387 use_mem_monitor = true; 1388 } else { 1389 throw new Daikon.BugInDaikon("Unhandled long option " + option_name); 1390 } 1391 break; 1392 case 'o': 1393 String inv_filename = getOptarg(g); 1394 1395 if (inv_file != null) { 1396 throw new Daikon.UserError( 1397 "multiple serialization output files supplied on command line: " 1398 + inv_file 1399 + " " 1400 + inv_filename); 1401 } 1402 1403 inv_file = new File(inv_filename); 1404 1405 if (!FilesPlume.canCreateAndWrite(inv_file)) { 1406 throw new Daikon.UserError("Cannot write to serialization output file " + inv_file); 1407 } 1408 break; 1409 // 1410 default: 1411 throw new Daikon.BugInDaikon("getopt() returned " + c); 1412 } 1413 } 1414 1415 // This code is duplicated above within the switch processing. 1416 // First check that all the file names are OK, so we don't do lots of 1417 // processing only to bail out at the end. 1418 for (int i = g.getOptind(); i < args.length; i++) { 1419 String filename = args[i]; 1420 if (filename.equals("-") || filename.equals("+")) { 1421 dtrace_files.add(filename); 1422 continue; 1423 } 1424 1425 File file = new File(filename); 1426 if (!file.exists()) { 1427 throw new Daikon.UserError("File " + file + " not found."); 1428 } 1429 filename = file.toString(); 1430 1431 // These aren't "endsWith()" because there might be a suffix on the end 1432 // (eg, a date or ".gz"). 1433 if (filename.indexOf(".decls") != -1) { 1434 decl_files.add(file); 1435 } else if (filename.indexOf(".dtrace") != -1) { 1436 dtrace_files.add(filename); 1437 // Always output an invariant file by default, even if none is 1438 // specified on the command line. 1439 if (inv_file == null) { 1440 String basename; 1441 // This puts the .inv file in the current directory. 1442 basename = new File(filename).getName(); 1443 // This puts the .inv file in the same directory as the .dtrace file. 1444 // basename = filename; 1445 int base_end = basename.indexOf(".dtrace"); 1446 String inv_filename = basename.substring(0, base_end) + ".inv.gz"; 1447 1448 inv_file = new File(inv_filename); 1449 if (!FilesPlume.canCreateAndWrite(inv_file)) { 1450 throw new Daikon.UserError("Cannot write to file " + inv_file); 1451 } 1452 } 1453 } else if (filename.indexOf(".spinfo") != -1) { 1454 spinfo_files.add(file); 1455 } else if (filename.indexOf(".map") != -1) { 1456 map_files.add(file); 1457 } else { 1458 throw new Daikon.UserError("Unrecognized file type: " + file); 1459 } 1460 } 1461 1462 // Set the fuzzy float comparison ratio. This needs to be done after 1463 // any configuration options (which may set the ratio) are processed. 1464 Global.fuzzy.setRelativeRatio(Invariant.dkconfig_fuzzy_ratio); 1465 1466 // Setup ppt_max_name based on the specified percentage of ppts to process 1467 if (dkconfig_ppt_perc != 100) { 1468 ppt_max_name = setup_ppt_perc(decl_files, dtrace_files, dkconfig_ppt_perc); 1469 System.out.println("Max ppt name = " + ppt_max_name); 1470 } 1471 1472 // Validate guardNulls option 1473 PrintInvariants.validateGuardNulls(); 1474 1475 return new FileOptions(decl_files, dtrace_files, spinfo_files, map_files); 1476 } 1477 1478 /** 1479 * Set a static field to the given value. 1480 * 1481 * @param field a field; must be static 1482 * @param value the value to set the field to 1483 * @throws IllegalAccessException if {@code field} is enforcing Java language access control and 1484 * the underlying field is either inaccessible or final 1485 */ 1486 // This method exists to reduce the scope of the warning suppression. 1487 @SuppressWarnings({ 1488 "nullness:argument", // field is static, so object may be null 1489 "interning:argument" // interning is not necessary for how this method is used 1490 }) 1491 private static void setStaticField(Field field, Object value) throws IllegalAccessException { 1492 field.set(null, value); 1493 } 1494 1495 /** 1496 * Just like {@code g.getOptarg()}, but only to be called in circumstances when the programmer 1497 * knows that the return value is non-null. 1498 * 1499 * @param g a command-line argument processor 1500 * @return the value for an argument found by {@code g} 1501 */ 1502 @Pure 1503 public static String getOptarg(Getopt g) { 1504 String result = g.getOptarg(); 1505 if (result == null) { 1506 throw new Error("getOptarg returned null for " + g); 1507 } 1508 return result; 1509 } 1510 1511 /** 1512 * Invariants passed on the command line with the {@code --user-defined-invariant} option. A list 1513 * of class names in the format required by {@link Class#forName(String)}. 1514 */ 1515 private static List<@ClassGetName String> userDefinedInvariants = 1516 new ArrayList<@ClassGetName String>(); 1517 1518 /** 1519 * Creates the list of prototype invariants for all Daikon invariants. New invariants must be 1520 * added to this list. 1521 */ 1522 public static void setup_proto_invs() { 1523 1524 // Unary scalar invariants 1525 { 1526 // OneOf (OneOf.java.jpp) 1527 proto_invs.add(OneOfScalar.get_proto()); 1528 proto_invs.add(OneOfFloat.get_proto()); 1529 proto_invs.add(OneOfString.get_proto()); 1530 1531 // NonZero (NonZero.java.jpp) 1532 proto_invs.add(NonZero.get_proto()); 1533 proto_invs.add(NonZeroFloat.get_proto()); 1534 1535 proto_invs.add(IsPointer.get_proto()); 1536 1537 // Lower and Upper bound (Bound.java.jpp) 1538 proto_invs.add(LowerBound.get_proto()); 1539 proto_invs.add(LowerBoundFloat.get_proto()); 1540 proto_invs.add(UpperBound.get_proto()); 1541 proto_invs.add(UpperBoundFloat.get_proto()); 1542 1543 // Modulus and NonModulus (Modulus.java and NonModulus.java) 1544 proto_invs.add(Modulus.get_proto()); 1545 proto_invs.add(NonModulus.get_proto()); 1546 1547 // Range invariant (Range.java.jpp) 1548 proto_invs.addAll(RangeInt.get_proto_all()); 1549 proto_invs.addAll(RangeFloat.get_proto_all()); 1550 1551 // Printable String 1552 proto_invs.add(PrintableString.get_proto()); 1553 1554 // Complete One Of 1555 proto_invs.add(CompleteOneOfString.get_proto()); 1556 proto_invs.add(CompleteOneOfScalar.get_proto()); 1557 1558 // Positive (x > 0) (Positive.java). Positive is a sample invariant 1559 // that is only included as an example. 1560 // proto_invs.add (Positive.get_proto()); 1561 } 1562 1563 // Unary sequence invariants 1564 { 1565 // OneOf (OneOf.java.jpp) 1566 proto_invs.add(OneOfSequence.get_proto()); 1567 proto_invs.add(OneOfFloatSequence.get_proto()); 1568 proto_invs.add(OneOfStringSequence.get_proto()); 1569 proto_invs.add(EltOneOf.get_proto()); 1570 proto_invs.add(EltOneOfFloat.get_proto()); 1571 proto_invs.add(EltOneOfString.get_proto()); 1572 1573 // Range invariant (Range.java.jpp) 1574 proto_invs.addAll(EltRangeInt.get_proto_all()); 1575 proto_invs.addAll(EltRangeFloat.get_proto_all()); 1576 1577 // Sequence Index Comparisons (SeqIndexComparison.java.jpp) 1578 proto_invs.add(SeqIndexIntEqual.get_proto()); 1579 proto_invs.add(SeqIndexIntNonEqual.get_proto()); 1580 proto_invs.add(SeqIndexIntGreaterEqual.get_proto()); 1581 proto_invs.add(SeqIndexIntGreaterThan.get_proto()); 1582 proto_invs.add(SeqIndexIntLessEqual.get_proto()); 1583 proto_invs.add(SeqIndexIntLessThan.get_proto()); 1584 proto_invs.add(SeqIndexFloatEqual.get_proto()); 1585 proto_invs.add(SeqIndexFloatNonEqual.get_proto()); 1586 proto_invs.add(SeqIndexFloatGreaterEqual.get_proto()); 1587 proto_invs.add(SeqIndexFloatGreaterThan.get_proto()); 1588 proto_invs.add(SeqIndexFloatLessEqual.get_proto()); 1589 proto_invs.add(SeqIndexFloatLessThan.get_proto()); 1590 1591 // foreach i compare a[i] to a[i+1] (EltwiseIntComparisons.java.jpp) 1592 proto_invs.add(EltwiseIntEqual.get_proto()); 1593 proto_invs.add(EltwiseIntLessEqual.get_proto()); 1594 proto_invs.add(EltwiseIntGreaterEqual.get_proto()); 1595 proto_invs.add(EltwiseIntLessThan.get_proto()); 1596 proto_invs.add(EltwiseIntGreaterThan.get_proto()); 1597 proto_invs.add(EltwiseFloatEqual.get_proto()); 1598 proto_invs.add(EltwiseFloatLessEqual.get_proto()); 1599 proto_invs.add(EltwiseFloatGreaterEqual.get_proto()); 1600 proto_invs.add(EltwiseFloatLessThan.get_proto()); 1601 proto_invs.add(EltwiseFloatGreaterThan.get_proto()); 1602 1603 // EltNonZero (EltNonZero.java.jpp) 1604 proto_invs.add(EltNonZero.get_proto()); 1605 proto_invs.add(EltNonZeroFloat.get_proto()); 1606 1607 // No Duplicates (NoDuplicates.java.jpp) 1608 proto_invs.add(NoDuplicates.get_proto()); 1609 proto_invs.add(NoDuplicatesFloat.get_proto()); 1610 1611 // Element bounds (Bound.java.jpp) 1612 proto_invs.add(EltLowerBound.get_proto()); 1613 proto_invs.add(EltUpperBound.get_proto()); 1614 proto_invs.add(EltLowerBoundFloat.get_proto()); 1615 proto_invs.add(EltUpperBoundFloat.get_proto()); 1616 1617 // CommonSequence (CommonSequence.java.jpp) 1618 proto_invs.add(CommonSequence.get_proto()); 1619 proto_invs.add(CommonFloatSequence.get_proto()); 1620 1621 // CommonStringSequence (CommonStringSubsequence.java) 1622 proto_invs.add(CommonStringSequence.get_proto()); 1623 } 1624 1625 // Binary scalar-scalar invariants 1626 { 1627 // Int, Float, String comparisons (from IntComparisons.java.jpp) 1628 proto_invs.add(IntEqual.get_proto()); 1629 proto_invs.add(IntNonEqual.get_proto()); 1630 proto_invs.add(IntLessThan.get_proto()); 1631 proto_invs.add(IntGreaterThan.get_proto()); 1632 proto_invs.add(IntLessEqual.get_proto()); 1633 proto_invs.add(IntGreaterEqual.get_proto()); 1634 proto_invs.add(FloatEqual.get_proto()); 1635 proto_invs.add(FloatNonEqual.get_proto()); 1636 proto_invs.add(FloatLessThan.get_proto()); 1637 proto_invs.add(FloatGreaterThan.get_proto()); 1638 proto_invs.add(FloatLessEqual.get_proto()); 1639 proto_invs.add(FloatGreaterEqual.get_proto()); 1640 proto_invs.add(StringEqual.get_proto()); 1641 proto_invs.add(StringNonEqual.get_proto()); 1642 proto_invs.add(StringLessThan.get_proto()); 1643 proto_invs.add(StringGreaterThan.get_proto()); 1644 proto_invs.add(StringLessEqual.get_proto()); 1645 proto_invs.add(StringGreaterEqual.get_proto()); 1646 1647 // LinearBinary over integer/float (from LinearBinary.java.jpp) 1648 proto_invs.add(LinearBinary.get_proto()); 1649 proto_invs.add(LinearBinaryFloat.get_proto()); 1650 1651 // Numeric invariants (from Numeric.java.jpp) 1652 proto_invs.addAll(NumericInt.get_proto_all()); 1653 proto_invs.addAll(NumericFloat.get_proto_all()); 1654 1655 // Standard binary string invariants 1656 proto_invs.addAll(StdString.get_proto_all()); 1657 } 1658 1659 // Binary sequence-sequence invariants 1660 { 1661 // Numeric invariants (from Numeric.java.jpp) 1662 proto_invs.addAll(PairwiseNumericInt.get_proto_all()); 1663 proto_invs.addAll(PairwiseNumericFloat.get_proto_all()); 1664 1665 // Pairwise string invariants (also from Numeric.java.jpp) 1666 proto_invs.addAll(PairwiseString.get_proto_all()); 1667 1668 // Lexical sequence comparisons (from SeqComparison.java.jpp) 1669 proto_invs.add(SeqSeqIntEqual.get_proto()); 1670 proto_invs.add(SeqSeqIntLessThan.get_proto()); 1671 proto_invs.add(SeqSeqIntGreaterThan.get_proto()); 1672 proto_invs.add(SeqSeqIntLessEqual.get_proto()); 1673 proto_invs.add(SeqSeqIntGreaterEqual.get_proto()); 1674 proto_invs.add(SeqSeqFloatEqual.get_proto()); 1675 proto_invs.add(SeqSeqFloatLessThan.get_proto()); 1676 proto_invs.add(SeqSeqFloatGreaterThan.get_proto()); 1677 proto_invs.add(SeqSeqFloatLessEqual.get_proto()); 1678 proto_invs.add(SeqSeqFloatGreaterEqual.get_proto()); 1679 proto_invs.add(SeqSeqStringEqual.get_proto()); 1680 proto_invs.add(SeqSeqStringLessThan.get_proto()); 1681 proto_invs.add(SeqSeqStringGreaterThan.get_proto()); 1682 proto_invs.add(SeqSeqStringLessEqual.get_proto()); 1683 proto_invs.add(SeqSeqStringGreaterEqual.get_proto()); 1684 1685 // Pairwise sequence comparisons (from PairwiseIntComparison.java.jpp) 1686 proto_invs.add(PairwiseIntEqual.get_proto()); 1687 proto_invs.add(PairwiseIntLessThan.get_proto()); 1688 proto_invs.add(PairwiseIntGreaterThan.get_proto()); 1689 proto_invs.add(PairwiseIntLessEqual.get_proto()); 1690 proto_invs.add(PairwiseIntGreaterEqual.get_proto()); 1691 proto_invs.add(PairwiseFloatEqual.get_proto()); 1692 proto_invs.add(PairwiseFloatLessThan.get_proto()); 1693 proto_invs.add(PairwiseFloatGreaterThan.get_proto()); 1694 proto_invs.add(PairwiseFloatLessEqual.get_proto()); 1695 proto_invs.add(PairwiseFloatGreaterEqual.get_proto()); 1696 proto_invs.add(PairwiseStringEqual.get_proto()); 1697 proto_invs.add(PairwiseStringLessThan.get_proto()); 1698 proto_invs.add(PairwiseStringGreaterThan.get_proto()); 1699 proto_invs.add(PairwiseStringLessEqual.get_proto()); 1700 proto_invs.add(PairwiseStringGreaterEqual.get_proto()); 1701 1702 // Array Reverse (from Reverse.java.jpp) 1703 proto_invs.add(Reverse.get_proto()); 1704 proto_invs.add(ReverseFloat.get_proto()); 1705 1706 // Pairwise Linear Binary (from PairwiseLinearBinary.java.jpp) 1707 proto_invs.add(PairwiseLinearBinary.get_proto()); 1708 proto_invs.add(PairwiseLinearBinaryFloat.get_proto()); 1709 1710 // Subset and Superset (from SubSet.java.jpp) 1711 proto_invs.add(SubSet.get_proto()); 1712 proto_invs.add(SuperSet.get_proto()); 1713 proto_invs.add(SubSetFloat.get_proto()); 1714 proto_invs.add(SuperSetFloat.get_proto()); 1715 1716 // Subsequence (from SubSequence.java.jpp) 1717 proto_invs.add(SubSequence.get_proto()); 1718 proto_invs.add(SubSequenceFloat.get_proto()); 1719 proto_invs.add(SuperSequence.get_proto()); 1720 proto_invs.add(SuperSequenceFloat.get_proto()); 1721 } 1722 1723 // Binary sequence-scalar invariants 1724 { 1725 // Comparison of scalar to each array element (SeqIntComparison.java.jpp) 1726 proto_invs.add(SeqIntEqual.get_proto()); 1727 proto_invs.add(SeqIntLessThan.get_proto()); 1728 proto_invs.add(SeqIntGreaterThan.get_proto()); 1729 proto_invs.add(SeqIntLessEqual.get_proto()); 1730 proto_invs.add(SeqIntGreaterEqual.get_proto()); 1731 proto_invs.add(SeqFloatEqual.get_proto()); 1732 proto_invs.add(SeqFloatLessThan.get_proto()); 1733 proto_invs.add(SeqFloatGreaterThan.get_proto()); 1734 proto_invs.add(SeqFloatLessEqual.get_proto()); 1735 proto_invs.add(SeqFloatGreaterEqual.get_proto()); 1736 1737 // Scalar is an element of the array (Member.java.jpp) 1738 proto_invs.add(Member.get_proto()); 1739 proto_invs.add(MemberFloat.get_proto()); 1740 proto_invs.add(MemberString.get_proto()); 1741 } 1742 1743 // Ternary invariants 1744 { 1745 // FunctionBinary (FunctionBinary.java.jpp) 1746 proto_invs.addAll(FunctionBinary.get_proto_all()); 1747 proto_invs.addAll(FunctionBinaryFloat.get_proto_all()); 1748 1749 // LinearTernary (LinearTernary.java.jpp) 1750 proto_invs.add(LinearTernary.get_proto()); 1751 proto_invs.add(LinearTernaryFloat.get_proto()); 1752 } 1753 1754 // User-defined invariants 1755 for (String invariantClassName : userDefinedInvariants) { 1756 Class<?> invClass; 1757 try { 1758 invClass = Class.forName(invariantClassName); 1759 } catch (ClassNotFoundException e) { 1760 throw new Daikon.UserError( 1761 "Cannot load class " 1762 + invariantClassName 1763 + " in " 1764 + user_defined_invariant_SWITCH 1765 + " command-line argument; is it on the classpath?"); 1766 } 1767 Method get_proto_method; 1768 try { 1769 get_proto_method = invClass.getMethod("get_proto"); 1770 } catch (NoSuchMethodException e) { 1771 throw new Daikon.UserError( 1772 "No get_proto() method in user-defined invariant class " + invariantClassName); 1773 } catch (SecurityException e) { 1774 throw new Daikon.UserError( 1775 e, 1776 "SecurityException while looking up get_proto() method in user-defined invariant class " 1777 + invariantClassName); 1778 } 1779 Invariant inv; 1780 try { 1781 @SuppressWarnings("nullness") // null argument is OK because get_proto_method is static 1782 Object inv_as_object = get_proto_method.invoke(null); 1783 if (inv_as_object == null) { 1784 throw new Daikon.UserError( 1785 invariantClassName 1786 + ".get_proto() returned null but should have returned an Invariant"); 1787 } 1788 if (!(inv_as_object instanceof Invariant)) { 1789 Class<?> cls = inv_as_object.getClass(); 1790 throw new Daikon.UserError( 1791 invariantClassName 1792 + ".get_proto() returned object of the wrong type." 1793 + " It should have been a subclass of invariant, but was " 1794 + cls 1795 + ": " 1796 + inv_as_object); 1797 } 1798 inv = (Invariant) inv_as_object; 1799 } catch (Exception e) { 1800 throw new Daikon.UserError( 1801 e, "Exception while invoking " + invariantClassName + ".get_proto()"); 1802 } 1803 proto_invs.add(inv); 1804 } 1805 1806 // Remove any elements that are not enabled 1807 for (Iterator<@Prototype Invariant> i = proto_invs.iterator(); i.hasNext(); ) { 1808 @Prototype Invariant inv = i.next(); 1809 assert inv != null; 1810 if (!inv.enabled()) { 1811 i.remove(); 1812 } 1813 } 1814 } 1815 1816 /** 1817 * Creates invariants for upper program points by merging together the invariants from all of the 1818 * lower points. First, coarsens the comparability of each upper program point so that the merged 1819 * invariants can be represented there. 1820 */ 1821 public static void createUpperPpts(PptMap all_ppts) { 1822 1823 // Make each ppt's comparability at least as coarse as that of each of its children and of its 1824 // conditional ppts. Conditional ppts can have children too, so process them as well. Process 1825 // children before parents, so that usually each ppt is processed once. But a ppt may need to 1826 // be processed again: a ppt and its conditional ppts depend on one another, and USER 1827 // relations, if enabled (PptRelation.dkconfig_enable_object_user), can make the hierarchy 1828 // cyclic (for example, if classes A and B each have a field of the other's type, then each 1829 // OBJECT ppt is a parent of the other). So, when a ppt's comparability changes, put its 1830 // parents back on the worklist. 1831 Set<PptTopLevel> worklist = new LinkedHashSet<>(); 1832 // Track the unvisited ppts rather than the visited ones, so that the traversal stays within 1833 // all_ppts: in MergeInvariants, some children are in other PptMaps, and they must not be 1834 // visited. 1835 Set<PptTopLevel> unvisited = new LinkedHashSet<>(); 1836 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 1837 unvisited.add(ppt); 1838 } 1839 // Every element of unvisited gets visited, but only those that have children go on the 1840 // worklist. For a ppt with no children, coarsenComparability would do nothing: the ppt's 1841 // conditional ppts have no children either, and they already have the ppt's comparability. 1842 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 1843 addChildrenFirst(ppt, unvisited, worklist); 1844 } 1845 while (!worklist.isEmpty()) { 1846 Iterator<PptTopLevel> itor = worklist.iterator(); 1847 PptTopLevel ppt = itor.next(); 1848 itor.remove(); 1849 if (ppt.coarsenComparability()) { 1850 // coarsenComparability also changed the comparability of ppt's conditional ppts. 1851 for (PptRelation rel : ppt.parents) { 1852 worklist.add(rel.parent); 1853 } 1854 for (PptConditional pptCond : ppt.cond_iterable()) { 1855 for (PptRelation rel : pptCond.parents) { 1856 if (rel.parent != ppt) { 1857 worklist.add(rel.parent); 1858 } 1859 } 1860 } 1861 // Only the conditional ppts of a ppt's first splitter have a PPT_PPTCOND relation to it. 1862 if (ppt instanceof PptConditional) { 1863 worklist.add(((PptConditional) ppt).parent); 1864 } 1865 } 1866 } 1867 1868 // Process each ppt that doesn't have a parent 1869 // (mergeInvs is called on a root, and recursively processes children) 1870 for (PptTopLevel ppt : all_ppts.pptIterable()) { 1871 // System.out.printf("considering ppt %s parents: %s, children: %s%n", 1872 // ppt.name, ppt.parents, ppt.children); 1873 if (ppt.parents.isEmpty()) { 1874 ppt.mergeInvs(); 1875 } 1876 } 1877 } 1878 1879 /** 1880 * Adds to {@code worklist} each ppt that has children, among {@code ppt}, its conditional ppts, 1881 * and their descendants, each after its descendants. Does nothing for a ppt not in {@code 1882 * unvisited}. 1883 * 1884 * @param ppt a program point 1885 * @param unvisited the ppts that may still be visited; updated by this method 1886 * @param worklist the ppts to coarsen the comparability of; updated by this method 1887 */ 1888 private static void addChildrenFirst( 1889 PptTopLevel ppt, Set<PptTopLevel> unvisited, Set<PptTopLevel> worklist) { 1890 if (!unvisited.remove(ppt)) { 1891 return; 1892 } 1893 for (PptRelation rel : ppt.children) { 1894 addChildrenFirst(rel.child, unvisited, worklist); 1895 } 1896 for (PptConditional pptCond : ppt.cond_iterable()) { 1897 addChildrenFirst(pptCond, unvisited, worklist); 1898 } 1899 if (!ppt.children.isEmpty()) { 1900 worklist.add(ppt); 1901 } 1902 } 1903 1904 /** Setup splitters. Add orig and derived variables. Recursively call init_ppt on splits. */ 1905 public static void init_ppt(PptTopLevel ppt, PptMap all_ppts) { 1906 1907 if (!Daikon.using_DaikonSimple) { 1908 // Create orig variables and set up splitters. 1909 // This must be done before adding derived variables. 1910 // Do not add splitters to ppts that were already created by splitters! 1911 // Also, ppts created by splitters already have their orig_vars. 1912 if (!(ppt instanceof PptConditional)) { 1913 progress = "Creating orig variables and splitters for: " + ppt.name; 1914 create_orig_vars(ppt, all_ppts); 1915 setup_splitters(ppt); 1916 } 1917 } 1918 1919 // Create derived variables 1920 if (!Derivation.dkconfig_disable_derived_variables) { 1921 progress = "Creating derived variables for: " + ppt.name; 1922 ppt.create_derived_variables(); 1923 } 1924 1925 if (!Daikon.using_DaikonSimple) { 1926 // Initialize equality sets on leaf nodes 1927 setupEquality(ppt); 1928 // System.out.printf("initialized equality %s for ppt %s%n", 1929 // ppt.equality_view, ppt.name()); 1930 1931 // Recursively initialize ppts created by splitters 1932 if (ppt.has_splitters()) { 1933 for (PptConditional ppt_cond : ppt.cond_iterable()) { 1934 init_ppt(ppt_cond, all_ppts); 1935 } 1936 } 1937 } 1938 1939 if (VarInfo.assertionsEnabled()) { 1940 for (VarInfo vi : ppt.var_infos) { 1941 vi.checkRep(); 1942 } 1943 } 1944 } 1945 1946 /** 1947 * Create EXIT program points as needed for EXITnn program points. If a program point whose type 1948 * is not EXIT already has the name of the combined exit, such as a POINT named foo:::EXIT, the 1949 * combined exit is not created, and the numbered exits have no combined exit. In that case, 1950 * {@link PptRelation#init_hierarchy} connects each numbered exit directly to its enter point and 1951 * to its declared parents. 1952 * 1953 * @param ppts a map of program points, to which this adds the combined exits 1954 */ 1955 public static void create_combined_exits(PptMap ppts) { 1956 1957 // We can't add the newly created exit Ppts directly to ppts while we 1958 // are iterating over it, so store them temporarily in this map. 1959 PptMap exit_ppts = new PptMap(); 1960 1961 for (PptTopLevel ppt : ppts.pptIterable()) { 1962 // skip unless it's an EXITnn 1963 if (!ppt.is_subexit()) { 1964 continue; 1965 } 1966 1967 PptTopLevel exitnn_ppt = ppt; 1968 PptName exit_name = ppt.ppt_name.makeExit(); 1969 PptTopLevel declared = ppts.get(exit_name); 1970 if ((declared != null) && !declared.is_combined_exit()) { 1971 continue; 1972 } 1973 PptTopLevel exit_ppt = exit_ppts.get(exit_name); 1974 1975 if (debugInit.isLoggable(FINE)) { 1976 debugInit.fine("create_combined_exits: encountered exit " + exitnn_ppt.name()); 1977 } 1978 1979 // Create the exit, if necessary 1980 if (exit_ppt == null) { 1981 // This is a hack. It should probably filter out orig and derived 1982 // vars instead of taking the first n. 1983 int len = ppt.num_tracevars + ppt.num_static_constant_vars; 1984 VarInfo[] exit_vars = new VarInfo[len]; 1985 for (int j = 0; j < len; j++) { 1986 @SuppressWarnings("interning") // about to be used in new program point 1987 @Interned VarInfo exit_var = new VarInfo(ppt.var_infos[j]); 1988 exit_vars[j] = exit_var; 1989 // System.out.printf("exitNN name '%s', exit name '%s'%n", 1990 // ppt.var_infos[j].name(), exit_vars[j].name()); 1991 exit_vars[j].varinfo_index = ppt.var_infos[j].varinfo_index; 1992 exit_vars[j].value_index = ppt.var_infos[j].value_index; 1993 // Don't inherit the entry variable's equalitySet. 1994 @SuppressWarnings("nullness") // reinitialization 1995 @NonNull Equality es = null; 1996 exit_vars[j].equalitySet = es; 1997 } 1998 1999 exit_ppt = 2000 new PptTopLevel( 2001 exit_name.getName(), 2002 PptTopLevel.PptType.EXIT, 2003 ppt.parent_relations, 2004 ppt.flags, 2005 exit_vars); 2006 2007 // exit_ppt.ppt_name.setVisibility(exitnn_name.getVisibility()); 2008 exit_ppts.add(exit_ppt); 2009 if (debugInit.isLoggable(FINE)) { 2010 debugInit.fine("create_combined_exits: created exit " + exit_name); 2011 } 2012 init_ppt(exit_ppt, ppts); 2013 } 2014 } 2015 2016 // Now add the newly created Ppts to the global map. 2017 for (PptTopLevel ppt : exit_ppts.pptIterable()) { 2018 ppts.add(ppt); 2019 } 2020 } 2021 2022 // The function filters out the reflexive invs in binary slices, 2023 // reflexive and partially reflexive invs in ternary slices 2024 // and also filters out the invariants that have not seen enough 2025 // samples in ternary slices. 2026 static List<Invariant> filter_invs(List<Invariant> invs) { 2027 List<Invariant> new_list = new ArrayList<>(); 2028 2029 for (Invariant inv : invs) { 2030 VarInfo[] vars = inv.ppt.var_infos; 2031 2032 // This check is the most non-intrusive way to filter out the invs 2033 // Filter out reflexive invariants in the binary invs 2034 if (!((inv.ppt instanceof PptSlice2) && vars[0] == vars[1])) { 2035 2036 // Filter out the reflexive and partially reflexive invs in the 2037 // ternary slices 2038 if (!((inv.ppt instanceof PptSlice3) 2039 && (vars[0] == vars[1] || vars[1] == vars[2] || vars[0] == vars[2]))) { 2040 if (inv.ppt.num_values() != 0) { 2041 2042 // filters out "warning: too few samples for 2043 // daikon.inv.ternary.threeScalar.LinearTernary invariant" 2044 if (inv.isActive()) { 2045 new_list.add(inv); 2046 } 2047 } 2048 } 2049 } 2050 } 2051 2052 return new_list; 2053 } 2054 2055 /** 2056 * Add orig() variables to the given EXIT/EXITnn point. Does nothing if exit_ppt's type is not 2057 * EXIT or SUBEXIT, whatever its name. 2058 */ 2059 private static void create_orig_vars(PptTopLevel exit_ppt, PptMap ppts) { 2060 if (!exit_ppt.is_exit()) { 2061 if (VarInfo.assertionsEnabled()) { 2062 for (VarInfo vi : exit_ppt.var_infos) { 2063 try { 2064 vi.checkRep(); 2065 } catch (Throwable e) { 2066 System.err.println(); 2067 System.err.println("Error with variable " + vi + " at ppt " + exit_ppt); 2068 throw e; 2069 } 2070 } 2071 } 2072 return; 2073 } 2074 2075 if (debugInit.isLoggable(FINE)) { 2076 debugInit.fine("Doing create and relate orig vars for: " + exit_ppt.name()); 2077 } 2078 2079 PptTopLevel entry_ppt = ppts.get(exit_ppt.ppt_name.makeEnter()); 2080 if ((entry_ppt == null) || !entry_ppt.is_enter()) { 2081 throw new Daikon.UserError("exit found with no corresponding entry: " + exit_ppt.name()); 2082 } 2083 2084 // Add "orig(...)" (prestate) variables to the program point. 2085 // Don't bother to include the constants. Walk through 2086 // entry_ppt's vars. For each non-constant, put it on the 2087 // new_vis worklist after fixing its comparability information. 2088 exit_ppt.num_orig_vars = entry_ppt.num_tracevars; 2089 VarInfo[] new_vis = new VarInfo[exit_ppt.num_orig_vars]; 2090 { 2091 VarInfo[] entry_ppt_vis = entry_ppt.var_infos; 2092 int new_vis_index = 0; 2093 for (int k = 0; k < entry_ppt.num_declvars; k++) { 2094 VarInfo vi = entry_ppt_vis[k]; 2095 assert !vi.isDerived() : "Derived when making orig(): " + vi.name(); 2096 if (vi.isStaticConstant()) { 2097 continue; 2098 } 2099 VarInfo origvar = VarInfo.origVarInfo(vi); 2100 // Fix comparability 2101 VarInfo postvar = exit_ppt.find_var_by_name(vi.name()); 2102 if (postvar == null) { 2103 System.out.printf( 2104 "Looking for postvar, can't find var %s in exit of ppt %s%n", vi, exit_ppt.name()); 2105 for (VarInfo cvi : entry_ppt.var_infos) { 2106 System.out.printf(" entry var = %s%n", cvi); 2107 } 2108 for (VarInfo cvi : exit_ppt.var_infos) { 2109 System.out.printf(" exit var = %s%n", cvi); 2110 } 2111 throw new RuntimeException("this can't happen: postvar is null"); 2112 } 2113 origvar.postState = postvar; 2114 origvar.comparability = postvar.comparability.makeAlias(); 2115 2116 // add parents for override relations 2117 // exit_ppt.parents has not been loaded at this point 2118 for (VarParent pi : postvar.parents) { 2119 PptTopLevel parentppt = ppts.get(pi.parent_ppt); 2120 if (parentppt != null) { 2121 if (!parentppt.is_object() && !parentppt.is_class()) { 2122 VarInfo pvi = 2123 parentppt.find_var_by_name( 2124 pi.parent_variable == null ? postvar.name() : pi.parent_variable); 2125 if (pvi != null) { 2126 origvar.parents.add( 2127 new VarParent(pi.parent_ppt, pi.parent_relation_id, pvi.prestate_name())); 2128 } 2129 } 2130 } 2131 } 2132 2133 // Add to new_vis 2134 new_vis[new_vis_index] = origvar; 2135 new_vis_index++; 2136 // System.out.printf("adding origvar %s to ppt %s%n", origvar.name(), 2137 // exit_ppt.name()); 2138 } 2139 assert new_vis_index == exit_ppt.num_orig_vars; 2140 } 2141 exit_ppt.addVarInfos(new_vis); 2142 2143 if (VarInfo.assertionsEnabled()) { 2144 for (VarInfo vi : exit_ppt.var_infos) { 2145 try { 2146 vi.checkRep(); 2147 } catch (Throwable e) { 2148 System.err.println(); 2149 System.err.println("Error with variable " + vi + " at ppt " + exit_ppt); 2150 throw e; 2151 } 2152 } 2153 } 2154 } 2155 2156 // /////////////////////////////////////////////////////////////////////////// 2157 // Read decls, dtrace, etc. files 2158 2159 /** 2160 * Load a set of decl files. 2161 * 2162 * @param decl_files the files to load 2163 * @return the PptMap for the loaded files 2164 */ 2165 @RequiresNonNull("fileio_progress") 2166 // set in mainHelper 2167 private static PptMap load_decls_files(Set<File> decl_files) { 2168 long startTime = System.nanoTime(); 2169 try { 2170 if (!Daikon.dkconfig_quiet) { 2171 System.out.print("Reading declaration files "); 2172 } 2173 PptMap all_ppts = FileIO.read_declaration_files(decl_files); 2174 PptRelation.checkDeclaredParents(all_ppts); 2175 if (debugTrace.isLoggable(FINE)) { 2176 debugTrace.fine("Initializing partial order"); 2177 } 2178 fileio_progress.clear(); 2179 if (!Daikon.dkconfig_quiet && !decl_files.isEmpty()) { 2180 System.out.print("\r(read "); 2181 System.out.print(StringsPlume.nPlural(decl_files.size(), "decls file")); 2182 System.out.println(")"); 2183 } 2184 return all_ppts; 2185 } catch (IOException e) { 2186 // System.out.println(); 2187 // e.printStackTrace(); 2188 throw new Daikon.UserError(e, "Error parsing decl file"); 2189 } finally { 2190 long duration = System.nanoTime() - startTime; 2191 debugProgress.fine( 2192 "Time spent on read_declaration_files: " + TimeUnit.NANOSECONDS.toSeconds(duration)); 2193 } 2194 } 2195 2196 private static void load_spinfo_files(Set<File> spinfo_files) { 2197 if (PptSplitter.dkconfig_disable_splitting || spinfo_files.isEmpty()) { 2198 return; 2199 } 2200 long startTime = System.nanoTime(); 2201 try { 2202 System.out.print("Reading splitter info files "); 2203 create_splitters(spinfo_files); 2204 System.out.print("\r(read "); 2205 System.out.print(StringsPlume.nPlural(spinfo_files.size(), "spinfo file")); 2206 System.out.print(", "); 2207 System.out.print( 2208 StringsPlume.nPlural(SpinfoFile.numSplittterObjects(spinfoFiles), "splitter")); 2209 System.out.println(")"); 2210 } catch (IOException e) { 2211 System.out.println(); 2212 e.printStackTrace(); 2213 throw new Error(e); 2214 } finally { 2215 long duration = System.nanoTime() - startTime; 2216 debugProgress.fine( 2217 "Time spent on load_spinfo_files: " + TimeUnit.NANOSECONDS.toSeconds(duration)); 2218 } 2219 } 2220 2221 /** 2222 * A wrapper around {@link ContextSplitterFactory#load_mapfiles_into_splitterlist}. 2223 * 2224 * @param map_files the map files to read into SplitterList 2225 */ 2226 private static void load_map_files(Set<File> map_files) { 2227 long startTime = System.nanoTime(); 2228 if (!PptSplitter.dkconfig_disable_splitting && !map_files.isEmpty()) { 2229 System.out.print("Reading map (context) files "); 2230 ContextSplitterFactory.load_mapfiles_into_splitterlist( 2231 map_files, ContextSplitterFactory.dkconfig_granularity); 2232 System.out.print("\r(read "); 2233 System.out.print(StringsPlume.nPlural(map_files.size(), "map (context) file")); 2234 System.out.println(")"); 2235 long duration = System.nanoTime() - startTime; 2236 debugProgress.fine( 2237 "Time spent on load_map_files: " + TimeUnit.NANOSECONDS.toSeconds(duration)); 2238 } 2239 } 2240 2241 /** 2242 * Sets up splitting on all ppts. Currently only binary splitters over boolean returns or exactly 2243 * two return statements are enabled by default (though other splitters can be defined by the 2244 * user). 2245 * 2246 * @param ppt the program point to add conditions to 2247 */ 2248 @SuppressWarnings("nullness:contracts.precondition") 2249 public static void setup_splitters(PptTopLevel ppt) { 2250 if (PptSplitter.dkconfig_disable_splitting) { 2251 return; 2252 } 2253 2254 Global.debugSplit.fine("<<enter>> setup_splitters"); 2255 2256 SplitterFactory.load_splitters(ppt, spinfoFiles); 2257 2258 // pconds may contain several splitters with the same condition text, from different PPT_NAME 2259 // lines or .spinfo files; addConditions uses only one of them. 2260 Splitter[] pconds; 2261 if (SplitterList.dkconfig_all_splitters) { 2262 pconds = SplitterList.get_all(); 2263 } else { 2264 pconds = SplitterList.get(ppt.name()); 2265 } 2266 if (pconds != null) { 2267 Global.debugSplit.fine( 2268 "Got " + StringsPlume.nPlural(pconds.length, "splitter") + " for " + ppt.name()); 2269 ppt.addConditions(pconds); 2270 } 2271 2272 Global.debugSplit.fine("<<exit>> setup_splitters"); 2273 } 2274 2275 // /////////////////////////////////////////////////////////////////////////// 2276 // Infer invariants over the trace data 2277 2278 /** 2279 * The number of columns of progress information to display. In many Unix shells, this can be set 2280 * to an appropriate value by {@code --config_option 2281 * daikon.Daikon.progress_display_width=$COLUMNS}. 2282 */ 2283 public static int dkconfig_progress_display_width = 80; 2284 2285 /** 2286 * Human-friendly progress status message. If {@code fileio_progress} is non-null, then this is 2287 * ignored. So this is primarily for progress reports that are not IO-related. 2288 */ 2289 public static String progress = ""; 2290 2291 // Is set unconditionally in mainHelper 2292 /** Takes precedence over the progress variable. */ 2293 private static @MonotonicNonNull FileIOProgress fileio_progress = null; 2294 2295 /** Outputs FileIO progress information. Uses global variable FileIO.data_trace_state. */ 2296 public static class FileIOProgress extends Thread { 2297 public FileIOProgress() { 2298 setDaemon(true); 2299 } 2300 2301 /** 2302 * Clients should set this variable instead of calling Thread.stop(), which is deprecated. 2303 * Typically a client calls "display()" before setting this. The stopping happens later, and 2304 * calls clear() anyway. 2305 */ 2306 public boolean shouldStop = false; 2307 2308 @Override 2309 public void run() { 2310 if (dkconfig_progress_delay == -1) { 2311 return; 2312 } 2313 while (true) { 2314 if (shouldStop) { 2315 clear(); 2316 return; 2317 } 2318 display(); 2319 try { 2320 sleep(dkconfig_progress_delay); 2321 } catch (InterruptedException e) { 2322 // hmm 2323 } 2324 } 2325 } 2326 2327 /** Clear the display; good to do before printing to System.out. */ 2328 public void clear() { 2329 if (dkconfig_progress_delay == -1) { 2330 return; 2331 } 2332 // "display("");" is wrong because it leaves the timestamp and writes 2333 // spaces across the screen. 2334 String status = StringsPlume.rpad("", dkconfig_progress_display_width - 1); 2335 System.out.print("\r" + status); 2336 System.out.print("\r"); // return to beginning of line 2337 System.out.flush(); 2338 } 2339 2340 /** 2341 * Displays the current status. Call this if you don't want to wait until the next automatic 2342 * display. 2343 */ 2344 public void display() { 2345 if (dkconfig_progress_delay == -1) { 2346 return; 2347 } 2348 2349 String message; 2350 if (FileIO.data_trace_state != null) { 2351 message = FileIO.data_trace_state.reading_message(); 2352 } else { 2353 if (Daikon.progress == null) { 2354 message = "[no status]"; 2355 } else { 2356 message = Daikon.progress; 2357 } 2358 } 2359 display(message); 2360 } 2361 2362 /** 2363 * Displays the given message. 2364 * 2365 * @param message message to be displayed 2366 */ 2367 public void display(String message) { 2368 if (dkconfig_progress_delay == -1) { 2369 return; 2370 } 2371 String status = 2372 StringsPlume.rpad( 2373 "[" + LocalDateTime.now(ZoneId.systemDefault()) + "]: " + message, 2374 dkconfig_progress_display_width - 1); 2375 System.out.print("\r" + status); 2376 System.out.flush(); 2377 // System.out.println (status); // for debugging 2378 2379 if (debugTrace.isLoggable(FINE)) { 2380 debugTrace.fine("Free memory: " + java.lang.Runtime.getRuntime().freeMemory()); 2381 debugTrace.fine( 2382 "Used memory: " 2383 + (java.lang.Runtime.getRuntime().totalMemory() 2384 - java.lang.Runtime.getRuntime().freeMemory())); 2385 try { 2386 if (FileIO.data_trace_state != null) { 2387 debugTrace.fine("Active slices: " + FileIO.data_trace_state.all_ppts.countSlices()); 2388 } 2389 } catch (ConcurrentModificationException e) { 2390 // Because this code is a separate thread, the number of ppts 2391 // could change during countSlices. Just ignore and continue. 2392 } 2393 } 2394 } 2395 } 2396 2397 /** 2398 * The data-processing routine of the daikon engine. At this point, the decls and spinfo files 2399 * have been loaded, all of the program points have been setup, and candidate invariants have been 2400 * instantiated. This routine processes data to falsify the candidate invariants. 2401 */ 2402 @RequiresNonNull("fileio_progress") 2403 // set in mainHelper 2404 private static void process_data(PptMap all_ppts, Set<String> dtrace_files) { 2405 MemMonitor monitor = null; 2406 if (use_mem_monitor) { 2407 monitor = new MemMonitor("stat.out"); 2408 new Thread((Runnable) monitor).start(); 2409 } 2410 2411 long startTime = System.nanoTime(); 2412 2413 // Preprocessing 2414 setup_NISuppression(); 2415 2416 // Processing (actually using dtrace files) 2417 try { 2418 fileio_progress.clear(); 2419 if (!Daikon.dkconfig_quiet) { 2420 System.out.println( 2421 "Processing trace data; reading " 2422 + StringsPlume.nPlural(dtrace_files.size(), "dtrace file") 2423 + ":"); 2424 } 2425 FileIO.read_data_trace_files(dtrace_files, all_ppts); 2426 // Final update, so "100%", not "99.70%", is the last thing printed. 2427 // (This doesn't seem to achieve that, though...) 2428 fileio_progress.display(); 2429 fileio_progress.shouldStop = true; 2430 fileio_progress.display(); 2431 if (!Daikon.dkconfig_quiet) { 2432 System.out.println(); 2433 } 2434 // System.out.print("Creating implications "); // XXX untested code 2435 // for (PptTopLevel ppt : all_ppts) { 2436 // System.out.print('.'); 2437 // ppt.addImplications(); 2438 // } 2439 // System.out.println(); 2440 } catch (IOException e) { 2441 // System.out.println(); 2442 // e.printStackTrace(); 2443 throw new Error(e); 2444 } finally { 2445 long duration = System.nanoTime() - startTime; 2446 debugProgress.fine( 2447 "Time spent on read_data_trace_files: " + TimeUnit.NANOSECONDS.toSeconds(duration)); 2448 } 2449 2450 if (monitor != null) { 2451 monitor.stop(); 2452 } 2453 2454 if (FileIO.dkconfig_read_samples_only) { 2455 throw new Daikon.NormalTermination( 2456 String.format("Finished reading %d samples", FileIO.samples_processed)); 2457 } 2458 2459 if (all_ppts.isEmpty()) { 2460 String message = "No program point declarations were found."; 2461 if (FileIO.omitted_declarations != 0) { 2462 message += 2463 lineSep 2464 + " " 2465 + FileIO.omitted_declarations 2466 + " " 2467 + ((FileIO.omitted_declarations == 1) ? "declaration was" : "declarations were") 2468 + " omitted by regexps (e.g., --ppt-select-pattern)."; 2469 } 2470 throw new Daikon.UserError(message); 2471 } 2472 2473 // System.out.println("samples processed: " + FileIO.samples_processed); 2474 2475 if (FileIO.samples_processed == 0) { 2476 throw new Daikon.UserError( 2477 "No samples found for any of " + StringsPlume.nPlural(all_ppts.size(), "program point")); 2478 } 2479 // Count the samples that inference used, not all samples minus unmatched entries: an entry 2480 // sample can be both unmatched and used (if its ppt is declared as a leaf, such as a POINT). 2481 if (FileIO.samples_used == 0) { 2482 throw new Daikon.UserError( 2483 "Read " 2484 + StringsPlume.nPlural(FileIO.samples_processed, "sample") 2485 + ", but inference used none of them." 2486 + lineSep 2487 + " Inference ignores each exit that has no matching entry (when" 2488 + " daikon.FileIO.ignore_missing_enter is true)" 2489 + lineSep 2490 + " and, with the dataflow hierarchy, each sample at a program point that is not a" 2491 + " leaf, such as an ENTER program point."); 2492 } 2493 2494 // ppt_stats (all_ppts); 2495 2496 // if (debugStats.isLoggable (FINE)) { 2497 // PptSliceEquality.print_equality_stats (debugStats, all_ppts); 2498 // } 2499 2500 // Print equality set info 2501 // for (PptTopLevel ppt : all_ppts.pptIterable()) { 2502 // System.out.printf("ppt: %s", ppt.name); 2503 // if ((ppt.equality_view == null) || (ppt.equality_view.invs == null)) 2504 // continue; 2505 // for (Invariant inv : ppt.equality_view.invs) { 2506 // Equality e = (Equality) inv; 2507 // System.out.printf(" equality set = %s", e); 2508 // } 2509 // } 2510 2511 // System.out.printf("printing ternary invariants"); 2512 // PrintInvariants.print_all_ternary_invs (all_ppts); 2513 // System.exit(0); 2514 2515 // Postprocessing 2516 2517 debugProgress.fine("Create Combined Exits ... "); 2518 startTime = System.nanoTime(); 2519 create_combined_exits(all_ppts); 2520 long duration = System.nanoTime() - startTime; 2521 debugProgress.fine( 2522 "Create Combined Exits ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2523 2524 // Post process dynamic constants 2525 if (DynamicConstants.dkconfig_use_dynamic_constant_optimization) { 2526 debugProgress.fine("Constant Post Processing ... "); 2527 startTime = System.nanoTime(); 2528 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2529 if (ppt.constants != null) { 2530 ppt.constants.post_process(); 2531 } 2532 } 2533 duration = System.nanoTime() - startTime; 2534 debugProgress.fine( 2535 "Constant Post Processing ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2536 } 2537 2538 // Initialize the partial order hierarchy 2539 debugProgress.fine("Init Hierarchy ... "); 2540 startTime = System.nanoTime(); 2541 PptRelation.init_hierarchy(all_ppts); 2542 duration = System.nanoTime() - startTime; 2543 debugProgress.fine( 2544 "Init Hierarchy ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2545 2546 // Calculate invariants at all non-leaf ppts 2547 if (use_dataflow_hierarchy) { 2548 debugProgress.fine("createUpperPpts ... "); 2549 startTime = System.nanoTime(); 2550 // calculates invariants; does not actually create any ppts 2551 createUpperPpts(all_ppts); 2552 duration = System.nanoTime() - startTime; 2553 debugProgress.fine( 2554 "createUpperPpts ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2555 } 2556 2557 // Equality data for each PptTopLevel. 2558 if (Daikon.use_equality_optimization && !Daikon.dkconfig_undo_opts) { 2559 debugProgress.fine("Equality Post Process ... "); 2560 startTime = System.nanoTime(); 2561 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2562 // ppt.equality_view can be null here 2563 ppt.postProcessEquality(); 2564 } 2565 duration = System.nanoTime() - startTime; 2566 debugProgress.fine( 2567 "Equality Post Process ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2568 } 2569 2570 // undo optimizations; results in a more redundant but more complete 2571 // set of invariants 2572 if (Daikon.dkconfig_undo_opts) { 2573 undoOpts(all_ppts); 2574 } 2575 2576 // Debug print information about equality sets 2577 if (debugEquality.isLoggable(FINE)) { 2578 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2579 debugEquality.fine(ppt.name() + ": " + ppt.equality_sets_txt()); 2580 } 2581 } 2582 2583 debugProgress.fine("Non-implication postprocessing ... done"); 2584 2585 isInferencing = false; 2586 2587 // Add implications 2588 startTime = System.nanoTime(); 2589 fileio_progress.clear(); 2590 if (!PptSplitter.dkconfig_disable_splitting) { 2591 debugProgress.fine("Adding Implications ... "); 2592 for (PptTopLevel ppt : all_ppts.pptIterable()) { 2593 // debugProgress.fine (" Adding implications for " + ppt.name); 2594 ppt.addImplications(); 2595 } 2596 duration = System.nanoTime() - startTime; 2597 debugProgress.fine( 2598 "Adding Implications ... done [" + TimeUnit.NANOSECONDS.toSeconds(duration) + "]"); 2599 } 2600 } 2601 2602 private static class Count { 2603 int val; 2604 2605 Count(int val) { 2606 this.val = val; 2607 } 2608 } 2609 2610 /** Print out basic statistics (samples, invariants, variables, etc) about each ppt. */ 2611 public static void ppt_stats(PptMap all_ppts) { 2612 2613 int all_ppt_cnt = 0; 2614 int ppt_w_sample_cnt = 0; 2615 for (PptTopLevel ppt : all_ppts.pptIterable()) { 2616 all_ppt_cnt++; 2617 if (ppt.num_samples() == 0) { 2618 continue; 2619 } 2620 ppt_w_sample_cnt++; 2621 System.out.printf("%s%n", ppt.name()); 2622 System.out.printf(" samples = %n%d", ppt.num_samples()); 2623 System.out.printf(" invariants = %n%d", ppt.invariant_cnt()); 2624 Map<ProglangType, Count> type_map = new LinkedHashMap<>(); 2625 int leader_cnt = 0; 2626 for (VarInfo v : ppt.var_infos) { 2627 if (!v.isCanonical()) { 2628 continue; 2629 } 2630 leader_cnt++; 2631 Count cnt = type_map.computeIfAbsent(v.file_rep_type, __ -> new Count(0)); 2632 cnt.val++; 2633 } 2634 System.out.println(" vars = " + ppt.var_infos.length); 2635 System.out.println(" leaders = " + leader_cnt); 2636 for (Map.Entry<@KeyFor("type_map") ProglangType, Count> e : type_map.entrySet()) { 2637 ProglangType file_rep_type = e.getKey(); 2638 Count cnt = e.getValue(); 2639 System.out.printf(" %s = %d%n", file_rep_type, cnt.val); 2640 } 2641 } 2642 System.out.println("Total ppt count = " + all_ppt_cnt); 2643 System.out.println("PPts w/sample count = " + ppt_w_sample_cnt); 2644 } 2645 2646 /** Process the invariants with simplify to remove redundant invariants. */ 2647 private static void suppressWithSimplify(PptMap all_ppts) { 2648 System.out.print("Invoking Simplify to identify redundant invariants"); 2649 System.out.flush(); 2650 long startTime = System.nanoTime(); 2651 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2652 ppt.mark_implied_via_simplify(all_ppts); 2653 System.out.print("."); 2654 System.out.flush(); 2655 } 2656 long duration = System.nanoTime() - startTime; 2657 System.out.println(TimeUnit.NANOSECONDS.toSeconds(duration)); 2658 2659 // Make sure the Simplify process and helper threads are finished 2660 LemmaStack proverStack = PptTopLevel.getProverStack(); 2661 if (proverStack != null) { 2662 proverStack.close(); 2663 } 2664 } 2665 2666 /** Initialize NIS suppression. */ 2667 @EnsuresNonNull({ 2668 "daikon.suppress.NIS.suppressor_map", 2669 "daikon.suppress.NIS.suppressor_map_suppression_count", 2670 "daikon.suppress.NIS.all_suppressions", 2671 "daikon.suppress.NIS.suppressor_proto_invs" 2672 }) 2673 public static void setup_NISuppression() { 2674 NIS.init_ni_suppression(); 2675 } 2676 2677 /** Initialize the equality sets for each variable. */ 2678 public static void setupEquality(PptTopLevel ppt) { 2679 2680 if (!Daikon.use_equality_optimization) { 2681 return; 2682 } 2683 2684 // Skip points that are not leaves. 2685 if (use_dataflow_hierarchy) { 2686 PptTopLevel p = ppt; 2687 if (ppt instanceof PptConditional) { 2688 p = ((PptConditional) ppt).parent; 2689 } 2690 2691 if (!p.isDataflowLeaf()) { 2692 return; 2693 } 2694 2695 if (ppt.has_splitters()) { 2696 return; 2697 } 2698 } 2699 2700 ppt.createEqualityView(); 2701 } 2702 2703 private static List<SpinfoFile> spinfoFiles = new ArrayList<>(); 2704 2705 /** 2706 * Create user-defined splitters. For each file in the input, add a SpinfoFile to the spinfoFiles 2707 * variable. 2708 */ 2709 public static void create_splitters(Set<File> spinfo_files) throws IOException { 2710 for (File filename : spinfo_files) { 2711 SpinfoFile sf = SplitterFactory.parse_spinfofile(filename); 2712 spinfoFiles.add(sf); 2713 } 2714 } 2715 2716 // /** 2717 // * Guard the invariants at all PptTopLevels. Note that this changes 2718 // * the contents of the PptTopLevels, and the changes made should 2719 // * probably not be written out to an inv file (save the file before 2720 // * this is called). 2721 // */ 2722 // public static void guardInvariants(PptMap allPpts) { 2723 // for (PptTopLevel ppt : allPpts.asCollection()) { 2724 // if (ppt.num_samples() == 0) 2725 // continue; 2726 // // Make sure isDerivedParam is set before guarding. Otherwise 2727 // // we'll never get it correct. 2728 // for (int iVarInfo = 0; 2729 // iVarInfo < ppt.var_infos.length; 2730 // iVarInfo++) { 2731 // boolean temp = 2732 // ppt.var_infos[iVarInfo].isDerivedParamAndUninteresting(); 2733 // } 2734 // 2735 // ppt.guardInvariants(); 2736 // } 2737 // } 2738 2739 /** Removed invariants as specified in omit_types. */ 2740 private static void processOmissions(PptMap allPpts) { 2741 if (omit_types['0']) { 2742 allPpts.removeUnsampled(); 2743 } 2744 for (PptTopLevel ppt : allPpts.asCollection()) { 2745 ppt.processOmissions(omit_types); 2746 } 2747 } 2748 2749 /** 2750 * Returns the ppt name, max_ppt, that corresponds to the specified percentage of ppts (presuming 2751 * that only those ppts ≤ max_ppt will be processed). 2752 * 2753 * <p>The ppts are those declared in the declaration files and in the data trace files. A data 2754 * trace file that is standard input ("-"), a Chicory socket ("+"), or a URL is not read, because 2755 * it might not be possible to read it twice. 2756 * 2757 * @param decl_files the declaration files 2758 * @param dtrace_files the data trace files, as given on the command line 2759 * @param ppt_perc a percentage of ppts to process, from 1 to 100 2760 * @return the name of the last ppt to process, or null if ppt_perc is 100 2761 */ 2762 public static @Nullable String setup_ppt_perc( 2763 Collection<File> decl_files, Collection<String> dtrace_files, int ppt_perc) { 2764 2765 // Make sure the percentage is valid 2766 if ((ppt_perc < 1) || (ppt_perc > 100)) { 2767 // The number should already have been checked, so don't use UserError. 2768 throw new BugInDaikon("ppt_perc of " + ppt_perc + " is out of range 1..100"); 2769 } 2770 if (ppt_perc == 100) { 2771 return null; 2772 } 2773 2774 // Keep track of all of the ppts in a set ordered by the ppt name 2775 Set<String> ppts = new TreeSet<>(); 2776 2777 // Read all of the ppt names out of the files. 2778 try { 2779 for (File file : decl_files) { 2780 add_declared_ppt_names(file.toString(), ppts); 2781 } 2782 for (String filename : dtrace_files) { 2783 if (filename.equals("-") 2784 || filename.equals("+") 2785 || filename.startsWith("file:") 2786 || filename.startsWith("jar:")) { 2787 continue; 2788 } 2789 add_declared_ppt_names(filename, ppts); 2790 } 2791 } catch (IOException e) { 2792 e.printStackTrace(); 2793 throw new Error(e); 2794 } 2795 2796 // Determine the ppt_name that matches the specified percentage. Always 2797 // return the last exit point from the method (so we don't get half the 2798 // exits from a method or enters without exits, etc) 2799 int ppt_cnt = (ppts.size() * ppt_perc) / 100; 2800 if (ppt_cnt == 0) { 2801 throw new Daikon.UserError( 2802 "ppt_perc of " + ppt_perc + "% results in processing 0 out of " + ppts.size() + " ppts"); 2803 } 2804 for (Iterator<String> i = ppts.iterator(); i.hasNext(); ) { 2805 String ppt_name = i.next(); 2806 if (--ppt_cnt <= 0) { 2807 String last_ppt_name = ppt_name; 2808 while (i.hasNext()) { 2809 ppt_name = i.next(); 2810 if ((last_ppt_name.indexOf("EXIT") != -1) && (ppt_name.indexOf("EXIT") == -1)) { 2811 return last_ppt_name; 2812 } 2813 last_ppt_name = ppt_name; 2814 } 2815 return ppt_name; 2816 } 2817 } 2818 // Execution should not reach this line 2819 throw new Error("ppt_cnt " + ppt_cnt + " ppts.size " + ppts.size()); 2820 } 2821 2822 /** 2823 * Adds to a set the names of the ppts declared in the given file, except GLOBAL, OBJECT, and 2824 * CLASS ppts, which are always processed (see {@link FileIO#ppt_included}). 2825 * 2826 * @param filename a .decls or .dtrace file name 2827 * @param ppts the set to which to add the ppt names 2828 * @throws IOException if there is trouble reading the file 2829 */ 2830 private static void add_declared_ppt_names(String filename, Set<String> ppts) throws IOException { 2831 try (LineNumberReader fp = FilesPlume.newLineNumberFileReader(filename)) { 2832 // As in FileIO, only the first line of a record determines what the record is. A blank 2833 // line ends a record, and so does the end of a comment or of a one-line header record. 2834 boolean recordStart = true; 2835 for (String line = fp.readLine(); line != null; line = fp.readLine()) { 2836 if (line.trim().isEmpty()) { 2837 recordStart = true; 2838 continue; 2839 } 2840 if (!recordStart || FileIO.isComment(line)) { 2841 continue; 2842 } 2843 if (FileIO.is_one_line_header_record(line)) { 2844 continue; 2845 } 2846 recordStart = false; 2847 // ppt_name is null if the record is a sample or another kind of header record. 2848 String ppt_name = FileIO.declared_ppt_name(line); 2849 if (ppt_name != null && !FileIO.is_parent_only_ppt_name(ppt_name)) { 2850 ppts.add(ppt_name); 2851 } 2852 } 2853 } 2854 } 2855 2856 /** 2857 * Undoes the invariants suppressed for the dynamic constant, suppression and equality set 2858 * optimizations (should yield the same invariants as the simple incremental algorithm. 2859 */ 2860 @RequiresNonNull({"daikon.suppress.NIS.all_suppressions", "daikon.suppress.NIS.suppressor_map"}) 2861 public static void undoOpts(PptMap all_ppts) { 2862 2863 // undo suppressions 2864 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2865 NIS.create_suppressed_invs(ppt); 2866 } 2867 2868 // undo equality sets 2869 for (PptTopLevel ppt : all_ppts.ppt_all_iterable()) { 2870 PptSliceEquality sliceEquality = ppt.equality_view; 2871 2872 // some program points have no equality sets? 2873 if (sliceEquality == null) { 2874 // System.out.println(ppt.name); 2875 continue; 2876 } 2877 2878 // get the new leaders 2879 List<Equality> allNewInvs = new ArrayList<>(); 2880 2881 for (Invariant eq_as_inv : sliceEquality.invs) { 2882 Equality eq = (Equality) eq_as_inv; 2883 VarInfo leader = eq.leader(); 2884 List<VarInfo> vars = new ArrayList<>(); 2885 2886 for (VarInfo var : eq.getVars()) { 2887 if (!var.equals(leader)) { 2888 vars.add(var); 2889 } 2890 } 2891 2892 if (!vars.isEmpty()) { 2893 2894 // Create new equality sets for all of the non-equal vars 2895 List<Equality> newInvs = sliceEquality.createEqualityInvs(vars, eq); 2896 2897 // Create new slices and invariants for each new leader 2898 // copyInvsFromLeader(sliceEquality, leader, vars); 2899 sliceEquality.copyInvsFromLeader(leader, vars); 2900 2901 // Keep track of all of the new invariants created. 2902 // Add all of the new equality sets to our list 2903 allNewInvs.addAll(newInvs); 2904 } 2905 } 2906 2907 sliceEquality.invs.addAll(allNewInvs); 2908 } 2909 } 2910}