Skip to content

Commit 5ff4dee

Browse files
LiedtkeV8-internal LUCI CQ
authored andcommitted
Simplify constrained string generation in code generators
Change-Id: I0ed4abed4a3ef0c7e150971ec58f0aae7e5b0982 Reviewed-on: https://chrome-internal-review.googlesource.com/c/v8/fuzzilli/+/8591236 Auto-Submit: Matthias Liedtke <[email protected]> Reviewed-by: Carl Smith <[email protected]> Commit-Queue: Matthias Liedtke <[email protected]>
1 parent 92a61c5 commit 5ff4dee

File tree

2 files changed

+70
-198
lines changed

2 files changed

+70
-198
lines changed

Sources/Fuzzilli/Base/ProgramBuilder.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,36 @@ public class ProgramBuilder {
483483
return probability(0.5) ? randomBuiltinMethodName() : randomCustomMethodName()
484484
}
485485

486+
private static func generateConstrained<T: Equatable>(
487+
_ generator: () -> T,
488+
notIn: any Collection<T>,
489+
fallback: () -> T) -> T {
490+
var result: T
491+
var attempts = 0
492+
repeat {
493+
if attempts >= 10 {
494+
return fallback()
495+
}
496+
result = generator()
497+
attempts += 1
498+
} while notIn.contains(result)
499+
return result
500+
}
501+
502+
// Generate a string not already contained in `notIn` using the provided `generator`. If it fails
503+
// repeatedly, return a random string instead.
504+
public func generateString(_ generator: () -> String, notIn: any Collection<String>) -> String {
505+
Self.generateConstrained(generator, notIn: notIn,
506+
fallback: {String.random(ofLength: Int.random(in: 1...5))})
507+
}
508+
509+
// Find a random variable to use as a string that isn't contained in `notIn`. If it fails
510+
// repeatedly, create a random string literal instead.
511+
public func findOrGenerateStringLikeVariable(notIn: any Collection<Variable>) -> Variable {
512+
return Self.generateConstrained(randomJsVariable, notIn: notIn,
513+
fallback: {loadString(String.random(ofLength: Int.random(in: 1...5)))})
514+
}
515+
486516
// Settings and constants controlling the behavior of randomParameters() below.
487517
// This determines how many variables of a given type need to be visible before
488518
// that type is considered a candidate for a parameter type. For example, if this

0 commit comments

Comments
 (0)