1"""
2Test lldb settings command.
3"""
4
5import os, time
6import unittest2
7import lldb
8from lldbtest import *
9
10class SettingsCommandTestCase(TestBase):
11
12    mydir = "settings"
13
14    @classmethod
15    def classCleanup(cls):
16        """Cleanup the test byproducts."""
17        cls.RemoveTempFile("output1.txt")
18        cls.RemoveTempFile("output2.txt")
19        cls.RemoveTempFile("stderr.txt")
20        cls.RemoveTempFile("stdout.txt")
21
22    def test_apropos_should_also_search_settings_description(self):
23        """Test that 'apropos' command should also search descriptions for the settings variables."""
24
25        self.expect("apropos 'environment variable'",
26            substrs = ["target.env-vars",
27                       "environment variables",
28                       "executable's environment"])
29
30    def test_append_target_env_vars(self):
31        """Test that 'append target.run-args' works."""
32        # Append the env-vars.
33        self.runCmd('settings append target.env-vars MY_ENV_VAR=YES')
34        # And add hooks to restore the settings during tearDown().
35        self.addTearDownHook(
36            lambda: self.runCmd("settings clear target.env-vars"))
37
38        # Check it immediately!
39        self.expect('settings show target.env-vars',
40            substrs = ['MY_ENV_VAR=YES'])
41
42    def test_insert_before_and_after_target_run_args(self):
43        """Test that 'insert-before/after target.run-args' works."""
44        # Set the run-args first.
45        self.runCmd('settings set target.run-args a b c')
46        # And add hooks to restore the settings during tearDown().
47        self.addTearDownHook(
48            lambda: self.runCmd("settings clear target.run-args"))
49
50        # Now insert-before the index-0 element with '__a__'.
51        self.runCmd('settings insert-before target.run-args 0 __a__')
52        # And insert-after the index-1 element with '__A__'.
53        self.runCmd('settings insert-after target.run-args 1 __A__')
54        # Check it immediately!
55        self.expect('settings show target.run-args',
56            substrs = ['target.run-args',
57                       '[0]: "__a__"',
58                       '[1]: "a"',
59                       '[2]: "__A__"',
60                       '[3]: "b"',
61                       '[4]: "c"'])
62
63    def test_replace_target_run_args(self):
64        """Test that 'replace target.run-args' works."""
65        # Set the run-args and then replace the index-0 element.
66        self.runCmd('settings set target.run-args a b c')
67        # And add hooks to restore the settings during tearDown().
68        self.addTearDownHook(
69            lambda: self.runCmd("settings clear target.run-args"))
70
71        # Now replace the index-0 element with 'A', instead.
72        self.runCmd('settings replace target.run-args 0 A')
73        # Check it immediately!
74        self.expect('settings show target.run-args',
75            substrs = ['target.run-args (arguments) =',
76                       '[0]: "A"',
77                       '[1]: "b"',
78                       '[2]: "c"'])
79
80    def test_set_prompt(self):
81        """Test that 'set prompt' actually changes the prompt."""
82
83        # Set prompt to 'lldb2'.
84        self.runCmd("settings set prompt 'lldb2 '")
85
86        # Immediately test the setting.
87        self.expect("settings show prompt", SETTING_MSG("prompt"),
88            startstr = 'prompt (string) = "lldb2 "')
89
90        # The overall display should also reflect the new setting.
91        self.expect("settings show", SETTING_MSG("prompt"),
92            substrs = ['prompt (string) = "lldb2 "'])
93
94        # Use '-r' option to reset to the original default prompt.
95        self.runCmd("settings clear prompt")
96
97    def test_set_term_width(self):
98        """Test that 'set term-width' actually changes the term-width."""
99
100        self.runCmd("settings set term-width 70")
101
102        # Immediately test the setting.
103        self.expect("settings show term-width", SETTING_MSG("term-width"),
104            startstr = "term-width (int) = 70")
105
106        # The overall display should also reflect the new setting.
107        self.expect("settings show", SETTING_MSG("term-width"),
108            substrs = ["term-width (int) = 70"])
109
110    #rdar://problem/10712130
111    def test_set_frame_format(self):
112        """Test that 'set frame-format' with a backtick char in the format string works as well as fullpath."""
113        self.buildDefault()
114
115        exe = os.path.join(os.getcwd(), "a.out")
116        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
117
118        def cleanup():
119            format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}{`${function.name}${function.pc-offset}}}{ at ${line.file.basename}:${line.number}}\n"
120            self.runCmd("settings set frame-format %s" % format_string, check=False)
121
122        # Execute the cleanup function during test case tear down.
123        self.addTearDownHook(cleanup)
124
125        format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}`${function.name-with-args}{${function.pc-offset}}}{ at ${line.file.fullpath}:${line.number}}\n"
126        self.runCmd("settings set frame-format %s" % format_string)
127
128        # Immediately test the setting.
129        self.expect("settings show frame-format", SETTING_MSG("frame-format"),
130            substrs = [format_string])
131
132        self.runCmd("breakpoint set -n main")
133        self.runCmd("run")
134        self.expect("thread backtrace",
135            substrs = ["`main", os.getcwd()])
136
137    def test_set_auto_confirm(self):
138        """Test that after 'set auto-confirm true', manual confirmation should not kick in."""
139        self.buildDefault()
140
141        exe = os.path.join(os.getcwd(), "a.out")
142        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
143
144        self.runCmd("settings set auto-confirm true")
145
146        # Immediately test the setting.
147        self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
148            startstr = "auto-confirm (boolean) = true")
149
150        # Now 'breakpoint delete' should just work fine without confirmation
151        # prompt from the command interpreter.
152        self.runCmd("breakpoint set -n main")
153        self.expect("breakpoint delete",
154            startstr = "All breakpoints removed")
155
156        # Restore the original setting of auto-confirm.
157        self.runCmd("settings clear auto-confirm")
158        self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
159            startstr = "auto-confirm (boolean) = false")
160
161    @unittest2.skipUnless(os.uname()[4] in ['i386', 'x86_64'], "requires x86 or x86_64")
162    def test_disassembler_settings(self):
163        """Test that user options for the disassembler take effect."""
164        self.buildDefault()
165
166        exe = os.path.join(os.getcwd(), "a.out")
167        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
168
169        # AT&T syntax
170        self.runCmd("settings set target.x86-disassembly-flavor att")
171        self.runCmd("settings set target.use-hex-immediates false")
172        self.expect("disassemble -n numberfn",
173            substrs = ["$90"])
174        self.runCmd("settings set target.use-hex-immediates true")
175        self.runCmd("settings set target.hex-immediate-style c")
176        self.expect("disassemble -n numberfn",
177            substrs = ["$0x5a"])
178        self.runCmd("settings set target.hex-immediate-style asm")
179        self.expect("disassemble -n numberfn",
180            substrs = ["$5ah"])
181
182        # Intel syntax
183        self.runCmd("settings set target.x86-disassembly-flavor intel")
184        self.runCmd("settings set target.use-hex-immediates false")
185        self.expect("disassemble -n numberfn",
186            substrs = ["90"])
187        self.runCmd("settings set target.use-hex-immediates true")
188        self.runCmd("settings set target.hex-immediate-style c")
189        self.expect("disassemble -n numberfn",
190            substrs = ["0x5a"])
191        self.runCmd("settings set target.hex-immediate-style asm")
192        self.expect("disassemble -n numberfn",
193            substrs = ["5ah"])
194
195    @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin")
196    @dsym_test
197    def test_run_args_and_env_vars_with_dsym(self):
198        """Test that run-args and env-vars are passed to the launched process."""
199        self.buildDsym()
200        self.pass_run_args_and_env_vars()
201
202    @dwarf_test
203    def test_run_args_and_env_vars_with_dwarf(self):
204        """Test that run-args and env-vars are passed to the launched process."""
205        self.buildDwarf()
206        self.pass_run_args_and_env_vars()
207
208    def pass_run_args_and_env_vars(self):
209        """Test that run-args and env-vars are passed to the launched process."""
210        exe = os.path.join(os.getcwd(), "a.out")
211        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
212
213        # Set the run-args and the env-vars.
214        # And add hooks to restore the settings during tearDown().
215        self.runCmd('settings set target.run-args A B C')
216        self.addTearDownHook(
217            lambda: self.runCmd("settings clear target.run-args"))
218        self.runCmd('settings set target.env-vars ["MY_ENV_VAR"]=YES')
219        self.addTearDownHook(
220            lambda: self.runCmd("settings clear target.env-vars"))
221
222        self.runCmd("run", RUN_SUCCEEDED)
223
224        # Read the output file produced by running the program.
225        with open('output2.txt', 'r') as f:
226            output = f.read()
227
228        self.expect(output, exe=False,
229            substrs = ["argv[1] matches",
230                       "argv[2] matches",
231                       "argv[3] matches",
232                       "Environment variable 'MY_ENV_VAR' successfully passed."])
233
234    def test_pass_host_env_vars(self):
235        """Test that the host env vars are passed to the launched process."""
236        self.buildDefault()
237
238        exe = os.path.join(os.getcwd(), "a.out")
239        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
240
241        # By default, inherit-env is 'true'.
242        self.expect('settings show target.inherit-env', "Default inherit-env is 'true'",
243            startstr = "target.inherit-env (boolean) = true")
244
245        # Set some host environment variables now.
246        os.environ["MY_HOST_ENV_VAR1"] = "VAR1"
247        os.environ["MY_HOST_ENV_VAR2"] = "VAR2"
248
249        # This is the function to unset the two env variables set above.
250        def unset_env_variables():
251            os.environ.pop("MY_HOST_ENV_VAR1")
252            os.environ.pop("MY_HOST_ENV_VAR2")
253
254        self.addTearDownHook(unset_env_variables)
255        self.runCmd("run", RUN_SUCCEEDED)
256
257        # Read the output file produced by running the program.
258        with open('output1.txt', 'r') as f:
259            output = f.read()
260
261        self.expect(output, exe=False,
262            substrs = ["The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.",
263                       "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."])
264
265    def test_set_error_output_path(self):
266        """Test that setting target.error/output-path for the launched process works."""
267        self.buildDefault()
268
269        exe = os.path.join(os.getcwd(), "a.out")
270        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
271
272        # Set the error-path and output-path and verify both are set.
273        self.runCmd("settings set target.error-path stderr.txt")
274        self.runCmd("settings set target.output-path stdout.txt")
275        # And add hooks to restore the original settings during tearDown().
276        self.addTearDownHook(
277            lambda: self.runCmd("settings clear target.output-path"))
278        self.addTearDownHook(
279            lambda: self.runCmd("settings clear target.error-path"))
280
281        self.expect("settings show target.error-path",
282                    SETTING_MSG("target.error-path"),
283            startstr = 'target.error-path (file) = "stderr.txt"')
284
285        self.expect("settings show target.output-path",
286                    SETTING_MSG("target.output-path"),
287            startstr = 'target.output-path (file) = "stdout.txt"')
288
289        self.runCmd("run", RUN_SUCCEEDED)
290
291        # The 'stderr.txt' file should now exist.
292        self.assertTrue(os.path.isfile("stderr.txt"),
293                        "'stderr.txt' exists due to target.error-path.")
294
295        # Read the output file produced by running the program.
296        with open('stderr.txt', 'r') as f:
297            output = f.read()
298
299        self.expect(output, exe=False,
300            startstr = "This message should go to standard error.")
301
302        # The 'stdout.txt' file should now exist.
303        self.assertTrue(os.path.isfile("stdout.txt"),
304                        "'stdout.txt' exists due to target.output-path.")
305
306        # Read the output file produced by running the program.
307        with open('stdout.txt', 'r') as f:
308            output = f.read()
309
310        self.expect(output, exe=False,
311            startstr = "This message should go to standard out.")
312
313    def test_print_dictionary_setting(self):
314        self.runCmd ("settings clear target.env-vars")
315        self.runCmd ("settings set target.env-vars [\"MY_VAR\"]=some-value")
316        self.expect ("settings show target.env-vars",
317                     substrs = [ "MY_VAR=some-value" ])
318        self.runCmd ("settings clear target.env-vars")
319
320    def test_print_array_setting(self):
321        self.runCmd ("settings clear target.run-args")
322        self.runCmd ("settings set target.run-args gobbledy-gook")
323        self.expect ("settings show target.run-args",
324                     substrs = [ '[0]: "gobbledy-gook"' ])
325        self.runCmd ("settings clear target.run-args")
326
327    def test_settings_with_quotes (self):
328        self.runCmd ("settings clear target.run-args")
329        self.runCmd ("settings set target.run-args a b c")
330        self.expect ("settings show target.run-args",
331                     substrs = [ '[0]: "a"',
332                                 '[1]: "b"',
333                                 '[2]: "c"' ])
334        self.runCmd ("settings set target.run-args 'a b c'")
335        self.expect ("settings show target.run-args",
336                     substrs = [ '[0]: "a b c"' ])
337        self.runCmd ("settings clear target.run-args")
338        self.runCmd ("settings clear target.env-vars")
339        self.runCmd ('settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"')
340        self.expect ("settings show target.env-vars",
341                     substrs = [ 'MY_FILE=this is a file name with spaces.txt' ])
342        self.runCmd ("settings clear target.env-vars")
343
344    def test_settings_with_trailing_whitespace (self):
345
346        # boolean
347        self.runCmd ("settings set target.skip-prologue true")      # Set to known value
348        self.runCmd ("settings set target.skip-prologue false ")    # Set to new value with trailing whitespace
349        # Make sure the setting was correctly set to "false"
350        self.expect ("settings show target.skip-prologue", SETTING_MSG("target.skip-prologue"),
351            startstr = "target.skip-prologue (boolean) = false")
352        self.runCmd("settings clear target.skip-prologue", check=False)
353        # integer
354        self.runCmd ("settings set term-width 70")      # Set to known value
355        self.runCmd ("settings set term-width 60 \t")   # Set to new value with trailing whitespaces
356        self.expect ("settings show term-width", SETTING_MSG("term-width"),
357            startstr = "term-width (int) = 60")
358        self.runCmd("settings clear term-width", check=False)
359        # string
360        self.runCmd ("settings set target.arg0 abc")    # Set to known value
361        self.runCmd ("settings set target.arg0 cde\t ") # Set to new value with trailing whitespaces
362        self.expect ("settings show target.arg0", SETTING_MSG("target.arg0"),
363            startstr = 'target.arg0 (string) = "cde"')
364        self.runCmd("settings clear target.arg0", check=False)
365        # file
366        self.runCmd ("settings set target.output-path /bin/ls")   # Set to known value
367        self.runCmd ("settings set target.output-path /bin/cat ") # Set to new value with trailing whitespaces
368        self.expect ("settings show target.output-path", SETTING_MSG("target.output-path"),
369            startstr = 'target.output-path (file) = ', substrs=['/bin/cat"'])
370        self.runCmd("settings clear target.output-path", check=False)
371        # enum
372        self.runCmd ("settings set stop-disassembly-display never")   # Set to known value
373        self.runCmd ("settings set stop-disassembly-display always ") # Set to new value with trailing whitespaces
374        self.expect ("settings show stop-disassembly-display", SETTING_MSG("stop-disassembly-display"),
375            startstr = 'stop-disassembly-display (enum) = always')
376        self.runCmd("settings clear stop-disassembly-display", check=False)
377        # arguments
378        self.runCmd ("settings set target.run-args 1 2 3")  # Set to known value
379        self.runCmd ("settings set target.run-args 3 4 5 ") # Set to new value with trailing whitespaces
380        self.expect ("settings show target.run-args", SETTING_MSG("target.run-args"),
381            substrs = [ 'target.run-args (arguments) =',
382                        '[0]: "3"',
383                        '[1]: "4"',
384                        '[2]: "5"' ])
385        self.runCmd("settings clear target.run-args", check=False)
386        # dictionaries
387        self.runCmd ("settings clear target.env-vars")  # Set to known value
388        self.runCmd ("settings set target.env-vars A=B C=D\t ") # Set to new value with trailing whitespaces
389        self.expect ("settings show target.env-vars", SETTING_MSG("target.env-vars"),
390            substrs = [ 'target.env-vars (dictionary of strings) =',
391                        'A=B',
392                        'C=D'])
393        self.runCmd("settings clear target.env-vars", check=False)
394
395    def test_all_settings_exist (self):
396        self.expect ("settings show",
397                     substrs = [ "auto-confirm",
398                                 "frame-format",
399                                 "notify-void",
400                                 "prompt",
401                                 "script-lang",
402                                 "stop-disassembly-count",
403                                 "stop-disassembly-display",
404                                 "stop-line-count-after",
405                                 "stop-line-count-before",
406                                 "term-width",
407                                 "thread-format",
408                                 "use-external-editor",
409                                 "target.default-arch",
410                                 "target.expr-prefix",
411                                 "target.prefer-dynamic-value",
412                                 "target.enable-synthetic-value",
413                                 "target.skip-prologue",
414                                 "target.source-map",
415                                 "target.exec-search-paths",
416                                 "target.max-children-count",
417                                 "target.max-string-summary-length",
418                                 "target.breakpoints-use-platform-avoid-list",
419                                 "target.run-args",
420                                 "target.env-vars",
421                                 "target.inherit-env",
422                                 "target.input-path",
423                                 "target.output-path",
424                                 "target.error-path",
425                                 "target.disable-aslr",
426                                 "target.disable-stdio",
427                                 "target.x86-disassembly-flavor",
428                                 "target.use-hex-immediates",
429                                 "target.hex-immediate-style",
430                                 "target.process.disable-memory-cache",
431                                 "target.process.extra-startup-command",
432                                 "target.process.thread.step-avoid-regexp",
433                                 "target.process.thread.trace-thread"])
434
435
436
437if __name__ == '__main__':
438    import atexit
439    lldb.SBDebugger.Initialize()
440    atexit.register(lambda: lldb.SBDebugger.Terminate())
441    unittest2.main()
442