1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogExecutionTest
// RUN: %target-codesign %t/OSLogExecutionTest
// RUN: %target-run %t/OSLogExecutionTest
//
// RUN: %target-build-swift %s -O -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogExecutionTest
// RUN: %target-codesign %t/OSLogExecutionTest
// RUN: %target-run %t/OSLogExecutionTest
// REQUIRES: executable_test
// REQUIRES: foundation
//
// REQUIRES: VENDOR=apple
// Run-time tests for testing the correctness of the optimizations that optimize the
// construction of the format string and the byte buffer from a string interpolation.
// The tests here are run with -Onone (which includes only mandatory optimizations)
// and also with full optimizations -O.
import OSLogTestHelper
import StdlibUnittest
import Foundation
defer { runAllTests() }
internal var InterpolationTestSuite = TestSuite("OSLogInterpolationTest")
internal let bitsPerByte = 8
/// A struct that provides methods for checking whether a given byte buffer
/// conforms to the format expected by the os_log ABI. This struct acts as
/// a specification of the byte buffer format.
internal struct OSLogBufferChecker {
internal let buffer: UnsafeBufferPointer<UInt8>
internal init(_ byteBuffer: UnsafeBufferPointer<UInt8>) {
buffer = byteBuffer
}
/// Bit mask for setting bits in the preamble. The bits denoted by the bit
/// mask indicate whether there is an argument that is private, and whether
/// there is an argument that is non-scalar: String, NSObject or Pointer.
internal enum PreambleBitMask: UInt8 {
case privateBitMask = 0x1
case nonScalarBitMask = 0x2
}
/// Check the summary bytes of the byte buffer.
/// - Parameters:
/// - argumentCount: number of arguments expected to be in the buffer.
/// - hasPrivate: true iff there exists a private argument
/// - hasNonScalar: true iff there exists a non-scalar argument
internal func checkSummaryBytes(
argumentCount: UInt8,
hasPrivate: Bool,
hasNonScalar: Bool
) {
let preamble = buffer[0]
let privateBit = preamble & PreambleBitMask.privateBitMask.rawValue
expectEqual(hasPrivate, privateBit != 0)
let nonScalarBit = preamble & PreambleBitMask.nonScalarBitMask.rawValue
expectEqual(hasNonScalar, nonScalarBit != 0)
expectEqual(argumentCount, buffer[1])
}
/// The possible values for the argument flag as defined by the os_log ABI.
/// This occupies four least significant bits of the first byte of the
/// argument header. Two least significant bits are used to indicate privacy
/// and the other two bits are reserved.
internal enum ArgumentFlag: UInt8 {
case autoFlag = 0
case privateFlag = 0x1
case publicFlag = 0x2
}
/// The possible values for the argument type as defined by the os_log ABI.
/// This occupies four most significant bits of the first byte of the
/// argument header.
internal enum ArgumentType: UInt8 {
case scalar = 0, count = 1, string = 2, pointer = 3, object = 4, mask = 7
// TODO: include wide string and errno here if needed.
}
/// Check the encoding of an argument headers in the byte buffer starting from
/// the `startIndex` and return argument bytes.
private func checkArgumentHeadersAndGetBytes(
startIndex: Int,
size: UInt8,
flag: ArgumentFlag,
type: ArgumentType
) -> [UInt8] {
let argumentHeader = buffer[startIndex]
expectEqual((type.rawValue << 4) | flag.rawValue, argumentHeader)
expectEqual(size, buffer[startIndex + 1])
// Argument data starts after the two header bytes.
let argumentBytes: [UInt8] =
(0..<Int(size)).reduce(into: []) { (acc, index) in
acc.append(buffer[startIndex + 2 + index])
}
return argumentBytes
}
/// Check whether the bytes starting from `startIndex` contain the encoding for a
/// numerical value.
internal func checkNumeric<T>(
startIndex: Int,
flag: ArgumentFlag,
type: ArgumentType,
expectedValue: T
) where T : Numeric {
let byteSize = UInt8(MemoryLayout<T>.size)
let argumentBytes =
checkArgumentHeadersAndGetBytes(
startIndex: startIndex,
size: byteSize,
flag: flag,
type: type)
withUnsafeBytes(of: expectedValue) { expectedBytes in
for i in 0..<Int(byteSize) {
expectEqual(
expectedBytes[i],
argumentBytes[i],
"mismatch at byte number \(i) "
+ "of the expected value \(expectedValue)")
}
}
}
/// Check whether the bytes starting from `startIndex` contain the encoding for an Int.
internal func checkInt<T>(
startIndex: Int,
flag: ArgumentFlag,
expectedInt: T
) where T : FixedWidthInteger {
checkNumeric(
startIndex: startIndex,
flag: flag,
type: .scalar,
expectedValue: expectedInt)
}
/// Check whether the bytes starting from `startIndex` contain the encoding for a count.
internal func checkCount(
startIndex: Int,
expectedCount: Int,
precision: Bool
) {
checkNumeric(
startIndex: startIndex,
flag: .autoFlag,
type: precision ? .count : .scalar,
expectedValue: CInt(expectedCount))
}
/// Check whether the bytes starting from `startIndex` contain the encoding
/// for a string.
internal func checkString(
startIndex: Int,
flag: ArgumentFlag,
expectedString: String
) {
let pointerSize = UInt8(MemoryLayout<UnsafePointer<Int8>>.size)
let argumentBytes =
checkArgumentHeadersAndGetBytes(
startIndex: startIndex,
size: pointerSize,
flag: flag,
type: .string)
// Read the pointer to a string stored in the buffer and compare it with
// the expected string using `strcmp`. Note that it is important we use a
// C function here to compare the string as it more closely represents
// the C os_log functions.
var stringAddress: Int = 0
// Copy the bytes of the address byte by byte. Note that
// RawPointer.load(fromByteOffset:,_) function cannot be used here as the
// address: `buffer + offset` is not aligned for reading an Int.
for i in 0..<Int(pointerSize) {
stringAddress |= Int(argumentBytes[i]) << (8 * i)
}
let bufferDataPointer = UnsafePointer<Int8>(bitPattern: stringAddress)
expectedString.withCString {
let compareResult = strcmp($0, bufferDataPointer)
expectEqual(0, compareResult, "strcmp returned \(compareResult)")
}
}
/// Check whether the bytes starting from `startIndex` contain the encoding
/// for an NSObject.
internal func checkNSObject(
startIndex: Int,
flag: ArgumentFlag,
expectedObject: NSObject
) {
let pointerSize = UInt8(MemoryLayout<UnsafePointer<Int8>>.size)
let argumentBytes =
checkArgumentHeadersAndGetBytes(
startIndex: startIndex,
size: pointerSize,
flag: flag,
type: .object)
// Convert data to a pointer and check if the addresses stored in the
// pointer and the one in the buffer match.
let objectAddress =
Unmanaged
.passUnretained(expectedObject)
.toOpaque()
withUnsafeBytes(of: objectAddress) { expectedBytes in
for i in 0..<Int(pointerSize) {
// Argument data starts after the two header bytes.
expectEqual(
expectedBytes[i],
argumentBytes[i],
"mismatch at byte number \(i) "
+ "of the expected object address \(objectAddress)")
}
}
}
internal func checkDouble(
startIndex: Int,
flag: ArgumentFlag,
expectedValue: Double
) {
let byteSize: UInt8 = 8
let argumentBytes =
checkArgumentHeadersAndGetBytes(
startIndex: startIndex,
size: byteSize,
flag: flag,
type: .scalar)
withUnsafeBytes(of: expectedValue) { expectedBytes in
for i in 0..<Int(byteSize) {
expectEqual(
expectedBytes[i],
argumentBytes[i],
"mismatch at byte number \(i) "
+ "of the expected value \(expectedValue)")
}
}
}
/// Check the given assertions on the arguments stored in the byte buffer.
/// - Parameters:
/// - assertions: one assertion for each argument stored in the byte buffer.
internal func checkArguments(_ assertions: [(Int) -> Void]) {
var currentArgumentIndex = 2
for assertion in assertions {
expectTrue(currentArgumentIndex < buffer.count)
assertion(currentArgumentIndex)
// Advance the index to the next argument by adding the size of the
// current argument and the two bytes of headers.
currentArgumentIndex += 2 + Int(buffer[currentArgumentIndex + 1])
}
}
/// Check a sequence of assertions on the arguments stored in the byte buffer.
internal func checkArguments(_ assertions: (Int) -> Void ...) {
checkArguments(assertions)
}
}
InterpolationTestSuite.test("integer literal") {
_osLogTestHelper(
"An integer literal \(10)",
assertion: { (formatString, buffer) in
expectEqual(
"An integer literal %ld",
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 1,
hasPrivate: false,
hasNonScalar: false)
bufferChecker.checkArguments({
bufferChecker.checkInt(startIndex: $0, flag: .autoFlag, expectedInt: 10)
})
})
}
InterpolationTestSuite.test("integer with formatting") {
_osLogTestHelper(
"Minimum integer value: \(UInt.max, format: .hex)",
assertion: { (formatString, buffer) in
expectEqual(
"Minimum integer value: %lx",
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 1,
hasPrivate: false,
hasNonScalar: false)
bufferChecker.checkArguments({
bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: UInt.max)
})
})
}
InterpolationTestSuite.test("integer with privacy and formatting") {
let addr: UInt = 0x7afebabe
_osLogTestHelper(
"Access to invalid address: \(addr, format: .hex, privacy: .private)",
assertion: { (formatString, buffer) in
expectEqual(
"Access to invalid address: %{private}lx",
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 1,
hasPrivate: true,
hasNonScalar: false)
bufferChecker.checkArguments({
bufferChecker.checkInt(
startIndex: $0,
flag: .privateFlag,
expectedInt: addr)
})
})
}
InterpolationTestSuite.test("test multiple arguments") {
let filePerms: UInt = 0o777
let pid = 122225
let privateID = 0x79abcdef
_osLogTestHelper(
"""
Access prevented: process \(pid, privacy: .public) initiated by \
user: \(privateID, privacy: .private) attempted resetting \
permissions to \(filePerms, format: .octal)
""",
assertion: { (formatString, buffer) in
expectEqual(
"""
Access prevented: process %{public}ld initiated by \
user: %{private}ld attempted resetting permissions \
to %lo
""",
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 3,
hasPrivate: true,
hasNonScalar: false)
bufferChecker.checkArguments(
{
bufferChecker.checkInt(
startIndex: $0,
flag: .publicFlag,
expectedInt: pid)
},
{
bufferChecker.checkInt(
startIndex: $0,
flag: .privateFlag,
expectedInt: privateID)
},
{
bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: filePerms)
})
})
}
InterpolationTestSuite.test("interpolation of too many arguments") {
// The following string interpolation has 49 interpolated values. Only 48
// of these must be present in the generated format string and byte buffer.
_osLogTestHelper(
"""
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \
\(1) \(1) \(1) \(1) \(1) \(1) \(1)
""",
assertion: { (formatString, buffer) in
expectEqual(
String(
repeating: "%ld ",
count: Int(maxOSLogArgumentCount)),
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: maxOSLogArgumentCount,
hasPrivate: false,
hasNonScalar: false)
bufferChecker.checkArguments(
Array(
repeating: {
bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: 1) },
count: Int(maxOSLogArgumentCount))
)
})
}
InterpolationTestSuite.test("string interpolations with percents") {
_osLogTestHelper(
"a = (c % d)%%",
assertion: { (formatString, buffer) in
expectEqual("a = (c %% d)%%%%", formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 0,
hasPrivate: false,
hasNonScalar: false)
})
}
InterpolationTestSuite.test("integer types") {
_osLogTestHelper("Int32 max: \(Int32.max)") {
(formatString, buffer) in
expectEqual("Int32 max: %d", formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 1,
hasPrivate: false,
hasNonScalar: false)
bufferChecker.checkArguments({
bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: Int32.max)
})
}
}
InterpolationTestSuite.test("string arguments") {
let small = "a"
let large = "this is a large string"
_osLogTestHelper(
"small: \(small, privacy: .public) large: \(large)") {
(formatString, buffer) in
expectEqual("small: %{public}s large: %s", formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 2,
hasPrivate: false,
hasNonScalar: true
)
bufferChecker.checkArguments({
bufferChecker.checkString(
startIndex: $0,
flag: .publicFlag,
expectedString: small)
},
{ bufferChecker.checkString(
startIndex: $0,
flag: .autoFlag,
expectedString: large)
})
}
}
InterpolationTestSuite.test("dynamic strings") {
let concatString = "hello" + " - " + "world"
let interpolatedString = "\(31) trillion digits of pi are known so far"
_osLogTestHelper(
"""
concat: \(concatString, privacy: .public) \
interpolated: \(interpolatedString, privacy: .private)
""") { (formatString, buffer) in
expectEqual("concat: %{public}s interpolated: %{private}s", formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 2,
hasPrivate: true,
hasNonScalar: true
)
bufferChecker.checkArguments({
bufferChecker.checkString(
startIndex: $0,
flag: .publicFlag,
expectedString: concatString)
},
{ bufferChecker.checkString(
startIndex: $0,
flag: .privateFlag,
expectedString: interpolatedString)
})
}
}
InterpolationTestSuite.test("NSObject") {
let nsArray: NSArray = [0, 1, 2]
let nsDictionary: NSDictionary = [1 : ""]
_osLogTestHelper(
"""
NSArray: \(nsArray, privacy: .public) \
NSDictionary: \(nsDictionary)
""") { (formatString, buffer) in
expectEqual("NSArray: %{public}@ NSDictionary: %@", formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 2,
hasPrivate: false,
hasNonScalar: true
)
bufferChecker.checkArguments({
bufferChecker.checkNSObject(
startIndex: $0,
flag: .publicFlag,
expectedObject: nsArray)
},
{ bufferChecker.checkNSObject(
startIndex: $0,
flag: .autoFlag,
expectedObject: nsDictionary)
})
}
}
// A generic function.
func toString<T>(_ subject: T?) -> String {
return ""
}
protocol TestProto {
}
InterpolationTestSuite.test("Interpolation of complex expressions") {
class TestClass<T: TestProto>: NSObject {
func testFunction() {
// The following call should not crash.
_osLogTestHelper("A complex expression \(toString(self))") {
(formatString, _) in
expectEqual("A complex expression %s", formatString)
}
}
}
class B : TestProto { }
TestClass<B>().testFunction()
}
InterpolationTestSuite.test("Include prefix formatting option") {
let unsignedValue: UInt = 0o171
_osLogTestHelper(
"Octal with prefix: \(unsignedValue, format: .octal(includePrefix: true))") {
(formatString, buffer) in
expectEqual("Octal with prefix: 0o%lo", formatString)
}
}
InterpolationTestSuite.test("Hex with uppercase formatting option") {
let unsignedValue: UInt = 0xcafebabe
_osLogTestHelper(
"Hex with uppercase: \(unsignedValue, format: .hex(uppercase: true))") {
(formatString, buffer) in
expectEqual("Hex with uppercase: %lX", formatString)
}
}
InterpolationTestSuite.test("Integer with explicit positive sign") {
let posValue = Int.max
_osLogTestHelper(
"\(posValue, format: .decimal(explicitPositiveSign: true))") {
(formatString, buffer) in
expectEqual("%+ld", formatString)
}
}
InterpolationTestSuite.test("Unsigned integer with explicit positive sign") {
let posValue = UInt.max
_osLogTestHelper(
"\(posValue, format: .decimal(explicitPositiveSign: true))") {
(formatString, buffer) in
expectEqual("+%lu", formatString)
}
}
InterpolationTestSuite.test("Integer formatting with precision") {
let intValue = 1200
_osLogTestHelper(
"\(intValue, format: .decimal(minDigits: 10))") {
(formatString, buffer) in
expectEqual("%.*ld", formatString)
// The buffer should contain two arguments: precision and the actual argument.
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 2,
hasPrivate: false,
hasNonScalar: false
)
bufferChecker.checkArguments(
{ bufferChecker.checkCount(
startIndex: $0,
expectedCount: 10,
precision: true)
},
{ bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: intValue)
})
}
}
InterpolationTestSuite.test("Integer formatting with alignment") {
let intValue = 10
_osLogTestHelper(
"""
\(intValue, align: .right(columns: 10)) \
\(intValue, align: .left(columns: 5), privacy: .private)
""") {
(formatString, buffer) in
expectEqual("%*ld %{private}-*ld", formatString)
}
}
InterpolationTestSuite.test("Integer formatting with precision and alignment") {
let intValue = 1200
_osLogTestHelper(
"\(intValue, format: .decimal(minDigits: 10), align: .left(columns: 7))") {
(formatString, buffer) in
expectEqual("%-*.*ld", formatString)
// The buffer must contain three arguments: width, precision, and the argument.
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 3,
hasPrivate: false,
hasNonScalar: false
)
bufferChecker.checkArguments(
{ bufferChecker.checkCount(
startIndex: $0,
expectedCount: 7,
precision: false)
},
{ bufferChecker.checkCount(
startIndex: $0,
expectedCount: 10,
precision: true)
},
{ bufferChecker.checkInt(
startIndex: $0,
flag: .autoFlag,
expectedInt: intValue)
})
}
}
InterpolationTestSuite.test("String with alignment") {
let smallString = "a" + "b"
let concatString = "hello" + " - " + "world"
_osLogTestHelper(
"""
\(smallString, align: .right(columns: 10)) \
\(concatString, align: .left(columns: 7), privacy: .public)
""") {
(formatString, buffer) in
expectEqual("%*s %{public}-*s", formatString)
}
}
InterpolationTestSuite.test("Floats and Doubles") {
let x = 1.2 + 0.5
let pi: Double = 3.141593
let floatPi: Float = 3.141593
_osLogTestHelper(
"""
A double value: \(x, privacy: .private) \
pi as double: \(pi), pi as float: \(floatPi)
""") {
(formatString, buffer) in
expectEqual(
"""
A double value: %{private}f pi as double: %f, \
pi as float: %f
""",
formatString)
let bufferChecker = OSLogBufferChecker(buffer)
bufferChecker.checkSummaryBytes(
argumentCount: 3,
hasPrivate: true,
hasNonScalar: false)
bufferChecker.checkArguments(
{ bufferChecker.checkDouble(
startIndex: $0,
flag: .privateFlag,
expectedValue: x)
},
{ bufferChecker.checkDouble(
startIndex: $0,
flag: .autoFlag,
expectedValue: pi)
},
{ bufferChecker.checkDouble(
startIndex: $0,
flag: .autoFlag,
expectedValue: Double(floatPi))
})
}
}
|