1"""
2Test lldb settings command.
3"""
4
5
6
7import os
8import re
9import lldb
10from lldbsuite.test.decorators import *
11from lldbsuite.test.lldbtest import *
12from lldbsuite.test import lldbutil
13
14
15class SettingsCommandTestCase(TestBase):
16
17    mydir = TestBase.compute_mydir(__file__)
18    NO_DEBUG_INFO_TESTCASE = True
19
20    def test_apropos_should_also_search_settings_description(self):
21        """Test that 'apropos' command should also search descriptions for the settings variables."""
22
23        self.expect("apropos 'environment variable'",
24                    substrs=["target.env-vars",
25                             "environment variables",
26                             "executable's environment"])
27
28    def test_set_interpreter_repeat_prev_command(self):
29        """Test the `interpreter.repeat-previous-command` setting."""
30        self.build()
31
32        exe = self.getBuildArtifact("a.out")
33        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
34        setting = "interpreter.repeat-previous-command"
35
36        def cleanup(setting):
37            self.runCmd(
38                "settings clear %s" %
39                setting, check=False)
40
41        # Execute the cleanup function during test case tear down.
42        self.addTearDownHook(cleanup(setting))
43
44        # First, check for the setting default value.
45        self.expect("setting show %s" % setting,
46                    substrs=["interpreter.repeat-previous-command (boolean) = true"])
47
48        # Then, invert the setting, and check that was set correctly
49        self.runCmd("setting set %s false" % setting)
50        self.expect("setting show %s" % setting,
51                    substrs=["interpreter.repeat-previous-command (boolean) = false"])
52
53
54        ci  = self.dbg.GetCommandInterpreter()
55        self.assertTrue(ci.IsValid(), "Invalid command interpreter.")
56        # Now, test the functionnality
57        res = lldb.SBCommandReturnObject()
58        ci.HandleCommand('breakpoint set -n main', res)
59        self.assertTrue(res.Succeeded(), "Command failed.")
60        ci.HandleCommand('', res)
61        self.assertTrue(res.Succeeded(), "Empty command failed.")
62        self.assertEqual(self.dbg.GetSelectedTarget().GetNumBreakpoints(), 1)
63
64    def test_append_target_env_vars(self):
65        """Test that 'append target.run-args' works."""
66        # Append the env-vars.
67        self.runCmd('settings append target.env-vars MY_ENV_VAR=YES')
68        # And add hooks to restore the settings during tearDown().
69        self.addTearDownHook(
70            lambda: self.runCmd("settings clear target.env-vars"))
71
72        # Check it immediately!
73        self.expect('settings show target.env-vars',
74                    substrs=['MY_ENV_VAR=YES'])
75
76    def test_insert_before_and_after_target_run_args(self):
77        """Test that 'insert-before/after target.run-args' works."""
78        # Set the run-args first.
79        self.runCmd('settings set target.run-args a b c')
80        # And add hooks to restore the settings during tearDown().
81        self.addTearDownHook(
82            lambda: self.runCmd("settings clear target.run-args"))
83
84        # Now insert-before the index-0 element with '__a__'.
85        self.runCmd('settings insert-before target.run-args 0 __a__')
86        # And insert-after the index-1 element with '__A__'.
87        self.runCmd('settings insert-after target.run-args 1 __A__')
88        # Check it immediately!
89        self.expect('settings show target.run-args',
90                    substrs=['target.run-args',
91                             '[0]: "__a__"',
92                             '[1]: "a"',
93                             '[2]: "__A__"',
94                             '[3]: "b"',
95                             '[4]: "c"'])
96
97    def test_replace_target_run_args(self):
98        """Test that 'replace target.run-args' works."""
99        # Set the run-args and then replace the index-0 element.
100        self.runCmd('settings set target.run-args a b c')
101        # And add hooks to restore the settings during tearDown().
102        self.addTearDownHook(
103            lambda: self.runCmd("settings clear target.run-args"))
104
105        # Now replace the index-0 element with 'A', instead.
106        self.runCmd('settings replace target.run-args 0 A')
107        # Check it immediately!
108        self.expect('settings show target.run-args',
109                    substrs=['target.run-args (arguments) =',
110                             '[0]: "A"',
111                             '[1]: "b"',
112                             '[2]: "c"'])
113
114    def test_set_prompt(self):
115        """Test that 'set prompt' actually changes the prompt."""
116
117        # Set prompt to 'lldb2'.
118        self.runCmd("settings set prompt 'lldb2 '")
119
120        # Immediately test the setting.
121        self.expect("settings show prompt", SETTING_MSG("prompt"),
122                    startstr='prompt (string) = "lldb2 "')
123
124        # The overall display should also reflect the new setting.
125        self.expect("settings show", SETTING_MSG("prompt"),
126                    substrs=['prompt (string) = "lldb2 "'])
127
128        # Use '-r' option to reset to the original default prompt.
129        self.runCmd("settings clear prompt")
130
131    def test_set_term_width(self):
132        """Test that 'set term-width' actually changes the term-width."""
133
134        self.runCmd("settings set term-width 70")
135
136        # Immediately test the setting.
137        self.expect("settings show term-width", SETTING_MSG("term-width"),
138                    startstr="term-width (int) = 70")
139
140        # The overall display should also reflect the new setting.
141        self.expect("settings show", SETTING_MSG("term-width"),
142                    substrs=["term-width (int) = 70"])
143
144    # rdar://problem/10712130
145    @skipIf(oslist=["windows"], bugnumber="llvm.org/pr44431")
146    def test_set_frame_format(self):
147        """Test that 'set frame-format' with a backtick char in the format string works as well as fullpath."""
148        self.build()
149
150        exe = self.getBuildArtifact("a.out")
151        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
152
153        def cleanup():
154            self.runCmd(
155                "settings set frame-format %s" %
156                self.format_string, check=False)
157
158        # Execute the cleanup function during test case tear down.
159        self.addTearDownHook(cleanup)
160
161        self.runCmd("settings show frame-format")
162        m = re.match(
163            '^frame-format \(format-string\) = "(.*)\"$',
164            self.res.GetOutput())
165        self.assertTrue(m, "Bad settings string")
166        self.format_string = m.group(1)
167
168        # Change the default format to print function.name rather than
169        # function.name-with-args
170        format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}\`${function.name}{${function.pc-offset}}}{ at ${line.file.fullpath}:${line.number}}{, lang=${language}}\n"
171        self.runCmd("settings set frame-format %s" % format_string)
172
173        # Immediately test the setting.
174        self.expect("settings show frame-format", SETTING_MSG("frame-format"),
175                    substrs=[format_string])
176
177        self.runCmd("breakpoint set -n main")
178        self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()),
179                RUN_SUCCEEDED)
180        self.expect("thread backtrace",
181                    substrs=["`main", self.getSourceDir()])
182
183    def test_set_auto_confirm(self):
184        """Test that after 'set auto-confirm true', manual confirmation should not kick in."""
185        self.build()
186
187        exe = self.getBuildArtifact("a.out")
188        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
189
190        self.runCmd("settings set auto-confirm true")
191
192        # Immediately test the setting.
193        self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
194                    startstr="auto-confirm (boolean) = true")
195
196        # Now 'breakpoint delete' should just work fine without confirmation
197        # prompt from the command interpreter.
198        self.runCmd("breakpoint set -n main")
199        self.expect("breakpoint delete",
200                    startstr="All breakpoints removed")
201
202        # Restore the original setting of auto-confirm.
203        self.runCmd("settings clear auto-confirm")
204        self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
205                    startstr="auto-confirm (boolean) = false")
206
207    @skipIf(archs=no_match(['x86_64', 'i386', 'i686']))
208    def test_disassembler_settings(self):
209        """Test that user options for the disassembler take effect."""
210        self.build()
211
212        exe = self.getBuildArtifact("a.out")
213        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
214
215        # AT&T syntax
216        self.runCmd("settings set target.x86-disassembly-flavor att")
217        self.runCmd("settings set target.use-hex-immediates false")
218        self.expect("disassemble -n numberfn",
219                    substrs=["$90"])
220        self.runCmd("settings set target.use-hex-immediates true")
221        self.runCmd("settings set target.hex-immediate-style c")
222        self.expect("disassemble -n numberfn",
223                    substrs=["$0x5a"])
224        self.runCmd("settings set target.hex-immediate-style asm")
225        self.expect("disassemble -n numberfn",
226                    substrs=["$5ah"])
227
228        # Intel syntax
229        self.runCmd("settings set target.x86-disassembly-flavor intel")
230        self.runCmd("settings set target.use-hex-immediates false")
231        self.expect("disassemble -n numberfn",
232                    substrs=["90"])
233        self.runCmd("settings set target.use-hex-immediates true")
234        self.runCmd("settings set target.hex-immediate-style c")
235        self.expect("disassemble -n numberfn",
236                    substrs=["0x5a"])
237        self.runCmd("settings set target.hex-immediate-style asm")
238        self.expect("disassemble -n numberfn",
239                    substrs=["5ah"])
240
241    @skipIfDarwinEmbedded   # <rdar://problem/34446098> debugserver on ios etc can't write files
242    @skipIfReproducer
243    def test_run_args_and_env_vars(self):
244        self.do_test_run_args_and_env_vars(use_launchsimple=False)
245
246    @skipIfDarwinEmbedded   # <rdar://problem/34446098> debugserver on ios etc can't write files
247    @skipIfReproducer
248    def test_launchsimple_args_and_env_vars(self):
249        self.do_test_run_args_and_env_vars(use_launchsimple=True)
250
251    def do_test_run_args_and_env_vars(self, use_launchsimple):
252        """Test that run-args and env-vars are passed to the launched process."""
253        self.build()
254
255        # Set the run-args and the env-vars.
256        # And add hooks to restore the settings during tearDown().
257        self.runCmd('settings set target.run-args A B C')
258        self.addTearDownHook(
259            lambda: self.runCmd("settings clear target.run-args"))
260        self.runCmd('settings set target.env-vars ["MY_ENV_VAR"]=YES')
261        self.addTearDownHook(
262            lambda: self.runCmd("settings clear target.env-vars"))
263
264        exe = self.getBuildArtifact("a.out")
265        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
266
267        target = self.dbg.GetTargetAtIndex(0)
268        launch_info = target.GetLaunchInfo()
269        found_env_var = False
270        for i in range(0, launch_info.GetNumEnvironmentEntries()):
271            if launch_info.GetEnvironmentEntryAtIndex(i) == "MY_ENV_VAR=YES":
272                found_env_var = True
273                break
274        self.assertTrue(found_env_var,
275                        "MY_ENV_VAR was not set in LunchInfo object")
276
277        self.assertEqual(launch_info.GetNumArguments(), 3)
278        self.assertEqual(launch_info.GetArgumentAtIndex(0), "A")
279        self.assertEqual(launch_info.GetArgumentAtIndex(1), "B")
280        self.assertEqual(launch_info.GetArgumentAtIndex(2), "C")
281
282        self.expect(
283            'target show-launch-environment',
284            substrs=["MY_ENV_VAR=YES"])
285
286        wd = self.get_process_working_directory()
287        if use_launchsimple:
288            process = target.LaunchSimple(None, None, wd)
289            self.assertTrue(process)
290        else:
291            self.runCmd("process launch --working-dir '{0}'".format(wd),
292                RUN_SUCCEEDED)
293
294        # Read the output file produced by running the program.
295        output = lldbutil.read_file_from_process_wd(self, "output2.txt")
296
297        self.expect(
298            output,
299            exe=False,
300            substrs=[
301                "argv[1] matches",
302                "argv[2] matches",
303                "argv[3] matches",
304                "Environment variable 'MY_ENV_VAR' successfully passed."])
305
306        # Check that env-vars overrides unset-env-vars.
307        self.runCmd('settings set target.unset-env-vars MY_ENV_VAR')
308
309        self.expect(
310            'target show-launch-environment',
311            'env-vars overrides unset-env-vars',
312            substrs=["MY_ENV_VAR=YES"])
313
314        wd = self.get_process_working_directory()
315        if use_launchsimple:
316            process = target.LaunchSimple(None, None, wd)
317            self.assertTrue(process)
318        else:
319            self.runCmd("process launch --working-dir '{0}'".format(wd),
320                RUN_SUCCEEDED)
321
322        # Read the output file produced by running the program.
323        output = lldbutil.read_file_from_process_wd(self, "output2.txt")
324
325        self.expect(
326            output,
327            exe=False,
328            substrs=[
329                "Environment variable 'MY_ENV_VAR' successfully passed."])
330
331    @skipIfRemote  # it doesn't make sense to send host env to remote target
332    @skipIfReproducer
333    def test_pass_host_env_vars(self):
334        """Test that the host env vars are passed to the launched process."""
335        self.build()
336
337        # Set some host environment variables now.
338        os.environ["MY_HOST_ENV_VAR1"] = "VAR1"
339        os.environ["MY_HOST_ENV_VAR2"] = "VAR2"
340
341        # This is the function to unset the two env variables set above.
342        def unset_env_variables():
343            os.environ.pop("MY_HOST_ENV_VAR1")
344            os.environ.pop("MY_HOST_ENV_VAR2")
345        self.addTearDownHook(unset_env_variables)
346
347        exe = self.getBuildArtifact("a.out")
348        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
349
350        # By default, inherit-env is 'true'.
351        self.expect(
352            'settings show target.inherit-env',
353            "Default inherit-env is 'true'",
354            startstr="target.inherit-env (boolean) = true")
355
356        self.expect(
357            'target show-launch-environment',
358            'Host environment is passed correctly',
359            substrs=['MY_HOST_ENV_VAR1=VAR1', 'MY_HOST_ENV_VAR2=VAR2'])
360        self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()),
361                RUN_SUCCEEDED)
362
363        # Read the output file produced by running the program.
364        output = lldbutil.read_file_from_process_wd(self, "output1.txt")
365
366        self.expect(
367            output,
368            exe=False,
369            substrs=[
370                "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.",
371                "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."])
372
373        # Now test that we can prevent the inferior from inheriting the
374        # environment.
375        self.runCmd('settings set target.inherit-env false')
376
377        self.expect(
378            'target show-launch-environment',
379            'target.inherit-env affects `target show-launch-environment`',
380            matching=False,
381            substrs = ['MY_HOST_ENV_VAR1=VAR1', 'MY_HOST_ENV_VAR2=VAR2'])
382
383        self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()),
384                RUN_SUCCEEDED)
385
386        # Read the output file produced by running the program.
387        output = lldbutil.read_file_from_process_wd(self, "output1.txt")
388
389        self.expect(
390            output,
391            exe=False,
392            matching=False,
393            substrs=[
394                "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.",
395                "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."])
396
397        # Now test that we can unset variables from the inherited environment.
398        self.runCmd('settings set target.inherit-env true')
399        self.runCmd('settings set target.unset-env-vars MY_HOST_ENV_VAR1')
400        self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()),
401                RUN_SUCCEEDED)
402
403        # Read the output file produced by running the program.
404        output = lldbutil.read_file_from_process_wd(self, "output1.txt")
405
406        self.expect(
407            'target show-launch-environment',
408            'MY_HOST_ENV_VAR1 is unset, it shouldn\'t be in `target show-launch-environment`',
409            matching=False,
410            substrs = ['MY_HOST_ENV_VAR1=VAR1'])
411        self.expect(
412            'target show-launch-environment',
413            'MY_HOST_ENV_VAR2 shouldn be in `target show-launch-environment`',
414            substrs = ['MY_HOST_ENV_VAR2=VAR2'])
415
416        self.expect(
417            output,
418            exe=False,
419            matching=False,
420            substrs=[
421                "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed."])
422        self.expect(
423            output,
424            exe=False,
425            substrs=[
426                "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."])
427
428    @skipIfDarwinEmbedded   # <rdar://problem/34446098> debugserver on ios etc can't write files
429    @skipIfReproducer
430    def test_set_error_output_path(self):
431        """Test that setting target.error/output-path for the launched process works."""
432        self.build()
433
434        exe = self.getBuildArtifact("a.out")
435        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
436
437        # Set the error-path and output-path and verify both are set.
438        self.runCmd("settings set target.error-path '{0}'".format(
439            lldbutil.append_to_process_working_directory(self, "stderr.txt")))
440        self.runCmd("settings set target.output-path '{0}".format(
441            lldbutil.append_to_process_working_directory(self, "stdout.txt")))
442        # And add hooks to restore the original settings during tearDown().
443        self.addTearDownHook(
444            lambda: self.runCmd("settings clear target.output-path"))
445        self.addTearDownHook(
446            lambda: self.runCmd("settings clear target.error-path"))
447
448        self.expect("settings show target.error-path",
449                    SETTING_MSG("target.error-path"),
450                    substrs=['target.error-path (file)', 'stderr.txt"'])
451
452        self.expect("settings show target.output-path",
453                    SETTING_MSG("target.output-path"),
454                    substrs=['target.output-path (file)', 'stdout.txt"'])
455
456        self.runCmd("process launch --working-dir '{0}'".format(self.get_process_working_directory()),
457                RUN_SUCCEEDED)
458
459        output = lldbutil.read_file_from_process_wd(self, "stderr.txt")
460        message = "This message should go to standard error."
461        if lldbplatformutil.hasChattyStderr(self):
462            self.expect(output, exe=False, substrs=[message])
463        else:
464            self.expect(output, exe=False, startstr=message)
465
466        output = lldbutil.read_file_from_process_wd(self, "stdout.txt")
467        self.expect(output, exe=False,
468                    startstr="This message should go to standard out.")
469
470    def test_print_dictionary_setting(self):
471        self.runCmd("settings clear target.env-vars")
472        self.runCmd("settings set target.env-vars [\"MY_VAR\"]=some-value")
473        self.expect("settings show target.env-vars",
474                    substrs=["MY_VAR=some-value"])
475        self.runCmd("settings clear target.env-vars")
476
477    def test_print_array_setting(self):
478        self.runCmd("settings clear target.run-args")
479        self.runCmd("settings set target.run-args gobbledy-gook")
480        self.expect("settings show target.run-args",
481                    substrs=['[0]: "gobbledy-gook"'])
482        self.runCmd("settings clear target.run-args")
483
484    def test_settings_with_quotes(self):
485        self.runCmd("settings clear target.run-args")
486        self.runCmd("settings set target.run-args a b c")
487        self.expect("settings show target.run-args",
488                    substrs=['[0]: "a"',
489                             '[1]: "b"',
490                             '[2]: "c"'])
491        self.runCmd("settings set target.run-args 'a b c'")
492        self.expect("settings show target.run-args",
493                    substrs=['[0]: "a b c"'])
494        self.runCmd("settings clear target.run-args")
495        self.runCmd("settings clear target.env-vars")
496        self.runCmd(
497            'settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"')
498        self.expect("settings show target.env-vars",
499                    substrs=['MY_FILE=this is a file name with spaces.txt'])
500        self.runCmd("settings clear target.env-vars")
501        # Test and make sure that setting "format-string" settings obeys quotes
502        # if they are provided
503        self.runCmd("settings set thread-format    'abc def'   ")
504        self.expect("settings show thread-format",
505                    startstr='thread-format (format-string) = "abc def"')
506        self.runCmd('settings set thread-format    "abc def"   ')
507        self.expect("settings show thread-format",
508                    startstr='thread-format (format-string) = "abc def"')
509        # Make sure when no quotes are provided that we maintain any trailing
510        # spaces
511        self.runCmd('settings set thread-format abc def   ')
512        self.expect("settings show thread-format",
513                    startstr='thread-format (format-string) = "abc def   "')
514        self.runCmd('settings clear thread-format')
515
516    def test_settings_with_trailing_whitespace(self):
517
518        # boolean
519        # Set to known value
520        self.runCmd("settings set target.skip-prologue true")
521        # Set to new value with trailing whitespace
522        self.runCmd("settings set target.skip-prologue false ")
523        # Make sure the setting was correctly set to "false"
524        self.expect(
525            "settings show target.skip-prologue",
526            SETTING_MSG("target.skip-prologue"),
527            startstr="target.skip-prologue (boolean) = false")
528        self.runCmd("settings clear target.skip-prologue", check=False)
529        # integer
530        self.runCmd("settings set term-width 70")      # Set to known value
531        # Set to new value with trailing whitespaces
532        self.runCmd("settings set term-width 60 \t")
533        self.expect("settings show term-width", SETTING_MSG("term-width"),
534                    startstr="term-width (int) = 60")
535        self.runCmd("settings clear term-width", check=False)
536        # string
537        self.runCmd("settings set target.arg0 abc")    # Set to known value
538        # Set to new value with trailing whitespaces
539        self.runCmd("settings set target.arg0 cde\t ")
540        self.expect("settings show target.arg0", SETTING_MSG("target.arg0"),
541                    startstr='target.arg0 (string) = "cde"')
542        self.runCmd("settings clear target.arg0", check=False)
543        # file
544        path1 = self.getBuildArtifact("path1.txt")
545        path2 = self.getBuildArtifact("path2.txt")
546        self.runCmd(
547            "settings set target.output-path %s" %
548            path1)   # Set to known value
549        self.expect(
550            "settings show target.output-path",
551            SETTING_MSG("target.output-path"),
552            startstr='target.output-path (file) = ',
553            substrs=[path1])
554        self.runCmd("settings set target.output-path %s " %
555                    path2)  # Set to new value with trailing whitespaces
556        self.expect(
557            "settings show target.output-path",
558            SETTING_MSG("target.output-path"),
559            startstr='target.output-path (file) = ',
560            substrs=[path2])
561        self.runCmd("settings clear target.output-path", check=False)
562        # enum
563        # Set to known value
564        self.runCmd("settings set stop-disassembly-display never")
565        # Set to new value with trailing whitespaces
566        self.runCmd("settings set stop-disassembly-display always ")
567        self.expect(
568            "settings show stop-disassembly-display",
569            SETTING_MSG("stop-disassembly-display"),
570            startstr='stop-disassembly-display (enum) = always')
571        self.runCmd("settings clear stop-disassembly-display", check=False)
572        # language
573        # Set to known value
574        self.runCmd("settings set target.language c89")
575        # Set to new value with trailing whitespace
576        self.runCmd("settings set target.language c11 ")
577        self.expect(
578            "settings show target.language",
579            SETTING_MSG("target.language"),
580            startstr="target.language (language) = c11")
581        self.runCmd("settings clear target.language", check=False)
582        # arguments
583        self.runCmd("settings set target.run-args 1 2 3")  # Set to known value
584        # Set to new value with trailing whitespaces
585        self.runCmd("settings set target.run-args 3 4 5 ")
586        self.expect(
587            "settings show target.run-args",
588            SETTING_MSG("target.run-args"),
589            substrs=[
590                'target.run-args (arguments) =',
591                '[0]: "3"',
592                '[1]: "4"',
593                '[2]: "5"'])
594        self.runCmd("settings set target.run-args 1 2 3")  # Set to known value
595        # Set to new value with trailing whitespaces
596        self.runCmd("settings set target.run-args 3 \  \ ")
597        self.expect(
598            "settings show target.run-args",
599            SETTING_MSG("target.run-args"),
600            substrs=[
601                'target.run-args (arguments) =',
602                '[0]: "3"',
603                '[1]: " "',
604                '[2]: " "'])
605        self.runCmd("settings clear target.run-args", check=False)
606        # dictionaries
607        self.runCmd("settings clear target.env-vars")  # Set to known value
608        # Set to new value with trailing whitespaces
609        self.runCmd("settings set target.env-vars A=B C=D\t ")
610        self.expect(
611            "settings show target.env-vars",
612            SETTING_MSG("target.env-vars"),
613            substrs=[
614                'target.env-vars (dictionary of strings) =',
615                'A=B',
616                'C=D'])
617        self.runCmd("settings clear target.env-vars", check=False)
618        # regex
619        # Set to known value
620        self.runCmd("settings clear target.process.thread.step-avoid-regexp")
621        # Set to new value with trailing whitespaces
622        self.runCmd(
623            "settings set target.process.thread.step-avoid-regexp foo\\ ")
624        self.expect(
625            "settings show target.process.thread.step-avoid-regexp",
626            SETTING_MSG("target.process.thread.step-avoid-regexp"),
627            substrs=['target.process.thread.step-avoid-regexp (regex) = foo\\ '])
628        self.runCmd(
629            "settings clear target.process.thread.step-avoid-regexp",
630            check=False)
631        # format-string
632        self.runCmd("settings clear disassembly-format")  # Set to known value
633        # Set to new value with trailing whitespaces
634        self.runCmd("settings set disassembly-format foo ")
635        self.expect("settings show disassembly-format",
636                    SETTING_MSG("disassembly-format"),
637                    substrs=['disassembly-format (format-string) = "foo "'])
638        self.runCmd("settings clear disassembly-format", check=False)
639
640    def test_settings_list(self):
641        # List settings (and optionally test the filter to only show 'target' settings).
642        self.expect("settings list target", substrs=["arg0", "detach-on-error", "language"])
643        self.expect("settings list target", matching=False, substrs=["packet-timeout"])
644        self.expect("settings list", substrs=["language", "arg0", "detach-on-error", "packet-timeout"])
645
646    def test_settings_remove_single(self):
647        # Set some environment variables and use 'remove' to delete them.
648        self.runCmd("settings set target.env-vars a=b c=d")
649        self.expect("settings show target.env-vars", substrs=["a=b", "c=d"])
650        self.runCmd("settings remove target.env-vars a")
651        self.expect("settings show target.env-vars", matching=False, substrs=["a=b"])
652        self.expect("settings show target.env-vars", substrs=["c=d"])
653        self.runCmd("settings remove target.env-vars c")
654        self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "c=d"])
655
656    def test_settings_remove_multiple(self):
657        self.runCmd("settings set target.env-vars a=b c=d e=f")
658        self.expect("settings show target.env-vars", substrs=["a=b", "c=d", "e=f"])
659        self.runCmd("settings remove target.env-vars a e")
660        self.expect("settings show target.env-vars", matching=False, substrs=["a=b", "e=f"])
661        self.expect("settings show target.env-vars", substrs=["c=d"])
662
663    def test_settings_remove_nonexistent_value(self):
664        self.expect("settings remove target.env-vars doesntexist", error=True,
665                    substrs=["no value found named 'doesntexist'"])
666
667    def test_settings_remove_nonexistent_settings(self):
668        self.expect("settings remove doesntexist alsodoesntexist", error=True,
669                    substrs=["error: invalid value path 'doesntexist'"])
670
671    def test_settings_remove_missing_arg(self):
672        self.expect("settings remove", error=True,
673                    substrs=["'settings remove' takes an array or dictionary item, or"])
674
675    def test_settings_remove_empty_arg(self):
676        self.expect("settings remove ''", error=True,
677                    substrs=["'settings remove' command requires a valid variable name"])
678
679    def test_settings_clear_all(self):
680        # Change a dictionary.
681        self.runCmd("settings set target.env-vars a=1 b=2 c=3")
682        # Change an array.
683        self.runCmd("settings set target.run-args a1 b2 c3")
684        # Change a single boolean value.
685        self.runCmd("settings set auto-confirm true")
686        # Change a single integer value.
687        self.runCmd("settings set tab-size 2")
688
689        # Clear everything.
690        self.runCmd("settings clear --all")
691
692        # Check that settings have their default values after clearing.
693        self.expect("settings show target.env-vars", patterns=['^target.env-vars \(dictionary of strings\) =\s*$'])
694        self.expect("settings show target.run-args", patterns=['^target.run-args \(arguments\) =\s*$'])
695        self.expect("settings show auto-confirm", substrs=["false"])
696        self.expect("settings show tab-size", substrs=["4"])
697
698        # Check that the command fails if we combine '--all' option with any arguments.
699        self.expect(
700            "settings clear --all auto-confirm",
701            COMMAND_FAILED_AS_EXPECTED,
702            error=True,
703            substrs=["'settings clear --all' doesn't take any arguments"])
704
705    def test_all_settings_exist(self):
706        self.expect("settings show",
707                    substrs=["auto-confirm",
708                             "frame-format",
709                             "notify-void",
710                             "prompt",
711                             "script-lang",
712                             "stop-disassembly-count",
713                             "stop-disassembly-display",
714                             "stop-line-count-after",
715                             "stop-line-count-before",
716                             "stop-show-column",
717                             "term-width",
718                             "thread-format",
719                             "use-external-editor",
720                             "target.breakpoints-use-platform-avoid-list",
721                             "target.default-arch",
722                             "target.disable-aslr",
723                             "target.disable-stdio",
724                             "target.x86-disassembly-flavor",
725                             "target.enable-synthetic-value",
726                             "target.env-vars",
727                             "target.error-path",
728                             "target.exec-search-paths",
729                             "target.expr-prefix",
730                             "target.hex-immediate-style",
731                             "target.inherit-env",
732                             "target.input-path",
733                             "target.language",
734                             "target.max-children-count",
735                             "target.max-string-summary-length",
736                             "target.move-to-nearest-code",
737                             "target.output-path",
738                             "target.prefer-dynamic-value",
739                             "target.run-args",
740                             "target.skip-prologue",
741                             "target.source-map",
742                             "target.use-hex-immediates",
743                             "target.process.disable-memory-cache",
744                             "target.process.extra-startup-command",
745                             "target.process.thread.trace-thread",
746                             "target.process.thread.step-avoid-regexp",
747                             ])
748
749    # settings under an ".experimental" domain should have two properties:
750    #   1. If the name does not exist with "experimental" in the name path,
751    #      the name lookup should try to find it without "experimental".  So
752    #      a previously-experimental setting that has been promoted to a
753    #      "real" setting will still be set by the original name.
754    #   2. Changing a setting with .experimental., name, where the setting
755    #      does not exist either with ".experimental." or without, should
756    #      not generate an error.  So if an experimental setting is removed,
757    #      people who may have that in their ~/.lldbinit files should not see
758    #      any errors.
759    def test_experimental_settings(self):
760        cmdinterp = self.dbg.GetCommandInterpreter()
761        result = lldb.SBCommandReturnObject()
762
763        # Set target.arg0 to a known value, check that we can retrieve it via
764        # the actual name and via .experimental.
765        self.expect('settings set target.arg0 first-value')
766        self.expect('settings show target.arg0', substrs=['first-value'])
767        self.expect('settings show target.experimental.arg0', substrs=['first-value'], error=False)
768
769        # Set target.arg0 to a new value via a target.experimental.arg0 name,
770        # verify that we can read it back via both .experimental., and not.
771        self.expect('settings set target.experimental.arg0 second-value', error=False)
772        self.expect('settings show target.arg0', substrs=['second-value'])
773        self.expect('settings show target.experimental.arg0', substrs=['second-value'], error=False)
774
775        # showing & setting an undefined .experimental. setting should generate no errors.
776        self.expect('settings show target.experimental.setting-which-does-not-exist', patterns=['^\s$'], error=False)
777        self.expect('settings set target.experimental.setting-which-does-not-exist true', error=False)
778
779        # A domain component before .experimental. which does not exist should give an error
780        # But the code does not yet do that.
781        # self.expect('settings set target.setting-which-does-not-exist.experimental.arg0 true', error=True)
782
783        # finally, confirm that trying to set a setting that does not exist still fails.
784        # (SHOWING a setting that does not exist does not currently yield an error.)
785        self.expect('settings set target.setting-which-does-not-exist true', error=True)
786