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