TestFileHandle.py 35.9 KB
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 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
"""
Test lldb Python API for file handles.
"""


import os
import io
import re
import sys
from contextlib import contextmanager

import lldb
from lldbsuite.test import  lldbtest
from lldbsuite.test.decorators import *

class OhNoe(Exception):
    pass

class BadIO(io.TextIOBase):
    @property
    def closed(self):
        return False
    def writable(self):
        return True
    def readable(self):
        return True
    def write(self, s):
        raise OhNoe('OH NOE')
    def read(self, n):
        raise OhNoe("OH NOE")
    def flush(self):
        raise OhNoe('OH NOE')

# This class will raise an exception while it's being
# converted into a C++ object by swig
class ReallyBadIO(io.TextIOBase):
    def fileno(self):
        return 999
    def writable(self):
        raise OhNoe("OH NOE!!!")

class MutableBool():
    def __init__(self, value):
        self.value = value
    def set(self, value):
        self.value = bool(value)
    def __bool__(self):
        return self.value

class FlushTestIO(io.StringIO):
    def __init__(self, mutable_flushed, mutable_closed):
        super(FlushTestIO, self).__init__()
        self.mut_flushed = mutable_flushed
        self.mut_closed = mutable_closed
    def close(self):
        self.mut_closed.set(True)
        return super(FlushTestIO, self).close()
    def flush(self):
        self.mut_flushed.set(True)
        return super(FlushTestIO, self).flush()

@contextmanager
def replace_stdout(new):
    old = sys.stdout
    sys.stdout = new
    try:
        yield
    finally:
        sys.stdout = old

def readStrippedLines(f):
    def i():
        for line in f:
            line = line.strip()
            if line:
                yield line
    return list(i())


class FileHandleTestCase(lldbtest.TestBase):

    NO_DEBUG_INFO_TESTCASE = True
    mydir = lldbtest.Base.compute_mydir(__file__)

    # The way normal tests evaluate debugger commands is
    # by using a SBCommandInterpreter directly, which captures
    # the output in a result object.   For many of tests tests
    # we want the debugger to write the  output directly to
    # its I/O streams like it would have done interactively.
    #
    # For this reason we also define handleCmd() here, even though
    # it is similar to runCmd().

    def setUp(self):
        super(FileHandleTestCase, self).setUp()
        self.out_filename = self.getBuildArtifact('output')
        self.in_filename = self.getBuildArtifact('input')

    def tearDown(self):
        super(FileHandleTestCase, self).tearDown()
        for name in (self.out_filename, self.in_filename):
            if os.path.exists(name):
                os.unlink(name)

    # Similar to runCmd(), but letting the debugger just print the results
    # instead of collecting them.
    def handleCmd(self, cmd, check=True, collect_result=True):
        assert not check or collect_result
        ret = lldb.SBCommandReturnObject()
        if collect_result:
            interpreter = self.dbg.GetCommandInterpreter()
            interpreter.HandleCommand(cmd, ret)
        else:
            self.dbg.HandleCommand(cmd)
        self.dbg.GetOutputFile().Flush()
        self.dbg.GetErrorFile().Flush()
        if collect_result and check:
            self.assertTrue(ret.Succeeded())
        return ret.GetOutput()


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_legacy_file_out_script(self):
        with open(self.out_filename, 'w') as f:
            self.dbg.SetOutputFileHandle(f, False)
            # scripts print to output even if you capture the results
            # I'm not sure I love that behavior, but that's the way
            # it's been for a long time.  That's why this test works
            # even with collect_result=True.
            self.handleCmd('script 1+1')
            self.dbg.GetOutputFileHandle().write('FOO\n')
            self.dbg.GetOutputFileHandle().flush()
        with open(self.out_filename, 'r') as f:
            self.assertEqual(readStrippedLines(f), ['2', 'FOO'])


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_legacy_file_out(self):
        with open(self.out_filename, 'w') as f:
            self.dbg.SetOutputFileHandle(f, False)
            self.handleCmd('p/x 3735928559', collect_result=False, check=False)
        with open(self.out_filename, 'r') as f:
            self.assertIn('deadbeef', f.read())

    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_legacy_file_err_with_get(self):
        with open(self.out_filename, 'w') as f:
            self.dbg.SetErrorFileHandle(f, False)
            self.handleCmd('lolwut', check=False, collect_result=False)
            f2 = self.dbg.GetErrorFileHandle()
            f2.write('FOOBAR\n')
            f2.flush()
        with open(self.out_filename, 'r') as f:
            errors = f.read()
            self.assertTrue(re.search(r'error:.*lolwut', errors))
            self.assertTrue(re.search(r'FOOBAR', errors))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_legacy_file_err(self):
        with open(self.out_filename, 'w') as f:
            self.dbg.SetErrorFileHandle(f, False)
            self.handleCmd('lol', check=False, collect_result=False)
        with open(self.out_filename, 'r') as f:
            self.assertIn("is not a valid command", f.read())


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_legacy_file_error(self):
        with open(self.out_filename, 'w') as f:
            self.dbg.SetErrorFileHandle(f, False)
            self.handleCmd('lolwut', check=False, collect_result=False)
        with open(self.out_filename, 'r') as f:
            errors = f.read()
            self.assertTrue(re.search(r'error:.*lolwut', errors))

    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_type_errors(self):
        sbf = lldb.SBFile()
        self.assertRaises(Exception, sbf.Write, None)
        self.assertRaises(Exception, sbf.Read, None)
        self.assertRaises(Exception, sbf.Read, b'this bytes is not mutable')
        self.assertRaises(Exception, sbf.Write, u"ham sandwich")
        self.assertRaises(Exception, sbf.Read, u"ham sandwich")


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_fileno(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f.fileno(), "w", False)
            self.assertTrue(sbf.IsValid())
            e, n = sbf.Write(b'FOO\nBAR')
            self.assertTrue(e.Success())
            self.assertEqual(n, 7)
            sbf.Close()
            self.assertFalse(sbf.IsValid())
        with open(self.out_filename, 'r') as f:
            self.assertEqual(readStrippedLines(f), ['FOO', 'BAR'])


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f)
            e, n = sbf.Write(b'FOO\n')
            self.assertTrue(e.Success())
            self.assertEqual(n, 4)
            sbf.Close()
            self.assertTrue(f.closed)
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), 'FOO')


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_read_fileno(self):
        with open(self.out_filename, 'w') as f:
            f.write('FOO')
        with open(self.out_filename, 'r') as f:
            sbf = lldb.SBFile(f.fileno(), "r", False)
            self.assertTrue(sbf.IsValid())
            buffer = bytearray(100)
            e, n = sbf.Read(buffer)
            self.assertTrue(e.Success())
            self.assertEqual(buffer[:n], b'FOO')


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_read(self):
        with open(self.out_filename, 'w') as f:
            f.write('foo')
        with open(self.out_filename, 'r') as f:
            sbf = lldb.SBFile(f)
            buf = bytearray(100)
            e, n = sbf.Read(buf)
            self.assertTrue(e.Success())
            self.assertEqual(n, 3)
            self.assertEqual(buf[:n], b'foo')
            sbf.Close()
            self.assertTrue(f.closed)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_fileno_out(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f.fileno(), "w", False)
            status = self.dbg.SetOutputFile(sbf)
            self.assertTrue(status.Success())
            self.handleCmd('script 1+2')
            self.dbg.GetOutputFile().Write(b'quux')
            self.dbg.GetOutputFile().Flush()

        with open(self.out_filename, 'r') as f:
            self.assertEqual(readStrippedLines(f), ['3', 'quux'])


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_fileno_help(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f.fileno(), "w", False)
            status = self.dbg.SetOutputFile(sbf)
            self.assertTrue(status.Success())
            self.handleCmd("help help", collect_result=False, check=False)
        with open(self.out_filename, 'r') as f:
            self.assertTrue(re.search(r'Show a list of all debugger commands', f.read()))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_help(self):
        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetOutputFile(lldb.SBFile(f))
            self.assertTrue(status.Success())
            self.handleCmd("help help", check=False, collect_result=False)
        with open(self.out_filename, 'r') as f:
            self.assertIn('Show a list of all debugger commands', f.read())


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_immediate(self):
        with open(self.out_filename, 'w') as f:
            ret = lldb.SBCommandReturnObject()
            ret.SetImmediateOutputFile(f)
            interpreter = self.dbg.GetCommandInterpreter()
            interpreter.HandleCommand("help help", ret)
            # make sure the file wasn't closed early.
            f.write("\nQUUX\n")
        ret = None # call destructor and flush streams
        with open(self.out_filename, 'r') as f:
            output = f.read()
            self.assertTrue(re.search(r'Show a list of all debugger commands', output))
            self.assertTrue(re.search(r'QUUX', output))


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_immediate_string(self):
        f = io.StringIO()
        ret = lldb.SBCommandReturnObject()
        ret.SetImmediateOutputFile(f)
        interpreter = self.dbg.GetCommandInterpreter()
        interpreter.HandleCommand("help help", ret)
        # make sure the file wasn't closed early.
        f.write("\nQUUX\n")
        ret = None # call destructor and flush streams
        output = f.getvalue()
        self.assertTrue(re.search(r'Show a list of all debugger commands', output))
        self.assertTrue(re.search(r'QUUX', output))


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_immediate_sbfile_string(self):
        f = io.StringIO()
        ret = lldb.SBCommandReturnObject()
        ret.SetImmediateOutputFile(lldb.SBFile(f))
        interpreter = self.dbg.GetCommandInterpreter()
        interpreter.HandleCommand("help help", ret)
        output = f.getvalue()
        ret = None # call destructor and flush streams
        # sbfile default constructor doesn't borrow the file
        self.assertTrue(f.closed)
        self.assertTrue(re.search(r'Show a list of all debugger commands', output))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_fileno_inout(self):
        with open(self.in_filename, 'w') as f:
            f.write("help help\n")

        with open(self.out_filename, 'w') as outf, open(self.in_filename, 'r') as inf:

            outsbf = lldb.SBFile(outf.fileno(), "w", False)
            status = self.dbg.SetOutputFile(outsbf)
            self.assertTrue(status.Success())

            insbf = lldb.SBFile(inf.fileno(), "r", False)
            status = self.dbg.SetInputFile(insbf)
            self.assertTrue(status.Success())

            opts = lldb.SBCommandInterpreterRunOptions()
            self.dbg.RunCommandInterpreter(True, False, opts, 0, False, False)
            self.dbg.GetOutputFile().Flush()

        with open(self.out_filename, 'r') as f:
            self.assertTrue(re.search(r'Show a list of all debugger commands', f.read()))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_inout(self):
        with open(self.in_filename, 'w') as f:
            f.write("help help\n")
        with  open(self.out_filename, 'w') as outf, \
              open(self.in_filename, 'r') as inf:
            status = self.dbg.SetOutputFile(lldb.SBFile(outf))
            self.assertTrue(status.Success())
            status = self.dbg.SetInputFile(lldb.SBFile(inf))
            self.assertTrue(status.Success())
            opts = lldb.SBCommandInterpreterRunOptions()
            self.dbg.RunCommandInterpreter(True, False, opts, 0, False, False)
            self.dbg.GetOutputFile().Flush()
        with open(self.out_filename, 'r') as f:
            output = f.read()
            self.assertIn('Show a list of all debugger commands', output)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_binary_inout(self):
        with open(self.in_filename, 'w') as f:
            f.write("help help\n")
        with  open(self.out_filename, 'wb') as outf, \
              open(self.in_filename, 'rb') as inf:
            status = self.dbg.SetOutputFile(lldb.SBFile(outf))
            self.assertTrue(status.Success())
            status = self.dbg.SetInputFile(lldb.SBFile(inf))
            self.assertTrue(status.Success())
            opts = lldb.SBCommandInterpreterRunOptions()
            self.dbg.RunCommandInterpreter(True, False, opts, 0, False, False)
            self.dbg.GetOutputFile().Flush()
        with open(self.out_filename, 'r') as f:
            output = f.read()
            self.assertIn('Show a list of all debugger commands', output)


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_string_inout(self):
        inf = io.StringIO("help help\np/x ~0\n")
        outf = io.StringIO()
        status = self.dbg.SetOutputFile(lldb.SBFile(outf))
        self.assertTrue(status.Success())
        status = self.dbg.SetInputFile(lldb.SBFile(inf))
        self.assertTrue(status.Success())
        opts = lldb.SBCommandInterpreterRunOptions()
        self.dbg.RunCommandInterpreter(True, False, opts, 0, False, False)
        self.dbg.GetOutputFile().Flush()
        output = outf.getvalue()
        self.assertIn('Show a list of all debugger commands', output)
        self.assertIn('0xfff', output)


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_bytes_inout(self):
        inf = io.BytesIO(b"help help\nhelp b\n")
        outf = io.BytesIO()
        status = self.dbg.SetOutputFile(lldb.SBFile(outf))
        self.assertTrue(status.Success())
        status = self.dbg.SetInputFile(lldb.SBFile(inf))
        self.assertTrue(status.Success())
        opts = lldb.SBCommandInterpreterRunOptions()
        self.dbg.RunCommandInterpreter(True, False, opts, 0, False, False)
        self.dbg.GetOutputFile().Flush()
        output = outf.getvalue()
        self.assertIn(b'Show a list of all debugger commands', output)
        self.assertIn(b'Set a breakpoint', output)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_fileno_error(self):
        with open(self.out_filename, 'w') as f:

            sbf = lldb.SBFile(f.fileno(), 'w', False)
            status = self.dbg.SetErrorFile(sbf)
            self.assertTrue(status.Success())

            self.handleCmd('lolwut', check=False, collect_result=False)

            self.dbg.GetErrorFile().Write(b'\nzork\n')

        with open(self.out_filename, 'r') as f:
            errors = f.read()
            self.assertTrue(re.search(r'error:.*lolwut', errors))
            self.assertTrue(re.search(r'zork', errors))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_replace_stdout(self):
        f = io.StringIO()
        with replace_stdout(f):
            self.assertEqual(sys.stdout, f)
            self.handleCmd('script sys.stdout.write("lol")',
                collect_result=False, check=False)
            self.assertEqual(sys.stdout, f)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_replace_stdout_with_nonfile(self):
        f = io.StringIO()
        with replace_stdout(f):
            class Nothing():
                pass
            with replace_stdout(Nothing):
                self.assertEqual(sys.stdout, Nothing)
                self.handleCmd('script sys.stdout.write("lol")',
                    check=False, collect_result=False)
                self.assertEqual(sys.stdout, Nothing)
            sys.stdout.write(u"FOO")
        self.assertEqual(f.getvalue(), "FOO")


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_borrowed(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile.Create(f, borrow=True)
            e, n = sbf.Write(b'FOO')
            self.assertTrue(e.Success())
            self.assertEqual(n, 3)
            sbf.Close()
            self.assertFalse(f.closed)
            f.write('BAR\n')
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), 'FOOBAR')



    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_forced(self):
        with open(self.out_filename, 'w') as f:
            written = MutableBool(False)
            orig_write = f.write
            def mywrite(x):
                written.set(True)
                return orig_write(x)
            f.write = mywrite
            sbf = lldb.SBFile.Create(f, force_io_methods=True)
            e, n = sbf.Write(b'FOO')
            self.assertTrue(written)
            self.assertTrue(e.Success())
            self.assertEqual(n, 3)
            sbf.Close()
            self.assertTrue(f.closed)
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), 'FOO')


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_forced_borrowed(self):
        with open(self.out_filename, 'w') as f:
            written = MutableBool(False)
            orig_write = f.write
            def mywrite(x):
                written.set(True)
                return orig_write(x)
            f.write = mywrite
            sbf = lldb.SBFile.Create(f, borrow=True, force_io_methods=True)
            e, n = sbf.Write(b'FOO')
            self.assertTrue(written)
            self.assertTrue(e.Success())
            self.assertEqual(n, 3)
            sbf.Close()
            self.assertFalse(f.closed)
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), 'FOO')


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_string(self):
        f = io.StringIO()
        sbf = lldb.SBFile(f)
        e, n = sbf.Write(b'FOO')
        self.assertEqual(f.getvalue().strip(), "FOO")
        self.assertTrue(e.Success())
        self.assertEqual(n, 3)
        sbf.Close()
        self.assertTrue(f.closed)


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_string_out(self):
        f = io.StringIO()
        status = self.dbg.SetOutputFile(f)
        self.assertTrue(status.Success())
        self.handleCmd("script 'foobar'")
        self.assertEqual(f.getvalue().strip(), "'foobar'")


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_string_error(self):
        f = io.StringIO()
        status = self.dbg.SetErrorFile(f)
        self.assertTrue(status.Success())
        self.handleCmd('lolwut', check=False, collect_result=False)
        errors = f.getvalue()
        self.assertTrue(re.search(r'error:.*lolwut', errors))


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_write_bytes(self):
        f = io.BytesIO()
        sbf = lldb.SBFile(f)
        e, n = sbf.Write(b'FOO')
        self.assertEqual(f.getvalue().strip(), b"FOO")
        self.assertTrue(e.Success())
        self.assertEqual(n, 3)
        sbf.Close()
        self.assertTrue(f.closed)

    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_read_string(self):
        f = io.StringIO('zork')
        sbf = lldb.SBFile(f)
        buf = bytearray(100)
        e, n = sbf.Read(buf)
        self.assertTrue(e.Success())
        self.assertEqual(buf[:n], b'zork')


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_read_string_one_byte(self):
        f = io.StringIO('z')
        sbf = lldb.SBFile(f)
        buf = bytearray(1)
        e, n = sbf.Read(buf)
        self.assertTrue(e.Fail())
        self.assertEqual(n, 0)
        self.assertEqual(e.GetCString(), "can't read less than 6 bytes from a utf8 text stream")


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_read_bytes(self):
        f = io.BytesIO(b'zork')
        sbf = lldb.SBFile(f)
        buf = bytearray(100)
        e, n = sbf.Read(buf)
        self.assertTrue(e.Success())
        self.assertEqual(buf[:n], b'zork')


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_out(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f)
            status = self.dbg.SetOutputFile(sbf)
            self.assertTrue(status.Success())
            self.handleCmd('script 2+2')
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), '4')


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_file_out(self):
        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetOutputFile(f)
            self.assertTrue(status.Success())
            self.handleCmd('script 2+2')
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), '4')


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbfile_error(self):
        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f)
            status = self.dbg.SetErrorFile(sbf)
            self.assertTrue(status.Success())
            self.handleCmd('lolwut', check=False, collect_result=False)
        with open(self.out_filename, 'r') as f:
            errors = f.read()
            self.assertTrue(re.search(r'error:.*lolwut', errors))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_file_error(self):
        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetErrorFile(f)
            self.assertTrue(status.Success())
            self.handleCmd('lolwut', check=False, collect_result=False)
        with open(self.out_filename, 'r') as f:
            errors = f.read()
            self.assertTrue(re.search(r'error:.*lolwut', errors))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_exceptions(self):
        self.assertRaises(Exception, lldb.SBFile, None)
        self.assertRaises(Exception, lldb.SBFile, "ham sandwich")
        if sys.version_info[0] < 3:
            self.assertRaises(Exception, lldb.SBFile, ReallyBadIO())
        else:
            self.assertRaises(OhNoe, lldb.SBFile, ReallyBadIO())
            error, n = lldb.SBFile(BadIO()).Write(b"FOO")
            self.assertEqual(n, 0)
            self.assertTrue(error.Fail())
            self.assertIn('OH NOE', error.GetCString())
            error, n = lldb.SBFile(BadIO()).Read(bytearray(100))
            self.assertEqual(n, 0)
            self.assertTrue(error.Fail())
            self.assertIn('OH NOE', error.GetCString())


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_exceptions_logged(self):
        messages = list()
        self.dbg.SetLoggingCallback(messages.append)
        self.handleCmd('log enable lldb script')
        self.dbg.SetOutputFile(lldb.SBFile(BadIO()))
        self.handleCmd('script 1+1')
        self.assertTrue(any('OH NOE' in msg for msg in messages))


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_flush(self):
        flushed = MutableBool(False)
        closed = MutableBool(False)
        f = FlushTestIO(flushed, closed)
        self.assertFalse(flushed)
        self.assertFalse(closed)
        sbf = lldb.SBFile(f)
        self.assertFalse(flushed)
        self.assertFalse(closed)
        sbf = None
        self.assertFalse(flushed)
        self.assertTrue(closed)
        self.assertTrue(f.closed)

        flushed = MutableBool(False)
        closed = MutableBool(False)
        f = FlushTestIO(flushed, closed)
        self.assertFalse(flushed)
        self.assertFalse(closed)
        sbf = lldb.SBFile.Create(f, borrow=True)
        self.assertFalse(flushed)
        self.assertFalse(closed)
        sbf = None
        self.assertTrue(flushed)
        self.assertFalse(closed)
        self.assertFalse(f.closed)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_fileno_flush(self):
        with open(self.out_filename, 'w') as f:
            f.write("foo")
            sbf = lldb.SBFile(f)
            sbf.Write(b'bar')
            sbf = None
            self.assertTrue(f.closed)
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read(), 'foobar')

        with open(self.out_filename, 'w+') as f:
            f.write("foo")
            sbf = lldb.SBFile.Create(f, borrow=True)
            sbf.Write(b'bar')
            sbf = None
            self.assertFalse(f.closed)
            f.seek(0)
            self.assertEqual(f.read(), 'foobar')


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_close(self):
        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetOutputFile(f)
            self.assertTrue(status.Success())
            self.handleCmd("help help", check=False, collect_result=False)
            # make sure the file wasn't closed early.
            f.write("\nZAP\n")
            lldb.SBDebugger.Destroy(self.dbg)
            # check that output file was closed when debugger was destroyed.
            with self.assertRaises(ValueError):
                f.write("\nQUUX\n")
        with open(self.out_filename, 'r') as f:
            output = f.read()
            self.assertTrue(re.search(r'Show a list of all debugger commands', output))
            self.assertTrue(re.search(r'ZAP', output))


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_stdout(self):
        f = io.StringIO()
        status = self.dbg.SetOutputFile(f)
        self.assertTrue(status.Success())
        self.handleCmd(r"script sys.stdout.write('foobar\n')")
        self.assertEqual(f.getvalue().strip().split(), ["foobar", "7"])


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_stdout_file(self):
        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetOutputFile(f)
            self.assertTrue(status.Success())
            self.handleCmd(r"script sys.stdout.write('foobar\n')")
        with open(self.out_filename, 'r') as f:
            # In python2 sys.stdout.write() returns None, which
            # the REPL will ignore, but in python3 it will
            # return the number of bytes written, which the REPL
            # will print out.
            lines = [x for x in f.read().strip().split() if x != "7"]
            self.assertEqual(lines, ["foobar"])


    @add_test_categories(['pyapi'])
    @skipIf(py_version=['<', (3,)])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_identity(self):

        f = io.StringIO()
        sbf = lldb.SBFile(f)
        self.assertTrue(f is sbf.GetFile())
        sbf.Close()
        self.assertTrue(f.closed)

        f = io.StringIO()
        sbf = lldb.SBFile.Create(f, borrow=True)
        self.assertTrue(f is sbf.GetFile())
        sbf.Close()
        self.assertFalse(f.closed)

        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile(f)
            self.assertTrue(f is sbf.GetFile())
            sbf.Close()
            self.assertTrue(f.closed)

        with open(self.out_filename, 'w') as f:
            sbf = lldb.SBFile.Create(f, borrow=True)
            self.assertFalse(f is sbf.GetFile())
            sbf.Write(b"foobar\n")
            self.assertEqual(f.fileno(), sbf.GetFile().fileno())
            sbf.Close()
            self.assertFalse(f.closed)

        with open(self.out_filename, 'r') as f:
            self.assertEqual("foobar", f.read().strip())

        with open(self.out_filename, 'wb') as f:
            sbf = lldb.SBFile.Create(f, borrow=True, force_io_methods=True)
            self.assertTrue(f is sbf.GetFile())
            sbf.Write(b"foobar\n")
            self.assertEqual(f.fileno(), sbf.GetFile().fileno())
            sbf.Close()
            self.assertFalse(f.closed)

        with open(self.out_filename, 'r') as f:
            self.assertEqual("foobar", f.read().strip())

        with open(self.out_filename, 'wb') as f:
            sbf = lldb.SBFile.Create(f, force_io_methods=True)
            self.assertTrue(f is sbf.GetFile())
            sbf.Write(b"foobar\n")
            self.assertEqual(f.fileno(), sbf.GetFile().fileno())
            sbf.Close()
            self.assertTrue(f.closed)

        with open(self.out_filename, 'r') as f:
            self.assertEqual("foobar", f.read().strip())


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_back_and_forth(self):
        with open(self.out_filename, 'w') as f:
            # at each step here we're borrowing the file, so we have to keep
            # them all alive until the end.
            sbf = lldb.SBFile.Create(f, borrow=True)
            def i(sbf):
                for i in range(10):
                    f = sbf.GetFile()
                    self.assertEqual(f.mode, "w")
                    yield f
                    sbf = lldb.SBFile.Create(f, borrow=True)
                    yield sbf
                    sbf.Write(str(i).encode('ascii') + b"\n")
            files = list(i(sbf))
        with open(self.out_filename, 'r') as f:
            self.assertEqual(list(range(10)), list(map(int, f.read().strip().split())))


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_set_filehandle_none(self):
        self.assertRaises(Exception, self.dbg.SetOutputFile, None)
        self.assertRaises(Exception, self.dbg.SetOutputFile, "ham sandwich")
        self.assertRaises(Exception, self.dbg.SetOutputFileHandle, "ham sandwich")
        self.assertRaises(Exception, self.dbg.SetInputFile, None)
        self.assertRaises(Exception, self.dbg.SetInputFile, "ham sandwich")
        self.assertRaises(Exception, self.dbg.SetInputFileHandle, "ham sandwich")
        self.assertRaises(Exception, self.dbg.SetErrorFile, None)
        self.assertRaises(Exception, self.dbg.SetErrorFile, "ham sandwich")
        self.assertRaises(Exception, self.dbg.SetErrorFileHandle, "ham sandwich")

        with open(self.out_filename, 'w') as f:
            status = self.dbg.SetOutputFile(f)
            self.assertTrue(status.Success())
            status = self.dbg.SetErrorFile(f)
            self.assertTrue(status.Success())
            self.dbg.SetOutputFileHandle(None, False)
            self.dbg.SetErrorFileHandle(None, False)
            sbf = self.dbg.GetOutputFile()
            if sys.version_info.major >= 3:
                # python 2 lacks PyFile_FromFd, so GetFile() will
                # have to duplicate the file descriptor and make a FILE*
                # in order to convert a NativeFile it back to a python
                # file.
                self.assertEqual(sbf.GetFile().fileno(), 1)
            sbf = self.dbg.GetErrorFile()
            if sys.version_info.major >= 3:
                self.assertEqual(sbf.GetFile().fileno(), 2)
        with open(self.out_filename, 'r') as f:
            status = self.dbg.SetInputFile(f)
            self.assertTrue(status.Success())
            self.dbg.SetInputFileHandle(None, False)
            sbf = self.dbg.GetInputFile()
            if sys.version_info.major >= 3:
                self.assertEqual(sbf.GetFile().fileno(), 0)


    @add_test_categories(['pyapi'])
    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
    def test_sbstream(self):

        with open(self.out_filename, 'w') as f:
            stream = lldb.SBStream()
            stream.RedirectToFile(f)
            stream.Print("zork")
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), "zork")

        with open(self.out_filename, 'w') as f:
            stream = lldb.SBStream()
            stream.RedirectToFileHandle(f, True)
            stream.Print("Yendor")
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), "Yendor")

        stream = lldb.SBStream()
        f = open(self.out_filename,  'w')
        stream.RedirectToFile(lldb.SBFile.Create(f, borrow=False))
        stream.Print("Frobozz")
        stream = None
        self.assertTrue(f.closed)
        with open(self.out_filename, 'r') as f:
            self.assertEqual(f.read().strip(), "Frobozz")