/[ddp]/manuals/trunk/quick-reference/asciidoc/12_program.txt
ViewVC logotype

Contents of /manuals/trunk/quick-reference/asciidoc/12_program.txt

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6837 - (hide annotations) (download)
Sun Aug 16 16:31:08 2009 UTC (3 years, 9 months ago) by osamu
File MIME type: text/plain
File size: 38623 byte(s)
fix errors in svn descriptions
1 osamu 6683 == Programming
2    
3     // vim: set sts=2 expandtab:
4     // Use ":set nowrap" to edit table
5    
6     I provide some pointers for people to learn programming on the Debian system enough to trace the packaged source code. Here are notable packages and corresponding documentation packages for programing.
7    
8 osamu 6830 .List of packages to help programing
9 osamu 6683 [grid="all"]
10     `-----------------`-------------`------------`------------------------------------------------------------------------
11 osamu 6830 package popcon size documentation
12 osamu 6683 ----------------------------------------------------------------------------------------------------------------------
13 osamu 6830 `autoconf` @@@popcon1@@@ @@@psize1@@@ "`info autoconf`" provided by `autoconf-doc`
14     `automake` @@@popcon1@@@ @@@psize1@@@ "`info automake`" provided by `automake1.10-doc`
15     `bash` @@@popcon1@@@ @@@psize1@@@ "`info bash`" provided by `bash-doc`
16     `bison` @@@popcon1@@@ @@@psize1@@@ "`info bison`" provided by `bison-doc`
17     `cpp` @@@popcon1@@@ @@@psize1@@@ "`info cpp`" provided by `cpp-doc`
18     `ddd` @@@popcon1@@@ @@@psize1@@@ "`info ddd`" provided by `ddd-doc`
19     `exuberant-ctags` @@@popcon1@@@ @@@psize1@@@ `exuberant-ctags`(1)
20     `flex` @@@popcon1@@@ @@@psize1@@@ "`info flex`" provided by `flex-doc`
21     `gawk` @@@popcon1@@@ @@@psize1@@@ "`info gawk`" provided by `gawk-doc`
22     `gcc` @@@popcon1@@@ @@@psize1@@@ "`info gcc`" provided by `gcc-doc`
23     `gdb` @@@popcon1@@@ @@@psize1@@@ "`info gdb`" provided by `gdb-doc`
24     `gettext` @@@popcon1@@@ @@@psize1@@@ "`info gettext`" provided by `gettext-doc`
25     `gfortran` @@@popcon1@@@ @@@psize1@@@ "`info gfortran`" provided by `gfortran-doc`
26     `glade` @@@popcon1@@@ @@@psize1@@@ help provided via menu
27     `glade-gnome` @@@popcon1@@@ @@@psize1@@@ help provided via menu
28     `libc6` @@@popcon1@@@ @@@psize1@@@ "`info libc`" provided by `glibc-doc` and `glibc-doc-reference`
29     `make` @@@popcon1@@@ @@@psize1@@@ "`info make`" provided by `make-doc`
30     `mawk` @@@popcon1@@@ @@@psize1@@@ `mawk`(1)
31     `perl` @@@popcon1@@@ @@@psize1@@@ `perl`(1) and html pages provided by `perl-doc` and `perl-doc-html`
32     `python` @@@popcon1@@@ @@@psize1@@@ `python`(1) and html pages provided by `python-doc`
33     `tcl8.4` @@@popcon1@@@ @@@psize1@@@ `tcl`(3) and detail manual pages provided by `tcl8.4-doc`
34     `tk8.4` @@@popcon1@@@ @@@psize1@@@ `tk`(3) and detail manual pages provided by `tk8.4-doc`
35     `ruby` @@@popcon1@@@ @@@psize1@@@ `ruby`(1) and interactive reference provided by `ri`
36     `vim` @@@popcon1@@@ @@@psize1@@@ help(F1) menu provided by `vim-doc`
37     `susv2` @@@popcon1@@@ @@@psize1@@@ fetch "http://www.unix.org/version2/[The Single Unix Specifications v2]"
38     `susv3` @@@popcon1@@@ @@@psize1@@@ fetch "http://www.unix.org/version3/[The Single Unix Specifications v3]"
39 osamu 6683 ----------------------------------------------------------------------------------------------------------------------
40    
41     Online references are available by typing "`man name`" after installing `manpages` and `manpages-dev` packages. Online references for the GNU tools are available by typing "`info program_name`" after installing the pertinent documentation packages. You may need to include the `contrib` and `non-free` archives in addition to the `main` archive since some GFDL documentations are not considered to be DSFG compliant.
42    
43     WARNING: Do not use "`test`" as the name of an executable test file. "`test`" is a shell builtin.
44    
45     CAUTION: You should install software programs directly compiled from source into "`/usr/local`" or "`/opt`" to avoid collision with system programs.
46    
47     TIP: http://www.99-bottles-of-beer.net/[Code examples of creating "Song 99 Bottles of Beer"] should give you good idea of practically all the programming languages.
48    
49     === The shell script
50    
51     The http://en.wikipedia.org/wiki/Shell_script[shell script] is a text file with the execution bit set and contains the commands in the following format.
52    
53     --------------------
54     #!/bin/sh
55 osamu 6830 ... command lines
56 osamu 6683 --------------------
57     The first line specifies the shell interpreter which read and execute this file contents.
58    
59     Reading shell scripts is the **best** way to understand how a Unix-like system works. Here, I give some pointers and reminders for shell programming. See "Shell Mistakes" (http://www.greenend.org.uk/rjk/2001/04/shell.html) to learn from mistakes.
60    
61 osamu 6837 Unlike shell interactive mode (see <<_the_simple_shell_command>> and <<_unix_like_text_processing>>), shell scipts frequently use parameters, conditionals, and loops.
62 osamu 6683
63     ==== POSIX shell compatibility
64    
65 osamu 6830 Many system scripts may be interpreted by any one of http://en.wikipedia.org/wiki/POSIX[POSIX] shells (see <<list-of-shell-programs>>). The default shell for the system is "`/bin/sh`" which is a symlink pointing to the actual program.
66 osamu 6683
67 osamu 6830 - `bash`(1) for `lenny` or older
68     - `dash`(1) for `squeeze` or newer
69 osamu 6683
70 osamu 6757 Avoid writing a shell script with "bashisms" or "zshisms" to make it portable among all POSIX shells. You can check it using `checkbashisms`(1).
71 osamu 6683
72 osamu 6830 .List of typical bashisms
73 osamu 6683 [grid="all"]
74     `-----------------------------------`------------------------------------
75 osamu 6830 Good: POSIX Avoid: bashism
76 osamu 6683 -------------------------------------------------------------------------
77 osamu 6830 `if [ "$foo" = "$bar" ] ; then ...` `if [ "$foo" == "$bar" ] ; then ...`
78     `diff -u file.c.orig file.c` `diff -u file.c{.orig,`}
79     `mkdir /foobar /foobaz` `mkdir /foo{bar,baz`}
80     octal format: `"\377"` hexadecimal format: `"\xff"`
81 osamu 6683 -------------------------------------------------------------------------
82    
83 osamu 6830 The "`echo`" command must be used with following cares since its implementation differs among shell builtin and external commands.
84 osamu 6683
85 osamu 6830 - Avoid using command option "`-e`" and "`-E`".
86     - Avoid using any command options except "`-n`".
87 osamu 6683 - Avoid using escape sequences in the string since their handling varies.
88    
89     NOTE: Although "`-n` option is **not** really POSIX syntax, it is generally accepted.
90    
91     TIP: Use the "`printf`" command instead of the "`echo`" command if you need to embed escape sequences in the output string.
92    
93     ==== Shell parameters
94    
95 osamu 6830 Special shell parameters are frequently used in the shell script.
96 osamu 6683
97 osamu 6830 .List of shell parameters
98 osamu 6683 [grid="all"]
99     `---------------`-------------------------------------------
100 osamu 6830 shell parameter value
101 osamu 6683 ------------------------------------------------------------
102 osamu 6830 `$0` name of the shell or shell script
103     `$1` first(1) shell argument
104     `$9` ninth(9) shell argument
105     `$#` number of positional parameters
106     `"$\*"` `"$1 $2 $3 $4 ... "`
107     `"$@"` `"$1" "$2" "$3" "$4" ...`
108     `$?` exit status of the most recent command
109     `$$` PID of this shell script
110     `$!` PID of most recently started background job
111 osamu 6683 ------------------------------------------------------------
112    
113 osamu 6830 Basic **parameter expansions** to remember are followings.
114 osamu 6683
115    
116 osamu 6830 .List of shell parameter expansions
117 osamu 6683 [grid="all"]
118     `-------------------------`---------------------`---------------------------------------------------
119     parameter expression form value if `var` is set value if `var` is not set
120     ----------------------------------------------------------------------------------------------------
121     `$\{var:-string\}` "`$var`" "`string`"
122     `$\{var:+string\}` "`string`" "`null`"
123     `$\{var:=string\}` "`$var`" "`string`" (and run "`var=string`")
124     `$\{var:?string\}` "`$var`" echo "`string`" to **stderr** (and exit with error)
125     ----------------------------------------------------------------------------------------------------
126    
127     Here, the colon "`:`" in all of these operators is actually optional.
128    
129 osamu 6830 - **with** "`:`" = operator test for **exist** and **not null**
130     - **without** "`:`" = operator test for **exist** only
131 osamu 6683
132    
133 osamu 6830 .List of key shell parameter substitutions
134 osamu 6683 [grid="all"]
135     `---------------------------`------------------------------
136 osamu 6830 parameter substitution form result
137 osamu 6683 -----------------------------------------------------------
138 osamu 6830 `$\{var%suffix\}` remove smallest suffix pattern
139     `$\{var%%suffix\}` remove largest suffix pattern
140     `$\{var#prefix\}` remove smallest prefix pattern
141     `$\{var##prefix\}` remove largest prefix pattern
142 osamu 6683 -----------------------------------------------------------
143    
144     ==== Shell conditionals
145    
146 osamu 6830 Each command returns an **exit status** which can be used for conditional expressions.
147 osamu 6683
148 osamu 6830 - Success: 0 ("True")
149     - Error: non 0 ("False")
150 osamu 6683
151 osamu 6830 NOTE: "0" in the shell conditional context means "True", while "0" in the C conditional context means "False".
152 osamu 6683
153 osamu 6830 NOTE: "`[`" is the equivalent of the `test` command, which evaluates its arguments up to "`]`" as a conditional expression.
154    
155     Basic **conditional idioms** to remember are foolowings.
156    
157     - "`<command> && <if_success_run_this_command_too> || true`"
158     - "`<command> || <if_not_success_run_this_command_too> || true`"
159 osamu 6836 - A multi-line script snippet as the following
160 osamu 6830
161 osamu 6683 --------------------
162     if [ <conditional_expression> ]; then
163     <if_success_run_this_command>
164     else
165     <if_not_success_run_this_command>
166     fi
167     --------------------
168    
169     Here trailing "`|| true`" was needed to ensure this shell script will not exit at this line accidentally when shell is invoked with "`-e`" flag.
170    
171 osamu 6830 .List of file comparison operators in the conditional expression
172 osamu 6683 [grid="all"]
173     `-----------------------`------------------------------------------------------
174 osamu 6830 equation condition to return logical true
175 osamu 6683 -------------------------------------------------------------------------------
176 osamu 6830 ` -e <file> ` <file> exists
177     ` -d <file> ` <file> exists and is a directory
178     ` -f <file> ` <file> exists and is a regular file
179     ` -w <file> ` <file> exists and is writable
180     ` -x <file> ` <file> exists and is executable
181     ` <file1> -nt <file2> ` <file1> is newer than <file2> (modification)
182     ` <file1> -ot <file2> ` <file1> is older than <file2> (modification)
183     ` <file1> -ef <file2> ` <file1> and <file2> are on the same device and the same inode number
184 osamu 6683 -------------------------------------------------------------------------------
185    
186 osamu 6830 .List of string comparison operators in the conditional expression
187 osamu 6683 [grid="all"]
188     `--------------------`------------------------------------------------------
189 osamu 6830 equation condition to return logical true
190 osamu 6683 ----------------------------------------------------------------------------
191 osamu 6830 ` -z <str> ` the length of <str> is zero
192     ` -n <str> ` the length of <str> is non-zero
193     ` <str1> = <str2> ` <str1> and <str2> are equal
194     ` <str1> != <str2> ` <str1> and <str2> are not equal
195     ` <str1> < <str2> ` <str1> sorts before <str2> (locale dependent)
196     ` <str1> > <str2> ` <str1> sorts after <str2> (locale dependent)
197 osamu 6683 ----------------------------------------------------------------------------
198    
199     **Arithmetic** integer comparison operators in the conditional expression are "`-eq`", "`-ne`", "`-lt`", "`-le`", "`-gt`", and "`-ge`".
200    
201     ==== Shell loops
202    
203 osamu 6830 There are several loop idioms to use in POSIX shell.
204 osamu 6683
205 osamu 6830 - "`for name in word ; do list ; done`" loops over list of words.
206     - "`while list; do list; done`" repeats while true.
207     - "`until list; do list; done`" repeats while not true.
208     - "`break`" enables to exit from the loop.
209 osamu 6683 - "`continue`" enables to resume the next iteration of the loop.
210    
211     TIP: The http://en.wikipedia.org/wiki/C_(programming_language)[C]-language like numeric iteration can be realized by using `seq`(1) as the "`word`" generator.
212    
213     TIP: See <<_repeating_a_command_looping_over_files>>.
214    
215     ==== The shell command-line processing sequence
216    
217 osamu 6830 The shell processes a script as following sequence.
218 osamu 6683
219     - split line into **tokens** by the metacharacters: `SPACE TAB NEWLINE ; ( ) < > | &`
220     - check **keyword** if not within `"..."` or `\'...\'` (loop)
221     - expand **alias** if not within `"..."` or `\'...\'` (loop)
222     - expand **tilde**, "`\~<user>`" -> `<user>`\'s home directory, if not within `"..."` or `\'...\'`
223     - expand **parameter**, "`$PARAMETER`", if not within `\'...\'`
224     - expand **command substitution**, "`$( command )`", if not within `\'...\'`
225     - split into **words** with "`$IFS`" if not within `"..."` or `\'...\'`
226     - expand ` \* ? [ ] ` in **pathname** if not within `"..."` or `\'...\'`
227 osamu 6830 - look up **command** from
228 osamu 6683 * **function** definition
229     * **builtin** command
230     * **executable file** in "`$PATH`"
231     - go to the next line and repeat this process again from the top of this sequence
232    
233     Single quotes within double quotes have no effect.
234    
235     Executing "`set -x`" in the shell or invoking the shell with "`-x`" option make the shell to print all of commands executed. This is quite handy for debugging.
236    
237     ==== Utility programs for shell script
238    
239 osamu 6820 In order to make your shell program as portable as possible across Debian system, it is good idea to limit utility programs to ones provided by **essential** packages.
240 osamu 6683
241 osamu 6830 - "`aptitude search \~E`" lists **essential** packages.
242 osamu 6820 - "`dpkg -L <package_name> |grep \'/man/man.\*/\'`" lists manpages for commands offered by `<package_name>` package.
243 osamu 6683
244 osamu 6830 .List of packages containing small utility programs for shell scripts
245 osamu 6820 [grid="all"]
246     `--------------`-------------`------------`----------------------------------------------
247     package popcon size description
248     -----------------------------------------------------------------------------------------
249 osamu 6830 `coreutils` @@@popcon1@@@ @@@psize1@@@ GNU core utilities
250 osamu 6820 `debianutils` @@@popcon1@@@ @@@psize1@@@ miscellaneous utilities specific to Debian
251     `bsdmainutils` @@@popcon1@@@ @@@psize1@@@ collection of more utilities from FreeBSD
252     `bsdutils` @@@popcon1@@@ @@@psize1@@@ basic utilities from 4.4BSD-Lite
253     `moreutils` @@@popcon1@@@ @@@psize1@@@ additional unix utilities
254     ------------------------------------------------------------------------------------------
255    
256     TIP: Although `moreutils` may not exist ouside of Debian, it offers interesting small programs. Most notable one is `sponge`(8). See <<_global_substitution_with_regular_expressions>>.
257    
258 osamu 6683 ==== Shell script dialog
259    
260     The user interface of a simple shell program can be improved from dull interaction by `echo` and `read` commands to more interactive one by using one of the so-called dialog program etc.
261    
262 osamu 6830 .List of user interface programs
263 osamu 6683 [grid="all"]
264     `-----------`-------------`------------`-----------------------------------------------------------------------------------
265 osamu 6830 package popcon size description
266 osamu 6683 ---------------------------------------------------------------------------------------------------------------------------
267 osamu 6830 `x11-utils` @@@popcon1@@@ @@@psize1@@@ `xmessage`(1): display a message or query in a window (X)
268     `whiptail` @@@popcon1@@@ @@@psize1@@@ displays user-friendly dialog boxes from shell scripts (newt)
269     `dialog` @@@popcon1@@@ @@@psize1@@@ displays user-friendly dialog boxes from shell scripts (ncurses)
270     `zenity` @@@popcon1@@@ @@@psize1@@@ display graphical dialog boxes from shell scripts (gtk2.0)
271     `gtkdialog` @@@popcon1@@@ @@@psize1@@@ GUI-creation command-line utility based on GTK+ library (gtk2.0+glade2)
272     `ssft` @@@popcon1@@@ @@@psize1@@@ Shell Scripts Frontend Tool (wrapper for zenity, kdialog, and dialog with gettext)
273     `gettext` @@@popcon1@@@ @@@psize1@@@ "`/usr/bin/gettext.sh`": translate message
274 osamu 6683 ---------------------------------------------------------------------------------------------------------------------------
275    
276     // || {{{xbase-clients}}} || 29862 || - || The {{{xmessage}}}(1) displays a message or query in a window (X)({{{etch}}}) ||
277    
278     ==== Shell script example with zenity
279    
280 osamu 6830 Here is a simple script which creates ISO image with RS02 data supplemented by `dvdisaster`(1).
281 osamu 6683
282     --------------------
283     #!/bin/sh -e
284     # gmkrs02 : Copyright (C) 2007 Osamu Aoki <osamu@debian.org>, Public Domain
285     #set -x
286     error_exit()
287     {
288     echo "$1" >&2
289     exit 1
290     }
291     # Initialize variables
292     DATA_ISO="$HOME/Desktop/iso-$$.img"
293     LABEL=$(date +%Y%m%d-%H%M%S-%Z)
294     if [ $# != 0 ] && [ -d "$1" ]; then
295     DATA_SRC="$1"
296     else
297     # Select directory for creating ISO image from folder on desktop
298     DATA_SRC=$(zenity --file-selection --directory \
299     --title="Select the directory tree root to create ISO image") \
300     || error_exit "Exit on directory selection"
301     fi
302     # Check size of archive
303     xterm -T "Check size $DATA_SRC" -e du -s $DATA_SRC/*
304     SIZE=$(($(du -s $DATA_SRC | awk '{print $1}')/1024))
305     if [ $SIZE -le 520 ] ; then
306     zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \
307     --text="The data size is good for CD backup:\\n $SIZE MB"
308     elif [ $SIZE -le 3500 ]; then
309     zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \
310     --text="The data size is good for DVD backup :\\n $SIZE MB"
311     else
312     zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \
313     --text="The data size is too big to backup : $SIZE MB"
314     error_exit "The data size is too big to backup :\\n $SIZE MB"
315     fi
316     # only xterm is sure to have working -e option
317     # Create raw ISO image
318     rm -f "$DATA_ISO" || true
319     xterm -T "genisoimage $DATA_ISO" \
320     -e genisoimage -r -J -V "$LABEL" -o "$DATA_ISO" "$DATA_SRC"
321     # Create RS02 supplemental redundancy
322     xterm -T "dvdisaster $DATA_ISO" -e dvdisaster -i "$DATA_ISO" -mRS02 -c
323     zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \
324     --text="ISO/RS02 data ($SIZE MB) \\n created at: $DATA_ISO"
325     # EOF
326     --------------------
327    
328     You may wish to create launcher on the desktop with command set something like "`/usr/local/bin/gmkrs02 %d`".
329    
330     === Make
331    
332     http://en.wikipedia.org/wiki/Make_(software)[Make] is a utility to maintain groups of programs. Upon execution of `make`(1), `make` read the rule file, "`Makefile`", and updates a target if it depends on prerequisite files that have been modified since the target was last modified, or if the target does not exist. The execution of these updates may occur concurrently.
333    
334 osamu 6830 The rule file syntax is the following.
335 osamu 6683
336     --------------------
337     target: [ prerequisites ... ]
338     [TAB] command1
339     [TAB] -command2 # ignore errors
340     [TAB] @command3 # suppress echoing
341     --------------------
342    
343     Here "` [TAB] `" is a TAB code. Each line is interpreted by the shell after make variable substitution. Use "`\`" at the end of a line to continue the script. Use "`$$`" to enter "`$`" for environment values for a shell script.
344    
345 osamu 6830 Implicit rules for the target and prerequisites can be written, for example, by the following.
346 osamu 6683
347     --------------------
348     %.o: %.c header.h
349     --------------------
350 osamu 6830
351 osamu 6683 Here, the target contains the character "`%`" (exactly one of them). The "`%`" can match any nonempty substring in the actual target filenames. The prerequisites likewise use "`%`" to show how their names relate to the actual target name.
352    
353 osamu 6830 .List of make automatic variables
354 osamu 6683 [grid="all"]
355     `------------------`----------------------------------------
356 osamu 6830 automatic variable value
357 osamu 6683 ------------------------------------------------------------
358 osamu 6830 `$@` target
359     `$<` first prerequisite
360     `$?` all newer prerequisites
361     `$\^` all prerequisites
362     `$\*` "`%`" matched stem in the target pattern
363 osamu 6683 ------------------------------------------------------------
364    
365 osamu 6830 .List of make variable expansions
366 osamu 6683 [grid="all"]
367     `------------------`-------------------
368 osamu 6830 variable expansion description
369 osamu 6683 ---------------------------------------
370 osamu 6830 `foo1 := bar` one-time expansion
371     `foo2 = bar` recursive expansion
372     `foo3 += bar` append
373 osamu 6683 ---------------------------------------
374    
375     Run "`make -p -f/dev/null`" to see automatic internal rules.
376    
377     === C
378    
379 osamu 6830 You can set up proper environment to compile programs written in the http://en.wikipedia.org/wiki/C_(programming_language)[C programming language] by the following.
380 osamu 6683
381     --------------------
382     # aptitude install glibc-doc manpages-dev libc6-dev gcc build-essential
383     --------------------
384    
385     The `libc6-dev` package, i.e., GNU C Library, provides http://en.wikipedia.org/wiki/C_standard_library[C standard library] which is collection of header files and library routines used by the C programming language.
386    
387 osamu 6830 See references for C as the following.
388 osamu 6683
389     - "`info libc`" (C library function reference)
390     - `gcc`(1) and "`info gcc`"
391     - `each_C_library_function_name`(3)
392 osamu 6830 - Kernighan &amp; Ritchie, "The C Programming Language", 2nd edition (Prentice Hall)
393 osamu 6683
394     ==== Simple C program (gcc)
395    
396 osamu 6830 A simple example "`example.c`" can compiled with a library "`libm`" into an executable "`run_example`" by the following.
397 osamu 6683
398     --------------------
399     $ cat > example.c << EOF
400     #include <stdio.h>
401     #include <math.h>
402     #include <string.h>
403    
404     int main(int argc, char **argv, char **envp){
405     double x;
406     char y[11];
407     x=sqrt(argc+7.5);
408     strncpy(y, argv[0], 10); /* prevent buffer overflow */
409     y[10] = '\0'; /* fill to make sure string ends with '\0' */
410     printf("%5i, %5.3f, %10s, %10s\n", argc, x, y, argv[1]);
411     return 0;
412     }
413     EOF
414     $ gcc -Wall -g -o run_example example.c -lm
415     $ ./run_example
416     1, 2.915, ./run_exam, (null)
417     $ ./run_example 1234567890qwerty
418     2, 3.082, ./run_exam, 1234567890qwerty
419     --------------------
420    
421     Here, "`-lm`" is needed to link library "`/usr/lib/libm.so`" from the `libc6` package for `sqrt`(3). The actual library is in "`/lib/`" with filename "`libm.so.6`", which is a symlink to "`libm-2.7.so`".
422    
423     Look at the last parameter in the output text. There are more than 10 characters even though "`%10s`" is specified.
424    
425     The use of pointer memory operation functions without boundary checks, such as `sprintf`(3) and `strcpy`(3), is deprecated to prevent buffer overflow exploits that leverage the above overrun effects. Instead, use `snprintf`(3) and `strncpy`(3).
426    
427 osamu 6783 === Debug
428 osamu 6683
429 osamu 6783 Debuag is important part programing activities. Knowing how to debug programs makes you a good Debian user who can produce meaningful bug report.
430 osamu 6683
431 osamu 6783 ==== Basic gdb execution
432 osamu 6683
433 osamu 6783 Primary http://en.wikipedia.org/wiki/Debugger[debugger] on Debian is `gdb`(1) which enables you to inspect a program while it executes.
434    
435 osamu 6830 Let's install `gdb` and related programs by the following.
436 osamu 6783
437 osamu 6683 --------------------
438     # aptitude install gdb gdb-doc build-essential devscripts
439     --------------------
440    
441     Good tutorial of `gdb` is provided by "`info gdb`" or found http://www.unknownroad.com/rtfm/gdbtut/gdbtoc.html[elsewhere on the web].
442     Here is a simple example of using `gdb`(1) on a "`program`" compiled with the "`-g`" option to produce debugging information.
443    
444     --------------------
445     $ gdb program
446     (gdb) b 1 # set break point at line 1
447     (gdb) run args # run program with args
448     (gdb) next # next line
449     ...
450     (gdb) step # step forward
451     ...
452     (gdb) p parm # print parm
453     ...
454     (gdb) p parm=12 # set value to 12
455     ...
456     (gdb) quit
457     --------------------
458    
459 osamu 6783 TIP: Many `gdb`(1) commands can be abbreviated. Tab expansion works as in the shell.
460 osamu 6683
461 osamu 6783 ==== Debugging the Debian package
462 osamu 6683
463     Since all installed binaries should be stripped on the Debian system by default, most debugging symbols are removed in the normal package. In order to debug Debian packages with `gdb`(1), corresponding `\*-dbg` packages need to be installed (e.g. libc6-dbg in the case of libc6).
464    
465 osamu 6830 If a package to be debugged does not provide its `\*-dbg` package, you need to install it after rebuilding it by theeferences for C following.
466 osamu 6683
467     --------------------
468     $ mkdir /path/new ; cd /path/new
469     $ sudo aptitude update
470     $ sudo aptitude dist-upgrade
471     $ sudo aptitude install fakeroot devscripts build-essential
472     $ sudo apt-get build-dep source_package_name
473     $ apt-get source package_name
474     $ cd package_name*
475     --------------------
476    
477 osamu 6830 Fix bugs if needed.
478 osamu 6683
479 osamu 6830 Bump package version to one which does not collide with official Debian versions, e.g. one appended with "`+debug1`" when recompiling existing package version, or one appended with "`\~pre1`" when compiling unreleased package version by the following.
480    
481 osamu 6683 --------------------
482     $ dch -i
483     --------------------
484    
485 osamu 6830 Compile and install packages with debug symbols by the following.
486 osamu 6683
487     --------------------
488     $ export DEB_BUILD_OPTIONS=nostrip,noopt
489     $ debuild
490     $ cd ..
491     $ sudo debi package_name*.changes
492     --------------------
493    
494     You need to check build scripts of the package and ensure to use "`CFLAGS=-g -Wall`" for compiling binaries.
495    
496 osamu 6783 ==== Obtaining backtrace
497 osamu 6683
498     When you encounter program crash, reporting bug report with cut-and-pasted backtrace information is a good idea.
499    
500 osamu 6830 The backtrace can be obtained by the following steps.
501 osamu 6683
502 osamu 6830 - run the program under `gdb`(1)
503     - reproduce crash (causing you to be dropped back to the `gdb` prompt)
504     - type "`bt`" at the `gdb` prompt
505 osamu 6683
506     In case of program freeze, you can crash the program by pressing `Ctrl-C` in the terminal running `gdb` to obtain `gdb` prompt.
507    
508 osamu 6830 TIP: Often, you will see a backtrace where one or more of the top lines is in "`malloc()`" or "`g_malloc()`". When this happens, chances are your backtrace isn\'t very useful. The easiest way to find some useful information is to set the environment variable "`$MALLOC_CHECK_`" to a value of 2 (`malloc`(3)). You can do this while running `gdb` by doing the following.
509 osamu 6683
510     --------------------
511     $ MALLOC_CHECK_=2 gdb hello
512     --------------------
513    
514 osamu 6783 ==== Advanced gdb commands
515 osamu 6683
516     .List of advanced gdb commands
517     [grid="all"]
518 osamu 6768 `-----------------------------------`------------------------------------------------------------------------------
519 osamu 6830 command description for command objectives
520 osamu 6683 -------------------------------------------------------------------------------------------------------------------
521 osamu 6830 `(gdb) thread apply all bt` get a backtrace for all threads for multi-threaded program
522     `(gdb) bt full` get parameters came on the stack of function calls
523     `(gdb) thread apply all bt full` get a backtrace and parameters as the combination of the preceding options
524     `(gdb) thread apply all bt full 10` get them for top 10 calls to cut off irrelevant output
525     `(gdb) set logging on` write log of gdb output to a file (the default is gdb.txt)
526 osamu 6683 -------------------------------------------------------------------------------------------------------------------
527    
528 osamu 6783 ==== Debugging X Errors
529 osamu 6683
530 osamu 6830 If the GNOME program has received an X error; i.e. you see a message as follows.
531 osamu 6683
532     --------------------
533     The program 'preview1' received an X Window System error.
534     --------------------
535    
536     then you can try running the program with "`--sync`", and break on the "`gdk_x_error`" function in order to obtain a backtrace.
537    
538     ==== Check dependency on libraries
539    
540 osamu 6830 Use `ldd`(1) to find out a program\'s dependency on libraries by the followings.
541 osamu 6683
542     --------------------
543     $ ldd /bin/ls
544     librt.so.1 => /lib/librt.so.1 (0x4001e000)
545     libc.so.6 => /lib/libc.so.6 (0x40030000)
546     libpthread.so.0 => /lib/libpthread.so.0 (0x40153000)
547     /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
548     --------------------
549    
550     For `ls`(1) to work in a `chroot`ed environment, the above libraries must be available in your `chroot`ed environment.
551    
552 osamu 6830 See <<_tracing_program_activities>>.
553 osamu 6683
554 osamu 6783 ==== Memory leak detection tools
555 osamu 6683
556     There are several memory leak detection tools available in Debian.
557    
558     .List of memory leak detection tools
559     [grid="all"]
560     `----------------`-------------`------------`----------------------------------------------------
561 osamu 6830 package popcon size description
562 osamu 6683 -------------------------------------------------------------------------------------------------
563 osamu 6830 `libc6-dev` @@@popcon1@@@ @@@psize1@@@ `mtrace`(1): malloc debugging functionality in glibc
564     `valgrind` @@@popcon1@@@ @@@psize1@@@ memory debugger and profiler
565     `kmtrace` @@@popcon1@@@ @@@psize1@@@ KDE memory leak tracer using glibc\'s `mtrace`(1)
566     `alleyoop` @@@popcon1@@@ @@@psize1@@@ GNOME front-end to the Valgrind memory checker
567     `electric-fence` @@@popcon1@@@ @@@psize1@@@ `malloc`(3) debugger
568     `ccmalloc` @@@popcon1@@@ @@@psize1@@@ memory profiler/debugger
569     `leaktracer` @@@popcon1@@@ @@@psize1@@@ memory-leak tracer for C++ programs
570     `libdmalloc5` @@@popcon1@@@ @@@psize1@@@ debug memory allocation library
571     `mpatrolc2` @@@popcon1@@@ @@@psize1@@@ library for debugging memory allocations
572 osamu 6683 -------------------------------------------------------------------------------------------------
573    
574 osamu 6783 ==== Static code analysis tools
575    
576 osamu 6830 There are http://en.wikipedia.org/wiki/Lint_programming_tool[lint] like tools for http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis[static code analysis].
577 osamu 6783
578     .List of tools for static code analysis
579     [grid="all"]
580     `---------------`-------------`------------`---------------------------------------------------------------------
581 osamu 6830 package popcon size description
582 osamu 6783 -----------------------------------------------------------------------------------------------------------------
583 osamu 6830 `splint` @@@popcon1@@@ @@@psize1@@@ tool for statically checking C programs for bugs
584     `rats` @@@popcon1@@@ @@@psize1@@@ rough Auditing Tool for Security (C, C++, PHP, Perl, and Python code)
585     `flawfinder` @@@popcon1@@@ @@@psize1@@@ tool to examine C/C++ source code and looks for security weaknesses
586     `perl` @@@popcon1@@@ @@@psize1@@@ interpreter with internal code static checker: `B::Lint`(3perl)
587     `pylint` @@@popcon1@@@ @@@psize1@@@ Python code static checker
588     `jlint` @@@popcon1@@@ @@@psize1@@@ Java program checker
589     `weblint-perl` @@@popcon1@@@ @@@psize1@@@ syntax and minimal style checker for HTML
590     `linklint` @@@popcon1@@@ @@@psize1@@@ fast link checker and web site maintenance tool
591     `libxml2-utils` @@@popcon1@@@ @@@psize1@@@ utilities with `xmllint`(1) to validate XML files
592 osamu 6783 -----------------------------------------------------------------------------------------------------------------
593    
594 osamu 6683 ==== Disassemble binary
595    
596 osamu 6830 You can disassemble binary code with `objdump`(1) by the following.
597 osamu 6683
598     --------------------
599     $ objdump -m i386 -b binary -D /usr/lib/grub/x86_64-pc/stage1
600     --------------------
601    
602     NOTE: `gdb`(1) may be used to disassemble code interactively.
603    
604 osamu 6783 === Flex -- a better Lex
605 osamu 6683
606     http://en.wikipedia.org/wiki/Flex_lexical_analyser[Flex] is a a http://en.wikipedia.org/wiki/Lex_programming_tool[Lex]-compatible fast http://en.wikipedia.org/wiki/Lexical_analysis[lexical analyzer] generator.
607    
608     Tutorial for `flex`(1) can be found in "`info flex`".
609    
610 osamu 6830 You need to provide your own "`main()`" and "`yywrap()`", or your "`program.l`" should look like this to compile without a library ("`yywrap`" is a macro; "`%option main`" turns on "`%option noyywrap`" implicitly).
611 osamu 6683
612     --------------------
613     %option main
614     %%
615     .|\n ECHO ;
616     %%
617     --------------------
618    
619     Alternatively, you may compile with the "`-lfl`" linker option at the end of your `cc`(1) command line (like AT&T-Lex with "`-ll`"). No "`%option`" is needed in this case.
620    
621 osamu 6783 === Bison -- a better Yacc
622 osamu 6683
623 osamu 6830 Several packages provide a http://en.wikipedia.org/wiki/Yacc[Yacc]-compatible lookahead http://en.wikipedia.org/wiki/LR_parser[LR parser] or http://en.wikipedia.org/wiki/LALR_parser[LALR parser] generator in Debian.
624 osamu 6683
625     .List of Yacc-compatible LALR parser generators
626     [grid="all"]
627     `--------`-------------`------------`-----------------------------------------------------------------
628 osamu 6830 package popcon size description
629 osamu 6683 ------------------------------------------------------------------------------------------------------
630 osamu 6830 `bison` @@@popcon1@@@ @@@psize1@@@ http://en.wikipedia.org/wiki/GNU_bison[GNU LALR parser generator]
631     `byacc` @@@popcon1@@@ @@@psize1@@@ Berkeley LALR parser generator
632     `btyacc` @@@popcon1@@@ @@@psize1@@@ backtracking parser generator based on `byacc`
633 osamu 6683 ------------------------------------------------------------------------------------------------------
634    
635     Tutorial for `bison`(1) can be found in "`info bison`".
636    
637     You need to provide your own "`main()`" and "`yyerror()`". "`main()`" calls "`yyparse()`" which calls "`yylex()`", usually created with Flex.
638    
639     --------------------
640     %%
641    
642     %%
643     --------------------
644    
645     === Autoconf
646    
647     http://en.wikipedia.org/wiki/Autoconf[Autoconf] is a tool for producing shell scripts that automatically configure software source code packages to adapt to many kinds of Unix-like systems using the entire GNU build system.
648    
649     `autoconf`(1) produces the configuration script "`configure`". "`configure`" automatically creates a customized "`Makefile`" using the "`Makefile.in`" template.
650    
651     ==== Compile and install a program
652    
653     WARNING: Do not overwrite system files with your compiled programs when installing them.
654    
655     Debian does not touch files in "`/usr/local/`" or "`/opt`". So if you compile a program from source, install it into "`/usr/local/`" so it will not interfere with Debian.
656    
657     --------------------
658     $ cd src
659     $ ./configure --prefix=/usr/local
660     $ make
661     $ make install # this puts the files in the system
662     --------------------
663    
664     ==== Uninstall program
665    
666 osamu 6830 If you still have the source and if it uses `autoconf`(1)/`automake`(1) and if you can remember how you configured it, execure as follows.
667 osamu 6683
668     --------------------
669     $ ./configure ''all-of-the-options-you-gave-it''
670     # make uninstall
671     --------------------
672    
673 osamu 6830 Alternatively, if you are absolutely sure that the install process puts files only under "`/usr/local/`" and there is nothing important there, you can erase all its contents by the following.
674 osamu 6683
675     --------------------
676     # find /usr/local -type f -print0 | xargs -0 rm -f
677     --------------------
678    
679     If you are not sure where files are installed, you should consider using `checkinstall`(8) from the `checkinstall` package, which provides a clean path for the uninstall. It now supports to create a Debian package with "`-D`" option.
680    
681     === Perl short script madness
682    
683 osamu 6830 Although any http://en.wikipedia.org/wiki/AWK[AWK] scripts can be automatically rewritten in http://en.wikipedia.org/wiki/Perl[Perl] using `a2p`(1), one-liner AWK scripts are best converted to one-liner perl scripts manually.
684 osamu 6683
685 osamu 6830 Let\'s think following awk script snippet.
686    
687 osamu 6683 --------------------
688     awk '($2=="1957") { print $3 }' |
689     --------------------
690    
691 osamu 6830 This is equivalent to any one of the following lines.
692    
693 osamu 6683 --------------------
694     perl -ne '@f=split; if ($f[1] eq "1957") { print "$f[2]\n"}' |
695     --------------------
696    
697     --------------------
698     perl -ne 'if ((@f=split)[1] eq "1957") { print "$f[2]\n"}' |
699     --------------------
700    
701     --------------------
702     perl -ne '@f=split; print $f[2] if ( $f[1]==1957 )' |
703     --------------------
704    
705     --------------------
706     perl -lane 'print $F[2] if $F[1] eq "1957"' |
707     --------------------
708    
709     --------------------
710     perl -lane 'print$F[2]if$F[1]eq+1957' |
711     --------------------
712    
713 osamu 6830 The last one is a riddle. It took advantage of following Perl features.
714 osamu 6683
715 osamu 6830 - The whitespace is optional.
716     - The automatic conversion exists from number to the string.
717 osamu 6683
718     See `perlrun`(1) for the command-line options. For more crazy Perl scripts, http://perlgolf.sourceforge.net[Perl Golf] may be interesting.
719    
720     === Web
721    
722 osamu 6830 Basic interactive dynamic web pages can be made as follows.
723 osamu 6683
724     - Queries are presented to the browser user using http://en.wikipedia.org/wiki/HTML[HTML] forms.
725 osamu 6830 - Filling and clicking on the form entries will send one of the following http://en.wikipedia.org/wiki/Uniform_Resource_Locator[URL] string with encoded parameters from the browser to the web server.
726 osamu 6683 * "`http://www.foo.dom/cgi-bin/program.pl?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3`"
727     * "`http://www.foo.dom/cgi-bin/program.py?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3`"
728     * "`http://www.foo.dom/program.php?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3`"
729     - "`%nn`" in URL is replaced with a character with hexadecimal `nn` value.
730 osamu 6830 - The environment variable is set as: "`QUERY_STRING="VAR1=VAL1 VAR2=VAL2 VAR3=VAL3"`".
731 osamu 6683 - http://en.wikipedia.org/wiki/Common_Gateway_Interface[CGI] program (any one of "`program.\*`") on the web server executes itself with the environment variable "`$QUERY_STRING`".
732     - `stdout` of CGI program will be sent to the web browser and is presented as an interactive dynamic web page.
733    
734     For security reasons it is better not to hand craft new hacks for parsing CGI parameters. There are established modules for them in Perl and Python. http://en.wikipedia.org/wiki/PHP[PHP] comes with these functionalities. When client data storage is needed, cookies are used. When client side data processing is needed, javascript is frequently used.
735    
736     For more, see http://hoohoo.ncsa.uiuc.edu/cgi/[The Common Gateway Interface], http://www.apache.org/[The Apache Software Foundation], and http://www.mozilla.org/js/[JavaScript].
737    
738     Searching "CGI tutorial" on Google by typing encoded URL http://www.google.com/search?hl=en@@@amp@@@ie=UTF-8@@@amp@@@q=CGI+tutorial[http://www.google.com/search?hl=en@@@amp@@@ie=UTF-8@@@amp@@@q=CGI+tutorial] directly to the browser address is a good way to see the CGI script in action on the Google server.
739    
740     === The source code translation
741    
742 osamu 6830 There are programs to convert source codes.
743 osamu 6683
744 osamu 6830 .List of source code translation tools
745 osamu 6683 [grid="all"]
746     `-----------`-------------`------------`----------`------------------------------------------------------------------
747 osamu 6830 package popcon size keyword description
748 osamu 6683 ---------------------------------------------------------------------------------------------------------------------
749 osamu 6830 `perl` @@@popcon1@@@ @@@psize1@@@ AWK->PERL convert source codes from AWK to PERL: `a2p`(1)
750     `f2c` @@@popcon1@@@ @@@psize1@@@ FORTRAN->C convert source codes from FORTRAN 77 to C/C++: `f2c`(1)
751     `protoize` @@@popcon1@@@ @@@psize1@@@ ANSI C create/remove ANSI prototypes from C code
752     `intel2gas` @@@popcon1@@@ @@@psize1@@@ intel->gas converter from NASM (intel format) to the GNU Assembler (GAS)
753 osamu 6683 ---------------------------------------------------------------------------------------------------------------------
754    
755     === Making Debian package
756    
757 osamu 6830 If you want to make a Debian package, read followings.
758 osamu 6683
759 osamu 6830 - <<_debian_package_management>> to understand the basic package system
760     - <<_porting_a_package_to_the_stable_system>> to understand basic porting process
761     - <<_chroot_system>> to understand basic chroot techniques
762     - `debuild`(1), `pbuilder`(1) and `pdebuild`(1)
763     - <<_debugging_the_debian_package>> for recompiling for debugging
764     - http://www.debian.org/doc/manuals/maint-guide/[Debian New Maintainers\' Guide] as tutorial (the `maint-guide` package)
765     - http://www.debian.org/doc/manuals/developers-reference/[Debian Developer\'s Reference] (the `developers-reference` package)
766     - http://www.debian.org/doc/debian-policy/[Debian Policy Manual] (the `debian-policy` package)
767 osamu 6683
768     There are packages such as `dh-make`, `dh-make-perl`, etc., which help packaging.
769 osamu 6783

  ViewVC Help
Powered by ViewVC 1.1.5