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

  ViewVC Help
Powered by ViewVC 1.1.5