aboutsummaryrefslogtreecommitdiff
path: root/documentation
diff options
context:
space:
mode:
Diffstat (limited to 'documentation')
-rw-r--r--documentation/content/en/articles/linux-emulation/_index.adoc2
-rw-r--r--documentation/content/en/books/developers-handbook/secure/_index.adoc4
-rw-r--r--documentation/content/en/books/handbook/advanced-networking/_index.adoc2
-rw-r--r--documentation/content/en/books/handbook/glossary.adoc1
-rw-r--r--documentation/content/en/books/handbook/mirrors/_index.adoc4
-rw-r--r--documentation/content/en/books/handbook/preface/_index.adoc2
-rw-r--r--documentation/content/en/books/handbook/x11/_index.adoc2
-rw-r--r--documentation/content/en/books/porters-handbook/makefiles/_index.adoc17
-rw-r--r--documentation/content/en/books/porters-handbook/testing/_index.adoc84
-rw-r--r--documentation/content/es/articles/linux-emulation/_index.adoc2
-rw-r--r--documentation/content/pt-br/articles/linux-emulation/_index.adoc2
-rw-r--r--documentation/content/ru/articles/vm-design/_index.adoc49
-rw-r--r--documentation/content/ru/articles/vm-design/_index.po1356
-rw-r--r--documentation/content/ru/books/developers-handbook/_index.adoc253
-rw-r--r--documentation/content/ru/books/developers-handbook/_index.po70
-rw-r--r--documentation/content/ru/books/developers-handbook/bibliography/_index.adoc62
-rw-r--r--documentation/content/ru/books/developers-handbook/bibliography/_index.po92
-rw-r--r--documentation/content/ru/books/developers-handbook/book.adoc84
-rw-r--r--documentation/content/ru/books/developers-handbook/book.po70
-rw-r--r--documentation/content/ru/books/developers-handbook/introduction/_index.adoc86
-rw-r--r--documentation/content/ru/books/developers-handbook/introduction/_index.po185
-rw-r--r--documentation/content/ru/books/developers-handbook/ipv6/_index.adoc687
-rw-r--r--documentation/content/ru/books/developers-handbook/ipv6/_index.po2818
-rw-r--r--documentation/content/ru/books/developers-handbook/kernelbuild/_index.adoc94
-rw-r--r--documentation/content/ru/books/developers-handbook/kernelbuild/_index.po140
-rw-r--r--documentation/content/ru/books/developers-handbook/kerneldebug/_index.adoc773
-rw-r--r--documentation/content/ru/books/developers-handbook/kerneldebug/_index.po2243
-rw-r--r--documentation/content/ru/books/developers-handbook/l10n/_index.adoc228
-rw-r--r--documentation/content/ru/books/developers-handbook/l10n/_index.po659
-rw-r--r--documentation/content/ru/books/developers-handbook/parti.adoc12
-rw-r--r--documentation/content/ru/books/developers-handbook/parti.po31
-rw-r--r--documentation/content/ru/books/developers-handbook/partii.adoc12
-rw-r--r--documentation/content/ru/books/developers-handbook/partii.po31
-rw-r--r--documentation/content/ru/books/developers-handbook/partiii.adoc12
-rw-r--r--documentation/content/ru/books/developers-handbook/partiii.po31
-rw-r--r--documentation/content/ru/books/developers-handbook/partiv.adoc12
-rw-r--r--documentation/content/ru/books/developers-handbook/partiv.po31
-rw-r--r--documentation/content/ru/books/developers-handbook/partv.adoc12
-rw-r--r--documentation/content/ru/books/developers-handbook/partv.po31
-rw-r--r--documentation/content/ru/books/developers-handbook/policies/_index.adoc148
-rw-r--r--documentation/content/ru/books/developers-handbook/policies/_index.po523
-rw-r--r--documentation/content/ru/books/developers-handbook/secure/_index.adoc230
-rw-r--r--documentation/content/ru/books/developers-handbook/secure/_index.po824
-rw-r--r--documentation/content/ru/books/developers-handbook/sockets/_index.adoc909
-rw-r--r--documentation/content/ru/books/developers-handbook/sockets/_index.po3021
-rw-r--r--documentation/content/ru/books/developers-handbook/testing/_index.adoc187
-rw-r--r--documentation/content/ru/books/developers-handbook/testing/_index.po802
-rw-r--r--documentation/content/ru/books/developers-handbook/tools/_index.adoc1428
-rw-r--r--documentation/content/ru/books/developers-handbook/tools/_index.po4483
-rw-r--r--documentation/content/ru/books/developers-handbook/x86/_index.adoc3864
-rw-r--r--documentation/content/ru/books/developers-handbook/x86/_index.po11160
51 files changed, 37532 insertions, 333 deletions
diff --git a/documentation/content/en/articles/linux-emulation/_index.adoc b/documentation/content/en/articles/linux-emulation/_index.adoc
index a252df5f54..425e1b6c9f 100644
--- a/documentation/content/en/articles/linux-emulation/_index.adoc
+++ b/documentation/content/en/articles/linux-emulation/_index.adoc
@@ -1431,6 +1431,6 @@ I would like to thank all those people for their advice, code reviews and genera
[[literatures]]
== Literatures
-. Marshall Kirk McKusick - George V. Nevile-Neil. Design and Implementation of the FreeBSD operating system. Addison-Wesley, 2005.
+. Marshall Kirk McKusick - George V. Neville-Neil. Design and Implementation of the FreeBSD operating system. Addison-Wesley, 2005.
. https://tldp.org[https://tldp.org]
. https://www.kernel.org[https://www.kernel.org]
diff --git a/documentation/content/en/books/developers-handbook/secure/_index.adoc b/documentation/content/en/books/developers-handbook/secure/_index.adoc
index 738a18988c..a871193a5b 100644
--- a/documentation/content/en/books/developers-handbook/secure/_index.adoc
+++ b/documentation/content/en/books/developers-handbook/secure/_index.adoc
@@ -69,7 +69,7 @@ UNIX(R) processes do not execute synchronously so logical operations are rarely
[[secure-bufferov]]
== Buffer Overflows
-Buffer Overflows have been around since the very beginnings of the von Neumann crossref:bibliography[cod,1] architecture.
+Buffer Overflows have been around since the very beginnings of the von Neumann crossref:bibliography[COD,1] architecture.
They first gained widespread notoriety in 1988 with the Morris Internet worm.
Unfortunately, the same basic attack remains effective today.
By far the most common type of buffer overflow attack is based on corrupting the stack.
@@ -81,7 +81,7 @@ This stack frame consists of the arguments passed to the function as well as a d
The "stack pointer" is a register that holds the current location of the top of the stack.
Since this value is constantly changing as new values are pushed onto the top of the stack,
many implementations also provide a "frame pointer" that is located near the beginning of a stack frame so that local variables can more easily be addressed relative to this value.
-crossref:bibliography[cod,1] The return address for function calls is also stored on the stack, and this is the cause of stack-overflow exploits since overflowing a local variable in a function can overwrite the return address of that function, potentially allowing a malicious user to execute any code he or she wants.
+crossref:bibliography[COD,1] The return address for function calls is also stored on the stack, and this is the cause of stack-overflow exploits since overflowing a local variable in a function can overwrite the return address of that function, potentially allowing a malicious user to execute any code he or she wants.
Although stack-based attacks are by far the most common,
it would also be possible to overrun the stack with a heap-based (malloc/free) attack.
diff --git a/documentation/content/en/books/handbook/advanced-networking/_index.adoc b/documentation/content/en/books/handbook/advanced-networking/_index.adoc
index 42125e86d7..7090c1cd39 100644
--- a/documentation/content/en/books/handbook/advanced-networking/_index.adoc
+++ b/documentation/content/en/books/handbook/advanced-networking/_index.adoc
@@ -758,7 +758,7 @@ The client machine found the AP and can be associated with it:
This section focuses on setting up a FreeBSD access point using the WPA2 security protocol.
More details regarding WPA and the configuration of WPA-based wireless clients
-can be found in crossref:advanced-networking[network-wireless-wpa, WPA with EAP-TLS].
+can be found in crossref:advanced-networking[network-wireless-wpa-eap-tls, WPA with EAP-TLS].
The man:hostapd[8] daemon is used to deal with client authentication and key management on the WPA2-enabled AP.
diff --git a/documentation/content/en/books/handbook/glossary.adoc b/documentation/content/en/books/handbook/glossary.adoc
index 005a10e66f..28439170fa 100644
--- a/documentation/content/en/books/handbook/glossary.adoc
+++ b/documentation/content/en/books/handbook/glossary.adoc
@@ -310,6 +310,7 @@ See crossref:glossary[elf-glossary,Executable and Linking Format].
ESP::
See crossref:glossary[esp-glossary,Encapsulated Security Payload].
+[[esp-glossary]]
Encapsulated Security Payload::
{empty}
diff --git a/documentation/content/en/books/handbook/mirrors/_index.adoc b/documentation/content/en/books/handbook/mirrors/_index.adoc
index e60a92988d..a43bbecb46 100644
--- a/documentation/content/en/books/handbook/mirrors/_index.adoc
+++ b/documentation/content/en/books/handbook/mirrors/_index.adoc
@@ -257,10 +257,6 @@ Mirror list maintained by the community and other companies:
| link:http://ftp.si.FreeBSD.org/pub/FreeBSD[http] link:http://ftp.si.FreeBSD.org/pub/FreeBSD[http_v6] link:ftp://ftp.si.FreeBSD.org/pub/FreeBSD[ftp] link:ftp://ftp.si.FreeBSD.org/pub/FreeBSD[ftp_v6]
| South Africa icon:envelope[link=mailto:{mirrors-south-africa-email}, title="mirror contact"]
-| ftp.za.FreeBSD.org
-| link:https://ftp.za.FreeBSD.org/pub/FreeBSD[https] link:https://ftp.za.FreeBSD.org/pub/FreeBSD[https_v6] link:rsync://ftp.za.FreeBSD.org[rsync] link:rsync://ftp.za.FreeBSD.org[rsync_v6]
-
-|
| ftp2.za.FreeBSD.org
| link:http://ftp2.za.FreeBSD.org/pub/FreeBSD[http] link:http://ftp2.za.FreeBSD.org/pub/FreeBSD[http_v6] link:ftp://ftp2.za.FreeBSD.org/pub/FreeBSD[ftp_v6]
diff --git a/documentation/content/en/books/handbook/preface/_index.adoc b/documentation/content/en/books/handbook/preface/_index.adoc
index dfed27ebd1..0c9fcd9dfb 100644
--- a/documentation/content/en/books/handbook/preface/_index.adoc
+++ b/documentation/content/en/books/handbook/preface/_index.adoc
@@ -74,7 +74,7 @@ These are the major updates since the fourth edition of the Handbook.
* The crossref:desktop[desktop, Desktop] chapter has been updated with upgraded installation instructions for KDE Plasma, GNOME, XFCE, MATE, Cinnamon, and LXQT, expanded browser options, a new development tools section, and updates to office productivity, document viewers, and finance sections.
* The crossref:multimedia[multimedia, Multimedia] chapter has been reworked with updates to the sound section, new tables for sound mixers, audio players, and video players, guidance on automatic headphone switching, a new conferencing and meetings section, and a revised image scanners section.
* The crossref:linuxemu[linuxemu, Linuxemu] chapter has been improved with updated instructions for setting up a Debian/Ubuntu base system using debootstrap.
-* The crossref:config[config, Config] chapter has been renamed for accuracy, with updates to service management, cron and periodic, syslog, power management, and swap sections. A new entry on config files was added, and the outdated tuning section was removed.
+* The crossref:config[config-tuning, Config] chapter has been renamed for accuracy, with updates to service management, cron and periodic, syslog, power management, and swap sections. A new entry on config files was added, and the outdated tuning section was removed.
* The crossref:security[security, Security] chapter has been updated with enhancements to VPN over IPSec, securing accounts, password hashes, sudo/doas, and OpenSSH/OpenSSL. New sections have been added covering IDS, secure levels, file flags, Capsicum, NFSv4 ACLs, and resource limits.
* The crossref:jails[jails, Jails] chapter has been updated to include details on jail types (Thick, Thin, VNET, and Linux Jails), host system configuration, networking options, the jail configuration file, setup procedures, upgrade methods, resource limits, and different jail managers and container solutions.
* The crossref:mail[mail, Mail] chapter has been updated to include information on DMA, upgrades to Sendmail, instructions for changing DMA and Sendmail to use different MTAs, and the removal of Dialup and Fetchmail sections, along with a reorganization of the chapter.
diff --git a/documentation/content/en/books/handbook/x11/_index.adoc b/documentation/content/en/books/handbook/x11/_index.adoc
index 46d9c3caad..f549ceffec 100644
--- a/documentation/content/en/books/handbook/x11/_index.adoc
+++ b/documentation/content/en/books/handbook/x11/_index.adoc
@@ -308,7 +308,7 @@ To enable the driver, add the module to
# sysrc kld_list+=nvidia-drm
....
-This is the direct rendering crossref:glossary[glossary-kms,KMS] driver.
+This is the direct rendering crossref:glossary[kms-glossary,KMS] driver.
Kernel modesetting is the option to set the graphics mode in the kernel.
Enable it for subsequent boots with the following man:loader.conf[5]
diff --git a/documentation/content/en/books/porters-handbook/makefiles/_index.adoc b/documentation/content/en/books/porters-handbook/makefiles/_index.adoc
index bf37987160..e6842bec60 100644
--- a/documentation/content/en/books/porters-handbook/makefiles/_index.adoc
+++ b/documentation/content/en/books/porters-handbook/makefiles/_index.adoc
@@ -2290,8 +2290,7 @@ Furthermore, `DEFAULT` is a special purpose word (check item
crossref:makefiles[porting-master-sites-n-DEFAULT-group,3]).
. Elements postfixed with `:n` belong to the group `n`, `:m` belong to group `m` and so forth.
+
-[[porting-master-sites-n-DEFAULT-group]]
-. Elements without a postfix are groupless, they all belong to the special group
+. [[porting-master-sites-n-DEFAULT-group]] Elements without a postfix are groupless, they all belong to the special group
`DEFAULT`. Any elements postfixed with `DEFAULT`, is just being redundant
unless an element belongs to both `DEFAULT` and other groups at the same time
(check item crossref:makefiles[porting-master-sites-n-comma-operator,5]).
@@ -2310,8 +2309,7 @@ MASTER_SITES= alpha:DEFAULT
. Groups are not exclusive, an element may belong to several different groups at the same time and a group can either have either several different elements or none at all.
+
-[[porting-master-sites-n-comma-operator]]
-. When an element belongs to several groups at the same time, use the comma operator (`,`).
+. [[porting-master-sites-n-comma-operator]] When an element belongs to several groups at the same time, use the comma operator (`,`).
+
Instead of repeating it several times, each time with a different postfix, we can list several groups at once in a single postfix.
For instance, `:m,n,o` marks an element that belongs to group `m`, `n` and `o`.
@@ -2340,8 +2338,7 @@ MASTER_SITES= alpha:DEFAULT,SOME_SITE
. All sites within a given group are sorted according to `MASTER_SORT_AWK`. All groups within `MASTER_SITES` and `PATCH_SITES` are sorted as well.
+
-[[porting-master-sites-n-group-semantics]]
-. Group semantics can be used in any of the variables `MASTER_SITES`, `PATCH_SITES`, `MASTER_SITE_SUBDIR`, `PATCH_SITE_SUBDIR`, `DISTFILES`, and `PATCHFILES` according to this syntax:
+. [[porting-master-sites-n-group-semantics]] Group semantics can be used in any of the variables `MASTER_SITES`, `PATCH_SITES`, `MASTER_SITE_SUBDIR`, `PATCH_SITE_SUBDIR`, `DISTFILES`, and `PATCHFILES` according to this syntax:
.. All `MASTER_SITES`, `PATCH_SITES`, `MASTER_SITE_SUBDIR` and
`PATCH_SITE_SUBDIR` elements must be terminated with the forward slash `/`
character. If any elements belong to any groups, the group postfix `:__n__`
@@ -2492,8 +2489,7 @@ PATCHFILES= patch1:test
according to the aforementioned syntax rules, especially as shown in item
crossref:makefiles[porting-master-sites-n-group-semantics, 7].
+
-[[porting-master-sites-n-what-changes-in-port-targets]]
-. The port targets remain the same: `checksum`, `makesum`, `patch`, `configure`, `build`, etc. With the obvious exceptions of `do-fetch`, `fetch-list`, `master-sites` and `patch-sites`.
+. [[porting-master-sites-n-what-changes-in-port-targets]] The port targets remain the same: `checksum`, `makesum`, `patch`, `configure`, `build`, etc. With the obvious exceptions of `do-fetch`, `fetch-list`, `master-sites` and `patch-sites`.
** `do-fetch`: deploys the new grouping postfixed `DISTFILES` and `PATCHFILES`
with their matching group elements within both `MASTER_SITES` and
@@ -2511,8 +2507,7 @@ crossref:makefiles[porting-master-sites-n-new-port-targets-master-sites-all, B]
. New port targets
.. There are `master-sites-_n_` and `patch-sites-_n_` targets which will list the elements of the respective group _n_ within `MASTER_SITES` and `PATCH_SITES` respectively. For instance, both `master-sites-DEFAULT` and `patch-sites-DEFAULT` will return the elements of group `DEFAULT`, `master-sites-test` and `patch-sites-test` of group `test`, and thereon.
+
-[[porting-master-sites-n-new-port-targets-master-sites-all]]
-.. There are new targets `master-sites-all` and `patch-sites-all` which do the work of the old `master-sites` and `patch-sites` ones. They return the elements of all groups as if they all belonged to the same group with the caveat that it lists as many `MASTER_SITE_BACKUP` and `MASTER_SITE_OVERRIDE` as there are groups defined within either `DISTFILES` or `PATCHFILES`; respectively for `master-sites-all` and `patch-sites-all`.
+.. [[porting-master-sites-n-new-port-targets-master-sites-all]] There are new targets `master-sites-all` and `patch-sites-all` which do the work of the old `master-sites` and `patch-sites` ones. They return the elements of all groups as if they all belonged to the same group with the caveat that it lists as many `MASTER_SITE_BACKUP` and `MASTER_SITE_OVERRIDE` as there are groups defined within either `DISTFILES` or `PATCHFILES`; respectively for `master-sites-all` and `patch-sites-all`.
[[makefile-dist_subdir]]
=== `DIST_SUBDIR`
@@ -3717,7 +3712,7 @@ Perl related variables are described in crossref:special[using-perl,Using Perl].
X11 variables are listed in crossref:special[using-x11,Using X11].
crossref:special[using-gnome,Using Gnome] deals with GNOME and crossref:special[using-kde,Using KDE] with KDE related variables.
crossref:special[using-java,Using Java] documents Java variables, while crossref:special[using-php,Web Applications, Apache and PHP] contains information on Apache, PHP and PEAR modules.
-Python is discussed in crossref:special[using-python,Using Python], while Ruby in crossref:special[using-ruby,Using Ruby].
+Python is discussed in crossref:special[using-python,Using Python], while Ruby in crossref:uses[uses-ruby,Ruby].
crossref:special[using-sdl,Using SDL] provides variables used for SDL applications and finally, crossref:special[using-xfce,Using Xfce] contains information on Xfce.
[[makefile-version-dependency]]
diff --git a/documentation/content/en/books/porters-handbook/testing/_index.adoc b/documentation/content/en/books/porters-handbook/testing/_index.adoc
index 4c94b4fc85..85433d1df0 100644
--- a/documentation/content/en/books/porters-handbook/testing/_index.adoc
+++ b/documentation/content/en/books/porters-handbook/testing/_index.adoc
@@ -293,41 +293,41 @@ Create the base jails which poudriere will use for building:
[source,shell]
....
-# poudriere jail -c -j 131Ramd64 -v 13.1-RELEASE -a amd64
+# poudriere jail -c -j 143Ramd64 -v 14.3-RELEASE -a amd64
....
-Fetch a `13.1-RELEASE` for `amd64` from the FTP server given by `FREEBSD_HOST` in [.filename]#poudriere.conf#,
-create the zfs file system `tank/poudriere/jails/131Ramd64`,
-mount it on [.filename]#/poudriere/jails/131Ramd64# and extract the `13.1-RELEASE` tarballs into this file system.
+Fetch a `14.3-RELEASE` for `amd64` from the HTTPS server given by `FREEBSD_HOST` in [.filename]#poudriere.conf#,
+create the zfs file system `tank/poudriere/jails/143Ramd64`,
+mount it on [.filename]#/poudriere/jails/143Ramd64# and extract the `14.3-RELEASE` tarballs into this file system.
[source,shell]
....
-# poudriere jail -c -j 12i386 -v stable/12 -a i386 -m git+https
+# poudriere jail -c -j 13i386 -v stable/13 -a i386 -m git+https
....
-Create `tank/poudriere/jails/12i386`, mount it on [.filename]#/poudriere/jails/12i386#,
-then check out the tip of the Git branch of `FreeBSD-12-STABLE` from `GIT_HOST` in [.filename]#poudriere.conf# or the default `git.freebsd.org` into [.filename]#/poudriere/jails/12i386/usr/src#,
-then complete a `buildworld` and install it into [.filename]#/poudriere/jails/12i386#.
+Create `tank/poudriere/jails/13i386`, mount it on [.filename]#/poudriere/jails/13i386#,
+then check out the tip of the Git branch of `FreeBSD-13-STABLE` from `GIT_HOST` in [.filename]#poudriere.conf# or the default `git.freebsd.org` into [.filename]#/poudriere/jails/13i386/usr/src#,
+then complete a `buildworld` and install it into [.filename]#/poudriere/jails/13i386#.
[NOTE]
====
While it is possible to build a newer version of FreeBSD on an older version, most of the time it will not run.
-For example, if a `stable/13` jail is needed, the host will have to run `stable/13` too.
-Running `13.1-RELEASE` is not enough.
+For example, if a `stable/14` jail is needed, the host will have to run `stable/14` too.
+Running `14.3-RELEASE` is not enough.
====
[NOTE]
====
-To create a poudriere jail for `14.0-CURRENT`:
+To create a poudriere jail for `16.0-CURRENT`:
[source,shell]
....
-# poudriere jail -c -j 14amd64 -v main -a amd64 -m git+https
+# poudriere jail -c -j 16amd64 -v main -a amd64 -m git+https
....
-In order to run a `14.0-CURRENT` poudriere jail the host must be running `14.0-CURRENT`.
+In order to run a `16.0-CURRENT` poudriere jail the host must be running `16.0-CURRENT`.
In general, newer kernels can build and run older jails.
-For instance, a `14.0-CURRENT` kernel can build and run a `12.4-STABLE` if the `COMPAT_FREEBSD12` kernel option was compiled in (on by default in `14.0-CURRENT`[.filename]#GENERIC# kernel config).
+For instance, a `16.0-CURRENT` kernel can build and run a `14.3-STABLE` if the `COMPAT_FREEBSD14` kernel option was compiled in (on by default in `16.0-CURRENT`[.filename]#GENERIC# kernel config).
====
A list of jails currently known to poudriere can be shown with `poudriere jail -l`:
@@ -336,8 +336,8 @@ A list of jails currently known to poudriere can be shown with `poudriere jail -
....
# poudriere jail -l
JAILNAME VERSION ARCH METHOD
-131Ramd64 13.1-RELEASE amd64 ftp
-12i386 12.4-STABLE i386 git+https
+143Ramd64 14.3-RELEASE amd64 http
+13i386 13.5-STABLE i386 git+https
....
[[testing-poudriere-maintaining-jails]]
@@ -385,7 +385,7 @@ Afterward it is included in the list of known ports trees:
....
# poudriere ports -l
PORTSTREE METHOD TIMESTAMP PATH
-default git+https 2020-07-20 04:23:56 /poudriere/ports/default
+default git+https 2025-07-20 04:23:56 /poudriere/ports/default
....
[NOTE]
@@ -416,7 +416,7 @@ This will be listed in the table of known trees:
....
# poudriere ports -l
PORTSTREE METHOD TIMESTAMP PATH
-development null 2020-07-20 05:06:33 /work/ports
+development null 2025-07-20 05:06:33 /work/ports
....
[NOTE]
@@ -448,11 +448,11 @@ crossref:testing[testing-poudriere-ports-tree-manual, Using Manually Managed Por
After jails and ports trees have been set up, the result of a contributor's modifications to the ports tree can be tested.
-For example, local modifications to the package:www/firefox[] port located in [.filename]#/work/ports/www/firefox# can be tested in the previously created 13.1-RELEASE jail:
+For example, local modifications to the package:www/firefox[] port located in [.filename]#/work/ports/www/firefox# can be tested in the previously created 14.3-RELEASE jail:
[source,shell]
....
-# poudriere testport -j 131Ramd64 -p development -o www/firefox
+# poudriere testport -j 143Ramd64 -p development -o www/firefox
....
This will build all dependencies of Firefox.
@@ -460,10 +460,10 @@ If a dependency has been built previously and is still up-to-date, the pre-built
If a dependency has no up-to-date package, one will be built with default options in a jail.
Then Firefox itself is built.
-The complete build of every port is logged to [.filename]#/poudriere/data/logs/bulk/131Ri386-development/build-time/logs#.
+The complete build of every port is logged to [.filename]#/poudriere/data/logs/bulk/143Ri386-development/build-time/logs#.
-The directory name `131Ri386-development` is derived from the arguments to `-j` and `-p`, respectively.
-For convenience, a symbolic link [.filename]#/poudriere/data/logs/bulk/131Ri386-development/latest# is also maintained.
+The directory name `143Ri386-development` is derived from the arguments to `-j` and `-p`, respectively.
+For convenience, a symbolic link [.filename]#/poudriere/data/logs/bulk/143Ri386-development/latest# is also maintained.
The link points to the latest _build-time_ directory.
Also in this directory is an [.filename]#index.html# for observing the build process with a web browser.
@@ -472,7 +472,7 @@ To ease investigation, jails can be kept running after the build by adding `-i`
[source,shell]
....
-# poudriere testport -j 131Ramd64 -p development -i -o www/firefox
+# poudriere testport -j 143Ramd64 -p development -i -o www/firefox
....
After the build completes, and regardless of whether it was successful, a shell is provided within the jail.
@@ -483,16 +483,16 @@ It is then possible to man:jexec[8] into it:
[source,shell]
....
-# poudriere testport -j 131Ramd64 -p development -I -o www/firefox
+# poudriere testport -j 143Ramd64 -p development -I -o www/firefox
[...]
====>> Installing local Pkg repository to /usr/local/etc/pkg/repos
-====>> Leaving jail 131Ramd64-development-n running, mounted at /poudriere/data/.m/131Ramd64-development/ref for interactive run testing
-====>> To enter jail: jexec 131Ramd64-development-n env -i TERM=$TERM /usr/bin/login -fp root
-====>> To stop jail: poudriere jail -k -j 131Ramd64 -p development
-# jexec 131Ramd64-development-n env -i TERM=$TERM /usr/bin/login -fp root
+====>> Leaving jail 143Ramd64-development-n running, mounted at /poudriere/data/.m/143Ramd64-development/ref for interactive run testing
+====>> To enter jail: jexec 143Ramd64-development-n env -i TERM=$TERM /usr/bin/login -fp root
+====>> To stop jail: poudriere jail -k -j 143Ramd64 -p development
+# jexec 143Ramd64-development-n env -i TERM=$TERM /usr/bin/login -fp root
# [do some stuff in the jail]
# exit
-# poudriere jail -k -j 131Ramd64 -p development
+# poudriere jail -k -j 143Ramd64 -p development
====>> Umounting file systems
....
@@ -502,7 +502,7 @@ Adding the `-c`:
[source,shell]
....
-# poudriere testport -j 131Ramd64 -c -o www/firefox
+# poudriere testport -j 143Ramd64 -c -o www/firefox
....
Presents the port configuration dialog before the port is built.
@@ -531,17 +531,17 @@ For instance, testing package:www/firefox[] in a specific set named `devset`, ad
[source,shell]
....
-# poudriere testport -j 131Ramd64 -p development -z devset -o www/firefox
+# poudriere testport -j 143Ramd64 -p development -z devset -o www/firefox
....
This will look for the existence of these directories in this order:
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-development-devset-options#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-devset-options#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-development-options#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-development-devset-options#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-devset-options#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-development-options#
* [.filename]#/usr/local/etc/poudriere.d/devset-options#
* [.filename]#/usr/local/etc/poudriere.d/development-options#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-options#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-options#
* [.filename]#/usr/local/etc/poudriere.d/options#
From this list, poudriere man:nullfs[5]-mounts the _first existing_ directory tree into the [.filename]#/var/db/ports# directory of the build jails.
@@ -575,7 +575,7 @@ For instance:
[source,shell]
....
-# poudriere testport -j 131Ramd64 -p development -z devset -o www/firefox
+# poudriere testport -j 143Ramd64 -p development -z devset -o www/firefox
....
causes poudriere to check for the existence of these files in this order:
@@ -583,14 +583,14 @@ causes poudriere to check for the existence of these files in this order:
* [.filename]#/usr/local/etc/poudriere.d/make.conf#
* [.filename]#/usr/local/etc/poudriere.d/devset-make.conf#
* [.filename]#/usr/local/etc/poudriere.d/development-make.conf#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-make.conf#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-development-make.conf#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-devset-make.conf#
-* [.filename]#/usr/local/etc/poudriere.d/131Ramd64-development-devset-make.conf#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-make.conf#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-development-make.conf#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-devset-make.conf#
+* [.filename]#/usr/local/etc/poudriere.d/143Ramd64-development-devset-make.conf#
Unlike with sets, all of the found files will be appended, _in that order_, into one [.filename]#make.conf# inside the build jails.
It is hence possible to have general make variables, intended to affect all builds in [.filename]#/usr/local/etc/poudriere.d/make.conf#.
-Special variables, intended to affect only certain jails or sets can be set in specialised [.filename]#make.conf# files, such as [.filename]#/usr/local/etc/poudriere.d/131Ramd64-development-devset-make.conf#.
+Special variables, intended to affect only certain jails or sets can be set in specialised [.filename]#make.conf# files, such as [.filename]#/usr/local/etc/poudriere.d/143Ramd64-development-devset-make.conf#.
[[testing-poudriere-sets-perl]]
.Using [.filename]#make.conf# to Change Default Perl
diff --git a/documentation/content/es/articles/linux-emulation/_index.adoc b/documentation/content/es/articles/linux-emulation/_index.adoc
index 19b4c23c12..14772edc88 100644
--- a/documentation/content/es/articles/linux-emulation/_index.adoc
+++ b/documentation/content/es/articles/linux-emulation/_index.adoc
@@ -968,6 +968,6 @@ Me gustaría agradecer a todas esas personas por sus consejos, revisiones de có
[[literatures]]
== Bibliografía
-. Marshall Kirk McKusick - George V. Nevile-Neil. Diseño e implementación del sistema operativo FreeBSD. Addison-Wesley, 2005.
+. Marshall Kirk McKusick - George V. Neville-Neil. Diseño e implementación del sistema operativo FreeBSD. Addison-Wesley, 2005.
. https://tldp.org[https://tldp.org]
. https://www.kernel.org[https://www.kernel.org]
diff --git a/documentation/content/pt-br/articles/linux-emulation/_index.adoc b/documentation/content/pt-br/articles/linux-emulation/_index.adoc
index 27ae1fe7ca..5e0a712e05 100644
--- a/documentation/content/pt-br/articles/linux-emulation/_index.adoc
+++ b/documentation/content/pt-br/articles/linux-emulation/_index.adoc
@@ -968,6 +968,6 @@ Gostaria de agradecer a todas as pessoas por seus conselhos, revisões de códig
[[literatures]]
== Literaturas
-. Marshall Kirk McKusick - George V. Nevile-Neil. Design and Implementation of the FreeBSD operating system. Addison-Wesley, 2005.
+. Marshall Kirk McKusick - George V. Neville-Neil. Design and Implementation of the FreeBSD operating system. Addison-Wesley, 2005.
. https://tldp.org[https://tldp.org]
. https://www.kernel.org[https://www.kernel.org]
diff --git a/documentation/content/ru/articles/vm-design/_index.adoc b/documentation/content/ru/articles/vm-design/_index.adoc
index 99af966d20..e0847dea68 100644
--- a/documentation/content/ru/articles/vm-design/_index.adoc
+++ b/documentation/content/ru/articles/vm-design/_index.adoc
@@ -1,9 +1,12 @@
---
-title: Элементы архитектуры системы виртуальной памяти во FreeBSD
authors:
- - author: Matthew Dillon
+ -
+ author: 'Matthew Dillon'
email: dillon@apollo.backplane.com
-trademarks: ["freebsd", "linux", "microsoft", "opengroup", "general"]
+description: 'Простое и понятное описание архитектуры системы виртуальной памяти FreeBSD'
+tags: ["Design", "virtual machine", "FreeBSD"]
+title: 'Элементы архитектуры системы виртуальной памяти во FreeBSD'
+trademarks: ["freebsd", "linux", "microsoft", "opengroup", "daemon-news", "general"]
---
= Элементы архитектуры системы виртуальной памяти во FreeBSD
@@ -37,10 +40,17 @@ ifndef::env-beastie[]
include::../../../../../shared/asciidoctor.adoc[]
endif::[]
+[NOTE]
+====
+Этот документ устарел, и некоторые разделы больше не соответствуют текущему состоянию системы виртуальной памяти. Он сохранён в исторических целях и может быть обновлён в будущем.
+====
+
[.abstract-title]
Аннотация
-Название статьи говорит лишь о том, что я попытаюсь описать в целом VM-систему понятным языком. Последний год я сосредоточил усилия в работе над несколькими основными подсистемами ядра FreeBSD, среди которых подсистемы VM и подкачки были самыми интересными, а NFS оказалась "необходимой рутиной". Я переписал лишь малую часть кода. Что касается VM, то я единственным большим обновлением, которое я сделал, является переделка подсистемы подкачки. Основная часть моей работы заключалась в зачистке и поддержке кода, с единственной заметной переделкой кода и без значительной переделки алгоритмов в VM-подсистеме. В основном теоретическая база работы VM-подсистемы осталась неизменной, а большинство благодарностей за современных нововведения за последние несколько лет принадлежат John Dyson и David Greenman. Не являясь историком, как Керк, я не буду пытаться связать различные возможности системы с именами, потому что обязательно ошибусь.
+Matthew Dillon <dillon@apollo.backplane.com>
+
+Это название — просто замысловатый способ сказать, что я попытаюсь описать всю систему виртуальной памяти (VM) целиком, по возможности так, чтобы это было понятно каждому.В течение последнего года я сосредоточился на нескольких основных подсистемах ядра FreeBSD. Наиболее интересными из них стали подсистемы VM и подкачки (Swap), тогда как работа с NFS оказалась, скорее, «необходимой рутиной». Я переписал лишь небольшие части кода. В области VM моей единственной крупной переработкой стала подсистема подкачки. В основном моя работа заключалась в очистке и поддержке кода, с умеренными правками и без серьёзных изменений алгоритмов в подсистеме VM. Теоретическая основа VM-подсистемы осталась неизменной, и львиная доля заслуг в её модернизации за последние годы принадлежит Джону Дайсону и Дэвиду Гринману. Я не историк, в отличие от Кирка, поэтому не стану приписывать различные функции конкретным людям — всё равно где-нибудь ошибусь.
'''
@@ -69,7 +79,7 @@ toc::[]
FreeBSD управляет всем этим при помощи многоуровневой модели VM-объектов. Исходный файл с двоичной программой переносится на самый нижний уровень объектов VM. Уровень страниц, копируемых при записи, находится выше него, и хранит те страницы, которые были скопированы из исходного файла. Если программа модифицирует страницы данных, относящиеся к исходному файлу, то система VM обнаруживает это и переносит копию этой страницы на более высокий уровень. Когда процесс разветвляется, добавляются новые уровни VM-объектов. Это можно показать на простом примере. Функция `fork()` является общей операцией для всех систем *BSD, так что в этом примере будет рассматриваться программа, которая запускается, а затем разветвляется. Когда процесс запускается, VM-система создает некоторый уровень объектов, обозначим его A:
-image::fig1.png[Рисунок]
+image::fig1.png["Рисунок"]
A соответствует файлу-по необходимости страницы памяти могут высвобождаться и подгружаться с носителя файла. Подгрузка с диска может потребоваться программе, однако на самом деле мы не хотим, чтобы она записывалась обратно в файл. Поэтому VM-система создает второй уровень, B, который физически поддерживается дисковым пространством подкачки:
@@ -140,20 +150,13 @@ FreeBSD использует несколько очередей страниц
Большой процент ошибок доступа к страницам, относится к ошибкам при заполнении нулями. Вы можете обычно видеть это, просматривая вывод команды `vmstat -s`. Это происходит, когда процесс обращается к страницам в своей области BSS. Область BSS предполагается изначально заполненной нулями, но VM-система не заботится о выделении памяти до тех пор, пока процесс реально к ней не обратится. При возникновении ошибки VM-система должна не только выделить новую страницу, но и заполнить ее нулями. Для оптимизации операции по заполнению нулями в системе VM имеется возможность предварительно обнулять страницы и помечать их, и запрашивать уже обнуленные страницы при возникновении ошибок заполнения нулями. Предварительное заполнение нулями происходит, когда CPU простаивает, однако количество страниц, которые система заранее заполняет нулями, ограничено, для того, чтобы не переполнить кэши памяти. Это прекрасный пример добавления сложности в VM-систему ради оптимизации критического пути.
-[[pre-table-optimizations]]
+[[page-table-optimizations]]
== Оптимизация таблицы страниц
Оптимизация таблицы страниц составляет самую содержательную часть архитектуры VM во FreeBSD и она проявляется при появлении нагрузки при значительном использовании `mmap()`. Я думаю, что это на самом деле особенность работы большинства BSD-систем, хотя я не уверен, когда это проявилось впервые. Есть два основных подхода к оптимизации. Первый заключается в том, что аппаратные таблицы страниц не содержат постоянного состояния, а вместо этого могут быть сброшены в любой момент с малыми накладными расходами. Второй подход состоит в том, что каждая активная таблица страниц в системе имеет управляющую структуру `pv_entry`, которая связана в структуру `vm_page`. FreeBSD может просто просматривать эти отображения, которые существуют, когда как в Linux должны проверяться все таблицы страниц, которые _могут_ содержать нужное отображение, что в некоторых ситуация дает увеличение сложности O(n^2). Из-за того, что FreeBSD стремится выбрать наиболее подходящую к повторному использованию или сбросу в область подкачки страницу, когда ощущается нехватка памяти, система дает лучшую производительность при нагрузке. Однако во FreeBSD требуется тонкая настройка ядра для соответствия ситуациям с большим совместно используемым адресным пространством, которые могут случиться в системе, обслуживающей сервер телеконференций, потому что структуры `pv_entry` могут оказаться исчерпанными.
И в Linux, и во FreeBSD требуются доработки в этой области. FreeBSD пытается максимизировать преимущества от потенциально редко применяемой модели активного отображения (к примеру, не всем процессам нужно отображать все страницы динамической библиотеки), когда как Linux пытается упростить свои алгоритмы. FreeBSD имеет здесь общее преимущество в производительности за счет использования дополнительной памяти, но FreeBSD выглядит хуже в случае, когда большой файл совместно используется сотнями процессов. Linux, с другой стороны, выглядит хуже в случае, когда много процессов частично используют одну и ту же динамическую библиотеку, а также работает неоптимально при попытке определить, может ли страница повторно использоваться, или нет.
-[[page-coloring-optimizations]]
-== Подгонка страниц
-
-Мы закончим рассмотрением метода оптимизации подгонкой страниц. Подгонка является методом оптимизации, разработанным для того, чтобы доступ в последовательные страницы виртуальной памяти максимально использовал кэш процессора. В далеком прошлом (то есть больше 10 лет назад) процессорные кэши предпочитали отображать виртуальную память, а не физическую. Это приводило к огромному количеству проблем, включая необходимость очистки кэша в некоторых случаях при каждом переключении контекста и проблемы с замещением данных в кэше. В современных процессорах кэши отображают физическую память именно для решения этих проблем. Это означает, что две соседние страницы в адресном пространстве процессов могут не соответствовать двух соседним страницам в кэше. Фактически, если вы об этом не позаботились, то соседние страницы в виртуальной памяти могут использовать ту же самую страницу в кэше процессора-это приводит к сбросу кэшируемых данных и снижению производительности CPU. Это так даже с множественными ассоциативными кэшами (хотя здесь эффект несколько сглажен).
-
-Код выделения памяти во FreeBSD выполняет оптимизацию с применением подгонки страниц, означающую то, что код выделения памяти будет пытаться найти свободные страницы, которые являются последовательными с точки зрения кэша. Например, если страница 16 физической памяти назначается странице 0 виртуальной памяти процесса, а в кэш помещается 4 страницы, то код подгонки страниц не будет назначать страницу 20 физической памяти странице 1 виртуальной памяти процесса. Вместо этого будет назначена страница 21 физической памяти. Код подгонки страниц попытается избежать назначение страницы 20, потому что такое отображение перекрывается в той же самой памяти кэша как страница 16, и приведет к неоптимальному кэшированию. Как вы можете предположить, такой код значительно добавляет сложности в подсистему выделения памяти VM, но результат стоит того. Подгонка страниц делает память VM предсказуемой, как и обычная физическая память, относительно производительности кэша.
-
[[conclusion]]
== Заключение
@@ -201,23 +204,3 @@ FreeBSD 3.X использует "последовательный список
Но во FreeBSD имеется проблема масштабирования, которой нет в Linux, потому что имеется ограниченное число структур `pv_entry`, и это приводит к возникновению проблем при большом объеме совместно используемых данных. В этом случае у вас может возникнуть нехватка структур `pv_entry`, даже если свободной памяти хватает. Это может быть достаточно легко исправлено увеличением количества структур `pv_entry` при настройке, но на самом деле нам нужно найти лучший способ делать это.
Что касается использования памяти под таблицу страниц против схемы с `pv_entry`: Linux использует "постоянные" таблицы страниц, которые не сбрасываются, но ему не нужны `pv_entry` для каждого потенциально отображаемого pte. FreeBSD использует "сбрасываемые" таблицы страниц, но для каждого реально отображаемого pte добавляется структура `pv_entry`. Я думаю, что использование памяти будет примерно одинакова, тем более что у FreeBSD есть алгоритмическое преимущество, заключающееся в способности сбрасывать таблицы страниц с очень малыми накладными расходами.
-
-=== Наконец, в разделе о подгонке страниц хорошо бы было иметь краткое описание того, что это значит. Я не совсем это понял.
-
-Знаете ли вы, как работает аппаратный кэш памяти L1? Объясняю: Представьте машину с 16МБ основной памяти и только со 128К памяти кэша L1. В общем, этот кэш работает так, что каждый блок по 128К основной памяти использует _те же самые_ 128К кэша. Если вы обращаетесь к основной памяти по смещению 0, а затем к основной памяти по смещению 128К, вы перезаписываете данные кэша, прочтенные по смещению 0!
-
-Я очень сильно все упрощаю. То, что я только что описал, называется "напрямую отображаемым" аппаратным кэшем памяти. Большинство современных кэшей являются так называемыми 2-сторонними множественными ассоциативными или 4-сторонними множественными ассоциативными кэшами. Множественная ассоциативность позволяет вам обращаться к вплоть до N различным областям памяти, которые используют одну и ту же память кэша без уничтожения ранее помещенных в кэш данных. Но только N.
-
-Так что если у меня имеется 4-сторонний ассоциативный кэш, я могу обратиться к памяти по смещению 0, смещению 128К, 256К и смещению 384K, затем снова обратиться к памяти по смещению 0 и получу ее из кэша L1. Однако, если после этого я обращусь к памяти по смещению 512К, один из ранее помещенных в кэш объектов данных будет из кэша удален.
-
-Это чрезвычайно важно... для большинства обращений к памяти процессора _чрезвычайно_ важно, чтобы данные находились в кэше L1, так как кэш L1 работает на тактовой частоте работы процессора. В случае, если данных в кэше L1 не обнаруживается, и они ищутся в кэше L2 или в основной памяти, процессор будет простаивать, или, скорее, сидеть, сложив ручки, в ожидании окончания чтения из основной памяти, хотя за это время можно было выполнить _сотни_ операций. Основная память (динамическое ОЗУ, которое установлено в компьютере) работает по сравнению со скоростью работы ядра современных процессоров __медленно__.
-
-Хорошо, а теперь рассмотрим подгонку страниц: Все современные кэши памяти являются так называемыми _физическими_ кэшами. Они кэшируют адреса физической памяти, а не виртуальной. Это позволяет кэшу не принимать во внимание переключение контекстов процессов, что очень важно.
-
-Но в мире UNIX(R) вы работаете с виртуальными адресными пространствами, а не с физическими. Любая программа, вами написанная, имеет дело с виртуальным адресным пространством, ей предоставленным. Реальные _физические_ страницы, соответствующие виртуальному адресному пространству, не обязательно расположены физически последовательно! На самом деле у вас могут оказаться две страницы, которые в адресном пространстве процессов являются граничащими, но располагающимися по смещению 0 и по смещению 128К в _физической_ памяти.
-
-Обычно программа полагает, что две граничащие страницы будут кэшироваться оптимально. То есть вы можете обращаться к объектам данных в обеих страницах без замещений в кэше данных друг друга. Но это имеет место, если только физические страницы, соответствующие виртуальному адресному пространству, располагаются рядом (в такой мере, что попадают в кэш).
-
-Это именно то, что выполняет подгонка. Вместо того, чтобы назначать _случайные_ физические страницы виртуальным адресам, что может привести к неоптимальной работе кэша, при подгонке страниц виртуальным адресам назначаются _примерно подходящие по порядку_ физические страницы. Таким образом, программы могут писаться в предположении, что характеристики низлежащего аппаратного кэша для виртуального адресного пространства будут такими же, как если бы программа работала непосредственно в физическом адресном пространстве.
-
-Заметьте, что я сказал "примерно" подходящие, а не просто "последовательные". С точки зрения напрямую отображаемого кэша в 128К, физический адрес 0 одинаков с физическим адресом 128К. Так что две граничащие страницы в вашем виртуальном адресном пространстве могут располагаться по смещению 128К и 132К физической памяти, но могут легко находиться по смещению 128К и по смещению 4К физической памяти, и иметь те же самые характеристики работы кэша. Так что при подгонке _не нужно_ назначать в действительности последовательные страницы физической памяти последовательным страницам виртуальной памяти, достаточно просто добиться расположения страниц по соседству друг с другом с точки зрения работы кэша.
diff --git a/documentation/content/ru/articles/vm-design/_index.po b/documentation/content/ru/articles/vm-design/_index.po
new file mode 100644
index 0000000000..8dda5aa52d
--- /dev/null
+++ b/documentation/content/ru/articles/vm-design/_index.po
@@ -0,0 +1,1356 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:25+0300\n"
+"PO-Revision-Date: 2025-07-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/articlesvm-design_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/articles/vm-design/_index.adoc:1
+#, no-wrap
+msgid "An easy to follow description of the design of the FreeBSD virtual memory system"
+msgstr "Простое и понятное описание архитектуры системы виртуальной памяти FreeBSD"
+
+#. type: Title =
+#: documentation/content/en/articles/vm-design/_index.adoc:1
+#: documentation/content/en/articles/vm-design/_index.adoc:11
+#, no-wrap
+msgid "Design elements of the FreeBSD VM system"
+msgstr "Элементы архитектуры системы виртуальной памяти во FreeBSD"
+
+#. type: delimited block = 4
+#: documentation/content/en/articles/vm-design/_index.adoc:46
+msgid ""
+"This document is outdated and some sections do not accurately describe the "
+"current state of the VM system. It is retained for historical purposes and "
+"may be updated over time."
+msgstr ""
+"Этот документ устарел, и некоторые разделы больше не соответствуют текущему "
+"состоянию системы виртуальной памяти. Он сохранён в исторических целях и "
+"может быть обновлён в будущем."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:50
+msgid "Abstract"
+msgstr "Аннотация"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:52
+msgid "Matthew Dillon <dillon@apollo.backplane.com>"
+msgstr "Matthew Dillon <dillon@apollo.backplane.com>"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:59
+msgid ""
+"The title is really just a fancy way of saying that I am going to attempt to "
+"describe the whole VM enchilada, hopefully in a way that everyone can "
+"follow. For the last year I have concentrated on a number of major kernel "
+"subsystems within FreeBSD, with the VM and Swap subsystems being the most "
+"interesting and NFS being \"a necessary chore\". I rewrote only small "
+"portions of the code. In the VM arena the only major rewrite I have done is "
+"to the swap subsystem. Most of my work was cleanup and maintenance, with "
+"only moderate code rewriting and no major algorithmic adjustments within the "
+"VM subsystem. The bulk of the VM subsystem's theoretical base remains "
+"unchanged and a lot of the credit for the modernization effort in the last "
+"few years belongs to John Dyson and David Greenman. Not being a historian "
+"like Kirk I will not attempt to tag all the various features with peoples "
+"names, since I will invariably get it wrong."
+msgstr ""
+"Это название — просто замысловатый способ сказать, что я попытаюсь описать "
+"всю систему виртуальной памяти (VM) целиком, по возможности так, чтобы это "
+"было понятно каждому.В течение последнего года я сосредоточился на "
+"нескольких основных подсистемах ядра FreeBSD. Наиболее интересными из них "
+"стали подсистемы VM и подкачки (Swap), тогда как работа с NFS оказалась, "
+"скорее, «необходимой рутиной». Я переписал лишь небольшие части кода. В "
+"области VM моей единственной крупной переработкой стала подсистема подкачки. "
+"В основном моя работа заключалась в очистке и поддержке кода, с умеренными "
+"правками и без серьёзных изменений алгоритмов в подсистеме VM. Теоретическая "
+"основа VM-подсистемы осталась неизменной, и львиная доля заслуг в её "
+"модернизации за последние годы принадлежит Джону Дайсону и Дэвиду Гринману. "
+"Я не историк, в отличие от Кирка, поэтому не стану приписывать различные "
+"функции конкретным людям — всё равно где-нибудь ошибусь."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:61
+msgid "'''"
+msgstr "'''"
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:65
+#, no-wrap
+msgid "Introduction"
+msgstr "Введение"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:81
+msgid ""
+"Before moving along to the actual design let's spend a little time on the "
+"necessity of maintaining and modernizing any long-living codebase. In the "
+"programming world, algorithms tend to be more important than code and it is "
+"precisely due to BSD's academic roots that a great deal of attention was "
+"paid to algorithm design from the beginning. More attention paid to the "
+"design generally leads to a clean and flexible codebase that can be fairly "
+"easily modified, extended, or replaced over time. While BSD is considered "
+"an \"old\" operating system by some people, those of us who work on it tend "
+"to view it more as a \"mature\" codebase which has various components "
+"modified, extended, or replaced with modern code. It has evolved, and "
+"FreeBSD is at the bleeding edge no matter how old some of the code might "
+"be. This is an important distinction to make and one that is unfortunately "
+"lost to many people. The biggest error a programmer can make is to not "
+"learn from history, and this is precisely the error that many other modern "
+"operating systems have made. Windows NT(R) is the best example of this, and "
+"the consequences have been dire. Linux also makes this mistake to some "
+"degree-enough that we BSD folk can make small jokes about it every once in a "
+"while, anyway. Linux's problem is simply one of a lack of experience and "
+"history to compare ideas against, a problem that is easily and rapidly being "
+"addressed by the Linux community in the same way it has been addressed in "
+"the BSD community-by continuous code development. The Windows NT(R) folk, "
+"on the other hand, repeatedly make the same mistakes solved by UNIX(R) "
+"decades ago and then spend years fixing them. Over and over again. They "
+"have a severe case of \"not designed here\" and \"we are always right "
+"because our marketing department says so\". I have little tolerance for "
+"anyone who cannot learn from history."
+msgstr ""
+"Перед тем, как перейти непосредственно к существующей архитектуре, потратим "
+"немного времени на рассмотрение вопроса о необходимости поддержки и "
+"модернизации любого длительно живущего кода. В мире программирования "
+"алгоритмы становятся более важными, чем код, и именно из-за академических "
+"корней BSD изначально большое внимание уделялось проработке алгоритмов. "
+"Внимание, уделенное архитектуре, в общем отражается на ясности и гибкости "
+"кода, который может быть достаточно легко изменен, расширен или с течением "
+"времени заменен. Хотя некоторые считают BSD \"старой\" операционной "
+"системой, те их нас, кто работает над ней, видят ее скорее системой со "
+"\"зрелым\" кодом с различными компонентами, которые были заменены, расширены "
+"или изменены современным кодом. Он развивается, и FreeBSD остается передовой "
+"системой, вне зависимости от того, насколько старой может быть часть кода. "
+"Это важное отличие, которое, к сожалению, не всеми понимается. Самой большой "
+"ошибкой, которую может допустить программист, является игнорирование "
+"истории, и это именно та ошибка, которую сделали многие другие современные "
+"операционные системы. Самым ярки примером здесь является Windows NT(R), и "
+"последствия ужасны. Linux также в некоторой степени совершил эту ошибку-"
+"достаточно, чтобы мы, люди BSD, по крайней мере по разу отпустили по этому "
+"поводу шутку. Проблема Linux заключается просто в отсутствии опыта и истории "
+"для сравнения идей, проблема, которая легко и быстро решается сообществом "
+"Linux точно так же, как она решается в сообществе BSD-постоянной работой над "
+"кодом. Разработчики Windows NT(R), с другой стороны, постоянно совершают те "
+"же самые ошибки, что были решены в UNIX(R) десятки лет назад, а затем тратят "
+"годы на их устранение. Снова и снова. Есть несколько случаев \"проработка "
+"архитектуры отсутствует\" и \"мы всегда правы, потому что так говорит наш "
+"отдел продаж\". Я плохо переношу тех, кого не учит история."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:86
+msgid ""
+"Much of the apparent complexity of the FreeBSD design, especially in the VM/"
+"Swap subsystem, is a direct result of having to solve serious performance "
+"issues that occur under various conditions. These issues are not due to bad "
+"algorithmic design but instead rise from environmental factors. In any "
+"direct comparison between platforms, these issues become most apparent when "
+"system resources begin to get stressed. As I describe FreeBSD's VM/Swap "
+"subsystem the reader should always keep two points in mind:"
+msgstr ""
+"Большинство очевидной сложности архитектуры FreeBSD, особенно в подсистеме "
+"VM/Swap, является прямым следствием того, что она решает серьезные проблемы "
+"с производительностью, которые проявляются при различных условиях. Эти "
+"проблемы вызваны не плохой проработкой алгоритмов, а возникают из окружающих "
+"факторов. В любом прямом сравнении между платформами эти проблемы "
+"проявляются, когда системные ресурсы начинают истощаться. Так как я описываю "
+"подсистему VM/Swap во FreeBSD, то читатель должен всегда иметь в виду два "
+"обстоятельства:"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:88
+msgid ""
+"The most important aspect of performance design is what is known as "
+"\"Optimizing the Critical Path\". It is often the case that performance "
+"optimizations add a little bloat to the code to make the critical path "
+"perform better."
+msgstr ""
+"Самым важным аспектом при проектировании производительности является то, что "
+"называется \"оптимизацией критического маршрута\". Часто случается, что "
+"оптимизация производительности дает прирост объема кода ради того, чтобы "
+"критический маршрут работал быстрее."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:89
+msgid ""
+"A solid, generalized design outperforms a heavily-optimized design over the "
+"long run. While a generalized design may end up being slower than an heavily-"
+"optimized design when they are first implemented, the generalized design "
+"tends to be easier to adapt to changing conditions and the heavily-optimized "
+"design winds up having to be thrown away."
+msgstr ""
+"Четкость общей архитектуры оказывается лучше сильно оптимизированной "
+"архитектуры с течением времени. Когда как обобщенная архитектура может быть "
+"медленнее, чем оптимизированная архитектура, при первой реализации, при "
+"обобщенной архитектуре легче подстраиваться под изменяющиеся условия и "
+"чрезмерно оптимизированная архитектура оказывается непригодной."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:93
+msgid ""
+"Any codebase that will survive and be maintainable for years must therefore "
+"be designed properly from the beginning even if it costs some performance. "
+"Twenty years ago people were still arguing that programming in assembly was "
+"better than programming in a high-level language because it produced code "
+"that was ten times as fast. Today, the fallibility of that argument is "
+"obvious - as are the parallels to algorithmic design and code generalization."
+msgstr ""
+"Любой код, который должен выжить и поддаваться поддержке годы, должен "
+"поэтому быть тщательно продуман с самого начала, даже если это стоит потери "
+"производительности. Двадцать лет назад были те, кто отстаивал преимущество "
+"программирования на языке ассемблера перед программированием на языке "
+"высокого уровня, потому что первый генерировал в десять раз более быстрый "
+"код. В наши дни ошибочность этого аргумента очевидна - можно провести "
+"параллели с построением алгоритмов и обобщением кода."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:95
+#, no-wrap
+msgid "VM Objects"
+msgstr "Объекты VM"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:105
+msgid ""
+"The best way to begin describing the FreeBSD VM system is to look at it from "
+"the perspective of a user-level process. Each user process sees a single, "
+"private, contiguous VM address space containing several types of memory "
+"objects. These objects have various characteristics. Program code and "
+"program data are effectively a single memory-mapped file (the binary file "
+"being run), but program code is read-only while program data is copy-on-"
+"write. Program BSS is just memory allocated and filled with zeros on "
+"demand, called demand zero page fill. Arbitrary files can be memory-mapped "
+"into the address space as well, which is how the shared library mechanism "
+"works. Such mappings can require modifications to remain private to the "
+"process making them. The fork system call adds an entirely new dimension to "
+"the VM management problem on top of the complexity already given."
+msgstr ""
+"Лучше всего начать описание VM-системы FreeBSD с попытки взглянуть на нее с "
+"точки зрения пользовательского процесса. Каждый пользовательский процесс "
+"имеет единое, принадлежащее только ему и неразрывное адресное пространство "
+"VM, содержащее несколько типов объектов памяти. Эти объекты имеют различные "
+"характеристики. Код программы и ее данные являются единым файлом, "
+"отображаемым в память (это выполняющийся двоичный файл), однако код "
+"программы доступен только для чтения, когда как данные программы размещаются "
+"в режиме копирования-при-записи. BSS программы представляет собой всего лишь "
+"выделенную область памяти, заполненную, если это требовалось, нулями, что "
+"называется обнулением страниц памяти по требованию. Отдельные файлы могут "
+"также отображаться в адресное пространство, именно так работают динамические "
+"библиотеки. Такие отображения требуют изменений, чтобы оставаться "
+"принадлежащими процессу, который их выполнил. Системный вызов fork добавляет "
+"переводит проблему управления VM полностью в новую плоскость, вдобавок к уже "
+"имеющимся сложностям."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:111
+msgid ""
+"A program binary data page (which is a basic copy-on-write page) illustrates "
+"the complexity. A program binary contains a preinitialized data section "
+"which is initially mapped directly from the program file. When a program is "
+"loaded into a process's VM space, this area is initially memory-mapped and "
+"backed by the program binary itself, allowing the VM system to free/reuse "
+"the page and later load it back in from the binary. The moment a process "
+"modifies this data, however, the VM system must make a private copy of the "
+"page for that process. Since the private copy has been modified, the VM "
+"system may no longer free it, because there is no longer any way to restore "
+"it later on."
+msgstr ""
+"Иллюстрирует сложность страница данных двоичной программы (которая является "
+"страницей копируемой-при-записи). Двоичная программа содержит секцию "
+"предварительно инициализированных данных, которая первоначально отображается "
+"непосредственно из файла программы. Когда программа загружается в Vm-"
+"пространство процесса, эта область сначала отображается в память и "
+"поддерживается бинарным файлом программы, позволяя VM-системе освобождать/"
+"повторно использовать страницу, а потом загружать ее снова из бинарного "
+"файла. Однако в момент, когда процесс изменяет эти данные, VM-система должна "
+"сделать копию страницы, принадлежащую только этому процессу. Так как эта "
+"копия была изменена, то VM-система не может больше освобождать эту страницу, "
+"так как впоследствии ее невозможно будет восстановить."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:118
+msgid ""
+"You will notice immediately that what was originally a simple file mapping "
+"has become much more complex. Data may be modified on a page-by-page basis "
+"whereas the file mapping encompasses many pages at once. The complexity "
+"further increases when a process forks. When a process forks, the result is "
+"two processes-each with their own private address spaces, including any "
+"modifications made by the original process prior to the call to `fork()`. "
+"It would be silly for the VM system to make a complete copy of the data at "
+"the time of the `fork()` because it is quite possible that at least one of "
+"the two processes will only need to read from that page from then on, "
+"allowing the original page to continue to be used. What was a private page "
+"is made copy-on-write again, since each process (parent and child) expects "
+"their own personal post-fork modifications to remain private to themselves "
+"and not affect the other."
+msgstr ""
+"Вы тут же заметите, что то, что сначала было простым отображением файла в "
+"память, становится гораздо более сложным предметом. Данные могут "
+"модифицироваться постранично, когда как отображение файла выполняется для "
+"многих страниц за раз. Сложность еще более увеличивается, когда процесс "
+"выполняет вызов fork. При этом порождаются два процесса-каждый со с "
+"собственным адресным пространством, включающим все изменения, выполненные "
+"исходным процессом до вызова функции `fork()`. Было бы глупо для VM-системы "
+"делать полную копию данных во время вызова `fork()`, так как весьма "
+"вероятно, что один из двух процессов будет нужен только для чтения из той "
+"страницы, что позволяет использование исходной страницы. То, что было "
+"страницей, принадлежащей только процессу, сделается снова страницей, "
+"копируемой при записи, так как каждый из процессов (и родитель, и потомок) "
+"полагают, что их собственные изменения после разветвления будут принадлежать "
+"только им, и не затронут родственный процесс."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:127
+msgid ""
+"FreeBSD manages all of this with a layered VM Object model. The original "
+"binary program file winds up being the lowest VM Object layer. A copy-on-"
+"write layer is pushed on top of that to hold those pages which had to be "
+"copied from the original file. If the program modifies a data page "
+"belonging to the original file the VM system takes a fault and makes a copy "
+"of the page in the higher layer. When a process forks, additional VM Object "
+"layers are pushed on. This might make a little more sense with a fairly "
+"basic example. A `fork()` is a common operation for any *BSD system, so "
+"this example will consider a program that starts up, and forks. When the "
+"process starts, the VM system creates an object layer, let's call this A:"
+msgstr ""
+"FreeBSD управляет всем этим при помощи многоуровневой модели VM-объектов. "
+"Исходный файл с двоичной программой переносится на самый нижний уровень "
+"объектов VM. Уровень страниц, копируемых при записи, находится выше него, и "
+"хранит те страницы, которые были скопированы из исходного файла. Если "
+"программа модифицирует страницы данных, относящиеся к исходному файлу, то "
+"система VM обнаруживает это и переносит копию этой страницы на более высокий "
+"уровень. Когда процесс разветвляется, добавляются новые уровни VM-объектов. "
+"Это можно показать на простом примере. Функция `fork()` является общей "
+"операцией для всех систем *BSD, так что в этом примере будет рассматриваться "
+"программа, которая запускается, а затем разветвляется. Когда процесс "
+"запускается, VM-система создает некоторый уровень объектов, обозначим его A:"
+
+#. type: Positional ($1) AttributeList argument for macro 'image'
+#: documentation/content/en/articles/vm-design/_index.adoc:128
+#, no-wrap
+msgid "A picture"
+msgstr "Рисунок"
+
+#. type: Target for macro image
+#: documentation/content/en/articles/vm-design/_index.adoc:128
+#, no-wrap
+msgid "fig1.png"
+msgstr "fig1.png"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:133
+msgid ""
+"A represents the file-pages may be paged in and out of the file's physical "
+"media as necessary. Paging in from the disk is reasonable for a program, "
+"but we really do not want to page back out and overwrite the executable. "
+"The VM system therefore creates a second layer, B, that will be physically "
+"backed by swap space:"
+msgstr ""
+"A соответствует файлу-по необходимости страницы памяти могут высвобождаться "
+"и подгружаться с носителя файла. Подгрузка с диска может потребоваться "
+"программе, однако на самом деле мы не хотим, чтобы она записывалась обратно "
+"в файл. Поэтому VM-система создает второй уровень, B, который физически "
+"поддерживается дисковым пространством подкачки:"
+
+#. type: Target for macro image
+#: documentation/content/en/articles/vm-design/_index.adoc:134
+#, no-wrap
+msgid "fig2.png"
+msgstr "fig2.png"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:139
+msgid ""
+"On the first write to a page after this, a new page is created in B, and its "
+"contents are initialized from A. All pages in B can be paged in or out to a "
+"swap device. When the program forks, the VM system creates two new object "
+"layers-C1 for the parent, and C2 for the child-that rest on top of B:"
+msgstr ""
+"При первой записи в страницу после выполнения этой операции, в B создается "
+"новая страница, содержимое которой берется из A. Все страницы в B могут "
+"сбрасываться и считываться из устройства подкачки. Когда программа ветвится, "
+"VM-система создает два новых уровня объектов-C1 для порождающего процесса и "
+"C2 для порожденного-они располагаются поверх B:"
+
+#. type: Target for macro image
+#: documentation/content/en/articles/vm-design/_index.adoc:140
+#, no-wrap
+msgid "fig3.png"
+msgstr "fig3.png"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:151
+msgid ""
+"In this case, let's say a page in B is modified by the original parent "
+"process. The process will take a copy-on-write fault and duplicate the page "
+"in C1, leaving the original page in B untouched. Now, let's say the same "
+"page in B is modified by the child process. The process will take a copy-on-"
+"write fault and duplicate the page in C2. The original page in B is now "
+"completely hidden since both C1 and C2 have a copy and B could theoretically "
+"be destroyed if it does not represent a \"real\" file; however, this sort of "
+"optimization is not trivial to make because it is so fine-grained. FreeBSD "
+"does not make this optimization. Now, suppose (as is often the case) that "
+"the child process does an `exec()`. Its current address space is usually "
+"replaced by a new address space representing a new file. In this case, the "
+"C2 layer is destroyed:"
+msgstr ""
+"В этом случае, допустим, что страница в B была изменена начальным "
+"родительским процессом. В процессе возникнет ситуация копирования при записи "
+"и страница скопируется в C1, при этом исходная страница останется в B "
+"нетронутой. Теперь допустим, что та же самая страница в B изменяется "
+"порожденным процессом. В процессе возникнет ситуация копирования при записи "
+"и страница скопируется в C2. Исходная страница в B теперь полностью скрыта, "
+"так как и C1, и C2 имеют копии, а B теоретически может быть уничтожена, если "
+"она не представляет собой \"реального\" файла). Однако такую оптимизацию не "
+"так уж просто осуществить, потому что она делается на уровне мелких единиц. "
+"Во FreeBSD такая оптимизация не выполняется. Теперь положим (а это часто "
+"случается), что порожденный процесс выполняет вызов `exec()`. Его текущее "
+"адресное пространство обычно заменяется новым адресным пространством, "
+"представляющим новый файл. В этом случае уровень C2 уничтожается:"
+
+#. type: Target for macro image
+#: documentation/content/en/articles/vm-design/_index.adoc:152
+#, no-wrap
+msgid "fig4.png"
+msgstr "fig4.png"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:158
+msgid ""
+"In this case, the number of children of B drops to one, and all accesses to "
+"B now go through C1. This means that B and C1 can be collapsed together. "
+"Any pages in B that also exist in C1 are deleted from B during the "
+"collapse. Thus, even though the optimization in the previous step could not "
+"be made, we can recover the dead pages when either of the processes exit or "
+"`exec()`."
+msgstr ""
+"В этом случае количество потомков B становится равным одному и все обращения "
+"к B теперь выполняются через C1. Это означает, что B и C1 могут быть "
+"объединены. Все страницы в B, которые также существуют и в C1, во время "
+"объединения из B удаляются. Таким образом, хотя оптимизация на предыдущем "
+"шаге может не делаться, мы можем восстановить мертвые страницы при окончании "
+"работы процессов или при вызове `exec()`."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:165
+msgid ""
+"This model creates a number of potential problems. The first is that you "
+"can wind up with a relatively deep stack of layered VM Objects which can "
+"cost scanning time and memory when you take a fault. Deep layering can "
+"occur when processes fork and then fork again (either parent or child). The "
+"second problem is that you can wind up with dead, inaccessible pages deep in "
+"the stack of VM Objects. In our last example if both the parent and child "
+"processes modify the same page, they both get their own private copies of "
+"the page and the original page in B is no longer accessible by anyone. That "
+"page in B can be freed."
+msgstr ""
+"Такая модель создает некоторое количество потенциальных проблем. Первая, с "
+"которой вы можете столкнуться, заключается в сравнительно большой "
+"последовательности уровней объектов VM, на сканирование которых тратится "
+"время и память. Большое количество уровней может возникнуть, когда процессы "
+"разветвляются, а затем разветвляются еще раз (как порожденные, так и "
+"порождающие). Вторая проблема заключается в том, что вы можете столкнуться с "
+"мертвыми, недоступными страницами глубоко в иерархии объектов VM. В нашем "
+"последнем примере если как родитель, так и потомок изменяют одну и ту же "
+"страницу, они оба получают собственные копии страницы, а исходная страница в "
+"B становится никому не доступной. такая страница в B может быть высвобождена."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:176
+msgid ""
+"FreeBSD solves the deep layering problem with a special optimization called "
+"the \"All Shadowed Case\". This case occurs if either C1 or C2 take "
+"sufficient COW faults to completely shadow all pages in B. Lets say that C1 "
+"achieves this. C1 can now bypass B entirely, so rather then have C1->B->A "
+"and C2->B->A we now have C1->A and C2->B->A. But look what also happened-"
+"now B has only one reference (C2), so we can collapse B and C2 together. "
+"The end result is that B is deleted entirely and we have C1->A and C2->A. "
+"It is often the case that B will contain a large number of pages and neither "
+"C1 nor C2 will be able to completely overshadow it. If we fork again and "
+"create a set of D layers, however, it is much more likely that one of the D "
+"layers will eventually be able to completely overshadow the much smaller "
+"dataset represented by C1 or C2. The same optimization will work at any "
+"point in the graph and the grand result of this is that even on a heavily "
+"forked machine VM Object stacks tend to not get much deeper then 4. This is "
+"true of both the parent and the children and true whether the parent is "
+"doing the forking or whether the children cascade forks."
+msgstr ""
+"FreeBSD решает проблему с глубиной вложенности с помощью приема оптимизации, "
+"который называется \"All Shadowed Case\". Этот случай возникает, если в C1 "
+"либо C2 возникает столько случаев копирования страниц при записи, что они "
+"полностью закрывают все страницы в B. Допустим, что такое произошло в C1. C1 "
+"может теперь полностью заменить B, так что вместо цепочек C1->B->A и C2->B-"
+">A мы теперь имеем цепочки C1->A и C2->B->A. Но посмотрите, что получается-"
+"теперь B имеет только одну ссылку (C2), так что мы можем объединить B и C2. "
+"В конечном итоге B будет полностью удален и мы имеем цепочки C1->A и C2->A. "
+"Часто B будет содержать большое количество страниц, и ни C1, ни C2 не смогут "
+"полностью их заменить. Если мы снова породим процесс и создадим набор "
+"уровней D, при этом, однако, более вероятно, что один из уровней D "
+"постепенно сможет полностью заместить гораздо меньший набор данных, "
+"представленный C1 и C2. Та же самая оптимизация будет работать в любой точке "
+"графа и главным результатом этого является то, что даже на сильно "
+"загруженной машине с множеством порождаемых процессов стеки объектов VM не "
+"часто бывают глубже четырех уровней. Это так как для порождающего, так и для "
+"порожденного процессов, и остается в силе как в случае, когда ветвление "
+"делает родитель, так и в случае, когда ветвление выполняет потомок."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:180
+msgid ""
+"The dead page problem still exists in the case where C1 or C2 do not "
+"completely overshadow B. Due to our other optimizations this case does not "
+"represent much of a problem and we simply allow the pages to be dead. If "
+"the system runs low on memory it will swap them out, eating a little swap, "
+"but that is it."
+msgstr ""
+"Проблема с мертвой страницей все еще имеет место, когда C1 или C2 не "
+"полностью перекрывают B. Из-за других применяемых нами методов оптимизации "
+"этот случай не представляет большой проблемы и мы просто позволяем таким "
+"страницам существовать. Если система испытывает нехватку оперативной памяти, "
+"она выполняет их выгрузку в область подкачки, что занимает некоторое "
+"пространство в области подкачки, но это все."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:184
+msgid ""
+"The advantage to the VM Object model is that `fork()` is extremely fast, "
+"since no real data copying need take place. The disadvantage is that you "
+"can build a relatively complex VM Object layering that slows page fault "
+"handling down a little, and you spend memory managing the VM Object "
+"structures. The optimizations FreeBSD makes proves to reduce the problems "
+"enough that they can be ignored, leaving no real disadvantage."
+msgstr ""
+"Преимущество модели VM-объектов заключается в очень быстром выполнении "
+"функции `fork()`, так как при этом не выполняется реального копирования "
+"данных. Минусом этого подхода является то, что вы можете построить "
+"сравнительно сложную иерархию объектов VM, которая несколько замедляет "
+"обработку ситуаций отсутствия страниц памяти, и к тому же тратится память на "
+"управление структурами объектов VM. Приемы оптимизации, применяемые во "
+"FreeBSD, позволяют снизить значимость этих проблем до степени, когда их "
+"можно без особых потерь игнорировать."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:186
+#, no-wrap
+msgid "SWAP Layers"
+msgstr "Уровни области подкачки"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:194
+msgid ""
+"Private data pages are initially either copy-on-write or zero-fill pages. "
+"When a change, and therefore a copy, is made, the original backing object "
+"(usually a file) can no longer be used to save a copy of the page when the "
+"VM system needs to reuse it for other purposes. This is where SWAP comes "
+"in. SWAP is allocated to create backing store for memory that does not "
+"otherwise have it. FreeBSD allocates the swap management structure for a VM "
+"Object only when it is actually needed. However, the swap management "
+"structure has had problems historically:"
+msgstr ""
+"Страницы с собственными данными первоначально являются страницами, "
+"копируемыми при записи или заполняемыми нулями. Когда выполняется изменение, "
+"и, соответственно, копирование, начальное хранилище объекта (обычно файл) не "
+"может больше использоваться для хранения копии страницы, когда VM-системе "
+"нужно использовать ее повторно для других целей. В этот момент на помощь "
+"приходит область подкачки. Область подкачки выделяется для организации "
+"хранилища памяти, которая иначе не может быть доступна. FreeBSD создает "
+"структуру управления подкачкой для объекта VM, только когда это "
+"действительно нужно. Однако структура управления подкачкой исторически имела "
+"некоторые проблемы:"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:196
+msgid ""
+"Under FreeBSD 3.X the swap management structure preallocates an array that "
+"encompasses the entire object requiring swap backing store-even if only a "
+"few pages of that object are swap-backed. This creates a kernel memory "
+"fragmentation problem when large objects are mapped, or processes with large "
+"runsizes (RSS) fork."
+msgstr ""
+"Во FreeBSD 3.X в структуре управления областью подкачки предварительно "
+"выделяется массив, который представляет целый объект, требующий хранения в "
+"области подкачки-даже если только несколько страниц этого объекта хранятся в "
+"области подкачки. Это создает проблему фрагментации памяти ядра в случае, "
+"когда в память отображаются большие объекты или когда ветвятся процессы, "
+"занимающие большой объем памяти при работе (RSS)."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:197
+msgid ""
+"Also, to keep track of swap space, a \"list of holes\" is kept in kernel "
+"memory, and this tends to get severely fragmented as well. Since the \"list "
+"of holes\" is a linear list, the swap allocation and freeing performance is "
+"a non-optimal O(n)-per-page."
+msgstr ""
+"Также для отслеживания памяти подкачки в памяти ядра поддерживается \"список "
+"дыр\", и он также несколько фрагментирован. Так как \"список дыр\" является "
+"последовательным списком, то производительность при распределении и "
+"высвобождении памяти в области подкачки неоптимально и ее сложность зависит "
+"от количества страниц как O(n)."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:198
+msgid ""
+"It requires kernel memory allocations to take place during the swap freeing "
+"process, and that creates low memory deadlock problems."
+msgstr ""
+"Также в процессе высвобождения памяти в области подкачки требуется выделение "
+"памяти в ядре, и это приводит к проблемам блокировки при недостатке памяти."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:199
+msgid ""
+"The problem is further exacerbated by holes created due to the interleaving "
+"algorithm."
+msgstr ""
+"Проблема еще более обостряется из-за дыр, создаваемых по чередующемуся "
+"алгоритму."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:200
+msgid ""
+"Also, the swap block map can become fragmented fairly easily resulting in "
+"non-contiguous allocations."
+msgstr ""
+"Кроме того, список распределения блоков в области подкачки легко оказывается "
+"фрагментированным, что приводит к распределению непоследовательных областей."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:201
+msgid ""
+"Kernel memory must also be allocated on the fly for additional swap "
+"management structures when a swapout occurs."
+msgstr ""
+"Память ядра также должна распределяться по ходу работы для дополнительных "
+"структур по управлению областью подкачки при выгрузке страниц памяти в эту "
+"область."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:204
+msgid ""
+"It is evident from that list that there was plenty of room for improvement. "
+"For FreeBSD 4.X, I completely rewrote the swap subsystem:"
+msgstr ""
+"Очевидно, что мест для усовершенствований предостаточно. Во FreeBSD 4.X "
+"подсистема управления областью подкачки была полностью переписана мною:"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:206
+msgid ""
+"Swap management structures are allocated through a hash table rather than a "
+"linear array giving them a fixed allocation size and much finer granularity."
+msgstr ""
+"Структуры управления областью подкачки распределяются при помощи хэш-"
+"таблицы, а не через линейный массив, что дает им фиксированный размер при "
+"распределении и работу с гораздо меньшими структурами."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:207
+msgid ""
+"Rather then using a linearly linked list to keep track of swap space "
+"reservations, it now uses a bitmap of swap blocks arranged in a radix tree "
+"structure with free-space hinting in the radix node structures. This "
+"effectively makes swap allocation and freeing an O(1) operation."
+msgstr ""
+"Вместо того, чтобы использовать однонаправленный связный список для "
+"отслеживания выделения пространства в области подкачки, теперь используется "
+"побитовая карта блоков области подкачки, выполненная в основном в виде "
+"древовидной структуры с информацией о свободном пространстве, находящейся в "
+"узлах структур. Это приводит к тому, что выделение и высвобождение памяти в "
+"области подкачки становится операцией сложности O(1)."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:208
+msgid ""
+"The entire radix tree bitmap is also preallocated to avoid having to "
+"allocate kernel memory during critical low memory swapping operations. After "
+"all, the system tends to swap when it is low on memory so we should avoid "
+"allocating kernel memory at such times to avoid potential deadlocks."
+msgstr ""
+"Все дерево также распределяется заранее для того, чтобы избежать "
+"распределения памяти ядра во время операций с областью подкачки при "
+"критически малом объеме свободной памяти. В конце концов, система обращается "
+"к области подкачки при нехватке памяти, так что мы должны избежать "
+"распределения памяти ядра в такие моменты для избежания потенциальных "
+"блокировок."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:209
+msgid ""
+"To reduce fragmentation the radix tree is capable of allocating large "
+"contiguous chunks at once, skipping over smaller fragmented chunks."
+msgstr ""
+"Для уменьшения фрагментации дерево может распределять большой "
+"последовательный кусок за раз, пропуская меньшие фрагментированные области."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:211
+msgid ""
+"I did not take the final step of having an \"allocating hint pointer\" that "
+"would trundle through a portion of swap as allocations were made to further "
+"guarantee contiguous allocations or at least locality of reference, but I "
+"ensured that such an addition could be made."
+msgstr ""
+"Я не сделал последний шаг к заведению \"указателя на распределение\", "
+"который будет передвигаться по участку области подкачки при выделении памяти "
+"для обеспечения в будущем распределения последовательных участков, или по "
+"крайней мере местоположения ссылки, но я убежден, что это может быть сделано."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:213
+#, no-wrap
+msgid "When to free a page"
+msgstr "Когда освобождать страницу"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:218
+msgid ""
+"Since the VM system uses all available memory for disk caching, there are "
+"usually very few truly-free pages. The VM system depends on being able to "
+"properly choose pages which are not in use to reuse for new allocations. "
+"Selecting the optimal pages to free is possibly the single-most important "
+"function any VM system can perform because if it makes a poor selection, the "
+"VM system may be forced to unnecessarily retrieve pages from disk, seriously "
+"degrading system performance."
+msgstr ""
+"Так как система VM использует всю доступную память для кэширования диска, то "
+"обычно действительно незанятых страниц очень мало. Система VM зависит от "
+"того, как она точно выбирает незанятые страницы для повторного использования "
+"для новых распределений. Оптимальный выбор страниц для высвобождения, "
+"возможно, является самой важной функцией любой VM-системы, из тех, что она "
+"может выполнять, потому что при неправильном выборе система VM вынуждена "
+"будет запрашивать страницы с диска, значительно снижая производительность "
+"всей системы."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:221
+msgid ""
+"How much overhead are we willing to suffer in the critical path to avoid "
+"freeing the wrong page? Each wrong choice we make will cost us hundreds of "
+"thousands of CPU cycles and a noticeable stall of the affected processes, so "
+"we are willing to endure a significant amount of overhead to be sure that "
+"the right page is chosen. This is why FreeBSD tends to outperform other "
+"systems when memory resources become stressed."
+msgstr ""
+"Какую дополнительную нагрузку мы может выделить в критическом пути для "
+"избежания высвобождения не той страницы? Каждый неправильный выбор будет "
+"стоить нам сотни тысяч тактов работы центрального процессора и заметное "
+"замедление работы затронутых процессов, так что мы должны смириться со "
+"значительными издержками для того, чтобы была заведомо выбрана правильная "
+"страница. Вот почему FreeBSD превосходит другие системы в производительности "
+"при нехватке ресурсов памяти."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:224
+msgid ""
+"The free page determination algorithm is built upon a history of the use of "
+"memory pages. To acquire this history, the system takes advantage of a page-"
+"used bit feature that most hardware page tables have."
+msgstr ""
+"Алгоритм определения свободной страницы написан на основе истории "
+"использования страниц памяти. Для получения этой истории система использует "
+"возможности бита использования памяти, которые имеются в большинстве "
+"аппаратных таблицах страниц памяти."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:230
+msgid ""
+"In any case, the page-used bit is cleared and at some later point the VM "
+"system comes across the page again and sees that the page-used bit has been "
+"set. This indicates that the page is still being actively used. If the bit "
+"is still clear it is an indication that the page is not being actively "
+"used. By testing this bit periodically, a use history (in the form of a "
+"counter) for the physical page is developed. When the VM system later needs "
+"to free up some pages, checking this history becomes the cornerstone of "
+"determining the best candidate page to reuse."
+msgstr ""
+"В любом случае, бит использования страницы очищается, и в некоторый более "
+"поздний момент VM-система обращается к странице снова и обнаруживает, что "
+"этот бит установлен. Это указывает на то, что страница активно используется. "
+"Периодически проверяя этот бит, накапливается история использования (в виде "
+"счетчика) физической страницы. Когда позже VM-системе требуется высвободить "
+"некоторые страницы, проверка истории выступает указателем при определении "
+"наиболее вероятной кандидатуры для повторного использования."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:235
+msgid ""
+"For those platforms that do not have this feature, the system actually "
+"emulates a page-used bit. It unmaps or protects a page, forcing a page "
+"fault if the page is accessed again. When the page fault is taken, the "
+"system simply marks the page as having been used and unprotects the page so "
+"that it may be used. While taking such page faults just to determine if a "
+"page is being used appears to be an expensive proposition, it is much less "
+"expensive than reusing the page for some other purpose only to find that a "
+"process needs it back and then have to go to disk."
+msgstr ""
+"Для тех платформ, что не имеют этой возможности, система эмулирует этот бит. "
+"Она снимает отображение или защищает страницу, что приводит к ошибке доступа "
+"к странице, если к странице выполняется повторное обращение. При "
+"возникновении этой ошибки система просто помечает страницу как используемую "
+"и снимает защиту со страницы, так что она может использоваться. Хотя "
+"использование такого приема только для определения использования страницы "
+"весьма накладно, это выгоднее, чем повторно использовать страницу для других "
+"целей и обнаружить, что она снова нужна процессу и подгружать ее с диска."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:245
+msgid ""
+"FreeBSD makes use of several page queues to further refine the selection of "
+"pages to reuse as well as to determine when dirty pages must be flushed to "
+"their backing store. Since page tables are dynamic entities under FreeBSD, "
+"it costs virtually nothing to unmap a page from the address space of any "
+"processes using it. When a page candidate has been chosen based on the page-"
+"use counter, this is precisely what is done. The system must make a "
+"distinction between clean pages which can theoretically be freed up at any "
+"time, and dirty pages which must first be written to their backing store "
+"before being reusable. When a page candidate has been found it is moved to "
+"the inactive queue if it is dirty, or the cache queue if it is clean. A "
+"separate algorithm based on the dirty-to-clean page ratio determines when "
+"dirty pages in the inactive queue must be flushed to disk. Once this is "
+"accomplished, the flushed pages are moved from the inactive queue to the "
+"cache queue. At this point, pages in the cache queue can still be "
+"reactivated by a VM fault at relatively low cost. However, pages in the "
+"cache queue are considered to be \"immediately freeable\" and will be reused "
+"in an LRU (least-recently used) fashion when the system needs to allocate "
+"new memory."
+msgstr ""
+"FreeBSD использует несколько очередей страниц для обновления выбора страниц "
+"для повторного использования, а также для определения того, когда же грязные "
+"страницы должны быть сброшены в хранилище. Так как таблицы страниц во "
+"FreeBSD являются динамическими объектами, практически ничего не стоит "
+"вырезать страницу из адресного пространства любого использующего ее "
+"процесса. После того, как подходящая страница, на основе счетчика "
+"использования, выбрана, именно это и выполняется. Система должна отличать "
+"между чистыми страницами, которые теоретически могут быть высвобождены в "
+"любое время, и грязными страницами, которые сначала должны быть переписаны в "
+"хранилище перед тем, как их можно будет использовать повторно. После "
+"нахождения подходящей страницы она перемещается в неактивную очередь, если "
+"она является грязной, или в очередь кэша, если она чистая. Отдельный "
+"алгоритм, основывающийся на отношении количества грязных страниц к чистым, "
+"определяет, когда грязные страницы в неактивной очереди должны быть сброшены "
+"на диск. Когда это выполнится, сброшенные страницы перемещаются из "
+"неактивной очереди в очередь кэша. В этот момент страницы в очереди кэша "
+"могут быть повторно активизированы VM со сравнительно малыми накладными "
+"расходами. Однако страницы в очереди кэша предполагается \"высвобождать "
+"немедленно\" и повторно использовать в LRU-порядке (меньше всего "
+"используемый), когда системе потребуется выделение дополнительной памяти."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:249
+msgid ""
+"It is important to note that the FreeBSD VM system attempts to separate "
+"clean and dirty pages for the express reason of avoiding unnecessary flushes "
+"of dirty pages (which eats I/O bandwidth), nor does it move pages between "
+"the various page queues gratuitously when the memory subsystem is not being "
+"stressed. This is why you will see some systems with very low cache queue "
+"counts and high active queue counts when doing a `systat -vm` command. As "
+"the VM system becomes more stressed, it makes a greater effort to maintain "
+"the various page queues at the levels determined to be the most effective."
+msgstr ""
+"Стоит отметить, что во FreeBSD VM-система пытается разделить чистые и "
+"грязные страницы во избежание срочной необходимости в ненужных сбросах "
+"грязных страниц (что отражается на пропускной способности ввода/вывода) и не "
+"перемещает беспричинно страницы между разными очередями, когда подсистема "
+"управления памятью не испытывает нехватку ресурсов. Вот почему вы можете "
+"видеть, что при выполнении команды `systat -vm` в некоторых системах "
+"значение счетчика очереди кэша мало, а счетчик активной очереди большой. При "
+"повышении нагрузки на VM-систему она прилагает большие усилия на поддержку "
+"различных очередей страниц в соотношениях, которые являются наиболее "
+"эффективными."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:253
+msgid ""
+"An urban myth has circulated for years that Linux did a better job avoiding "
+"swapouts than FreeBSD, but this in fact is not true. What was actually "
+"occurring was that FreeBSD was proactively paging out unused pages to make "
+"room for more disk cache while Linux was keeping unused pages in core and "
+"leaving less memory available for cache and process pages. I do not know "
+"whether this is still true today."
+msgstr ""
+"Годами ходили современные легенды, что Linux выполняет работу по "
+"предотвращению выгрузки на диск лучше, чем FreeBSD, но это не так. На самом "
+"деле FreeBSD старается сбросить на диск неиспользуемые страницы для "
+"освобождения места под дисковый кэш, когда как Linux хранит неиспользуемые "
+"страницы в памяти и оставляет под кэш и страницы процессов меньше памяти. Я "
+"не знаю, остается ли это правдой на сегодняшний день."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:255
+#, no-wrap
+msgid "Pre-Faulting and Zeroing Optimizations"
+msgstr "Оптимизация ошибок доступа к страницам и их обнуления"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:265
+msgid ""
+"Taking a VM fault is not expensive if the underlying page is already in core "
+"and can simply be mapped into the process, but it can become expensive if "
+"you take a whole lot of them on a regular basis. A good example of this is "
+"running a program such as man:ls[1] or man:ps[1] over and over again. If "
+"the program binary is mapped into memory but not mapped into the page table, "
+"then all the pages that will be accessed by the program will have to be "
+"faulted in every time the program is run. This is unnecessary when the "
+"pages in question are already in the VM Cache, so FreeBSD will attempt to "
+"pre-populate a process's page tables with those pages that are already in "
+"the VM Cache. One thing that FreeBSD does not yet do is pre-copy-on-write "
+"certain pages on exec. For example, if you run the man:ls[1] program while "
+"running `vmstat 1` you will notice that it always takes a certain number of "
+"page faults, even when you run it over and over again. These are zero-fill "
+"faults, not program code faults (which were pre-faulted in already). Pre-"
+"copying pages on exec or fork is an area that could use more study."
+msgstr ""
+"Полагая, что ошибка доступа к странице памяти в VM не является операцией с "
+"большими накладными расходами, если страница уже находится в основной памяти "
+"и может быть просто отображена в адресное пространство процесса, может "
+"оказаться, что это станет весьма накладно, если их будет оказываться "
+"регулярно много. Хорошим примером этой ситуации является запуск таких "
+"программ, как man:ls[1] или man:ps[1], снова и снова. Если бинарный файл "
+"программы отображен в память, но не отображен в таблицу страниц, то все "
+"страницы, к которым обращалась программа, окажутся недоступными при каждом "
+"запуске программы. Это не так уж необходимо, если эти страницы уже "
+"присутствуют в кэше VM, так что FreeBSD будет пытаться восстанавливать "
+"таблицы страниц процесса из тех страниц, что уже располагаются в VM-кэше. "
+"Однако во FreeBSD пока не выполняется предварительное копирование при записи "
+"определенных страниц при выполнении вызова exec. Например, если вы "
+"запускаете программу man:ls[1] одновременно с работающей `vmstat 1`, то "
+"заметите, что она всегда выдает некоторое количество ошибок доступа к "
+"страницам, даже когда вы запускаете ее снова и снова. Это ошибки заполнения "
+"нулями, а не ошибки кода программы (которые уже были обработаны). "
+"Предварительное копирование страниц при выполнении вызовов exec или fork "
+"находятся в области, требующей более тщательного изучения."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:274
+msgid ""
+"A large percentage of page faults that occur are zero-fill faults. You can "
+"usually see this by observing the `vmstat -s` output. These occur when a "
+"process accesses pages in its BSS area. The BSS area is expected to be "
+"initially zero but the VM system does not bother to allocate any memory at "
+"all until the process actually accesses it. When a fault occurs the VM "
+"system must not only allocate a new page, it must zero it as well. To "
+"optimize the zeroing operation the VM system has the ability to pre-zero "
+"pages and mark them as such, and to request pre-zeroed pages when zero-fill "
+"faults occur. The pre-zeroing occurs whenever the CPU is idle but the "
+"number of pages the system pre-zeros is limited to avoid blowing away the "
+"memory caches. This is an excellent example of adding complexity to the VM "
+"system to optimize the critical path."
+msgstr ""
+"Большой процент ошибок доступа к страницам, относится к ошибкам при "
+"заполнении нулями. Вы можете обычно видеть это, просматривая вывод команды "
+"`vmstat -s`. Это происходит, когда процесс обращается к страницам в своей "
+"области BSS. Область BSS предполагается изначально заполненной нулями, но VM-"
+"система не заботится о выделении памяти до тех пор, пока процесс реально к "
+"ней не обратится. При возникновении ошибки VM-система должна не только "
+"выделить новую страницу, но и заполнить ее нулями. Для оптимизации операции "
+"по заполнению нулями в системе VM имеется возможность предварительно "
+"обнулять страницы и помечать их, и запрашивать уже обнуленные страницы при "
+"возникновении ошибок заполнения нулями. Предварительное заполнение нулями "
+"происходит, когда CPU простаивает, однако количество страниц, которые "
+"система заранее заполняет нулями, ограничено, для того, чтобы не переполнить "
+"кэши памяти. Это прекрасный пример добавления сложности в VM-систему ради "
+"оптимизации критического пути."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:276
+#, no-wrap
+msgid "Page Table Optimizations"
+msgstr "Оптимизация таблицы страниц"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:286
+msgid ""
+"The page table optimizations make up the most contentious part of the "
+"FreeBSD VM design and they have shown some strain with the advent of serious "
+"use of `mmap()`. I think this is actually a feature of most BSDs though I "
+"am not sure when it was first introduced. There are two major "
+"optimizations. The first is that hardware page tables do not contain "
+"persistent state but instead can be thrown away at any time with only a "
+"minor amount of management overhead. The second is that every active page "
+"table entry in the system has a governing `pv_entry` structure which is tied "
+"into the `vm_page` structure. FreeBSD can simply iterate through those "
+"mappings that are known to exist while Linux must check all page tables that "
+"_might_ contain a specific mapping to see if it does, which can achieve "
+"O(n^2) overhead in certain situations. It is because of this that FreeBSD "
+"tends to make better choices on which pages to reuse or swap when memory is "
+"stressed, giving it better performance under load. However, FreeBSD "
+"requires kernel tuning to accommodate large-shared-address-space situations "
+"such as those that can occur in a news system because it may run out of "
+"`pv_entry` structures."
+msgstr ""
+"Оптимизация таблицы страниц составляет самую содержательную часть "
+"архитектуры VM во FreeBSD и она проявляется при появлении нагрузки при "
+"значительном использовании `mmap()`. Я думаю, что это на самом деле "
+"особенность работы большинства BSD-систем, хотя я не уверен, когда это "
+"проявилось впервые. Есть два основных подхода к оптимизации. Первый "
+"заключается в том, что аппаратные таблицы страниц не содержат постоянного "
+"состояния, а вместо этого могут быть сброшены в любой момент с малыми "
+"накладными расходами. Второй подход состоит в том, что каждая активная "
+"таблица страниц в системе имеет управляющую структуру `pv_entry`, которая "
+"связана в структуру `vm_page`. FreeBSD может просто просматривать эти "
+"отображения, которые существуют, когда как в Linux должны проверяться все "
+"таблицы страниц, которые _могут_ содержать нужное отображение, что в "
+"некоторых ситуация дает увеличение сложности O(n^2). Из-за того, что FreeBSD "
+"стремится выбрать наиболее подходящую к повторному использованию или сбросу "
+"в область подкачки страницу, когда ощущается нехватка памяти, система дает "
+"лучшую производительность при нагрузке. Однако во FreeBSD требуется тонкая "
+"настройка ядра для соответствия ситуациям с большим совместно используемым "
+"адресным пространством, которые могут случиться в системе, обслуживающей "
+"сервер телеконференций, потому что структуры `pv_entry` могут оказаться "
+"исчерпанными."
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:291
+msgid ""
+"Both Linux and FreeBSD need work in this area. FreeBSD is trying to "
+"maximize the advantage of a potentially sparse active-mapping model (not all "
+"processes need to map all pages of a shared library, for example), whereas "
+"Linux is trying to simplify its algorithms. FreeBSD generally has the "
+"performance advantage here at the cost of wasting a little extra memory, but "
+"FreeBSD breaks down in the case where a large file is massively shared "
+"across hundreds of processes. Linux, on the other hand, breaks down in the "
+"case where many processes are sparsely-mapping the same shared library and "
+"also runs non-optimally when trying to determine whether a page can be "
+"reused or not."
+msgstr ""
+"И в Linux, и во FreeBSD требуются доработки в этой области. FreeBSD пытается "
+"максимизировать преимущества от потенциально редко применяемой модели "
+"активного отображения (к примеру, не всем процессам нужно отображать все "
+"страницы динамической библиотеки), когда как Linux пытается упростить свои "
+"алгоритмы. FreeBSD имеет здесь общее преимущество в производительности за "
+"счет использования дополнительной памяти, но FreeBSD выглядит хуже в случае, "
+"когда большой файл совместно используется сотнями процессов. Linux, с другой "
+"стороны, выглядит хуже в случае, когда много процессов частично используют "
+"одну и ту же динамическую библиотеку, а также работает неоптимально при "
+"попытке определить, может ли страница повторно использоваться, или нет."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:293
+#, no-wrap
+msgid "Conclusion"
+msgstr "Заключение"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:298
+msgid ""
+"Virtual memory in modern operating systems must address a number of "
+"different issues efficiently and for many different usage patterns. The "
+"modular and algorithmic approach that BSD has historically taken allows us "
+"to study and understand the current implementation as well as relatively "
+"cleanly replace large sections of the code. There have been a number of "
+"improvements to the FreeBSD VM system in the last several years, and work is "
+"ongoing."
+msgstr ""
+"Виртуальная память в современных операционных системах должна решать "
+"несколько различных задач эффективно и при разных условиях. Модульный и "
+"алгоритмический подход, которому исторически следует BSD, позволяет нам "
+"изучить и понять существующую реализацию, а также сравнительно легко "
+"изменить большие блоки кода. За несколько последних лет в VM-системе FreeBSD "
+"было сделано некоторое количество усовершенствований, и работа над ними "
+"продолжается."
+
+#. type: Title ==
+#: documentation/content/en/articles/vm-design/_index.adoc:300
+#, no-wrap
+msgid "Bonus QA session by Allen Briggs"
+msgstr "Дополнительный сеанс вопросов и ответов от Аллена Бриггса (Allen Briggs)"
+
+#. type: Title ===
+#: documentation/content/en/articles/vm-design/_index.adoc:302
+#, no-wrap
+msgid "What is the interleaving algorithm that you refer to in your listing of the ills of the FreeBSD 3.X swap arrangements?"
+msgstr "Что это за алгоритм чередования, который вы упоминали в списке недостатков подсистемы управления разделом подкачки во FreeBSD 3.X?"
+
+#. type: .abstract-title
+#: documentation/content/en/articles/vm-design/_index.adoc:308
+msgid ""
+"FreeBSD uses a fixed swap interleave which defaults to 4. This means that "
+"FreeBSD reserves space for four swap areas even if you only have one, two, "
+"or three. Since swap is interleaved the linear address space representing "
+"the \"four swap areas\" will be fragmented if you do not actually have four "
+"swap areas. For example, if you have two swap areas A and B FreeBSD's "
+"address space representation for that swap area will be interleaved in "
+"blocks of 16 pages:"
+msgstr ""
+"FreeBSD использует в области подкачки механизм чередования, с индексом по "
+"умолчанию, равным четырем. Это означает, что FreeBSD резервирует "
+"пространство для четырех областей подкачки, даже если у вас имеется всего "
+"лишь одна, две или три области. Так как в области подкачки имеется "
+"чередование, то линейное адресное пространство, представляющее \"четыре "
+"области подкачки\", будет фрагментироваться, если у вас нет на самом деле "
+"четырех областей подкачки. Например, если у вас две области A и B, то "
+"представление адресного пространства для этой области подкачки во FreeBSD "
+"будет организовано с чередованием блоков из 16 страниц:"
+
+#. type: delimited block . 4
+#: documentation/content/en/articles/vm-design/_index.adoc:311
+#, no-wrap
+msgid "A B C D A B C D A B C D A B C D\n"
+msgstr "A B C D A B C D A B C D A B C D\n"
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:318
+msgid ""
+"FreeBSD 3.X uses a \"sequential list of free regions\" approach to "
+"accounting for the free swap areas. The idea is that large blocks of free "
+"linear space can be represented with a single list node ([.filename]#kern/"
+"subr_rlist.c#). But due to the fragmentation the sequential list winds up "
+"being insanely fragmented. In the above example, completely unused swap "
+"will have A and B shown as \"free\" and C and D shown as \"all allocated\". "
+"Each A-B sequence requires a list node to account for because C and D are "
+"holes, so the list node cannot be combined with the next A-B sequence."
+msgstr ""
+"FreeBSD 3.X использует \"последовательный список свободных областей\" для "
+"управления свободными областями в разделе подкачки. Идея состоит в том, что "
+"большие последовательные блоки свободного пространства могут быть "
+"представлены при помощи узла односвязного списка ([.filename]#kern/"
+"subr_rlist.c#). Но из-за фрагментации последовательный список сам становится "
+"фрагментированным. В примере выше полностью неиспользуемое пространство в A "
+"и B будет показано как \"свободное\", а C и D как \"полностью занятое\". "
+"Каждой последовательности A-B требуется для учета узел списка, потому что C "
+"и D являются дырами, так что узел списка не может быть связан со следующей "
+"последовательностью A-B."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:320
+msgid ""
+"Why do we interleave our swap space instead of just tack swap areas onto the "
+"end and do something fancier? It is a whole lot easier to allocate linear "
+"swaths of an address space and have the result automatically be interleaved "
+"across multiple disks than it is to try to put that sophistication elsewhere."
+msgstr ""
+"Почему мы организуем чередование в области подкачки вместо того, чтобы "
+"просто объединить области подкачки в одно целое и придумать что-то более "
+"умное? Потому что гораздо легче выделять последовательные полосы адресного "
+"пространства и получать в результате автоматическое чередование между "
+"несколькими дисками, чем пытаться выдумывать сложности в другом месте."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:325
+msgid ""
+"The fragmentation causes other problems. Being a linear list under 3.X, and "
+"having such a huge amount of inherent fragmentation, allocating and freeing "
+"swap winds up being an O(N) algorithm instead of an O(1) algorithm. "
+"Combined with other factors (heavy swapping) and you start getting into "
+"O(N^2) and O(N^3) levels of overhead, which is bad. The 3.X system may also "
+"need to allocate KVM during a swap operation to create a new list node which "
+"can lead to a deadlock if the system is trying to pageout pages in a low-"
+"memory situation."
+msgstr ""
+"Фрагментация вызывает другие проблемы. Являясь последовательным списком в "
+"3.X и имея такое огромную фрагментацию, выделение и освобождение в области "
+"подкачки становится алгоритмом сложности O(N), а не O(1). Вместе с другими "
+"факторами (частое обращение к области подкачки) вы получаете сложность "
+"уровней O(N^2) и O(N^3), что плохо. В системе 3.X также может потребоваться "
+"выделение KVM во время работы с областью подкачки для создания нового узла "
+"списка, что в условии нехватки памяти может привести к блокировке, если "
+"система попытается сбросить страницы в область подкачки."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:330
+msgid ""
+"Under 4.X we do not use a sequential list. Instead we use a radix tree and "
+"bitmaps of swap blocks rather than ranged list nodes. We take the hit of "
+"preallocating all the bitmaps required for the entire swap area up front but "
+"it winds up wasting less memory due to the use of a bitmap (one bit per "
+"block) instead of a linked list of nodes. The use of a radix tree instead "
+"of a sequential list gives us nearly O(1) performance no matter how "
+"fragmented the tree becomes."
+msgstr ""
+"В 4.X мы не используем последовательный список. Вместо этого мы используем "
+"базисное дерево и битовые карты блоков области подкачки, а не ограниченный "
+"список узлов. Мы принимаем предварительное выделение всех битовых карт, "
+"требуемых для всей области подкачки, но при этом тратится меньше памяти, "
+"потому что мы используем битовые карты (один бит на блок), а не связанный "
+"список узлов. Использование базисного дерева вместо последовательного списка "
+"дает нам производительность O(1) вне зависимости от фрагментации дерева."
+
+#. type: Title ===
+#: documentation/content/en/articles/vm-design/_index.adoc:331
+#, no-wrap
+msgid "How is the separation of clean and dirty (inactive) pages related to the situation where you see low cache queue counts and high active queue counts in systat -vm? Do the systat stats roll the active and dirty pages together for the active queue count?"
+msgstr "Как разделение чистых и грязных (неактивных) страниц связано с ситуацией, когда вы видите маленький счетчик очереди кэша и большой счетчик активной очереди в выдаче команды systat -vm? Разве системная статистика не считает активные и грязные страницы вместе за счетчик активной очереди?"
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:336
+msgid ""
+"Yes, that is confusing. The relationship is \"goal\" verses \"reality\". "
+"Our goal is to separate the pages but the reality is that if we are not in a "
+"memory crunch, we do not really have to."
+msgstr ""
+"Да, это запутывает. Связь заключается в \"желаемом\" и \"действительном\". "
+"Мы желаем разделить страницы, но реальность такова, что пока у нас нет "
+"проблем с памятью, нам это на самом деле не нужно."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:338
+msgid ""
+"What this means is that FreeBSD will not try very hard to separate out dirty "
+"pages (inactive queue) from clean pages (cache queue) when the system is not "
+"being stressed, nor will it try to deactivate pages (active queue -> "
+"inactive queue) when the system is not being stressed, even if they are not "
+"being used."
+msgstr ""
+"Это означает, что FreeBSD не будет очень сильно стараться над отделением "
+"грязных страниц (неактивная очередь) от чистых страниц (очередь кэша), когда "
+"система не находится под нагрузкой, и не будет деактивировать страницы "
+"(активная очередь -> неактивная очередь), когда система не нагружена, даже "
+"если они не используются."
+
+#. type: Title ===
+#: documentation/content/en/articles/vm-design/_index.adoc:339
+#, no-wrap
+msgid "In man:ls[1] the / vmstat 1 example, would not some of the page faults be data page faults (COW from executable file to private page)? I.e., I would expect the page faults to be some zero-fill and some program data. Or are you implying that FreeBSD does do pre-COW for the program data?"
+msgstr "В примере с / vmstat 1 могут ли некоторые ошибки доступа к странице быть ошибками страниц данных (COW из выполнимого файла в приватные страницы)? То есть я полагаю, что ошибки доступа к страницам являются частично ошибками при заполнении нулями, а частично данных программы. Или вы гарантируете, что FreeBSD выполняет предварительно COW для данных программы?"
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:345
+msgid ""
+"A COW fault can be either zero-fill or program-data. The mechanism is the "
+"same either way because the backing program-data is almost certainly already "
+"in the cache. I am indeed lumping the two together. FreeBSD does not pre-"
+"COW program data or zero-fill, but it _does_ pre-map pages that exist in its "
+"cache."
+msgstr ""
+"Ошибка COW может быть ошибкой при заполнении нулями или данных программы. "
+"Механизм в любом случае один и тот же, потому что хранилище данных программы "
+"уже в кэше. Я на самом деле не рад ни тому, ни другому. FreeBSD не выполняет "
+"предварительное COW данных программы и заполнение нулями, но она _выполняет_ "
+"предварительно отображение страниц, которые имеются в ее кэше."
+
+#. type: Title ===
+#: documentation/content/en/articles/vm-design/_index.adoc:346
+#, no-wrap
+msgid "In your section on page table optimizations, can you give a little more detail about pv_entry and vm_page (or should vm_page be vm_pmap-as in 4.4, cf. pp. 180-181 of McKusick, Bostic, Karel, Quarterman)? Specifically, what kind of operation/reaction would require scanning the mappings?"
+msgstr "В вашем разделе об оптимизации таблицы страниц, не могли бы вы более подробно рассказать о pv_entry и vm_page (или vm_page должна быть vm_pmap-как в 4.4, cf. pp. 180-181 of McKusick, Bostic, Karel, Quarterman)? А именно какое действие/реакцию должно потребоваться для сканирования отображений?"
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:350
+msgid ""
+"A `vm_page` represents an (object,index#) tuple. A `pv_entry` represents a "
+"hardware page table entry (pte). If you have five processes sharing the "
+"same physical page, and three of those processes's page tables actually map "
+"the page, that page will be represented by a single `vm_page` structure and "
+"three `pv_entry` structures."
+msgstr ""
+"`vm_page` представляет собой пару (object,index#). `pv_entry` является "
+"записью из аппаратной таблицы страниц (pte). Если у вас имеется пять "
+"процессов, совместно использующих одну и ту же физическую страницу, и в трех "
+"таблицах страниц этих процессов на самом деле отображается страница, то "
+"страница будет представляться одной структурой `vm_page` и тремя структурами "
+"`pv_entry`."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:353
+msgid ""
+"`pv_entry` structures only represent pages mapped by the MMU (one `pv_entry` "
+"represents one pte). This means that when we need to remove all hardware "
+"references to a `vm_page` (to reuse the page for something else, page it "
+"out, clear it, dirty it, and so forth) we can simply scan the linked list of "
+"pv_entry's associated with that vm_page to remove or modify the pte's from "
+"their page tables."
+msgstr ""
+"Структуры `pv_entry` представляют страницы, отображаемые MMU (одна структура "
+"`pv_entry` соответствует одной pte). Это означает, что, когда нам нужно "
+"убрать все аппаратные ссылки на `vm_page` (для того, чтобы повторно "
+"использовать страницу для чего-то еще, выгрузить ее, очистить, пометить как "
+"грязную и так далее), мы можем просто просмотреть связный список структур "
+"`pv_entry`, связанных с этой `vm_page`, для того, чтобы удалить или изменить "
+"pte из их таблиц страниц."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:360
+msgid ""
+"Under Linux there is no such linked list. To remove all the hardware page "
+"table mappings for a `vm_page` linux must index into every VM object that "
+"_might_ have mapped the page. For example, if you have 50 processes all "
+"mapping the same shared library and want to get rid of page X in that "
+"library, you need to index into the page table for each of those 50 "
+"processes even if only 10 of them have actually mapped the page. So Linux "
+"is trading off the simplicity of its design against performance. Many VM "
+"algorithms which are O(1) or (small N) under FreeBSD wind up being O(N), "
+"O(N^2), or worse under Linux. Since the pte's representing a particular "
+"page in an object tend to be at the same offset in all the page tables they "
+"are mapped in, reducing the number of accesses into the page tables at the "
+"same pte offset will often avoid blowing away the L1 cache line for that "
+"offset, which can lead to better performance."
+msgstr ""
+"В Linux нет такого связного списка. Для того, чтобы удалить все отображения "
+"аппаратной таблицы страниц для `vm_page`, linux должен пройти по индексу "
+"каждого объекта VM, который _может_ отображать страницу. К примеру, если у "
+"вас имеется 50 процессов, которые все отображают ту же самую динамическую "
+"библиотеку и хотите избавиться от страницы X в этой библиотеке, то вам нужно "
+"пройтись по индексу всей таблицы страниц для каждого из этих 50 процессов, "
+"даже если только 10 из них на самом деле отображают страницу. Так что Linux "
+"использует простоту подхода за счет производительности. Многие алгоритмы VM, "
+"которые имеют сложность O(1) или (N малое) во FreeBSD, в Linux приобретают "
+"сложность O(N), O(N^2) или хуже. Так как pte, представляющий конкретную "
+"страницу в объекте, скорее всего, будет с тем же смещением во всех таблицах "
+"страниц, в которых они отображаются, то уменьшение количества обращений в "
+"таблицы страниц по тому же самому смещению часто позволяет избежать "
+"разрастания кэша L1 для этого смещения, что приводит к улучшению "
+"производительности."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:362
+msgid ""
+"FreeBSD has added complexity (the `pv_entry` scheme) to increase performance "
+"(to limit page table accesses to _only_ those pte's that need to be "
+"modified)."
+msgstr ""
+"Во FreeBSD введены дополнительные сложности (схема с `pv_entry`) для "
+"увеличения производительности (уменьшая количество обращений _только_ к тем "
+"pte, которые нужно модифицировать)."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:366
+msgid ""
+"But FreeBSD has a scaling problem that Linux does not in that there are a "
+"limited number of `pv_entry` structures and this causes problems when you "
+"have massive sharing of data. In this case you may run out of `pv_entry` "
+"structures even though there is plenty of free memory available. This can "
+"be fixed easily enough by bumping up the number of `pv_entry` structures in "
+"the kernel config, but we really need to find a better way to do it."
+msgstr ""
+"Но во FreeBSD имеется проблема масштабирования, которой нет в Linux, потому "
+"что имеется ограниченное число структур `pv_entry`, и это приводит к "
+"возникновению проблем при большом объеме совместно используемых данных. В "
+"этом случае у вас может возникнуть нехватка структур `pv_entry`, даже если "
+"свободной памяти хватает. Это может быть достаточно легко исправлено "
+"увеличением количества структур `pv_entry` при настройке, но на самом деле "
+"нам нужно найти лучший способ делать это."
+
+#. type: Plain text
+#: documentation/content/en/articles/vm-design/_index.adoc:369
+msgid ""
+"In regards to the memory overhead of a page table verses the `pv_entry` "
+"scheme: Linux uses \"permanent\" page tables that are not throw away, but "
+"does not need a `pv_entry` for each potentially mapped pte. FreeBSD uses "
+"\"throw away\" page tables but adds in a `pv_entry` structure for each "
+"actually-mapped pte. I think memory utilization winds up being about the "
+"same, giving FreeBSD an algorithmic advantage with its ability to throw away "
+"page tables at will with very low overhead."
+msgstr ""
+"Что касается использования памяти под таблицу страниц против схемы с "
+"`pv_entry`: Linux использует \"постоянные\" таблицы страниц, которые не "
+"сбрасываются, но ему не нужны `pv_entry` для каждого потенциально "
+"отображаемого pte. FreeBSD использует \"сбрасываемые\" таблицы страниц, но "
+"для каждого реально отображаемого pte добавляется структура `pv_entry`. Я "
+"думаю, что использование памяти будет примерно одинакова, тем более что у "
+"FreeBSD есть алгоритмическое преимущество, заключающееся в способности "
+"сбрасывать таблицы страниц с очень малыми накладными расходами."
diff --git a/documentation/content/ru/books/developers-handbook/_index.adoc b/documentation/content/ru/books/developers-handbook/_index.adoc
index 98a3fbc883..9e83164861 100644
--- a/documentation/content/ru/books/developers-handbook/_index.adoc
+++ b/documentation/content/ru/books/developers-handbook/_index.adoc
@@ -1,24 +1,31 @@
---
-title: Руководство FreeBSD для разработчиков
+add_single_page_link: true
authors:
- - author: The FreeBSD Documentation Project
-copyright: 1995-2020 The FreeBSD Documentation Project
+ -
+ author: 'The FreeBSD Documentation Project'
+bookOrder: 25
+copyright: '1995-2023 The FreeBSD Documentation Project'
+description: 'Для тех, кто хочет разрабатывать программное обеспечение для FreeBSD (а не только для тех, кто разрабатывает саму FreeBSD)'
+next: books/developers-handbook/parti
+params:
+ path: /books/developers-handbook/
+showBookMenu: true
+tags: "[\"FreeBSD Developers' Handbook\"]"
+title: 'Руководство разработчика FreeBSD'
trademarks: ["freebsd", "apple", "ibm", "ieee", "intel", "linux", "microsoft", "opengroup", "sun", "general"]
-isIndex: true
+weight: 0
---
-= Руководство FreeBSD для разработчиков
+= Руководство разработчика FreeBSD
:doctype: book
:toc: macro
-:toclevels: 2
+:toclevels: 1
:icons: font
:sectnums:
:sectnumlevels: 6
:partnums:
:source-highlighter: rouge
:experimental:
-:book: true
-:pdf: false
:images-path: books/developers-handbook/
ifdef::env-beastie[]
@@ -30,245 +37,21 @@ include::shared/attributes/attributes-{{% lang %}}.adoc[]
include::shared/{{% lang %}}/teams.adoc[]
include::shared/{{% lang %}}/mailing-lists.adoc[]
include::shared/{{% lang %}}/urls.adoc[]
-:chapters-path: content/{{% lang %}}/books/developers-handbook/
endif::[]
ifdef::backend-pdf,backend-epub3[]
-:chapters-path:
include::../../../../../shared/asciidoctor.adoc[]
endif::[]
endif::[]
ifndef::env-beastie[]
-:chapters-path:
include::../../../../../shared/asciidoctor.adoc[]
endif::[]
[.abstract-title]
Аннотация
-Добро пожаловать в руководство FreeBSD для разработчиков.
+Добро пожаловать в Руководство разработчика. Этот документ находится в _процессе разработки_ и создаётся усилиями многих людей. Многие разделы пока отсутствуют, а существующие нуждаются в обновлении. Если вы хотите помочь с этим проектом, отправьте письмо на {freebsd-doc}.
-'''
-
-toc::[]
-
-[[introduction]]
-= Введение
-
-[[developmentplatform]]
-== Разработка во FreeBSD
-
-Здесь необходимо будет обсудить FreeBSD в качестве платформы для разработки, подход к этому BSD, обзор архитектуры, структура /usr/src, история и так далее.
-
-Спасибо вам за выбор FreeBSD в качестве платформы разработки! Надеемся, что она вас не подведет.
-
-[[bsdvision]]
-== Парадигма BSD
-
-[[archoverview]]
-== Обзор архитектуры
-
-[[sourcelayout]]
-== Структура /usr/src
-
-Полный исходный код FreeBSD имеется на нашем общедоступном хранилище CVS. Как правило, исходный код устанавливается в каталог [.filename]#/usr/src#, содержащий следующие подкаталоги.
-
-[.informaltable]
-[cols="1,1", frame="none", options="header"]
-|===
-| Каталог
-| Описание
-
-|[.filename]#bin/#
-|Исходный код файлов из [.filename]#/bin#
-
-|[.filename]#contrib/#
-|Исходный код файлов программного обеспечения, которое предоставлено третьими лицами.
-
-|[.filename]#crypto/#
-|Исходный код DES
-
-|[.filename]#etc/#
-|Исходный код файлов из [.filename]#/etc#
-
-|[.filename]#games/#
-|Исходный код файлов из [.filename]#/usr/games#
-
-|[.filename]#gnu/#
-|Утилиты, подпадающие под условия GNU Public License
-
-|[.filename]#include/#
-|Исходный код файлов из [.filename]#/usr/include#
-
-|[.filename]#kerberosIV/#
-|Исходный код Kerbereros версии IV
-
-|[.filename]#kerberos5/#
-|Исходный код Kerbereros версии 5
-
-|[.filename]#lib/#
-|Исходный код файлов из [.filename]#/usr/lib#
-
-|[.filename]#libexec/#
-|Исходный код файлов из [.filename]#/usr/libexec#
-
-|[.filename]#release/#
-|Файлы, необходимые для выпуска релиза FreeBSD
-
-|[.filename]#sbin/#
-|Исходный код файлов из [.filename]#/sbin#
-
-|[.filename]#secure/#
-|Исходный код FreeSec
-
-|[.filename]#share/#
-|Исходный код файлов из [.filename]#/sbin#
-
-|[.filename]#sys/#
-|Исходные тексты ядра
-
-|[.filename]#tools/#
-|Инструментальные средства, использемые для обслуживания и тестирования FreeBSD
-
-|[.filename]#usr.bin/#
-|Исходный код файлов из [.filename]#/usr/bin#
-
-|[.filename]#usr.sbin/#
-|Исходный код файлов из [.filename]#/usr/sbin#
-|===
-
-[[Basics]]
-= Основы
-include::{chapters-path}secure/chapter.adoc[leveloffset=+1]
-
-[[kernel]]
-= Ядро
-
-[[kernelhistory]]
-== История ядра Unix
-
-Немного истории о ядре Unix/BSD, системных вызовах, как работают процессы, блокировке, планировке задач, нити (ядра), переключение контекста, сигналы, прерывания, модули и так далее.
-
-[[memory]]
-= Память и виртуальная память
-
-[[virtualmemory]]
-== Виртуальная память
-
-VM, постраничная подкачка и свопирование, выделение памяти, тестирование ошибок утечки памяти, mmap, vnode и так далее.
-
-[[iosystem]]
-= Система ввода/вывода
-
-[[ufs]]
-== UFS
-
-UFS, FFS, Ext2FS, JFS, inodes, buffer cache, labeling, locking, metadata, soft-updates, LFS, portalfs, procfs, vnodes, memory sharing, memory objects, TLBs, caching
-
-[[ipc]]
-= Межпроцессное взаимодействие
+Последняя версия этого документа всегда доступна по ссылке link:https://www.FreeBSD.org[веб-сервер FreeBSD]. Его также можно загрузить в различных форматах и с разными вариантами сжатия с link:https://download.freebsd.org/doc/[сервера загрузки FreeBSD] или одного из многочисленных extref:{handbook}[зеркальных сайтов, mirrors].
-[[signals]]
-== Сигналы
-
-Сигналы, конвейеры, семафоры, очереди сообщений, совместно используемая память, сокеты, двери
-
-[[networking]]
-= Работа в сети
-
-[[sockets]]
-== Сокеты
-
-Сокеты, bpf, IP, TCP, UDP, ICMP, OSI, bridging, firewalling, NAT, коммутация и так далее
-
-[[networkfs]]
-= Сетевые файловые системы
-
-[[afs]]
-== AFS
-
-AFS, NFS, SANs etc]
-
-[[terminal]]
-= Работа с терминалами
-
-[[syscons]]
-== Системные консоли
-
-Syscons, tty, PCVT, последовательная консоль, хранители экрана и так далее
-
-[[sound]]
-= Звук
-
-[[oss]]
-== OSS
-
-OSS, waveforms, etc
-
-[[devicedrivers]]
-= Драйверы устройств
-
-[[usb]]
-== Устройства USB
-
-Эта глава расскажет о механизмах, используемых во FreeBSD для написания драйверов для устройств на шине USB.
-
-[[newbus]]
-== NewBus
-
-Эта глава расскажет об архитектуре NewBus во FreeBSD.
-
-[[architectures]]
-= Аппаратные платформы
-
-[[ia32]]
-== IA-32
-
-Рассказ об архитектурных особенностях FreeBSD/x86.
-
-[[alpha]]
-== Alpha
-
-Рассказ об архитектурных особенностях FreeBSD/alpha.
-
-Описание ошибок выравнивания, как их исправлять и как игнорировать.
-
-Пример ассемблерного кода для FreeBSD/alpha.
-
-[[ia64]]
-== IA-64
-
-Рассказ об архитектурных особенностях FreeBSD/ia64.
-
-[[debuggingpart]]
-= Отладка
-
-[[truss]]
-== Truss
-
-Различные описания того, как отлаживать отдельные компоненты системы при помощи утилит truss, ktrace, gdb, kgdb, etc
-
-[[compatibility]]
-= Обеспечение совместимости
-
-[[linux]]
-== Linux
-
-Linux, SVR4 и так далее
-
-// Appendices
-[[appendices]]
-[bibliography]
-= Приложения
-
-[[COD,1]] [1] Dave A Patterson and John L Hennessy. Copyright(R) 1998 Morgan Kaufmann Publishers, Inc. 1-55860-428-6. Morgan Kaufmann Publishers, Inc. Computer Organization and Design. The Hardware / Software Interface. 1-2.
-
-[[APUE, 2]] [2] W. Richard Stevens. Copyright(R) 1993 Addison Wesley Longman, Inc. 0-201-56317-7. Addison Wesley Longman, Inc. Advanced Programming in the Unix Environment. 1-2.
-
-[[DIFOS, 3]] [3] Marshall Kirk McKusick and George Neville-Neil. Copyright(R) 2004 Addison-Wesley. 0-201-70245-2. Addison-Wesley. The Design and Implementation of the FreeBSD Operating System. 1-2.
-
-[[Phrack, 4]] [4] Aleph One. Phrack 49; "Smashing the Stack for Fun and Profit".
-
-[[StackGuard, 5]] [5] Chrispin Cowan, Calton Pu, and Dave Maier. StackGuard; Automatic Adaptive Detection and Prevention of Buffer-Overflow Attacks.
-
-[[OpenBSD, 6]] [6] Todd Miller and Theo de Raadt. strlcpy and strlcat -- consistent, safe string copy and concatenation.
+'''
diff --git a/documentation/content/ru/books/developers-handbook/_index.po b/documentation/content/ru/books/developers-handbook/_index.po
new file mode 100644
index 0000000000..17abcc726d
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/_index.po
@@ -0,0 +1,70 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-07-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbook_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/_index.adoc:1
+#, no-wrap
+msgid "For people who want to develop software for FreeBSD (and not just people who are developing FreeBSD itself)"
+msgstr "Для тех, кто хочет разрабатывать программное обеспечение для FreeBSD (а не только для тех, кто разрабатывает саму FreeBSD)"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/_index.adoc:18
+#, no-wrap
+msgid "FreeBSD Developers' Handbook"
+msgstr "Руководство разработчика FreeBSD"
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/_index.adoc:51
+msgid "Abstract"
+msgstr "Аннотация"
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/_index.adoc:56
+msgid ""
+"Welcome to the Developers' Handbook. This manual is a _work in progress_ "
+"and is the work of many individuals. Many sections do not yet exist and "
+"some of those that do exist need to be updated. If you are interested in "
+"helping with this project, send email to the {freebsd-doc}."
+msgstr ""
+"Добро пожаловать в Руководство разработчика. Этот документ находится в "
+"_процессе разработки_ и создаётся усилиями многих людей. Многие разделы пока "
+"отсутствуют, а существующие нуждаются в обновлении. Если вы хотите помочь с "
+"этим проектом, отправьте письмо на {freebsd-doc}."
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/_index.adoc:59
+msgid ""
+"The latest version of this document is always available from the "
+"link:https://www.FreeBSD.org[FreeBSD World Wide Web server]. It may also be "
+"downloaded in a variety of formats and compression options from the "
+"link:https://download.freebsd.org/doc/[FreeBSD download server] or one of "
+"the numerous extref:{handbook}[mirror sites, mirrors]."
+msgstr ""
+"Последняя версия этого документа всегда доступна по ссылке link:https://"
+"www.FreeBSD.org[веб-сервер FreeBSD]. Его также можно загрузить в различных "
+"форматах и с разными вариантами сжатия с link:https://download.freebsd.org/"
+"doc/[сервера загрузки FreeBSD] или одного из многочисленных extref:{handbook}"
+"[зеркальных сайтов, mirrors]."
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/_index.adoc:60
+msgid "'''"
+msgstr "'''"
diff --git a/documentation/content/ru/books/developers-handbook/bibliography/_index.adoc b/documentation/content/ru/books/developers-handbook/bibliography/_index.adoc
new file mode 100644
index 0000000000..d107cef3fa
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/bibliography/_index.adoc
@@ -0,0 +1,62 @@
+---
+description: 'Библиография Руководства разработчика FreeBSD'
+params:
+ path: /books/developers-handbook/bibliography/
+prev: books/developers-handbook/partv
+showBookMenu: true
+tags: "[\"FreeBSD Developers' Handbook\", \"bibliography\"]"
+title: Библиография
+weight: 17
+---
+
+[appendix]
+[[bibliography]]
+= Библиография
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: A
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[COD,1]] [1] Dave A Patterson and John L Hennessy. Copyright(R) 1998 Morgan Kaufmann Publishers, Inc. 1-55860-428-6. Morgan Kaufmann Publishers, Inc. Computer Organization and Design. The Hardware / Software Interface. 1-2.
+
+[[APUE, 2]] [2] W. Richard Stevens. Copyright(R) 1993 Addison Wesley Longman, Inc. 0-201-56317-7. Addison Wesley Longman, Inc. Advanced Programming in the Unix Environment. 1-2.
+
+[[DIFOS, 3]] [3] Marshall Kirk McKusick and George Neville-Neil. Copyright(R) 2004 Addison-Wesley. 0-201-70245-2. Addison-Wesley. The Design and Implementation of the FreeBSD Operating System. 1-2.
+
+[[Phrack, 4]] [4] Aleph One. Phrack 49; "Smashing the Stack for Fun and Profit".
+
+[[StackGuard, 5]] [5] Chrispin Cowan, Calton Pu, and Dave Maier. StackGuard; Automatic Adaptive Detection and Prevention of Buffer-Overflow Attacks.
+
+[[OpenBSD, 6]] [6] Todd Miller and Theo de Raadt. strlcpy and strlcat -- consistent, safe string copy and concatenation.
+
diff --git a/documentation/content/ru/books/developers-handbook/bibliography/_index.po b/documentation/content/ru/books/developers-handbook/bibliography/_index.po
new file mode 100644
index 0000000000..82f48421ac
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/bibliography/_index.po
@@ -0,0 +1,92 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-21 19:10+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookbibliography_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:1
+#, no-wrap
+msgid "FreeBSD Developers Handbook Bibliography"
+msgstr "Библиография Руководства разработчика FreeBSD"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:14
+#, no-wrap
+msgid "Bibliography"
+msgstr "Библиография"
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:52
+msgid ""
+"[[COD,1]] [1] Dave A Patterson and John L Hennessy. Copyright(R) 1998 Morgan "
+"Kaufmann Publishers, Inc. 1-55860-428-6. Morgan Kaufmann Publishers, Inc. "
+"Computer Organization and Design. The Hardware / Software Interface. 1-2."
+msgstr ""
+"[[COD,1]] [1] Dave A Patterson and John L Hennessy. Copyright(R) 1998 Morgan "
+"Kaufmann Publishers, Inc. 1-55860-428-6. Morgan Kaufmann Publishers, Inc. "
+"Computer Organization and Design. The Hardware / Software Interface. 1-2."
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:54
+msgid ""
+"[[APUE, 2]] [2] W. Richard Stevens. Copyright(R) 1993 Addison Wesley "
+"Longman, Inc. 0-201-56317-7. Addison Wesley Longman, Inc. Advanced "
+"Programming in the Unix Environment. 1-2."
+msgstr ""
+"[[APUE, 2]] [2] W. Richard Stevens. Copyright(R) 1993 Addison Wesley "
+"Longman, Inc. 0-201-56317-7. Addison Wesley Longman, Inc. Advanced "
+"Programming in the Unix Environment. 1-2."
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:56
+msgid ""
+"[[DIFOS, 3]] [3] Marshall Kirk McKusick and George Neville-Neil. "
+"Copyright(R) 2004 Addison-Wesley. 0-201-70245-2. Addison-Wesley. The Design "
+"and Implementation of the FreeBSD Operating System. 1-2."
+msgstr ""
+"[[DIFOS, 3]] [3] Marshall Kirk McKusick and George Neville-Neil. "
+"Copyright(R) 2004 Addison-Wesley. 0-201-70245-2. Addison-Wesley. The Design "
+"and Implementation of the FreeBSD Operating System. 1-2."
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:58
+msgid ""
+"[[Phrack, 4]] [4] Aleph One. Phrack 49; \"Smashing the Stack for Fun and "
+"Profit\"."
+msgstr ""
+"[[Phrack, 4]] [4] Aleph One. Phrack 49; \"Smashing the Stack for Fun and "
+"Profit\"."
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:60
+msgid ""
+"[[StackGuard, 5]] [5] Chrispin Cowan, Calton Pu, and Dave Maier. StackGuard; "
+"Automatic Adaptive Detection and Prevention of Buffer-Overflow Attacks."
+msgstr ""
+"[[StackGuard, 5]] [5] Chrispin Cowan, Calton Pu, and Dave Maier. StackGuard; "
+"Automatic Adaptive Detection and Prevention of Buffer-Overflow Attacks."
+
+#. type: appendix
+#: documentation/content/en/books/developers-handbook/bibliography/_index.adoc:62
+msgid ""
+"[[OpenBSD, 6]] [6] Todd Miller and Theo de Raadt. strlcpy and strlcat -- "
+"consistent, safe string copy and concatenation."
+msgstr ""
+"[[OpenBSD, 6]] [6] Todd Miller and Theo de Raadt. strlcpy and strlcat -- "
+"consistent, safe string copy and concatenation."
diff --git a/documentation/content/ru/books/developers-handbook/book.adoc b/documentation/content/ru/books/developers-handbook/book.adoc
new file mode 100644
index 0000000000..1ff909d433
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/book.adoc
@@ -0,0 +1,84 @@
+---
+add_split_page_link: true
+authors:
+ -
+ author: 'The FreeBSD Documentation Project'
+copyright: '1995-2023 The FreeBSD Documentation Project'
+description: 'Для тех, кто хочет разрабатывать программное обеспечение для FreeBSD (а не только для тех, кто разрабатывает саму FreeBSD)'
+tags: "[\"FreeBSD Developers' Handbook\"]"
+title: 'Руководство разработчика FreeBSD'
+trademarks: ["freebsd", "apple", "ibm", "ieee", "intel", "linux", "microsoft", "opengroup", "sun", "general"]
+---
+
+= Руководство разработчика FreeBSD
+:doctype: book
+:toc: macro
+:toclevels: 2
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:book: true
+:pdf: false
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+:chapters-path: content/{{% lang %}}/books/developers-handbook/
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+:chapters-path:
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+:chapters-path:
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[.abstract-title]
+Аннотация
+
+Добро пожаловать в Руководство разработчика. Этот документ находится в _процессе разработки_ и создаётся усилиями многих людей. Многие разделы пока отсутствуют, а существующие нуждаются в обновлении. Если вы хотите помочь с этим проектом, отправьте письмо на {freebsd-doc}.
+
+Последняя версия этого документа всегда доступна по ссылке link:https://www.FreeBSD.org[веб-сервер FreeBSD]. Его также можно загрузить в различных форматах и с разными вариантами сжатия с link:https://download.freebsd.org/doc/[сервера загрузки FreeBSD] или одного из многочисленных extref:{handbook}[зеркальных сайтов, mirrors].
+
+'''
+
+toc::[]
+
+// Section one
+include::{chapters-path}parti.adoc[]
+include::{chapters-path}introduction/_index.adoc[leveloffset=+1]
+include::{chapters-path}tools/_index.adoc[leveloffset=+1]
+include::{chapters-path}secure/_index.adoc[leveloffset=+1]
+include::{chapters-path}l10n/_index.adoc[leveloffset=+1]
+include::{chapters-path}policies/_index.adoc[leveloffset=+1]
+include::{chapters-path}testing/_index.adoc[leveloffset=+1]
+
+// Section two
+include::{chapters-path}partii.adoc[]
+include::{chapters-path}sockets/_index.adoc[leveloffset=+1]
+include::{chapters-path}ipv6/_index.adoc[leveloffset=+1]
+
+// Section three
+include::{chapters-path}partiii.adoc[]
+include::{chapters-path}kernelbuild/_index.adoc[leveloffset=+1]
+include::{chapters-path}kerneldebug/_index.adoc[leveloffset=+1]
+
+// Section four
+include::{chapters-path}partiv.adoc[]
+include::{chapters-path}x86/_index.adoc[leveloffset=+1]
+
+// Appendices
+include::{chapters-path}partv.adoc[]
+include::{chapters-path}bibliography/_index.adoc[leveloffset=+1]
diff --git a/documentation/content/ru/books/developers-handbook/book.po b/documentation/content/ru/books/developers-handbook/book.po
new file mode 100644
index 0000000000..cf8b6b30d0
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/book.po
@@ -0,0 +1,70 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-07-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookbook/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/book.adoc:1
+#, no-wrap
+msgid "For people who want to develop software for FreeBSD (and not just people who are developing FreeBSD itself)"
+msgstr "Для тех, кто хочет разрабатывать программное обеспечение для FreeBSD (а не только для тех, кто разрабатывает саму FreeBSD)"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/book.adoc:1
+#: documentation/content/en/books/developers-handbook/book.adoc:12
+#, no-wrap
+msgid "FreeBSD Developers' Handbook"
+msgstr "Руководство разработчика FreeBSD"
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/book.adoc:49
+msgid "Abstract"
+msgstr "Аннотация"
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/book.adoc:54
+msgid ""
+"Welcome to the Developers' Handbook. This manual is a _work in progress_ "
+"and is the work of many individuals. Many sections do not yet exist and "
+"some of those that do exist need to be updated. If you are interested in "
+"helping with this project, send email to the {freebsd-doc}."
+msgstr ""
+"Добро пожаловать в Руководство разработчика. Этот документ находится в "
+"_процессе разработки_ и создаётся усилиями многих людей. Многие разделы пока "
+"отсутствуют, а существующие нуждаются в обновлении. Если вы хотите помочь с "
+"этим проектом, отправьте письмо на {freebsd-doc}."
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/book.adoc:57
+msgid ""
+"The latest version of this document is always available from the "
+"link:https://www.FreeBSD.org[FreeBSD World Wide Web server]. It may also be "
+"downloaded in a variety of formats and compression options from the "
+"link:https://download.freebsd.org/doc/[FreeBSD download server] or one of "
+"the numerous extref:{handbook}[mirror sites, mirrors]."
+msgstr ""
+"Последняя версия этого документа всегда доступна по ссылке link:https://"
+"www.FreeBSD.org[веб-сервер FreeBSD]. Его также можно загрузить в различных "
+"форматах и с разными вариантами сжатия с link:https://download.freebsd.org/"
+"doc/[сервера загрузки FreeBSD] или одного из многочисленных extref:{handbook}"
+"[зеркальных сайтов, mirrors]."
+
+#. type: .abstract-title
+#: documentation/content/en/books/developers-handbook/book.adoc:59
+msgid "'''"
+msgstr "'''"
diff --git a/documentation/content/ru/books/developers-handbook/introduction/_index.adoc b/documentation/content/ru/books/developers-handbook/introduction/_index.adoc
new file mode 100644
index 0000000000..d212e92f3a
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/introduction/_index.adoc
@@ -0,0 +1,86 @@
+---
+authors:
+ -
+ author: 'Murray Stokely'
+ -
+ author: 'Jeroen Ruigrok van der Werven'
+description: 'Введение в Руководство разработчика FreeBSD'
+next: books/developers-handbook/tools
+params:
+ path: /books/developers-handbook/introduction/
+prev: books/developers-handbook/parti
+showBookMenu: true
+tags: ["introduction", "Developing on FreeBSD", "BSD Vision", "Architectural Guidelines"]
+title: 'Глава 1. Введение'
+weight: 2
+---
+
+[[introduction]]
+= Введение
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 1
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[introduction-devel]]
+== Разработка на FreeBSD
+
+Вот мы и здесь. Система установлена, и вы готовы начать программировать. Но с чего начать? Что предоставляет FreeBSD? Что она может сделать для меня как для программиста?
+
+Вот некоторые вопросы, на которые эта глава пытается ответить. Конечно, программирование, как и любое другое ремесло, имеет разные уровни мастерства. Для кого-то это хобби, для других — профессия. Информация в этой главе может быть ориентирована на начинающего программиста; действительно, она может быть полезна программисту, не знакомому с платформой FreeBSD.
+
+[[introduction-bsdvision]]
+== Видение BSD
+
+Создать наилучший пакет операционной системы, подобной UNIX(R), с должным уважением к оригинальной идеологии программных инструментов, а также к удобству использования, производительности и стабильности.
+
+[[introduction-archguide]]
+== Архитектурные рекомендации
+
+Наша идеология может быть описана следующими принципами
+
+* Не добавляйте новую функциональность, если разработчик не может завершить реальное приложение без неё.
+* Важно не только определить, чем является система, но и чем она не является. Не стоит пытаться удовлетворить все возможные потребности; вместо этого сделайте систему расширяемой, чтобы дополнительные требования могли быть реализованы с сохранением совместимости.
+* Худшее, чем обобщение на основе одного примера — это обобщение без примеров вообще.
+* Если проблема не до конца понятна, вероятно, лучше вообще не предоставлять решения.
+* Если вы можете получить 90% желаемого эффекта за 10% работы, используйте более простое решение.
+* Изолируйте сложность настолько, насколько это возможно.
+* Предоставлять механизмы, а не политики. В частности, передайте политику пользовательского интерфейса в руки клиента.
+
+Из Шейфлера и Геттиса: «X Window System»
+
+[[introduction-layout]]
+== Структура каталога /usr/src
+
+Полный исходный код FreeBSD доступен в нашем link:https://cgit.freebsd.org/src/[публичном Git-репозитории]. Исходный код обычно устанавливается в [.filename]#/usr/src#. Структура дерева каталогов исходного кода описана в файле link:https://cgit.freebsd.org/src/tree/README.md[README.md] на верхнем уровне дерева.
diff --git a/documentation/content/ru/books/developers-handbook/introduction/_index.po b/documentation/content/ru/books/developers-handbook/introduction/_index.po
new file mode 100644
index 0000000000..8c010f6a5d
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/introduction/_index.po
@@ -0,0 +1,185 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-07-06 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookintroduction_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:1
+#, no-wrap
+msgid "Introduction to the FreeBSD Developers Handbook"
+msgstr "Введение в Руководство разработчика FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:1
+#, no-wrap
+msgid "Chapter 1. Introduction"
+msgstr "Глава 1. Введение"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:17
+#, no-wrap
+msgid "Introduction"
+msgstr "Введение"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:55
+#, no-wrap
+msgid "Developing on FreeBSD"
+msgstr "Разработка на FreeBSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:60
+msgid ""
+"So here we are. System all installed and you are ready to start "
+"programming. But where to start? What does FreeBSD provide? What can it do "
+"for me, as a programmer?"
+msgstr ""
+"Вот мы и здесь. Система установлена, и вы готовы начать программировать. Но "
+"с чего начать? Что предоставляет FreeBSD? Что она может сделать для меня как "
+"для программиста?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:66
+msgid ""
+"These are some questions which this chapter tries to answer. Of course, "
+"programming has different levels of proficiency like any other trade. For "
+"some it is a hobby, for others it is their profession. The information in "
+"this chapter might be aimed toward the beginning programmer; indeed, it "
+"could serve useful for the programmer unfamiliar with the FreeBSD platform."
+msgstr ""
+"Вот некоторые вопросы, на которые эта глава пытается ответить. Конечно, "
+"программирование, как и любое другое ремесло, имеет разные уровни "
+"мастерства. Для кого-то это хобби, для других — профессия. Информация в этой "
+"главе может быть ориентирована на начинающего программиста; действительно, "
+"она может быть полезна программисту, не знакомому с платформой FreeBSD."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:68
+#, no-wrap
+msgid "The BSD Vision"
+msgstr "Видение BSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:71
+msgid ""
+"To produce the best UNIX(R) like operating system package possible, with due "
+"respect to the original software tools ideology as well as usability, "
+"performance and stability."
+msgstr ""
+"Создать наилучший пакет операционной системы, подобной UNIX(R), с должным "
+"уважением к оригинальной идеологии программных инструментов, а также к "
+"удобству использования, производительности и стабильности."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:73
+#, no-wrap
+msgid "Architectural Guidelines"
+msgstr "Архитектурные рекомендации"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:76
+msgid "Our ideology can be described by the following guidelines"
+msgstr "Наша идеология может быть описана следующими принципами"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:78
+msgid ""
+"Do not add new functionality unless an implementor cannot complete a real "
+"application without it."
+msgstr ""
+"Не добавляйте новую функциональность, если разработчик не может завершить "
+"реальное приложение без неё."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:79
+msgid ""
+"It is as important to decide what a system is not as to decide what it is. "
+"Do not serve all the world's needs; rather, make the system extensible so "
+"that additional needs can be met in an upwardly compatible fashion."
+msgstr ""
+"Важно не только определить, чем является система, но и чем она не является. "
+"Не стоит пытаться удовлетворить все возможные потребности; вместо этого "
+"сделайте систему расширяемой, чтобы дополнительные требования могли быть "
+"реализованы с сохранением совместимости."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:80
+msgid ""
+"The only thing worse than generalizing from one example is generalizing from "
+"no examples at all."
+msgstr ""
+"Худшее, чем обобщение на основе одного примера — это обобщение без примеров "
+"вообще."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:81
+msgid ""
+"If a problem is not completely understood, it is probably best to provide no "
+"solution at all."
+msgstr ""
+"Если проблема не до конца понятна, вероятно, лучше вообще не предоставлять "
+"решения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:82
+msgid ""
+"If you can get 90 percent of the desired effect for 10 percent of the work, "
+"use the simpler solution."
+msgstr ""
+"Если вы можете получить 90% желаемого эффекта за 10% работы, используйте "
+"более простое решение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:83
+msgid "Isolate complexity as much as possible."
+msgstr "Изолируйте сложность настолько, насколько это возможно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:84
+msgid ""
+"Provide mechanism, rather than policy. In particular, place user interface "
+"policy in the client's hands."
+msgstr ""
+"Предоставлять механизмы, а не политики. В частности, передайте политику "
+"пользовательского интерфейса в руки клиента."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:86
+msgid "From Scheifler & Gettys: \"X Window System\""
+msgstr "Из Шейфлера и Геттиса: «X Window System»"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:88
+#, no-wrap
+msgid "The Layout of /usr/src"
+msgstr "Структура каталога /usr/src"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/introduction/_index.adoc:92
+msgid ""
+"The complete source code for FreeBSD is available from our link:https://"
+"cgit.freebsd.org/src/[public Git repository]. The source code is normally "
+"installed in [.filename]#/usr/src#. The layout of the source tree is "
+"described by the top-level link:https://cgit.freebsd.org/src/tree/"
+"README.md[README.md] file."
+msgstr ""
+"Полный исходный код FreeBSD доступен в нашем link:https://cgit.freebsd.org/"
+"src/[публичном Git-репозитории]. Исходный код обычно устанавливается в "
+"[.filename]#/usr/src#. Структура дерева каталогов исходного кода описана в "
+"файле link:https://cgit.freebsd.org/src/tree/README.md[README.md] на верхнем "
+"уровне дерева."
diff --git a/documentation/content/ru/books/developers-handbook/ipv6/_index.adoc b/documentation/content/ru/books/developers-handbook/ipv6/_index.adoc
new file mode 100644
index 0000000000..70f6853b87
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/ipv6/_index.adoc
@@ -0,0 +1,687 @@
+---
+authors:
+ -
+ author: 'Yoshinobu Inoue'
+description: 'Внутреннее устройство IPv6'
+next: books/developers-handbook/partiii
+params:
+ path: /books/developers-handbook/ipv6/
+prev: books/developers-handbook/sockets
+showBookMenu: true
+tags: ["IPv6", "FreeBSD"]
+title: 'Глава 8. Внутреннее устройство IPv6'
+weight: 10
+---
+
+[[ipv6]]
+= Внутреннее устройство IPv6
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 8
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[ipv6-implementation]]
+== Реализация IPv6/IPsec
+
+В этом разделе мы объясним внутреннюю реализацию, связанную с IPv6 и IPsec. Данная функциональность заимствована из http://www.kame.net/[проекта KAME]
+
+[[ipv6details]]
+=== IPv6
+
+==== Соответствие
+
+Функции, связанные с IPv6, соответствуют или пытаются соответствовать последнему набору спецификаций IPv6. Для дальнейшего использования мы приводим некоторые из соответствующих документов ниже (_ПРИМЕЧАНИЕ_: это не полный список — его слишком сложно поддерживать...).
+
+Для подробностей обратитесь к соответствующей главе документа, RFC, страницам Справосника или комментариям в исходном коде.
+
+Тесты на соответствие стандартам были проведены для KAME STABLE в проекте TAHI. Результаты можно посмотреть по ссылке http://www.tahi.org/report/KAME/[http://www.tahi.org/report/KAME/]. Мы также участвовали в тестах IOL Университета Нью-Гэмпшира (http://www.iol.unh.edu/[http://www.iol.unh.edu/]) в прошлом, используя наши предыдущие версии.
+
+* RFC1639: FTP Operation Over Big Address Records (FOOBAR)
+
+** RFC2428 предпочтительнее RFC1639. FTP-клиенты сначала попробуют RFC2428, затем RFC1639 в случае неудачи.
+
+* RFC1886: DNS Extensions to support IPv6
+* RFC1933: Transition Mechanisms for IPv6 Hosts and Routers
+
+** IPv4-совместимый адрес не поддерживается.
+** автоматическое туннелирование (описано в разделе 4.3 данного RFC) не поддерживается.
+** man:gif[4] интерфейс реализует IPv[46]-поверх-IPv[46] туннель в общем виде и включает "настроенный туннель", описанный в спецификации. Подробности см. в crossref:ipv6[gif,23.5.1.5] этого документа.
+
+* RFC1981: Path MTU Discovery for IPv6
+* RFC2080: RIPng for IPv6
+
+** usr.sbin/route6d это поддерживает.
+
+* RFC2292: Advanced Sockets API for IPv6
+
+** Для поддерживаемых функций библиотек/API ядра см. [.filename]#sys/netinet6/ADVAPI#.
+
+* RFC2362: Protocol Independent Multicast-Sparse Mode (PIM-SM)
+
+** RFC2362 определяет форматы пакетов для PIM-SM. [.filename]#draft-ietf-pim-ipv6-01.txt# написан на основе этого.
+
+* RFC2373: IPv6 Addressing Architecture
+
+** поддерживает обязательные адреса узлов и соответствует требованиям области видимости.
+
+* RFC2374: An IPv6 Aggregatable Global Unicast Address Format
+
+** поддерживает 64-битную длину Идентификатора Интерфейса.
+
+* RFC2375: IPv6 Multicast Address Assignments
+
+** Пользовательские приложения используют общеизвестные адреса, назначенные в RFC.
+
+* RFC2428: FTP Extensions for IPv6 and NATs
+
+** RFC2428 предпочтительнее RFC1639. FTP-клиенты сначала попробуют RFC2428, затем RFC1639 в случае неудачи.
+
+* RFC2460: IPv6 specification
+* RFC2461: Neighbor discovery for IPv6
+
+** См. crossref:ipv6[neighbor-discovery,23.5.1.2] в этом документе для получения подробностей.
+
+* RFC2462: IPv6 Stateless Address Autoconfiguration
+
+** См. crossref:ipv6[ipv6-pnp,23.5.1.4] в этом документе для получения подробностей.
+
+* RFC2463: ICMPv6 for IPv6 specification
+
+** См. crossref:ipv6[icmpv6,23.5.1.9] в этом документе для получения подробностей.
+
+* RFC2464: Transmission of IPv6 Packets over Ethernet Networks
+* RFC2465: MIB for IPv6: Textual Conventions and General Group
+
+** Необходимая статистика собирается ядром. Фактическая поддержка MIB для IPv6 предоставляется в виде набора патчей для ucd-snmp.
+
+* RFC2466: MIB for IPv6: ICMPv6 group
+
+** Необходимая статистика собирается ядром. Фактическая поддержка MIB IPv6 предоставляется в виде патча для ucd-snmp.
+
+* RFC2467: Transmission of IPv6 Packets over FDDI Networks
+* RFC2497: Transmission of IPv6 packet over ARCnet Networks
+* RFC2553: Basic Socket Interface Extensions for IPv6
+
+** Отображаемый адрес IPv4 (3.7) и особое поведение сокета с привязкой по шаблону IPv6 (3.8) поддерживаются. Подробности см. в разделе crossref:ipv6[ipv6-wildcard-socket,23.5.1.12] этого документа.
+
+* RFC2675: IPv6 Jumbograms
+
+** См. crossref:ipv6[ipv6-jumbo,23.5.1.7] в этом документе для получения подробностей.
+
+* RFC2710: Multicast Listener Discovery for IPv6
+* RFC2711: IPv6 router alert option
+* [.filename]#draft-ietf-ipngwg-router-renum-08#: Перенумерация маршрутизаторов для IPv6
+* [.filename]#draft-ietf-ipngwg-icmp-namelookups-02#: Поиск имен через ICMP в IPv6
+* [.filename]#draft-ietf-ipngwg-icmp-name-lookups-03#: Поиск имен IPv6 через ICMP
+* [.filename]#draft-ietf-pim-ipv6-01.txt#: PIM for IPv6
+
+** man:pim6dd[8] реализует плотный режим. man:pim6sd[8] реализует разреженный режим.
+
+* [.filename]#draft-itojun-ipv6-tcp-to-anycast-00#: Разрыв TCP-соединения с anycast-адресом IPv6
+* [.filename]#draft-yamamoto-wideipv6-comm-model-00#
+
+** См. crossref:ipv6[ipv6-sas,23.5.1.6] в этом документе для более подробной информации.
+
+* [.filename]#draft-ietf-ipngwg-scopedaddr-format-00.txt#: Расширение формата для адресов с областью действия IPv6
+
+[[neighbor-discovery]]
+==== Функция "Обнаружение соседей"
+
+Обнаружение соседей достаточно стабильно. В настоящее время поддерживаются следующие функции: определение адреса (Address Resolution), обнаружение дублирования адресов (DAD — Duplicated Address Detection) и обнаружение недоступности соседей (Neighbor Unreachability Detection). В ближайшем будущем мы добавим поддержку прокси-объявлений соседей (Proxy Neighbor Advertisement) в ядро и команду передачи непрошенных объявлений соседей (Unsolicited Neighbor Advertisement) в качестве инструмента администратора.
+
+Если DAD завершается неудачно, адрес будет помечен как "дублированный" (duplicated), и сообщение будет записано в syslog (а также обычно выведено на консоль). Метку "дублированный" можно проверить с помощью man:ifconfig[8]. Обязанность администратора — проверять и устранять сбои DAD. В ближайшем будущем поведение должно быть улучшено.
+
+Некоторые сетевые драйверы закольцовывают multicast-пакеты обратно на себя, даже если им указано так не делать (особенно в promiscuous mode). В таких случаях DAD может завершиться неудачей, так как механизм DAD видит входящий NS-пакет (на самом деле от самого узла) и считает его признаком дубликата. В качестве обходного решения можно рассмотреть условие #if с пометкой "heuristics" в sys/netinet6/nd6_nbr.c:nd6_dad_timer() (обратите внимание, что фрагмент кода в разделе "heuristics" не соответствует спецификации).
+
+Спецификация обнаружения соседей (RFC2461) не рассматривает обработку кэша соседей в следующих случаях:
+
+. когда отсутствовала запись в кэше соседей, узел получал нежелательный пакет RS/NS/NA/редирект без адреса канального уровня
+. обработка кэша соседей в среде без адреса канального уровня (нам нужна запись в кэше соседей для бита IsRouter)
+
+Для первого случая мы реализовали временное решение на основе обсуждений в рассылке IETF ipngwg. Подробности можно найти в комментариях исходного кода и ветке электронной почты, начавшейся с (IPng 7155) от 6 февраля 1999 года.
+
+Правило определения локальной IPv6 сети (RFC2461) значительно отличается от предположений в сетевом коде BSD. На данный момент не поддерживается правило определения локальной сети при пустом списке маршрутизаторов по умолчанию (RFC2461, раздел 5.2, последнее предложение во 2-м абзаце - обратите внимание, что в спецификации некорректно используются слова "host" и "node" в нескольких местах раздела).
+
+Во избежание возможных атак типа DoS и бесконечных циклов, сейчас принимается только 10 опций в ND-пакете. Таким образом, если к RA прикреплено 20 опций префиксов, будут распознаны только первые 10 префиксов. Если это вызывает проблемы, пожалуйста, задайте вопрос в рассылке FREEBSD-CURRENT и/или измените nd6_maxndopt в [.filename]#sys/netinet6/nd6.c#. При высоком спросе мы можем предоставить sysctl-параметр для этой переменной.
+
+[[ipv6-scope-index]]
+==== Индекс зоны
+
+В IPv6 используются адреса с областями видимости — зонами. Поэтому очень важно указывать индекс зоны (индекс интерфейса для линк-локального адреса или индекс сайта для сайт-локального адреса) вместе с IPv6 адресом. Без индекса зоны адрес IPv6 с ограниченной областью действия является неоднозначным для ядра, и ядро не сможет определить исходящий интерфейс для пакета.
+
+Обычные пользовательские приложения должны использовать расширенный API (RFC2292) для указания индекса зоны или индекса интерфейса. Для аналогичных целей член sin6_scope_id в структуре sockaddr_in6 определён в RFC2553. Однако семантика sin6_scope_id довольно расплывчата. Если важна переносимость вашего приложения, мы рекомендуем использовать расширенный API вместо sin6_scope_id.
+
+В ядре индекс интерфейса для адреса с областью действия link-local встраивается во второе 16-битное слово (3-й и 4-й байт) в IPv6-адресе. Например, вы можете увидеть что-то вроде:
+
+[source, bash]
+....
+ fe80:1::200:f8ff:fe01:6317
+....
+
+в таблице маршрутизации и структуре адреса интерфейса (struct in6_ifaddr). Указанный выше адрес является линк-локальным уникастным адресом, который принадлежит сетевому интерфейсу с идентификатором интерфейса 1. Встроенный индекс позволяет эффективно идентифицировать локальные адреса IPv6 на нескольких интерфейсах с минимальными изменениями кода.
+
+Демоны маршрутизации и программы настройки, такие как man:route6d[8] и man:ifconfig[8], должны управлять "встроенным" индексом зоны. Эти программы используют сокеты маршрутизации и ioctl (например, SIOCGIFADDR_IN6), и API ядра будет возвращать IPv6-адреса с заполненным вторым 16-битным словом. API предназначены для управления внутренними структурами ядра. Программы, использующие эти API, в любом случае должны быть готовы к различиям в ядрах.
+
+При указании адреса с ограниченной областью действия в командной строке НИКОГДА не используйте встроенную форму (например, ff02:1::1 или fe80:2::fedc). Это не должно работать. Всегда используйте стандартную форму, такую как ff02::1 или fe80::fedc, с параметром командной строки для указания интерфейса (например, `ping -6 -I ne0 ff02::1`). В общем, если команда не имеет параметра командной строки для указания исходящего интерфейса, эта команда не готова принимать адрес с областью действия. Это кажется противоречащим принципу IPv6 поддерживать сценарий "кабинета стоматолога". Мы считаем, что спецификации нуждаются в некоторых улучшениях для этого.
+
+Некоторые пользовательские утилиты поддерживают расширенный числовой синтаксис IPv6, как описано в [.filename]#draft-ietf-ipngwg-scopedaddr-format-00.txt#. Можно указать исходящее соединение, используя имя исходящего интерфейса, например "fe80::1%ne0". Таким образом можно легко указать линк-локальный адрес с ограниченной областью действия.
+
+Для использования этого расширения в вашей программе потребуется использовать man:getaddrinfo[3] и man:getnameinfo[3] с NI_WITHSCOPEID. В текущей реализации предполагается однозначное соответствие между каналом и интерфейсом, что является более строгим условием, чем указано в спецификациях.
+
+[[ipv6-pnp]]
+==== Plug and Play (подключи и работай)
+
+Большая часть автонастройки адресов IPv6 без сохранения состояния реализована в ядре. Функции обнаружения соседей (Neighbor Discovery) реализованы в ядре целиком. Ввод рекламы маршрутизатора (RA) для хостов реализован в ядре. Вывод запроса маршрутизатора (RS) для конечных хостов, ввод RS для маршрутизаторов и вывод RA для маршрутизаторов реализованы в пользовательском пространстве.
+
+===== Назначение линк-локальных и специальных адресов
+
+Линк-локальный адрес IPv6 генерируется из IEEE802 адреса (Ethernet MAC адреса). Каждому интерфейсу автоматически присваивается IPv6 линк-локальный адрес, когда интерфейс поднимается (IFF_UP). Также в таблицу маршрутизации добавляется прямой маршрут для линк-локального адреса.
+
+Вот вывод команды netstat:
+
+[source, bash]
+....
+Internet6:
+Destination Gateway Flags Netif Expire
+fe80:1::%ed0/64 link#1 UC ed0
+fe80:2::%ep0/64 link#2 UC ep0
+....
+
+Интерфейсы, не имеющие адреса IEEE802 (псевдоинтерфейсы, такие как туннельные интерфейсы или интерфейсы ppp), будут заимствовать адрес IEEE802 у других интерфейсов, например, Ethernet-интерфейсов, когда это возможно. Если нет подключенного оборудования IEEE802, в качестве последнего средства будет использовано псевдослучайное значение MD5(hostname) для формирования линк-локального адреса. Если это не подходит для вашего использования, вам потребуется настроить линк-локальный адрес вручную.
+
+Если интерфейс не поддерживает IPv6 (например, отсутствует поддержка multicast), на этот интерфейс не будет назначен линк-локальный адрес. Подробности см. в разделе 2.
+
+Каждый интерфейс присоединяется к запрашиваемому широковещательному адресу и линк-локальным широковещательным адресам всех узлов (например, fe80::1:ff01:6317 и ff02::1 соответственно на соединении, к которому подключен интерфейс). В дополнение к линк-локальному адресу, адрес обратной петли (::1 — loopback) будет назначен интерфейсу обратной петли. Также, ::1/128 и ff01::/32 автоматически добавляются в таблицу маршрутизации, а loopback-интерфейс (интерфейс обратной петли) присоединяется к групповому адресу в пределах узла ff01::1.
+
+===== Автоматическая настройка адресов без состояния на узлах
+
+В спецификации IPv6 узлы разделены на две категории: _маршрутизаторы_ и _хосты_. Маршрутизаторы пересылают пакеты, адресованные другим, хосты не пересылают пакеты. Параметр net.inet6.ip6.forwarding определяет, является ли данный узел маршрутизатором или хостом (маршрутизатор, если значение равно 1, хост, если 0).
+
+Когда хост получает Объявление Маршрутизатора (Router Advertisement) от маршрутизатора, он может автоматически настроить себя с помощью автонастройки адреса без сохранения состояния. Это поведение можно контролировать с помощью параметра net.inet6.ip6.accept_rtadv (хост автонастраивается, если значение равно 1). При автонастройке добавляется префикс сетевого адреса для принимающего интерфейса (обычно префикс глобального адреса). Также настраивается маршрут по умолчанию. Маршрутизаторы периодически генерируют пакеты Router Advertisement. Чтобы запросить соседний маршрутизатор сгенерировать RA-пакет, хост может отправить Router Solicitation. Для генерации RS-пакета в любое время используйте команду _rtsol_. Также доступен демон man:rtsold[8]. man:rtsold[8] генерирует Router Solicitation по мере необходимости и отлично подходит для мобильного использования (ноутбуки/лэптопы). Если необходимо игнорировать Router Advertisements, используйте sysctl для установки net.inet6.ip6.accept_rtadv в 0.
+
+Для генерации Router Advertisement от маршрутизатора используйте демон man:rtadvd[8].
+
+Обратите внимание, что спецификация IPv6 предполагает следующие пункты, а случаи несоответствия остаются неуточнёнными:
+
+* Только хосты будут принимать объявления от маршрутизаторов
+* Узлы имеют один сетевой интерфейс (за исключением loopback)
+
+Поэтому не рекомендуется включать net.inet6.ip6.accept_rtadv на маршрутизаторах или многопортовых хостах. Неправильно настроенный узел может вести себя странно (нестандартная конфигурация разрешена для тех, кто хочет провести эксперименты).
+
+Резюмируя настройку sysctl:
+
+[source, bash]
+....
+ accept_rtadv forwarding role of the node
+ --- --- ---
+ 0 0 host (to be manually configured)
+ 0 1 router
+ 1 0 autoconfigured host
+ (spec assumes that host has single
+ interface only, autoconfigured host
+ with multiple interface is
+ out-of-scope)
+ 1 1 invalid, or experimental
+ (out-of-scope of spec)
+....
+
+В RFC2462 есть правило проверки для входящей информации о префиксе в RA, в разделе 5.5.3 (e). Это защищает хосты от злонамеренных (или неправильно настроенных) маршрутизаторов, которые анонсируют очень короткое время жизни префикса. Было обновление от Джима Баунда в рассылке ipngwg (ищите "(ipng 6712)" в архиве), и это обновление Джима реализовано.
+
+См. crossref:ipv6[neighbor-discovery,23.5.1.2] в документе для информации о взаимосвязи между DAD и автонастройкой.
+
+[[gif]]
+==== Универсальный Туннельный Интерфейс
+
+GIF (Generic InterFace) — это псевдоинтерфейс для настроенного туннеля. Подробности описаны в man:gif[4]. В настоящее время
+
+* v6 в v6
+* v6 в v4
+* v4 в v6
+* v4 в v4
+
+доступны. Используйте man:gifconfig[8] для назначения физических (внешних) исходных и конечных адресов интерфейсам gif. Конфигурация, использующая одно семейство адресов для внутреннего и внешнего IP-заголовка (v4 в v4 или v6 в v6), является опасной. Очень легко настроить интерфейсы и таблицы маршрутизации для выполнения бесконечного уровня туннелирования. _Пожалуйста, будьте осторожны_.
+
+gif можно настроить так, чтобы он был дружественным к ECN. Подробнее о дружелюбности к ECN для туннелей см. crossref:ipv6[ipsec-ecn,23.5.4.5], а о настройке — в man:gif[4].
+
+Если вы хотите настроить туннель IPv4-в-IPv6 с интерфейсом gif, внимательно прочитайте man:gif[4]. Вам потребуется удалить линк-локальный адрес IPv6, автоматически назначенный интерфейсу gif.
+
+[[ipv6-sas]]
+==== Выбор исходящего адреса
+
+Текущее правило выбора источника ориентировано на зону (есть несколько исключений — см. ниже). Для заданного адреса назначения исходящий IPv6-адрес выбирается по следующему правилу:
+
+. Если исходящий адрес явно указан пользователем (например, через расширенный API), используется указанный адрес.
+. Если на исходящем интерфейсе назначен адрес (который обычно определяется путем просмотра таблицы маршрутизации) с той же зоной действия, что и адрес назначения, используется этот адрес.
++
+Это наиболее типичный случай.
+. Если нет адреса, удовлетворяющего указанному выше условию, выберите глобальный адрес, назначенный одному из интерфейсов на отправляющем узле.
+. Если нет адреса, удовлетворяющего указанному выше условию, и адрес назначения имеет сайт-локальную зону, выберите сайт-локальный адрес, назначенный одному из интерфейсов на отправляющем узле.
+. Если нет адреса, удовлетворяющего указанному условию, выберите адрес, связанный с записью таблицы маршрутизации для назначения. Это крайняя мера, которая может нарушить границы зоны действия.
+
+Например, ::1 выбирается для ff01::1, fe80:1::200:f8ff:fe01:6317 для fe80:1::2a0:24ff:feab:839b (обратите внимание, что встроенный индекс интерфейса — описанный в crossref:ipv6[ipv6-scope-index,23.5.1.3] — помогает нам выбрать правильный исходный адрес. Эти встроенные индексы не будут передаваться по сети). Если исходящий интерфейс имеет несколько адресов для данной зоны, исходный адрес выбирается на основе наибольшего соответствия (правило 3). Предположим, что 2001:0DB8:808:1:200:f8ff:fe01:6317 и 2001:0DB8:9:124:200:f8ff:fe01:6317 назначены исходящему интерфейсу. 2001:0DB8:808:1:200:f8ff:fe01:6317 выбирается в качестве исходящего адреса для адреса назначения 2001:0DB8:800::1.
+
+Обратите внимание, что приведенное выше правило не документировано в спецификации IPv6. Оно считается элементом, оставленным "на усмотрение реализации". Существуют случаи, когда мы не используем это правило. Один из примеров — установленное TCP-соединение, где мы используем адрес, сохраненный в tcb, в качестве источника. Другой пример — исходящий адрес для Объявления Соседа (Neighbor Advertisement). Согласно спецификации (RFC2461 7.2.2) источник NA должен быть целевым адресом соответствующего NS. В этом случае мы следуем спецификации, а не приведенному выше правилу наибольшего совпадения.
+
+Для новых соединений (когда правило 1 не применяется), устаревшие адреса (адреса с предпочтительным временем жизни = 0) не будут выбираться в качестве исходящего адреса, если доступны другие варианты. Если других вариантов нет, устаревший адрес будет использован в качестве последнего средства. Если есть несколько устаревших адресов, для выбора между ними будет применено указанное выше правило области видимости. Если вы хотите запретить использование устаревших адресов по какой-либо причине, установите параметр net.inet6.ip6.use_deprecated в значение 0. Проблема, связанная с устаревшими адресами, описана в RFC2462 5.5.4 (ПРИМЕЧАНИЕ: в IETF ipngwg ведутся дебаты о том, как использовать "устаревшие" адреса).
+
+[[ipv6-jumbo]]
+==== Джамбо-пакет (Jumbo Payload)
+
+Опция джамбо-пакет типа "от прыжка к прыжку" реализована и может использоваться для отправки IPv6-пакетов с полезной нагрузкой длиной более 65 535 октетов. Однако в настоящее время не поддерживаются физические интерфейсы с MTU более 65 535, поэтому такие нагрузки могут быть только на интерфейсе loopback (т.е. lo0).
+
+Если вы хотите попробовать джамбо-пакеты, сначала необходимо переконфигурировать ядро, чтобы MTU интерфейса loopback превышал 65 535 байт; добавьте следующее в конфигурационный файл ядра:
+
+`options "LARGE_LOMTU" #To test jumbo payload`
+
+и пересоберите новое ядро.
+
+Затем вы можете проверить работу с большими пакетами с помощью команды man:ping[8] с опциями -6, -b и -s. Опция -b необходима для увеличения размера буфера сокета, а опция -s задает длину пакета, которая должна быть больше 65 535. Например, введите следующее:
+
+[source, bash]
+....
+% ping -6 -b 70000 -s 68000 ::1
+....
+
+Спецификация IPv6 требует, чтобы опция Джамбо-пакет не использовалась в пакете, содержащем заголовок фрагмента. Если это условие нарушено, должно быть отправлено ICMPv6 сообщение Parameter Problem отправителю. Спецификация соблюдается, но обычно вы не можете увидеть ICMPv6 ошибку, вызванную этим требованием.
+
+При получении IPv6-пакета проверяется длина кадра и сравнивается с длиной, указанной в поле длины полезной нагрузки заголовка IPv6 или в значении опции Джамбо-пакета, если она присутствует. Если первое значение меньше второго, пакет отбрасывается, и статистика увеличивается. Статистику можно увидеть в выводе команды man:netstat[8] с опцией `-s -p ip6`:
+
+[source, bash]
+....
+% netstat -s -p ip6
+ ip6:
+ (snip)
+ 1 with data size < data length
+....
+
+Итак, ядро не отправляет ICMPv6 ошибку, если ошибочный пакет не является фактически Джамбо-пакетом, то есть его размер пакета превышает 65 535 байт. Как описано выше, в настоящее время не поддерживаются физические интерфейсы с таким огромным MTU, поэтому ICMPv6 ошибка возвращается редко.
+
+В настоящее время поддержка TCP/UDP через jumbogram не реализована. Это связано с отсутствием среды (кроме loopback) для тестирования данной функциональности. Свяжитесь с нами, если вам это необходимо.
+
+IPsec не работает с jumbogram. Это связано с особенностями спецификации, касающимися поддержки AH для джамбограмм (размер заголовка AH влияет на длину полезной нагрузки, что делает крайне сложной аутентификацию входящего пакета с опцией Джамбо-пакет, а также AH).
+
+Существуют фундаментальные проблемы в поддержке *BSD для jumbogram. Мы хотели бы решить их, но нам нужно больше времени для завершения работы. Вот некоторые из них:
+
+* Поле `mbuf pkthdr.len` имеет тип `int` в 4.4BSD, поэтому оно не сможет содержать джамбограмму с длиной > 2G на 32-битных архитектурах CPU. Если мы хотим правильно поддерживать джамбограммы, это поле необходимо расширить, чтобы оно могло содержать 4G + заголовок IPv6 + заголовок канального уровня. Следовательно, его необходимо расширить как минимум до `int64_t` (`u_int32_t` НЕ достаточно).
+
+* Мы ошибочно используем "int" для хранения длины пакета во многих местах. Нам необходимо преобразовать их в более крупный целочисленный тип. Это требует большой осторожности, так как мы можем столкнуться с переполнением во время вычисления длины пакета.
+* Мы ошибочно проверяем поле ip6_plen заголовка IPv6 для определения длины полезной нагрузки пакета в различных местах. Вместо этого следует проверять mbuf pkthdr.len. Функция ip6_input() выполняет проверку корректности опции Джамбо-пакет при вводе, и после этого можно безопасно использовать mbuf pkthdr.len.
+* Код TCP требует тщательного обновления в ряде мест, разумеется.
+
+==== Предотвращение петель при обработке заголовков
+
+Спецификация IPv6 допускает размещение произвольного количества расширений в заголовках пакетов. Если реализовать код обработки пакетов IPv6 так, как реализован код IPv4 в BSD, может произойти переполнение стека ядра из-за длинной цепочки вызовов функций. Код в sys/netinet6 тщательно спроектирован, чтобы избежать переполнения стека ядра, поэтому он определяет собственную структуру переключения протоколов — "struct ip6protosw" (см. [.filename]#netinet6/ip6protosw.h#). Для IPv4 части (sys/netinet) подобных обновлений не было сделано для сохранения совместимости, но в прототип pr_input() внесено небольшое изменение. Поэтому также определена "struct ipprotosw". В результате, если получен пакет IPsec-over-IPv4 с большим количеством заголовков IPsec, стек ядра может переполниться. С IPsec-over-IPv6 такой проблемы нет. (Разумеется, чтобы все эти заголовки IPsec были обработаны, каждый такой заголовок должен пройти все проверки IPsec. Поэтому анонимный злоумышленник не сможет осуществить подобную атаку.)
+
+[[icmpv6]]
+==== ICMPv6
+
+После публикации RFC2463 IETF ipngwg решил запретить ICMPv6 пакеты ошибок для ICMPv6 перенаправлений, чтобы предотвратить ICMPv6 шторм в сетевой среде. Это уже реализовано в ядре.
+
+==== Приложения (Applications)
+
+Для программирования в пользовательском пространстве мы поддерживаем API сокетов IPv6, как указано в RFC2553, RFC2292 и готовящихся интернет-черновиках.
+
+TCP/UDP поверх IPv6 доступны и достаточно стабильны. Вы можете использовать man:telnet[1], man:ftp[1], man:rlogin[1], man:rsh[1], man:ssh[1] и т.д. Эти приложения не зависят от протокола. То есть они автоматически выбирают IPv4 или IPv6 в соответствии с DNS.
+
+==== Внутреннее устройство ядра
+
+В то время как ip_forward() вызывает ip_output(), ip6_forward() напрямую вызывает if_output(), поскольку маршрутизаторы не должны разделять пакеты IPv6 на фрагменты.
+
+ICMPv6 должен содержать исходный пакет по возможности вплоть до 1280 байт. Например, сообщение "Ошибка недоступности порта UDP6/IP6" должно содержать все расширенные заголовки и *неизменённые* заголовки UDP6 и IP6. Таким образом, все функции IP6, кроме TCP, никогда не преобразуют порядок байтов сети в порядок байтов хоста, чтобы сохранить исходный пакет.
+
+Функции tcp_input(), udp6_input() и icmp6_input() не могут предполагать, что заголовок IP6 предшествует транспортным заголовкам из-за наличия расширенных заголовков. Поэтому была реализована in6_cksum() для обработки пакетов, у которых заголовок IP6 и транспортный заголовок не являются непрерывными. Но ни для TCP/IP6, ни для UDP6/IP6 в заголовке нет структуры для расчёта контрольной суммы.
+
+Для удобной обработки заголовка IP6, дополнительных заголовков и транспортных заголовков, от сетевых драйверов теперь требуется хранить пакеты в одном внутреннем mbuf или одном или нескольких внешних mbuf. Типичный старый драйвер подготавливает два внутренних mbuf для данных размером 96–204 байт, однако теперь такие данные пакета хранятся в одном внешнем mbuf.
+
+`netstat -s -p ip6` показывает, соответствует ли ваш драйвер этому требованию. В следующем примере "cce0" нарушает это требование. (Для получения дополнительной информации обратитесь к разделу 2.)
+
+[source, bash]
+....
+Mbuf statistics:
+ 317 one mbuf
+ two or more mbuf::
+ lo0 = 8
+ cce0 = 10
+ 3282 one ext mbuf
+ 0 two or more ext mbuf
+....
+
+Каждая входная функция вызывает IP6_EXTHDR_CHECK в начале, чтобы проверить, является ли область между IP6 и его заголовком непрерывной. IP6_EXTHDR_CHECK вызывает m_pullup() только если mbuf имеет флаг M_LOOP, то есть пакет пришел с интерфейса loopback. m_pullup() никогда не вызывается для пакетов, приходящих с физических сетевых интерфейсов.
+
+Как функции повторной сборки IP, так и IP6 никогда не вызывают m_pullup().
+
+[[ipv6-wildcard-socket]]
+==== IPv4-отображённые адреса и IPv6-сокет с подстановочным адресом
+
+RFC2553 описывает IPv4 отображённые адреса (3.7) и особое поведение IPv6 сокета с привязкой к любому адресу (3.8). Спецификация позволяет вам:
+
+* Принимать IPv4-подключения через сокет с привязкой к подстановочному адресу AF_INET6.
+* Передача IPv4-пакета через сокет AF_INET6 с использованием специальной формы адреса, например ::ffff:10.1.1.1.
+
+но сама спецификация очень сложна и не определяет, как должен вести себя сокетный уровень. Здесь мы называем первую сторону «слушающей», а вторую — «инициирующей» для удобства ссылок.
+
+Вы можете выполнить привязку к подстановочному адресу для обоих семейств адресов на одном и том же порту.
+
+Следующая таблица показывает поведение FreeBSD 4.x.
+
+[source, bash]
+....
+listening side initiating side
+ (AF_INET6 wildcard (connection to ::ffff:10.1.1.1)
+ socket gets IPv4 conn.)
+ --- ---
+FreeBSD 4.x configurable supported
+ default: enabled
+....
+
+Следующие разделы предоставят вам более подробную информацию и объяснят, как можно настроить поведение.
+
+Комментарии о принимающей стороне:
+
+Похоже, что в RFC2553 слишком мало сказано о проблеме привязки к подстановочному адресу, особенно о вопросе пространства портов, режиме отказа и взаимосвязи между AF_INET/INET6 wildcard bind. Может быть несколько различных интерпретаций этого RFC, которые соответствуют ему, но ведут себя по-разному. Поэтому для создания переносимых приложений не следует делать никаких предположений о поведении в ядре. Использование man:getaddrinfo[3] является наиболее безопасным способом. Вопросы пространства номеров портов и привязки к подстановочному адресу подробно обсуждались в рассылке ipv6imp в середине марта 1999 года, и похоже, что конкретного консенсуса нет (то есть, остается на усмотрение реализаторов). Возможно, вам стоит проверить архивы рассылки.
+
+Если серверное приложение хочет принимать IPv4 и IPv6 соединения, есть два варианта.
+
+Один из способов — использование сокетов AF_INET и AF_INET6 (вам понадобятся два сокета). Используйте man:getaddrinfo[3] с AI_PASSIVE в ai_flags, а также man:socket[2] и man:bind[2] для всех возвращённых адресов. Открыв несколько сокетов, вы можете принимать соединения сокетом соответствующей адресной семьи. IPv4-соединения будут приниматься сокетом AF_INET, а IPv6-соединения — сокетом AF_INET6.
+
+Еще один способ — использование одного сокета с универсальной привязкой AF_INET6. Используйте man:getaddrinfo[3] с AI_PASSIVE в ai_flags и AF_INET6 в ai_family, установив первый аргумент hostname в NULL. Затем используйте man:socket[2] и man:bind[2] для адреса, который был возвращен. (должен быть неспецифицированный адрес IPv6). Через этот один сокет можно принимать пакеты как IPv4, так и IPv6.
+
+Для поддержки только IPv6-трафика на AF_INET6-сокете с привязкой к любому адресу переносимым способом всегда проверяйте адрес узла при установке соединения с AF_INET6-сокетом в режиме прослушивания. Если адрес является IPv4-отображённым, возможно, стоит отклонить соединение. Это условие можно проверить с помощью макроса IN6_IS_ADDR_V4MAPPED().
+
+Для более простого решения этой задачи существует зависящий от системы параметр man:setsockopt[2] под названием IPV6_BINDV6ONLY, используемый следующим образом.
+
+[.programlisting]
+....
+ int on;
+
+ setsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
+ (char *)&on, sizeof (on)) < 0));
+....
+
+При успешном вызове этот сокет будет принимать только IPv6-пакеты.
+
+Комментарии о стороне инициатора:
+
+Совет разработчикам приложений: для создания переносимого IPv6-приложения (которое работает на различных IPv6-ядрах), мы считаем, что следующие моменты являются ключом к успеху:
+
+* НИКОГДА не используйте жёстко заданные AF_INET или AF_INET6.
+* Используйте man:getaddrinfo[3] и man:getnameinfo[3] во всей системе. Никогда не используйте gethostby*(), getaddrby*(), inet_*() или getipnodeby*(). (Для облегчения обновления существующих приложений для поддержки IPv6 иногда может быть полезен getipnodeby*(). Но по возможности старайтесь переписать код для использования man:getaddrinfo[3] и man:getnameinfo[3].)
+* Если вы хотите подключиться к назначению, используйте man:getaddrinfo[3] и попробуйте все возвращённые назначения, как это делает man:telnet[1].
+* Некоторые реализации стека IPv6 поставляются с некорректной man:getaddrinfo[3]. Включите минимально рабочую версию в ваше приложение и используйте её в крайнем случае.
+
+Если вы хотите использовать сокет AF_INET6 для исходящих подключений как IPv4, так и IPv6, вам потребуется использовать man:getipnodebyname[3]. Если вы хотите обновить существующее приложение для поддержки IPv6 с минимальными усилиями, можно выбрать этот подход. Однако учтите, что это временное решение, поскольку man:getipnodebyname[3] сам по себе не рекомендуется, так как он вообще не обрабатывает IPv6-адреса с зоной. Для разрешения IPv6-имён предпочтительным API является man:getaddrinfo[3]. Поэтому вам следует переписать ваше приложение для использования man:getaddrinfo[3], когда у вас будет время это сделать.
+
+При написании приложений, которые устанавливают исходящие соединения, история становится намного проще, если рассматривать AF_INET и AF_INET6 как совершенно отдельные семейства адресов. Проблемы с {set,get}sockopt упрощаются, проблемы с DNS также станут проще. Мы не рекомендуем полагаться на IPv4-отображённые адреса.
+
+===== унифицированный код tcp и inpcb
+
+FreeBSD 4.x использует общий код tcp для IPv4 и IPv6 (из sys/netinet/tcp*) и раздельный код udp4/6. В нем используется унифицированная структура inpcb.
+
+Платформа может быть настроена для поддержки IPv4-отображённых адресов. Конфигурация ядра кратко описана ниже:
+
+* По умолчанию сокет AF_INET6 может принимать IPv4-соединения при определённых условиях и инициировать соединение с IPv4-адресами, встроенными в IPv4-отображённые IPv6-адреса.
+* Вы можете отключить это во всей системе с помощью sysctl, как показано ниже.
++
+`sysctl net.inet6.ip6.mapped_addr=0`
+
+====== Сторона, принимающая соединения
+
+Каждый сокет может быть настроен для поддержки специальной привязки к подстановочному адресу AF_INET6 (включено по умолчанию). Это можно отключить для каждого отдельного сокета с помощью man:setsockopt[2], как показано ниже.
+
+[.programlisting]
+....
+ int on;
+
+ setsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,
+ (char *)&on, sizeof (on)) < 0));
+....
+
+Сокет с универсальной привязкой AF_INET6 перехватывает IPv4-подключение тогда и только тогда, когда выполнены следующие условия:
+
+* нет AF_INET сокета, соответствующего IPv4-подключению
+* Сокет AF_INET6 настроен на прием IPv4-трафика, т.е., getsockopt(IPV6_BINDV6ONLY) возвращает 0.
+
+Нет проблем с порядком открытия/закрытия.
+
+====== Инициирующая сторона
+
+FreeBSD 4.x поддерживает исходящее соединение с IPv4-отображённым адресом (::ffff:10.1.1.1), если узел настроен на поддержку IPv4-отображённых адресов.
+
+==== sockaddr_storage
+
+Когда RFC2553 был близок к завершению, велись дискуссии о том, как называть элементы структуры `sockaddr_storage`. Одно предложение заключалось в добавлении "__" перед именами элементов (например, "__ss_len"), так как к ним не следует обращаться напрямую. Другое предложение было не добавлять префикс (например, "ss_len"), поскольку необходимо прямое обращение к этим элементам. Четкого консенсуса по этому вопросу достигнуто не было.
+
+В результате, RFC2553 определяет структуру sockaddr_storage следующим образом:
+
+[.programlisting]
+....
+ struct sockaddr_storage {
+ u_char __ss_len; /* address length */
+ u_char __ss_family; /* address family */
+ /* and bunch of padding */
+ };
+....
+
+Напротив, черновик XNET определяет следующее:
+
+[.programlisting]
+....
+ struct sockaddr_storage {
+ u_char ss_len; /* address length */
+ u_char ss_family; /* address family */
+ /* and bunch of padding */
+ };
+....
+
+В декабре 1999 года было согласовано, что RFC2553bis должен принять последнее (XNET) определение.
+
+Текущая реализация соответствует определению XNET, основанному на обсуждении RFC2553bis.
+
+Если вы рассмотрите несколько реализаций IPv6, то сможете увидеть оба определения. Для программиста в пользовательском пространстве наиболее переносимый способ работы с этим:
+
+. с помощью GNU autoconf сконфигурировать доступ к `ss_family` и/или `ss_len` на целевой платформе,
+. добавить -Dss_family=__ss_family для унификации всех использований (включая заголовочный файл) __ss_family, или
+. никогда не трогайте __ss_family. Приводите к sockaddr * и используйте sa_family, например:
++
+[.programlisting]
+....
+ struct sockaddr_storage ss;
+ family = ((struct sockaddr *)&ss)->sa_family
+....
+
+=== Драйверы сетевых устройств
+
+В настоящее время следующие два пункта должны поддерживаться стандартными драйверами:
+
+. Требование к кластеризации mbuf. В этом стабильном выпуске мы изменили MINCLSIZE на MHLEN+1 для всех операционных систем, чтобы все драйверы работали так, как мы ожидаем.
+. многоадресная рассылка (multicast). Если man:ifmcstat[8] не выводит ни одной многоадресной группы для интерфейса, этот интерфейс необходимо исправить.
+
+Если какие-либо драйверы не поддерживают требования, то их нельзя использовать для IPv6 и/или IPsec-связи. Если вы обнаружили проблему с вашей картой при использовании IPv6/IPsec, пожалуйста, сообщите об этом в {freebsd-bugs}.
+
+(NOTE: Раньше мы требовали, чтобы все драйверы PCMCIA содержали вызов in6_ifattach(). Теперь такого требования нет)
+
+=== Транслятор
+
+Мы классифицируем трансляторы IPv4/IPv6 на 4 типа:
+
+* _Транслятор А_ --- Он используется на раннем этапе перехода, чтобы позволить установить соединение с IPv6-хоста на IPv6-острове к IPv4-хосту в IPv4-океане.
+* _Транслятор Б_ --- Он используется на раннем этапе перехода, чтобы обеспечить возможность установления соединения с IPv6-узлом на IPv6-острове от IPv4-узла в IPv4-океане.
+* _Транслятор C_ --- Он используется на позднем этапе перехода, чтобы сделать возможным установление соединения с IPv6-узлом в IPv6-океане от IPv4-узла на IPv4-острове.
+* _Транслятор D_ --- Он используется на позднем этапе перехода, чтобы сделать возможным установление соединения с IPv6-хоста в IPv6-океане на IPv4-хост на IPv4-острове.
+
+[[ipsec-implementation]]
+=== IPsec
+
+IPsec состоит в основном из трех компонент.
+
+. Управление политиками
+. Управление ключами
+. Обработка AH и ESP
+
+==== Управление политиками
+
+Ядро реализует экспериментальный код управления политикой безопасности. Существует два способа управления политикой безопасности. Первый — настройка политики для каждого сокета с помощью man:setsockopt[2]. В этом случае конфигурация политики описана в man:ipsec_set_policy[3]. Второй способ — настройка политики на основе фильтра пакетов ядра с использованием интерфейса PF_KEY через man:setkey[8].
+
+Запись политики не переупорядочивается вместе со своими индексами, поэтому порядок добавления записей очень важен.
+
+==== Управление ключами
+
+Код управления ключами, реализованный в этом наборе (sys/netkey), представляет собой собственную реализацию PFKEY v2. Это соответствует RFC2367.
+
+В комплект включена "домашняя" реализация демона IKE — "racoon" (kame/kame/racoon). Обычно вам потребуется запустить racoon в качестве демона, затем настроить политику для требования ключей (например, `ping -P 'out ipsec esp/transport//use'`). Ядро будет связываться с демоном racoon по мере необходимости для обмена ключами.
+
+==== Обработка AH и ESP
+
+Модуль IPsec реализован в виде "хуков" к стандартной обработке IPv4/IPv6. При отправке пакета функция ip{,6}_output() проверяет, требуется ли обработка ESP/AH, путем поиска соответствующей базы данных политик безопасности (SPD — Security Policy Database). Если ESP/AH необходим, вызывается {esp,ah}{4,6}_output(), и mbuf соответствующим образом обновляется. При получении пакета функция {esp,ah}4_input() вызывается на основе номера протокола, т.е. (*inetsw[proto])(). {esp,ah}4_input() расшифровывает/проверяет подлинность пакета, а также удаляет цепочку заголовков и выравнивание для ESP/AH. Безопасно удалять заголовок ESP/AH при получении пакета, так как полученный пакет никогда не будет использоваться в "сыром" виде.
+
+Использование ESP/AH влияет на эффективный размер сегмента данных TCP4/6 из-за дополнительных цепочечных заголовков, вставляемых ESP/AH. Наш код учитывает этот случай.
+
+Основные криптографические функции можно найти в директории `sys/crypto`. Преобразования ESP/AH перечислены в `{esp,ah}_core.c` с обёрточными функциями. Если вы хотите добавить какой-либо алгоритм, добавьте обёрточную функцию в `{esp,ah}_core.c` и поместите код вашего криптографического алгоритма в `sys/crypto`.
+
+Режим туннеля частично поддерживается в этом выпуске со следующими ограничениями:
+
+* Туннель IPsec не объединён с универсальным туннельным интерфейсом GIF. Это требует особой осторожности, так как может возникнуть бесконечный цикл между `ip_output()` и `tunnelifp->if_output()`. Мнения расходятся относительно того, лучше ли их объединить или нет.
+* MTU и бит Don't Fragment (IPv4) требуют дополнительной проверки, но в основном работают нормально.
+* Модель аутентификации для туннеля AH должна быть пересмотрена. Нам потребуется улучшить механизм управления политиками в конечном итоге.
+
+==== Соответствие RFC и ID
+
+Код IPsec в ядре соответствует (или пытается соответствовать) следующим стандартам:
+
+Спецификация "старого IPsec", описанная в [.filename]#rfc182[5-9].txt#
+
+Спецификация "new IPsec" описана в [.filename]#rfc240[1-6].txt#, [.filename]#rfc241[01].txt#, [.filename]#rfc2451.txt# и [.filename]#draft-mcdonald-simple-ipsec-api-01.txt# (черновик устарел, но его можно взять по ссылке: link:ftp://ftp.kame.net/pub/internet-drafts/[ ftp://ftp.kame.net/pub/internet-drafts/]). (ПРИМЕЧАНИЕ: Спецификации IKE, [.filename]#rfc241[7-9].txt#, реализованы в пользовательском пространстве в виде демона IKE "racoon")
+
+В настоящее время поддерживаются следующие алгоритмы:
+
+* old IPsec AH
+
+** нулевая криптографическая контрольная сумма (нет документа, только для отладки)
+** MD5 с ключом и с 128-битной криптографической контрольной суммой ([.filename]#rfc1828.txt#)
+** SHA1 с ключом и с 128-битной криптографической контрольной суммой (без документа)
+** HMAC MD5 с 128-битной криптографической контрольной суммой ([.filename]#rfc2085.txt#)
+** HMAC SHA1 с 128-битной криптографической контрольной суммой (без документа)
+
+* old IPsec ESP
+
+** нулевое шифрование (нет документа, аналогично [.filename]#rfc2410.txt#)
+** Режим DES-CBC ([.filename]#rfc1829.txt#)
+
+* new IPsec AH
+
+** нулевая криптографическая контрольная сумма (нет документа, только для отладки)
+** MD5 с ключом и с 96-битной криптографической контрольной суммой (нет документа)
+** SHA1 с ключом и с 96-битной криптографической контрольной суммой (без документа)
+** HMAC MD5 с 96-битной криптографической контрольной суммой ([.filename]#rfc2403.txt#)
+** HMAC SHA1 с 96-битной криптографической контрольной суммой ([.filename]#rfc2404.txt#)
+
+* new IPsec ESP
+
+** нулевое шифрование ([.filename]#rfc2410.txt#)
+** DES-CBC с производным IV ([.filename]#draft-ietf-ipsec-ciph-des-derived-01.txt#, черновик истек)
+** DES-CBC с явным вектором инициализации ([.filename]#rfc2405.txt#)
+** 3DES-CBC с явным вектором инициализации ([.filename]#rfc2451.txt#)
+** BLOWFISH CBC ([.filename]#rfc2451.txt#)
+** CAST128 CBC ([.filename]#rfc2451.txt#)
+** RC5 CBC ([.filename]#rfc2451.txt#)
+** каждый из вышеперечисленных может быть объединён с:
+
+*** Аутентификация ESP с HMAC-MD5 (96 бит)
+*** Аутентификация ESP с HMAC-SHA1(96 бит)
+
+Следующие алгоритмы НЕ поддерживаются:
+
+* old IPsec AH
+
+** HMAC MD5 с 128-битной криптографической контрольной суммой + 64-битная защита от повторного воспроизведения ([.filename]#rfc2085.txt#)
+** SHA1 с ключом и с 160-битной криптографической контрольной суммой +
+32-битное дополнение ([.filename]#rfc1852.txt#)
+
+IPsec (в ядре) и IKE (в пользовательском пространстве как "racoon") были протестированы на нескольких мероприятиях по тестированию взаимодействия и известно, что они хорошо работают со многими другими реализациями. Кроме того, текущая реализация IPsec поддерживает довольно широкий спектр криптографических алгоритмов IPsec, описанных в RFC (мы поддерживаем только алгоритмы без проблем с интеллектуальной собственностью).
+
+[[ipsec-ecn]]
+==== Учет ECN в IPsec-туннелях
+
+Поддерживается ECN-совместимый IPsec-туннель, как описано в [.filename]#draft-ipsec-ecn-00.txt#.
+
+Обычный IPsec-туннель описан в RFC2401. При инкапсуляции поле TOS IPv4 (или поле класса трафика IPv6) копируется из внутреннего IP-заголовка во внешний IP-заголовок. При декапсуляции внешний IP-заголовок просто отбрасывается. Правило декапсуляции несовместимо с ECN, так как бит ECN в поле TOS/класса трафика внешнего IP-заголовка будет потерян.
+
+Чтобы сделать IPsec-туннель дружественным к ECN, следует изменить процедуры инкапсуляции и декапсуляции. Это описано в http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt[ http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt], глава 3.
+
+Реализация туннеля IPsec может обеспечить три варианта поведения, в зависимости от значения параметра `net.inet.ipsec.ecn` (или `net.inet6.ipsec6.ecn`):
+
+* RFC2401: отсутствие учета ECN (значение sysctl -1)
+* ECN запрещён (значение sysctl 0)
+* ECN разрешён (значение sysctl 1)
+
+Обратите внимание, что поведение настраивается для каждого узла, а не для каждой SA (в draft-ipsec-ecn-00 предлагается настройка для каждой SA, но это кажется излишним).
+
+Поведение можно обобщить следующим образом (подробности см. в исходном коде):
+
+[source, bash]
+....
+encapsulate decapsulate
+ --- ---
+RFC2401 copy all TOS bits drop TOS bits on outer
+ from inner to outer. (use inner TOS bits as is)
+
+ECN forbidden copy TOS bits except for ECN drop TOS bits on outer
+ (masked with 0xfc) from inner (use inner TOS bits as is)
+ to outer. set ECN bits to 0.
+
+ECN allowed copy TOS bits except for ECN use inner TOS bits with some
+ CE (masked with 0xfe) from change. if outer ECN CE bit
+ inner to outer. is 1, enable ECN CE bit on
+ set ECN CE bit to 0. the inner.
+....
+
+Общая стратегия настройки выглядит следующим образом:
+
+* если оба конечных пункта туннеля IPsec поддерживают поведение, дружественное к ECN, лучше настроить оба конца на "разрешено ECN" (значение sysctl 1).
+* если другая сторона очень строга к биту TOS, используйте "RFC2401" (значение sysctl -1).
+* в остальных случаях используйте "ECN запрещено" (значение sysctl 0).
+
+Поведение по умолчанию — "ECN запрещён" (значение sysctl 0).
+
+Для получения дополнительной информации обратитесь к:
+
+http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt[ http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt], RFC2481 (Явное Уведомление о Перегрузке), src/sys/netinet6/{ah,esp}_input.c
+
+(Благодарности Kenjiro Cho mailto:kjc@csl.sony.co.jp[kjc@csl.sony.co.jp] за детальный анализ)
+
+==== Совместимость
+
+Вот некоторые из платформ, на которых код KAME тестировал взаимодействие IPsec/IKE в прошлом. Обратите внимание, что обе стороны могли изменить свои реализации, поэтому используйте следующий список только в справочных целях.
+
+Altiga, Ashley-laurent (vpcom.com), Data Fellows (F-Secure), Ericsson ACC, FreeS/WAN, HITACHI, IBM AIX(R), IIJ, Intel, Microsoft(R) Windows NT(R), NIST (linux IPsec + plutoplus), Netscreen, OpenBSD, RedCreek, Routerware, SSH, Secure Computing, Soliton, Toshiba, VPNet, Yamaha RT100i
diff --git a/documentation/content/ru/books/developers-handbook/ipv6/_index.po b/documentation/content/ru/books/developers-handbook/ipv6/_index.po
new file mode 100644
index 0000000000..d842459698
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/ipv6/_index.po
@@ -0,0 +1,2818 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-23 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookipv6_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:16
+#, no-wrap
+msgid "IPv6 Internals"
+msgstr "Внутреннее устройство IPv6"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:1
+#, no-wrap
+msgid "Chapter 8. IPv6 Internals"
+msgstr "Глава 8. Внутреннее устройство IPv6"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:54
+#, no-wrap
+msgid "IPv6/IPsec Implementation"
+msgstr "Реализация IPv6/IPsec"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:58
+msgid ""
+"This section should explain IPv6 and IPsec related implementation "
+"internals. These functionalities are derived from http://www.kame.net/[KAME "
+"project]"
+msgstr ""
+"В этом разделе мы объясним внутреннюю реализацию, связанную с IPv6 и IPsec. "
+"Данная функциональность заимствована из http://www.kame.net/[проекта KAME]"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:60
+#, no-wrap
+msgid "IPv6"
+msgstr "IPv6"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:62
+#, no-wrap
+msgid "Conformance"
+msgstr "Соответствие"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:66
+msgid ""
+"The IPv6 related functions conforms, or tries to conform to the latest set "
+"of IPv6 specifications. For future reference we list some of the relevant "
+"documents below (_NOTE_: this is not a complete list - this is too hard to "
+"maintain...)."
+msgstr ""
+"Функции, связанные с IPv6, соответствуют или пытаются соответствовать "
+"последнему набору спецификаций IPv6. Для дальнейшего использования мы "
+"приводим некоторые из соответствующих документов ниже (_ПРИМЕЧАНИЕ_: это не "
+"полный список — его слишком сложно поддерживать...)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:68
+msgid ""
+"For details please refer to specific chapter in the document, RFCs, manual "
+"pages, or comments in the source code."
+msgstr ""
+"Для подробностей обратитесь к соответствующей главе документа, RFC, "
+"страницам Справосника или комментариям в исходном коде."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:72
+msgid ""
+"Conformance tests have been performed on the KAME STABLE kit at TAHI "
+"project. Results can be viewed at http://www.tahi.org/report/KAME/[http://"
+"www.tahi.org/report/KAME/]. We also attended University of New Hampshire "
+"IOL tests (http://www.iol.unh.edu/[http://www.iol.unh.edu/]) in the past, "
+"with our past snapshots."
+msgstr ""
+"Тесты на соответствие стандартам были проведены для KAME STABLE в проекте "
+"TAHI. Результаты можно посмотреть по ссылке http://www.tahi.org/report/KAME/"
+"[http://www.tahi.org/report/KAME/]. Мы также участвовали в тестах IOL "
+"Университета Нью-Гэмпшира (http://www.iol.unh.edu/[http://www.iol.unh.edu/]) "
+"в прошлом, используя наши предыдущие версии."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:74
+msgid "RFC1639: FTP Operation Over Big Address Records (FOOBAR)"
+msgstr "RFC1639: FTP Operation Over Big Address Records (FOOBAR)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:76
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:113
+msgid ""
+"RFC2428 is preferred over RFC1639. FTP clients will first try RFC2428, then "
+"RFC1639 if failed."
+msgstr ""
+"RFC2428 предпочтительнее RFC1639. FTP-клиенты сначала попробуют RFC2428, "
+"затем RFC1639 в случае неудачи."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:78
+msgid "RFC1886: DNS Extensions to support IPv6"
+msgstr "RFC1886: DNS Extensions to support IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:79
+msgid "RFC1933: Transition Mechanisms for IPv6 Hosts and Routers"
+msgstr "RFC1933: Transition Mechanisms for IPv6 Hosts and Routers"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:81
+msgid "IPv4 compatible address is not supported."
+msgstr "IPv4-совместимый адрес не поддерживается."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:82
+msgid "automatic tunneling (described in 4.3 of this RFC) is not supported."
+msgstr ""
+"автоматическое туннелирование (описано в разделе 4.3 данного RFC) не "
+"поддерживается."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:84
+msgid ""
+"man:gif[4] interface implements IPv[46]-over-IPv[46] tunnel in a generic "
+"way, and it covers \"configured tunnel\" described in the spec. See "
+"crossref:ipv6[gif,23.5.1.5] in this document for details."
+msgstr ""
+"man:gif[4] интерфейс реализует IPv[46]-поверх-IPv[46] туннель в общем виде и "
+"включает \"настроенный туннель\", описанный в спецификации. Подробности см. "
+"в crossref:ipv6[gif,23.5.1.5] этого документа."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:86
+msgid "RFC1981: Path MTU Discovery for IPv6"
+msgstr "RFC1981: Path MTU Discovery for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:87
+msgid "RFC2080: RIPng for IPv6"
+msgstr "RFC2080: RIPng for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:89
+msgid "usr.sbin/route6d support this."
+msgstr "usr.sbin/route6d это поддерживает."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:91
+msgid "RFC2292: Advanced Sockets API for IPv6"
+msgstr "RFC2292: Advanced Sockets API for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:93
+msgid ""
+"For supported library functions/kernel APIs, see [.filename]#sys/netinet6/"
+"ADVAPI#."
+msgstr ""
+"Для поддерживаемых функций библиотек/API ядра см. [.filename]#sys/netinet6/"
+"ADVAPI#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:95
+msgid "RFC2362: Protocol Independent Multicast-Sparse Mode (PIM-SM)"
+msgstr "RFC2362: Protocol Independent Multicast-Sparse Mode (PIM-SM)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:97
+msgid ""
+"RFC2362 defines packet formats for PIM-SM. [.filename]#draft-ietf-pim-"
+"ipv6-01.txt# is written based on this."
+msgstr ""
+"RFC2362 определяет форматы пакетов для PIM-SM. [.filename]#draft-ietf-pim-"
+"ipv6-01.txt# написан на основе этого."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:99
+msgid "RFC2373: IPv6 Addressing Architecture"
+msgstr "RFC2373: IPv6 Addressing Architecture"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:101
+msgid ""
+"supports node required addresses, and conforms to the scope requirement."
+msgstr ""
+"поддерживает обязательные адреса узлов и соответствует требованиям области "
+"видимости."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:103
+msgid "RFC2374: An IPv6 Aggregatable Global Unicast Address Format"
+msgstr "RFC2374: An IPv6 Aggregatable Global Unicast Address Format"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:105
+msgid "supports 64-bit length of Interface ID."
+msgstr "поддерживает 64-битную длину Идентификатора Интерфейса."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:107
+msgid "RFC2375: IPv6 Multicast Address Assignments"
+msgstr "RFC2375: IPv6 Multicast Address Assignments"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:109
+msgid "Userland applications use the well-known addresses assigned in the RFC."
+msgstr ""
+"Пользовательские приложения используют общеизвестные адреса, назначенные в "
+"RFC."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:111
+msgid "RFC2428: FTP Extensions for IPv6 and NATs"
+msgstr "RFC2428: FTP Extensions for IPv6 and NATs"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:115
+msgid "RFC2460: IPv6 specification"
+msgstr "RFC2460: IPv6 specification"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:116
+msgid "RFC2461: Neighbor discovery for IPv6"
+msgstr "RFC2461: Neighbor discovery for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:118
+msgid ""
+"See crossref:ipv6[neighbor-discovery,23.5.1.2] in this document for details."
+msgstr ""
+"См. crossref:ipv6[neighbor-discovery,23.5.1.2] в этом документе для "
+"получения подробностей."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:120
+msgid "RFC2462: IPv6 Stateless Address Autoconfiguration"
+msgstr "RFC2462: IPv6 Stateless Address Autoconfiguration"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:122
+msgid "See crossref:ipv6[ipv6-pnp,23.5.1.4] in this document for details."
+msgstr ""
+"См. crossref:ipv6[ipv6-pnp,23.5.1.4] в этом документе для получения "
+"подробностей."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:124
+msgid "RFC2463: ICMPv6 for IPv6 specification"
+msgstr "RFC2463: ICMPv6 for IPv6 specification"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:126
+msgid "See crossref:ipv6[icmpv6,23.5.1.9] in this document for details."
+msgstr ""
+"См. crossref:ipv6[icmpv6,23.5.1.9] в этом документе для получения "
+"подробностей."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:128
+msgid "RFC2464: Transmission of IPv6 Packets over Ethernet Networks"
+msgstr "RFC2464: Transmission of IPv6 Packets over Ethernet Networks"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:129
+msgid "RFC2465: MIB for IPv6: Textual Conventions and General Group"
+msgstr "RFC2465: MIB for IPv6: Textual Conventions and General Group"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:131
+msgid ""
+"Necessary statistics are gathered by the kernel. Actual IPv6 MIB support is "
+"provided as a patchkit for ucd-snmp."
+msgstr ""
+"Необходимая статистика собирается ядром. Фактическая поддержка MIB для IPv6 "
+"предоставляется в виде набора патчей для ucd-snmp."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:133
+msgid "RFC2466: MIB for IPv6: ICMPv6 group"
+msgstr "RFC2466: MIB for IPv6: ICMPv6 group"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:135
+msgid ""
+"Necessary statistics are gathered by the kernel. Actual IPv6 MIB support is "
+"provided as patchkit for ucd-snmp."
+msgstr ""
+"Необходимая статистика собирается ядром. Фактическая поддержка MIB IPv6 "
+"предоставляется в виде патча для ucd-snmp."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:137
+msgid "RFC2467: Transmission of IPv6 Packets over FDDI Networks"
+msgstr "RFC2467: Transmission of IPv6 Packets over FDDI Networks"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:138
+msgid "RFC2497: Transmission of IPv6 packet over ARCnet Networks"
+msgstr "RFC2497: Transmission of IPv6 packet over ARCnet Networks"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:139
+msgid "RFC2553: Basic Socket Interface Extensions for IPv6"
+msgstr "RFC2553: Basic Socket Interface Extensions for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:142
+msgid ""
+"IPv4 mapped address (3.7) and special behavior of IPv6 wildcard bind socket "
+"(3.8) are supported. See crossref:ipv6[ipv6-wildcard-socket,23.5.1.12] in "
+"this document for details."
+msgstr ""
+"Отображаемый адрес IPv4 (3.7) и особое поведение сокета с привязкой по "
+"шаблону IPv6 (3.8) поддерживаются. Подробности см. в разделе "
+"crossref:ipv6[ipv6-wildcard-socket,23.5.1.12] этого документа."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:144
+msgid "RFC2675: IPv6 Jumbograms"
+msgstr "RFC2675: IPv6 Jumbograms"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:146
+msgid "See crossref:ipv6[ipv6-jumbo,23.5.1.7] in this document for details."
+msgstr ""
+"См. crossref:ipv6[ipv6-jumbo,23.5.1.7] в этом документе для получения "
+"подробностей."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:148
+msgid "RFC2710: Multicast Listener Discovery for IPv6"
+msgstr "RFC2710: Multicast Listener Discovery for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:149
+msgid "RFC2711: IPv6 router alert option"
+msgstr "RFC2711: IPv6 router alert option"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:150
+msgid ""
+"[.filename]#draft-ietf-ipngwg-router-renum-08#: Router renumbering for IPv6"
+msgstr ""
+"[.filename]#draft-ietf-ipngwg-router-renum-08#: Перенумерация "
+"маршрутизаторов для IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:151
+msgid ""
+"[.filename]#draft-ietf-ipngwg-icmp-namelookups-02#: IPv6 Name Lookups "
+"Through ICMP"
+msgstr ""
+"[.filename]#draft-ietf-ipngwg-icmp-namelookups-02#: Поиск имен через ICMP в "
+"IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:152
+msgid ""
+"[.filename]#draft-ietf-ipngwg-icmp-name-lookups-03#: IPv6 Name Lookups "
+"Through ICMP"
+msgstr ""
+"[.filename]#draft-ietf-ipngwg-icmp-name-lookups-03#: Поиск имен IPv6 через "
+"ICMP"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:153
+msgid "[.filename]#draft-ietf-pim-ipv6-01.txt#: PIM for IPv6"
+msgstr "[.filename]#draft-ietf-pim-ipv6-01.txt#: PIM for IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:155
+msgid ""
+"man:pim6dd[8] implements dense mode. man:pim6sd[8] implements sparse mode."
+msgstr ""
+"man:pim6dd[8] реализует плотный режим. man:pim6sd[8] реализует разреженный "
+"режим."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:157
+msgid ""
+"[.filename]#draft-itojun-ipv6-tcp-to-anycast-00#: Disconnecting TCP "
+"connection toward IPv6 anycast address"
+msgstr ""
+"[.filename]#draft-itojun-ipv6-tcp-to-anycast-00#: Разрыв TCP-соединения с "
+"anycast-адресом IPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:158
+msgid "[.filename]#draft-yamamoto-wideipv6-comm-model-00#"
+msgstr "[.filename]#draft-yamamoto-wideipv6-comm-model-00#"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:160
+msgid "See crossref:ipv6[ipv6-sas,23.5.1.6] in this document for details."
+msgstr ""
+"См. crossref:ipv6[ipv6-sas,23.5.1.6] в этом документе для более подробной "
+"информации."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:162
+msgid ""
+"[.filename]#draft-ietf-ipngwg-scopedaddr-format-00.txt#: An Extension of "
+"Format for IPv6 Scoped Addresses"
+msgstr ""
+"[.filename]#draft-ietf-ipngwg-scopedaddr-format-00.txt#: Расширение формата "
+"для адресов с областью действия IPv6"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:164
+#, no-wrap
+msgid "Neighbor Discovery"
+msgstr "Функция \"Обнаружение соседей\""
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:169
+msgid ""
+"Neighbor Discovery is fairly stable. Currently Address Resolution, "
+"Duplicated Address Detection, and Neighbor Unreachability Detection are "
+"supported. In the near future we will be adding Proxy Neighbor "
+"Advertisement support in the kernel and Unsolicited Neighbor Advertisement "
+"transmission command as admin tool."
+msgstr ""
+"Обнаружение соседей достаточно стабильно. В настоящее время поддерживаются "
+"следующие функции: определение адреса (Address Resolution), обнаружение "
+"дублирования адресов (DAD — Duplicated Address Detection) и обнаружение "
+"недоступности соседей (Neighbor Unreachability Detection). В ближайшем "
+"будущем мы добавим поддержку прокси-объявлений соседей (Proxy Neighbor "
+"Advertisement) в ядро и команду передачи непрошенных объявлений соседей "
+"(Unsolicited Neighbor Advertisement) в качестве инструмента администратора."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:174
+msgid ""
+"If DAD fails, the address will be marked \"duplicated\" and message will be "
+"generated to syslog (and usually to console). The \"duplicated\" mark can "
+"be checked with man:ifconfig[8]. It is administrators' responsibility to "
+"check for and recover from DAD failures. The behavior should be improved in "
+"the near future."
+msgstr ""
+"Если DAD завершается неудачно, адрес будет помечен как \"дублированный\" "
+"(duplicated), и сообщение будет записано в syslog (а также обычно выведено "
+"на консоль). Метку \"дублированный\" можно проверить с помощью "
+"man:ifconfig[8]. Обязанность администратора — проверять и устранять сбои "
+"DAD. В ближайшем будущем поведение должно быть улучшено."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:178
+msgid ""
+"Some of the network driver loops multicast packets back to itself, even if "
+"instructed not to do so (especially in promiscuous mode). In such cases DAD "
+"may fail, because DAD engine sees inbound NS packet (actually from the node "
+"itself) and considers it as a sign of duplicate. You may want to look at "
+"#if condition marked \"heuristics\" in sys/netinet6/"
+"nd6_nbr.c:nd6_dad_timer() as workaround (note that the code fragment in "
+"\"heuristics\" section is not spec conformant)."
+msgstr ""
+"Некоторые сетевые драйверы закольцовывают multicast-пакеты обратно на себя, "
+"даже если им указано так не делать (особенно в promiscuous mode). В таких "
+"случаях DAD может завершиться неудачей, так как механизм DAD видит входящий "
+"NS-пакет (на самом деле от самого узла) и считает его признаком дубликата. В "
+"качестве обходного решения можно рассмотреть условие #if с пометкой "
+"\"heuristics\" в sys/netinet6/nd6_nbr.c:nd6_dad_timer() (обратите внимание, "
+"что фрагмент кода в разделе \"heuristics\" не соответствует спецификации)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:180
+msgid ""
+"Neighbor Discovery specification (RFC2461) does not talk about neighbor "
+"cache handling in the following cases:"
+msgstr ""
+"Спецификация обнаружения соседей (RFC2461) не рассматривает обработку кэша "
+"соседей в следующих случаях:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:182
+msgid ""
+"when there was no neighbor cache entry, node received unsolicited RS/NS/NA/"
+"redirect packet without link-layer address"
+msgstr ""
+"когда отсутствовала запись в кэше соседей, узел получал нежелательный пакет "
+"RS/NS/NA/редирект без адреса канального уровня"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:183
+msgid ""
+"neighbor cache handling on medium without link-layer address (we need a "
+"neighbor cache entry for IsRouter bit)"
+msgstr ""
+"обработка кэша соседей в среде без адреса канального уровня (нам нужна "
+"запись в кэше соседей для бита IsRouter)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:186
+msgid ""
+"For first case, we implemented workaround based on discussions on IETF "
+"ipngwg mailing list. For more details, see the comments in the source code "
+"and email thread started from (IPng 7155), dated Feb 6 1999."
+msgstr ""
+"Для первого случая мы реализовали временное решение на основе обсуждений в "
+"рассылке IETF ipngwg. Подробности можно найти в комментариях исходного кода "
+"и ветке электронной почты, начавшейся с (IPng 7155) от 6 февраля 1999 года."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:189
+msgid ""
+"IPv6 on-link determination rule (RFC2461) is quite different from "
+"assumptions in BSD network code. At this moment, no on-link determination "
+"rule is supported where default router list is empty (RFC2461, section 5.2, "
+"last sentence in 2nd paragraph - note that the spec misuse the word \"host\" "
+"and \"node\" in several places in the section)."
+msgstr ""
+"Правило определения локальной IPv6 сети (RFC2461) значительно отличается от "
+"предположений в сетевом коде BSD. На данный момент не поддерживается правило "
+"определения локальной сети при пустом списке маршрутизаторов по умолчанию "
+"(RFC2461, раздел 5.2, последнее предложение во 2-м абзаце - обратите "
+"внимание, что в спецификации некорректно используются слова \"host\" и "
+"\"node\" в нескольких местах раздела)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:194
+msgid ""
+"To avoid possible DoS attacks and infinite loops, only 10 options on ND "
+"packet is accepted now. Therefore, if you have 20 prefix options attached "
+"to RA, only the first 10 prefixes will be recognized. If this troubles you, "
+"please ask it on FREEBSD-CURRENT mailing list and/or modify nd6_maxndopt in "
+"[.filename]#sys/netinet6/nd6.c#. If there are high demands we may provide "
+"sysctl knob for the variable."
+msgstr ""
+"Во избежание возможных атак типа DoS и бесконечных циклов, сейчас "
+"принимается только 10 опций в ND-пакете. Таким образом, если к RA "
+"прикреплено 20 опций префиксов, будут распознаны только первые 10 префиксов. "
+"Если это вызывает проблемы, пожалуйста, задайте вопрос в рассылке FREEBSD-"
+"CURRENT и/или измените nd6_maxndopt в [.filename]#sys/netinet6/nd6.c#. При "
+"высоком спросе мы можем предоставить sysctl-параметр для этой переменной."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:196
+#, no-wrap
+msgid "Scope Index"
+msgstr "Индекс зоны"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:201
+msgid ""
+"IPv6 uses scoped addresses. Therefore, it is very important to specify "
+"scope index (interface index for link-local address, or site index for site-"
+"local address) with an IPv6 address. Without scope index, scoped IPv6 "
+"address is ambiguous to the kernel, and kernel will not be able to determine "
+"the outbound interface for a packet."
+msgstr ""
+"В IPv6 используются адреса с областями видимости — зонами. Поэтому очень "
+"важно указывать индекс зоны (индекс интерфейса для линк-локального адреса "
+"или индекс сайта для сайт-локального адреса) вместе с IPv6 адресом. Без "
+"индекса зоны адрес IPv6 с ограниченной областью действия является "
+"неоднозначным для ядра, и ядро не сможет определить исходящий интерфейс для "
+"пакета."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:206
+msgid ""
+"Ordinary userland applications should use advanced API (RFC2292) to specify "
+"scope index, or interface index. For similar purpose, sin6_scope_id member "
+"in sockaddr_in6 structure is defined in RFC2553. However, the semantics for "
+"sin6_scope_id is rather vague. If you care about portability of your "
+"application, we suggest you to use advanced API rather than sin6_scope_id."
+msgstr ""
+"Обычные пользовательские приложения должны использовать расширенный API "
+"(RFC2292) для указания индекса зоны или индекса интерфейса. Для аналогичных "
+"целей член sin6_scope_id в структуре sockaddr_in6 определён в RFC2553. "
+"Однако семантика sin6_scope_id довольно расплывчата. Если важна "
+"переносимость вашего приложения, мы рекомендуем использовать расширенный API "
+"вместо sin6_scope_id."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:209
+msgid ""
+"In the kernel, an interface index for link-local scoped address is embedded "
+"into 2nd 16bit-word (3rd and 4th byte) in IPv6 address. For example, you "
+"may see something like:"
+msgstr ""
+"В ядре индекс интерфейса для адреса с областью действия link-local "
+"встраивается во второе 16-битное слово (3-й и 4-й байт) в IPv6-адресе. "
+"Например, вы можете увидеть что-то вроде:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:213
+#, no-wrap
+msgid "\tfe80:1::200:f8ff:fe01:6317\n"
+msgstr "\tfe80:1::200:f8ff:fe01:6317\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:218
+msgid ""
+"in the routing table and interface address structure (struct in6_ifaddr). "
+"The address above is a link-local unicast address which belongs to a network "
+"interface whose interface identifier is 1. The embedded index enables us to "
+"identify IPv6 link local addresses over multiple interfaces effectively and "
+"with only a little code change."
+msgstr ""
+"в таблице маршрутизации и структуре адреса интерфейса (struct in6_ifaddr). "
+"Указанный выше адрес является линк-локальным уникастным адресом, который "
+"принадлежит сетевому интерфейсу с идентификатором интерфейса 1. Встроенный "
+"индекс позволяет эффективно идентифицировать локальные адреса IPv6 на "
+"нескольких интерфейсах с минимальными изменениями кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:223
+msgid ""
+"Routing daemons and configuration programs, like man:route6d[8] and "
+"man:ifconfig[8], will need to manipulate the \"embedded\" scope index. "
+"These programs use routing sockets and ioctls (like SIOCGIFADDR_IN6) and the "
+"kernel API will return IPv6 addresses with 2nd 16bit-word filled in. The "
+"APIs are for manipulating kernel internal structure. Programs that use "
+"these APIs have to be prepared about differences in kernels anyway."
+msgstr ""
+"Демоны маршрутизации и программы настройки, такие как man:route6d[8] и "
+"man:ifconfig[8], должны управлять \"встроенным\" индексом зоны. Эти "
+"программы используют сокеты маршрутизации и ioctl (например, "
+"SIOCGIFADDR_IN6), и API ядра будет возвращать IPv6-адреса с заполненным "
+"вторым 16-битным словом. API предназначены для управления внутренними "
+"структурами ядра. Программы, использующие эти API, в любом случае должны "
+"быть готовы к различиям в ядрах."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:230
+msgid ""
+"When you specify scoped address to the command line, NEVER write the "
+"embedded form (such as ff02:1::1 or fe80:2::fedc). This is not supposed to "
+"work. Always use standard form, like ff02::1 or fe80::fedc, with command "
+"line option for specifying interface (like `ping -6 -I ne0 ff02::1`). In "
+"general, if a command does not have command line option to specify outgoing "
+"interface, that command is not ready to accept scoped address. This may "
+"seem to be opposite from IPv6's premise to support \"dentist office\" "
+"situation. We believe that specifications need some improvements for this."
+msgstr ""
+"При указании адреса с ограниченной областью действия в командной строке "
+"НИКОГДА не используйте встроенную форму (например, ff02:1::1 или "
+"fe80:2::fedc). Это не должно работать. Всегда используйте стандартную форму, "
+"такую как ff02::1 или fe80::fedc, с параметром командной строки для указания "
+"интерфейса (например, `ping -6 -I ne0 ff02::1`). В общем, если команда не "
+"имеет параметра командной строки для указания исходящего интерфейса, эта "
+"команда не готова принимать адрес с областью действия. Это кажется "
+"противоречащим принципу IPv6 поддерживать сценарий \"кабинета стоматолога\". "
+"Мы считаем, что спецификации нуждаются в некоторых улучшениях для этого."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:234
+msgid ""
+"Some of the userland tools support extended numeric IPv6 syntax, as "
+"documented in [.filename]#draft-ietf-ipngwg-scopedaddr-format-00.txt#. You "
+"can specify outgoing link, by using name of the outgoing interface like "
+"\"fe80::1%ne0\". This way you will be able to specify link-local scoped "
+"address without much trouble."
+msgstr ""
+"Некоторые пользовательские утилиты поддерживают расширенный числовой "
+"синтаксис IPv6, как описано в [.filename]#draft-ietf-ipngwg-scopedaddr-"
+"format-00.txt#. Можно указать исходящее соединение, используя имя исходящего "
+"интерфейса, например \"fe80::1%ne0\". Таким образом можно легко указать линк-"
+"локальный адрес с ограниченной областью действия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:237
+msgid ""
+"To use this extension in your program, you will need to use "
+"man:getaddrinfo[3], and man:getnameinfo[3] with NI_WITHSCOPEID. The "
+"implementation currently assumes 1-to-1 relationship between a link and an "
+"interface, which is stronger than what specs say."
+msgstr ""
+"Для использования этого расширения в вашей программе потребуется "
+"использовать man:getaddrinfo[3] и man:getnameinfo[3] с NI_WITHSCOPEID. В "
+"текущей реализации предполагается однозначное соответствие между каналом и "
+"интерфейсом, что является более строгим условием, чем указано в "
+"спецификациях."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:239
+#, no-wrap
+msgid "Plug and Play"
+msgstr "Plug and Play (подключи и работай)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:245
+msgid ""
+"Most of the IPv6 stateless address autoconfiguration is implemented in the "
+"kernel. Neighbor Discovery functions are implemented in the kernel as a "
+"whole. Router Advertisement (RA) input for hosts is implemented in the "
+"kernel. Router Solicitation (RS) output for endhosts, RS input for routers, "
+"and RA output for routers are implemented in the userland."
+msgstr ""
+"Большая часть автонастройки адресов IPv6 без сохранения состояния "
+"реализована в ядре. Функции обнаружения соседей (Neighbor Discovery) "
+"реализованы в ядре целиком. Ввод рекламы маршрутизатора (RA) для хостов "
+"реализован в ядре. Вывод запроса маршрутизатора (RS) для конечных хостов, "
+"ввод RS для маршрутизаторов и вывод RA для маршрутизаторов реализованы в "
+"пользовательском пространстве."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:246
+#, no-wrap
+msgid "Assignment of link-local, and special addresses"
+msgstr "Назначение линк-локальных и специальных адресов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:251
+msgid ""
+"IPv6 link-local address is generated from IEEE802 address (Ethernet MAC "
+"address). Each of interface is assigned an IPv6 link-local address "
+"automatically, when the interface becomes up (IFF_UP). Also, direct route "
+"for the link-local address is added to routing table."
+msgstr ""
+"Линк-локальный адрес IPv6 генерируется из IEEE802 адреса (Ethernet MAC "
+"адреса). Каждому интерфейсу автоматически присваивается IPv6 линк-локальный "
+"адрес, когда интерфейс поднимается (IFF_UP). Также в таблицу маршрутизации "
+"добавляется прямой маршрут для линк-локального адреса."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:253
+msgid "Here is an output of netstat command:"
+msgstr "Вот вывод команды netstat:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:260
+#, no-wrap
+msgid ""
+"Internet6:\n"
+"Destination Gateway Flags Netif Expire\n"
+"fe80:1::%ed0/64 link#1 UC ed0\n"
+"fe80:2::%ep0/64 link#2 UC ep0\n"
+msgstr ""
+"Internet6:\n"
+"Destination Gateway Flags Netif Expire\n"
+"fe80:1::%ed0/64 link#1 UC ed0\n"
+"fe80:2::%ep0/64 link#2 UC ep0\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:265
+msgid ""
+"Interfaces that has no IEEE802 address (pseudo interfaces like tunnel "
+"interfaces, or ppp interfaces) will borrow IEEE802 address from other "
+"interfaces, such as Ethernet interfaces, whenever possible. If there is no "
+"IEEE802 hardware attached, a last resort pseudo-random value, MD5(hostname), "
+"will be used as source of link-local address. If it is not suitable for "
+"your usage, you will need to configure the link-local address manually."
+msgstr ""
+"Интерфейсы, не имеющие адреса IEEE802 (псевдоинтерфейсы, такие как "
+"туннельные интерфейсы или интерфейсы ppp), будут заимствовать адрес IEEE802 "
+"у других интерфейсов, например, Ethernet-интерфейсов, когда это возможно. "
+"Если нет подключенного оборудования IEEE802, в качестве последнего средства "
+"будет использовано псевдослучайное значение MD5(hostname) для формирования "
+"линк-локального адреса. Если это не подходит для вашего использования, вам "
+"потребуется настроить линк-локальный адрес вручную."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:268
+msgid ""
+"If an interface is not capable of handling IPv6 (such as lack of multicast "
+"support), link-local address will not be assigned to that interface. See "
+"section 2 for details."
+msgstr ""
+"Если интерфейс не поддерживает IPv6 (например, отсутствует поддержка "
+"multicast), на этот интерфейс не будет назначен линк-локальный адрес. "
+"Подробности см. в разделе 2."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:272
+msgid ""
+"Each interface joins the solicited multicast address and the link-local all-"
+"nodes multicast addresses (e.g., fe80::1:ff01:6317 and ff02::1, "
+"respectively, on the link the interface is attached). In addition to a link-"
+"local address, the loopback address (::1) will be assigned to the loopback "
+"interface. Also, ::1/128 and ff01::/32 are automatically added to routing "
+"table, and loopback interface joins node-local multicast group ff01::1."
+msgstr ""
+"Каждый интерфейс присоединяется к запрашиваемому широковещательному адресу и "
+"линк-локальным широковещательным адресам всех узлов (например, "
+"fe80::1:ff01:6317 и ff02::1 соответственно на соединении, к которому "
+"подключен интерфейс). В дополнение к линк-локальному адресу, адрес обратной "
+"петли (::1 — loopback) будет назначен интерфейсу обратной петли. "
+"Также, ::1/128 и ff01::/32 автоматически добавляются в таблицу "
+"маршрутизации, а loopback-интерфейс (интерфейс обратной петли) "
+"присоединяется к групповому адресу в пределах узла ff01::1."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:273
+#, no-wrap
+msgid "Stateless address autoconfiguration on Hosts"
+msgstr "Автоматическая настройка адресов без состояния на узлах"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:277
+msgid ""
+"In IPv6 specification, nodes are separated into two categories: _routers_ "
+"and _hosts_. Routers forward packets addressed to others, hosts does not "
+"forward the packets. net.inet6.ip6.forwarding defines whether this node is "
+"router or host (router if it is 1, host if it is 0)."
+msgstr ""
+"В спецификации IPv6 узлы разделены на две категории: _маршрутизаторы_ и "
+"_хосты_. Маршрутизаторы пересылают пакеты, адресованные другим, хосты не "
+"пересылают пакеты. Параметр net.inet6.ip6.forwarding определяет, является ли "
+"данный узел маршрутизатором или хостом (маршрутизатор, если значение равно "
+"1, хост, если 0)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:286
+msgid ""
+"When a host hears Router Advertisement from the router, a host may "
+"autoconfigure itself by stateless address autoconfiguration. This behavior "
+"can be controlled by net.inet6.ip6.accept_rtadv (host autoconfigures itself "
+"if it is set to 1). By autoconfiguration, network address prefix for the "
+"receiving interface (usually global address prefix) is added. Default route "
+"is also configured. Routers periodically generate Router Advertisement "
+"packets. To request an adjacent router to generate RA packet, a host can "
+"transmit Router Solicitation. To generate a RS packet at any time, use the "
+"_rtsol_ command. man:rtsold[8] daemon is also available. man:rtsold[8] "
+"generates Router Solicitation whenever necessary, and it works great for "
+"nomadic usage (notebooks/laptops). If one wishes to ignore Router "
+"Advertisements, use sysctl to set net.inet6.ip6.accept_rtadv to 0."
+msgstr ""
+"Когда хост получает Объявление Маршрутизатора (Router Advertisement) от "
+"маршрутизатора, он может автоматически настроить себя с помощью "
+"автонастройки адреса без сохранения состояния. Это поведение можно "
+"контролировать с помощью параметра net.inet6.ip6.accept_rtadv (хост "
+"автонастраивается, если значение равно 1). При автонастройке добавляется "
+"префикс сетевого адреса для принимающего интерфейса (обычно префикс "
+"глобального адреса). Также настраивается маршрут по умолчанию. "
+"Маршрутизаторы периодически генерируют пакеты Router Advertisement. Чтобы "
+"запросить соседний маршрутизатор сгенерировать RA-пакет, хост может "
+"отправить Router Solicitation. Для генерации RS-пакета в любое время "
+"используйте команду _rtsol_. Также доступен демон man:rtsold[8]. "
+"man:rtsold[8] генерирует Router Solicitation по мере необходимости и отлично "
+"подходит для мобильного использования (ноутбуки/лэптопы). Если необходимо "
+"игнорировать Router Advertisements, используйте sysctl для установки "
+"net.inet6.ip6.accept_rtadv в 0."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:288
+msgid ""
+"To generate Router Advertisement from a router, use the man:rtadvd[8] daemon."
+msgstr ""
+"Для генерации Router Advertisement от маршрутизатора используйте демон "
+"man:rtadvd[8]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:290
+msgid ""
+"Note that, IPv6 specification assumes the following items, and nonconforming "
+"cases are left unspecified:"
+msgstr ""
+"Обратите внимание, что спецификация IPv6 предполагает следующие пункты, а "
+"случаи несоответствия остаются неуточнёнными:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:292
+msgid "Only hosts will listen to router advertisements"
+msgstr "Только хосты будут принимать объявления от маршрутизаторов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:293
+msgid "Hosts have single network interface (except loopback)"
+msgstr "Узлы имеют один сетевой интерфейс (за исключением loopback)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:296
+msgid ""
+"Therefore, this is unwise to enable net.inet6.ip6.accept_rtadv on routers, "
+"or multi-interface host. A misconfigured node can behave strange "
+"(nonconforming configuration allowed for those who would like to do some "
+"experiments)."
+msgstr ""
+"Поэтому не рекомендуется включать net.inet6.ip6.accept_rtadv на "
+"маршрутизаторах или многопортовых хостах. Неправильно настроенный узел может "
+"вести себя странно (нестандартная конфигурация разрешена для тех, кто хочет "
+"провести эксперименты)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:298
+msgid "To summarize the sysctl knob:"
+msgstr "Резюмируя настройку sysctl:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:312
+#, no-wrap
+msgid ""
+"\taccept_rtadv\tforwarding\trole of the node\n"
+"\t---\t\t---\t\t---\n"
+"\t0\t\t0\t\thost (to be manually configured)\n"
+"\t0\t\t1\t\trouter\n"
+"\t1\t\t0\t\tautoconfigured host\n"
+"\t\t\t\t\t(spec assumes that host has single\n"
+"\t\t\t\t\tinterface only, autoconfigured host\n"
+"\t\t\t\t\twith multiple interface is\n"
+"\t\t\t\t\tout-of-scope)\n"
+"\t1\t\t1\t\tinvalid, or experimental\n"
+"\t\t\t\t\t(out-of-scope of spec)\n"
+msgstr ""
+"\taccept_rtadv\tforwarding\trole of the node\n"
+"\t---\t\t---\t\t---\n"
+"\t0\t\t0\t\thost (to be manually configured)\n"
+"\t0\t\t1\t\trouter\n"
+"\t1\t\t0\t\tautoconfigured host\n"
+"\t\t\t\t\t(spec assumes that host has single\n"
+"\t\t\t\t\tinterface only, autoconfigured host\n"
+"\t\t\t\t\twith multiple interface is\n"
+"\t\t\t\t\tout-of-scope)\n"
+"\t1\t\t1\t\tinvalid, or experimental\n"
+"\t\t\t\t\t(out-of-scope of spec)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:317
+msgid ""
+"RFC2462 has validation rule against incoming RA prefix information option, "
+"in 5.5.3 (e). This is to protect hosts from malicious (or misconfigured) "
+"routers that advertise very short prefix lifetime. There was an update from "
+"Jim Bound to ipngwg mailing list (look for \"(ipng 6712)\" in the archive) "
+"and it is implemented Jim's update."
+msgstr ""
+"В RFC2462 есть правило проверки для входящей информации о префиксе в RA, в "
+"разделе 5.5.3 (e). Это защищает хосты от злонамеренных (или неправильно "
+"настроенных) маршрутизаторов, которые анонсируют очень короткое время жизни "
+"префикса. Было обновление от Джима Баунда в рассылке ipngwg (ищите \"(ipng "
+"6712)\" в архиве), и это обновление Джима реализовано."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:319
+msgid ""
+"See crossref:ipv6[neighbor-discovery,23.5.1.2] in the document for "
+"relationship between DAD and autoconfiguration."
+msgstr ""
+"См. crossref:ipv6[neighbor-discovery,23.5.1.2] в документе для информации о "
+"взаимосвязи между DAD и автонастройкой."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:321
+#, no-wrap
+msgid "Generic Tunnel Interface"
+msgstr "Универсальный Туннельный Интерфейс"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:325
+msgid ""
+"GIF (Generic InterFace) is a pseudo interface for configured tunnel. "
+"Details are described in man:gif[4]. Currently"
+msgstr ""
+"GIF (Generic InterFace) — это псевдоинтерфейс для настроенного туннеля. "
+"Подробности описаны в man:gif[4]. В настоящее время"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:327
+msgid "v6 in v6"
+msgstr "v6 в v6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:328
+msgid "v6 in v4"
+msgstr "v6 в v4"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:329
+msgid "v4 in v6"
+msgstr "v4 в v6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:330
+msgid "v4 in v4"
+msgstr "v4 в v4"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:335
+msgid ""
+"are available. Use man:gifconfig[8] to assign physical (outer) source and "
+"destination address to gif interfaces. Configuration that uses same address "
+"family for inner and outer IP header (v4 in v4, or v6 in v6) is dangerous. "
+"It is very easy to configure interfaces and routing tables to perform "
+"infinite level of tunneling. _Please be warned_."
+msgstr ""
+"доступны. Используйте man:gifconfig[8] для назначения физических (внешних) "
+"исходных и конечных адресов интерфейсам gif. Конфигурация, использующая одно "
+"семейство адресов для внутреннего и внешнего IP-заголовка (v4 в v4 или v6 в "
+"v6), является опасной. Очень легко настроить интерфейсы и таблицы "
+"маршрутизации для выполнения бесконечного уровня туннелирования. "
+"_Пожалуйста, будьте осторожны_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:338
+msgid ""
+"gif can be configured to be ECN-friendly. See crossref:ipv6[ipsec-"
+"ecn,23.5.4.5] for ECN-friendliness of tunnels, and man:gif[4] for how to "
+"configure."
+msgstr ""
+"gif можно настроить так, чтобы он был дружественным к ECN. Подробнее о "
+"дружелюбности к ECN для туннелей см. crossref:ipv6[ipsec-ecn,23.5.4.5], а о "
+"настройке — в man:gif[4]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:341
+msgid ""
+"If you would like to configure an IPv4-in-IPv6 tunnel with gif interface, "
+"read man:gif[4] carefully. You will need to remove IPv6 link-local address "
+"automatically assigned to the gif interface."
+msgstr ""
+"Если вы хотите настроить туннель IPv4-в-IPv6 с интерфейсом gif, внимательно "
+"прочитайте man:gif[4]. Вам потребуется удалить линк-локальный адрес IPv6, "
+"автоматически назначенный интерфейсу gif."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:343
+#, no-wrap
+msgid "Source Address Selection"
+msgstr "Выбор исходящего адреса"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:347
+msgid ""
+"Current source selection rule is scope oriented (there are some exceptions - "
+"see below). For a given destination, a source IPv6 address is selected by "
+"the following rule:"
+msgstr ""
+"Текущее правило выбора источника ориентировано на зону (есть несколько "
+"исключений — см. ниже). Для заданного адреса назначения исходящий IPv6-адрес "
+"выбирается по следующему правилу:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:349
+msgid ""
+"If the source address is explicitly specified by the user (e.g., via the "
+"advanced API), the specified address is used."
+msgstr ""
+"Если исходящий адрес явно указан пользователем (например, через расширенный "
+"API), используется указанный адрес."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:350
+msgid ""
+"If there is an address assigned to the outgoing interface (which is usually "
+"determined by looking up the routing table) that has the same scope as the "
+"destination address, the address is used."
+msgstr ""
+"Если на исходящем интерфейсе назначен адрес (который обычно определяется "
+"путем просмотра таблицы маршрутизации) с той же зоной действия, что и адрес "
+"назначения, используется этот адрес."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:352
+msgid "This is the most typical case."
+msgstr "Это наиболее типичный случай."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:353
+msgid ""
+"If there is no address that satisfies the above condition, choose a global "
+"address assigned to one of the interfaces on the sending node."
+msgstr ""
+"Если нет адреса, удовлетворяющего указанному выше условию, выберите "
+"глобальный адрес, назначенный одному из интерфейсов на отправляющем узле."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:354
+msgid ""
+"If there is no address that satisfies the above condition, and destination "
+"address is site local scope, choose a site local address assigned to one of "
+"the interfaces on the sending node."
+msgstr ""
+"Если нет адреса, удовлетворяющего указанному выше условию, и адрес "
+"назначения имеет сайт-локальную зону, выберите сайт-локальный адрес, "
+"назначенный одному из интерфейсов на отправляющем узле."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:355
+msgid ""
+"If there is no address that satisfies the above condition, choose the "
+"address associated with the routing table entry for the destination. This is "
+"the last resort, which may cause scope violation."
+msgstr ""
+"Если нет адреса, удовлетворяющего указанному условию, выберите адрес, "
+"связанный с записью таблицы маршрутизации для назначения. Это крайняя мера, "
+"которая может нарушить границы зоны действия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:361
+msgid ""
+"For instance, ::1 is selected for ff01::1, fe80:1::200:f8ff:fe01:6317 for "
+"fe80:1::2a0:24ff:feab:839b (note that embedded interface index - described "
+"in crossref:ipv6[ipv6-scope-index,23.5.1.3] - helps us choose the right "
+"source address. Those embedded indices will not be on the wire). If the "
+"outgoing interface has multiple address for the scope, a source is selected "
+"longest match basis (rule 3). Suppose 2001:0DB8:808:1:200:f8ff:fe01:6317 "
+"and 2001:0DB8:9:124:200:f8ff:fe01:6317 are given to the outgoing interface. "
+"2001:0DB8:808:1:200:f8ff:fe01:6317 is chosen as the source for the "
+"destination 2001:0DB8:800::1."
+msgstr ""
+"Например, ::1 выбирается для ff01::1, fe80:1::200:f8ff:fe01:6317 для "
+"fe80:1::2a0:24ff:feab:839b (обратите внимание, что встроенный индекс "
+"интерфейса — описанный в crossref:ipv6[ipv6-scope-index,23.5.1.3] — помогает "
+"нам выбрать правильный исходный адрес. Эти встроенные индексы не будут "
+"передаваться по сети). Если исходящий интерфейс имеет несколько адресов для "
+"данной зоны, исходный адрес выбирается на основе наибольшего соответствия "
+"(правило 3). Предположим, что 2001:0DB8:808:1:200:f8ff:fe01:6317 и "
+"2001:0DB8:9:124:200:f8ff:fe01:6317 назначены исходящему интерфейсу. "
+"2001:0DB8:808:1:200:f8ff:fe01:6317 выбирается в качестве исходящего адреса "
+"для адреса назначения 2001:0DB8:800::1."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:368
+msgid ""
+"Note that the above rule is not documented in the IPv6 spec. It is "
+"considered \"up to implementation\" item. There are some cases where we do "
+"not use the above rule. One example is connected TCP session, and we use "
+"the address kept in tcb as the source. Another example is source address "
+"for Neighbor Advertisement. Under the spec (RFC2461 7.2.2) NA's source "
+"should be the target address of the corresponding NS's target. In this case "
+"we follow the spec rather than the above longest-match rule."
+msgstr ""
+"Обратите внимание, что приведенное выше правило не документировано в "
+"спецификации IPv6. Оно считается элементом, оставленным \"на усмотрение "
+"реализации\". Существуют случаи, когда мы не используем это правило. Один из "
+"примеров — установленное TCP-соединение, где мы используем адрес, "
+"сохраненный в tcb, в качестве источника. Другой пример — исходящий адрес для "
+"Объявления Соседа (Neighbor Advertisement). Согласно спецификации (RFC2461 "
+"7.2.2) источник NA должен быть целевым адресом соответствующего NS. В этом "
+"случае мы следуем спецификации, а не приведенному выше правилу наибольшего "
+"совпадения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:374
+msgid ""
+"For new connections (when rule 1 does not apply), deprecated addresses "
+"(addresses with preferred lifetime = 0) will not be chosen as source address "
+"if other choices are available. If no other choices are available, "
+"deprecated address will be used as a last resort. If there are multiple "
+"choice of deprecated addresses, the above scope rule will be used to choose "
+"from those deprecated addresses. If you would like to prohibit the use of "
+"deprecated address for some reason, configure net.inet6.ip6.use_deprecated "
+"to 0. The issue related to deprecated address is described in RFC2462 5.5.4 "
+"(NOTE: there is some debate underway in IETF ipngwg on how to use "
+"\"deprecated\" address)."
+msgstr ""
+"Для новых соединений (когда правило 1 не применяется), устаревшие адреса "
+"(адреса с предпочтительным временем жизни = 0) не будут выбираться в "
+"качестве исходящего адреса, если доступны другие варианты. Если других "
+"вариантов нет, устаревший адрес будет использован в качестве последнего "
+"средства. Если есть несколько устаревших адресов, для выбора между ними "
+"будет применено указанное выше правило области видимости. Если вы хотите "
+"запретить использование устаревших адресов по какой-либо причине, установите "
+"параметр net.inet6.ip6.use_deprecated в значение 0. Проблема, связанная с "
+"устаревшими адресами, описана в RFC2462 5.5.4 (ПРИМЕЧАНИЕ: в IETF ipngwg "
+"ведутся дебаты о том, как использовать \"устаревшие\" адреса)."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:376
+#, no-wrap
+msgid "Jumbo Payload"
+msgstr "Джамбо-пакет (Jumbo Payload)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:380
+msgid ""
+"The Jumbo Payload hop-by-hop option is implemented and can be used to send "
+"IPv6 packets with payloads longer than 65,535 octets. But currently no "
+"physical interface whose MTU is more than 65,535 is supported, so such "
+"payloads can be seen only on the loopback interface (i.e., lo0)."
+msgstr ""
+"Опция джамбо-пакет типа \"от прыжка к прыжку\" реализована и может "
+"использоваться для отправки IPv6-пакетов с полезной нагрузкой длиной более "
+"65 535 октетов. Однако в настоящее время не поддерживаются физические "
+"интерфейсы с MTU более 65 535, поэтому такие нагрузки могут быть только на "
+"интерфейсе loopback (т.е. lo0)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:382
+msgid ""
+"If you want to try jumbo payloads, you first have to reconfigure the kernel "
+"so that the MTU of the loopback interface is more than 65,535 bytes; add the "
+"following to the kernel configuration file:"
+msgstr ""
+"Если вы хотите попробовать джамбо-пакеты, сначала необходимо "
+"переконфигурировать ядро, чтобы MTU интерфейса loopback превышал 65 535 "
+"байт; добавьте следующее в конфигурационный файл ядра:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:384
+msgid "`options \"LARGE_LOMTU\" #To test jumbo payload`"
+msgstr "`options \"LARGE_LOMTU\" #To test jumbo payload`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:386
+msgid "and recompile the new kernel."
+msgstr "и пересоберите новое ядро."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:390
+msgid ""
+"Then you can test jumbo payloads by the man:ping[8] command with -6, -b and "
+"-s options. The -b option must be specified to enlarge the size of the "
+"socket buffer and the -s option specifies the length of the packet, which "
+"should be more than 65,535. For example, type as follows:"
+msgstr ""
+"Затем вы можете проверить работу с большими пакетами с помощью команды "
+"man:ping[8] с опциями -6, -b и -s. Опция -b необходима для увеличения "
+"размера буфера сокета, а опция -s задает длину пакета, которая должна быть "
+"больше 65 535. Например, введите следующее:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:394
+#, no-wrap
+msgid "% ping -6 -b 70000 -s 68000 ::1\n"
+msgstr "% ping -6 -b 70000 -s 68000 ::1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:399
+msgid ""
+"The IPv6 specification requires that the Jumbo Payload option must not be "
+"used in a packet that carries a fragment header. If this condition is "
+"broken, an ICMPv6 Parameter Problem message must be sent to the sender. "
+"specification is followed, but you cannot usually see an ICMPv6 error caused "
+"by this requirement."
+msgstr ""
+"Спецификация IPv6 требует, чтобы опция Джамбо-пакет не использовалась в "
+"пакете, содержащем заголовок фрагмента. Если это условие нарушено, должно "
+"быть отправлено ICMPv6 сообщение Parameter Problem отправителю. Спецификация "
+"соблюдается, но обычно вы не можете увидеть ICMPv6 ошибку, вызванную этим "
+"требованием."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:403
+msgid ""
+"When an IPv6 packet is received, the frame length is checked and compared to "
+"the length specified in the payload length field of the IPv6 header or in "
+"the value of the Jumbo Payload option, if any. If the former is shorter "
+"than the latter, the packet is discarded and statistics are incremented. "
+"You can see the statistics as output of man:netstat[8] command with `-s -p "
+"ip6' option:"
+msgstr ""
+"При получении IPv6-пакета проверяется длина кадра и сравнивается с длиной, "
+"указанной в поле длины полезной нагрузки заголовка IPv6 или в значении опции "
+"Джамбо-пакета, если она присутствует. Если первое значение меньше второго, "
+"пакет отбрасывается, и статистика увеличивается. Статистику можно увидеть в "
+"выводе команды man:netstat[8] с опцией `-s -p ip6`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:410
+#, no-wrap
+msgid ""
+"% netstat -s -p ip6\n"
+"\t ip6:\n"
+"\t\t(snip)\n"
+"\t\t1 with data size < data length\n"
+msgstr ""
+"% netstat -s -p ip6\n"
+"\t ip6:\n"
+"\t\t(snip)\n"
+"\t\t1 with data size < data length\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:414
+msgid ""
+"So, kernel does not send an ICMPv6 error unless the erroneous packet is an "
+"actual Jumbo Payload, that is, its packet size is more than 65,535 bytes. "
+"As described above, currently no physical interface with such a huge MTU is "
+"supported, so it rarely returns an ICMPv6 error."
+msgstr ""
+"Итак, ядро не отправляет ICMPv6 ошибку, если ошибочный пакет не является "
+"фактически Джамбо-пакетом, то есть его размер пакета превышает 65 535 байт. "
+"Как описано выше, в настоящее время не поддерживаются физические интерфейсы "
+"с таким огромным MTU, поэтому ICMPv6 ошибка возвращается редко."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:417
+msgid ""
+"TCP/UDP over jumbogram is not supported at this moment. This is because we "
+"have no medium (other than loopback) to test this. Contact us if you need "
+"this."
+msgstr ""
+"В настоящее время поддержка TCP/UDP через jumbogram не реализована. Это "
+"связано с отсутствием среды (кроме loopback) для тестирования данной "
+"функциональности. Свяжитесь с нами, если вам это необходимо."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:420
+msgid ""
+"IPsec does not work on jumbograms. This is due to some specification twists "
+"in supporting AH with jumbograms (AH header size influences payload length, "
+"and this makes it real hard to authenticate inbound packet with jumbo "
+"payload option as well as AH)."
+msgstr ""
+"IPsec не работает с jumbogram. Это связано с особенностями спецификации, "
+"касающимися поддержки AH для джамбограмм (размер заголовка AH влияет на "
+"длину полезной нагрузки, что делает крайне сложной аутентификацию входящего "
+"пакета с опцией Джамбо-пакет, а также AH)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:424
+msgid ""
+"There are fundamental issues in *BSD support for jumbograms. We would like "
+"to address those, but we need more time to finalize these. To name a few:"
+msgstr ""
+"Существуют фундаментальные проблемы в поддержке *BSD для jumbogram. Мы "
+"хотели бы решить их, но нам нужно больше времени для завершения работы. Вот "
+"некоторые из них:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:428
+msgid ""
+"mbuf pkthdr.len field is typed as \"int\" in 4.4BSD, so it will not hold "
+"jumbogram with len > 2G on 32bit architecture CPUs. If we would like to "
+"support jumbogram properly, the field must be expanded to hold 4G + IPv6 "
+"header + link-layer header. Therefore, it must be expanded to at least "
+"int64_t (u_int32_t is NOT enough)."
+msgstr ""
+"Поле `mbuf pkthdr.len` имеет тип `int` в 4.4BSD, поэтому оно не сможет "
+"содержать джамбограмму с длиной > 2G на 32-битных архитектурах CPU. Если мы "
+"хотим правильно поддерживать джамбограммы, это поле необходимо расширить, "
+"чтобы оно могло содержать 4G + заголовок IPv6 + заголовок канального уровня. "
+"Следовательно, его необходимо расширить как минимум до `int64_t` "
+"(`u_int32_t` НЕ достаточно)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:430
+msgid ""
+"We mistakingly use \"int\" to hold packet length in many places. We need to "
+"convert them into larger integral type. It needs a great care, as we may "
+"experience overflow during packet length computation."
+msgstr ""
+"Мы ошибочно используем \"int\" для хранения длины пакета во многих местах. "
+"Нам необходимо преобразовать их в более крупный целочисленный тип. Это "
+"требует большой осторожности, так как мы можем столкнуться с переполнением "
+"во время вычисления длины пакета."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:431
+msgid ""
+"We mistakingly check for ip6_plen field of IPv6 header for packet payload "
+"length in various places. We should be checking mbuf pkthdr.len instead. "
+"ip6_input() will perform sanity check on jumbo payload option on input, and "
+"we can safely use mbuf pkthdr.len afterwards."
+msgstr ""
+"Мы ошибочно проверяем поле ip6_plen заголовка IPv6 для определения длины "
+"полезной нагрузки пакета в различных местах. Вместо этого следует проверять "
+"mbuf pkthdr.len. Функция ip6_input() выполняет проверку корректности опции "
+"Джамбо-пакет при вводе, и после этого можно безопасно использовать mbuf "
+"pkthdr.len."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:432
+msgid "TCP code needs a careful update in bunch of places, of course."
+msgstr "Код TCP требует тщательного обновления в ряде мест, разумеется."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:433
+#, no-wrap
+msgid "Loop Prevention in Header Processing"
+msgstr "Предотвращение петель при обработке заголовков"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:444
+msgid ""
+"IPv6 specification allows arbitrary number of extension headers to be placed "
+"onto packets. If we implement IPv6 packet processing code in the way BSD "
+"IPv4 code is implemented, kernel stack may overflow due to long function "
+"call chain. sys/netinet6 code is carefully designed to avoid kernel stack "
+"overflow, so sys/netinet6 code defines its own protocol switch structure, as "
+"\"struct ip6protosw\" (see [.filename]#netinet6/ip6protosw.h#). There is no "
+"such update to IPv4 part (sys/netinet) for compatibility, but small change "
+"is added to its pr_input() prototype. So \"struct ipprotosw\" is also "
+"defined. As a result, if you receive IPsec-over-IPv4 packet with massive "
+"number of IPsec headers, kernel stack may blow up. IPsec-over-IPv6 is "
+"okay. (Of-course, for those all IPsec headers to be processed, each such "
+"IPsec header must pass each IPsec check. So an anonymous attacker will not "
+"be able to do such an attack.)"
+msgstr ""
+"Спецификация IPv6 допускает размещение произвольного количества расширений в "
+"заголовках пакетов. Если реализовать код обработки пакетов IPv6 так, как "
+"реализован код IPv4 в BSD, может произойти переполнение стека ядра из-за "
+"длинной цепочки вызовов функций. Код в sys/netinet6 тщательно спроектирован, "
+"чтобы избежать переполнения стека ядра, поэтому он определяет собственную "
+"структуру переключения протоколов — \"struct ip6protosw\" (см. "
+"[.filename]#netinet6/ip6protosw.h#). Для IPv4 части (sys/netinet) подобных "
+"обновлений не было сделано для сохранения совместимости, но в прототип "
+"pr_input() внесено небольшое изменение. Поэтому также определена \"struct "
+"ipprotosw\". В результате, если получен пакет IPsec-over-IPv4 с большим "
+"количеством заголовков IPsec, стек ядра может переполниться. С IPsec-over-"
+"IPv6 такой проблемы нет. (Разумеется, чтобы все эти заголовки IPsec были "
+"обработаны, каждый такой заголовок должен пройти все проверки IPsec. Поэтому "
+"анонимный злоумышленник не сможет осуществить подобную атаку.)"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:446
+#, no-wrap
+msgid "ICMPv6"
+msgstr "ICMPv6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:450
+msgid ""
+"After RFC2463 was published, IETF ipngwg has decided to disallow ICMPv6 "
+"error packet against ICMPv6 redirect, to prevent ICMPv6 storm on a network "
+"medium. This is already implemented into the kernel."
+msgstr ""
+"После публикации RFC2463 IETF ipngwg решил запретить ICMPv6 пакеты ошибок "
+"для ICMPv6 перенаправлений, чтобы предотвратить ICMPv6 шторм в сетевой "
+"среде. Это уже реализовано в ядре."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:451
+#, no-wrap
+msgid "Applications"
+msgstr "Приложения (Applications)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:454
+msgid ""
+"For userland programming, we support IPv6 socket API as specified in "
+"RFC2553, RFC2292 and upcoming Internet drafts."
+msgstr ""
+"Для программирования в пользовательском пространстве мы поддерживаем API "
+"сокетов IPv6, как указано в RFC2553, RFC2292 и готовящихся интернет-"
+"черновиках."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:459
+msgid ""
+"TCP/UDP over IPv6 is available and quite stable. You can enjoy "
+"man:telnet[1], man:ftp[1], man:rlogin[1], man:rsh[1], man:ssh[1], etc. "
+"These applications are protocol independent. That is, they automatically "
+"chooses IPv4 or IPv6 according to DNS."
+msgstr ""
+"TCP/UDP поверх IPv6 доступны и достаточно стабильны. Вы можете использовать "
+"man:telnet[1], man:ftp[1], man:rlogin[1], man:rsh[1], man:ssh[1] и т.д. Эти "
+"приложения не зависят от протокола. То есть они автоматически выбирают IPv4 "
+"или IPv6 в соответствии с DNS."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:460
+#, no-wrap
+msgid "Kernel Internals"
+msgstr "Внутреннее устройство ядра"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:463
+msgid ""
+"While ip_forward() calls ip_output(), ip6_forward() directly calls "
+"if_output() since routers must not divide IPv6 packets into fragments."
+msgstr ""
+"В то время как ip_forward() вызывает ip_output(), ip6_forward() напрямую "
+"вызывает if_output(), поскольку маршрутизаторы не должны разделять пакеты "
+"IPv6 на фрагменты."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:467
+msgid ""
+"ICMPv6 should contain the original packet as long as possible up to 1280. "
+"UDP6/IP6 port unreach, for instance, should contain all extension headers "
+"and the *unchanged* UDP6 and IP6 headers. So, all IP6 functions except TCP "
+"never convert network byte order into host byte order, to save the original "
+"packet."
+msgstr ""
+"ICMPv6 должен содержать исходный пакет по возможности вплоть до 1280 байт. "
+"Например, сообщение \"Ошибка недоступности порта UDP6/IP6\" должно содержать "
+"все расширенные заголовки и *неизменённые* заголовки UDP6 и IP6. Таким "
+"образом, все функции IP6, кроме TCP, никогда не преобразуют порядок байтов "
+"сети в порядок байтов хоста, чтобы сохранить исходный пакет."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:471
+msgid ""
+"tcp_input(), udp6_input() and icmp6_input() can not assume that IP6 header "
+"is preceding the transport headers due to extension headers. So, "
+"in6_cksum() was implemented to handle packets whose IP6 header and transport "
+"header is not continuous. TCP/IP6 nor UDP6/IP6 header structures do not "
+"exist for checksum calculation."
+msgstr ""
+"Функции tcp_input(), udp6_input() и icmp6_input() не могут предполагать, что "
+"заголовок IP6 предшествует транспортным заголовкам из-за наличия расширенных "
+"заголовков. Поэтому была реализована in6_cksum() для обработки пакетов, у "
+"которых заголовок IP6 и транспортный заголовок не являются непрерывными. Но "
+"ни для TCP/IP6, ни для UDP6/IP6 в заголовке нет структуры для расчёта "
+"контрольной суммы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:474
+msgid ""
+"To process IP6 header, extension headers and transport headers easily, "
+"network drivers are now required to store packets in one internal mbuf or "
+"one or more external mbufs. A typical old driver prepares two internal "
+"mbufs for 96 - 204 bytes data, however, now such packet data is stored in "
+"one external mbuf."
+msgstr ""
+"Для удобной обработки заголовка IP6, дополнительных заголовков и "
+"транспортных заголовков, от сетевых драйверов теперь требуется хранить "
+"пакеты в одном внутреннем mbuf или одном или нескольких внешних mbuf. "
+"Типичный старый драйвер подготавливает два внутренних mbuf для данных "
+"размером 96–204 байт, однако теперь такие данные пакета хранятся в одном "
+"внешнем mbuf."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:478
+msgid ""
+"`netstat -s -p ip6` tells you whether or not your driver conforms such "
+"requirement. In the following example, \"cce0\" violates the requirement. "
+"(For more information, refer to Section 2.)"
+msgstr ""
+"`netstat -s -p ip6` показывает, соответствует ли ваш драйвер этому "
+"требованию. В следующем примере \"cce0\" нарушает это требование. (Для "
+"получения дополнительной информации обратитесь к разделу 2.)"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:488
+#, no-wrap
+msgid ""
+"Mbuf statistics:\n"
+" 317 one mbuf\n"
+" two or more mbuf::\n"
+" lo0 = 8\n"
+"\t\t\tcce0 = 10\n"
+" 3282 one ext mbuf\n"
+" 0 two or more ext mbuf\n"
+msgstr ""
+"Mbuf statistics:\n"
+" 317 one mbuf\n"
+" two or more mbuf::\n"
+" lo0 = 8\n"
+"\t\t\tcce0 = 10\n"
+" 3282 one ext mbuf\n"
+" 0 two or more ext mbuf\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:493
+msgid ""
+"Each input function calls IP6_EXTHDR_CHECK in the beginning to check if the "
+"region between IP6 and its header is continuous. IP6_EXTHDR_CHECK calls "
+"m_pullup() only if the mbuf has M_LOOP flag, that is, the packet comes from "
+"the loopback interface. m_pullup() is never called for packets coming from "
+"physical network interfaces."
+msgstr ""
+"Каждая входная функция вызывает IP6_EXTHDR_CHECK в начале, чтобы проверить, "
+"является ли область между IP6 и его заголовком непрерывной. IP6_EXTHDR_CHECK "
+"вызывает m_pullup() только если mbuf имеет флаг M_LOOP, то есть пакет пришел "
+"с интерфейса loopback. m_pullup() никогда не вызывается для пакетов, "
+"приходящих с физических сетевых интерфейсов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:495
+msgid "Both IP and IP6 reassemble functions never call m_pullup()."
+msgstr ""
+"Как функции повторной сборки IP, так и IP6 никогда не вызывают m_pullup()."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:497
+#, no-wrap
+msgid "IPv4 Mapped Address and IPv6 Wildcard Socket"
+msgstr "IPv4-отображённые адреса и IPv6-сокет с подстановочным адресом"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:501
+msgid ""
+"RFC2553 describes IPv4 mapped address (3.7) and special behavior of IPv6 "
+"wildcard bind socket (3.8). The spec allows you to:"
+msgstr ""
+"RFC2553 описывает IPv4 отображённые адреса (3.7) и особое поведение IPv6 "
+"сокета с привязкой к любому адресу (3.8). Спецификация позволяет вам:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:503
+msgid "Accept IPv4 connections by AF_INET6 wildcard bind socket."
+msgstr ""
+"Принимать IPv4-подключения через сокет с привязкой к подстановочному адресу "
+"AF_INET6."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:504
+msgid ""
+"Transmit IPv4 packet over AF_INET6 socket by using special form of the "
+"address like ::ffff:10.1.1.1."
+msgstr ""
+"Передача IPv4-пакета через сокет AF_INET6 с использованием специальной формы "
+"адреса, например ::ffff:10.1.1.1."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:507
+msgid ""
+"but the spec itself is very complicated and does not specify how the socket "
+"layer should behave. Here we call the former one \"listening side\" and the "
+"latter one \"initiating side\", for reference purposes."
+msgstr ""
+"но сама спецификация очень сложна и не определяет, как должен вести себя "
+"сокетный уровень. Здесь мы называем первую сторону «слушающей», а вторую — "
+"«инициирующей» для удобства ссылок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:509
+msgid ""
+"You can perform wildcard bind on both of the address families, on the same "
+"port."
+msgstr ""
+"Вы можете выполнить привязку к подстановочному адресу для обоих семейств "
+"адресов на одном и том же порту."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:511
+msgid "The following table show the behavior of FreeBSD 4.x."
+msgstr "Следующая таблица показывает поведение FreeBSD 4.x."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:520
+#, no-wrap
+msgid ""
+"listening side initiating side\n"
+" (AF_INET6 wildcard (connection to ::ffff:10.1.1.1)\n"
+" socket gets IPv4 conn.)\n"
+" --- ---\n"
+"FreeBSD 4.x configurable supported\n"
+" default: enabled\n"
+msgstr ""
+"listening side initiating side\n"
+" (AF_INET6 wildcard (connection to ::ffff:10.1.1.1)\n"
+" socket gets IPv4 conn.)\n"
+" --- ---\n"
+"FreeBSD 4.x configurable supported\n"
+" default: enabled\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:523
+msgid ""
+"The following sections will give you more details, and how you can configure "
+"the behavior."
+msgstr ""
+"Следующие разделы предоставят вам более подробную информацию и объяснят, как "
+"можно настроить поведение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:525
+msgid "Comments on listening side:"
+msgstr "Комментарии о принимающей стороне:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:532
+msgid ""
+"It looks that RFC2553 talks too little on wildcard bind issue, especially on "
+"the port space issue, failure mode and relationship between AF_INET/INET6 "
+"wildcard bind. There can be several separate interpretation for this RFC "
+"which conform to it but behaves differently. So, to implement portable "
+"application you should assume nothing about the behavior in the kernel. "
+"Using man:getaddrinfo[3] is the safest way. Port number space and wildcard "
+"bind issues were discussed in detail on ipv6imp mailing list, in mid March "
+"1999 and it looks that there is no concrete consensus (means, up to "
+"implementers). You may want to check the mailing list archives."
+msgstr ""
+"Похоже, что в RFC2553 слишком мало сказано о проблеме привязки к "
+"подстановочному адресу, особенно о вопросе пространства портов, режиме "
+"отказа и взаимосвязи между AF_INET/INET6 wildcard bind. Может быть "
+"несколько различных интерпретаций этого RFC, которые соответствуют ему, но "
+"ведут себя по-разному. Поэтому для создания переносимых приложений не "
+"следует делать никаких предположений о поведении в ядре. Использование "
+"man:getaddrinfo[3] является наиболее безопасным способом. Вопросы "
+"пространства номеров портов и привязки к подстановочному адресу подробно "
+"обсуждались в рассылке ipv6imp в середине марта 1999 года, и похоже, что "
+"конкретного консенсуса нет (то есть, остается на усмотрение реализаторов). "
+"Возможно, вам стоит проверить архивы рассылки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:534
+msgid ""
+"If a server application would like to accept IPv4 and IPv6 connections, "
+"there will be two alternatives."
+msgstr ""
+"Если серверное приложение хочет принимать IPv4 и IPv6 соединения, есть два "
+"варианта."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:539
+msgid ""
+"One is using AF_INET and AF_INET6 socket (you will need two sockets). Use "
+"man:getaddrinfo[3] with AI_PASSIVE into ai_flags, and man:socket[2] and "
+"man:bind[2] to all the addresses returned. By opening multiple sockets, you "
+"can accept connections onto the socket with proper address family. IPv4 "
+"connections will be accepted by AF_INET socket, and IPv6 connections will be "
+"accepted by AF_INET6 socket."
+msgstr ""
+"Один из способов — использование сокетов AF_INET и AF_INET6 (вам понадобятся "
+"два сокета). Используйте man:getaddrinfo[3] с AI_PASSIVE в ai_flags, а также "
+"man:socket[2] и man:bind[2] для всех возвращённых адресов. Открыв несколько "
+"сокетов, вы можете принимать соединения сокетом соответствующей адресной "
+"семьи. IPv4-соединения будут приниматься сокетом AF_INET, а IPv6-соединения "
+"— сокетом AF_INET6."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:545
+msgid ""
+"Another way is using one AF_INET6 wildcard bind socket. Use "
+"man:getaddrinfo[3] with AI_PASSIVE into ai_flags and with AF_INET6 into "
+"ai_family, and set the 1st argument hostname to NULL. And man:socket[2] and "
+"man:bind[2] to the address returned. (should be IPv6 unspecified addr). "
+"You can accept either of IPv4 and IPv6 packet via this one socket."
+msgstr ""
+"Еще один способ — использование одного сокета с универсальной привязкой "
+"AF_INET6. Используйте man:getaddrinfo[3] с AI_PASSIVE в ai_flags и AF_INET6 "
+"в ai_family, установив первый аргумент hostname в NULL. Затем используйте "
+"man:socket[2] и man:bind[2] для адреса, который был возвращен. (должен быть "
+"неспецифицированный адрес IPv6). Через этот один сокет можно принимать "
+"пакеты как IPv4, так и IPv6."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:549
+msgid ""
+"To support only IPv6 traffic on AF_INET6 wildcard binded socket portably, "
+"always check the peer address when a connection is made toward AF_INET6 "
+"listening socket. If the address is IPv4 mapped address, you may want to "
+"reject the connection. You can check the condition by using "
+"IN6_IS_ADDR_V4MAPPED() macro."
+msgstr ""
+"Для поддержки только IPv6-трафика на AF_INET6-сокете с привязкой к любому "
+"адресу переносимым способом всегда проверяйте адрес узла при установке "
+"соединения с AF_INET6-сокетом в режиме прослушивания. Если адрес является "
+"IPv4-отображённым, возможно, стоит отклонить соединение. Это условие можно "
+"проверить с помощью макроса IN6_IS_ADDR_V4MAPPED()."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:551
+msgid ""
+"To resolve this issue more easily, there is system dependent "
+"man:setsockopt[2] option, IPV6_BINDV6ONLY, used like below."
+msgstr ""
+"Для более простого решения этой задачи существует зависящий от системы "
+"параметр man:setsockopt[2] под названием IPV6_BINDV6ONLY, используемый "
+"следующим образом."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:555
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:602
+#, no-wrap
+msgid "\tint on;\n"
+msgstr "\tint on;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:558
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:605
+#, no-wrap
+msgid ""
+"\tsetsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,\n"
+"\t\t (char *)&on, sizeof (on)) < 0));\n"
+msgstr ""
+"\tsetsockopt(s, IPPROTO_IPV6, IPV6_BINDV6ONLY,\n"
+"\t\t (char *)&on, sizeof (on)) < 0));\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:561
+msgid "When this call succeed, then this socket only receive IPv6 packets."
+msgstr "При успешном вызове этот сокет будет принимать только IPv6-пакеты."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:563
+msgid "Comments on initiating side:"
+msgstr "Комментарии о стороне инициатора:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:565
+msgid ""
+"Advise to application implementers: to implement a portable IPv6 application "
+"(which works on multiple IPv6 kernels), we believe that the following is the "
+"key to the success:"
+msgstr ""
+"Совет разработчикам приложений: для создания переносимого IPv6-приложения "
+"(которое работает на различных IPv6-ядрах), мы считаем, что следующие "
+"моменты являются ключом к успеху:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:567
+msgid "NEVER hardcode AF_INET nor AF_INET6."
+msgstr "НИКОГДА не используйте жёстко заданные AF_INET или AF_INET6."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:568
+msgid ""
+"Use man:getaddrinfo[3] and man:getnameinfo[3] throughout the system. Never "
+"use gethostby*(), getaddrby*(), inet_*() or getipnodeby*(). (To update "
+"existing applications to be IPv6 aware easily, sometime getipnodeby*() will "
+"be useful. But if possible, try to rewrite the code to use "
+"man:getaddrinfo[3] and man:getnameinfo[3].)"
+msgstr ""
+"Используйте man:getaddrinfo[3] и man:getnameinfo[3] во всей системе. Никогда "
+"не используйте gethostby*(), getaddrby*(), inet_*() или getipnodeby*(). (Для "
+"облегчения обновления существующих приложений для поддержки IPv6 иногда "
+"может быть полезен getipnodeby*(). Но по возможности старайтесь переписать "
+"код для использования man:getaddrinfo[3] и man:getnameinfo[3].)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:569
+msgid ""
+"If you would like to connect to destination, use man:getaddrinfo[3] and try "
+"all the destination returned, like man:telnet[1] does."
+msgstr ""
+"Если вы хотите подключиться к назначению, используйте man:getaddrinfo[3] и "
+"попробуйте все возвращённые назначения, как это делает man:telnet[1]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:570
+msgid ""
+"Some of the IPv6 stack is shipped with buggy man:getaddrinfo[3]. Ship a "
+"minimal working version with your application and use that as last resort."
+msgstr ""
+"Некоторые реализации стека IPv6 поставляются с некорректной "
+"man:getaddrinfo[3]. Включите минимально рабочую версию в ваше приложение и "
+"используйте её в крайнем случае."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:576
+msgid ""
+"If you would like to use AF_INET6 socket for both IPv4 and IPv6 outgoing "
+"connection, you will need to use man:getipnodebyname[3]. When you would "
+"like to update your existing application to be IPv6 aware with minimal "
+"effort, this approach might be chosen. But please note that it is a "
+"temporal solution, because man:getipnodebyname[3] itself is not recommended "
+"as it does not handle scoped IPv6 addresses at all. For IPv6 name "
+"resolution, man:getaddrinfo[3] is the preferred API. So you should rewrite "
+"your application to use man:getaddrinfo[3], when you get the time to do it."
+msgstr ""
+"Если вы хотите использовать сокет AF_INET6 для исходящих подключений как "
+"IPv4, так и IPv6, вам потребуется использовать man:getipnodebyname[3]. Если "
+"вы хотите обновить существующее приложение для поддержки IPv6 с минимальными "
+"усилиями, можно выбрать этот подход. Однако учтите, что это временное "
+"решение, поскольку man:getipnodebyname[3] сам по себе не рекомендуется, так "
+"как он вообще не обрабатывает IPv6-адреса с зоной. Для разрешения IPv6-имён "
+"предпочтительным API является man:getaddrinfo[3]. Поэтому вам следует "
+"переписать ваше приложение для использования man:getaddrinfo[3], когда у вас "
+"будет время это сделать."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:580
+msgid ""
+"When writing applications that make outgoing connections, story goes much "
+"simpler if you treat AF_INET and AF_INET6 as totally separate address "
+"family. {set,get}sockopt issue goes simpler, DNS issue will be made "
+"simpler. We do not recommend you to rely upon IPv4 mapped address."
+msgstr ""
+"При написании приложений, которые устанавливают исходящие соединения, "
+"история становится намного проще, если рассматривать AF_INET и AF_INET6 как "
+"совершенно отдельные семейства адресов. Проблемы с {set,get}sockopt "
+"упрощаются, проблемы с DNS также станут проще. Мы не рекомендуем полагаться "
+"на IPv4-отображённые адреса."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:581
+#, no-wrap
+msgid "unified tcp and inpcb code"
+msgstr "унифицированный код tcp и inpcb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:585
+msgid ""
+"FreeBSD 4.x uses shared tcp code between IPv4 and IPv6 (from sys/netinet/"
+"tcp*) and separate udp4/6 code. It uses unified inpcb structure."
+msgstr ""
+"FreeBSD 4.x использует общий код tcp для IPv4 и IPv6 (из sys/netinet/tcp*) и "
+"раздельный код udp4/6. В нем используется унифицированная структура inpcb."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:588
+msgid ""
+"The platform can be configured to support IPv4 mapped address. Kernel "
+"configuration is summarized as follows:"
+msgstr ""
+"Платформа может быть настроена для поддержки IPv4-отображённых адресов. "
+"Конфигурация ядра кратко описана ниже:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:590
+msgid ""
+"By default, AF_INET6 socket will grab IPv4 connections in certain condition, "
+"and can initiate connection to IPv4 destination embedded in IPv4 mapped IPv6 "
+"address."
+msgstr ""
+"По умолчанию сокет AF_INET6 может принимать IPv4-соединения при определённых "
+"условиях и инициировать соединение с IPv4-адресами, встроенными в IPv4-"
+"отображённые IPv6-адреса."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:591
+msgid "You can disable it on entire system with sysctl like below."
+msgstr ""
+"Вы можете отключить это во всей системе с помощью sysctl, как показано ниже."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:593
+msgid "`sysctl net.inet6.ip6.mapped_addr=0`"
+msgstr "`sysctl net.inet6.ip6.mapped_addr=0`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:595
+msgid "====== Listening Side"
+msgstr "====== Сторона, принимающая соединения"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:598
+msgid ""
+"Each socket can be configured to support special AF_INET6 wildcard bind "
+"(enabled by default). You can disable it on each socket basis with "
+"man:setsockopt[2] like below."
+msgstr ""
+"Каждый сокет может быть настроен для поддержки специальной привязки к "
+"подстановочному адресу AF_INET6 (включено по умолчанию). Это можно отключить "
+"для каждого отдельного сокета с помощью man:setsockopt[2], как показано ниже."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:608
+msgid ""
+"Wildcard AF_INET6 socket grabs IPv4 connection if and only if the following "
+"conditions are satisfied:"
+msgstr ""
+"Сокет с универсальной привязкой AF_INET6 перехватывает IPv4-подключение "
+"тогда и только тогда, когда выполнены следующие условия:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:610
+msgid "there is no AF_INET socket that matches the IPv4 connection"
+msgstr "нет AF_INET сокета, соответствующего IPv4-подключению"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:611
+msgid ""
+"the AF_INET6 socket is configured to accept IPv4 traffic, i.e., "
+"getsockopt(IPV6_BINDV6ONLY) returns 0."
+msgstr ""
+"Сокет AF_INET6 настроен на прием IPv4-трафика, т.е., "
+"getsockopt(IPV6_BINDV6ONLY) возвращает 0."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:613
+msgid "There is no problem with open/close ordering."
+msgstr "Нет проблем с порядком открытия/закрытия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:615
+msgid "====== Initiating Side"
+msgstr "====== Инициирующая сторона"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:617
+msgid ""
+"FreeBSD 4.x supports outgoing connection to IPv4 mapped address "
+"(::ffff:10.1.1.1), if the node is configured to support IPv4 mapped address."
+msgstr ""
+"FreeBSD 4.x поддерживает исходящее соединение с IPv4-отображённым адресом "
+"(::ffff:10.1.1.1), если узел настроен на поддержку IPv4-отображённых адресов."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:618
+#, no-wrap
+msgid "sockaddr_storage"
+msgstr "sockaddr_storage"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:624
+msgid ""
+"When RFC2553 was about to be finalized, there was discussion on how struct "
+"sockaddr_storage members are named. One proposal is to prepend \"__\" to "
+"the members (like \"__ss_len\") as they should not be touched. The other "
+"proposal was not to prepend it (like \"ss_len\") as we need to touch those "
+"members directly. There was no clear consensus on it."
+msgstr ""
+"Когда RFC2553 был близок к завершению, велись дискуссии о том, как называть "
+"элементы структуры `sockaddr_storage`. Одно предложение заключалось в "
+"добавлении \"__\" перед именами элементов (например, \"__ss_len\"), так как "
+"к ним не следует обращаться напрямую. Другое предложение было не добавлять "
+"префикс (например, \"ss_len\"), поскольку необходимо прямое обращение к этим "
+"элементам. Четкого консенсуса по этому вопросу достигнуто не было."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:626
+msgid "As a result, RFC2553 defines struct sockaddr_storage as follows:"
+msgstr ""
+"В результате, RFC2553 определяет структуру sockaddr_storage следующим "
+"образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:634
+#, no-wrap
+msgid ""
+"\tstruct sockaddr_storage {\n"
+"\t\tu_char\t__ss_len;\t/* address length */\n"
+"\t\tu_char\t__ss_family;\t/* address family */\n"
+"\t\t/* and bunch of padding */\n"
+"\t};\n"
+msgstr ""
+"\tstruct sockaddr_storage {\n"
+"\t\tu_char\t__ss_len;\t/* address length */\n"
+"\t\tu_char\t__ss_family;\t/* address family */\n"
+"\t\t/* and bunch of padding */\n"
+"\t};\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:637
+msgid "On the contrary, XNET draft defines as follows:"
+msgstr "Напротив, черновик XNET определяет следующее:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:645
+#, no-wrap
+msgid ""
+"\tstruct sockaddr_storage {\n"
+"\t\tu_char\tss_len;\t\t/* address length */\n"
+"\t\tu_char\tss_family;\t/* address family */\n"
+"\t\t/* and bunch of padding */\n"
+"\t};\n"
+msgstr ""
+"\tstruct sockaddr_storage {\n"
+"\t\tu_char\tss_len;\t\t/* address length */\n"
+"\t\tu_char\tss_family;\t/* address family */\n"
+"\t\t/* and bunch of padding */\n"
+"\t};\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:648
+msgid ""
+"In December 1999, it was agreed that RFC2553bis should pick the latter "
+"(XNET) definition."
+msgstr ""
+"В декабре 1999 года было согласовано, что RFC2553bis должен принять "
+"последнее (XNET) определение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:650
+msgid ""
+"Current implementation conforms to XNET definition, based on RFC2553bis "
+"discussion."
+msgstr ""
+"Текущая реализация соответствует определению XNET, основанному на обсуждении "
+"RFC2553bis."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:653
+msgid ""
+"If you look at multiple IPv6 implementations, you will be able to see both "
+"definitions. As an userland programmer, the most portable way of dealing "
+"with it is to:"
+msgstr ""
+"Если вы рассмотрите несколько реализаций IPv6, то сможете увидеть оба "
+"определения. Для программиста в пользовательском пространстве наиболее "
+"переносимый способ работы с этим:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:655
+msgid ""
+"ensure ss_family and/or ss_len are available on the platform, by using GNU "
+"autoconf,"
+msgstr ""
+"с помощью GNU autoconf сконфигурировать доступ к `ss_family` и/или `ss_len` "
+"на целевой платформе,"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:656
+msgid ""
+"have -Dss_family=__ss_family to unify all occurrences (including header "
+"file) into __ss_family, or"
+msgstr ""
+"добавить -Dss_family=__ss_family для унификации всех использований (включая "
+"заголовочный файл) __ss_family, или"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:657
+msgid "never touch __ss_family. cast to sockaddr * and use sa_family like:"
+msgstr ""
+"никогда не трогайте __ss_family. Приводите к sockaddr * и используйте "
+"sa_family, например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:662
+#, no-wrap
+msgid ""
+"\tstruct sockaddr_storage ss;\n"
+"\tfamily = ((struct sockaddr *)&ss)->sa_family\n"
+msgstr ""
+"\tstruct sockaddr_storage ss;\n"
+"\tfamily = ((struct sockaddr *)&ss)->sa_family\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:664
+#, no-wrap
+msgid "Network Drivers"
+msgstr "Драйверы сетевых устройств"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:667
+msgid ""
+"Now following two items are required to be supported by standard drivers:"
+msgstr ""
+"В настоящее время следующие два пункта должны поддерживаться стандартными "
+"драйверами:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:669
+msgid ""
+"mbuf clustering requirement. In this stable release, we changed MINCLSIZE "
+"into MHLEN+1 for all the operating systems in order to make all the drivers "
+"behave as we expect."
+msgstr ""
+"Требование к кластеризации mbuf. В этом стабильном выпуске мы изменили "
+"MINCLSIZE на MHLEN+1 для всех операционных систем, чтобы все драйверы "
+"работали так, как мы ожидаем."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:670
+msgid ""
+"multicast. If man:ifmcstat[8] yields no multicast group for a interface, "
+"that interface has to be patched."
+msgstr ""
+"многоадресная рассылка (multicast). Если man:ifmcstat[8] не выводит ни одной "
+"многоадресной группы для интерфейса, этот интерфейс необходимо исправить."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:673
+msgid ""
+"If any of the drivers do not support the requirements, then the drivers "
+"cannot be used for IPv6 and/or IPsec communication. If you find any problem "
+"with your card using IPv6/IPsec, then, please report it to the {freebsd-"
+"bugs}."
+msgstr ""
+"Если какие-либо драйверы не поддерживают требования, то их нельзя "
+"использовать для IPv6 и/или IPsec-связи. Если вы обнаружили проблему с вашей "
+"картой при использовании IPv6/IPsec, пожалуйста, сообщите об этом в {freebsd-"
+"bugs}."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:676
+msgid ""
+"(NOTE: In the past we required all PCMCIA drivers to have a call to "
+"in6_ifattach(). We have no such requirement any more)"
+msgstr ""
+"(NOTE: Раньше мы требовали, чтобы все драйверы PCMCIA содержали вызов "
+"in6_ifattach(). Теперь такого требования нет)"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:677
+#, no-wrap
+msgid "Translator"
+msgstr "Транслятор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:680
+msgid "We categorize IPv4/IPv6 translator into 4 types:"
+msgstr "Мы классифицируем трансляторы IPv4/IPv6 на 4 типа:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:682
+msgid ""
+"_Translator A_ --- It is used in the early stage of transition to make it "
+"possible to establish a connection from an IPv6 host in an IPv6 island to an "
+"IPv4 host in the IPv4 ocean."
+msgstr ""
+"_Транслятор А_ --- Он используется на раннем этапе перехода, чтобы позволить "
+"установить соединение с IPv6-хоста на IPv6-острове к IPv4-хосту в IPv4-"
+"океане."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:683
+msgid ""
+"_Translator B_ --- It is used in the early stage of transition to make it "
+"possible to establish a connection from an IPv4 host in the IPv4 ocean to an "
+"IPv6 host in an IPv6 island."
+msgstr ""
+"_Транслятор Б_ --- Он используется на раннем этапе перехода, чтобы "
+"обеспечить возможность установления соединения с IPv6-узлом на IPv6-острове "
+"от IPv4-узла в IPv4-океане."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:684
+msgid ""
+"_Translator C_ --- It is used in the late stage of transition to make it "
+"possible to establish a connection from an IPv4 host in an IPv4 island to an "
+"IPv6 host in the IPv6 ocean."
+msgstr ""
+"_Транслятор C_ --- Он используется на позднем этапе перехода, чтобы сделать "
+"возможным установление соединения с IPv6-узлом в IPv6-океане от IPv4-узла на "
+"IPv4-острове."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:685
+msgid ""
+"_Translator D_ --- It is used in the late stage of transition to make it "
+"possible to establish a connection from an IPv6 host in the IPv6 ocean to an "
+"IPv4 host in an IPv4 island."
+msgstr ""
+"_Транслятор D_ --- Он используется на позднем этапе перехода, чтобы сделать "
+"возможным установление соединения с IPv6-хоста в IPv6-океане на IPv4-хост на "
+"IPv4-острове."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:687
+#, no-wrap
+msgid "IPsec"
+msgstr "IPsec"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:690
+msgid "IPsec is mainly organized by three components."
+msgstr "IPsec состоит в основном из трех компонент."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:692
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:695
+#, no-wrap
+msgid "Policy Management"
+msgstr "Управление политиками"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:693
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:705
+#, no-wrap
+msgid "Key Management"
+msgstr "Управление ключами"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:694
+msgid "AH and ESP handling"
+msgstr "Обработка AH и ESP"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:702
+msgid ""
+"The kernel implements experimental policy management code. There are two "
+"way to manage security policy. One is to configure per-socket policy using "
+"man:setsockopt[2]. In this cases, policy configuration is described in "
+"man:ipsec_set_policy[3]. The other is to configure kernel packet filter-"
+"based policy using PF_KEY interface, via man:setkey[8]."
+msgstr ""
+"Ядро реализует экспериментальный код управления политикой безопасности. "
+"Существует два способа управления политикой безопасности. Первый — настройка "
+"политики для каждого сокета с помощью man:setsockopt[2]. В этом случае "
+"конфигурация политики описана в man:ipsec_set_policy[3]. Второй способ — "
+"настройка политики на основе фильтра пакетов ядра с использованием "
+"интерфейса PF_KEY через man:setkey[8]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:704
+msgid ""
+"The policy entry is not re-ordered with its indexes, so the order of entry "
+"when you add is very significant."
+msgstr ""
+"Запись политики не переупорядочивается вместе со своими индексами, поэтому "
+"порядок добавления записей очень важен."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:709
+msgid ""
+"The key management code implemented in this kit (sys/netkey) is a home-brew "
+"PFKEY v2 implementation. This conforms to RFC2367."
+msgstr ""
+"Код управления ключами, реализованный в этом наборе (sys/netkey), "
+"представляет собой собственную реализацию PFKEY v2. Это соответствует "
+"RFC2367."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:713
+msgid ""
+"The home-brew IKE daemon, \"racoon\" is included in the kit (kame/kame/"
+"racoon). Basically you will need to run racoon as daemon, then set up a "
+"policy to require keys (like `ping -P 'out ipsec esp/transport//use'`). The "
+"kernel will contact racoon daemon as necessary to exchange keys."
+msgstr ""
+"В комплект включена \"домашняя\" реализация демона IKE — \"racoon\" (kame/"
+"kame/racoon). Обычно вам потребуется запустить racoon в качестве демона, "
+"затем настроить политику для требования ключей (например, `ping -P 'out "
+"ipsec esp/transport//use'`). Ядро будет связываться с демоном racoon по мере "
+"необходимости для обмена ключами."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:714
+#, no-wrap
+msgid "AH and ESP Handling"
+msgstr "Обработка AH и ESP"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:722
+msgid ""
+"IPsec module is implemented as \"hooks\" to the standard IPv4/IPv6 "
+"processing. When sending a packet, ip{,6}_output() checks if ESP/AH "
+"processing is required by checking if a matching SPD (Security Policy "
+"Database) is found. If ESP/AH is needed, {esp,ah}{4,6}_output() will be "
+"called and mbuf will be updated accordingly. When a packet is received, "
+"{esp,ah}4_input() will be called based on protocol number, i.e., "
+"(*inetsw[proto])(). {esp,ah}4_input() will decrypt/check authenticity of "
+"the packet, and strips off daisy-chained header and padding for ESP/AH. It "
+"is safe to strip off the ESP/AH header on packet reception, since we will "
+"never use the received packet in \"as is\" form."
+msgstr ""
+"Модуль IPsec реализован в виде \"хуков\" к стандартной обработке IPv4/IPv6. "
+"При отправке пакета функция ip{,6}_output() проверяет, требуется ли "
+"обработка ESP/AH, путем поиска соответствующей базы данных политик "
+"безопасности (SPD — Security Policy Database). Если ESP/AH необходим, "
+"вызывается {esp,ah}{4,6}_output(), и mbuf соответствующим образом "
+"обновляется. При получении пакета функция {esp,ah}4_input() вызывается на "
+"основе номера протокола, т.е. (*inetsw[proto])(). {esp,ah}4_input() "
+"расшифровывает/проверяет подлинность пакета, а также удаляет цепочку "
+"заголовков и выравнивание для ESP/AH. Безопасно удалять заголовок ESP/AH при "
+"получении пакета, так как полученный пакет никогда не будет использоваться в "
+"\"сыром\" виде."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:725
+msgid ""
+"By using ESP/AH, TCP4/6 effective data segment size will be affected by "
+"extra daisy-chained headers inserted by ESP/AH. Our code takes care of the "
+"case."
+msgstr ""
+"Использование ESP/AH влияет на эффективный размер сегмента данных TCP4/6 из-"
+"за дополнительных цепочечных заголовков, вставляемых ESP/AH. Наш код "
+"учитывает этот случай."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:729
+msgid ""
+"Basic crypto functions can be found in directory \"sys/crypto\". ESP/AH "
+"transform are listed in {esp,ah}_core.c with wrapper functions. If you wish "
+"to add some algorithm, add wrapper function in {esp,ah}_core.c, and add your "
+"crypto algorithm code into sys/crypto."
+msgstr ""
+"Основные криптографические функции можно найти в директории `sys/crypto`. "
+"Преобразования ESP/AH перечислены в `{esp,ah}_core.c` с обёрточными "
+"функциями. Если вы хотите добавить какой-либо алгоритм, добавьте обёрточную "
+"функцию в `{esp,ah}_core.c` и поместите код вашего криптографического "
+"алгоритма в `sys/crypto`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:731
+msgid ""
+"Tunnel mode is partially supported in this release, with the following "
+"restrictions:"
+msgstr ""
+"Режим туннеля частично поддерживается в этом выпуске со следующими "
+"ограничениями:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:733
+msgid ""
+"IPsec tunnel is not combined with GIF generic tunneling interface. It needs "
+"a great care because we may create an infinite loop between ip_output() and "
+"tunnelifp->if_output(). Opinion varies if it is better to unify them, or not."
+msgstr ""
+"Туннель IPsec не объединён с универсальным туннельным интерфейсом GIF. Это "
+"требует особой осторожности, так как может возникнуть бесконечный цикл между "
+"`ip_output()` и `tunnelifp->if_output()`. Мнения расходятся относительно "
+"того, лучше ли их объединить или нет."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:734
+msgid ""
+"MTU and Don't Fragment bit (IPv4) considerations need more checking, but "
+"basically works fine."
+msgstr ""
+"MTU и бит Don't Fragment (IPv4) требуют дополнительной проверки, но в "
+"основном работают нормально."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:735
+msgid ""
+"Authentication model for AH tunnel must be revisited. We will need to "
+"improve the policy management engine, eventually."
+msgstr ""
+"Модель аутентификации для туннеля AH должна быть пересмотрена. Нам "
+"потребуется улучшить механизм управления политиками в конечном итоге."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:736
+#, no-wrap
+msgid "Conformance to RFCs and IDs"
+msgstr "Соответствие RFC и ID"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:739
+msgid ""
+"The IPsec code in the kernel conforms (or, tries to conform) to the "
+"following standards:"
+msgstr ""
+"Код IPsec в ядре соответствует (или пытается соответствовать) следующим "
+"стандартам:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:741
+msgid "\"old IPsec\" specification documented in [.filename]#rfc182[5-9].txt#"
+msgstr ""
+"Спецификация \"старого IPsec\", описанная в [.filename]#rfc182[5-9].txt#"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:744
+msgid ""
+"\"new IPsec\" specification documented in [.filename]#rfc240[1-6].txt#, "
+"[.filename]#rfc241[01].txt#, [.filename]#rfc2451.txt# and [.filename]#draft-"
+"mcdonald-simple-ipsec-api-01.txt# (draft expired, but you can take from "
+"link:ftp://ftp.kame.net/pub/internet-drafts/[ ftp://ftp.kame.net/pub/"
+"internet-drafts/]). (NOTE: IKE specifications, [.filename]#rfc241[7-9].txt# "
+"are implemented in userland, as \"racoon\" IKE daemon)"
+msgstr ""
+"Спецификация \"new IPsec\" описана в [.filename]#rfc240[1-6].txt#, "
+"[.filename]#rfc241[01].txt#, [.filename]#rfc2451.txt# и [.filename]#draft-"
+"mcdonald-simple-ipsec-api-01.txt# (черновик устарел, но его можно взять по "
+"ссылке: link:ftp://ftp.kame.net/pub/internet-drafts/[ ftp://ftp.kame.net/pub/"
+"internet-drafts/]). (ПРИМЕЧАНИЕ: Спецификации IKE, "
+"[.filename]#rfc241[7-9].txt#, реализованы в пользовательском пространстве в "
+"виде демона IKE \"racoon\")"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:746
+msgid "Currently supported algorithms are:"
+msgstr "В настоящее время поддерживаются следующие алгоритмы:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:748
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:785
+msgid "old IPsec AH"
+msgstr "old IPsec AH"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:750
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:763
+msgid "null crypto checksum (no document, just for debugging)"
+msgstr ""
+"нулевая криптографическая контрольная сумма (нет документа, только для "
+"отладки)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:751
+msgid "keyed MD5 with 128bit crypto checksum ([.filename]#rfc1828.txt#)"
+msgstr ""
+"MD5 с ключом и с 128-битной криптографической контрольной суммой "
+"([.filename]#rfc1828.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:752
+msgid "keyed SHA1 with 128bit crypto checksum (no document)"
+msgstr ""
+"SHA1 с ключом и с 128-битной криптографической контрольной суммой (без "
+"документа)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:753
+msgid "HMAC MD5 with 128bit crypto checksum ([.filename]#rfc2085.txt#)"
+msgstr ""
+"HMAC MD5 с 128-битной криптографической контрольной суммой "
+"([.filename]#rfc2085.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:754
+msgid "HMAC SHA1 with 128bit crypto checksum (no document)"
+msgstr ""
+"HMAC SHA1 с 128-битной криптографической контрольной суммой (без документа)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:756
+msgid "old IPsec ESP"
+msgstr "old IPsec ESP"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:758
+msgid "null encryption (no document, similar to [.filename]#rfc2410.txt#)"
+msgstr ""
+"нулевое шифрование (нет документа, аналогично [.filename]#rfc2410.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:759
+msgid "DES-CBC mode ([.filename]#rfc1829.txt#)"
+msgstr "Режим DES-CBC ([.filename]#rfc1829.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:761
+msgid "new IPsec AH"
+msgstr "new IPsec AH"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:764
+msgid "keyed MD5 with 96bit crypto checksum (no document)"
+msgstr ""
+"MD5 с ключом и с 96-битной криптографической контрольной суммой (нет "
+"документа)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:765
+msgid "keyed SHA1 with 96bit crypto checksum (no document)"
+msgstr ""
+"SHA1 с ключом и с 96-битной криптографической контрольной суммой (без "
+"документа)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:766
+msgid "HMAC MD5 with 96bit crypto checksum ([.filename]#rfc2403.txt#)"
+msgstr ""
+"HMAC MD5 с 96-битной криптографической контрольной суммой "
+"([.filename]#rfc2403.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:767
+msgid "HMAC SHA1 with 96bit crypto checksum ([.filename]#rfc2404.txt#)"
+msgstr ""
+"HMAC SHA1 с 96-битной криптографической контрольной суммой "
+"([.filename]#rfc2404.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:769
+msgid "new IPsec ESP"
+msgstr "new IPsec ESP"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:771
+msgid "null encryption ([.filename]#rfc2410.txt#)"
+msgstr "нулевое шифрование ([.filename]#rfc2410.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:772
+msgid ""
+"DES-CBC with derived IV ([.filename]#draft-ietf-ipsec-ciph-des-"
+"derived-01.txt#, draft expired)"
+msgstr ""
+"DES-CBC с производным IV ([.filename]#draft-ietf-ipsec-ciph-des-"
+"derived-01.txt#, черновик истек)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:773
+msgid "DES-CBC with explicit IV ([.filename]#rfc2405.txt#)"
+msgstr "DES-CBC с явным вектором инициализации ([.filename]#rfc2405.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:774
+msgid "3DES-CBC with explicit IV ([.filename]#rfc2451.txt#)"
+msgstr "3DES-CBC с явным вектором инициализации ([.filename]#rfc2451.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:775
+msgid "BLOWFISH CBC ([.filename]#rfc2451.txt#)"
+msgstr "BLOWFISH CBC ([.filename]#rfc2451.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:776
+msgid "CAST128 CBC ([.filename]#rfc2451.txt#)"
+msgstr "CAST128 CBC ([.filename]#rfc2451.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:777
+msgid "RC5 CBC ([.filename]#rfc2451.txt#)"
+msgstr "RC5 CBC ([.filename]#rfc2451.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:778
+msgid "each of the above can be combined with:"
+msgstr "каждый из вышеперечисленных может быть объединён с:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:780
+msgid "ESP authentication with HMAC-MD5(96bit)"
+msgstr "Аутентификация ESP с HMAC-MD5 (96 бит)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:781
+msgid "ESP authentication with HMAC-SHA1(96bit)"
+msgstr "Аутентификация ESP с HMAC-SHA1(96 бит)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:783
+msgid "The following algorithms are NOT supported:"
+msgstr "Следующие алгоритмы НЕ поддерживаются:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:787
+msgid ""
+"HMAC MD5 with 128bit crypto checksum + 64bit replay prevention "
+"([.filename]#rfc2085.txt#)"
+msgstr ""
+"HMAC MD5 с 128-битной криптографической контрольной суммой + 64-битная "
+"защита от повторного воспроизведения ([.filename]#rfc2085.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:788
+msgid ""
+"keyed SHA1 with 160bit crypto checksum + 32bit padding "
+"([.filename]#rfc1852.txt#)"
+msgstr ""
+"SHA1 с ключом и с 160-битной криптографической контрольной суммой + 32-"
+"битное дополнение ([.filename]#rfc1852.txt#)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:791
+msgid ""
+"IPsec (in kernel) and IKE (in userland as \"racoon\") has been tested at "
+"several interoperability test events, and it is known to interoperate with "
+"many other implementations well. Also, current IPsec implementation as "
+"quite wide coverage for IPsec crypto algorithms documented in RFC (we cover "
+"algorithms without intellectual property issues only)."
+msgstr ""
+"IPsec (в ядре) и IKE (в пользовательском пространстве как \"racoon\") были "
+"протестированы на нескольких мероприятиях по тестированию взаимодействия и "
+"известно, что они хорошо работают со многими другими реализациями. Кроме "
+"того, текущая реализация IPsec поддерживает довольно широкий спектр "
+"криптографических алгоритмов IPsec, описанных в RFC (мы поддерживаем только "
+"алгоритмы без проблем с интеллектуальной собственностью)."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:793
+#, no-wrap
+msgid "ECN Consideration on IPsec Tunnels"
+msgstr "Учет ECN в IPsec-туннелях"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:796
+msgid ""
+"ECN-friendly IPsec tunnel is supported as described in [.filename]#draft-"
+"ipsec-ecn-00.txt#."
+msgstr ""
+"Поддерживается ECN-совместимый IPsec-туннель, как описано в "
+"[.filename]#draft-ipsec-ecn-00.txt#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:801
+msgid ""
+"Normal IPsec tunnel is described in RFC2401. On encapsulation, IPv4 TOS "
+"field (or, IPv6 traffic class field) will be copied from inner IP header to "
+"outer IP header. On decapsulation outer IP header will be simply dropped. "
+"The decapsulation rule is not compatible with ECN, since ECN bit on the "
+"outer IP TOS/traffic class field will be lost."
+msgstr ""
+"Обычный IPsec-туннель описан в RFC2401. При инкапсуляции поле TOS IPv4 (или "
+"поле класса трафика IPv6) копируется из внутреннего IP-заголовка во внешний "
+"IP-заголовок. При декапсуляции внешний IP-заголовок просто отбрасывается. "
+"Правило декапсуляции несовместимо с ECN, так как бит ECN в поле TOS/класса "
+"трафика внешнего IP-заголовка будет потерян."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:804
+msgid ""
+"To make IPsec tunnel ECN-friendly, we should modify encapsulation and "
+"decapsulation procedure. This is described in http://www.aciri.org/floyd/"
+"papers/draft-ipsec-ecn-00.txt[ http://www.aciri.org/floyd/papers/draft-ipsec-"
+"ecn-00.txt], chapter 3."
+msgstr ""
+"Чтобы сделать IPsec-туннель дружественным к ECN, следует изменить процедуры "
+"инкапсуляции и декапсуляции. Это описано в http://www.aciri.org/floyd/papers/"
+"draft-ipsec-ecn-00.txt[ http://www.aciri.org/floyd/papers/draft-ipsec-"
+"ecn-00.txt], глава 3."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:806
+msgid ""
+"IPsec tunnel implementation can give you three behaviors, by setting "
+"net.inet.ipsec.ecn (or net.inet6.ipsec6.ecn) to some value:"
+msgstr ""
+"Реализация туннеля IPsec может обеспечить три варианта поведения, в "
+"зависимости от значения параметра `net.inet.ipsec.ecn` (или "
+"`net.inet6.ipsec6.ecn`):"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:808
+msgid "RFC2401: no consideration for ECN (sysctl value -1)"
+msgstr "RFC2401: отсутствие учета ECN (значение sysctl -1)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:809
+msgid "ECN forbidden (sysctl value 0)"
+msgstr "ECN запрещён (значение sysctl 0)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:810
+msgid "ECN allowed (sysctl value 1)"
+msgstr "ECN разрешён (значение sysctl 1)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:812
+msgid ""
+"Note that the behavior is configurable in per-node manner, not per-SA manner "
+"(draft-ipsec-ecn-00 wants per-SA configuration, but it looks too much for "
+"me)."
+msgstr ""
+"Обратите внимание, что поведение настраивается для каждого узла, а не для "
+"каждой SA (в draft-ipsec-ecn-00 предлагается настройка для каждой SA, но это "
+"кажется излишним)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:814
+msgid ""
+"The behavior is summarized as follows (see source code for more detail):"
+msgstr ""
+"Поведение можно обобщить следующим образом (подробности см. в исходном коде):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:821
+#, no-wrap
+msgid ""
+"encapsulate decapsulate\n"
+" --- ---\n"
+"RFC2401 copy all TOS bits drop TOS bits on outer\n"
+" from inner to outer. (use inner TOS bits as is)\n"
+msgstr ""
+"encapsulate decapsulate\n"
+" --- ---\n"
+"RFC2401 copy all TOS bits drop TOS bits on outer\n"
+" from inner to outer. (use inner TOS bits as is)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:825
+#, no-wrap
+msgid ""
+"ECN forbidden copy TOS bits except for ECN drop TOS bits on outer\n"
+" (masked with 0xfc) from inner (use inner TOS bits as is)\n"
+" to outer. set ECN bits to 0.\n"
+msgstr ""
+"ECN forbidden copy TOS bits except for ECN drop TOS bits on outer\n"
+" (masked with 0xfc) from inner (use inner TOS bits as is)\n"
+" to outer. set ECN bits to 0.\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:830
+#, no-wrap
+msgid ""
+"ECN allowed copy TOS bits except for ECN use inner TOS bits with some\n"
+" CE (masked with 0xfe) from change. if outer ECN CE bit\n"
+" inner to outer. is 1, enable ECN CE bit on\n"
+" set ECN CE bit to 0. the inner.\n"
+msgstr ""
+"ECN allowed copy TOS bits except for ECN use inner TOS bits with some\n"
+" CE (masked with 0xfe) from change. if outer ECN CE bit\n"
+" inner to outer. is 1, enable ECN CE bit on\n"
+" set ECN CE bit to 0. the inner.\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:833
+msgid "General strategy for configuration is as follows:"
+msgstr "Общая стратегия настройки выглядит следующим образом:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:835
+msgid ""
+"if both IPsec tunnel endpoint are capable of ECN-friendly behavior, you "
+"should better configure both end to \"ECN allowed\" (sysctl value 1)."
+msgstr ""
+"если оба конечных пункта туннеля IPsec поддерживают поведение, дружественное "
+"к ECN, лучше настроить оба конца на \"разрешено ECN\" (значение sysctl 1)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:836
+msgid ""
+"if the other end is very strict about TOS bit, use \"RFC2401\" (sysctl value "
+"-1)."
+msgstr ""
+"если другая сторона очень строга к биту TOS, используйте \"RFC2401\" "
+"(значение sysctl -1)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:837
+msgid "in other cases, use \"ECN forbidden\" (sysctl value 0)."
+msgstr "в остальных случаях используйте \"ECN запрещено\" (значение sysctl 0)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:839
+msgid "The default behavior is \"ECN forbidden\" (sysctl value 0)."
+msgstr "Поведение по умолчанию — \"ECN запрещён\" (значение sysctl 0)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:841
+msgid "For more information, please refer to:"
+msgstr "Для получения дополнительной информации обратитесь к:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:843
+msgid ""
+"http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt[ http://"
+"www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt], RFC2481 (Explicit "
+"Congestion Notification), src/sys/netinet6/{ah,esp}_input.c"
+msgstr ""
+"http://www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt[ http://"
+"www.aciri.org/floyd/papers/draft-ipsec-ecn-00.txt], RFC2481 (Явное "
+"Уведомление о Перегрузке), src/sys/netinet6/{ah,esp}_input.c"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:845
+msgid ""
+"(Thanks goes to Kenjiro Cho mailto:kjc@csl.sony.co.jp[kjc@csl.sony.co.jp] "
+"for detailed analysis)"
+msgstr ""
+"(Благодарности Kenjiro Cho mailto:kjc@csl.sony.co.jp[kjc@csl.sony.co.jp] за "
+"детальный анализ)"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:846
+#, no-wrap
+msgid "Interoperability"
+msgstr "Совместимость"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:850
+msgid ""
+"Here are (some of) platforms that KAME code have tested IPsec/IKE "
+"interoperability in the past. Note that both ends may have modified their "
+"implementation, so use the following list just for reference purposes."
+msgstr ""
+"Вот некоторые из платформ, на которых код KAME тестировал взаимодействие "
+"IPsec/IKE в прошлом. Обратите внимание, что обе стороны могли изменить свои "
+"реализации, поэтому используйте следующий список только в справочных целях."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/ipv6/_index.adoc:851
+msgid ""
+"Altiga, Ashley-laurent (vpcom.com), Data Fellows (F-Secure), Ericsson ACC, "
+"FreeS/WAN, HITACHI, IBM AIX(R), IIJ, Intel, Microsoft(R) Windows NT(R), NIST "
+"(linux IPsec + plutoplus), Netscreen, OpenBSD, RedCreek, Routerware, SSH, "
+"Secure Computing, Soliton, Toshiba, VPNet, Yamaha RT100i"
+msgstr ""
+"Altiga, Ashley-laurent (vpcom.com), Data Fellows (F-Secure), Ericsson ACC, "
+"FreeS/WAN, HITACHI, IBM AIX(R), IIJ, Intel, Microsoft(R) Windows NT(R), NIST "
+"(linux IPsec + plutoplus), Netscreen, OpenBSD, RedCreek, Routerware, SSH, "
+"Secure Computing, Soliton, Toshiba, VPNet, Yamaha RT100i"
diff --git a/documentation/content/ru/books/developers-handbook/kernelbuild/_index.adoc b/documentation/content/ru/books/developers-handbook/kernelbuild/_index.adoc
new file mode 100644
index 0000000000..a020ccd898
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/kernelbuild/_index.adoc
@@ -0,0 +1,94 @@
+---
+authors:
+description: 'Сборка и установка ядра FreeBSD'
+next: books/developers-handbook/kerneldebug
+params:
+ path: /books/developers-handbook/kernelbuild/
+prev: books/developers-handbook/partiii
+showBookMenu: true
+tags: ["building", "installing", "kernel", "FreeBSD"]
+title: 'Глава 9. Сборка и установка ядра FreeBSD'
+weight: 12
+---
+
+[[kernelbuild]]
+= Сборка и установка ядра FreeBSD
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 9
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+Чтобы быть разработчиком ядра, требуется понимания процесса сборки ядра. Для отладки ядра FreeBSD необходимо уметь его собирать. Существует два известных способа сделать это:
+
+Поддерживаемая процедура сборки и установки ядра описана в главе extref:{handbook}kernelconfig/[Сборка и установка пользовательского ядра, kernelconfig-building] Руководства FreeBSD.
+
+[NOTE]
+====
+Предполагается, что читатель этой главы знаком с информацией, изложенной в главе extref:{handbook}kernelconfig/[Сборка и установка пользовательского ядра, kernelconfig-building] Руководства FreeBSD. Если это не так, пожалуйста, ознакомьтесь с упомянутой главой, чтобы понять, как работает процесс сборки.
+====
+
+[[kernelbuild-traditional]]
+== Построение более быстрым, но менее надежным способом
+
+Сборка ядра таким способом может быть полезной при работе с кодом ядра и может оказаться быстрее, чем описанная процедура, если в конфигурационном файле ядра были изменены только одна или две опции. С другой стороны, это может привести к неожиданным сбоям при сборке ядра.
+
+[.procedure]
+. Выполните man:config[8] для генерации исходного кода ядра:
++
+[source, bash]
+....
+# /usr/sbin/config MYKERNEL
+....
+
+. Перейдите в каталог сборки. man:config[8] выведет имя этого каталога после выполнения, как указано выше.
++
+[source, bash]
+....
+# cd ../compile/MYKERNEL
+....
+
+. Скомпилируйте ядро:
++
+[source, bash]
+....
+# make depend
+# make
+....
+
+. Установите новое ядро:
++
+[source, bash]
+....
+# make install
+....
diff --git a/documentation/content/ru/books/developers-handbook/kernelbuild/_index.po b/documentation/content/ru/books/developers-handbook/kernelbuild/_index.po
new file mode 100644
index 0000000000..0230e59c60
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/kernelbuild/_index.po
@@ -0,0 +1,140 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-24 20:10+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookkernelbuild_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:15
+#, no-wrap
+msgid "Building and Installing a FreeBSD Kernel"
+msgstr "Сборка и установка ядра FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:1
+#, no-wrap
+msgid "Chapter 9. Building and Installing a FreeBSD Kernel"
+msgstr "Глава 9. Сборка и установка ядра FreeBSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:55
+msgid ""
+"Being a kernel developer requires understanding of the kernel build "
+"process. To debug the FreeBSD kernel it is required to be able to build "
+"one. There are two known ways to do so:"
+msgstr ""
+"Чтобы быть разработчиком ядра, требуется понимания процесса сборки ядра. Для "
+"отладки ядра FreeBSD необходимо уметь его собирать. Существует два известных "
+"способа сделать это:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:57
+msgid ""
+"The supported procedure to build and install a kernel is documented in the "
+"extref:{handbook}kernelconfig/[Building and Installing a Custom Kernel, "
+"kernelconfig-building] chapter of the FreeBSD Handbook."
+msgstr ""
+"Поддерживаемая процедура сборки и установки ядра описана в главе extref:"
+"{handbook}kernelconfig/[Сборка и установка пользовательского ядра, "
+"kernelconfig-building] Руководства FreeBSD."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:62
+msgid ""
+"It is supposed that the reader of this chapter is familiar with the "
+"information described in the extref:{handbook}kernelconfig/[Building and "
+"Installing a Custom Kernel, kernelconfig-building] chapter of the FreeBSD "
+"Handbook. If this is not the case, please read through the above mentioned "
+"chapter to understand how the build process works."
+msgstr ""
+"Предполагается, что читатель этой главы знаком с информацией, изложенной в "
+"главе extref:{handbook}kernelconfig/[Сборка и установка пользовательского "
+"ядра, kernelconfig-building] Руководства FreeBSD. Если это не так, "
+"пожалуйста, ознакомьтесь с упомянутой главой, чтобы понять, как работает "
+"процесс сборки."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:65
+#, no-wrap
+msgid "Building the Faster but Brittle Way"
+msgstr "Построение более быстрым, но менее надежным способом"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:69
+msgid ""
+"Building the kernel this way may be useful when working on the kernel code "
+"and it may actually be faster than the documented procedure when only a "
+"single option or two were tweaked in the kernel configuration file. On the "
+"other hand, it might lead to unexpected kernel build breakage."
+msgstr ""
+"Сборка ядра таким способом может быть полезной при работе с кодом ядра и "
+"может оказаться быстрее, чем описанная процедура, если в конфигурационном "
+"файле ядра были изменены только одна или две опции. С другой стороны, это "
+"может привести к неожиданным сбоям при сборке ядра."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:72
+msgid "Run man:config[8] to generate the kernel source code:"
+msgstr "Выполните man:config[8] для генерации исходного кода ядра:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:76
+#, no-wrap
+msgid "# /usr/sbin/config MYKERNEL\n"
+msgstr "# /usr/sbin/config MYKERNEL\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:79
+msgid ""
+"Change into the build directory. man:config[8] will print the name of this "
+"directory after being run as above."
+msgstr ""
+"Перейдите в каталог сборки. man:config[8] выведет имя этого каталога после "
+"выполнения, как указано выше."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:83
+#, no-wrap
+msgid "# cd ../compile/MYKERNEL\n"
+msgstr "# cd ../compile/MYKERNEL\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:86
+msgid "Compile the kernel:"
+msgstr "Скомпилируйте ядро:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:91
+#, no-wrap
+msgid ""
+"# make depend\n"
+"# make\n"
+msgstr ""
+"# make depend\n"
+"# make\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:94
+msgid "Install the new kernel:"
+msgstr "Установите новое ядро:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kernelbuild/_index.adoc:98
+#, no-wrap
+msgid "# make install\n"
+msgstr "# make install\n"
diff --git a/documentation/content/ru/books/developers-handbook/kerneldebug/_index.adoc b/documentation/content/ru/books/developers-handbook/kerneldebug/_index.adoc
new file mode 100644
index 0000000000..5ac6d8df9f
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/kerneldebug/_index.adoc
@@ -0,0 +1,773 @@
+---
+authors:
+ -
+ author: 'Paul Richards'
+ -
+ author: 'Jörg Wunsch'
+ -
+ author: 'Robert Watson'
+description: 'Отладка ядра FreeBSD'
+next: books/developers-handbook/partiv
+params:
+ path: /books/developers-handbook/kerneldebug/
+prev: books/developers-handbook/kernelbuild
+showBookMenu: true
+tags: ["Debugging", "Dump", "kgdb", "DDB", "GDB"]
+title: 'Глава 10. Отладка ядра'
+weight: 13
+---
+
+[[kerneldebug]]
+= Отладка ядра
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 10
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[kerneldebug-obtain]]
+== Получение аварийного дампа ядра
+
+При работе с разрабатываемым ядром (например, FreeBSD-CURRENT), особенно в экстремальных условиях (например, при очень высокой загрузке, десятках тысяч соединений, чрезвычайно большом количестве одновременных пользователей, сотнях man:jail[8] и т.д.), или при использовании новой функции или драйвера устройства в FreeBSD-STABLE (например, PAE), иногда может возникнуть паника ядра. В случае, если это произойдет, данная глава покажет, как извлечь полезную информацию из аварийного дампа.
+
+Перезагрузка системы неизбежна после паники ядра. После перезагрузки системы содержимое физической памяти (RAM) теряется, как и любые данные на устройстве подкачки перед паникой. Чтобы сохранить данные в физической памяти, ядро использует устройство подкачки как временное хранилище для данных из RAM после сбоя и перезагрузки. Благодаря этому, когда FreeBSD загружается после сбоя, образ ядра может быть извлечен и проведена отладка.
+
+[NOTE]
+====
+Устройство подкачки, настроенное как устройство для дампа, продолжает функционировать как устройство подкачки. В настоящее время дампы на устройства, не являющиеся устройствами подкачки (например, на ленты или CDRW), не поддерживаются. Термин "устройство подкачки" является синонимом термина "раздел подкачки".
+====
+
+Есть несколько типов аварийных дампов ядра:
+
+Полные дампы памяти::
+Содержат полное содержимое физической памяти.
+
+Минидампы::
+Содержат только страницы памяти, используемые ядром (FreeBSD 6.2 и выше).
+
+Текстовые дампы::
+Содержать захваченные, записанные или интерактивные выходные данные отладчика (FreeBSD 7.1 и выше).
+
+Минидампы являются типом дампа по умолчанию, начиная с FreeBSD 7.0, и в большинстве случаев они сохраняют всю необходимую информацию, присутствующую в полном дампе памяти, так как большинство проблем можно изолировать, используя только состояние ядра.
+
+[[config-dumpdev]]
+=== Настройка устройства дампа
+
+Прежде чем ядро запишет содержимое своей физической памяти на устройство дампа, необходимо настроить это устройство. Устройство дампа указывается с помощью команды man:dumpon[8], чтобы сообщить ядру, куда сохранять аварийные дампы. Программа man:dumpon[8] должна быть вызвана после настройки раздела подкачки с помощью man:swapon[8]. Обычно это обрабатывается установкой переменной `dumpdev` в man:rc.conf[5] в путь к устройству подкачки (рекомендуемый способ извлечения дампа ядра) или в значение `AUTO` для использования первого настроенного устройства подкачки. По умолчанию `dumpdev` имеет значение `AUTO` в HEAD и изменено на `NO` в ветках RELENG_* (за исключением RELENG_7, где оставлено значение `AUTO`). Начиная с FreeBSD 9.0-RELEASE и более поздних версий, bsdinstall будет спрашивать, следует ли включить аварийные дампы на целевой системе во время процесса установки.
+
+[TIP]
+====
+Проверьте [.filename]#/etc/fstab# или man:swapinfo[8] для получения списка устройств подкачки.
+====
+
+[IMPORTANT]
+====
+Убедитесь, что каталог `dumpdir`, указанный в man:rc.conf[5], существует перед аварией ядра!
+
+[source, bash]
+....
+# mkdir /var/crash
+# chmod 700 /var/crash
+....
+
+Также помните, что содержимое [.filename]#/var/crash# является конфиденциальным и, скорее всего, содержит секретную информацию, такую как пароли.
+====
+
+[[extract-dump]]
+=== Извлечение дампа ядра
+
+После записи дампа на устройство дампа, дамп должен быть извлечен до монтирования устройства подкачки. Для извлечения дампа с устройства дампа используйте программу man:savecore[8]. Если в man:rc.conf[5] установлен параметр `dumpdev`, man:savecore[8] будет автоматически вызван при первой загрузке в многопользовательском режиме после сбоя и до монтирования устройства подкачки. Расположение извлеченного ядра указывается в параметре `dumpdir` файла man:rc.conf[5], по умолчанию это [.filename]#/var/crash#, а имя файла будет [.filename]#vmcore.0#.
+
+В случае, если файл с именем [.filename]#vmcore.0# уже существует в [.filename]#/var/crash# (или в каталоге, указанном в параметре `dumpdir`), ядро будет увеличивать завершающее число при каждом сбое, чтобы избежать перезаписи существующего файла [.filename]#vmcore# (например, [.filename]#vmcore.1#). man:savecore[8] всегда создает символическую ссылку с именем [.filename]#vmcore.last# в [.filename]#/var/crash# после сохранения дампа. Эта символическая ссылка может быть использована для определения имени последнего дампа.
+
+Утилита man:crashinfo[8] создаёт текстовый файл, содержащий сводную информацию из полного дампа памяти или минидампа. Если параметр `dumpdev` установлен в man:rc.conf[5], man:crashinfo[8] будет автоматически вызван после man:savecore[8]. Результат сохраняется в файл с именем [.filename]#core.txt.N# в директории `dumpdir`.
+
+[TIP]
+====
+Если вы тестируете новое ядро, но вам нужно загрузить другое, чтобы снова запустить систему, загрузите его только в однопользовательском режиме, используя флаг `-s` при загрузке, а затем выполните следующие шаги:
+
+[source, bash]
+....
+# fsck -p
+# mount -a -t ufs # make sure /var/crash is writable
+# savecore /var/crash /dev/ad0s1b
+# exit # exit to multi-user
+....
+
+Это указывает man:savecore[8] извлечь дамп ядра из [.filename]#/dev/ad0s1b# и поместить содержимое в [.filename]#/var/crash#. Не забудьте убедиться, что целевой каталог [.filename]#/var/crash# имеет достаточно места для дампа. Также не забудьте указать правильный путь к вашему swap-устройству, так как он, скорее всего, отличается от [.filename]#/dev/ad0s1b#!
+====
+
+=== Тестирование конфигурации дампа ядра
+
+Ядро включает узел man:sysctl[8], который вызывает панику ядра. Это можно использовать для проверки того, что ваша система правильно настроена для сохранения дампов аварийного завершения работы ядра. Возможно, вы захотите перемонтировать существующие файловые системы в режиме только для чтения в однопользовательском режиме перед тем, как вызвать панику, чтобы избежать потери данных.
+
+[source, bash]
+....
+# shutdown now
+...
+Enter full pathname of shell or RETURN for /bin/sh:
+# mount -a -u -r
+# sysctl debug.kdb.panic=1
+debug.kdb.panic:panic: kdb_sysctl_panic
+...
+....
+
+После перезагрузки система должна сохранить дамп в [.filename]#/var/crash# вместе с соответствующим отчетом из man:crashinfo[8].
+
+[[kerneldebug-gdb]]
+== Отладка аварийного дампа ядра с помощью `kgdb`
+
+[NOTE]
+====
+Этот раздел посвящен man:kgdb[1]. Последняя версия включена в пакет package:devel/gdb[]. Более старая версия также присутствует в FreeBSD 11 и более ранних версиях.
+====
+
+Чтобы войти в отладчик и начать получение информации из дампа, запустите kgdb:
+
+[source, bash]
+....
+# kgdb -n N
+....
+
+Где _N_ — это суффикс файла [.filename]#vmcore.N#, который нужно изучить. Чтобы открыть последний дамп, используйте:
+
+[source, bash]
+....
+# kgdb -n last
+....
+
+Обычно man:kgdb[1] должен быть способен найти ядро, работавшее в момент создания дампа. Если он не может найти нужное ядро, передайте путь к ядру и дампу в качестве двух аргументов для kgdb:
+
+[source, bash]
+....
+# kgdb /boot/kernel/kernel /var/crash/vmcore.0
+....
+
+Вы можете отлаживать дамп аварийного завершения, используя исходные коды ядра, так же, как и для любой другой программы.
+
+Этот дамп получен из ядра версии 5.2-BETA, а крах произошел глубоко внутри ядра. Приведенный ниже вывод был изменен для добавления номеров строк слева. Первый трассировочный вывод проверяет указатель инструкции и получает обратную трассировку. Адрес, используемый в строке 41 для команды `list`, является указателем инструкции и может быть найден в строке 17. Большинство разработчиков запросят как минимум эту информацию, если вы не сможете отладить проблему самостоятельно. Однако, если вы решите проблему, убедитесь, что ваш патч попадет в дерево исходников через отчет о проблеме, списки рассылки, или, может быть, у вас есть возможность его закоммитить!
+
+[source, bash]
+....
+ 1:# cd /usr/obj/usr/src/sys/KERNCONF
+ 2:# kgdb kernel.debug /var/crash/vmcore.0
+ 3:GNU gdb 5.2.1 (FreeBSD)
+ 4:Copyright 2002 Free Software Foundation, Inc.
+ 5:GDB is free software, covered by the GNU General Public License, and you are
+ 6:welcome to change it and/or distribute copies of it under certain conditions.
+ 7:Type "show copying" to see the conditions.
+ 8:There is absolutely no warranty for GDB. Type "show warranty" for details.
+ 9:This GDB was configured as "i386-undermydesk-freebsd"...
+10:panic: page fault
+11:panic messages:
+12:---
+13:Fatal trap 12: page fault while in kernel mode
+14:cpuid = 0; apic id = 00
+15:fault virtual address = 0x300
+16:fault code: = supervisor read, page not present
+17:instruction pointer = 0x8:0xc0713860
+18:stack pointer = 0x10:0xdc1d0b70
+19:frame pointer = 0x10:0xdc1d0b7c
+20:code segment = base 0x0, limit 0xfffff, type 0x1b
+21: = DPL 0, pres 1, def32 1, gran 1
+22:processor eflags = resume, IOPL = 0
+23:current process = 14394 (uname)
+24:trap number = 12
+25:panic: page fault
+26 cpuid = 0;
+27:Stack backtrace:
+28
+29:syncing disks, buffers remaining... 2199 2199 panic: mi_switch: switch in a critical section
+30:cpuid = 0;
+31:Uptime: 2h43m19s
+32:Dumping 255 MB
+33: 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240
+34:---
+35:Reading symbols from /boot/kernel/snd_maestro3.ko...done.
+36:Loaded symbols for /boot/kernel/snd_maestro3.ko
+37:Reading symbols from /boot/kernel/snd_pcm.ko...done.
+38:Loaded symbols for /boot/kernel/snd_pcm.ko
+39:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240
+40:240 dumping++;
+41:(kgdb) list *0xc0713860
+42:0xc0713860 is in lapic_ipi_wait (/usr/src/sys/i386/i386/local_apic.c:663).
+43:658 incr = 0;
+44:659 delay = 1;
+45:660 } else
+46:661 incr = 1;
+47:662 for (x = 0; x < delay; x += incr) {
+48:663 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
+49:664 return (1);
+50:665 ia32_pause();
+51:666 }
+52:667 return (0);
+53:(kgdb) backtrace
+54:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240
+55:#1 0xc055fd9b in boot (howto=260) at /usr/src/sys/kern/kern_shutdown.c:372
+56:#2 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550
+57:#3 0xc0567ef5 in mi_switch () at /usr/src/sys/kern/kern_synch.c:470
+58:#4 0xc055fa87 in boot (howto=256) at /usr/src/sys/kern/kern_shutdown.c:312
+59:#5 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550
+60:#6 0xc0720c66 in trap_fatal (frame=0xdc1d0b30, eva=0)
+61: at /usr/src/sys/i386/i386/trap.c:821
+62:#7 0xc07202b3 in trap (frame=
+63: {tf_fs = -1065484264, tf_es = -1065484272, tf_ds = -1065484272, tf_edi = 1, tf_esi = 0, tf_ebp = -602076292, tf_isp = -602076324, tf_ebx = 0, tf_edx = 0, tf_ecx = 1000000, tf_eax = 243, tf_trapno = 12, tf_err = 0, tf_eip = -1066321824, tf_cs = 8, tf_eflags = 65671, tf_esp = 243, tf_ss = 0})
+64: at /usr/src/sys/i386/i386/trap.c:250
+65:#8 0xc070c9f8 in calltrap () at {standard input}:94
+66:#9 0xc07139f3 in lapic_ipi_vectored (vector=0, dest=0)
+67: at /usr/src/sys/i386/i386/local_apic.c:733
+68:#10 0xc0718b23 in ipi_selected (cpus=1, ipi=1)
+69: at /usr/src/sys/i386/i386/mp_machdep.c:1115
+70:#11 0xc057473e in kseq_notify (ke=0xcc05e360, cpu=0)
+71: at /usr/src/sys/kern/sched_ule.c:520
+72:#12 0xc0575cad in sched_add (td=0xcbcf5c80)
+73: at /usr/src/sys/kern/sched_ule.c:1366
+74:#13 0xc05666c6 in setrunqueue (td=0xcc05e360)
+75: at /usr/src/sys/kern/kern_switch.c:422
+76:#14 0xc05752f4 in sched_wakeup (td=0xcbcf5c80)
+77: at /usr/src/sys/kern/sched_ule.c:999
+78:#15 0xc056816c in setrunnable (td=0xcbcf5c80)
+79: at /usr/src/sys/kern/kern_synch.c:570
+80:#16 0xc0567d53 in wakeup (ident=0xcbcf5c80)
+81: at /usr/src/sys/kern/kern_synch.c:411
+82:#17 0xc05490a8 in exit1 (td=0xcbcf5b40, rv=0)
+83: at /usr/src/sys/kern/kern_exit.c:509
+84:#18 0xc0548011 in sys_exit () at /usr/src/sys/kern/kern_exit.c:102
+85:#19 0xc0720fd0 in syscall (frame=
+86: {tf_fs = 47, tf_es = 47, tf_ds = 47, tf_edi = 0, tf_esi = -1, tf_ebp = -1077940712, tf_isp = -602075788, tf_ebx = 672411944, tf_edx = 10, tf_ecx = 672411600, tf_eax = 1, tf_trapno = 12, tf_err = 2, tf_eip = 671899563, tf_cs = 31, tf_eflags = 642, tf_esp = -1077940740, tf_ss = 47})
+87: at /usr/src/sys/i386/i386/trap.c:1010
+88:#20 0xc070ca4d in Xint0x80_syscall () at {standard input}:136
+89:---Can't read userspace from dump, or kernel process---
+90:(kgdb) quit
+....
+
+[TIP]
+====
+Если ваша система регулярно завершается аварийно и у вас заканчивается место на диске, удаление старых файлов [.filename]#vmcore# в [.filename]#/var/crash# может освободить значительное количество дискового пространства!
+====
+
+[[kerneldebug-online-ddb]]
+== Онлайн-отладка ядра с использованием DDB
+
+В то время как `kgdb` как автономный отладчик предоставляет очень высокий уровень пользовательского интерфейса, есть некоторые вещи, которые он не может выполнить. Наиболее важные из них — установка точек останова и пошаговое выполнение кода ядра.
+
+Если вам требуется выполнить низкоуровневую отладку ядра, доступен отладчик DDB, работающий в режиме реального времени. Он позволяет устанавливать точки останова, выполнять пошаговое выполнение функций ядра, проверять и изменять переменные ядра и т.д. Однако он не имеет доступа к исходным файлам ядра и работает только с глобальными и статическими символами, без доступа к полной отладочной информации, как это делает `kgdb`.
+
+Для настройки ядра с включенной поддержкой DDB добавьте параметры
+[.programlisting]
+....
+options KDB
+....
+
+[.programlisting]
+....
+options DDB
+....
+
+в ваш конфигурационный файл, и пересоберите. (Подробности о настройке ядра FreeBSD см. в extref:{handbook}[Руководстве FreeBSD]).
+
+После загрузки ядра DDB существует несколько способов войти в него. Первый и самый ранний способ — использовать флаг загрузки `-d`. Ядро запустится в режиме отладки и перейдет в DDB до начала обнаружения любого из устройств. Таким образом, можно отлаживать даже функции обнаружить (probe)/ присоединить (attach) устройств. Для использования этого метода выйдите из меню загрузки загрузчика и введите `boot -d` в командной строке загрузчика.
+
+Второй сценарий — перейти в отладчик после загрузки системы. Есть два простых способа это сделать. Если вы хотите перейти в отладчик из командной строки, просто введите команду:
+
+[source, bash]
+....
+# sysctl debug.kdb.enter=1
+....
+
+В качестве альтернативы, если вы находитесь за системной консолью, можно использовать горячую клавишу на клавиатуре. Стандартной комбинацией для перехода в отладчик является kbd:[Ctrl+Alt+ESC]. В syscons эта последовательность может быть переназначена, и некоторые распространённые раскладки клавиатуры делают это, поэтому убедитесь, что знаете правильную комбинацию. Для последовательных консолей доступна опция, позволяющая использовать сигнал BREAK на линии консоли для входа в DDB (`options BREAK_TO_DEBUGGER` в конфигурационном файле ядра). Это не установлено по умолчанию, так как существует множество последовательных адаптеров, которые излишне генерируют условие BREAK, например, при отключении кабеля.
+
+Третий способ заключается в том, чтобы любое условие паники переходило в DDB, если ядро настроено на его использование. По этой причине не рекомендуется настраивать ядро с DDB для машины, работающей без присмотра.
+
+Для получения неинтерактивной функциональности добавьте:
+
+[.programlisting]
+....
+options KDB_UNATTENDED
+....
+
+в файл конфигурации ядра и пересоберите/переустановите ядро.
+
+Команды DDB примерно напоминают некоторые команды `gdb`. Первое, что вам, вероятно, нужно сделать, это установить точку останова:
+
+[source, bash]
+....
+ break function-name address
+....
+
+Числа по умолчанию интерпретируются как шестнадцатеричные, но чтобы отличить
+их от символьных имен, шестнадцатеричные числа, начинающиеся с букв `a-f`,
+должны предваряться префиксом `0x` (для остальных чисел это
+необязательно). Допускаются простые выражения, например: `function-name +
+0x103`.
+
+Для выхода из отладчика и продолжения выполнения введите:
+
+[source, bash]
+....
+ continue
+....
+
+Для получения трассировки стека текущего потока используйте:
+
+[source, bash]
+....
+ trace
+....
+
+Для получения трассировки стека произвольного потока укажите идентификатор процесса или идентификатор потока в качестве второго аргумента команды `trace`.
+
+Если вы хотите удалить точку останова, используйте
+
+[source, bash]
+....
+ del
+ del address-expression
+....
+
+Первая форма будет принята сразу после срабатывания точки останова и удаляет текущую точку останова. Вторая форма может удалить любую точку останова, но необходимо указать точный адрес; его можно получить из:
+
+[source, bash]
+....
+ show b
+....
+
+или:
+
+[source, bash]
+....
+ show break
+....
+
+Для пошагового выполнения ядра попробуйте:
+
+[source, bash]
+....
+ s
+....
+
+Это позволит войти в функции, но вы можете заставить DDB отслеживать их до достижения соответствующего оператора return с помощью:
+
+[source, bash]
+....
+ n
+....
+
+[NOTE]
+====
+Это отличается от оператора `next` в ``gdb``; это похоже на `finish` в ``gdb``. Нажатие kbd:[n] более одного раза приведёт к продолжению.
+====
+
+Для просмотра данных в памяти используйте (например):
+
+[source, bash]
+....
+ x/wx 0xf0133fe0,40
+ x/hd db_symtab_space
+ x/bc termbuf,10
+ x/s stringbuf
+....
+
+для доступа к словам/полусловам/байтам и отображения в шестнадцатеричном/десятичном/символьном/строковом формате. Число после запятой указывает количество объектов. Для отображения следующих 0x10 элементов просто введите:
+
+[source, bash]
+....
+ x ,10
+....
+
+Аналогично, используйте
+
+[source, bash]
+....
+ x/ia foofunc,10
+....
+
+для дизассемблирования первых 0x10 инструкций функции `foofunc` и их отображения вместе с их смещением от начала `foofunc`.
+
+Для записи в память используйте команду write:
+
+[source, bash]
+....
+ w/b termbuf 0xa 0xb 0
+ w/w 0xf0010030 0 0
+....
+
+Модификатор команды (`b`/`h`/`w`) определяет размер данных для записи, первое следующее выражение — это адрес для записи, а остальное интерпретируется как данные для записи в последующие ячейки памяти.
+
+Если вам необходимо узнать текущее содержимое регистров, введите:
+
+[source, bash]
+....
+ show reg
+....
+
+Также можно отобразить значение одного регистра, например:
+
+[source, bash]
+....
+ p $eax
+....
+
+и изменить его с помощью:
+
+[source, bash]
+....
+ set $eax new-value
+....
+
+Если вам потребуется вызвать некоторые функции ядра из DDB, просто напишите:
+
+[source, bash]
+....
+ call func(arg1, arg2, ...)
+....
+
+Будет выведено возвращаемое значение.
+
+Для вывода информации о всех запущенных процессах в стиле man:ps[1] используйте:
+
+[source, bash]
+....
+ ps
+....
+
+Теперь вы выяснили причину сбоя ядра и хотите выполнить перезагрузку. Помните, что в зависимости от серьезности предыдущего сбоя не все части ядра могут работать корректно. Выполните одно из следующих действий для завершения работы и перезагрузки системы:
+
+[source, bash]
+....
+ panic
+....
+
+Это приведёт к дампу ядра и перезагрузке, чтобы позже можно было проанализировать дамп на более высоком уровне с помощью man:kgdb[1].
+
+[source, bash]
+....
+ call boot(0)
+....
+
+Может быть хорошим способом чисто завершить работу работающей системы, `sync()` все диски и, наконец, в некоторых случаях перезагрузиться. Пока интерфейсы дисков и файловых систем ядра не повреждены, это может быть хорошим способом для почти чистого завершения работы.
+
+[source, bash]
+....
+ reset
+....
+
+Это последний способ избежать катастрофы, и он почти такой же, как нажатие на Большую Красную Кнопку.
+
+Если вам нужна краткая сводка команд, просто введите:
+
+[source, bash]
+....
+ help
+....
+
+Настоятельно рекомендуется иметь распечатанную копию страницы руководства man:ddb[4] для сеанса отладки. Помните, что читать онлайн-руководство во время пошагового выполнения ядра сложно.
+
+[[kerneldebug-online-gdb]]
+== Онлайн-отладка ядра с использованием удаленного GDB
+
+Ядро FreeBSD предоставляет второй бэкенд KDB для отладки в реальном времени: man:gdb[4]. Эта возможность поддерживается с FreeBSD 2.2 и является действительно очень удобной.
+
+GDB давно поддерживает _удалённую отладку_. Это осуществляется с помощью очень простого протокола через последовательное соединение. В отличие от других методов отладки, описанных выше, для этого потребуются две машины. Одна — это хост, предоставляющий среду отладки, включая все исходные тексты и копию бинарного файла ядра со всеми символами. Другая — целевая машина, на которой запущена копия того же самого ядра (возможно, без отладочной информации).
+
+Чтобы использовать удалённый GDB, убедитесь, что следующие параметры присутствуют в конфигурации вашего ядра:
+[.programlisting]
+....
+makeoptions DEBUG=-g
+options KDB
+options GDB
+....
+
+Обратите внимание, что опция `GDB` отключена по умолчанию в ядрах `GENERIC` для веток -STABLE и -RELEASE, но включена в -CURRENT.
+
+После сборки скопируйте ядро на целевую машину и загрузите его. Подключите последовательный порт целевой машины, у которого на устройстве uart установлены флаги "080", к любому последовательному порту отладочной машины. Подробности о настройке флагов на устройстве uart смотрите в man:uart[4].
+
+Целевая машина должна быть переведена в режим отладчика GDB, либо из-за паники, либо путем преднамеренного перехода в отладчик. Перед этим выберите бэкенд отладчика GDB:
+[source, bash]
+....
+# sysctl debug.kdb.current=gdb
+debug.kdb.current: ddb -> gdb
+....
+
+[NOTE]
+====
+Поддерживаемые бэкенды можно вывести с помощью sysctl `debug.kdb.available`. Если конфигурация ядра включает `options DDB`, то man:ddb[4] будет выбран по умолчанию. Если `gdb` не отображается в списке доступных бэкендов, значит, последовательный порт отладки может быть настроен неправильно.
+====
+
+Затем принудительно войдите в отладчик:
+[source, bash]
+....
+# sysctl debug.kdb.enter=1
+debug.kdb.enter: 0KDB: enter: sysctl debug.kdb.enter
+....
+
+Целевая машина теперь ожидает подключения от удалённого клиента GDB. На машине для отладки перейдите в каталог сборки целевого ядра и запустите `gdb`:
+
+[source, bash]
+....
+# cd /usr/obj/usr/src/amd64.amd64/sys/GENERIC/
+# kgdb kernel
+GNU gdb (GDB) 10.2 [GDB v10.2 for FreeBSD]
+Copyright (C) 2021 Free Software Foundation, Inc.
+...
+Reading symbols from kernel...
+Reading symbols from /usr/obj/usr/src/amd64.amd64/sys/GENERIC/kernel.debug...
+(kgdb)
+....
+
+Инициализируйте сеанс удаленной отладки (предполагая, что используется первый последовательный порт) с помощью:
+
+[source, bash]
+....
+(kgdb) target remote /dev/cuau0
+....
+
+Ваш хостинг GDB теперь получит контроль над целевым ядром:
+
+[source, bash]
+....
+Remote debugging using /dev/cuau0
+kdb_enter (why=<optimized out>, msg=<optimized out>) at /usr/src/sys/kern/subr_kdb.c:506
+506 kdb_why = KDB_WHY_UNSET;
+(kgdb)
+....
+
+[TIP]
+====
+В зависимости от используемого компилятора, некоторые локальные переменные могут отображаться как `<optimized out>`, что не позволяет их напрямую исследовать с помощью `gdb`. Если это вызывает проблемы при отладке, можно собрать ядро с пониженным уровнем оптимизации, что может улучшить видимость некоторых переменных. Это можно сделать, передав `COPTFLAGS=-O1` в man:make[1]. Однако определённые классы ошибок в ядре могут проявляться иначе (или вообще не проявляться) при изменении уровня оптимизации.
+====
+
+Вы можете использовать этот сеанс почти как любой другой сеанс GDB, включая полный доступ к исходному коду, запуск в режиме gud (Grand Unified Debugger) внутри окна Emacs (что дает автоматическое отображение исходного кода в другом окне Emacs) и т.д.
+
+[[kerneldebug-console]]
+== Отладка драйвера консоли
+
+Поскольку для работы DDB требуется драйвер консоли, ситуация усложняется, если сам драйвер консоли неисправен. Возможно, вы вспомните о возможности использования последовательной консоли (либо с модифицированными загрузочными блоками, либо указав `-h` в строке `Boot:`), подключив стандартный терминал к первому последовательному порту. DDB работает с любым настроенным драйвером консоли, включая последовательную консоль.
+
+[[kerneldebug-deadlocks]]
+== Отладка взаимоблокировок
+
+Вы можете столкнуться с так называемыми взаимоблокировками — ситуацией, когда система перестает выполнять полезную работу. Чтобы предоставить полезный отчет об ошибке в такой ситуации, используйте man:ddb[4], как описано в предыдущем разделе. Включите в отчет вывод команд `ps` и `trace` для подозрительных процессов.
+
+Если возможно, рассмотрите проведение дополнительного исследования. Приведенный ниже рецепт особенно полезен, если вы подозреваете, что взаимная блокировка происходит на уровне VFS. Добавьте следующие параметры в файл конфигурации ядра.
+
+[.programlisting]
+....
+makeoptions DEBUG=-g
+options INVARIANTS
+options INVARIANT_SUPPORT
+options WITNESS
+options WITNESS_SKIPSPIN
+options DEBUG_LOCKS
+options DEBUG_VFS_LOCKS
+options DIAGNOSTIC
+....
+
+При возникновении взаимоблокировки, помимо вывода команды `ps`, предоставьте информацию из `show pcpu`, `show allpcpu`, `show locks`, `show alllocks`, `show lockedvnods` и `alltrace`.
+
+Для получения осмысленных трассировок стека для потоковых процессов используйте `thread thread-id` для переключения на стек потока и выполните трассировку с помощью `where`.
+
+[[kerneldebug-dcons]]
+== Отладка ядра с помощью Dcons
+
+man:dcons[4] — это очень простой драйвер консоли, который не связан напрямую с какими-либо физическими устройствами. Он просто читает и записывает символы из буфера в ядре или загрузчике и обратно. Благодаря своей простоте он очень полезен для отладки ядра, особенно с устройством FireWire(R). В настоящее время FreeBSD предоставляет два способа взаимодействия с буфером извне ядра с помощью man:dconschat[8].
+
+=== Dcons через FireWire(R)
+
+Большинство контроллеров FireWire(R) (IEEE1394) основаны на спецификации OHCI, которая поддерживает физический доступ к памяти хоста. Это означает, что после инициализации контроллера хоста мы можем получить доступ к памяти хоста без помощи программного обеспечения (ядра). Мы можем использовать эту возможность для взаимодействия с man:dcons[4]. man:dcons[4] предоставляет функциональность, аналогичную последовательной консоли. Он эмулирует два последовательных порта: один для консоли и DDB, другой для GDB. Поскольку удалённый доступ к памяти полностью обрабатывается аппаратным обеспечением, буфер man:dcons[4] остаётся доступным даже при крахе системы.
+
+Устройства FireWire(R) не только встраиваются в материнские платы. Для настольных компьютеров существуют PCI-карты, а для ноутбуков можно приобрести интерфейс CardBus.
+
+==== Включение поддержки FireWire(R) и Dcons на целевой машине
+
+Чтобы включить поддержку FireWire(R) и Dcons в ядре _целевой машины_:
+
+* Убедитесь, что ваше ядро поддерживает `dcons`, `dcons_crom` и `firewire`. `Dcons` должен быть статически связан с ядром. Для `dcons_crom` и `firewire` модули должны подойти.
+* Убедитесь, что физический DMA включен. Возможно, потребуется добавить `hw.firewire.phydma_enable=1` в [.filename]#/boot/loader.conf#.
+* Добавьте параметры для отладки.
+* Добавьте `dcons_gdb=1` в [.filename]#/boot/loader.conf#, если вы используете GDB через FireWire(R).
+* Включите `dcons` в [.filename]#/etc/ttys#.
+* Это необязательно: чтобы принудительно сделать `dcons` высокоуровневой консолью, добавьте `hw.firewire.dcons_crom.force_console=1` в [.filename]#loader.conf#.
+
+Чтобы включить поддержку FireWire(R) и Dcons в man:loader[8] на i386 или amd64:
+
+Добавьте `LOADER_FIREWIRE_SUPPORT=YES` в [.filename]#/etc/make.conf# и пересоберите man:loader[8]:
+
+[source, bash]
+....
+# cd /sys/boot/i386 && make clean && make && make install
+....
+
+Чтобы включить man:dcons[4] в качестве активной низкоуровневой консоли, добавьте `boot_multicons="YES"` в [.filename]#/boot/loader.conf#.
+
+Вот несколько примеров конфигурации. Образец файла конфигурации ядра может содержать:
+
+[source, bash]
+....
+device dcons
+device dcons_crom
+options KDB
+options DDB
+options GDB
+options ALT_BREAK_TO_DEBUGGER
+....
+
+И образец [.filename]#/boot/loader.conf# может содержать:
+
+[source, bash]
+....
+dcons_crom_load="YES"
+dcons_gdb=1
+boot_multicons="YES"
+hw.firewire.phydma_enable=1
+hw.firewire.dcons_crom.force_console=1
+....
+
+==== Включение поддержки FireWire(R) и Dcons на главной машине
+
+Чтобы включить поддержку FireWire(R) в ядре на _основной машине_:
+
+[source, bash]
+....
+# kldload firewire
+....
+
+Определите EUI64 (уникальный 64-битный идентификатор) контроллера FireWire(R) и используйте man:fwcontrol[8] или `dmesg`, чтобы найти EUI64 целевой машины.
+
+Запустите man:dconschat[8], с:
+
+[source, bash]
+....
+# dconschat -e \# -br -G 12345 -t 00-11-22-33-44-55-66-77
+....
+
+Следующие комбинации клавиш могут быть использованы после запуска man:dconschat[8]:
+
+[.informaltable]
+[cols="1,1"]
+|===
+
+|kbd:[~+.]
+|Отсоединиться
+
+|kbd:[~]
+|ALT BREAK
+
+|kbd:[~]
+|ПЕРЕЗАГРУЗИТЬ (RESET) целевую машину
+
+|kbd:[~]
+|Приостановить dconschat
+|===
+
+Присоедините удаленный GDB, запустив man:kgdb[1] с сеансом удаленной отладки:
+
+[source, bash]
+....
+ kgdb -r :12345 kernel
+....
+
+==== Некоторые общие рекомендации
+
+Вот несколько общих советов:
+
+Чтобы в полной мере использовать скорость FireWire(R), отключите другие медленные драйверы консоли:
+
+[source, bash]
+....
+# conscontrol delete ttyd0 # serial console
+# conscontrol delete consolectl # video/keyboard
+....
+
+Существует режим GDB для man:emacs[1]; вот что нужно добавить в ваш [.filename]#.emacs#:
+
+[source, bash]
+....
+(setq gud-gdba-command-name "kgdb -a -a -a -r :12345")
+(setq gdb-many-windows t)
+(xterm-mouse-mode 1)
+M-x gdba
+....
+
+=== Dcons с KVM
+
+Мы можем напрямую читать буфер man:dcons[4] через [.filename]#/dev/mem# для работающих систем и в дампе памяти для систем после аварии. Это даёт аналогичный вывод команде `dmesg -a`, но буфер man:dcons[4] содержит больше информации.
+
+==== Использование Dcons с KVM
+
+Для использования man:dcons[4] с KVM:
+
+Дамп буфера man:dcons[4] работающей системы:
+
+[source, bash]
+....
+# dconschat -1
+....
+
+Дамп буфера man:dcons[4] аварийного дампа:
+
+[source, bash]
+....
+# dconschat -1 -M vmcore.XX
+....
+
+Отладка ядра в реальном времени может быть выполнена через:
+
+[source, bash]
+....
+# fwcontrol -m target_eui64
+# kgdb kernel /dev/fwmem0.2
+....
+
+[[kerneldebug-options]]
+== Глоссарий параметров ядра для отладки
+
+В этом разделе представлен краткий глоссарий параметров ядра, указываемых при компиляции и относящихся к отладке:
+
+* `options KDB`: включает фреймворк отладки ядра. Необходим для `options DDB` и `options GDB`. Практически не влияет на производительность. По умолчанию отладчик будет запущен при панике вместо автоматической перезагрузки.
+* `options KDB_UNATTENDED`: изменяет значение по умолчанию системной настройки `debug.debugger_on_panic` на 0, что управляет входом в отладчик при панике. Если `options KDB` не вкомпилировано в ядро, поведение по умолчанию — автоматическая перезагрузка при панике; если оно вкомпилировано в ядро, поведение по умолчанию — переход в отладчик, если не вкомпилирована опция `options KDB_UNATTENDED`. Если вы хотите оставить отладчик ядра вкомпилированным в ядро, но желаете, чтобы система перезагружалась, пока вы не готовы использовать отладчик для диагностики, используйте эту опцию.
+* `options KDB_TRACE`: изменяет значение по умолчанию системной настройки `debug.trace_on_panic` на 1, что управляет автоматическим выводом трассировки стека при панике. Особенно полезно при использовании с `options KDB_UNATTENDED`, так как позволяет собрать базовую отладочную информацию на последовательной консоли или консоли FireWire, продолжая перезагрузку для восстановления.
+* `options DDB`: включает поддержку консольного отладчика DDB. Этот интерактивный отладчик работает на активной низкоуровневой консоли системы, включая видеоконсоль, последовательную консоль или консоль FireWire. Он предоставляет базовые встроенные средства отладки, такие как трассировка стека, список процессов и потоков, вывод состояния блокировок, состояния виртуальной памяти, состояния файловой системы и управления ядром памяти. DDB не требует работы программного обеспечения на второй машине или возможности создания дампа памяти или полных символов отладки ядра, а также предоставляет детальную диагностику ядра во время выполнения. Многие ошибки могут быть полностью диагностированы с использованием только вывода DDB. Эта опция зависит от `options KDB`.
+* `options GDB`: включает поддержку удалённого отладчика GDB, который может работать через последовательный кабель или FireWire. При входе в отладчик можно подключить GDB для проверки содержимого структур, генерации трассировки стека и т.д. Некоторые состояния ядра сложнее исследовать, чем в DDB, который способен автоматически создавать полезные сводки состояния ядра, например, автоматически обходить структуры отладки блокировок или управления памятью ядра, но для этого требуется вторая машина с запущенным отладчиком. С другой стороны, GDB объединяет информацию из исходного кода ядра и полных отладочных символов, знает полные определения структур данных, локальные переменные и поддерживает написание скриптов. Эта опция не требуется для запуска GDB на дампе памяти ядра. Данная опция зависит от `options KDB`.
+* `options BREAK_TO_DEBUGGER`, `options ALT_BREAK_TO_DEBUGGER`: позволяют сигналу прерывания или альтернативному сигналу на консоли войти в отладчик. Если система зависает без паники, это полезный способ попасть в отладчик. Из-за текущей блокировки ядра сигнал прерывания, сгенерированный на последовательной консоли, значительно надежнее для входа в отладчик и обычно рекомендуется. Данная опция оказывает незначительное или нулевое влияние на производительность.
+* `options INVARIANTS`: включает в ядро большое количество проверок и тестов во время выполнения, которые постоянно проверяют целостность структур данных ядра и инварианты алгоритмов ядра. Эти тесты могут быть затратными, поэтому по умолчанию не включены, но они помогают обеспечить полезное поведение "fail stop", при котором определённые классы нежелательного поведения попадают в отладчик до возникновения повреждения данных ядра, что упрощает их отладку. Тесты включают в себя очистку памяти и проверку использования после освобождения, что является одним из наиболее значимых источников накладных расходов. Эта опция зависит от `options INVARIANT_SUPPORT`.
+* `options INVARIANT_SUPPORT`: многие тесты, присутствующие в `options INVARIANTS`, требуют модифицированных структур данных или определения дополнительных символов ядра.
+* `options WITNESS`: эта опция включает отслеживание и проверку порядка блокировок во время выполнения, что является неоценимым инструментом для диагностики взаимоблокировок. WITNESS поддерживает граф полученных порядков блокировок по типам блокировок и проверяет граф на каждом получении на наличие циклов (явных или неявных). Если цикл обнаружен, на консоль выводится предупреждение и трассировка стека, указывающие на возможное возникновение взаимоблокировки. WITNESS необходим для использования команд DDB `show locks`, `show witness` и `show alllocks`. Эта отладочная опция создает значительную нагрузку на производительность, которую можно несколько уменьшить с помощью `options WITNESS_SKIPSPIN`. Подробная документация доступна в man:witness[4].
+* `options WITNESS_SKIPSPIN`: отключает проверку порядка блокировки spinlock во время выполнения с WITNESS. Поскольку spin-блокировки чаще всего захватываются в планировщике, а события планировщика происходят часто, эта опция может значительно ускорить системы, работающие с WITNESS. Эта опция зависит от `options WITNESS`.
+* `options WITNESS_KDB`: изменяет значение по умолчанию системной настройки `debug.witness.kdb` на 1, что приводит к входу в отладчик при обнаружении нарушения порядка блокировок вместо простого вывода предупреждения. Эта опция зависит от `options WITNESS`.
+* `options SOCKBUF_DEBUG`: выполнять расширенную проверку согласованности сокетных буферов во время выполнения, что может быть полезно для отладки как ошибок в сокетах, так и состояний гонки в протоколах и драйверах устройств, взаимодействующих с сокетами. Данная опция значительно влияет на производительность сети и может изменить временные параметры в состояниях гонки драйверов устройств.
+* `options DEBUG_VFS_LOCKS`: отслеживает точки получения блокировок для lockmgr/vnode, расширяя объем информации, отображаемой командой `show lockedvnods` в DDB. Данная опция оказывает заметное влияние на производительность.
+* `options DEBUG_MEMGUARD`: замена для man:malloc[9], аллокатор памяти ядра, который использует систему VM для обнаружения чтения или записи в освобождённую память. Подробности можно найти в man:memguard[9]. Данная опция значительно влияет на производительность, но может быть очень полезна при отладке ошибок повреждения памяти ядра.
+* `options DIAGNOSTIC`: включает дополнительные, более затратные диагностические тесты, аналогичные `options INVARIANTS`.
+* `options KASAN`: включает отладчик адресов ядра (Kernel Address Sanitizer). Это включает инструментирование компилятора, которое может использоваться для обнаружения недопустимых обращений к памяти в ядре, таких как использование после освобождения и переполнение буфера. В значительной степени заменяет `options DEBUG_MEMGUARD`. Подробности и список поддерживаемых платформ см. в man:kasan[9].
+* `options KMSAN`: включить отладчик использования памяти ядра (Kernel Memory Sanitizer). Это включает инструментирование компилятора, которое может использоваться для обнаружения использования неинициализированной памяти. Подробности и список поддерживаемых платформ см. в man:kmsan[9].
diff --git a/documentation/content/ru/books/developers-handbook/kerneldebug/_index.po b/documentation/content/ru/books/developers-handbook/kerneldebug/_index.po
new file mode 100644
index 0000000000..dd46c18a3c
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/kerneldebug/_index.po
@@ -0,0 +1,2243 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookkerneldebug_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:1
+#, no-wrap
+msgid "FreeBSD Kernel Debugging"
+msgstr "Отладка ядра FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:1
+#, no-wrap
+msgid "Chapter 10. Kernel Debugging"
+msgstr "Глава 10. Отладка ядра"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:18
+#, no-wrap
+msgid "Kernel Debugging"
+msgstr "Отладка ядра"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:56
+#, no-wrap
+msgid "Obtaining a Kernel Crash Dump"
+msgstr "Получение аварийного дампа ядра"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:61
+msgid ""
+"When running a development kernel (e.g., FreeBSD-CURRENT), such as a kernel "
+"under extreme conditions (e.g., very high load averages, tens of thousands "
+"of connections, exceedingly high number of concurrent users, hundreds of "
+"man:jail[8]s, etc.), or using a new feature or device driver on FreeBSD-"
+"STABLE (e.g., PAE), sometimes a kernel will panic. In the event that it "
+"does, this chapter will demonstrate how to extract useful information out of "
+"a crash."
+msgstr ""
+"При работе с разрабатываемым ядром (например, FreeBSD-CURRENT), особенно в "
+"экстремальных условиях (например, при очень высокой загрузке, десятках тысяч "
+"соединений, чрезвычайно большом количестве одновременных пользователей, "
+"сотнях man:jail[8] и т.д.), или при использовании новой функции или драйвера "
+"устройства в FreeBSD-STABLE (например, PAE), иногда может возникнуть паника "
+"ядра. В случае, если это произойдет, данная глава покажет, как извлечь "
+"полезную информацию из аварийного дампа."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:66
+msgid ""
+"A system reboot is inevitable once a kernel panics. Once a system is "
+"rebooted, the contents of a system's physical memory (RAM) is lost, as well "
+"as any bits that are on the swap device before the panic. To preserve the "
+"bits in physical memory, the kernel makes use of the swap device as a "
+"temporary place to store the bits that are in RAM across a reboot after a "
+"crash. In doing this, when FreeBSD boots after a crash, a kernel image can "
+"now be extracted and debugging can take place."
+msgstr ""
+"Перезагрузка системы неизбежна после паники ядра. После перезагрузки системы "
+"содержимое физической памяти (RAM) теряется, как и любые данные на "
+"устройстве подкачки перед паникой. Чтобы сохранить данные в физической "
+"памяти, ядро использует устройство подкачки как временное хранилище для "
+"данных из RAM после сбоя и перезагрузки. Благодаря этому, когда FreeBSD "
+"загружается после сбоя, образ ядра может быть извлечен и проведена отладка."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:72
+msgid ""
+"A swap device that has been configured as a dump device still acts as a swap "
+"device. Dumps to non-swap devices (such as tapes or CDRWs, for example) are "
+"not supported at this time. A \"swap device\" is synonymous with a \"swap "
+"partition.\""
+msgstr ""
+"Устройство подкачки, настроенное как устройство для дампа, продолжает "
+"функционировать как устройство подкачки. В настоящее время дампы на "
+"устройства, не являющиеся устройствами подкачки (например, на ленты или "
+"CDRW), не поддерживаются. Термин \"устройство подкачки\" является синонимом "
+"термина \"раздел подкачки\"."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:75
+msgid "Several types of kernel crash dumps are available:"
+msgstr "Есть несколько типов аварийных дампов ядра:"
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:76
+#, no-wrap
+msgid "Full memory dumps"
+msgstr "Полные дампы памяти"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:78
+msgid "Hold the complete contents of physical memory."
+msgstr "Содержат полное содержимое физической памяти."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:79
+#, no-wrap
+msgid "Minidumps"
+msgstr "Минидампы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:81
+msgid "Hold only memory pages in use by the kernel (FreeBSD 6.2 and higher)."
+msgstr ""
+"Содержат только страницы памяти, используемые ядром (FreeBSD 6.2 и выше)."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:82
+#, no-wrap
+msgid "Textdumps"
+msgstr "Текстовые дампы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:84
+msgid ""
+"Hold captured, scripted, or interactive debugger output (FreeBSD 7.1 and "
+"higher)."
+msgstr ""
+"Содержать захваченные, записанные или интерактивные выходные данные "
+"отладчика (FreeBSD 7.1 и выше)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:86
+msgid ""
+"Minidumps are the default dump type as of FreeBSD 7.0, and in most cases "
+"will capture all necessary information present in a full memory dump, as "
+"most problems can be isolated only using kernel state."
+msgstr ""
+"Минидампы являются типом дампа по умолчанию, начиная с FreeBSD 7.0, и в "
+"большинстве случаев они сохраняют всю необходимую информацию, присутствующую "
+"в полном дампе памяти, так как большинство проблем можно изолировать, "
+"используя только состояние ядра."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:88
+#, no-wrap
+msgid "Configuring the Dump Device"
+msgstr "Настройка устройства дампа"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:96
+msgid ""
+"Before the kernel will dump the contents of its physical memory to a dump "
+"device, a dump device must be configured. A dump device is specified by "
+"using the man:dumpon[8] command to tell the kernel where to save kernel "
+"crash dumps. The man:dumpon[8] program must be called after the swap "
+"partition has been configured with man:swapon[8]. This is normally handled "
+"by setting the `dumpdev` variable in man:rc.conf[5] to the path of the swap "
+"device (the recommended way to extract a kernel dump) or `AUTO` to use the "
+"first configured swap device. The default for `dumpdev` is `AUTO` in HEAD, "
+"and changed to `NO` on RELENG_* branches (except for RELENG_7, which was "
+"left set to `AUTO`). On FreeBSD 9.0-RELEASE and later versions, bsdinstall "
+"will ask whether crash dumps should be enabled on the target system during "
+"the install process."
+msgstr ""
+"Прежде чем ядро запишет содержимое своей физической памяти на устройство "
+"дампа, необходимо настроить это устройство. Устройство дампа указывается с "
+"помощью команды man:dumpon[8], чтобы сообщить ядру, куда сохранять аварийные "
+"дампы. Программа man:dumpon[8] должна быть вызвана после настройки раздела "
+"подкачки с помощью man:swapon[8]. Обычно это обрабатывается установкой "
+"переменной `dumpdev` в man:rc.conf[5] в путь к устройству подкачки "
+"(рекомендуемый способ извлечения дампа ядра) или в значение `AUTO` для "
+"использования первого настроенного устройства подкачки. По умолчанию "
+"`dumpdev` имеет значение `AUTO` в HEAD и изменено на `NO` в ветках RELENG_* "
+"(за исключением RELENG_7, где оставлено значение `AUTO`). Начиная с FreeBSD "
+"9.0-RELEASE и более поздних версий, bsdinstall будет спрашивать, следует ли "
+"включить аварийные дампы на целевой системе во время процесса установки."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:100
+msgid ""
+"Check [.filename]#/etc/fstab# or man:swapinfo[8] for a list of swap devices."
+msgstr ""
+"Проверьте [.filename]#/etc/fstab# или man:swapinfo[8] для получения списка "
+"устройств подкачки."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:105
+msgid ""
+"Make sure the `dumpdir` specified in man:rc.conf[5] exists before a kernel "
+"crash!"
+msgstr ""
+"Убедитесь, что каталог `dumpdir`, указанный в man:rc.conf[5], существует "
+"перед аварией ядра!"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:110
+#, no-wrap
+msgid ""
+"# mkdir /var/crash\n"
+"# chmod 700 /var/crash\n"
+msgstr ""
+"# mkdir /var/crash\n"
+"# chmod 700 /var/crash\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:113
+msgid ""
+"Also, remember that the contents of [.filename]#/var/crash# is sensitive and "
+"very likely contains confidential information such as passwords."
+msgstr ""
+"Также помните, что содержимое [.filename]#/var/crash# является "
+"конфиденциальным и, скорее всего, содержит секретную информацию, такую как "
+"пароли."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:116
+#, no-wrap
+msgid "Extracting a Kernel Dump"
+msgstr "Извлечение дампа ядра"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:122
+msgid ""
+"Once a dump has been written to a dump device, the dump must be extracted "
+"before the swap device is mounted. To extract a dump from a dump device, "
+"use the man:savecore[8] program. If `dumpdev` has been set in "
+"man:rc.conf[5], man:savecore[8] will be called automatically on the first "
+"multi-user boot after the crash and before the swap device is mounted. The "
+"location of the extracted core is placed in the man:rc.conf[5] value "
+"`dumpdir`, by default [.filename]#/var/crash# and will be named "
+"[.filename]#vmcore.0#."
+msgstr ""
+"После записи дампа на устройство дампа, дамп должен быть извлечен до "
+"монтирования устройства подкачки. Для извлечения дампа с устройства дампа "
+"используйте программу man:savecore[8]. Если в man:rc.conf[5] установлен "
+"параметр `dumpdev`, man:savecore[8] будет автоматически вызван при первой "
+"загрузке в многопользовательском режиме после сбоя и до монтирования "
+"устройства подкачки. Расположение извлеченного ядра указывается в параметре "
+"`dumpdir` файла man:rc.conf[5], по умолчанию это [.filename]#/var/crash#, а "
+"имя файла будет [.filename]#vmcore.0#."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:126
+msgid ""
+"In the event that there is already a file called [.filename]#vmcore.0# in "
+"[.filename]#/var/crash# (or whatever `dumpdir` is set to), the kernel will "
+"increment the trailing number for every crash to avoid overwriting an "
+"existing [.filename]#vmcore# (e.g., [.filename]#vmcore.1#). man:savecore[8] "
+"will always create a symbolic link to named [.filename]#vmcore.last# in "
+"[.filename]#/var/crash# after a dump is saved. This symbolic link can be "
+"used to locate the name of the most recent dump."
+msgstr ""
+"В случае, если файл с именем [.filename]#vmcore.0# уже существует в "
+"[.filename]#/var/crash# (или в каталоге, указанном в параметре `dumpdir`), "
+"ядро будет увеличивать завершающее число при каждом сбое, чтобы избежать "
+"перезаписи существующего файла [.filename]#vmcore# (например, "
+"[.filename]#vmcore.1#). man:savecore[8] всегда создает символическую ссылку "
+"с именем [.filename]#vmcore.last# в [.filename]#/var/crash# после сохранения "
+"дампа. Эта символическая ссылка может быть использована для определения "
+"имени последнего дампа."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:130
+msgid ""
+"The man:crashinfo[8] utility generates a text file containing a summary of "
+"information from a full memory dump or minidump. If `dumpdev` has been set "
+"in man:rc.conf[5], man:crashinfo[8] will be invoked automatically after "
+"man:savecore[8]. The output is saved to a file in `dumpdir` named "
+"[.filename]#core.txt.N#."
+msgstr ""
+"Утилита man:crashinfo[8] создаёт текстовый файл, содержащий сводную "
+"информацию из полного дампа памяти или минидампа. Если параметр `dumpdev` "
+"установлен в man:rc.conf[5], man:crashinfo[8] будет автоматически вызван "
+"после man:savecore[8]. Результат сохраняется в файл с именем "
+"[.filename]#core.txt.N# в директории `dumpdir`."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:135
+msgid ""
+"If you are testing a new kernel but need to boot a different one in order to "
+"get your system up and running again, boot it only into single user mode "
+"using the `-s` flag at the boot prompt, and then perform the following steps:"
+msgstr ""
+"Если вы тестируете новое ядро, но вам нужно загрузить другое, чтобы снова "
+"запустить систему, загрузите его только в однопользовательском режиме, "
+"используя флаг `-s` при загрузке, а затем выполните следующие шаги:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:142
+#, no-wrap
+msgid ""
+"# fsck -p\n"
+"# mount -a -t ufs # make sure /var/crash is writable\n"
+"# savecore /var/crash /dev/ad0s1b\n"
+"# exit # exit to multi-user\n"
+msgstr ""
+"# fsck -p\n"
+"# mount -a -t ufs # make sure /var/crash is writable\n"
+"# savecore /var/crash /dev/ad0s1b\n"
+"# exit # exit to multi-user\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:147
+msgid ""
+"This instructs man:savecore[8] to extract a kernel dump from [.filename]#/"
+"dev/ad0s1b# and place the contents in [.filename]#/var/crash#. Do not "
+"forget to make sure the destination directory [.filename]#/var/crash# has "
+"enough space for the dump. Also, do not forget to specify the correct path "
+"to your swap device as it is likely different than [.filename]#/dev/ad0s1b#!"
+msgstr ""
+"Это указывает man:savecore[8] извлечь дамп ядра из [.filename]#/dev/ad0s1b# "
+"и поместить содержимое в [.filename]#/var/crash#. Не забудьте убедиться, что "
+"целевой каталог [.filename]#/var/crash# имеет достаточно места для дампа. "
+"Также не забудьте указать правильный путь к вашему swap-устройству, так как "
+"он, скорее всего, отличается от [.filename]#/dev/ad0s1b#!"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:149
+#, no-wrap
+msgid "Testing Kernel Dump Configuration"
+msgstr "Тестирование конфигурации дампа ядра"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:154
+msgid ""
+"The kernel includes a man:sysctl[8] node that requests a kernel panic. This "
+"can be used to verify that your system is properly configured to save kernel "
+"crash dumps. You may wish to remount existing file systems as read-only in "
+"single user mode before triggering the crash to avoid data loss."
+msgstr ""
+"Ядро включает узел man:sysctl[8], который вызывает панику ядра. Это можно "
+"использовать для проверки того, что ваша система правильно настроена для "
+"сохранения дампов аварийного завершения работы ядра. Возможно, вы захотите "
+"перемонтировать существующие файловые системы в режиме только для чтения в "
+"однопользовательском режиме перед тем, как вызвать панику, чтобы избежать "
+"потери данных."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:164
+#, no-wrap
+msgid ""
+"# shutdown now\n"
+"...\n"
+"Enter full pathname of shell or RETURN for /bin/sh:\n"
+"# mount -a -u -r\n"
+"# sysctl debug.kdb.panic=1\n"
+"debug.kdb.panic:panic: kdb_sysctl_panic\n"
+"...\n"
+msgstr ""
+"# shutdown now\n"
+"...\n"
+"Enter full pathname of shell or RETURN for /bin/sh:\n"
+"# mount -a -u -r\n"
+"# sysctl debug.kdb.panic=1\n"
+"debug.kdb.panic:panic: kdb_sysctl_panic\n"
+"...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:167
+msgid ""
+"After rebooting, your system should save a dump in [.filename]#/var/crash# "
+"along with a matching summary from man:crashinfo[8]."
+msgstr ""
+"После перезагрузки система должна сохранить дамп в [.filename]#/var/crash# "
+"вместе с соответствующим отчетом из man:crashinfo[8]."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:169
+#, no-wrap
+msgid "Debugging a Kernel Crash Dump with `kgdb`"
+msgstr "Отладка аварийного дампа ядра с помощью `kgdb`"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:176
+msgid ""
+"This section covers man:kgdb[1]. The latest version is included in the "
+"package:devel/gdb[]. An older version is also present in FreeBSD 11 and "
+"earlier."
+msgstr ""
+"Этот раздел посвящен man:kgdb[1]. Последняя версия включена в пакет "
+"package:devel/gdb[]. Более старая версия также присутствует в FreeBSD 11 и "
+"более ранних версиях."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:179
+msgid ""
+"To enter into the debugger and begin getting information from the dump, "
+"start kgdb:"
+msgstr ""
+"Чтобы войти в отладчик и начать получение информации из дампа, запустите "
+"kgdb:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:183
+#, no-wrap
+msgid "# kgdb -n N\n"
+msgstr "# kgdb -n N\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:187
+msgid ""
+"Where _N_ is the suffix of the [.filename]#vmcore.N# to examine. To open "
+"the most recent dump use:"
+msgstr ""
+"Где _N_ — это суффикс файла [.filename]#vmcore.N#, который нужно изучить. "
+"Чтобы открыть последний дамп, используйте:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:191
+#, no-wrap
+msgid "# kgdb -n last\n"
+msgstr "# kgdb -n last\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:195
+msgid ""
+"Normally, man:kgdb[1] should be able to locate the kernel running at the "
+"time the dump was generated. If it is not able to locate the correct "
+"kernel, pass the pathname of the kernel and dump as two arguments to kgdb:"
+msgstr ""
+"Обычно man:kgdb[1] должен быть способен найти ядро, работавшее в момент "
+"создания дампа. Если он не может найти нужное ядро, передайте путь к ядру и "
+"дампу в качестве двух аргументов для kgdb:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:199
+#, no-wrap
+msgid "# kgdb /boot/kernel/kernel /var/crash/vmcore.0\n"
+msgstr "# kgdb /boot/kernel/kernel /var/crash/vmcore.0\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:202
+msgid ""
+"You can debug the crash dump using the kernel sources just like you can for "
+"any other program."
+msgstr ""
+"Вы можете отлаживать дамп аварийного завершения, используя исходные коды "
+"ядра, так же, как и для любой другой программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:209
+msgid ""
+"This dump is from a 5.2-BETA kernel and the crash comes from deep within the "
+"kernel. The output below has been modified to include line numbers on the "
+"left. This first trace inspects the instruction pointer and obtains a back "
+"trace. The address that is used on line 41 for the `list` command is the "
+"instruction pointer and can be found on line 17. Most developers will "
+"request having at least this information sent to them if you are unable to "
+"debug the problem yourself. If, however, you do solve the problem, make "
+"sure that your patch winds its way into the source tree via a problem "
+"report, mailing lists, or by being able to commit it!"
+msgstr ""
+"Этот дамп получен из ядра версии 5.2-BETA, а крах произошел глубоко внутри "
+"ядра. Приведенный ниже вывод был изменен для добавления номеров строк слева. "
+"Первый трассировочный вывод проверяет указатель инструкции и получает "
+"обратную трассировку. Адрес, используемый в строке 41 для команды `list`, "
+"является указателем инструкции и может быть найден в строке 17. Большинство "
+"разработчиков запросят как минимум эту информацию, если вы не сможете "
+"отладить проблему самостоятельно. Однако, если вы решите проблему, "
+"убедитесь, что ваш патч попадет в дерево исходников через отчет о проблеме, "
+"списки рассылки, или, может быть, у вас есть возможность его закоммитить!"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:302
+#, no-wrap
+msgid ""
+" 1:# cd /usr/obj/usr/src/sys/KERNCONF\n"
+" 2:# kgdb kernel.debug /var/crash/vmcore.0\n"
+" 3:GNU gdb 5.2.1 (FreeBSD)\n"
+" 4:Copyright 2002 Free Software Foundation, Inc.\n"
+" 5:GDB is free software, covered by the GNU General Public License, and you are\n"
+" 6:welcome to change it and/or distribute copies of it under certain conditions.\n"
+" 7:Type \"show copying\" to see the conditions.\n"
+" 8:There is absolutely no warranty for GDB. Type \"show warranty\" for details.\n"
+" 9:This GDB was configured as \"i386-undermydesk-freebsd\"...\n"
+"10:panic: page fault\n"
+"11:panic messages:\n"
+"12:---\n"
+"13:Fatal trap 12: page fault while in kernel mode\n"
+"14:cpuid = 0; apic id = 00\n"
+"15:fault virtual address = 0x300\n"
+"16:fault code: = supervisor read, page not present\n"
+"17:instruction pointer = 0x8:0xc0713860\n"
+"18:stack pointer = 0x10:0xdc1d0b70\n"
+"19:frame pointer = 0x10:0xdc1d0b7c\n"
+"20:code segment = base 0x0, limit 0xfffff, type 0x1b\n"
+"21: = DPL 0, pres 1, def32 1, gran 1\n"
+"22:processor eflags = resume, IOPL = 0\n"
+"23:current process = 14394 (uname)\n"
+"24:trap number = 12\n"
+"25:panic: page fault\n"
+"26 cpuid = 0;\n"
+"27:Stack backtrace:\n"
+"28\n"
+"29:syncing disks, buffers remaining... 2199 2199 panic: mi_switch: switch in a critical section\n"
+"30:cpuid = 0;\n"
+"31:Uptime: 2h43m19s\n"
+"32:Dumping 255 MB\n"
+"33: 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240\n"
+"34:---\n"
+"35:Reading symbols from /boot/kernel/snd_maestro3.ko...done.\n"
+"36:Loaded symbols for /boot/kernel/snd_maestro3.ko\n"
+"37:Reading symbols from /boot/kernel/snd_pcm.ko...done.\n"
+"38:Loaded symbols for /boot/kernel/snd_pcm.ko\n"
+"39:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240\n"
+"40:240 dumping++;\n"
+"41:(kgdb) list *0xc0713860\n"
+"42:0xc0713860 is in lapic_ipi_wait (/usr/src/sys/i386/i386/local_apic.c:663).\n"
+"43:658 incr = 0;\n"
+"44:659 delay = 1;\n"
+"45:660 } else\n"
+"46:661 incr = 1;\n"
+"47:662 for (x = 0; x < delay; x += incr) {\n"
+"48:663 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)\n"
+"49:664 return (1);\n"
+"50:665 ia32_pause();\n"
+"51:666 }\n"
+"52:667 return (0);\n"
+"53:(kgdb) backtrace\n"
+"54:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240\n"
+"55:#1 0xc055fd9b in boot (howto=260) at /usr/src/sys/kern/kern_shutdown.c:372\n"
+"56:#2 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550\n"
+"57:#3 0xc0567ef5 in mi_switch () at /usr/src/sys/kern/kern_synch.c:470\n"
+"58:#4 0xc055fa87 in boot (howto=256) at /usr/src/sys/kern/kern_shutdown.c:312\n"
+"59:#5 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550\n"
+"60:#6 0xc0720c66 in trap_fatal (frame=0xdc1d0b30, eva=0)\n"
+"61: at /usr/src/sys/i386/i386/trap.c:821\n"
+"62:#7 0xc07202b3 in trap (frame=\n"
+"63: {tf_fs = -1065484264, tf_es = -1065484272, tf_ds = -1065484272, tf_edi = 1, tf_esi = 0, tf_ebp = -602076292, tf_isp = -602076324, tf_ebx = 0, tf_edx = 0, tf_ecx = 1000000, tf_eax = 243, tf_trapno = 12, tf_err = 0, tf_eip = -1066321824, tf_cs = 8, tf_eflags = 65671, tf_esp = 243, tf_ss = 0})\n"
+"64: at /usr/src/sys/i386/i386/trap.c:250\n"
+"65:#8 0xc070c9f8 in calltrap () at {standard input}:94\n"
+"66:#9 0xc07139f3 in lapic_ipi_vectored (vector=0, dest=0)\n"
+"67: at /usr/src/sys/i386/i386/local_apic.c:733\n"
+"68:#10 0xc0718b23 in ipi_selected (cpus=1, ipi=1)\n"
+"69: at /usr/src/sys/i386/i386/mp_machdep.c:1115\n"
+"70:#11 0xc057473e in kseq_notify (ke=0xcc05e360, cpu=0)\n"
+"71: at /usr/src/sys/kern/sched_ule.c:520\n"
+"72:#12 0xc0575cad in sched_add (td=0xcbcf5c80)\n"
+"73: at /usr/src/sys/kern/sched_ule.c:1366\n"
+"74:#13 0xc05666c6 in setrunqueue (td=0xcc05e360)\n"
+"75: at /usr/src/sys/kern/kern_switch.c:422\n"
+"76:#14 0xc05752f4 in sched_wakeup (td=0xcbcf5c80)\n"
+"77: at /usr/src/sys/kern/sched_ule.c:999\n"
+"78:#15 0xc056816c in setrunnable (td=0xcbcf5c80)\n"
+"79: at /usr/src/sys/kern/kern_synch.c:570\n"
+"80:#16 0xc0567d53 in wakeup (ident=0xcbcf5c80)\n"
+"81: at /usr/src/sys/kern/kern_synch.c:411\n"
+"82:#17 0xc05490a8 in exit1 (td=0xcbcf5b40, rv=0)\n"
+"83: at /usr/src/sys/kern/kern_exit.c:509\n"
+"84:#18 0xc0548011 in sys_exit () at /usr/src/sys/kern/kern_exit.c:102\n"
+"85:#19 0xc0720fd0 in syscall (frame=\n"
+"86: {tf_fs = 47, tf_es = 47, tf_ds = 47, tf_edi = 0, tf_esi = -1, tf_ebp = -1077940712, tf_isp = -602075788, tf_ebx = 672411944, tf_edx = 10, tf_ecx = 672411600, tf_eax = 1, tf_trapno = 12, tf_err = 2, tf_eip = 671899563, tf_cs = 31, tf_eflags = 642, tf_esp = -1077940740, tf_ss = 47})\n"
+"87: at /usr/src/sys/i386/i386/trap.c:1010\n"
+"88:#20 0xc070ca4d in Xint0x80_syscall () at {standard input}:136\n"
+"89:---Can't read userspace from dump, or kernel process---\n"
+"90:(kgdb) quit\n"
+msgstr ""
+" 1:# cd /usr/obj/usr/src/sys/KERNCONF\n"
+" 2:# kgdb kernel.debug /var/crash/vmcore.0\n"
+" 3:GNU gdb 5.2.1 (FreeBSD)\n"
+" 4:Copyright 2002 Free Software Foundation, Inc.\n"
+" 5:GDB is free software, covered by the GNU General Public License, and you are\n"
+" 6:welcome to change it and/or distribute copies of it under certain conditions.\n"
+" 7:Type \"show copying\" to see the conditions.\n"
+" 8:There is absolutely no warranty for GDB. Type \"show warranty\" for details.\n"
+" 9:This GDB was configured as \"i386-undermydesk-freebsd\"...\n"
+"10:panic: page fault\n"
+"11:panic messages:\n"
+"12:---\n"
+"13:Fatal trap 12: page fault while in kernel mode\n"
+"14:cpuid = 0; apic id = 00\n"
+"15:fault virtual address = 0x300\n"
+"16:fault code: = supervisor read, page not present\n"
+"17:instruction pointer = 0x8:0xc0713860\n"
+"18:stack pointer = 0x10:0xdc1d0b70\n"
+"19:frame pointer = 0x10:0xdc1d0b7c\n"
+"20:code segment = base 0x0, limit 0xfffff, type 0x1b\n"
+"21: = DPL 0, pres 1, def32 1, gran 1\n"
+"22:processor eflags = resume, IOPL = 0\n"
+"23:current process = 14394 (uname)\n"
+"24:trap number = 12\n"
+"25:panic: page fault\n"
+"26 cpuid = 0;\n"
+"27:Stack backtrace:\n"
+"28\n"
+"29:syncing disks, buffers remaining... 2199 2199 panic: mi_switch: switch in a critical section\n"
+"30:cpuid = 0;\n"
+"31:Uptime: 2h43m19s\n"
+"32:Dumping 255 MB\n"
+"33: 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240\n"
+"34:---\n"
+"35:Reading symbols from /boot/kernel/snd_maestro3.ko...done.\n"
+"36:Loaded symbols for /boot/kernel/snd_maestro3.ko\n"
+"37:Reading symbols from /boot/kernel/snd_pcm.ko...done.\n"
+"38:Loaded symbols for /boot/kernel/snd_pcm.ko\n"
+"39:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240\n"
+"40:240 dumping++;\n"
+"41:(kgdb) list *0xc0713860\n"
+"42:0xc0713860 is in lapic_ipi_wait (/usr/src/sys/i386/i386/local_apic.c:663).\n"
+"43:658 incr = 0;\n"
+"44:659 delay = 1;\n"
+"45:660 } else\n"
+"46:661 incr = 1;\n"
+"47:662 for (x = 0; x < delay; x += incr) {\n"
+"48:663 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)\n"
+"49:664 return (1);\n"
+"50:665 ia32_pause();\n"
+"51:666 }\n"
+"52:667 return (0);\n"
+"53:(kgdb) backtrace\n"
+"54:#0 doadump () at /usr/src/sys/kern/kern_shutdown.c:240\n"
+"55:#1 0xc055fd9b in boot (howto=260) at /usr/src/sys/kern/kern_shutdown.c:372\n"
+"56:#2 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550\n"
+"57:#3 0xc0567ef5 in mi_switch () at /usr/src/sys/kern/kern_synch.c:470\n"
+"58:#4 0xc055fa87 in boot (howto=256) at /usr/src/sys/kern/kern_shutdown.c:312\n"
+"59:#5 0xc056019d in panic () at /usr/src/sys/kern/kern_shutdown.c:550\n"
+"60:#6 0xc0720c66 in trap_fatal (frame=0xdc1d0b30, eva=0)\n"
+"61: at /usr/src/sys/i386/i386/trap.c:821\n"
+"62:#7 0xc07202b3 in trap (frame=\n"
+"63: {tf_fs = -1065484264, tf_es = -1065484272, tf_ds = -1065484272, tf_edi = 1, tf_esi = 0, tf_ebp = -602076292, tf_isp = -602076324, tf_ebx = 0, tf_edx = 0, tf_ecx = 1000000, tf_eax = 243, tf_trapno = 12, tf_err = 0, tf_eip = -1066321824, tf_cs = 8, tf_eflags = 65671, tf_esp = 243, tf_ss = 0})\n"
+"64: at /usr/src/sys/i386/i386/trap.c:250\n"
+"65:#8 0xc070c9f8 in calltrap () at {standard input}:94\n"
+"66:#9 0xc07139f3 in lapic_ipi_vectored (vector=0, dest=0)\n"
+"67: at /usr/src/sys/i386/i386/local_apic.c:733\n"
+"68:#10 0xc0718b23 in ipi_selected (cpus=1, ipi=1)\n"
+"69: at /usr/src/sys/i386/i386/mp_machdep.c:1115\n"
+"70:#11 0xc057473e in kseq_notify (ke=0xcc05e360, cpu=0)\n"
+"71: at /usr/src/sys/kern/sched_ule.c:520\n"
+"72:#12 0xc0575cad in sched_add (td=0xcbcf5c80)\n"
+"73: at /usr/src/sys/kern/sched_ule.c:1366\n"
+"74:#13 0xc05666c6 in setrunqueue (td=0xcc05e360)\n"
+"75: at /usr/src/sys/kern/kern_switch.c:422\n"
+"76:#14 0xc05752f4 in sched_wakeup (td=0xcbcf5c80)\n"
+"77: at /usr/src/sys/kern/sched_ule.c:999\n"
+"78:#15 0xc056816c in setrunnable (td=0xcbcf5c80)\n"
+"79: at /usr/src/sys/kern/kern_synch.c:570\n"
+"80:#16 0xc0567d53 in wakeup (ident=0xcbcf5c80)\n"
+"81: at /usr/src/sys/kern/kern_synch.c:411\n"
+"82:#17 0xc05490a8 in exit1 (td=0xcbcf5b40, rv=0)\n"
+"83: at /usr/src/sys/kern/kern_exit.c:509\n"
+"84:#18 0xc0548011 in sys_exit () at /usr/src/sys/kern/kern_exit.c:102\n"
+"85:#19 0xc0720fd0 in syscall (frame=\n"
+"86: {tf_fs = 47, tf_es = 47, tf_ds = 47, tf_edi = 0, tf_esi = -1, tf_ebp = -1077940712, tf_isp = -602075788, tf_ebx = 672411944, tf_edx = 10, tf_ecx = 672411600, tf_eax = 1, tf_trapno = 12, tf_err = 2, tf_eip = 671899563, tf_cs = 31, tf_eflags = 642, tf_esp = -1077940740, tf_ss = 47})\n"
+"87: at /usr/src/sys/i386/i386/trap.c:1010\n"
+"88:#20 0xc070ca4d in Xint0x80_syscall () at {standard input}:136\n"
+"89:---Can't read userspace from dump, or kernel process---\n"
+"90:(kgdb) quit\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:308
+msgid ""
+"If your system is crashing regularly and you are running out of disk space, "
+"deleting old [.filename]#vmcore# files in [.filename]#/var/crash# could save "
+"a considerable amount of disk space!"
+msgstr ""
+"Если ваша система регулярно завершается аварийно и у вас заканчивается место "
+"на диске, удаление старых файлов [.filename]#vmcore# в [.filename]#/var/"
+"crash# может освободить значительное количество дискового пространства!"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:311
+#, no-wrap
+msgid "On-Line Kernel Debugging Using DDB"
+msgstr "Онлайн-отладка ядра с использованием DDB"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:315
+msgid ""
+"While `kgdb` as an off-line debugger provides a very high level of user "
+"interface, there are some things it cannot do. The most important ones "
+"being breakpointing and single-stepping kernel code."
+msgstr ""
+"В то время как `kgdb` как автономный отладчик предоставляет очень высокий "
+"уровень пользовательского интерфейса, есть некоторые вещи, которые он не "
+"может выполнить. Наиболее важные из них — установка точек останова и "
+"пошаговое выполнение кода ядра."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:319
+msgid ""
+"If you need to do low-level debugging on your kernel, there is an on-line "
+"debugger available called DDB. It allows setting of breakpoints, single-"
+"stepping kernel functions, examining and changing kernel variables, etc. "
+"However, it cannot access kernel source files, and only has access to the "
+"global and static symbols, not to the full debug information like `kgdb` "
+"does."
+msgstr ""
+"Если вам требуется выполнить низкоуровневую отладку ядра, доступен отладчик "
+"DDB, работающий в режиме реального времени. Он позволяет устанавливать точки "
+"останова, выполнять пошаговое выполнение функций ядра, проверять и изменять "
+"переменные ядра и т.д. Однако он не имеет доступа к исходным файлам ядра и "
+"работает только с глобальными и статическими символами, без доступа к полной "
+"отладочной информации, как это делает `kgdb`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:321
+msgid "To configure your kernel to include DDB, add the options"
+msgstr "Для настройки ядра с включенной поддержкой DDB добавьте параметры"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:324
+#, no-wrap
+msgid "options KDB\n"
+msgstr "options KDB\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:329
+#, no-wrap
+msgid "options DDB\n"
+msgstr "options DDB\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:333
+msgid ""
+"to your config file, and rebuild. (See extref:{handbook}[The FreeBSD "
+"Handbook] for details on configuring the FreeBSD kernel)."
+msgstr ""
+"в ваш конфигурационный файл, и пересоберите. (Подробности о настройке ядра "
+"FreeBSD см. в extref:{handbook}[Руководстве FreeBSD])."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:339
+msgid ""
+"Once your DDB kernel is running, there are several ways to enter DDB. The "
+"first, and earliest way is to use the boot flag `-d`. The kernel will start "
+"up in debug mode and enter DDB prior to any device probing. Hence you can "
+"even debug the device probe/attach functions. To use this, exit the "
+"loader's boot menu and enter `boot -d` at the loader prompt."
+msgstr ""
+"После загрузки ядра DDB существует несколько способов войти в него. Первый и "
+"самый ранний способ — использовать флаг загрузки `-d`. Ядро запустится в "
+"режиме отладки и перейдет в DDB до начала обнаружения любого из устройств. "
+"Таким образом, можно отлаживать даже функции обнаружить (probe)/ "
+"присоединить (attach) устройств. Для использования этого метода выйдите из "
+"меню загрузки загрузчика и введите `boot -d` в командной строке загрузчика."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:343
+msgid ""
+"The second scenario is to drop to the debugger once the system has booted. "
+"There are two simple ways to accomplish this. If you would like to break to "
+"the debugger from the command prompt, simply type the command:"
+msgstr ""
+"Второй сценарий — перейти в отладчик после загрузки системы. Есть два "
+"простых способа это сделать. Если вы хотите перейти в отладчик из командной "
+"строки, просто введите команду:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:347
+#, no-wrap
+msgid "# sysctl debug.kdb.enter=1\n"
+msgstr "# sysctl debug.kdb.enter=1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:354
+msgid ""
+"Alternatively, if you are at the system console, you may use a hot-key on "
+"the keyboard. The default break-to-debugger sequence is kbd:"
+"[Ctrl+Alt+ESC]. For syscons, this sequence can be remapped and some of the "
+"distributed maps out there do this, so check to make sure you know the right "
+"sequence to use. There is an option available for serial consoles that "
+"allows the use of a serial line BREAK on the console line to enter DDB "
+"(`options BREAK_TO_DEBUGGER` in the kernel config file). It is not the "
+"default since there are a lot of serial adapters around that gratuitously "
+"generate a BREAK condition, for example when pulling the cable."
+msgstr ""
+"В качестве альтернативы, если вы находитесь за системной консолью, можно "
+"использовать горячую клавишу на клавиатуре. Стандартной комбинацией для "
+"перехода в отладчик является kbd:[Ctrl+Alt+ESC]. В syscons эта "
+"последовательность может быть переназначена, и некоторые распространённые "
+"раскладки клавиатуры делают это, поэтому убедитесь, что знаете правильную "
+"комбинацию. Для последовательных консолей доступна опция, позволяющая "
+"использовать сигнал BREAK на линии консоли для входа в DDB (`options "
+"BREAK_TO_DEBUGGER` в конфигурационном файле ядра). Это не установлено по "
+"умолчанию, так как существует множество последовательных адаптеров, которые "
+"излишне генерируют условие BREAK, например, при отключении кабеля."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:357
+msgid ""
+"The third way is that any panic condition will branch to DDB if the kernel "
+"is configured to use it. For this reason, it is not wise to configure a "
+"kernel with DDB for a machine running unattended."
+msgstr ""
+"Третий способ заключается в том, чтобы любое условие паники переходило в "
+"DDB, если ядро настроено на его использование. По этой причине не "
+"рекомендуется настраивать ядро с DDB для машины, работающей без присмотра."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:359
+msgid "To obtain the unattended functionality, add:"
+msgstr "Для получения неинтерактивной функциональности добавьте:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:363
+#, no-wrap
+msgid "options\tKDB_UNATTENDED\n"
+msgstr "options\tKDB_UNATTENDED\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:366
+msgid "to the kernel configuration file and rebuild/reinstall."
+msgstr "в файл конфигурации ядра и пересоберите/переустановите ядро."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:369
+msgid ""
+"The DDB commands roughly resemble some `gdb` commands. The first thing you "
+"probably need to do is to set a breakpoint:"
+msgstr ""
+"Команды DDB примерно напоминают некоторые команды `gdb`. Первое, что вам, "
+"вероятно, нужно сделать, это установить точку останова:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:373
+#, no-wrap
+msgid " break function-name address\n"
+msgstr " break function-name address\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:378
+msgid ""
+"Numbers are taken hexadecimal by default, but to make them distinct from "
+"symbol names; hexadecimal numbers starting with the letters `a-f` need to be "
+"preceded with `0x` (this is optional for other numbers). Simple expressions "
+"are allowed, for example: `function-name + 0x103`."
+msgstr ""
+"Числа по умолчанию интерпретируются как шестнадцатеричные, но чтобы отличить "
+"их от символьных имен, шестнадцатеричные числа, начинающиеся с букв `a-f`, "
+"должны предваряться префиксом `0x` (для остальных чисел это необязательно). "
+"Допускаются простые выражения, например: `function-name + 0x103`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:380
+msgid "To exit the debugger and continue execution, type:"
+msgstr "Для выхода из отладчика и продолжения выполнения введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:384
+#, no-wrap
+msgid " continue\n"
+msgstr " continue\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:387
+msgid "To get a stack trace of the current thread, use:"
+msgstr "Для получения трассировки стека текущего потока используйте:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:391
+#, no-wrap
+msgid " trace\n"
+msgstr " trace\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:394
+msgid ""
+"To get a stack trace of an arbitrary thread, specify a process ID or thread "
+"ID as a second argument to `trace`."
+msgstr ""
+"Для получения трассировки стека произвольного потока укажите идентификатор "
+"процесса или идентификатор потока в качестве второго аргумента команды "
+"`trace`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:396
+msgid "If you want to remove a breakpoint, use"
+msgstr "Если вы хотите удалить точку останова, используйте"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:401
+#, no-wrap
+msgid ""
+" del\n"
+" del address-expression\n"
+msgstr ""
+" del\n"
+" del address-expression\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:405
+msgid ""
+"The first form will be accepted immediately after a breakpoint hit, and "
+"deletes the current breakpoint. The second form can remove any breakpoint, "
+"but you need to specify the exact address; this can be obtained from:"
+msgstr ""
+"Первая форма будет принята сразу после срабатывания точки останова и удаляет "
+"текущую точку останова. Вторая форма может удалить любую точку останова, но "
+"необходимо указать точный адрес; его можно получить из:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:409
+#, no-wrap
+msgid " show b\n"
+msgstr " show b\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:412
+msgid "or:"
+msgstr "или:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:416
+#, no-wrap
+msgid " show break\n"
+msgstr " show break\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:419
+msgid "To single-step the kernel, try:"
+msgstr "Для пошагового выполнения ядра попробуйте:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:423
+#, no-wrap
+msgid " s\n"
+msgstr " s\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:426
+msgid ""
+"This will step into functions, but you can make DDB trace them until the "
+"matching return statement is reached by:"
+msgstr ""
+"Это позволит войти в функции, но вы можете заставить DDB отслеживать их до "
+"достижения соответствующего оператора return с помощью:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:430
+#, no-wrap
+msgid " n\n"
+msgstr " n\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:436
+msgid ""
+"This is different from ``gdb``'s `next` statement; it is like ``gdb``'s "
+"`finish`. Pressing kbd:[n] more than once will cause a continue."
+msgstr ""
+"Это отличается от оператора `next` в ``gdb``; это похоже на `finish` в "
+"``gdb``. Нажатие kbd:[n] более одного раза приведёт к продолжению."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:439
+msgid "To examine data from memory, use (for example):"
+msgstr "Для просмотра данных в памяти используйте (например):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:446
+#, no-wrap
+msgid ""
+" x/wx 0xf0133fe0,40\n"
+" x/hd db_symtab_space\n"
+" x/bc termbuf,10\n"
+" x/s stringbuf\n"
+msgstr ""
+" x/wx 0xf0133fe0,40\n"
+" x/hd db_symtab_space\n"
+" x/bc termbuf,10\n"
+" x/s stringbuf\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:451
+msgid ""
+"for word/halfword/byte access, and hexadecimal/decimal/character/ string "
+"display. The number after the comma is the object count. To display the "
+"next 0x10 items, simply use:"
+msgstr ""
+"для доступа к словам/полусловам/байтам и отображения в шестнадцатеричном/"
+"десятичном/символьном/строковом формате. Число после запятой указывает "
+"количество объектов. Для отображения следующих 0x10 элементов просто введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:455
+#, no-wrap
+msgid " x ,10\n"
+msgstr " x ,10\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:458
+msgid "Similarly, use"
+msgstr "Аналогично, используйте"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:462
+#, no-wrap
+msgid " x/ia foofunc,10\n"
+msgstr " x/ia foofunc,10\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:465
+msgid ""
+"to disassemble the first 0x10 instructions of `foofunc`, and display them "
+"along with their offset from the beginning of `foofunc`."
+msgstr ""
+"для дизассемблирования первых 0x10 инструкций функции `foofunc` и их "
+"отображения вместе с их смещением от начала `foofunc`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:467
+msgid "To modify memory, use the write command:"
+msgstr "Для записи в память используйте команду write:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:472
+#, no-wrap
+msgid ""
+" w/b termbuf 0xa 0xb 0\n"
+" w/w 0xf0010030 0 0\n"
+msgstr ""
+" w/b termbuf 0xa 0xb 0\n"
+" w/w 0xf0010030 0 0\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:476
+msgid ""
+"The command modifier (`b`/`h`/`w`) specifies the size of the data to be "
+"written, the first following expression is the address to write to and the "
+"remainder is interpreted as data to write to successive memory locations."
+msgstr ""
+"Модификатор команды (`b`/`h`/`w`) определяет размер данных для записи, "
+"первое следующее выражение — это адрес для записи, а остальное "
+"интерпретируется как данные для записи в последующие ячейки памяти."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:478
+msgid "If you need to know the current registers, use:"
+msgstr "Если вам необходимо узнать текущее содержимое регистров, введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:482
+#, no-wrap
+msgid " show reg\n"
+msgstr " show reg\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:485
+msgid "Alternatively, you can display a single register value by e.g."
+msgstr "Также можно отобразить значение одного регистра, например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:489
+#, no-wrap
+msgid " p $eax\n"
+msgstr " p $eax\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:492
+msgid "and modify it by:"
+msgstr "и изменить его с помощью:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:496
+#, no-wrap
+msgid " set $eax new-value\n"
+msgstr " set $eax new-value\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:499
+msgid "Should you need to call some kernel functions from DDB, simply say:"
+msgstr ""
+"Если вам потребуется вызвать некоторые функции ядра из DDB, просто напишите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:503
+#, no-wrap
+msgid " call func(arg1, arg2, ...)\n"
+msgstr " call func(arg1, arg2, ...)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:506
+msgid "The return value will be printed."
+msgstr "Будет выведено возвращаемое значение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:508
+msgid "For a man:ps[1] style summary of all running processes, use:"
+msgstr ""
+"Для вывода информации о всех запущенных процессах в стиле man:ps[1] "
+"используйте:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:512
+#, no-wrap
+msgid " ps\n"
+msgstr " ps\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:517
+msgid ""
+"Now you have examined why your kernel failed, and you wish to reboot. "
+"Remember that, depending on the severity of previous malfunctioning, not all "
+"parts of the kernel might still be working as expected. Perform one of the "
+"following actions to shut down and reboot your system:"
+msgstr ""
+"Теперь вы выяснили причину сбоя ядра и хотите выполнить перезагрузку. "
+"Помните, что в зависимости от серьезности предыдущего сбоя не все части ядра "
+"могут работать корректно. Выполните одно из следующих действий для "
+"завершения работы и перезагрузки системы:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:521
+#, no-wrap
+msgid " panic\n"
+msgstr " panic\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:524
+msgid ""
+"This will cause your kernel to dump core and reboot, so you can later "
+"analyze the core on a higher level with man:kgdb[1]."
+msgstr ""
+"Это приведёт к дампу ядра и перезагрузке, чтобы позже можно было "
+"проанализировать дамп на более высоком уровне с помощью man:kgdb[1]."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:528
+#, no-wrap
+msgid " call boot(0)\n"
+msgstr " call boot(0)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:532
+msgid ""
+"Might be a good way to cleanly shut down the running system, `sync()` all "
+"disks, and finally, in some cases, reboot. As long as the disk and "
+"filesystem interfaces of the kernel are not damaged, this could be a good "
+"way for an almost clean shutdown."
+msgstr ""
+"Может быть хорошим способом чисто завершить работу работающей системы, "
+"`sync()` все диски и, наконец, в некоторых случаях перезагрузиться. Пока "
+"интерфейсы дисков и файловых систем ядра не повреждены, это может быть "
+"хорошим способом для почти чистого завершения работы."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:536
+#, no-wrap
+msgid " reset\n"
+msgstr " reset\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:539
+msgid ""
+"This is the final way out of disaster and almost the same as hitting the Big "
+"Red Button."
+msgstr ""
+"Это последний способ избежать катастрофы, и он почти такой же, как нажатие "
+"на Большую Красную Кнопку."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:541
+msgid "If you need a short command summary, simply type:"
+msgstr "Если вам нужна краткая сводка команд, просто введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:545
+#, no-wrap
+msgid " help\n"
+msgstr " help\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:549
+msgid ""
+"It is highly recommended to have a printed copy of the man:ddb[4] manual "
+"page ready for a debugging session. Remember that it is hard to read the on-"
+"line manual while single-stepping the kernel."
+msgstr ""
+"Настоятельно рекомендуется иметь распечатанную копию страницы руководства "
+"man:ddb[4] для сеанса отладки. Помните, что читать онлайн-руководство во "
+"время пошагового выполнения ядра сложно."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:551
+#, no-wrap
+msgid "On-Line Kernel Debugging Using Remote GDB"
+msgstr "Онлайн-отладка ядра с использованием удаленного GDB"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:555
+msgid ""
+"The FreeBSD kernel provides a second KDB backend for on-line debugging: "
+"man:gdb[4]. This feature has been supported since FreeBSD 2.2, and it is "
+"actually a very neat one."
+msgstr ""
+"Ядро FreeBSD предоставляет второй бэкенд KDB для отладки в реальном времени: "
+"man:gdb[4]. Эта возможность поддерживается с FreeBSD 2.2 и является "
+"действительно очень удобной."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:561
+msgid ""
+"GDB has supported _remote debugging_ for a long time. This is done using a "
+"very simple protocol along a serial line. Unlike the other debugging "
+"methods described above, you will need two machines for doing this. One is "
+"the host providing the debugging environment, including all the sources, and "
+"a copy of the kernel binary with all the symbols in it. The other is the "
+"target machine that runs a copy of the very same kernel (optionally stripped "
+"of the debugging information)."
+msgstr ""
+"GDB давно поддерживает _удалённую отладку_. Это осуществляется с помощью "
+"очень простого протокола через последовательное соединение. В отличие от "
+"других методов отладки, описанных выше, для этого потребуются две машины. "
+"Одна — это хост, предоставляющий среду отладки, включая все исходные тексты "
+"и копию бинарного файла ядра со всеми символами. Другая — целевая машина, на "
+"которой запущена копия того же самого ядра (возможно, без отладочной "
+"информации)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:563
+msgid ""
+"In order to use remote GDB, ensure that the following options are present in "
+"your kernel configuration:"
+msgstr ""
+"Чтобы использовать удалённый GDB, убедитесь, что следующие параметры "
+"присутствуют в конфигурации вашего ядра:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:568
+#, no-wrap
+msgid ""
+"makeoptions DEBUG=-g\n"
+"options KDB\n"
+"options GDB\n"
+msgstr ""
+"makeoptions DEBUG=-g\n"
+"options KDB\n"
+"options GDB\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:571
+msgid ""
+"Note that the `GDB` option is turned off by default in `GENERIC` kernels on "
+"-STABLE and -RELEASE branches, but enabled on -CURRENT."
+msgstr ""
+"Обратите внимание, что опция `GDB` отключена по умолчанию в ядрах `GENERIC` "
+"для веток -STABLE и -RELEASE, но включена в -CURRENT."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:575
+msgid ""
+"Once built, copy the kernel to the target machine, and boot it. Connect the "
+"serial line of the target machine that has \"flags 080\" set on its uart "
+"device to any serial line of the debugging host. See man:uart[4] for "
+"information on how to set the flags on a uart device."
+msgstr ""
+"После сборки скопируйте ядро на целевую машину и загрузите его. Подключите "
+"последовательный порт целевой машины, у которого на устройстве uart "
+"установлены флаги \"080\", к любому последовательному порту отладочной "
+"машины. Подробности о настройке флагов на устройстве uart смотрите в "
+"man:uart[4]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:578
+msgid ""
+"The target machine must be made to enter the GDB backend, either due to a "
+"panic or by taking a purposeful trap into the debugger. Before doing this, "
+"select the GDB debugger backend:"
+msgstr ""
+"Целевая машина должна быть переведена в режим отладчика GDB, либо из-за "
+"паники, либо путем преднамеренного перехода в отладчик. Перед этим выберите "
+"бэкенд отладчика GDB:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:582
+#, no-wrap
+msgid ""
+"# sysctl debug.kdb.current=gdb\n"
+"debug.kdb.current: ddb -> gdb\n"
+msgstr ""
+"# sysctl debug.kdb.current=gdb\n"
+"debug.kdb.current: ddb -> gdb\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:589
+msgid ""
+"The supported backends can be listed by the `debug.kdb.available` sysctl. "
+"If the kernel configuration includes `options DDB`, then man:ddb[4] will be "
+"selected by default. If `gdb` does not appear in the list of available "
+"backends, then the debug serial port may not have been configured correctly."
+msgstr ""
+"Поддерживаемые бэкенды можно вывести с помощью sysctl `debug.kdb.available`. "
+"Если конфигурация ядра включает `options DDB`, то man:ddb[4] будет выбран по "
+"умолчанию. Если `gdb` не отображается в списке доступных бэкендов, значит, "
+"последовательный порт отладки может быть настроен неправильно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:592
+msgid "Then, force entry to the debugger:"
+msgstr "Затем принудительно войдите в отладчик:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:596
+#, no-wrap
+msgid ""
+"# sysctl debug.kdb.enter=1\n"
+"debug.kdb.enter: 0KDB: enter: sysctl debug.kdb.enter\n"
+msgstr ""
+"# sysctl debug.kdb.enter=1\n"
+"debug.kdb.enter: 0KDB: enter: sysctl debug.kdb.enter\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:600
+msgid ""
+"The target machine now awaits connection from a remote GDB client. On the "
+"debugging machine, go to the compile directory of the target kernel, and "
+"start `gdb`:"
+msgstr ""
+"Целевая машина теперь ожидает подключения от удалённого клиента GDB. На "
+"машине для отладки перейдите в каталог сборки целевого ядра и запустите "
+"`gdb`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:611
+#, no-wrap
+msgid ""
+"# cd /usr/obj/usr/src/amd64.amd64/sys/GENERIC/\n"
+"# kgdb kernel\n"
+"GNU gdb (GDB) 10.2 [GDB v10.2 for FreeBSD]\n"
+"Copyright (C) 2021 Free Software Foundation, Inc.\n"
+"...\n"
+"Reading symbols from kernel...\n"
+"Reading symbols from /usr/obj/usr/src/amd64.amd64/sys/GENERIC/kernel.debug...\n"
+"(kgdb)\n"
+msgstr ""
+"# cd /usr/obj/usr/src/amd64.amd64/sys/GENERIC/\n"
+"# kgdb kernel\n"
+"GNU gdb (GDB) 10.2 [GDB v10.2 for FreeBSD]\n"
+"Copyright (C) 2021 Free Software Foundation, Inc.\n"
+"...\n"
+"Reading symbols from kernel...\n"
+"Reading symbols from /usr/obj/usr/src/amd64.amd64/sys/GENERIC/kernel.debug...\n"
+"(kgdb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:614
+msgid ""
+"Initialize the remote debugging session (assuming the first serial port is "
+"being used) by:"
+msgstr ""
+"Инициализируйте сеанс удаленной отладки (предполагая, что используется "
+"первый последовательный порт) с помощью:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:618
+#, no-wrap
+msgid "(kgdb) target remote /dev/cuau0\n"
+msgstr "(kgdb) target remote /dev/cuau0\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:621
+msgid "Your hosting GDB will now gain control over the target kernel:"
+msgstr "Ваш хостинг GDB теперь получит контроль над целевым ядром:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:628
+#, no-wrap
+msgid ""
+"Remote debugging using /dev/cuau0\n"
+"kdb_enter (why=<optimized out>, msg=<optimized out>) at /usr/src/sys/kern/subr_kdb.c:506\n"
+"506 kdb_why = KDB_WHY_UNSET;\n"
+"(kgdb)\n"
+msgstr ""
+"Remote debugging using /dev/cuau0\n"
+"kdb_enter (why=<optimized out>, msg=<optimized out>) at /usr/src/sys/kern/subr_kdb.c:506\n"
+"506 kdb_why = KDB_WHY_UNSET;\n"
+"(kgdb)\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:636
+msgid ""
+"Depending on the compiler used, some local variables may appear as "
+"`<optimized out>`, preventing them from being inspected directly by `gdb`. "
+"If this causes problems while debugging, it is possible to build the kernel "
+"at a decreased optimization level, which may improve the visibility of some "
+"variables. This can be done by passing `COPTFLAGS=-O1` to man:make[1]. "
+"However, certain classes of kernel bugs may manifest differently (or not at "
+"all) when the optimization level is changed."
+msgstr ""
+"В зависимости от используемого компилятора, некоторые локальные переменные "
+"могут отображаться как `<optimized out>`, что не позволяет их напрямую "
+"исследовать с помощью `gdb`. Если это вызывает проблемы при отладке, можно "
+"собрать ядро с пониженным уровнем оптимизации, что может улучшить видимость "
+"некоторых переменных. Это можно сделать, передав `COPTFLAGS=-O1` в "
+"man:make[1]. Однако определённые классы ошибок в ядре могут проявляться "
+"иначе (или вообще не проявляться) при изменении уровня оптимизации."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:640
+msgid ""
+"You can use this session almost as any other GDB session, including full "
+"access to the source, running it in gud-mode inside an Emacs window (which "
+"gives you an automatic source code display in another Emacs window), etc."
+msgstr ""
+"Вы можете использовать этот сеанс почти как любой другой сеанс GDB, включая "
+"полный доступ к исходному коду, запуск в режиме gud (Grand Unified Debugger) "
+"внутри окна Emacs (что дает автоматическое отображение исходного кода в "
+"другом окне Emacs) и т.д."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:642
+#, no-wrap
+msgid "Debugging a Console Driver"
+msgstr "Отладка драйвера консоли"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:648
+msgid ""
+"Since you need a console driver to run DDB on, things are more complicated "
+"if the console driver itself is failing. You might remember the use of a "
+"serial console (either with modified boot blocks, or by specifying `-h` at "
+"the `Boot:` prompt), and hook up a standard terminal onto your first serial "
+"port. DDB works on any configured console driver, including a serial "
+"console."
+msgstr ""
+"Поскольку для работы DDB требуется драйвер консоли, ситуация усложняется, "
+"если сам драйвер консоли неисправен. Возможно, вы вспомните о возможности "
+"использования последовательной консоли (либо с модифицированными "
+"загрузочными блоками, либо указав `-h` в строке `Boot:`), подключив "
+"стандартный терминал к первому последовательному порту. DDB работает с любым "
+"настроенным драйвером консоли, включая последовательную консоль."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:650
+#, no-wrap
+msgid "Debugging Deadlocks"
+msgstr "Отладка взаимоблокировок"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:655
+msgid ""
+"You may experience so called deadlocks, a situation where a system stops "
+"doing useful work. To provide a helpful bug report in this situation, use "
+"man:ddb[4] as described in the previous section. Include the output of `ps` "
+"and `trace` for suspected processes in the report."
+msgstr ""
+"Вы можете столкнуться с так называемыми взаимоблокировками — ситуацией, "
+"когда система перестает выполнять полезную работу. Чтобы предоставить "
+"полезный отчет об ошибке в такой ситуации, используйте man:ddb[4], как "
+"описано в предыдущем разделе. Включите в отчет вывод команд `ps` и `trace` "
+"для подозрительных процессов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:659
+msgid ""
+"If possible, consider doing further investigation. The recipe below is "
+"especially useful if you suspect that a deadlock occurs in the VFS layer. "
+"Add these options to the kernel configuration file."
+msgstr ""
+"Если возможно, рассмотрите проведение дополнительного исследования. "
+"Приведенный ниже рецепт особенно полезен, если вы подозреваете, что взаимная "
+"блокировка происходит на уровне VFS. Добавьте следующие параметры в файл "
+"конфигурации ядра."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:670
+#, no-wrap
+msgid ""
+"makeoptions \tDEBUG=-g\n"
+"options \tINVARIANTS\n"
+"options \tINVARIANT_SUPPORT\n"
+"options \tWITNESS\n"
+"options \tWITNESS_SKIPSPIN\n"
+"options \tDEBUG_LOCKS\n"
+"options \tDEBUG_VFS_LOCKS\n"
+"options \tDIAGNOSTIC\n"
+msgstr ""
+"makeoptions \tDEBUG=-g\n"
+"options \tINVARIANTS\n"
+"options \tINVARIANT_SUPPORT\n"
+"options \tWITNESS\n"
+"options \tWITNESS_SKIPSPIN\n"
+"options \tDEBUG_LOCKS\n"
+"options \tDEBUG_VFS_LOCKS\n"
+"options \tDIAGNOSTIC\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:673
+msgid ""
+"When a deadlock occurs, in addition to the output of the `ps` command, "
+"provide information from the `show pcpu`, `show allpcpu`, `show locks`, "
+"`show alllocks`, `show lockedvnods` and `alltrace`."
+msgstr ""
+"При возникновении взаимоблокировки, помимо вывода команды `ps`, предоставьте "
+"информацию из `show pcpu`, `show allpcpu`, `show locks`, `show alllocks`, "
+"`show lockedvnods` и `alltrace`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:675
+msgid ""
+"To obtain meaningful backtraces for threaded processes, use `thread thread-"
+"id` to switch to the thread stack, and do a backtrace with `where`."
+msgstr ""
+"Для получения осмысленных трассировок стека для потоковых процессов "
+"используйте `thread thread-id` для переключения на стек потока и выполните "
+"трассировку с помощью `where`."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:677
+#, no-wrap
+msgid "Kernel debugging with Dcons"
+msgstr "Отладка ядра с помощью Dcons"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:683
+msgid ""
+"man:dcons[4] is a very simple console driver that is not directly connected "
+"with any physical devices. It just reads and writes characters from and to "
+"a buffer in a kernel or loader. Due to its simple nature, it is very useful "
+"for kernel debugging, especially with a FireWire(R) device. Currently, "
+"FreeBSD provides two ways to interact with the buffer from outside of the "
+"kernel using man:dconschat[8]."
+msgstr ""
+"man:dcons[4] — это очень простой драйвер консоли, который не связан напрямую "
+"с какими-либо физическими устройствами. Он просто читает и записывает "
+"символы из буфера в ядре или загрузчике и обратно. Благодаря своей простоте "
+"он очень полезен для отладки ядра, особенно с устройством FireWire(R). В "
+"настоящее время FreeBSD предоставляет два способа взаимодействия с буфером "
+"извне ядра с помощью man:dconschat[8]."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:684
+#, no-wrap
+msgid "Dcons over FireWire(R)"
+msgstr "Dcons через FireWire(R)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:692
+msgid ""
+"Most FireWire(R) (IEEE1394) host controllers are based on the OHCI "
+"specification that supports physical access to the host memory. This means "
+"that once the host controller is initialized, we can access the host memory "
+"without the help of software (kernel). We can exploit this facility for "
+"interaction with man:dcons[4]. man:dcons[4] provides similar functionality "
+"as a serial console. It emulates two serial ports, one for the console and "
+"DDB, the other for GDB. Since remote memory access is fully handled by the "
+"hardware, the man:dcons[4] buffer is accessible even when the system crashes."
+msgstr ""
+"Большинство контроллеров FireWire(R) (IEEE1394) основаны на спецификации "
+"OHCI, которая поддерживает физический доступ к памяти хоста. Это означает, "
+"что после инициализации контроллера хоста мы можем получить доступ к памяти "
+"хоста без помощи программного обеспечения (ядра). Мы можем использовать эту "
+"возможность для взаимодействия с man:dcons[4]. man:dcons[4] предоставляет "
+"функциональность, аналогичную последовательной консоли. Он эмулирует два "
+"последовательных порта: один для консоли и DDB, другой для GDB. Поскольку "
+"удалённый доступ к памяти полностью обрабатывается аппаратным обеспечением, "
+"буфер man:dcons[4] остаётся доступным даже при крахе системы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:695
+msgid ""
+"FireWire(R) devices are not limited to those integrated into motherboards. "
+"PCI cards exist for desktops, and a cardbus interface can be purchased for "
+"laptops."
+msgstr ""
+"Устройства FireWire(R) не только встраиваются в материнские платы. Для "
+"настольных компьютеров существуют PCI-карты, а для ноутбуков можно "
+"приобрести интерфейс CardBus."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:696
+#, no-wrap
+msgid "Enabling FireWire(R) and Dcons support on the target machine"
+msgstr "Включение поддержки FireWire(R) и Dcons на целевой машине"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:699
+msgid ""
+"To enable FireWire(R) and Dcons support in the kernel of the _target "
+"machine_:"
+msgstr "Чтобы включить поддержку FireWire(R) и Dcons в ядре _целевой машины_:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:701
+msgid ""
+"Make sure your kernel supports `dcons`, `dcons_crom` and `firewire`. `Dcons` "
+"should be statically linked with the kernel. For `dcons_crom` and "
+"`firewire`, modules should be OK."
+msgstr ""
+"Убедитесь, что ваше ядро поддерживает `dcons`, `dcons_crom` и `firewire`. "
+"`Dcons` должен быть статически связан с ядром. Для `dcons_crom` и `firewire` "
+"модули должны подойти."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:702
+msgid ""
+"Make sure physical DMA is enabled. You may need to add "
+"`hw.firewire.phydma_enable=1` to [.filename]#/boot/loader.conf#."
+msgstr ""
+"Убедитесь, что физический DMA включен. Возможно, потребуется добавить "
+"`hw.firewire.phydma_enable=1` в [.filename]#/boot/loader.conf#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:703
+msgid "Add options for debugging."
+msgstr "Добавьте параметры для отладки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:704
+msgid ""
+"Add `dcons_gdb=1` in [.filename]#/boot/loader.conf# if you use GDB over "
+"FireWire(R)."
+msgstr ""
+"Добавьте `dcons_gdb=1` в [.filename]#/boot/loader.conf#, если вы используете "
+"GDB через FireWire(R)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:705
+msgid "Enable `dcons` in [.filename]#/etc/ttys#."
+msgstr "Включите `dcons` в [.filename]#/etc/ttys#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:706
+msgid ""
+"Optionally, to force `dcons` to be the high-level console, add "
+"`hw.firewire.dcons_crom.force_console=1` to [.filename]#loader.conf#."
+msgstr ""
+"Это необязательно: чтобы принудительно сделать `dcons` высокоуровневой "
+"консолью, добавьте `hw.firewire.dcons_crom.force_console=1` в "
+"[.filename]#loader.conf#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:708
+msgid ""
+"To enable FireWire(R) and Dcons support in man:loader[8] on i386 or amd64:"
+msgstr ""
+"Чтобы включить поддержку FireWire(R) и Dcons в man:loader[8] на i386 или "
+"amd64:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:710
+msgid ""
+"Add `LOADER_FIREWIRE_SUPPORT=YES` in [.filename]#/etc/make.conf# and rebuild "
+"man:loader[8]:"
+msgstr ""
+"Добавьте `LOADER_FIREWIRE_SUPPORT=YES` в [.filename]#/etc/make.conf# и "
+"пересоберите man:loader[8]:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:714
+#, no-wrap
+msgid "# cd /sys/boot/i386 && make clean && make && make install\n"
+msgstr "# cd /sys/boot/i386 && make clean && make && make install\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:717
+msgid ""
+"To enable man:dcons[4] as an active low-level console, add "
+"`boot_multicons=\"YES\"` to [.filename]#/boot/loader.conf#."
+msgstr ""
+"Чтобы включить man:dcons[4] в качестве активной низкоуровневой консоли, "
+"добавьте `boot_multicons=\"YES\"` в [.filename]#/boot/loader.conf#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:720
+msgid ""
+"Here are a few configuration examples. A sample kernel configuration file "
+"would contain:"
+msgstr ""
+"Вот несколько примеров конфигурации. Образец файла конфигурации ядра может "
+"содержать:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:729
+#, no-wrap
+msgid ""
+"device dcons\n"
+"device dcons_crom\n"
+"options KDB\n"
+"options DDB\n"
+"options GDB\n"
+"options ALT_BREAK_TO_DEBUGGER\n"
+msgstr ""
+"device dcons\n"
+"device dcons_crom\n"
+"options KDB\n"
+"options DDB\n"
+"options GDB\n"
+"options ALT_BREAK_TO_DEBUGGER\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:732
+msgid "And a sample [.filename]#/boot/loader.conf# would contain:"
+msgstr "И образец [.filename]#/boot/loader.conf# может содержать:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:740
+#, no-wrap
+msgid ""
+"dcons_crom_load=\"YES\"\n"
+"dcons_gdb=1\n"
+"boot_multicons=\"YES\"\n"
+"hw.firewire.phydma_enable=1\n"
+"hw.firewire.dcons_crom.force_console=1\n"
+msgstr ""
+"dcons_crom_load=\"YES\"\n"
+"dcons_gdb=1\n"
+"boot_multicons=\"YES\"\n"
+"hw.firewire.phydma_enable=1\n"
+"hw.firewire.dcons_crom.force_console=1\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:742
+#, no-wrap
+msgid "Enabling FireWire(R) and Dcons support on the host machine"
+msgstr "Включение поддержки FireWire(R) и Dcons на главной машине"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:745
+msgid "To enable FireWire(R) support in the kernel on the _host machine_:"
+msgstr "Чтобы включить поддержку FireWire(R) в ядре на _основной машине_:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:749
+#, no-wrap
+msgid "# kldload firewire\n"
+msgstr "# kldload firewire\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:752
+msgid ""
+"Find out the EUI64 (the unique 64 bit identifier) of the FireWire(R) host "
+"controller, and use man:fwcontrol[8] or `dmesg` to find the EUI64 of the "
+"target machine."
+msgstr ""
+"Определите EUI64 (уникальный 64-битный идентификатор) контроллера "
+"FireWire(R) и используйте man:fwcontrol[8] или `dmesg`, чтобы найти EUI64 "
+"целевой машины."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:754
+msgid "Run man:dconschat[8], with:"
+msgstr "Запустите man:dconschat[8], с:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:758
+#, no-wrap
+msgid "# dconschat -e \\# -br -G 12345 -t 00-11-22-33-44-55-66-77\n"
+msgstr "# dconschat -e \\# -br -G 12345 -t 00-11-22-33-44-55-66-77\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:761
+msgid ""
+"The following key combinations can be used once man:dconschat[8] is running:"
+msgstr ""
+"Следующие комбинации клавиш могут быть использованы после запуска "
+"man:dconschat[8]:"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:767
+#, no-wrap
+msgid "kbd:[~+.]"
+msgstr "kbd:[~+.]"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:769
+#, no-wrap
+msgid "Disconnect"
+msgstr "Отсоединиться"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:770
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:773
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:776
+#, no-wrap
+msgid "kbd:[~]"
+msgstr "kbd:[~]"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:772
+#, no-wrap
+msgid "ALT BREAK"
+msgstr "ALT BREAK"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:775
+#, no-wrap
+msgid "RESET target"
+msgstr "ПЕРЕЗАГРУЗИТЬ (RESET) целевую машину"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:777
+#, no-wrap
+msgid "Suspend dconschat"
+msgstr "Приостановить dconschat"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:780
+msgid ""
+"Attach remote GDB by starting man:kgdb[1] with a remote debugging session:"
+msgstr ""
+"Присоедините удаленный GDB, запустив man:kgdb[1] с сеансом удаленной отладки:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:784
+#, no-wrap
+msgid " kgdb -r :12345 kernel\n"
+msgstr " kgdb -r :12345 kernel\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:786
+#, no-wrap
+msgid "Some general tips"
+msgstr "Некоторые общие рекомендации"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:789
+msgid "Here are some general tips:"
+msgstr "Вот несколько общих советов:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:791
+msgid ""
+"To take full advantage of the speed of FireWire(R), disable other slow "
+"console drivers:"
+msgstr ""
+"Чтобы в полной мере использовать скорость FireWire(R), отключите другие "
+"медленные драйверы консоли:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:796
+#, no-wrap
+msgid ""
+"# conscontrol delete ttyd0\t # serial console\n"
+"# conscontrol delete consolectl\t# video/keyboard\n"
+msgstr ""
+"# conscontrol delete ttyd0\t # serial console\n"
+"# conscontrol delete consolectl\t# video/keyboard\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:799
+msgid ""
+"There exists a GDB mode for man:emacs[1]; this is what you will need to add "
+"to your [.filename]#.emacs#:"
+msgstr ""
+"Существует режим GDB для man:emacs[1]; вот что нужно добавить в ваш "
+"[.filename]#.emacs#:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:806
+#, no-wrap
+msgid ""
+"(setq gud-gdba-command-name \"kgdb -a -a -a -r :12345\")\n"
+"(setq gdb-many-windows t)\n"
+"(xterm-mouse-mode 1)\n"
+"M-x gdba\n"
+msgstr ""
+"(setq gud-gdba-command-name \"kgdb -a -a -a -r :12345\")\n"
+"(setq gdb-many-windows t)\n"
+"(xterm-mouse-mode 1)\n"
+"M-x gdba\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:808
+#, no-wrap
+msgid "Dcons with KVM"
+msgstr "Dcons с KVM"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:812
+msgid ""
+"We can directly read the man:dcons[4] buffer via [.filename]#/dev/mem# for "
+"live systems, and in the core dump for crashed systems. These give you "
+"similar output to `dmesg -a`, but the man:dcons[4] buffer includes more "
+"information."
+msgstr ""
+"Мы можем напрямую читать буфер man:dcons[4] через [.filename]#/dev/mem# для "
+"работающих систем и в дампе памяти для систем после аварии. Это даёт "
+"аналогичный вывод команде `dmesg -a`, но буфер man:dcons[4] содержит больше "
+"информации."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:813
+#, no-wrap
+msgid "Using Dcons with KVM"
+msgstr "Использование Dcons с KVM"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:816
+msgid "To use man:dcons[4] with KVM:"
+msgstr "Для использования man:dcons[4] с KVM:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:818
+msgid "Dump a man:dcons[4] buffer of a live system:"
+msgstr "Дамп буфера man:dcons[4] работающей системы:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:822
+#, no-wrap
+msgid "# dconschat -1\n"
+msgstr "# dconschat -1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:825
+msgid "Dump a man:dcons[4] buffer of a crash dump:"
+msgstr "Дамп буфера man:dcons[4] аварийного дампа:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:829
+#, no-wrap
+msgid "# dconschat -1 -M vmcore.XX\n"
+msgstr "# dconschat -1 -M vmcore.XX\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:832
+msgid "Live core debugging can be done via:"
+msgstr "Отладка ядра в реальном времени может быть выполнена через:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:837
+#, no-wrap
+msgid ""
+"# fwcontrol -m target_eui64\n"
+"# kgdb kernel /dev/fwmem0.2\n"
+msgstr ""
+"# fwcontrol -m target_eui64\n"
+"# kgdb kernel /dev/fwmem0.2\n"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:840
+#, no-wrap
+msgid "Glossary of Kernel Options for Debugging"
+msgstr "Глоссарий параметров ядра для отладки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:843
+msgid ""
+"This section provides a brief glossary of compile-time kernel options used "
+"for debugging:"
+msgstr ""
+"В этом разделе представлен краткий глоссарий параметров ядра, указываемых "
+"при компиляции и относящихся к отладке:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:845
+msgid ""
+"`options KDB`: compiles in the kernel debugger framework. Required for "
+"`options DDB` and `options GDB`. Little or no performance overhead. By "
+"default, the debugger will be entered on panic instead of an automatic "
+"reboot."
+msgstr ""
+"`options KDB`: включает фреймворк отладки ядра. Необходим для `options DDB` "
+"и `options GDB`. Практически не влияет на производительность. По умолчанию "
+"отладчик будет запущен при панике вместо автоматической перезагрузки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:846
+msgid ""
+"`options KDB_UNATTENDED`: change the default value of the "
+"`debug.debugger_on_panic` sysctl to 0, which controls whether the debugger "
+"is entered on panic. When `options KDB` is not compiled into the kernel, the "
+"behavior is to automatically reboot on panic; when it is compiled into the "
+"kernel, the default behavior is to drop into the debugger unless `options "
+"KDB_UNATTENDED` is compiled in. If you want to leave the kernel debugger "
+"compiled into the kernel but want the system to come back up unless you're "
+"on-hand to use the debugger for diagnostics, use this option."
+msgstr ""
+"`options KDB_UNATTENDED`: изменяет значение по умолчанию системной настройки "
+"`debug.debugger_on_panic` на 0, что управляет входом в отладчик при панике. "
+"Если `options KDB` не вкомпилировано в ядро, поведение по умолчанию — "
+"автоматическая перезагрузка при панике; если оно вкомпилировано в ядро, "
+"поведение по умолчанию — переход в отладчик, если не вкомпилирована опция "
+"`options KDB_UNATTENDED`. Если вы хотите оставить отладчик ядра "
+"вкомпилированным в ядро, но желаете, чтобы система перезагружалась, пока вы "
+"не готовы использовать отладчик для диагностики, используйте эту опцию."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:847
+msgid ""
+"`options KDB_TRACE`: change the default value of the `debug.trace_on_panic` "
+"sysctl to 1, which controls whether the debugger automatically prints a "
+"stack trace on panic. Especially if running with `options KDB_UNATTENDED`, "
+"this can be helpful to gather basic debugging information on the serial or "
+"firewire console while still rebooting to recover."
+msgstr ""
+"`options KDB_TRACE`: изменяет значение по умолчанию системной настройки "
+"`debug.trace_on_panic` на 1, что управляет автоматическим выводом "
+"трассировки стека при панике. Особенно полезно при использовании с `options "
+"KDB_UNATTENDED`, так как позволяет собрать базовую отладочную информацию на "
+"последовательной консоли или консоли FireWire, продолжая перезагрузку для "
+"восстановления."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:848
+msgid ""
+"`options DDB`: compile in support for the console debugger, DDB. This "
+"interactive debugger runs on whatever the active low-level console of the "
+"system is, which includes the video console, serial console, or firewire "
+"console. It provides basic integrated debugging facilities, such as stack "
+"tracing, process and thread listing, dumping of lock state, VM state, file "
+"system state, and kernel memory management. DDB does not require software "
+"running on a second machine or being able to generate a core dump or full "
+"debugging kernel symbols, and provides detailed diagnostics of the kernel at "
+"run-time. Many bugs can be fully diagnosed using only DDB output. This "
+"option depends on `options KDB`."
+msgstr ""
+"`options DDB`: включает поддержку консольного отладчика DDB. Этот "
+"интерактивный отладчик работает на активной низкоуровневой консоли системы, "
+"включая видеоконсоль, последовательную консоль или консоль FireWire. Он "
+"предоставляет базовые встроенные средства отладки, такие как трассировка "
+"стека, список процессов и потоков, вывод состояния блокировок, состояния "
+"виртуальной памяти, состояния файловой системы и управления ядром памяти. "
+"DDB не требует работы программного обеспечения на второй машине или "
+"возможности создания дампа памяти или полных символов отладки ядра, а также "
+"предоставляет детальную диагностику ядра во время выполнения. Многие ошибки "
+"могут быть полностью диагностированы с использованием только вывода DDB. Эта "
+"опция зависит от `options KDB`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:849
+msgid ""
+"`options GDB`: compile in support for the remote debugger, GDB, which can "
+"operate over serial cable or firewire. When the debugger is entered, GDB may "
+"be attached to inspect structure contents, generate stack traces, etc. Some "
+"kernel state is more awkward to access than in DDB, which is able to "
+"generate useful summaries of kernel state automatically, such as "
+"automatically walking lock debugging or kernel memory management structures, "
+"and a second machine running the debugger is required. On the other hand, "
+"GDB combines information from the kernel source and full debugging symbols, "
+"and is aware of full data structure definitions, local variables, and is "
+"scriptable. This option is not required to run GDB on a kernel core dump. "
+"This option depends on `options KDB`."
+msgstr ""
+"`options GDB`: включает поддержку удалённого отладчика GDB, который может "
+"работать через последовательный кабель или FireWire. При входе в отладчик "
+"можно подключить GDB для проверки содержимого структур, генерации "
+"трассировки стека и т.д. Некоторые состояния ядра сложнее исследовать, чем в "
+"DDB, который способен автоматически создавать полезные сводки состояния "
+"ядра, например, автоматически обходить структуры отладки блокировок или "
+"управления памятью ядра, но для этого требуется вторая машина с запущенным "
+"отладчиком. С другой стороны, GDB объединяет информацию из исходного кода "
+"ядра и полных отладочных символов, знает полные определения структур данных, "
+"локальные переменные и поддерживает написание скриптов. Эта опция не "
+"требуется для запуска GDB на дампе памяти ядра. Данная опция зависит от "
+"`options KDB`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:850
+msgid ""
+"`options BREAK_TO_DEBUGGER`, `options ALT_BREAK_TO_DEBUGGER`: allow a break "
+"signal or alternative signal on the console to enter the debugger. If the "
+"system hangs without a panic, this is a useful way to reach the debugger. "
+"Due to the current kernel locking, a break signal generated on a serial "
+"console is significantly more reliable at getting into the debugger, and is "
+"generally recommended. This option has little or no performance impact."
+msgstr ""
+"`options BREAK_TO_DEBUGGER`, `options ALT_BREAK_TO_DEBUGGER`: позволяют "
+"сигналу прерывания или альтернативному сигналу на консоли войти в отладчик. "
+"Если система зависает без паники, это полезный способ попасть в отладчик. Из-"
+"за текущей блокировки ядра сигнал прерывания, сгенерированный на "
+"последовательной консоли, значительно надежнее для входа в отладчик и обычно "
+"рекомендуется. Данная опция оказывает незначительное или нулевое влияние на "
+"производительность."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:851
+msgid ""
+"`options INVARIANTS`: compile into the kernel a large number of run-time "
+"assertion checks and tests, which constantly test the integrity of kernel "
+"data structures and the invariants of kernel algorithms. These tests can be "
+"expensive, so are not compiled in by default, but help provide useful \"fail "
+"stop\" behavior, in which certain classes of undesired behavior enter the "
+"debugger before kernel data corruption occurs, making them easier to debug. "
+"Tests include memory scrubbing and use-after-free testing, which is one of "
+"the more significant sources of overhead. This option depends on `options "
+"INVARIANT_SUPPORT`."
+msgstr ""
+"`options INVARIANTS`: включает в ядро большое количество проверок и тестов "
+"во время выполнения, которые постоянно проверяют целостность структур данных "
+"ядра и инварианты алгоритмов ядра. Эти тесты могут быть затратными, поэтому "
+"по умолчанию не включены, но они помогают обеспечить полезное поведение "
+"\"fail stop\", при котором определённые классы нежелательного поведения "
+"попадают в отладчик до возникновения повреждения данных ядра, что упрощает "
+"их отладку. Тесты включают в себя очистку памяти и проверку использования "
+"после освобождения, что является одним из наиболее значимых источников "
+"накладных расходов. Эта опция зависит от `options INVARIANT_SUPPORT`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:852
+msgid ""
+"`options INVARIANT_SUPPORT`: many of the tests present in `options "
+"INVARIANTS` require modified data structures or additional kernel symbols to "
+"be defined."
+msgstr ""
+"`options INVARIANT_SUPPORT`: многие тесты, присутствующие в `options "
+"INVARIANTS`, требуют модифицированных структур данных или определения "
+"дополнительных символов ядра."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:853
+msgid ""
+"`options WITNESS`: this option enables run-time lock order tracking and "
+"verification, and is an invaluable tool for deadlock diagnosis. WITNESS "
+"maintains a graph of acquired lock orders by lock type, and checks the graph "
+"at each acquire for cycles (implicit or explicit). If a cycle is detected, a "
+"warning and stack trace are generated to the console, indicating that a "
+"potential deadlock might have occurred. WITNESS is required in order to use "
+"the `show locks`, `show witness` and `show alllocks` DDB commands. This "
+"debug option has significant performance overhead, which may be somewhat "
+"mitigated through the use of `options WITNESS_SKIPSPIN`. Detailed "
+"documentation may be found in man:witness[4]."
+msgstr ""
+"`options WITNESS`: эта опция включает отслеживание и проверку порядка "
+"блокировок во время выполнения, что является неоценимым инструментом для "
+"диагностики взаимоблокировок. WITNESS поддерживает граф полученных порядков "
+"блокировок по типам блокировок и проверяет граф на каждом получении на "
+"наличие циклов (явных или неявных). Если цикл обнаружен, на консоль "
+"выводится предупреждение и трассировка стека, указывающие на возможное "
+"возникновение взаимоблокировки. WITNESS необходим для использования команд "
+"DDB `show locks`, `show witness` и `show alllocks`. Эта отладочная опция "
+"создает значительную нагрузку на производительность, которую можно несколько "
+"уменьшить с помощью `options WITNESS_SKIPSPIN`. Подробная документация "
+"доступна в man:witness[4]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:854
+msgid ""
+"`options WITNESS_SKIPSPIN`: disable run-time checking of spinlock lock order "
+"with WITNESS. As spin locks are acquired most frequently in the scheduler, "
+"and scheduler events occur often, this option can significantly speed up "
+"systems running with WITNESS. This option depends on `options WITNESS`."
+msgstr ""
+"`options WITNESS_SKIPSPIN`: отключает проверку порядка блокировки spinlock "
+"во время выполнения с WITNESS. Поскольку spin-блокировки чаще всего "
+"захватываются в планировщике, а события планировщика происходят часто, эта "
+"опция может значительно ускорить системы, работающие с WITNESS. Эта опция "
+"зависит от `options WITNESS`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:855
+msgid ""
+"`options WITNESS_KDB`: change the default value of the `debug.witness.kdb` "
+"sysctl to 1, which causes WITNESS to enter the debugger when a lock order "
+"violation is detected, rather than simply printing a warning. This option "
+"depends on `options WITNESS`."
+msgstr ""
+"`options WITNESS_KDB`: изменяет значение по умолчанию системной настройки "
+"`debug.witness.kdb` на 1, что приводит к входу в отладчик при обнаружении "
+"нарушения порядка блокировок вместо простого вывода предупреждения. Эта "
+"опция зависит от `options WITNESS`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:856
+msgid ""
+"`options SOCKBUF_DEBUG`: perform extensive run-time consistency checking on "
+"socket buffers, which can be useful for debugging both socket bugs and race "
+"conditions in protocols and device drivers that interact with sockets. This "
+"option significantly impacts network performance, and may change the timing "
+"in device driver races."
+msgstr ""
+"`options SOCKBUF_DEBUG`: выполнять расширенную проверку согласованности "
+"сокетных буферов во время выполнения, что может быть полезно для отладки как "
+"ошибок в сокетах, так и состояний гонки в протоколах и драйверах устройств, "
+"взаимодействующих с сокетами. Данная опция значительно влияет на "
+"производительность сети и может изменить временные параметры в состояниях "
+"гонки драйверов устройств."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:857
+msgid ""
+"`options DEBUG_VFS_LOCKS`: track lock acquisition points for lockmgr/vnode "
+"locks, expanding the amount of information displayed by `show lockedvnods` "
+"in DDB. This option has a measurable performance impact."
+msgstr ""
+"`options DEBUG_VFS_LOCKS`: отслеживает точки получения блокировок для "
+"lockmgr/vnode, расширяя объем информации, отображаемой командой `show "
+"lockedvnods` в DDB. Данная опция оказывает заметное влияние на "
+"производительность."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:858
+msgid ""
+"`options DEBUG_MEMGUARD`: a replacement for the man:malloc[9] kernel memory "
+"allocator that uses the VM system to detect reads or writes from allocated "
+"memory after free. Details may be found in man:memguard[9]. This option has "
+"a significant performance impact, but can be very helpful in debugging "
+"kernel memory corruption bugs."
+msgstr ""
+"`options DEBUG_MEMGUARD`: замена для man:malloc[9], аллокатор памяти ядра, "
+"который использует систему VM для обнаружения чтения или записи в "
+"освобождённую память. Подробности можно найти в man:memguard[9]. Данная "
+"опция значительно влияет на производительность, но может быть очень полезна "
+"при отладке ошибок повреждения памяти ядра."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:859
+msgid ""
+"`options DIAGNOSTIC`: enable additional, more expensive diagnostic tests "
+"along the lines of `options INVARIANTS`."
+msgstr ""
+"`options DIAGNOSTIC`: включает дополнительные, более затратные "
+"диагностические тесты, аналогичные `options INVARIANTS`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:860
+msgid ""
+"`options KASAN`: enable the Kernel Address Sanitizer. This enables compiler "
+"instrumentation which can be used to detect invalid memory accesses in the "
+"kernel, such as use-after-frees and buffer overflows. This largely "
+"supersedes `options DEBUG_MEMGUARD`. See man:kasan[9] for details, and for "
+"the currently supported platforms."
+msgstr ""
+"`options KASAN`: включает отладчик адресов ядра (Kernel Address Sanitizer). "
+"Это включает инструментирование компилятора, которое может использоваться "
+"для обнаружения недопустимых обращений к памяти в ядре, таких как "
+"использование после освобождения и переполнение буфера. В значительной "
+"степени заменяет `options DEBUG_MEMGUARD`. Подробности и список "
+"поддерживаемых платформ см. в man:kasan[9]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/kerneldebug/_index.adoc:860
+msgid ""
+"`options KMSAN`: enable the Kernel Memory Sanitizer. This enables compiler "
+"instrumentation which can be used to detect uses of uninitialized memory. "
+"See man:kmsan[9] for details, and for the currently supported platforms."
+msgstr ""
+"`options KMSAN`: включить отладчик использования памяти ядра (Kernel Memory "
+"Sanitizer). Это включает инструментирование компилятора, которое может "
+"использоваться для обнаружения использования неинициализированной памяти. "
+"Подробности и список поддерживаемых платформ см. в man:kmsan[9]."
+
+#~ msgid "And for DDD ([.filename]#devel/ddd#):"
+#~ msgstr "И для DDD ([.filename]#devel/ddd#):"
+
+#, no-wrap
+#~ msgid ""
+#~ "# remote serial protocol\n"
+#~ "LANG=C ddd --debugger kgdb -r :12345 kernel\n"
+#~ "# live core debug\n"
+#~ "LANG=C ddd --debugger kgdb kernel /dev/fwmem0.2\n"
+#~ msgstr ""
+#~ "# remote serial protocol\n"
+#~ "LANG=C ddd --debugger kgdb -r :12345 kernel\n"
+#~ "# live core debug\n"
+#~ "LANG=C ddd --debugger kgdb kernel /dev/fwmem0.2\n"
diff --git a/documentation/content/ru/books/developers-handbook/l10n/_index.adoc b/documentation/content/ru/books/developers-handbook/l10n/_index.adoc
new file mode 100644
index 0000000000..7b21ea51f3
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/l10n/_index.adoc
@@ -0,0 +1,228 @@
+---
+authors:
+description: 'Локализация и интернационализация - L10N и I18N в FreeBSD'
+next: books/developers-handbook/policies
+params:
+ path: /books/developers-handbook/l10n/
+prev: books/developers-handbook/secure
+showBookMenu: true
+tags: ["L10N", "I18N", "Localization", "Internationalization", "FreeBSD"]
+title: 'Глава 4. Локализация и интернационализация - L10N и I18N'
+weight: 5
+---
+
+[[l10n]]
+= Локализация и интернационализация - L10N и I18N
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 4
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[l10n-programming]]
+== Программирование приложений с поддержкой I18N
+
+Чтобы сделать ваше приложение более полезным для пользователей, говорящих на других языках, мы надеемся, что вы будете разрабатывать его с поддержкой интернационализации (I18N). Компилятор GNU gcc и библиотеки для графического интерфейса, такие как QT и GTK, поддерживают I18N за счёт специальной обработки строк. Создание программы с поддержкой I18N очень просто. Это позволяет участникам быстро адаптировать ваше приложение для других языков. Для получения более подробной информации обратитесь к документации по I18N для конкретной библиотеки.
+
+Вопреки распространённому мнению, написание кода, соответствующего стандарту I18N, является простой задачей. Обычно оно заключается лишь в оборачивании строк в специфичные для библиотеки функции. Кроме того, убедитесь, что поддерживаются широкие или многобайтовые символы.
+
+=== Призыв к объединению усилий по интернационализации
+
+Нам стало известно, что индивидуальные усилия по интернационализации (I18N) и локализации (L10N) в каждой стране дублируют работу друг друга. Многие из нас снова и снова неэффективно изобретают велосипед. Мы надеемся, что различные крупные группы разработчиков в области I18N смогут объединится для совместной работы и ответственности, подобно Core Team в FreeBSD.
+
+В настоящее время мы надеемся, что при написании или портировании I18N-программ вы будете отправлять их в соответствующие списки рассылки FreeBSD каждой страны для тестирования. В будущем мы надеемся создать приложения, которые будут работать на всех языках "из коробки" без грязных хаков.
+
+Создана группа {freebsd-i18n}. Если вы разработчик в области I18N/L10N, присылайте свои комментарии, идеи, вопросы и всё, что относится к этой теме по вашему мнению.
+
+=== Perl и Python
+
+В Perl и Python есть библиотеки для I18N и работы с широкими символами. Пожалуйста, используйте их для соответствия требованиям I18N.
+
+[[posix-nls]]
+== Локализованные сообщения с поддержкой родного языка POSIX.1 (NLS — Native Language Support)
+
+Помимо основных функций интернационализации (I18N), таких как поддержка различных кодировок ввода или национальных соглашений, например, различных разделителей десятичных знаков, на более высоком уровне I18N можно локализовать сообщения, выводимые различными программами. Распространённый способ сделать это — использовать функции NLS POSIX.1, которые предоставляются как часть базовой системы FreeBSD.
+
+[[nls-catalogs]]
+=== Организация локализованных сообщений в файлы каталогов
+
+POSIX.1 NLS использует файлы каталогов. Эти файлы содержат локализованные сообщения в желаемой кодировке. Сообщения организованы в наборы, и каждое сообщение идентифицируется целым числом в соответствующем наборе. Файлы каталогов традиционно называются по имени локали, для которой они содержат локализованные сообщения, с добавлением расширения `.msg`. Например, венгерские сообщения для кодировки ISO8859-2 должны храниться в файле с именем [.filename]#hu_HU.ISO8859-2#.
+
+Эти файлы каталогов представляют собой обычные текстовые файлы, содержащие нумерованные сообщения. Можно добавлять комментарии, начиная строку со знака `$`. Границы наборов также разделяются специальными комментариями, где ключевое слово `set` должно следовать непосредственно за знаком `$`. После ключевого слова `set` указывается номер набора. Например:
+
+[.programlisting]
+....
+$set 1
+....
+
+Фактические записи сообщений начинаются с номера сообщения, за которым следует локализованное сообщение. Допускаются известные модификаторы из man:printf[3]:
+
+[.programlisting]
+....
+15 "File not found: %s\n"
+....
+
+Файлы языкового каталога должны быть скомпилированы в бинарный формат перед тем, как они могут быть открыты программой. Это преобразование выполняется с помощью утилиты man:gencat[1]. Её первый аргумент — это имя файла скомпилированного каталога, а последующие аргументы — входные каталоги. Локализованные сообщения также могут быть организованы в несколько файлов каталогов, и затем все они могут быть обработаны с помощью man:gencat[1].
+
+[[nls-using]]
+=== Использование файлов каталога из исходного кода
+
+Использование файлов каталогов простое. Чтобы вызвать функции, работающие с ними, необходимо включить файл [.filename]#nl_types.h#. Перед использованием каталога его нужно открыть с помощью man:catopen[3]. Функция принимает два аргумента. Первый параметр — это имя установленного и скомпилированного каталога. Обычно используется имя программы, например, grep. Это имя будет использоваться при поиске скомпилированного файла каталога. Вызов man:catopen[3] ищет этот файл в [.filename]#/usr/share/nls/locale/catname# и в [.filename]#/usr/local/share/nls/locale/catname#, где `locale` — установленная локализация, а `catname` — имя обсуждаемого каталога. Второй параметр — это константа, которая может принимать два значения:
+
+* `NL_CAT_LOCALE`, что означает, что используемый файл каталога будет основан на `LC_MESSAGES`.
+* `0`, что означает, что для открытия соответствующего каталога необходимо использовать `LANG`.
+
+Вызов man:catopen[3] возвращает идентификатор каталога типа `nl_catd`. Обратитесь к справочной странице для получения списка возможных кодов ошибок.
+
+После открытия каталога man:catgets[3] может быть использована для извлечения сообщения. Первый параметр — это идентификатор каталога, возвращаемый man:catopen[3], второй — номер набора, третий — номер сообщения, а четвертый — резервное сообщение, которое будет возвращено, если запрошенное сообщение не может быть извлечено из файла каталога.
+
+После использования файла каталога его необходимо закрыть, вызвав man:catclose[3], которая принимает один аргумент — идентификатор каталога.
+
+[[nls-example]]
+=== Практический пример
+
+Следующий пример демонстрирует простое решение по гибкому использованию каталогов NLS.
+
+Нижеследующие строки необходимо поместить в общий заголовочный файл программы, который включается во все исходные файлы, где необходимы локализованные сообщения:
+
+[.programlisting]
+....
+#ifdef WITHOUT_NLS
+#define getstr(n) nlsstr[n]
+#else
+#include nl_types.h
+
+extern nl_catd catalog;
+#define getstr(n) catgets(catalog, 1, n, nlsstr[n])
+#endif
+
+extern char *nlsstr[];
+....
+
+Далее, добавьте эти строки в глобальную секцию объявлений основного исходного файла:
+
+[.programlisting]
+....
+#ifndef WITHOUT_NLS
+#include nl_types.h
+nl_catd catalog;
+#endif
+
+/*
+ * Default messages to use when NLS is disabled or no catalog
+ * is found.
+ */
+char *nlsstr[] = {
+ "",
+/* 1*/ "some random message",
+/* 2*/ "some other message"
+};
+....
+
+Далее следуют реальные фрагменты кода, которые открывают, читают и закрывают каталог:
+
+[.programlisting]
+....
+#ifndef WITHOUT_NLS
+ catalog = catopen("myapp", NL_CAT_LOCALE);
+#endif
+
+...
+
+printf(getstr(1));
+
+...
+
+#ifndef WITHOUT_NLS
+ catclose(catalog);
+#endif
+....
+
+==== Уменьшение количества строк для локализации
+
+Хороший способ уменьшить количество строк, требующих локализации, — использовать сообщения об ошибках из libc. Это также полезно для избежания дублирования и обеспечения единообразия сообщений об ошибках, с которыми может столкнуться множество программ.
+
+Вот пример, который не использует сообщения об ошибках из libc:
+
+[.programlisting]
+....
+#include err.h
+...
+if (!S_ISDIR(st.st_mode))
+ errx(1, "argument is not a directory");
+....
+
+Это можно преобразовать для вывода сообщения об ошибке, считывая `errno` и выводя соответствующее сообщение об ошибке:
+
+[.programlisting]
+....
+#include err.h
+#include errno.h
+...
+if (!S_ISDIR(st.st_mode)) {
+ errno = ENOTDIR;
+ err(1, NULL);
+}
+....
+
+В этом примере пользовательская строка исключена, что упростит работу переводчиков при локализации программы, а пользователи увидят стандартное сообщение об ошибке "Not a directory" при возникновении данной ошибки. Это сообщение, вероятно, будет выглядеть более привычным для них. Обратите внимание, что для прямого доступа к `errno` потребовалось включить [.filename]#errno.h#.
+
+Стоит отметить, что бывают случаи, когда `errno` устанавливается автоматически предыдущим вызовом, поэтому нет необходимости устанавливать его явно:
+
+[.programlisting]
+....
+#include err.h
+...
+if ((p = malloc(size)) == NULL)
+ err(1, NULL);
+....
+
+[[nls-mk]]
+=== Использование [.filename]#bsd.nls.mk#
+
+Использование файлов каталогов требует нескольких повторяемых шагов, таких как компиляция каталогов и их установка в нужное место. Чтобы ещё больше упростить этот процесс, [.filename]#bsd.nls.mk# вводит некоторые макросы. Нет необходимости явно включать [.filename]#bsd.nls.mk#, он подключается автоматически из общих Makefiles, таких как [.filename]#bsd.prog.mk# или [.filename]#bsd.lib.mk#.
+
+Обычно достаточно определить `NLSNAME`, которое должно содержать имя каталога, указанное в качестве первого аргумента man:catopen[3], и перечислить файлы каталогов в `NLS` без расширения `.msg`. Вот пример, который позволяет отключить NLS при использовании с предыдущими примерами кода. Для сборки программы без поддержки NLS необходимо определить переменную `WITHOUT_NLS` man:make[1].
+
+[.programlisting]
+....
+.if !defined(WITHOUT_NLS)
+NLS= es_ES.ISO8859-1
+NLS+= hu_HU.ISO8859-2
+NLS+= pt_BR.ISO8859-1
+.else
+CFLAGS+= -DWITHOUT_NLS
+.endif
+....
+
+Обычно файлы каталогов размещаются в подкаталоге [.filename]#nls#, и это поведение по умолчанию для [.filename]#bsd.nls.mk#. Однако можно переопределить расположение каталогов с помощью переменной `NLSSRCDIR` man:make[1]. Имя по умолчанию для предварительно скомпилированных файлов каталогов также следует упомянутому ранее соглашению об именовании. Его можно переопределить, установив переменную `NLSNAME`. Существуют и другие параметры для точной настройки обработки файлов каталогов, но обычно в этом нет необходимости, поэтому они здесь не описаны. Для получения дополнительной информации о [.filename]#bsd.nls.mk# обратитесь к самому файлу — он короткий и легко понятен.
diff --git a/documentation/content/ru/books/developers-handbook/l10n/_index.po b/documentation/content/ru/books/developers-handbook/l10n/_index.po
new file mode 100644
index 0000000000..3a8d1dfcbc
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/l10n/_index.po
@@ -0,0 +1,659 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-24 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookl10n_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:1
+#, no-wrap
+msgid "Localization and Internationalization - L10N and I18N in FreeBSD"
+msgstr "Локализация и интернационализация - L10N и I18N в FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:1
+#, no-wrap
+msgid "Chapter 4. Localization and Internationalization - L10N and I18N"
+msgstr "Глава 4. Локализация и интернационализация - L10N и I18N"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:15
+#, no-wrap
+msgid "Localization and Internationalization - L10N and I18N"
+msgstr "Локализация и интернационализация - L10N и I18N"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:53
+#, no-wrap
+msgid "Programming I18N Compliant Applications"
+msgstr "Программирование приложений с поддержкой I18N"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:60
+msgid ""
+"To make your application more useful for speakers of other languages, we "
+"hope that you will program I18N compliant. The GNU gcc compiler and GUI "
+"libraries like QT and GTK support I18N through special handling of strings. "
+"Making a program I18N compliant is very easy. It allows contributors to "
+"port your application to other languages quickly. Refer to the library "
+"specific I18N documentation for more details."
+msgstr ""
+"Чтобы сделать ваше приложение более полезным для пользователей, говорящих на "
+"других языках, мы надеемся, что вы будете разрабатывать его с поддержкой "
+"интернационализации (I18N). Компилятор GNU gcc и библиотеки для графического "
+"интерфейса, такие как QT и GTK, поддерживают I18N за счёт специальной "
+"обработки строк. Создание программы с поддержкой I18N очень просто. Это "
+"позволяет участникам быстро адаптировать ваше приложение для других языков. "
+"Для получения более подробной информации обратитесь к документации по I18N "
+"для конкретной библиотеки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:64
+msgid ""
+"In contrast with common perception, I18N compliant code is easy to write. "
+"Usually, it only involves wrapping your strings with library specific "
+"functions. In addition, please be sure to allow for wide or multibyte "
+"character support."
+msgstr ""
+"Вопреки распространённому мнению, написание кода, соответствующего стандарту "
+"I18N, является простой задачей. Обычно оно заключается лишь в оборачивании "
+"строк в специфичные для библиотеки функции. Кроме того, убедитесь, что "
+"поддерживаются широкие или многобайтовые символы."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:65
+#, no-wrap
+msgid "A Call to Unify the I18N Effort"
+msgstr "Призыв к объединению усилий по интернационализации"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:70
+msgid ""
+"It has come to our attention that the individual I18N/L10N efforts for each "
+"country has been repeating each others' efforts. Many of us have been "
+"reinventing the wheel repeatedly and inefficiently. We hope that the "
+"various major groups in I18N could congregate into a group effort similar to "
+"the Core Team's responsibility."
+msgstr ""
+"Нам стало известно, что индивидуальные усилия по интернационализации (I18N) "
+"и локализации (L10N) в каждой стране дублируют работу друг друга. Многие из "
+"нас снова и снова неэффективно изобретают велосипед. Мы надеемся, что "
+"различные крупные группы разработчиков в области I18N смогут объединится для "
+"совместной работы и ответственности, подобно Core Team в FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:73
+msgid ""
+"Currently, we hope that, when you write or port I18N programs, you would "
+"send it out to each country's related FreeBSD mailing list for testing. In "
+"the future, we hope to create applications that work in all the languages "
+"out-of-the-box without dirty hacks."
+msgstr ""
+"В настоящее время мы надеемся, что при написании или портировании I18N-"
+"программ вы будете отправлять их в соответствующие списки рассылки FreeBSD "
+"каждой страны для тестирования. В будущем мы надеемся создать приложения, "
+"которые будут работать на всех языках \"из коробки\" без грязных хаков."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:76
+msgid ""
+"The {freebsd-i18n} has been established. If you are an I18N/L10N developer, "
+"please send your comments, ideas, questions, and anything you deem related "
+"to it."
+msgstr ""
+"Создана группа {freebsd-i18n}. Если вы разработчик в области I18N/L10N, "
+"присылайте свои комментарии, идеи, вопросы и всё, что относится к этой теме "
+"по вашему мнению."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:77
+#, no-wrap
+msgid "Perl and Python"
+msgstr "Perl и Python"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:81
+msgid ""
+"Perl and Python have I18N and wide character handling libraries. Please use "
+"them for I18N compliance."
+msgstr ""
+"В Perl и Python есть библиотеки для I18N и работы с широкими символами. "
+"Пожалуйста, используйте их для соответствия требованиям I18N."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:83
+#, no-wrap
+msgid "Localized Messages with POSIX.1 Native Language Support (NLS)"
+msgstr "Локализованные сообщения с поддержкой родного языка POSIX.1 (NLS — Native Language Support)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:87
+msgid ""
+"Beyond the basic I18N functions, like supporting various input encodings or "
+"supporting national conventions, such as the different decimal separators, "
+"at a higher level of I18N, it is possible to localize the messages written "
+"to the output by the various programs. A common way of doing this is using "
+"the POSIX.1 NLS functions, which are provided as a part of the FreeBSD base "
+"system."
+msgstr ""
+"Помимо основных функций интернационализации (I18N), таких как поддержка "
+"различных кодировок ввода или национальных соглашений, например, различных "
+"разделителей десятичных знаков, на более высоком уровне I18N можно "
+"локализовать сообщения, выводимые различными программами. Распространённый "
+"способ сделать это — использовать функции NLS POSIX.1, которые "
+"предоставляются как часть базовой системы FreeBSD."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:89
+#, no-wrap
+msgid "Organizing Localized Messages into Catalog Files"
+msgstr "Организация локализованных сообщений в файлы каталогов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:95
+msgid ""
+"POSIX.1 NLS is based on catalog files, which contain the localized messages "
+"in the desired encoding. The messages are organized into sets and each "
+"message is identified by an integer number in the containing set. The "
+"catalog files are conventionally named after the locale they contain "
+"localized messages for, followed by the `.msg` extension. For instance, the "
+"Hungarian messages for ISO8859-2 encoding should be stored in a file called "
+"[.filename]#hu_HU.ISO8859-2#."
+msgstr ""
+"POSIX.1 NLS использует файлы каталогов. Эти файлы содержат локализованные "
+"сообщения в желаемой кодировке. Сообщения организованы в наборы, и каждое "
+"сообщение идентифицируется целым числом в соответствующем наборе. Файлы "
+"каталогов традиционно называются по имени локали, для которой они содержат "
+"локализованные сообщения, с добавлением расширения `.msg`. Например, "
+"венгерские сообщения для кодировки ISO8859-2 должны храниться в файле с "
+"именем [.filename]#hu_HU.ISO8859-2#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:100
+msgid ""
+"These catalog files are common text files that contain the numbered "
+"messages. It is possible to write comments by starting the line with a `$` "
+"sign. Set boundaries are also separated by special comments, where the "
+"keyword `set` must directly follow the `$` sign. The `set` keyword is then "
+"followed by the set number. For example:"
+msgstr ""
+"Эти файлы каталогов представляют собой обычные текстовые файлы, содержащие "
+"нумерованные сообщения. Можно добавлять комментарии, начиная строку со знака "
+"`$`. Границы наборов также разделяются специальными комментариями, где "
+"ключевое слово `set` должно следовать непосредственно за знаком `$`. После "
+"ключевого слова `set` указывается номер набора. Например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:104
+#, no-wrap
+msgid "$set 1\n"
+msgstr "$set 1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:108
+msgid ""
+"The actual message entries start with the message number and followed by the "
+"localized message. The well-known modifiers from man:printf[3] are accepted:"
+msgstr ""
+"Фактические записи сообщений начинаются с номера сообщения, за которым "
+"следует локализованное сообщение. Допускаются известные модификаторы из "
+"man:printf[3]:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:112
+#, no-wrap
+msgid "15 \"File not found: %s\\n\"\n"
+msgstr "15 \"File not found: %s\\n\"\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:118
+msgid ""
+"The language catalog files have to be compiled into a binary form before "
+"they can be opened from the program. This conversion is done with the "
+"man:gencat[1] utility. Its first argument is the filename of the compiled "
+"catalog and its further arguments are the input catalogs. The localized "
+"messages can also be organized into more catalog files and then all of them "
+"can be processed with man:gencat[1]."
+msgstr ""
+"Файлы языкового каталога должны быть скомпилированы в бинарный формат перед "
+"тем, как они могут быть открыты программой. Это преобразование выполняется с "
+"помощью утилиты man:gencat[1]. Её первый аргумент — это имя файла "
+"скомпилированного каталога, а последующие аргументы — входные каталоги. "
+"Локализованные сообщения также могут быть организованы в несколько файлов "
+"каталогов, и затем все они могут быть обработаны с помощью man:gencat[1]."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:120
+#, no-wrap
+msgid "Using the Catalog Files from the Source Code"
+msgstr "Использование файлов каталога из исходного кода"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:131
+msgid ""
+"Using the catalog files is simple. To use the related functions, "
+"[.filename]#nl_types.h# must be included. Before using a catalog, it has to "
+"be opened with man:catopen[3]. The function takes two arguments. The first "
+"parameter is the name of the installed and compiled catalog. Usually, the "
+"name of the program is used, such as grep. This name will be used when "
+"looking for the compiled catalog file. The man:catopen[3] call looks for "
+"this file in [.filename]#/usr/share/nls/locale/catname# and in [.filename]#/"
+"usr/local/share/nls/locale/catname#, where `locale` is the locale set and "
+"`catname` is the catalog name being discussed. The second parameter is a "
+"constant, which can have two values:"
+msgstr ""
+"Использование файлов каталогов простое. Чтобы вызвать функции, работающие с "
+"ними, необходимо включить файл [.filename]#nl_types.h#. Перед использованием "
+"каталога его нужно открыть с помощью man:catopen[3]. Функция принимает два "
+"аргумента. Первый параметр — это имя установленного и скомпилированного "
+"каталога. Обычно используется имя программы, например, grep. Это имя будет "
+"использоваться при поиске скомпилированного файла каталога. Вызов "
+"man:catopen[3] ищет этот файл в [.filename]#/usr/share/nls/locale/catname# и "
+"в [.filename]#/usr/local/share/nls/locale/catname#, где `locale` — "
+"установленная локализация, а `catname` — имя обсуждаемого каталога. Второй "
+"параметр — это константа, которая может принимать два значения:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:133
+msgid ""
+"`NL_CAT_LOCALE`, which means that the used catalog file will be based on "
+"`LC_MESSAGES`."
+msgstr ""
+"`NL_CAT_LOCALE`, что означает, что используемый файл каталога будет основан "
+"на `LC_MESSAGES`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:134
+msgid "`0`, which means that `LANG` has to be used to open the proper catalog."
+msgstr ""
+"`0`, что означает, что для открытия соответствующего каталога необходимо "
+"использовать `LANG`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:137
+msgid ""
+"The man:catopen[3] call returns a catalog identifier of type `nl_catd`. "
+"Please refer to the manual page for a list of possible returned error codes."
+msgstr ""
+"Вызов man:catopen[3] возвращает идентификатор каталога типа `nl_catd`. "
+"Обратитесь к справочной странице для получения списка возможных кодов ошибок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:140
+msgid ""
+"After opening a catalog man:catgets[3] can be used to retrieve a message. "
+"The first parameter is the catalog identifier returned by man:catopen[3], "
+"the second one is the number of the set, the third one is the number of the "
+"messages, and the fourth one is a fallback message, which will be returned "
+"if the requested message cannot be retrieved from the catalog file."
+msgstr ""
+"После открытия каталога man:catgets[3] может быть использована для "
+"извлечения сообщения. Первый параметр — это идентификатор каталога, "
+"возвращаемый man:catopen[3], второй — номер набора, третий — номер "
+"сообщения, а четвертый — резервное сообщение, которое будет возвращено, если "
+"запрошенное сообщение не может быть извлечено из файла каталога."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:142
+msgid ""
+"After using the catalog file, it must be closed by calling man:catclose[3], "
+"which has one argument, the catalog id."
+msgstr ""
+"После использования файла каталога его необходимо закрыть, вызвав "
+"man:catclose[3], которая принимает один аргумент — идентификатор каталога."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:144
+#, no-wrap
+msgid "A Practical Example"
+msgstr "Практический пример"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:147
+msgid ""
+"The following example will demonstrate an easy solution on how to use NLS "
+"catalogs in a flexible way."
+msgstr ""
+"Следующий пример демонстрирует простое решение по гибкому использованию "
+"каталогов NLS."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:149
+msgid ""
+"The below lines need to be put into a common header file of the program, "
+"which is included into all source files where localized messages are "
+"necessary:"
+msgstr ""
+"Нижеследующие строки необходимо поместить в общий заголовочный файл "
+"программы, который включается во все исходные файлы, где необходимы "
+"локализованные сообщения:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:156
+#, no-wrap
+msgid ""
+"#ifdef WITHOUT_NLS\n"
+"#define getstr(n)\t nlsstr[n]\n"
+"#else\n"
+"#include nl_types.h\n"
+msgstr ""
+"#ifdef WITHOUT_NLS\n"
+"#define getstr(n)\t nlsstr[n]\n"
+"#else\n"
+"#include nl_types.h\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:160
+#, no-wrap
+msgid ""
+"extern nl_catd\t\t catalog;\n"
+"#define getstr(n)\t catgets(catalog, 1, n, nlsstr[n])\n"
+"#endif\n"
+msgstr ""
+"extern nl_catd\t\t catalog;\n"
+"#define getstr(n)\t catgets(catalog, 1, n, nlsstr[n])\n"
+"#endif\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:162
+#, no-wrap
+msgid "extern char\t\t*nlsstr[];\n"
+msgstr "extern char\t\t*nlsstr[];\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:165
+msgid ""
+"Next, put these lines into the global declaration part of the main source "
+"file:"
+msgstr ""
+"Далее, добавьте эти строки в глобальную секцию объявлений основного "
+"исходного файла:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:172
+#, no-wrap
+msgid ""
+"#ifndef WITHOUT_NLS\n"
+"#include nl_types.h\n"
+"nl_catd\t catalog;\n"
+"#endif\n"
+msgstr ""
+"#ifndef WITHOUT_NLS\n"
+"#include nl_types.h\n"
+"nl_catd\t catalog;\n"
+"#endif\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:182
+#, no-wrap
+msgid ""
+"/*\n"
+" * Default messages to use when NLS is disabled or no catalog\n"
+" * is found.\n"
+" */\n"
+"char *nlsstr[] = {\n"
+" \"\",\n"
+"/* 1*/ \"some random message\",\n"
+"/* 2*/ \"some other message\"\n"
+"};\n"
+msgstr ""
+"/*\n"
+" * Default messages to use when NLS is disabled or no catalog\n"
+" * is found.\n"
+" */\n"
+"char *nlsstr[] = {\n"
+" \"\",\n"
+"/* 1*/ \"some random message\",\n"
+"/* 2*/ \"some other message\"\n"
+"};\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:185
+msgid ""
+"Next come the real code snippets, which open, read, and close the catalog:"
+msgstr ""
+"Далее следуют реальные фрагменты кода, которые открывают, читают и закрывают "
+"каталог:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:191
+#, no-wrap
+msgid ""
+"#ifndef WITHOUT_NLS\n"
+"\tcatalog = catopen(\"myapp\", NL_CAT_LOCALE);\n"
+"#endif\n"
+msgstr ""
+"#ifndef WITHOUT_NLS\n"
+"\tcatalog = catopen(\"myapp\", NL_CAT_LOCALE);\n"
+"#endif\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:193
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:197
+#, no-wrap
+msgid "...\n"
+msgstr "...\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:195
+#, no-wrap
+msgid "printf(getstr(1));\n"
+msgstr "printf(getstr(1));\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:201
+#, no-wrap
+msgid ""
+"#ifndef WITHOUT_NLS\n"
+"\tcatclose(catalog);\n"
+"#endif\n"
+msgstr ""
+"#ifndef WITHOUT_NLS\n"
+"\tcatclose(catalog);\n"
+"#endif\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:203
+#, no-wrap
+msgid "Reducing Strings to Localize"
+msgstr "Уменьшение количества строк для локализации"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:207
+msgid ""
+"There is a good way of reducing the strings that need to be localized by "
+"using libc error messages. This is also useful to just avoid duplication "
+"and provide consistent error messages for the common errors that can be "
+"encountered by a great many of programs."
+msgstr ""
+"Хороший способ уменьшить количество строк, требующих локализации, — "
+"использовать сообщения об ошибках из libc. Это также полезно для избежания "
+"дублирования и обеспечения единообразия сообщений об ошибках, с которыми "
+"может столкнуться множество программ."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:209
+msgid "First, here is an example that does not use libc error messages:"
+msgstr "Вот пример, который не использует сообщения об ошибках из libc:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:216
+#, no-wrap
+msgid ""
+"#include err.h\n"
+"...\n"
+"if (!S_ISDIR(st.st_mode))\n"
+"\terrx(1, \"argument is not a directory\");\n"
+msgstr ""
+"#include err.h\n"
+"...\n"
+"if (!S_ISDIR(st.st_mode))\n"
+"\terrx(1, \"argument is not a directory\");\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:219
+msgid ""
+"This can be transformed to print an error message by reading `errno` and "
+"printing an error message accordingly:"
+msgstr ""
+"Это можно преобразовать для вывода сообщения об ошибке, считывая `errno` и "
+"выводя соответствующее сообщение об ошибке:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:229
+#, no-wrap
+msgid ""
+"#include err.h\n"
+"#include errno.h\n"
+"...\n"
+"if (!S_ISDIR(st.st_mode)) {\n"
+"\terrno = ENOTDIR;\n"
+"\terr(1, NULL);\n"
+"}\n"
+msgstr ""
+"#include err.h\n"
+"#include errno.h\n"
+"...\n"
+"if (!S_ISDIR(st.st_mode)) {\n"
+"\terrno = ENOTDIR;\n"
+"\terr(1, NULL);\n"
+"}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:234
+msgid ""
+"In this example, the custom string is eliminated, thus translators will have "
+"less work when localizing the program and users will see the usual \"Not a "
+"directory\" error message when they encounter this error. This message will "
+"probably seem more familiar to them. Please note that it was necessary to "
+"include [.filename]#errno.h# in order to directly access `errno`."
+msgstr ""
+"В этом примере пользовательская строка исключена, что упростит работу "
+"переводчиков при локализации программы, а пользователи увидят стандартное "
+"сообщение об ошибке \"Not a directory\" при возникновении данной ошибки. Это "
+"сообщение, вероятно, будет выглядеть более привычным для них. Обратите "
+"внимание, что для прямого доступа к `errno` потребовалось включить "
+"[.filename]#errno.h#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:236
+msgid ""
+"It is worth to note that there are cases when `errno` is set automatically "
+"by a preceding call, so it is not necessary to set it explicitly:"
+msgstr ""
+"Стоит отметить, что бывают случаи, когда `errno` устанавливается "
+"автоматически предыдущим вызовом, поэтому нет необходимости устанавливать "
+"его явно:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:243
+#, no-wrap
+msgid ""
+"#include err.h\n"
+"...\n"
+"if ((p = malloc(size)) == NULL)\n"
+"\terr(1, NULL);\n"
+msgstr ""
+"#include err.h\n"
+"...\n"
+"if ((p = malloc(size)) == NULL)\n"
+"\terr(1, NULL);\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:246
+#, no-wrap
+msgid "Making use of [.filename]#bsd.nls.mk#"
+msgstr "Использование [.filename]#bsd.nls.mk#"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:251
+msgid ""
+"Using the catalog files requires few repeatable steps, such as compiling the "
+"catalogs and installing them to the proper location. In order to simplify "
+"this process even more, [.filename]#bsd.nls.mk# introduces some macros. It "
+"is not necessary to include [.filename]#bsd.nls.mk# explicitly, it is pulled "
+"in from the common Makefiles, such as [.filename]#bsd.prog.mk# or "
+"[.filename]#bsd.lib.mk#."
+msgstr ""
+"Использование файлов каталогов требует нескольких повторяемых шагов, таких "
+"как компиляция каталогов и их установка в нужное место. Чтобы ещё больше "
+"упростить этот процесс, [.filename]#bsd.nls.mk# вводит некоторые макросы. "
+"Нет необходимости явно включать [.filename]#bsd.nls.mk#, он подключается "
+"автоматически из общих Makefiles, таких как [.filename]#bsd.prog.mk# или "
+"[.filename]#bsd.lib.mk#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:255
+msgid ""
+"Usually it is enough to define `NLSNAME`, which should have the catalog name "
+"mentioned as the first argument of man:catopen[3] and list the catalog files "
+"in `NLS` without their `.msg` extension. Here is an example, which makes it "
+"possible to to disable NLS when used with the code examples before. The "
+"`WITHOUT_NLS` man:make[1] variable has to be defined in order to build the "
+"program without NLS support."
+msgstr ""
+"Обычно достаточно определить `NLSNAME`, которое должно содержать имя "
+"каталога, указанное в качестве первого аргумента man:catopen[3], и "
+"перечислить файлы каталогов в `NLS` без расширения `.msg`. Вот пример, "
+"который позволяет отключить NLS при использовании с предыдущими примерами "
+"кода. Для сборки программы без поддержки NLS необходимо определить "
+"переменную `WITHOUT_NLS` man:make[1]."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:265
+#, no-wrap
+msgid ""
+".if !defined(WITHOUT_NLS)\n"
+"NLS=\tes_ES.ISO8859-1\n"
+"NLS+=\thu_HU.ISO8859-2\n"
+"NLS+=\tpt_BR.ISO8859-1\n"
+".else\n"
+"CFLAGS+=\t-DWITHOUT_NLS\n"
+".endif\n"
+msgstr ""
+".if !defined(WITHOUT_NLS)\n"
+"NLS=\tes_ES.ISO8859-1\n"
+"NLS+=\thu_HU.ISO8859-2\n"
+"NLS+=\tpt_BR.ISO8859-1\n"
+".else\n"
+"CFLAGS+=\t-DWITHOUT_NLS\n"
+".endif\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/l10n/_index.adoc:272
+msgid ""
+"Conventionally, the catalog files are placed under the [.filename]#nls# "
+"subdirectory and this is the default behavior of [.filename]#bsd.nls.mk#. "
+"It is possible, though to override the location of the catalogs with the "
+"`NLSSRCDIR` man:make[1] variable. The default name of the precompiled "
+"catalog files also follow the naming convention mentioned before. It can be "
+"overridden by setting the `NLSNAME` variable. There are other options to "
+"fine tune the processing of the catalog files but usually it is not needed, "
+"thus they are not described here. For further information on "
+"[.filename]#bsd.nls.mk#, please refer to the file itself, it is short and "
+"easy to understand."
+msgstr ""
+"Обычно файлы каталогов размещаются в подкаталоге [.filename]#nls#, и это "
+"поведение по умолчанию для [.filename]#bsd.nls.mk#. Однако можно "
+"переопределить расположение каталогов с помощью переменной `NLSSRCDIR` "
+"man:make[1]. Имя по умолчанию для предварительно скомпилированных файлов "
+"каталогов также следует упомянутому ранее соглашению об именовании. Его "
+"можно переопределить, установив переменную `NLSNAME`. Существуют и другие "
+"параметры для точной настройки обработки файлов каталогов, но обычно в этом "
+"нет необходимости, поэтому они здесь не описаны. Для получения "
+"дополнительной информации о [.filename]#bsd.nls.mk# обратитесь к самому "
+"файлу — он короткий и легко понятен."
diff --git a/documentation/content/ru/books/developers-handbook/parti.adoc b/documentation/content/ru/books/developers-handbook/parti.adoc
new file mode 100644
index 0000000000..adce578cf4
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/parti.adoc
@@ -0,0 +1,12 @@
+---
+next: books/developers-handbook/introduction
+params:
+ path: /books/developers-handbook/parti/
+prev: books/developers-handbook
+showBookMenu: true
+title: 'Часть I. Основы'
+weight: 1
+---
+
+[[basics]]
+= Основы
diff --git a/documentation/content/ru/books/developers-handbook/parti.po b/documentation/content/ru/books/developers-handbook/parti.po
new file mode 100644
index 0000000000..1b1ac9c56c
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/parti.po
@@ -0,0 +1,31 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-22 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookparti/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/parti.adoc:1
+#, no-wrap
+msgid "Part I. Basics"
+msgstr "Часть I. Основы"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/parti.adoc:12
+#, no-wrap
+msgid "Basics"
+msgstr "Основы"
diff --git a/documentation/content/ru/books/developers-handbook/partii.adoc b/documentation/content/ru/books/developers-handbook/partii.adoc
new file mode 100644
index 0000000000..90b195599b
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partii.adoc
@@ -0,0 +1,12 @@
+---
+next: books/developers-handbook/sockets
+params:
+ path: /books/developers-handbook/partii/
+prev: books/developers-handbook/testing
+showBookMenu: true
+title: 'Часть II. Межпроцессное взаимодействие'
+weight: 8
+---
+
+[[ipc]]
+= Межпроцессное взаимодействие
diff --git a/documentation/content/ru/books/developers-handbook/partii.po b/documentation/content/ru/books/developers-handbook/partii.po
new file mode 100644
index 0000000000..e6ef620442
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partii.po
@@ -0,0 +1,31 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-22 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookpartii/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/partii.adoc:1
+#, no-wrap
+msgid "Part II. Interprocess Communication"
+msgstr "Часть II. Межпроцессное взаимодействие"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/partii.adoc:12
+#, no-wrap
+msgid "Interprocess Communication"
+msgstr "Межпроцессное взаимодействие"
diff --git a/documentation/content/ru/books/developers-handbook/partiii.adoc b/documentation/content/ru/books/developers-handbook/partiii.adoc
new file mode 100644
index 0000000000..af235ae481
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partiii.adoc
@@ -0,0 +1,12 @@
+---
+next: books/developers-handbook/kernelbuild
+params:
+ path: /books/developers-handbook/partiii/
+prev: books/developers-handbook/ipv6
+showBookMenu: true
+title: 'Часть III. Ядро системы'
+weight: 11
+---
+
+[[kernel]]
+= Ядро системы
diff --git a/documentation/content/ru/books/developers-handbook/partiii.po b/documentation/content/ru/books/developers-handbook/partiii.po
new file mode 100644
index 0000000000..784ac2476a
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partiii.po
@@ -0,0 +1,31 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-12 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookpartiii/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/partiii.adoc:1
+#, no-wrap
+msgid "Part III. Kernel"
+msgstr "Часть III. Ядро системы"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/partiii.adoc:12
+#, no-wrap
+msgid "Kernel"
+msgstr "Ядро системы"
diff --git a/documentation/content/ru/books/developers-handbook/partiv.adoc b/documentation/content/ru/books/developers-handbook/partiv.adoc
new file mode 100644
index 0000000000..e97b97bcaa
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partiv.adoc
@@ -0,0 +1,12 @@
+---
+next: books/developers-handbook/x86
+params:
+ path: /books/developers-handbook/partiv/
+prev: books/developers-handbook/kerneldebug
+showBookMenu: true
+title: 'Часть IV. Архитектуры'
+weight: 14
+---
+
+[[architectures]]
+= Архитектуры
diff --git a/documentation/content/ru/books/developers-handbook/partiv.po b/documentation/content/ru/books/developers-handbook/partiv.po
new file mode 100644
index 0000000000..729cc84399
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partiv.po
@@ -0,0 +1,31 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-22 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookpartiv/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/partiv.adoc:1
+#, no-wrap
+msgid "Part IV. Architectures"
+msgstr "Часть IV. Архитектуры"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/partiv.adoc:12
+#, no-wrap
+msgid "Architectures"
+msgstr "Архитектуры"
diff --git a/documentation/content/ru/books/developers-handbook/partv.adoc b/documentation/content/ru/books/developers-handbook/partv.adoc
new file mode 100644
index 0000000000..a5f2aec1f5
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partv.adoc
@@ -0,0 +1,12 @@
+---
+next: books/developers-handbook/bibliography
+params:
+ path: /books/developers-handbook/partv/
+prev: books/developers-handbook/x86
+showBookMenu: true
+title: 'Часть V. Приложения'
+weight: 16
+---
+
+[[appendices]]
+= Приложения
diff --git a/documentation/content/ru/books/developers-handbook/partv.po b/documentation/content/ru/books/developers-handbook/partv.po
new file mode 100644
index 0000000000..1871f3f359
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/partv.po
@@ -0,0 +1,31 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-07 17:10+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookpartv/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/partv.adoc:1
+#, no-wrap
+msgid "Part V. Appendices"
+msgstr "Часть V. Приложения"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/partv.adoc:12
+#, no-wrap
+msgid "Appendices"
+msgstr "Приложения"
diff --git a/documentation/content/ru/books/developers-handbook/policies/_index.adoc b/documentation/content/ru/books/developers-handbook/policies/_index.adoc
new file mode 100644
index 0000000000..7264035d7e
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/policies/_index.adoc
@@ -0,0 +1,148 @@
+---
+authors:
+ -
+ author: 'Poul-Henning Kamp'
+ -
+ author: 'Giorgos Keramidas'
+description: 'Руководство и политика работы с деревом исходного кода'
+next: books/developers-handbook/testing
+params:
+ path: /books/developers-handbook/policies/
+prev: books/developers-handbook/l10n
+showBookMenu: true
+tags: ["Style Guidelines", "MAINTAINER", "Makefiles", "Contributed Software", "Shared libraries"]
+title: 'Глава 5. Руководство и политика работы с деревом исходного кода'
+weight: 6
+---
+
+[[policies]]
+= Руководство и политика работы с деревом исходного кода
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 5
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+Эта глава документирует различные руководства и политики, действующие для дерева исходных кодов FreeBSD.
+
+[[policies-style]]
+== Рекомендации по стилю
+
+Соблюдение единого стиля написания кода чрезвычайно важно, особенно в крупных проектах, таких как FreeBSD. Код должен соответствовать стилям программирования FreeBSD, описанным в man:style[9] и man:style.Makefile[5].
+
+[[policies-maintainer]]
+== `MAINTAINER` в Makefile-ах
+
+Если определённая часть дистрибутива FreeBSD [.filename]#src/# поддерживается человеком или группой лиц, это указывается в файле [.filename]#src/MAINTAINERS#. Сопровождающие портов в Коллекции портов указывают свою ответственность, добавляя строку `MAINTAINER` в [.filename]#Makefile# соответствующего порта:
+
+[.programlisting]
+....
+MAINTAINER= email-addresses
+....
+
+[TIP]
+====
+Для других частей репозитория или для разделов, в которых не указан сопровождающий, или если вы не уверены, кто является активным сопровождающим, попробуйте посмотреть историю последних коммитов соответствующих частей дерева исходного кода. Довольно часто сопровождающий явно не указан, но люди, которые активно работали с частью дерева исходного кода, скажем, последние пару лет, заинтересованы в проверке изменений. Даже если это не указано явно в документации или в самом исходном коде, запросить проверку из вежливости — вполне разумное действие.
+====
+
+Роль сопровождающего заключается в следующем:
+
+* Сопровождающий является владельцем и ответственным за этот код. Это означает, что он или она отвечает за исправление ошибок и решение проблем, связанных с этой частью кода, а в случае с предоставленным программным обеспечением — за отслеживание новых версий, если это необходимо.
+* Изменения в каталогах, для которых определен сопровождающий, должны быть отправлены сопровождающему на проверку и рецензирование перед коммитом. Только если сопровождающий не отвечает в течение недопустимо долгого времени на несколько писем, допустимо закоммитить изменения без его проверки. Тем не менее, рекомендуется по возможности попытаться получить рецензирование изменений у кого-нибудь ещё.
+* Конечно, недопустимо добавлять человека или группу в качестве сопровождающего, если они не согласны взять на себя эти обязанности. С другой стороны, это не обязательно должен быть один коммиттер, и это может быть и группа людей.
+
+[[policies-contributed]]
+== Стороннее программное обеспечение
+
+Некоторые части дистрибутива FreeBSD состоят из программного обеспечения, которое активно поддерживается за пределами проекта FreeBSD. По историческим причинам мы называем это _сторонним_ программным обеспечением. Некоторые примеры: LLVM, man:zlib[3] и man:awk[1].
+
+Принятая процедура управления вносимым программным обеспечением включает создание _ветки поставщика_ (_vendor branch_), где программное обеспечение может быть импортировано в чистом виде (без изменений), а обновления могут отслеживаться с учётом версий. Затем содержимое ветки поставщика применяется к дереву исходного кода, возможно, с локальными изменениями. Специфичные для FreeBSD элементы сборки поддерживаются в дереве исходного кода, а не в ветке поставщика.
+
+В зависимости от потребностей и сложности, отдельные программные проекты могут отклоняться от этой процедуры по усмотрению сопровождающего. Точные шаги, необходимые для обновления конкретного программного обеспечения, должны быть записаны в файле с именем `FREEBSD-upgrade`; например, link:https://cgit.freebsd.org/src/tree/contrib/libarchive/FREEBSD-upgrade[файл FREEBSD-upgrade libarchive].
+
+Стороннее программное обеспечение обычно размещается в подкаталоге [.filepath]#contrib/# дерева исходных кодов, за некоторыми исключениями. Стороннее программное обеспечение, используемое только ядром, находится в [.filepath]#sys/contrib/#.
+
+[NOTE]
+====
+Поскольку это затрудняет импорт будущих версий, незначительные, тривиальные и/или косметические изменения _настоятельно не рекомендуются_ для файлов, которые всё ещё отслеживают ветку поставщика.
+====
+
+[[vendor-import]]
+=== Импорт веток поставщика
+
+Стандартный процесс управления сторонним программным обеспечением и ветками поставщиков подробно описан в extref:{committers-guide}#vendor-import-git[Руководстве коммиттера].
+
+[[policies-encumbered]]
+== Файлы с правовыми ограничениями
+
+Время от времени может возникнуть необходимость включить файл с правовыми ограничениями (обремененными лицензиями, патентами) в дерево исходного кода FreeBSD. Например, если устройство требует загрузки небольшого бинарного кода перед началом работы, а у нас нет исходного кода для него, то такой бинарный файл считается обремененным. Следующие политики применяются к включению обремененных файлов в дерево исходного кода FreeBSD.
+
+. Любой файл, который интерпретируется или выполняется процессором(-ами) системы и не представлен в исходном формате, является обременённым.
+. Любой файл с лицензией более ограничительной, чем BSD или GNU, является обременённым.
+. Файл, содержащий загружаемые двоичные данные для использования оборудованием, не является обремененным, если к нему не применяется пункт (1) или (2).
+. Любой файл с правовыми ограничениями требует специального одобрения от link:https://www.FreeBSD.org/administration/#t-core[Core Team] перед добавлением в репозиторий.
+. Обремененные файлы помещаются в [.filename]#src/contrib# или [.filename]#src/sys/contrib#.
+. Весь модуль должен храниться вместе. Нет смысла разделять его, если только нет совместного использования кода с необременённой частью кода.
+. В прошлом бинарные файлы обычно кодировались с помощью uuencode и назывались [.filename]#arch/filename.o.uu#. Теперь в этом нет необходимости, и бинарные файлы могут добавляться в репозиторий без изменений.
+. Файлы ядра системы:
+.. Всегда должны быть указана в [.filename]#conf/files.*# (для упрощения сборки).
+.. Всегда должны быть в [.filename]#LINT#, но link:https://www.FreeBSD.org/administration/#t-core[Core Team] решает в каждом конкретном случае, следует ли их закомментировать или нет. link:https://www.FreeBSD.org/administration/#t-core[Core Team] может, конечно, позже изменить свое решение.
+.. _Инженер по выпуску_ решает, будет ли это включено в выпуск.
+
+. Пользовательские файлы:
+.. Команда link:https://www.FreeBSD.org/administration/#t-core[Core team] принимает решение о включении кода в базовую устанавливаемую систему.
+.. link:https://www.FreeBSD.org/administration/#t-re[Отдел разработки релизов] решает, войдет ли это в релиз.
+
+[[policies-shlib]]
+== Динамические библиотеки
+
+Если вы добавляете поддержку динамических библиотек в порт или другое программное обеспечение, у которого её нет, номера версий библиотек должны следовать этим правилам. Обычно итоговые номера не будут иметь ничего общего с версией выпуска программного обеспечения.
+
+Для портов:
+
+* Предпочитайте использовать номер, уже выбранный вышестоящим проектом
+* Если вышестоящий источник предоставляет управление версиями символов, убедитесь, что мы используем их скрипт
+
+Для базовой системы:
+
+* Начните версии библиотеки с 1
+* Настоятельно рекомендуется добавить контроль версий символов в новую библиотеку
+* Если есть несовместимое изменение, обработайте его с помощью версионирования символов, сохраняя обратную совместимость ABI
+* Если это невозможно или библиотека не использует версионирование символов, увеличьте версию библиотеки
+* Прежде чем даже рассматривать увеличение версии библиотеки для библиотеки с версионированием символов, проконсультируйтесь с командой Release Engineering, предоставив причины, почему изменение настолько важно, что его следует разрешить, несмотря на нарушение ABI
+
+Например, добавленные функции и исправления ошибок, не изменяющие интерфейсы, допустимы, тогда как удалённые функции, изменённый синтаксис вызовов и т.д. должны либо предоставлять обратно-совместимые символы, либо приведут к изменению старшего номера версии.
+
+Обязанность коммиттера, вносящего изменения, — управлять версионированием библиотек.
+
+Динамический загрузчик ELF сопоставляет имена библиотек буквально. Существует популярное соглашение, согласно которому версия библиотеки записывается в виде `libexample.so.x.y`, где x — это мажорная версия, а y — минорная. Общепринятой практикой является установка поля soname у библиотеки (тег ELF `DT_SONAME`) в `libexample.so.x`, а также создание символических ссылок `libexample.so.x->libexample.so.x.y`, `libexample.so->libexample.so.x` при установке библиотеки для последней минорной версии y. Таким образом, поскольку статический компоновщик ищет `libexample.so`, когда указана опция командной строки `-lexample`, объекты, скомпонованные с libexample, получают информацию о зависимости от правильной библиотеки. Почти все популярные системы сборки автоматически используют эту схему.
diff --git a/documentation/content/ru/books/developers-handbook/policies/_index.po b/documentation/content/ru/books/developers-handbook/policies/_index.po
new file mode 100644
index 0000000000..a5bda85033
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/policies/_index.po
@@ -0,0 +1,523 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookpolicies_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:17
+#, no-wrap
+msgid "Source Tree Guidelines and Policies"
+msgstr "Руководство и политика работы с деревом исходного кода"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:1
+#, no-wrap
+msgid "Chapter 5. Source Tree Guidelines and Policies"
+msgstr "Глава 5. Руководство и политика работы с деревом исходного кода"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:55
+msgid ""
+"This chapter documents various guidelines and policies in force for the "
+"FreeBSD source tree."
+msgstr ""
+"Эта глава документирует различные руководства и политики, действующие для "
+"дерева исходных кодов FreeBSD."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:57
+#, no-wrap
+msgid "Style Guidelines"
+msgstr "Рекомендации по стилю"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:61
+msgid ""
+"Consistent coding style is extremely important, particularly with large "
+"projects like FreeBSD. Code should follow the FreeBSD coding styles "
+"described in man:style[9] and man:style.Makefile[5]."
+msgstr ""
+"Соблюдение единого стиля написания кода чрезвычайно важно, особенно в "
+"крупных проектах, таких как FreeBSD. Код должен соответствовать стилям "
+"программирования FreeBSD, описанным в man:style[9] и man:style.Makefile[5]."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:63
+#, no-wrap
+msgid "`MAINTAINER` on Makefiles"
+msgstr "`MAINTAINER` в Makefile-ах"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:67
+msgid ""
+"If a particular portion of the FreeBSD [.filename]#src/# distribution is "
+"being maintained by a person or group of persons, this is communicated "
+"through an entry in [.filename]#src/MAINTAINERS#. Maintainers of ports "
+"within the Ports Collection express their maintainership to the world by "
+"adding a `MAINTAINER` line to the [.filename]#Makefile# of the port in "
+"question:"
+msgstr ""
+"Если определённая часть дистрибутива FreeBSD [.filename]#src/# "
+"поддерживается человеком или группой лиц, это указывается в файле "
+"[.filename]#src/MAINTAINERS#. Сопровождающие портов в Коллекции портов "
+"указывают свою ответственность, добавляя строку `MAINTAINER` в "
+"[.filename]#Makefile# соответствующего порта:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:71
+#, no-wrap
+msgid "MAINTAINER= email-addresses\n"
+msgstr "MAINTAINER= email-addresses\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:78
+msgid ""
+"For other parts of the repository, or for sections not listed as having a "
+"maintainer, or when you are unsure who the active maintainer is, try looking "
+"at the recent commit history of the relevant parts of the source tree. It "
+"is quite often the case that a maintainer is not explicitly named, but the "
+"people who are actively working in a part of the source tree for, say, the "
+"last couple of years are interested in reviewing changes. Even if this is "
+"not specifically mentioned in the documentation or the source itself, asking "
+"for a review as a form of courtesy is a very reasonable thing to do."
+msgstr ""
+"Для других частей репозитория или для разделов, в которых не указан "
+"сопровождающий, или если вы не уверены, кто является активным "
+"сопровождающим, попробуйте посмотреть историю последних коммитов "
+"соответствующих частей дерева исходного кода. Довольно часто сопровождающий "
+"явно не указан, но люди, которые активно работали с частью дерева исходного "
+"кода, скажем, последние пару лет, заинтересованы в проверке изменений. Даже "
+"если это не указано явно в документации или в самом исходном коде, запросить "
+"проверку из вежливости — вполне разумное действие."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:81
+msgid "The role of the maintainer is as follows:"
+msgstr "Роль сопровождающего заключается в следующем:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:83
+msgid ""
+"The maintainer owns and is responsible for that code. This means that he or "
+"she is responsible for fixing bugs and answering problem reports pertaining "
+"to that piece of the code, and in the case of contributed software, for "
+"tracking new versions, as appropriate."
+msgstr ""
+"Сопровождающий является владельцем и ответственным за этот код. Это "
+"означает, что он или она отвечает за исправление ошибок и решение проблем, "
+"связанных с этой частью кода, а в случае с предоставленным программным "
+"обеспечением — за отслеживание новых версий, если это необходимо."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:84
+msgid ""
+"Changes to directories which have a maintainer defined shall be sent to the "
+"maintainer for review before being committed. Only if the maintainer does "
+"not respond for an unacceptable period of time, to several emails, will it "
+"be acceptable to commit changes without review by the maintainer. However, "
+"it is suggested that you try to have the changes reviewed by someone else if "
+"at all possible."
+msgstr ""
+"Изменения в каталогах, для которых определен сопровождающий, должны быть "
+"отправлены сопровождающему на проверку и рецензирование перед коммитом. "
+"Только если сопровождающий не отвечает в течение недопустимо долгого времени "
+"на несколько писем, допустимо закоммитить изменения без его проверки. Тем не "
+"менее, рекомендуется по возможности попытаться получить рецензирование "
+"изменений у кого-нибудь ещё."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:85
+msgid ""
+"It is of course not acceptable to add a person or group as maintainer unless "
+"they agree to assume this duty. On the other hand it does not have to be a "
+"committer and it can easily be a group of people."
+msgstr ""
+"Конечно, недопустимо добавлять человека или группу в качестве "
+"сопровождающего, если они не согласны взять на себя эти обязанности. С "
+"другой стороны, это не обязательно должен быть один коммиттер, и это может "
+"быть и группа людей."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:87
+#, no-wrap
+msgid "Contributed Software"
+msgstr "Стороннее программное обеспечение"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:92
+msgid ""
+"Some parts of the FreeBSD distribution consist of software that is actively "
+"being maintained outside the FreeBSD project. For historical reasons, we "
+"call this _contributed_ software. Some examples are LLVM, man:zlib[3], and "
+"man:awk[1]."
+msgstr ""
+"Некоторые части дистрибутива FreeBSD состоят из программного обеспечения, "
+"которое активно поддерживается за пределами проекта FreeBSD. По историческим "
+"причинам мы называем это _сторонним_ программным обеспечением. Некоторые "
+"примеры: LLVM, man:zlib[3] и man:awk[1]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:96
+msgid ""
+"The accepted procedure for managing contributed software involves creating a "
+"_vendor branch_, where the software can be imported cleanly (without "
+"modification) and updates can be tracked in a versioned manner. Then, the "
+"content of the vendor branch is applied to the source tree, possibly with "
+"local modifications. FreeBSD-specific build glue is maintained in the "
+"source tree, not in the vendor branch."
+msgstr ""
+"Принятая процедура управления вносимым программным обеспечением включает "
+"создание _ветки поставщика_ (_vendor branch_), где программное обеспечение "
+"может быть импортировано в чистом виде (без изменений), а обновления могут "
+"отслеживаться с учётом версий. Затем содержимое ветки поставщика применяется "
+"к дереву исходного кода, возможно, с локальными изменениями. Специфичные для "
+"FreeBSD элементы сборки поддерживаются в дереве исходного кода, а не в ветке "
+"поставщика."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:100
+msgid ""
+"Depending on their needs and complexity, individual software projects may "
+"deviate from this procedure, at the discretion of the maintainer. The exact "
+"steps required to update a particular piece of contributed software should "
+"be recorded in a file named `FREEBSD-upgrade`; for example, link:https://"
+"cgit.freebsd.org/src/tree/contrib/libarchive/FREEBSD-upgrade[libarchive's "
+"FREEBSD-upgrade file]."
+msgstr ""
+"В зависимости от потребностей и сложности, отдельные программные проекты "
+"могут отклоняться от этой процедуры по усмотрению сопровождающего. Точные "
+"шаги, необходимые для обновления конкретного программного обеспечения, "
+"должны быть записаны в файле с именем `FREEBSD-upgrade`; например, "
+"link:https://cgit.freebsd.org/src/tree/contrib/libarchive/FREEBSD-"
+"upgrade[файл FREEBSD-upgrade libarchive]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:103
+msgid ""
+"Contributed software is usually placed in the [.filepath]#contrib/# "
+"subdirectory of the source tree, with some exceptions. Contributed software "
+"used only by the kernel lives under [.filepath]#sys/contrib/#."
+msgstr ""
+"Стороннее программное обеспечение обычно размещается в подкаталоге "
+"[.filepath]#contrib/# дерева исходных кодов, за некоторыми исключениями. "
+"Стороннее программное обеспечение, используемое только ядром, находится в "
+"[.filepath]#sys/contrib/#."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:107
+msgid ""
+"Because it makes it harder to import future versions minor, trivial and/or "
+"cosmetic changes are _strongly discouraged_ on files that are still tracking "
+"the vendor branch."
+msgstr ""
+"Поскольку это затрудняет импорт будущих версий, незначительные, тривиальные "
+"и/или косметические изменения _настоятельно не рекомендуются_ для файлов, "
+"которые всё ещё отслеживают ветку поставщика."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:110
+#, no-wrap
+msgid "Vendor Imports"
+msgstr "Импорт веток поставщика"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:113
+msgid ""
+"The standard process for managing contributed software and vendor branches "
+"is described in detail by the extref:{committers-guide}#vendor-import-"
+"git[Committer's Guide]."
+msgstr ""
+"Стандартный процесс управления сторонним программным обеспечением и ветками "
+"поставщиков подробно описан в extref:{committers-guide}#vendor-import-"
+"git[Руководстве коммиттера]."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:115
+#, no-wrap
+msgid "Encumbered Files"
+msgstr "Файлы с правовыми ограничениями"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:121
+msgid ""
+"It might occasionally be necessary to include an encumbered file in the "
+"FreeBSD source tree. For example, if a device requires a small piece of "
+"binary code to be loaded to it before the device will operate, and we do not "
+"have the source to that code, then the binary file is said to be "
+"encumbered. The following policies apply to including encumbered files in "
+"the FreeBSD source tree."
+msgstr ""
+"Время от времени может возникнуть необходимость включить файл с правовыми "
+"ограничениями (обремененными лицензиями, патентами) в дерево исходного кода "
+"FreeBSD. Например, если устройство требует загрузки небольшого бинарного "
+"кода перед началом работы, а у нас нет исходного кода для него, то такой "
+"бинарный файл считается обремененным. Следующие политики применяются к "
+"включению обремененных файлов в дерево исходного кода FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:123
+msgid ""
+"Any file which is interpreted or executed by the system CPU(s) and not in "
+"source format is encumbered."
+msgstr ""
+"Любой файл, который интерпретируется или выполняется процессором(-ами) "
+"системы и не представлен в исходном формате, является обременённым."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:124
+msgid "Any file with a license more restrictive than BSD or GNU is encumbered."
+msgstr ""
+"Любой файл с лицензией более ограничительной, чем BSD или GNU, является "
+"обременённым."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:125
+msgid ""
+"A file which contains downloadable binary data for use by the hardware is "
+"not encumbered, unless (1) or (2) apply to it."
+msgstr ""
+"Файл, содержащий загружаемые двоичные данные для использования "
+"оборудованием, не является обремененным, если к нему не применяется пункт "
+"(1) или (2)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:126
+msgid ""
+"Any encumbered file requires specific approval from the link:https://"
+"www.FreeBSD.org/administration/#t-core[Core Team] before it is added to the "
+"repository."
+msgstr ""
+"Любой файл с правовыми ограничениями требует специального одобрения от "
+"link:https://www.FreeBSD.org/administration/#t-core[Core Team] перед "
+"добавлением в репозиторий."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:127
+msgid ""
+"Encumbered files go in [.filename]#src/contrib# or [.filename]#src/sys/"
+"contrib#."
+msgstr ""
+"Обремененные файлы помещаются в [.filename]#src/contrib# или [.filename]#src/"
+"sys/contrib#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:128
+msgid ""
+"The entire module should be kept together. There is no point in splitting "
+"it, unless there is code-sharing with non-encumbered code."
+msgstr ""
+"Весь модуль должен храниться вместе. Нет смысла разделять его, если только "
+"нет совместного использования кода с необременённой частью кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:130
+msgid ""
+"In the past binary files were typically uuencoded, and named "
+"[.filename]#arch/filename.o.uu#. This is no longer necessary, and binary "
+"files may be added to the repository unchanged."
+msgstr ""
+"В прошлом бинарные файлы обычно кодировались с помощью uuencode и назывались "
+"[.filename]#arch/filename.o.uu#. Теперь в этом нет необходимости, и бинарные "
+"файлы могут добавляться в репозиторий без изменений."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:131
+msgid "Kernel files:"
+msgstr "Файлы ядра системы:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:132
+msgid ""
+"Should always be referenced in [.filename]#conf/files.*# (for build "
+"simplicity)."
+msgstr ""
+"Всегда должны быть указана в [.filename]#conf/files.*# (для упрощения "
+"сборки)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:133
+msgid ""
+"Should always be in [.filename]#LINT#, but the link:https://www.FreeBSD.org/"
+"administration/#t-core[Core Team] decides per case if it should be commented "
+"out or not. The link:https://www.FreeBSD.org/administration/#t-core[Core "
+"Team] can, of course, change their minds later on."
+msgstr ""
+"Всегда должны быть в [.filename]#LINT#, но link:https://www.FreeBSD.org/"
+"administration/#t-core[Core Team] решает в каждом конкретном случае, следует "
+"ли их закомментировать или нет. link:https://www.FreeBSD.org/administration/"
+"#t-core[Core Team] может, конечно, позже изменить свое решение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:134
+msgid "The _Release Engineer_ decides whether or not it goes into the release."
+msgstr "_Инженер по выпуску_ решает, будет ли это включено в выпуск."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:136
+msgid "User-land files:"
+msgstr "Пользовательские файлы:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:137
+msgid ""
+"The link:https://www.FreeBSD.org/administration/#t-core[Core team] decides "
+"if the code should be part of the installed base system."
+msgstr ""
+"Команда link:https://www.FreeBSD.org/administration/#t-core[Core team] "
+"принимает решение о включении кода в базовую устанавливаемую систему."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:138
+msgid ""
+"The link:https://www.FreeBSD.org/administration/#t-re[Release Engineering] "
+"decides if it goes into the release."
+msgstr ""
+"link:https://www.FreeBSD.org/administration/#t-re[Отдел разработки релизов] "
+"решает, войдет ли это в релиз."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:140
+#, no-wrap
+msgid "Shared Libraries"
+msgstr "Динамические библиотеки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:144
+msgid ""
+"If you are adding shared library support to a port or other piece of "
+"software that does not have one, the version numbers should follow these "
+"rules. Generally, the resulting numbers will have nothing to do with the "
+"release version of the software."
+msgstr ""
+"Если вы добавляете поддержку динамических библиотек в порт или другое "
+"программное обеспечение, у которого её нет, номера версий библиотек должны "
+"следовать этим правилам. Обычно итоговые номера не будут иметь ничего общего "
+"с версией выпуска программного обеспечения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:146
+msgid "For ports:"
+msgstr "Для портов:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:148
+msgid "Prefer using the number already selected by upstream"
+msgstr "Предпочитайте использовать номер, уже выбранный вышестоящим проектом"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:149
+msgid "If upstream provides symbol versioning, ensure that we use their script"
+msgstr ""
+"Если вышестоящий источник предоставляет управление версиями символов, "
+"убедитесь, что мы используем их скрипт"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:151
+msgid "For the base system:"
+msgstr "Для базовой системы:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:153
+msgid "Start library version from 1"
+msgstr "Начните версии библиотеки с 1"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:154
+msgid "It is strongly recommended to add symbol versioning to the new library"
+msgstr ""
+"Настоятельно рекомендуется добавить контроль версий символов в новую "
+"библиотеку"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:155
+msgid ""
+"If there is an incompatible change, handle it with symbol versioning, "
+"maintaining backward ABI compatibility"
+msgstr ""
+"Если есть несовместимое изменение, обработайте его с помощью версионирования "
+"символов, сохраняя обратную совместимость ABI"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:156
+msgid ""
+"If this is impossible, or the library does not use symbol versioning, bump "
+"the library version"
+msgstr ""
+"Если это невозможно или библиотека не использует версионирование символов, "
+"увеличьте версию библиотеки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:157
+msgid ""
+"Before even considering bumping library version for symbol-versioned "
+"library, consult with Release Engineering team, providing reasons why the "
+"change is so important that it should be allowed despite breaking the ABI"
+msgstr ""
+"Прежде чем даже рассматривать увеличение версии библиотеки для библиотеки с "
+"версионированием символов, проконсультируйтесь с командой Release "
+"Engineering, предоставив причины, почему изменение настолько важно, что его "
+"следует разрешить, несмотря на нарушение ABI"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:159
+msgid ""
+"For instance, added functions and bugfixes not changing the interfaces are "
+"fine, while deleted functions, changed function call syntax, etc. should "
+"either provide backward-compat symbols, or will force the major version "
+"number to change."
+msgstr ""
+"Например, добавленные функции и исправления ошибок, не изменяющие "
+"интерфейсы, допустимы, тогда как удалённые функции, изменённый синтаксис "
+"вызовов и т.д. должны либо предоставлять обратно-совместимые символы, либо "
+"приведут к изменению старшего номера версии."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:161
+msgid ""
+"It is the duty of the committer making the change to handle library "
+"versioning."
+msgstr ""
+"Обязанность коммиттера, вносящего изменения, — управлять версионированием "
+"библиотек."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/policies/_index.adoc:166
+msgid ""
+"The ELF dynamic linker matches library names literally. There is a popular "
+"convention where library version is written in the form `libexample.so.x.y`, "
+"where x is the major version, and y is minor. Common practice is to set the "
+"library' soname (`DT_SONAME` ELF tag) to `libexample.so.x`, and set up "
+"symlinks `libexample.so.x->libexample.so.x.y`, `libexample.so-"
+">libexample.so.x` on library installation for the latest minor version y. "
+"Then, since the static linker searches for `libexample.so` when the `-"
+"lexample` command line option is specified, objects linked with libexample "
+"get a dependency on the right library. Almost all popular build systems use "
+"this scheme automatically."
+msgstr ""
+"Динамический загрузчик ELF сопоставляет имена библиотек буквально. "
+"Существует популярное соглашение, согласно которому версия библиотеки "
+"записывается в виде `libexample.so.x.y`, где x — это мажорная версия, а y — "
+"минорная. Общепринятой практикой является установка поля soname у библиотеки "
+"(тег ELF `DT_SONAME`) в `libexample.so.x`, а также создание символических "
+"ссылок `libexample.so.x->libexample.so.x.y`, `libexample.so-"
+">libexample.so.x` при установке библиотеки для последней минорной версии y. "
+"Таким образом, поскольку статический компоновщик ищет `libexample.so`, когда "
+"указана опция командной строки `-lexample`, объекты, скомпонованные с "
+"libexample, получают информацию о зависимости от правильной библиотеки. "
+"Почти все популярные системы сборки автоматически используют эту схему."
diff --git a/documentation/content/ru/books/developers-handbook/secure/_index.adoc b/documentation/content/ru/books/developers-handbook/secure/_index.adoc
new file mode 100644
index 0000000000..1631ee018b
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/secure/_index.adoc
@@ -0,0 +1,230 @@
+---
+authors:
+ -
+ author: 'Murray Stokely'
+description: 'Безопасное программирование в FreeBSD'
+next: books/developers-handbook/l10n
+params:
+ path: /books/developers-handbook/secure/
+prev: books/developers-handbook/tools
+showBookMenu: true
+tags: ["secure programming", "Buffer Overflows", "SetUID issues"]
+title: 'Глава 3. Безопасное программирование'
+weight: 4
+---
+
+[[secure]]
+= Безопасное программирование
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 3
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[secure-synopsis]]
+== Обзор
+
+В этой главе описываются некоторые проблемы безопасности, которые преследуют программистов UNIX(R) на протяжении десятилетий, а также новые инструменты, помогающие избежать написания уязвимого кода.
+
+[[secure-philosophy]]
+== Методология безопасного проектирования
+
+Написание безопасных приложений требует очень внимательного и пессимистичного взгляда на жизнь. Приложения должны работать по принципу "наименьших привилегий", чтобы ни один процесс не выполнялся с доступом, превышающим необходимый минимум для выполнения его функций. По возможности следует повторно использовать уже проверенный код, чтобы избежать распространённых ошибок, которые, возможно, уже исправили другие.
+
+Одной из ловушек среды UNIX(R) является то, насколько легко делать предположения о разумности окружения. Приложения никогда не должны доверять пользовательскому вводу (во всех его формах), системным ресурсам, межпроцессному взаимодействию или времени событий. Процессы UNIX(R) выполняются не синхронно, поэтому логические операции редко бывают атомарными.
+
+[[secure-bufferov]]
+== Переполнение буфера
+
+Переполнение буфера существовало с самых истоков архитектуры фон Неймана crossref:bibliography[cod,1]. Впервые оно получило широкую известность в 1988 году благодаря червю Морриса. К сожалению, эта базовая атака остаётся эффективной и по сей день. Наиболее распространённый тип атаки с переполнением буфера основан на повреждении стека.
+
+Большинство современных компьютерных систем используют стек для передачи аргументов процедурам и хранения локальных переменных. Стек — это буфер типа "последним пришёл — первым ушёл" (LIFO) в верхней области памяти процесса. Когда программа вызывает функцию, создаётся новый "стековый кадр". Этот стековый кадр состоит из аргументов, переданных функции, а также динамического количества места для локальных переменных. "Указатель стека" — это регистр, который содержит текущее местоположение вершины стека. Поскольку это значение постоянно меняется по мере добавления новых значений на вершину стека, многие реализации также предоставляют "указатель кадра", который располагается вблизи начала стекового кадра, чтобы локальные переменные могли легче адресоваться относительно этого значения. crossref:bibliography[cod,1] Адрес возврата для вызовов функций также хранится в стеке, и это является причиной эксплойтов переполнения стека, поскольку переполнение локальной переменной в функции может перезаписать адрес возврата этой функции, потенциально позволяя злоумышленнику выполнить любой код по своему усмотрению.
+
+Хотя атаки на стек являются наиболее распространенными, также возможно переполнение стека с помощью атаки на кучу (malloc/free).
+
+Язык программирования C не выполняет автоматическую проверку границ массивов или указателей, как это делают многие другие языки. Кроме того, стандартная библиотека C содержит множество очень опасных функций.
+
+[.informaltable]
+[cols="1,1", frame="none"]
+|===
+
+|`strcpy`(char *dest, const char *src)
+|
+
+Может переполнить буфер назначения
+
+|`strcat`(char *dest, const char *src)
+|
+
+Может переполнить буфер назначения
+
+|`getwd`(char *buf)
+|
+
+Может переполнить буфер buf
+
+|`gets`(char *s)
+|
+
+Может переполнить буфер s
+
+|`[vf]scanf`(const char *format, ...)
+|
+
+Может переполнить свои аргументы.
+
+|`realpath`(char *path, char resolved_path[])
+|
+
+Может переполнить буфер пути
+
+|`[v]sprintf`(char *str, const char *format, ...)
+|
+
+Может переполнить буфер str.
+|===
+
+=== Пример переполнения буфера
+
+Следующий пример кода содержит переполнение буфера, предназначенное для перезаписи адреса возврата и пропуска инструкции, следующей сразу после вызова функции. (Вдохновлено crossref:bibliography[Phrack,4])
+
+[.programlisting]
+....
+#include <stdio.h>
+
+void manipulate(char *buffer) {
+ char newbuffer[80];
+ strcpy(newbuffer,buffer);
+}
+
+int main() {
+ char ch,buffer[4096];
+ int i=0;
+
+ while ((buffer[i++] = getchar()) != '\n') {};
+
+ i=1;
+ manipulate(buffer);
+ i=2;
+ printf("The value of i is : %d\n",i);
+ return 0;
+}
+....
+
+Давайте рассмотрим, как будет выглядеть образ памяти этого процесса, если мы введем 160 пробелов в нашу небольшую программу перед нажатием Enter.
+
+[XXX figure here!]
+
+Очевидно, что можно разработать более вредоносные входные данные для выполнения реальных скомпилированных инструкций (например, exec(/bin/sh)).
+
+=== Избегание переполнения буфера
+
+Наиболее простое решение проблемы переполнения стека — всегда использовать функции копирования памяти и строк с ограничением длины. `strncpy` и `strncat` являются частью стандартной библиотеки C. Эти функции принимают параметр длины, который не должен превышать размер целевого буфера. Затем эти функции копируют до 'length' байтов из источника в назначение. Однако у этих функций есть ряд проблем. Ни одна из них не гарантирует завершающий NUL, если размер входного буфера равен размеру целевого. Параметр длины также используется неодинаково между `strncpy` и `strncat`, что может сбивать программистов с толку относительно их правильного использования. Также наблюдается значительное снижение производительности по сравнению с `strcpy` при копировании короткой строки в большой буфер, поскольку `strncpy` заполняет оставшееся пространство до указанного размера символами NUL.
+
+Существует другая реализация копирования памяти для решения этих проблем. Функции `strlcpy` и `strlcat` гарантируют, что они всегда завершат строку назначения нулевым символом при передаче аргумента ненулевой длины.
+
+==== Скомпилированная проверка границ во время выполнения
+
+К сожалению, до сих пор существует очень большое количество кода в открытом доступе, который бездумно копирует память, не используя ни одну из ограниченных функций копирования, которые мы только что обсудили. К счастью, есть способ помочь предотвратить такие атаки — проверка границ во время выполнения, которая реализована в нескольких компиляторах C/C++.
+
+ProPolice — это одна из таких функций компилятора, интегрированная в man:gcc[1] версий 4.1 и выше. Она заменяет и расширяет более раннее расширение StackGuard для man:gcc[1].
+
+ProPolice помогает защититься от переполнений буфера на стеке и других атак, размещая псевдослучайные числа в ключевых областях стека перед вызовом любой функции. Когда функция завершается, эти "канарейки" проверяются, и если обнаруживается, что они были изменены, выполнение программы немедленно прекращается. Таким образом, любая попытка изменить адрес возврата или другие переменные, хранящиеся на стеке, с целью запуска вредоносного кода, вряд ли увенчается успехом, так как злоумышленнику также необходимо оставить псевдослучайные канарейки нетронутыми.
+
+Перекомпиляция вашего приложения с использованием ProPolice является эффективным способом предотвращения большинства атак, связанных с переполнением буфера, но оно всё ещё может быть скомпрометировано.
+
+==== Библиотечная проверка границ во время выполнения
+
+Механизмы на основе компилятора совершенно бесполезны для проприетарного программного обеспечения, которое невозможно перекомпилировать. Для таких ситуаций существует ряд библиотек, которые переопределяют небезопасные функции стандартной библиотеки C (`strcpy`, `fscanf`, `getwd` и т.д.) и гарантируют, что эти функции никогда не смогут записать данные за указатель стека.
+
+* libsafe
+* libverify
+* libparanoia
+
+К сожалению, эти защиты на основе библиотек имеют ряд недостатков. Они защищают лишь от очень небольшого набора проблем, связанных с безопасностью, и не устраняют основную причину. Эти защиты могут не сработать, если приложение было скомпилировано с флагом -fomit-frame-pointer. Кроме того, переменные окружения LD_PRELOAD и LD_LIBRARY_PATH могут быть перезаписаны или сброшены пользователем.
+
+[[secure-setuid]]
+== Проблемы с SetUID
+
+Существует как минимум 6 различных идентификаторов, связанных с каждым процессом, поэтому необходимо очень внимательно следить за уровнем доступа вашего процесса в любой момент времени. В частности, все приложения с seteuid должны отказываться от своих привилегий, как только в них больше нет необходимости.
+
+Действительный идентификатор пользователя может быть изменён только процессом с правами суперпользователя. Программа login устанавливает его при первоначальном входе пользователя в систему, и он редко изменяется.
+
+Эффективный идентификатор пользователя устанавливается функциями `exec()`, если у программы установлен бит seteuid. Приложение может вызывать `seteuid()` в любое время, чтобы установить эффективный идентификатор пользователя либо в реальный идентификатор пользователя, либо в сохранённый set-user-ID. Когда эффективный идентификатор пользователя устанавливается функциями `exec()`, предыдущее значение сохраняется в сохранённом set-user-ID.
+
+[[secure-chroot]]
+== Ограничение окружения вашей программы
+
+Традиционный метод ограничения процесса — это системный вызов `chroot()`. Этот системный вызов изменяет корневой каталог, от которого ссылаются все остальные пути для процесса и любых дочерних процессов. Для успешного выполнения этого вызова процесс должен иметь право на выполнение (поиск) в указанном каталоге. Новая среда фактически не вступает в силу, пока вы не выполните `chdir()` в новой среде. Также следует отметить, что процесс может легко выйти из окружения chroot, если он имеет привилегии root. Это может быть достигнуто путем создания узлов устройств для чтения памяти ядра, подключения отладчика к процессу вне окружения man:chroot[8] или многими другими творческими способами.
+
+Поведение системного вызова `chroot()` можно частично контролировать с помощью переменной `sysctl` kern.chroot_allow_open_directories. Если этому параметру присвоено значение 0, `chroot()` завершится с ошибкой EPERM, если есть какие-либо открытые каталоги. Если установлено значение по умолчанию 1, то `chroot()` завершится с ошибкой EPERM, если есть открытые каталоги и процесс уже находится внутри вызова `chroot()`. Для любого другого значения проверка на открытые каталоги будет полностью пропущена.
+
+=== Функциональность клеток FreeBSD
+
+Концепция `клетки` расширяет возможности `chroot()`, ограничивая права суперпользователя для создания настоящего `виртуального сервера`. После настройки клетки все сетевые взаимодействия должны осуществляться через указанный IP-адрес, а привилегии `root` внутри этой клетки сильно ограничены.
+
+Находясь в клетке, любые проверки прав суперпользователя в ядре с использованием вызова `suser()` завершатся неудачей. Однако некоторые вызовы `suser()` были заменены на новый интерфейс `suser_xxx()`. Эта функция отвечает за распознавание или запрет доступа к правам суперпользователя для процессов в клетке.
+
+Суперпользователь в среде клетки имеет возможность:
+
+* Управлять учетными данными с помощью `setuid`, `seteuid`, `setgid`, `setegid`, `setgroups`, `setreuid`, `setregid`, `setlogin`
+* Установливать ограничений ресурсов с помощью `setrlimit`
+* Изменять некоторые узлы sysctl (kern.hostname)
+* `chroot()`
+* Устанавливать флаги на vnode: `chflags`, `fchflags`
+* Устанавливать атрибуты vnode, такие как права доступа к файлу, владелец, группа, размер, время доступа и время изменения.
+* Привязываться к привилегированным портам в домене Интернета (порты < 1024)
+
+`Клетка` — это очень полезный инструмент для запуска приложений в безопасной среде, но у него есть некоторые недостатки. В настоящее время механизмы IPC не были преобразованы в `suser_xxx`, поэтому такие приложения, как MySQL, не могут быть запущены внутри клетки. Доступ суперпользователя может иметь очень ограниченное значение внутри клетки, но нет возможности точно указать, что означает «очень ограниченный».
+
+=== Возможности процесса в POSIX(R).1e
+
+POSIX(R) выпустил рабочий проект, который добавляет аудит событий, списки контроля доступа, детализированные привилегии, маркировку информации и обязательный контроль доступа.
+
+Это работа в процессе, и она является основным направлением проекта http://www.trustedbsd.org/[TrustedBSD]. Некоторые первоначальные наработки были добавлены в FreeBSD-CURRENT (cap_set_proc(3)).
+
+[[secure-trust]]
+== Доверие
+
+Приложение никогда не должно предполагать, что окружение пользователя является предсказуемым. Это включает (но не ограничивается): пользовательский ввод, сигналы, переменные окружения, ресурсы, IPC, mmaps, текущую рабочую директорию файловой системы, файловые дескрипторы, количество открытых файлов и т.д.
+
+Никогда не следует предполагать, что можно отловить все виды некорректных входных данных, которые может предоставить пользователь. Вместо этого ваше приложение должно использовать позитивную фильтрацию, разрешая только определённое подмножество входных данных, которые вы считаете безопасными. Некорректная проверка данных стала причиной многих уязвимостей, особенно в CGI-скриптах во всемирной паутине. Для имён файлов необходимо быть особенно осторожными с путями ("../", "/"), символическими ссылками и escape-символами оболочки.
+
+В Perl есть замечательная функция под названием "Режим Taint", которая может использоваться для предотвращения небезопасного использования данных, полученных извне программы. Этот режим проверяет аргументы командной строки, переменные окружения, информацию о локали, результаты определённых системных вызовов (`readdir()`, `readlink()`, `getpwxxx()`) и все вводимые данные из файлов.
+
+[[secure-race-conditions]]
+== Состояние гонки
+
+Состояние гонки — это аномальное поведение, вызванное непредвиденной зависимостью от относительного времени событий. Другими словами, программист ошибочно предположил, что определенное событие всегда произойдет раньше другого.
+
+Некоторые из распространённых причин состояний гонки — это сигналы, проверки доступа и открытие файлов. Сигналы по своей природе являются асинхронными событиями, поэтому при работе с ними необходимо проявлять особую осторожность. Проверка доступа с помощью `access(2)`, а затем `open(2)` явно неатомарна. Пользователи могут перемещать файлы между этими двумя вызовами. Вместо этого привилегированные приложения должны использовать `seteuid()`, а затем вызывать `open()` напрямую. По аналогии, приложение всегда должно устанавливать правильную маску (`umask`) перед вызовом `open()`, чтобы избежать необходимости в лишних вызовах `chmod()`.
diff --git a/documentation/content/ru/books/developers-handbook/secure/_index.po b/documentation/content/ru/books/developers-handbook/secure/_index.po
new file mode 100644
index 0000000000..c2900d4b7a
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/secure/_index.po
@@ -0,0 +1,824 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbooksecure_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:1
+#, no-wrap
+msgid "Secure Programming in FreeBSD"
+msgstr "Безопасное программирование в FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:1
+#, no-wrap
+msgid "Chapter 3. Secure Programming"
+msgstr "Глава 3. Безопасное программирование"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:16
+#, no-wrap
+msgid "Secure Programming"
+msgstr "Безопасное программирование"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:54
+#, no-wrap
+msgid "Synopsis"
+msgstr "Обзор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:57
+msgid ""
+"This chapter describes some of the security issues that have plagued UNIX(R) "
+"programmers for decades and some of the new tools available to help "
+"programmers avoid writing exploitable code."
+msgstr ""
+"В этой главе описываются некоторые проблемы безопасности, которые преследуют "
+"программистов UNIX(R) на протяжении десятилетий, а также новые инструменты, "
+"помогающие избежать написания уязвимого кода."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:59
+#, no-wrap
+msgid "Secure Design Methodology"
+msgstr "Методология безопасного проектирования"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:64
+msgid ""
+"Writing secure applications takes a very scrutinous and pessimistic outlook "
+"on life. Applications should be run with the principle of \"least "
+"privilege\" so that no process is ever running with more than the bare "
+"minimum access that it needs to accomplish its function. Previously tested "
+"code should be reused whenever possible to avoid common mistakes that others "
+"may have already fixed."
+msgstr ""
+"Написание безопасных приложений требует очень внимательного и "
+"пессимистичного взгляда на жизнь. Приложения должны работать по принципу "
+"\"наименьших привилегий\", чтобы ни один процесс не выполнялся с доступом, "
+"превышающим необходимый минимум для выполнения его функций. По возможности "
+"следует повторно использовать уже проверенный код, чтобы избежать "
+"распространённых ошибок, которые, возможно, уже исправили другие."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:68
+msgid ""
+"One of the pitfalls of the UNIX(R) environment is how easy it is to make "
+"assumptions about the sanity of the environment. Applications should never "
+"trust user input (in all its forms), system resources, inter-process "
+"communication, or the timing of events. UNIX(R) processes do not execute "
+"synchronously so logical operations are rarely atomic."
+msgstr ""
+"Одной из ловушек среды UNIX(R) является то, насколько легко делать "
+"предположения о разумности окружения. Приложения никогда не должны доверять "
+"пользовательскому вводу (во всех его формах), системным ресурсам, "
+"межпроцессному взаимодействию или времени событий. Процессы UNIX(R) "
+"выполняются не синхронно, поэтому логические операции редко бывают "
+"атомарными."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:70
+#, no-wrap
+msgid "Buffer Overflows"
+msgstr "Переполнение буфера"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:76
+msgid ""
+"Buffer Overflows have been around since the very beginnings of the von "
+"Neumann crossref:bibliography[cod,1] architecture. They first gained "
+"widespread notoriety in 1988 with the Morris Internet worm. Unfortunately, "
+"the same basic attack remains effective today. By far the most common type "
+"of buffer overflow attack is based on corrupting the stack."
+msgstr ""
+"Переполнение буфера существовало с самых истоков архитектуры фон Неймана "
+"crossref:bibliography[cod,1]. Впервые оно получило широкую известность в "
+"1988 году благодаря червю Морриса. К сожалению, эта базовая атака остаётся "
+"эффективной и по сей день. Наиболее распространённый тип атаки с "
+"переполнением буфера основан на повреждении стека."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:85
+msgid ""
+"Most modern computer systems use a stack to pass arguments to procedures and "
+"to store local variables. A stack is a last in first out (LIFO) buffer in "
+"the high memory area of a process image. When a program invokes a function "
+"a new \"stack frame\" is created. This stack frame consists of the "
+"arguments passed to the function as well as a dynamic amount of local "
+"variable space. The \"stack pointer\" is a register that holds the current "
+"location of the top of the stack. Since this value is constantly changing "
+"as new values are pushed onto the top of the stack, many implementations "
+"also provide a \"frame pointer\" that is located near the beginning of a "
+"stack frame so that local variables can more easily be addressed relative to "
+"this value. crossref:bibliography[cod,1] The return address for function "
+"calls is also stored on the stack, and this is the cause of stack-overflow "
+"exploits since overflowing a local variable in a function can overwrite the "
+"return address of that function, potentially allowing a malicious user to "
+"execute any code he or she wants."
+msgstr ""
+"Большинство современных компьютерных систем используют стек для передачи "
+"аргументов процедурам и хранения локальных переменных. Стек — это буфер типа "
+"\"последним пришёл — первым ушёл\" (LIFO) в верхней области памяти процесса. "
+"Когда программа вызывает функцию, создаётся новый \"стековый кадр\". Этот "
+"стековый кадр состоит из аргументов, переданных функции, а также "
+"динамического количества места для локальных переменных. \"Указатель стека\" "
+"— это регистр, который содержит текущее местоположение вершины стека. "
+"Поскольку это значение постоянно меняется по мере добавления новых значений "
+"на вершину стека, многие реализации также предоставляют \"указатель кадра\", "
+"который располагается вблизи начала стекового кадра, чтобы локальные "
+"переменные могли легче адресоваться относительно этого значения. "
+"crossref:bibliography[cod,1] Адрес возврата для вызовов функций также "
+"хранится в стеке, и это является причиной эксплойтов переполнения стека, "
+"поскольку переполнение локальной переменной в функции может перезаписать "
+"адрес возврата этой функции, потенциально позволяя злоумышленнику выполнить "
+"любой код по своему усмотрению."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:88
+msgid ""
+"Although stack-based attacks are by far the most common, it would also be "
+"possible to overrun the stack with a heap-based (malloc/free) attack."
+msgstr ""
+"Хотя атаки на стек являются наиболее распространенными, также возможно "
+"переполнение стека с помощью атаки на кучу (malloc/free)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:91
+msgid ""
+"The C programming language does not perform automatic bounds checking on "
+"arrays or pointers as many other languages do. In addition, the standard C "
+"library is filled with a handful of very dangerous functions."
+msgstr ""
+"Язык программирования C не выполняет автоматическую проверку границ массивов "
+"или указателей, как это делают многие другие языки. Кроме того, стандартная "
+"библиотека C содержит множество очень опасных функций."
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:97
+#, no-wrap
+msgid "`strcpy`(char *dest, const char *src)"
+msgstr "`strcpy`(char *dest, const char *src)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:101
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:106
+#, no-wrap
+msgid "May overflow the dest buffer"
+msgstr "Может переполнить буфер назначения"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:102
+#, no-wrap
+msgid "`strcat`(char *dest, const char *src)"
+msgstr "`strcat`(char *dest, const char *src)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:107
+#, no-wrap
+msgid "`getwd`(char *buf)"
+msgstr "`getwd`(char *buf)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:111
+#, no-wrap
+msgid "May overflow the buf buffer"
+msgstr "Может переполнить буфер buf"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:112
+#, no-wrap
+msgid "`gets`(char *s)"
+msgstr "`gets`(char *s)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:116
+#, no-wrap
+msgid "May overflow the s buffer"
+msgstr "Может переполнить буфер s"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:117
+#, no-wrap
+msgid "`[vf]scanf`(const char *format, ...)"
+msgstr "`[vf]scanf`(const char *format, ...)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:121
+#, no-wrap
+msgid "May overflow its arguments."
+msgstr "Может переполнить свои аргументы."
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:122
+#, no-wrap
+msgid "`realpath`(char *path, char resolved_path[])"
+msgstr "`realpath`(char *path, char resolved_path[])"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:126
+#, no-wrap
+msgid "May overflow the path buffer"
+msgstr "Может переполнить буфер пути"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:127
+#, no-wrap
+msgid "`[v]sprintf`(char *str, const char *format, ...)"
+msgstr "`[v]sprintf`(char *str, const char *format, ...)"
+
+#. type: Table
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:130
+#, no-wrap
+msgid "May overflow the str buffer."
+msgstr "Может переполнить буфер str."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:132
+#, no-wrap
+msgid "Example Buffer Overflow"
+msgstr "Пример переполнения буфера"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:135
+msgid ""
+"The following example code contains a buffer overflow designed to overwrite "
+"the return address and skip the instruction immediately following the "
+"function call. (Inspired by crossref:bibliography[Phrack,4])"
+msgstr ""
+"Следующий пример кода содержит переполнение буфера, предназначенное для "
+"перезаписи адреса возврата и пропуска инструкции, следующей сразу после "
+"вызова функции. (Вдохновлено crossref:bibliography[Phrack,4])"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:139
+#, no-wrap
+msgid "#include <stdio.h>\n"
+msgstr "#include <stdio.h>\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:144
+#, no-wrap
+msgid ""
+"void manipulate(char *buffer) {\n"
+" char newbuffer[80];\n"
+" strcpy(newbuffer,buffer);\n"
+"}\n"
+msgstr ""
+"void manipulate(char *buffer) {\n"
+" char newbuffer[80];\n"
+" strcpy(newbuffer,buffer);\n"
+"}\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:148
+#, no-wrap
+msgid ""
+"int main() {\n"
+" char ch,buffer[4096];\n"
+" int i=0;\n"
+msgstr ""
+"int main() {\n"
+" char ch,buffer[4096];\n"
+" int i=0;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:150
+#, no-wrap
+msgid " while ((buffer[i++] = getchar()) != '\\n') {};\n"
+msgstr " while ((buffer[i++] = getchar()) != '\\n') {};\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:157
+#, no-wrap
+msgid ""
+" i=1;\n"
+" manipulate(buffer);\n"
+" i=2;\n"
+" printf(\"The value of i is : %d\\n\",i);\n"
+" return 0;\n"
+"}\n"
+msgstr ""
+" i=1;\n"
+" manipulate(buffer);\n"
+" i=2;\n"
+" printf(\"The value of i is : %d\\n\",i);\n"
+" return 0;\n"
+"}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:160
+msgid ""
+"Let us examine what the memory image of this process would look like if we "
+"were to input 160 spaces into our little program before hitting return."
+msgstr ""
+"Давайте рассмотрим, как будет выглядеть образ памяти этого процесса, если мы "
+"введем 160 пробелов в нашу небольшую программу перед нажатием Enter."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:164
+msgid ""
+"Obviously more malicious input can be devised to execute actual compiled "
+"instructions (such as exec(/bin/sh))."
+msgstr ""
+"Очевидно, что можно разработать более вредоносные входные данные для "
+"выполнения реальных скомпилированных инструкций (например, exec(/bin/sh))."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:165
+#, no-wrap
+msgid "Avoiding Buffer Overflows"
+msgstr "Избегание переполнения буфера"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:175
+msgid ""
+"The most straightforward solution to the problem of stack-overflows is to "
+"always use length restricted memory and string copy functions. `strncpy` "
+"and `strncat` are part of the standard C library. These functions accept a "
+"length value as a parameter which should be no larger than the size of the "
+"destination buffer. These functions will then copy up to 'length' bytes "
+"from the source to the destination. However there are a number of problems "
+"with these functions. Neither function guarantees NUL termination if the "
+"size of the input buffer is as large as the destination. The length "
+"parameter is also used inconsistently between strncpy and strncat so it is "
+"easy for programmers to get confused as to their proper usage. There is "
+"also a significant performance loss compared to `strcpy` when copying a "
+"short string into a large buffer since `strncpy` NUL fills up the size "
+"specified."
+msgstr ""
+"Наиболее простое решение проблемы переполнения стека — всегда использовать "
+"функции копирования памяти и строк с ограничением длины. `strncpy` и "
+"`strncat` являются частью стандартной библиотеки C. Эти функции принимают "
+"параметр длины, который не должен превышать размер целевого буфера. Затем "
+"эти функции копируют до 'length' байтов из источника в назначение. Однако у "
+"этих функций есть ряд проблем. Ни одна из них не гарантирует завершающий "
+"NUL, если размер входного буфера равен размеру целевого. Параметр длины "
+"также используется неодинаково между `strncpy` и `strncat`, что может "
+"сбивать программистов с толку относительно их правильного использования. "
+"Также наблюдается значительное снижение производительности по сравнению с "
+"`strcpy` при копировании короткой строки в большой буфер, поскольку "
+"`strncpy` заполняет оставшееся пространство до указанного размера символами "
+"NUL."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:178
+msgid ""
+"Another memory copy implementation exists to get around these problems. The "
+"`strlcpy` and `strlcat` functions guarantee that they will always null "
+"terminate the destination string when given a non-zero length argument."
+msgstr ""
+"Существует другая реализация копирования памяти для решения этих проблем. "
+"Функции `strlcpy` и `strlcat` гарантируют, что они всегда завершат строку "
+"назначения нулевым символом при передаче аргумента ненулевой длины."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:179
+#, no-wrap
+msgid "Compiler based run-time bounds checking"
+msgstr "Скомпилированная проверка границ во время выполнения"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:183
+msgid ""
+"Unfortunately there is still a very large assortment of code in public use "
+"which blindly copies memory around without using any of the bounded copy "
+"routines we just discussed. Fortunately, there is a way to help prevent "
+"such attacks - run-time bounds checking, which is implemented by several C/C+"
+"+ compilers."
+msgstr ""
+"К сожалению, до сих пор существует очень большое количество кода в открытом "
+"доступе, который бездумно копирует память, не используя ни одну из "
+"ограниченных функций копирования, которые мы только что обсудили. К счастью, "
+"есть способ помочь предотвратить такие атаки — проверка границ во время "
+"выполнения, которая реализована в нескольких компиляторах C/C++."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:186
+msgid ""
+"ProPolice is one such compiler feature, and is integrated into man:gcc[1] "
+"versions 4.1 and later. It replaces and extends the earlier StackGuard "
+"man:gcc[1] extension."
+msgstr ""
+"ProPolice — это одна из таких функций компилятора, интегрированная в "
+"man:gcc[1] версий 4.1 и выше. Она заменяет и расширяет более раннее "
+"расширение StackGuard для man:gcc[1]."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:190
+msgid ""
+"ProPolice helps to protect against stack-based buffer overflows and other "
+"attacks by laying pseudo-random numbers in key areas of the stack before "
+"calling any function. When a function returns, these \"canaries\" are "
+"checked and if they are found to have been changed the executable is "
+"immediately aborted. Thus any attempt to modify the return address or other "
+"variable stored on the stack in an attempt to get malicious code to run is "
+"unlikely to succeed, as the attacker would have to also manage to leave the "
+"pseudo-random canaries untouched."
+msgstr ""
+"ProPolice помогает защититься от переполнений буфера на стеке и других атак, "
+"размещая псевдослучайные числа в ключевых областях стека перед вызовом любой "
+"функции. Когда функция завершается, эти \"канарейки\" проверяются, и если "
+"обнаруживается, что они были изменены, выполнение программы немедленно "
+"прекращается. Таким образом, любая попытка изменить адрес возврата или "
+"другие переменные, хранящиеся на стеке, с целью запуска вредоносного кода, "
+"вряд ли увенчается успехом, так как злоумышленнику также необходимо оставить "
+"псевдослучайные канарейки нетронутыми."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:192
+msgid ""
+"Recompiling your application with ProPolice is an effective means of "
+"stopping most buffer-overflow attacks, but it can still be compromised."
+msgstr ""
+"Перекомпиляция вашего приложения с использованием ProPolice является "
+"эффективным способом предотвращения большинства атак, связанных с "
+"переполнением буфера, но оно всё ещё может быть скомпрометировано."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:193
+#, no-wrap
+msgid "Library based run-time bounds checking"
+msgstr "Библиотечная проверка границ во время выполнения"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:197
+msgid ""
+"Compiler-based mechanisms are completely useless for binary-only software "
+"for which you cannot recompile. For these situations there are a number of "
+"libraries which re-implement the unsafe functions of the C-library "
+"(`strcpy`, `fscanf`, `getwd`, etc..) and ensure that these functions can "
+"never write past the stack pointer."
+msgstr ""
+"Механизмы на основе компилятора совершенно бесполезны для проприетарного "
+"программного обеспечения, которое невозможно перекомпилировать. Для таких "
+"ситуаций существует ряд библиотек, которые переопределяют небезопасные "
+"функции стандартной библиотеки C (`strcpy`, `fscanf`, `getwd` и т.д.) и "
+"гарантируют, что эти функции никогда не смогут записать данные за указатель "
+"стека."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:199
+msgid "libsafe"
+msgstr "libsafe"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:200
+msgid "libverify"
+msgstr "libverify"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:201
+msgid "libparanoia"
+msgstr "libparanoia"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:206
+msgid ""
+"Unfortunately these library-based defenses have a number of shortcomings. "
+"These libraries only protect against a very small set of security related "
+"issues and they neglect to fix the actual problem. These defenses may fail "
+"if the application was compiled with -fomit-frame-pointer. Also, the "
+"LD_PRELOAD and LD_LIBRARY_PATH environment variables can be overwritten/"
+"unset by the user."
+msgstr ""
+"К сожалению, эти защиты на основе библиотек имеют ряд недостатков. Они "
+"защищают лишь от очень небольшого набора проблем, связанных с безопасностью, "
+"и не устраняют основную причину. Эти защиты могут не сработать, если "
+"приложение было скомпилировано с флагом -fomit-frame-pointer. Кроме того, "
+"переменные окружения LD_PRELOAD и LD_LIBRARY_PATH могут быть перезаписаны "
+"или сброшены пользователем."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:208
+#, no-wrap
+msgid "SetUID issues"
+msgstr "Проблемы с SetUID"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:212
+msgid ""
+"There are at least 6 different IDs associated with any given process, and "
+"you must therefore be very careful with the access that your process has at "
+"any given time. In particular, all seteuid applications should give up "
+"their privileges as soon as it is no longer required."
+msgstr ""
+"Существует как минимум 6 различных идентификаторов, связанных с каждым "
+"процессом, поэтому необходимо очень внимательно следить за уровнем доступа "
+"вашего процесса в любой момент времени. В частности, все приложения с "
+"seteuid должны отказываться от своих привилегий, как только в них больше нет "
+"необходимости."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:215
+msgid ""
+"The real user ID can only be changed by a superuser process. The login "
+"program sets this when a user initially logs in and it is seldom changed."
+msgstr ""
+"Действительный идентификатор пользователя может быть изменён только "
+"процессом с правами суперпользователя. Программа login устанавливает его при "
+"первоначальном входе пользователя в систему, и он редко изменяется."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:219
+msgid ""
+"The effective user ID is set by the `exec()` functions if a program has its "
+"seteuid bit set. An application can call `seteuid()` at any time to set the "
+"effective user ID to either the real user ID or the saved set-user-ID. When "
+"the effective user ID is set by `exec()` functions, the previous value is "
+"saved in the saved set-user-ID."
+msgstr ""
+"Эффективный идентификатор пользователя устанавливается функциями `exec()`, "
+"если у программы установлен бит seteuid. Приложение может вызывать "
+"`seteuid()` в любое время, чтобы установить эффективный идентификатор "
+"пользователя либо в реальный идентификатор пользователя, либо в сохранённый "
+"set-user-ID. Когда эффективный идентификатор пользователя устанавливается "
+"функциями `exec()`, предыдущее значение сохраняется в сохранённом set-user-"
+"ID."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:221
+#, no-wrap
+msgid "Limiting your program's environment"
+msgstr "Ограничение окружения вашей программы"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:229
+msgid ""
+"The traditional method of restricting a process is with the `chroot()` "
+"system call. This system call changes the root directory from which all "
+"other paths are referenced for a process and any child processes. For this "
+"call to succeed the process must have execute (search) permission on the "
+"directory being referenced. The new environment does not actually take "
+"effect until you `chdir()` into your new environment. It should also be "
+"noted that a process can easily break out of a chroot environment if it has "
+"root privilege. This could be accomplished by creating device nodes to read "
+"kernel memory, attaching a debugger to a process outside of the "
+"man:chroot[8] environment, or in many other creative ways."
+msgstr ""
+"Традиционный метод ограничения процесса — это системный вызов `chroot()`. "
+"Этот системный вызов изменяет корневой каталог, от которого ссылаются все "
+"остальные пути для процесса и любых дочерних процессов. Для успешного "
+"выполнения этого вызова процесс должен иметь право на выполнение (поиск) в "
+"указанном каталоге. Новая среда фактически не вступает в силу, пока вы не "
+"выполните `chdir()` в новой среде. Также следует отметить, что процесс может "
+"легко выйти из окружения chroot, если он имеет привилегии root. Это может "
+"быть достигнуто путем создания узлов устройств для чтения памяти ядра, "
+"подключения отладчика к процессу вне окружения man:chroot[8] или многими "
+"другими творческими способами."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:234
+msgid ""
+"The behavior of the `chroot()` system call can be controlled somewhat with "
+"the kern.chroot_allow_open_directories `sysctl` variable. When this value "
+"is set to 0, `chroot()` will fail with EPERM if there are any directories "
+"open. If set to the default value of 1, then `chroot()` will fail with "
+"EPERM if there are any directories open and the process is already subject "
+"to a `chroot()` call. For any other value, the check for open directories "
+"will be bypassed completely."
+msgstr ""
+"Поведение системного вызова `chroot()` можно частично контролировать с "
+"помощью переменной `sysctl` kern.chroot_allow_open_directories. Если этому "
+"параметру присвоено значение 0, `chroot()` завершится с ошибкой EPERM, если "
+"есть какие-либо открытые каталоги. Если установлено значение по умолчанию 1, "
+"то `chroot()` завершится с ошибкой EPERM, если есть открытые каталоги и "
+"процесс уже находится внутри вызова `chroot()`. Для любого другого значения "
+"проверка на открытые каталоги будет полностью пропущена."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:235
+#, no-wrap
+msgid "FreeBSD's jail functionality"
+msgstr "Функциональность клеток FreeBSD"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:239
+msgid ""
+"The concept of a Jail extends upon the `chroot()` by limiting the powers of "
+"the superuser to create a true `virtual server'. Once a prison is set up "
+"all network communication must take place through the specified IP address, "
+"and the power of \"root privilege\" in this jail is severely constrained."
+msgstr ""
+"Концепция `клетки` расширяет возможности `chroot()`, ограничивая права "
+"суперпользователя для создания настоящего `виртуального сервера`. После "
+"настройки клетки все сетевые взаимодействия должны осуществляться через "
+"указанный IP-адрес, а привилегии `root` внутри этой клетки сильно ограничены."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:243
+msgid ""
+"While in a prison, any tests of superuser power within the kernel using the "
+"`suser()` call will fail. However, some calls to `suser()` have been "
+"changed to a new interface `suser_xxx()`. This function is responsible for "
+"recognizing or denying access to superuser power for imprisoned processes."
+msgstr ""
+"Находясь в клетке, любые проверки прав суперпользователя в ядре с "
+"использованием вызова `suser()` завершатся неудачей. Однако некоторые вызовы "
+"`suser()` были заменены на новый интерфейс `suser_xxx()`. Эта функция "
+"отвечает за распознавание или запрет доступа к правам суперпользователя для "
+"процессов в клетке."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:245
+msgid "A superuser process within a jailed environment has the power to:"
+msgstr "Суперпользователь в среде клетки имеет возможность:"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:247
+msgid ""
+"Manipulate credential with `setuid`, `seteuid`, `setgid`, `setegid`, "
+"`setgroups`, `setreuid`, `setregid`, `setlogin`"
+msgstr ""
+"Управлять учетными данными с помощью `setuid`, `seteuid`, `setgid`, "
+"`setegid`, `setgroups`, `setreuid`, `setregid`, `setlogin`"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:248
+msgid "Set resource limits with `setrlimit`"
+msgstr "Установливать ограничений ресурсов с помощью `setrlimit`"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:249
+msgid "Modify some sysctl nodes (kern.hostname)"
+msgstr "Изменять некоторые узлы sysctl (kern.hostname)"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:250
+msgid "`chroot()`"
+msgstr "`chroot()`"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:251
+msgid "Set flags on a vnode: `chflags`, `fchflags`"
+msgstr "Устанавливать флаги на vnode: `chflags`, `fchflags`"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:252
+msgid ""
+"Set attributes of a vnode such as file permission, owner, group, size, "
+"access time, and modification time."
+msgstr ""
+"Устанавливать атрибуты vnode, такие как права доступа к файлу, владелец, "
+"группа, размер, время доступа и время изменения."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:253
+msgid "Bind to privileged ports in the Internet domain (ports < 1024)"
+msgstr ""
+"Привязываться к привилегированным портам в домене Интернета (порты < 1024)"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:257
+msgid ""
+"`Jail` is a very useful tool for running applications in a secure "
+"environment but it does have some shortcomings. Currently, the IPC "
+"mechanisms have not been converted to the `suser_xxx` so applications such "
+"as MySQL cannot be run within a jail. Superuser access may have a very "
+"limited meaning within a jail, but there is no way to specify exactly what "
+"\"very limited\" means."
+msgstr ""
+"`Клетка` — это очень полезный инструмент для запуска приложений в безопасной "
+"среде, но у него есть некоторые недостатки. В настоящее время механизмы IPC "
+"не были преобразованы в `suser_xxx`, поэтому такие приложения, как MySQL, не "
+"могут быть запущены внутри клетки. Доступ суперпользователя может иметь "
+"очень ограниченное значение внутри клетки, но нет возможности точно указать, "
+"что означает «очень ограниченный»."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:258
+#, no-wrap
+msgid "POSIX(R).1e Process Capabilities"
+msgstr "Возможности процесса в POSIX(R).1e"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:261
+msgid ""
+"POSIX(R) has released a working draft that adds event auditing, access "
+"control lists, fine grained privileges, information labeling, and mandatory "
+"access control."
+msgstr ""
+"POSIX(R) выпустил рабочий проект, который добавляет аудит событий, списки "
+"контроля доступа, детализированные привилегии, маркировку информации и "
+"обязательный контроль доступа."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:264
+msgid ""
+"This is a work in progress and is the focus of the http://www.trustedbsd.org/"
+"[TrustedBSD] project. Some of the initial work has been committed to "
+"FreeBSD-CURRENT (cap_set_proc(3))."
+msgstr ""
+"Это работа в процессе, и она является основным направлением проекта http://"
+"www.trustedbsd.org/[TrustedBSD]. Некоторые первоначальные наработки были "
+"добавлены в FreeBSD-CURRENT (cap_set_proc(3))."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:266
+#, no-wrap
+msgid "Trust"
+msgstr "Доверие"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:270
+msgid ""
+"An application should never assume that anything about the users environment "
+"is sane. This includes (but is certainly not limited to): user input, "
+"signals, environment variables, resources, IPC, mmaps, the filesystem "
+"working directory, file descriptors, the # of open files, etc."
+msgstr ""
+"Приложение никогда не должно предполагать, что окружение пользователя "
+"является предсказуемым. Это включает (но не ограничивается): "
+"пользовательский ввод, сигналы, переменные окружения, ресурсы, IPC, mmaps, "
+"текущую рабочую директорию файловой системы, файловые дескрипторы, "
+"количество открытых файлов и т.д."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:275
+msgid ""
+"You should never assume that you can catch all forms of invalid input that a "
+"user might supply. Instead, your application should use positive filtering "
+"to only allow a specific subset of inputs that you deem safe. Improper data "
+"validation has been the cause of many exploits, especially with CGI scripts "
+"on the world wide web. For filenames you need to be extra careful about "
+"paths (\"../\", \"/\"), symbolic links, and shell escape characters."
+msgstr ""
+"Никогда не следует предполагать, что можно отловить все виды некорректных "
+"входных данных, которые может предоставить пользователь. Вместо этого ваше "
+"приложение должно использовать позитивную фильтрацию, разрешая только "
+"определённое подмножество входных данных, которые вы считаете безопасными. "
+"Некорректная проверка данных стала причиной многих уязвимостей, особенно в "
+"CGI-скриптах во всемирной паутине. Для имён файлов необходимо быть особенно "
+"осторожными с путями (\"../\", \"/\"), символическими ссылками и escape-"
+"символами оболочки."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:278
+msgid ""
+"Perl has a really cool feature called \"Taint\" mode which can be used to "
+"prevent scripts from using data derived outside the program in an unsafe "
+"way. This mode will check command line arguments, environment variables, "
+"locale information, the results of certain syscalls (`readdir()`, "
+"`readlink()`, `getpwxxx()`), and all file input."
+msgstr ""
+"В Perl есть замечательная функция под названием \"Режим Taint\", которая "
+"может использоваться для предотвращения небезопасного использования данных, "
+"полученных извне программы. Этот режим проверяет аргументы командной строки, "
+"переменные окружения, информацию о локали, результаты определённых системных "
+"вызовов (`readdir()`, `readlink()`, `getpwxxx()`) и все вводимые данные из "
+"файлов."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:280
+#, no-wrap
+msgid "Race Conditions"
+msgstr "Состояние гонки"
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:284
+msgid ""
+"A race condition is anomalous behavior caused by the unexpected dependence "
+"on the relative timing of events. In other words, a programmer incorrectly "
+"assumed that a particular event would always happen before another."
+msgstr ""
+"Состояние гонки — это аномальное поведение, вызванное непредвиденной "
+"зависимостью от относительного времени событий. Другими словами, программист "
+"ошибочно предположил, что определенное событие всегда произойдет раньше "
+"другого."
+
+#. type: XXX figure here!
+#: documentation/content/en/books/developers-handbook/secure/_index.adoc:290
+msgid ""
+"Some of the common causes of race conditions are signals, access checks, and "
+"file opens. Signals are asynchronous events by nature so special care must "
+"be taken in dealing with them. Checking access with `access(2)` then "
+"`open(2)` is clearly non-atomic. Users can move files in between the two "
+"calls. Instead, privileged applications should `seteuid()` and then call "
+"`open()` directly. Along the same lines, an application should always set a "
+"proper umask before `open()` to obviate the need for spurious `chmod()` "
+"calls."
+msgstr ""
+"Некоторые из распространённых причин состояний гонки — это сигналы, проверки "
+"доступа и открытие файлов. Сигналы по своей природе являются асинхронными "
+"событиями, поэтому при работе с ними необходимо проявлять особую "
+"осторожность. Проверка доступа с помощью `access(2)`, а затем `open(2)` явно "
+"неатомарна. Пользователи могут перемещать файлы между этими двумя вызовами. "
+"Вместо этого привилегированные приложения должны использовать `seteuid()`, а "
+"затем вызывать `open()` напрямую. По аналогии, приложение всегда должно "
+"устанавливать правильную маску (`umask`) перед вызовом `open()`, чтобы "
+"избежать необходимости в лишних вызовах `chmod()`."
diff --git a/documentation/content/ru/books/developers-handbook/sockets/_index.adoc b/documentation/content/ru/books/developers-handbook/sockets/_index.adoc
new file mode 100644
index 0000000000..669a53fb60
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/sockets/_index.adoc
@@ -0,0 +1,909 @@
+---
+authors:
+ -
+ author: 'G. Adam Stanislav'
+description: 'Сокеты FreeBSD'
+next: books/developers-handbook/ipv6
+params:
+ path: /books/developers-handbook/sockets/
+prev: books/developers-handbook/partii
+showBookMenu: true
+tags: ["Sockets", "Protocols"]
+title: 'Глава 7. Сокеты'
+weight: 9
+---
+
+[[sockets]]
+= Сокеты
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 7
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[sockets-synopsis]]
+== Обзор
+
+Сокеты BSD выводят межпроцессное взаимодействие на новый уровень. Теперь взаимодействующие процессы не обязательно должны выполняться на одной машине. Они всё ещё _могут_, но не обязаны.
+
+Не только эти процессы не обязаны выполняться на одной машине, они также могут работать под разными операционными системами. Благодаря BSD-сокетам, ваше ПО на FreeBSD может легко взаимодействовать с программой, работающей на Macintosh(R), другой — на рабочей станции Sun(TM), и ещё одной — под Windows(R) 2000, при этом все они подключены к локальной сети на основе Ethernet.
+
+Но ваше программное обеспечение может так же эффективно взаимодействовать с процессами, работающими в другом здании, на другом континенте, внутри подводной лодки или космического челнока.
+
+Он также может взаимодействовать с процессами, которые не являются частью компьютера (по крайней мере, не в строгом смысле этого слова), а таких устройств, как принтеры, цифровые камеры, медицинское оборудование. Практически со всем, что способно к цифровой коммуникации.
+
+[[sockets-diversity]]
+== Сетевое взаимодействие и разнообразие
+
+Мы уже упоминали о _разнообразии_ сетевых технологий. Множество различных систем должны взаимодействовать друг с другом. И они должны говорить на одном языке. Также они должны _понимать_ этот язык одинаковым образом.
+
+Часто думают, что _язык тела_ универсален. Но это не так. В ранней юности отец взял меня с собой в Болгарию. Мы сидели за столиком в парке Софии, когда к нам подошел продавец, предлагая купить жареный миндаль.
+
+Я тогда еще не знал болгарского, поэтому вместо словесного отказа я покачал головой из стороны в сторону — это «универсальный» язык тела для обозначения _нет_. Продавец тут же начал угощать нас миндалем.
+
+Затем я вспомнил, что мне говорили, будто в Болгарии покачивание головой из стороны в сторону означает _да_. Быстро я начал кивать головой вверх-вниз. Продавец заметил, взял свои миндалины и ушёл. Для непосвящённого наблюдателя я не изменил язык тела: я продолжал использовать движения головой — покачивание и кивание. Изменился _смысл_ языка тела. Сначала продавец и я интерпретировали одни и те же жесты как имеющие совершенно разный смысл. Мне пришлось скорректировать свою собственную интерпретацию этих жестов, чтобы продавец меня понял.
+
+То же самое и с компьютерами: одни и те же символы могут иметь разное, даже полностью противоположное значение. Поэтому, чтобы два компьютера понимали друг друга, они должны договориться не только об одном _языке_, но и об одном _толковании_ языка.
+
+[[sockets-protocols]]
+== Протоколы
+
+В то время как различные языки программирования обычно имеют сложный синтаксис и используют множество многосимвольных зарезервированных слов (что облегчает их понимание для человека-программиста), языки передачи данных, как правило, очень лаконичны. Вместо многосимвольных слов они часто используют отдельные _биты_. Для этого есть очень убедительная причина: хотя данные внутри вашего компьютера передаются со скоростью, близкой к скорости света, между двумя компьютерами они часто передаются значительно медленнее.
+
+Поскольку языки, используемые в передаче данных, настолько лаконичны, мы обычно называем их _протоколами_, а не языками.
+
+При передаче данных от одного компьютера к другому всегда используется более одного протокола. Эти протоколы _располагаются слоями_. Данные можно сравнить с внутренней частью лука: необходимо снять несколько слоёв «кожи», чтобы добраться до данных. Это лучше всего проиллюстрировано на рисунке:
+
+.Уровни протоколов
+image::layers.png[]
+
+В этом примере мы пытаемся получить изображение с веб-страницы, к которой подключены через Ethernet.
+
+Изображение состоит из необработанных данных, которые представляют собой просто последовательность значений RGB, которые наше программное обеспечение может обработать, т.е. преобразовать в изображение и отобразить на нашем мониторе.
+
+Увы, наше программное обеспечение не может определить, как организованы сырые данные: это последовательность значений RGB, последовательность интенсивностей в градациях серого или, возможно, цвета в кодировке CMYK? Представлены ли данные 8-битными квантами, или они имеют размер 16 бит, а может быть, 4 бита? Из скольких строк и столбцов состоит изображение? Должны ли определённые пиксели быть прозрачными?
+
+Я думаю, вы поняли...
+
+Чтобы наше программное обеспечение понимало, как обрабатывать сырые данные, они кодируются в формате PNG. Это мог бы быть GIF или JPEG, но выбран PNG.
+
+И PNG — это протокол.
+
+В этот момент я слышу, как некоторые из вас кричат: _"Нет, это не так! Это формат файла!"_
+
+Ну что ж, конечно, это формат файла. Но с точки зрения передачи данных, формат файла — это протокол: структура файла — это _язык_, причем лаконичный, сообщающий нашему _процессу_, как организованы данные. Следовательно, это _протокол_.
+
+Увы, если бы мы получили только PNG-файл, наше программное обеспечение столкнулось бы с серьёзной проблемой: как ему узнать, что данные представляют изображение, а не текст, звук или что-то ещё? Во-вторых, как ему определить, что изображение сохранено в формате PNG, а не GIF, JPEG или каком-либо другом формате изображений?
+
+Для получения этой информации мы используем другой протокол: HTTP. Этот протокол может точно сообщить нам, что данные представляют изображение и используют протокол PNG. Он также может сообщить некоторые другие сведения, но давайте сосредоточимся на уровнях протоколов здесь.
+
+Итак, теперь у нас есть некоторые данные, упакованные в протокол PNG, который в свою очередь упакован в протокол HTTP. Как мы получили их с сервера?
+
+Используя TCP/IP поверх Ethernet, вот как. Действительно, это ещё три протокола. Вместо того чтобы продолжать изнутри наружу, я теперь расскажу про Ethernet, просто потому что так проще объяснить остальное.
+
+Ethernet — это интересная система соединения компьютеров в _локальной сети_ (LAN). У каждого компьютера есть _карта сетевого интерфейса_ (NIC — Network Interface Card) с уникальным 48-битным идентификатором, называемым _адресом_. Не существует двух сетевых интерфейсов Ethernet в мире с одинаковым адресом.
+
+Эти сетевые карты соединены между собой. Когда один компьютер хочет связаться с другим в той же локальной сети Ethernet, он отправляет сообщение по сети. Каждая сетевая карта видит это сообщение. Однако, согласно _протоколу_ Ethernet, данные содержат адрес сетевой карты назначения (среди прочего). Таким образом, только одна из всех сетевых карт обратит на него внимание, остальные проигнорируют его.
+
+Но не все компьютеры подключены к одной сети. Тот факт, что мы получили данные через наш Ethernet, не означает, что они возникли в нашей локальной сети. Они могли попасть к нам из другой сети (которая может быть даже не на основе Ethernet), соединённой с нашей сетью через Интернет.
+
+Все данные передаются через Интернет с использованием IP, что означает _Internet Protocol_. Его основная роль — сообщать нам, откуда в мире пришли данные и куда они должны быть направлены. Он не _гарантирует_, что мы получим данные, только что мы узнаем, откуда они пришли, _если_ мы их получим.
+
+Даже если мы получим данные, IP не гарантирует, что различные фрагменты данных придут в том же порядке, в котором их отправил другой компьютер. Например, мы можем получить центр нашего изображения до того, как получим его верхний левый угол, а после — нижний правый.
+
+Это TCP (_Transmission Control Protocol_), который запрашивает у отправителя повторную отправку потерянных данных и располагает их в правильном порядке.
+
+В итоге потребовалось _пять_ различных протоколов, чтобы один компьютер мог сообщить другому, как выглядит изображение. Мы получили данные, упакованные в протокол PNG, который был упакован в протокол HTTP, который был упакован в протокол TCP, который был упакован в протокол IP, который был упакован в протокол Ethernet.
+
+О, и кстати, вероятно, на пути были задействованы и несколько других протоколов. Например, если наша локальная сеть была подключена к Интернету через дозвон, то использовался протокол PPP над модемом, который, в свою очередь, использовал один (или несколько) из различных модемных протоколов, и так далее, и так далее, и так далее...
+
+Как разработчик, вы уже должны задаваться вопросом: _"Как я должен со всем этим справляться?"_
+
+К счастью для вас, вам _не_ нужно разбираться во всём этом. Вам _придётся_ разобраться в некоторой части, но не во всей. В частности, вам не нужно беспокоиться о физическом подключении (в нашем случае Ethernet и, возможно, PPP и т.д.). Также вам не нужно разбираться с протоколом IP или протоколом TCP.
+
+Другими словами, вам не нужно ничего делать, чтобы получить данные с другого компьютера. Ну, разве что _попросить_ их, но это почти так же просто, как открыть файл.
+
+Получив данные, вам предстоит решить, что с ними делать. В нашем случае потребуется понимание протокола HTTP и структуры файла PNG.
+
+Используя аналогию, все межсетевые протоколы становятся серой зоной: не столько потому, что мы не понимаем, как они работают, а потому, что нас это больше не беспокоит. Интерфейс сокетов берёт на себя заботу об этой серой зоне:
+
+.Уровни протоколов, покрываемые сокетами
+image::slayers.png[]
+
+Нам нужно понимать только те протоколы, которые говорят нам, как _интерпретировать данные_, а не как _получать_ их от другого процесса или как _передавать_ их другому процессу.
+
+[[sockets-model]]
+== Модель сокетов
+
+Сокеты BSD построены по базовой модели UNIX(R): _Все является файлом._ Таким образом, в нашем примере сокеты позволят нам получить, образно говоря, _HTTP-файл_. Затем нам предстоит извлечь из него _PNG-файл_.
+
+Из-за сложности межсетевого взаимодействия мы не можем просто использовать системный вызов `open` или функцию `open()` в языке C. Вместо этого необходимо выполнить несколько шагов для "открытия" сокета.
+
+Однако, как только мы это сделаем, мы можем начать обращаться с _сокетом_ так же, как и с любым _файловым дескриптором_: мы можем `читать` из него, `писать` в него, передавать его через `канал` и, в конечном итоге, `закрывать` его.
+
+[[sockets-essential-functions]]
+== Основные функции сокетов
+
+В то время как FreeBSD предлагает различные функции для работы с сокетами, нам _требуется_ только четыре, чтобы "открыть" сокет. А в некоторых случаях достаточно двух.
+
+[[sockets-client-server]]
+=== Разница между клиентом и сервером
+
+Обычно одним из концов связи на основе сокетов является _сервер_, а другой — _клиент_.
+
+[[sockets-common-elements]]
+==== Общие элементы
+
+[[sockets-socket]]
+===== `socket`
+
+Функция, используемая как клиентами, так и серверами, это man:socket[2]. Она объявляется следующим образом:
+
+[.programlisting]
+....
+int socket(int domain, int type, int protocol);
+....
+
+Возвращаемое значение имеет тот же тип, что и у `open`, целое число. FreeBSD выделяет его значение из того же пула, что и дескрипторы файлов. Это позволяет обрабатывать сокеты так же, как файлы.
+
+Аргумент `domain` указывает системе, какое _семейство протоколов_ следует использовать. Существует множество семейств, некоторые из них специфичны для определённых поставщиков, другие широко распространены. Они объявлены в [.filename]#sys/socket.h#.
+
+Используйте `PF_INET` для UDP, TCP и других интернет-протоколов (IPv4).
+
+Для аргумента `type` определено пять значений, также указанных в [.filename]#sys/socket.h#. Все они начинаются с "`SOCK_`". Наиболее распространённое — `SOCK_STREAM`, которое указывает системе, что запрашивается _надёжный сервис потоковой доставки_ (это TCP при использовании с `PF_INET`).
+
+Если бы вы запросили `SOCK_DGRAM`, вы бы запросили _сервис доставки датаграмм без установления соединения_ (в нашем случае, UDP).
+
+Если вы хотите управлять низкоуровневыми протоколами (такими как IP) или даже сетевыми интерфейсами (например, Ethernet), вам потребуется указать `SOCK_RAW`.
+
+Наконец, аргумент `protocol` зависит от двух предыдущих аргументов и не всегда имеет смысл. В таком случае используйте значение `0`.
+
+[NOTE]
+.Неподключенный сокет
+====
+Нигде в функции `socket` мы не указали, к какой другой системе должны быть подключены. Наш только что созданный сокет остаётся _неподключённым_.
+
+Это сделано намеренно: если проводить аналогию с телефоном, мы только что подключили модем к телефонной линии. Мы не сказали модему совершить звонок или ответить, если телефон зазвонит.
+====
+
+[[sockets-sockaddr]]
+===== `sockaddr`
+
+Различные функции семейства сокетов ожидают адрес (или указатель, если использовать терминологию языка C) небольшой области памяти. Различные объявления на языке C в файле [.filename]#sys/socket.h# ссылаются на неё как на `struct sockaddr`. Эта структура объявлена в том же файле:
+
+[.programlisting]
+....
+/*
+ * Structure used by kernel to store most
+ * addresses.
+ */
+struct sockaddr {
+ unsigned char sa_len; /* total length */
+ sa_family_t sa_family; /* address family */
+ char sa_data[14]; /* actually longer; address value */
+};
+#define SOCK_MAXADDRLEN 255 /* longest possible addresses */
+....
+
+Обратите внимание на _неопределённость_, с которой объявлено поле `sa_data` — просто как массив из `14` байт, с комментарием, намекающим, что их может быть больше `14`.
+
+Эта неопределенность вполне преднамеренна. Сокеты — это очень мощный интерфейс. Хотя большинство людей, возможно, считают их не более чем интерфейсом для Интернета — и большинство приложений, вероятно, используют их именно для этого в наши дни — сокеты могут быть использованы практически для _любого_ вида межпроцессного взаимодействия, из которых Интернет (или, точнее, IP) — лишь один из них.
+
+[.filename]#sys/socket.h# ссылается на различные типы протоколов, с которыми работают сокеты, как на _семейства адресов_, и перечисляет их непосредственно перед определением `sockaddr`:
+
+[.programlisting]
+....
+/*
+ * Address families.
+ */
+#define AF_UNSPEC 0 /* unspecified */
+#define AF_LOCAL 1 /* local to host (pipes, portals) */
+#define AF_UNIX AF_LOCAL /* backward compatibility */
+#define AF_INET 2 /* internetwork: UDP, TCP, etc. */
+#define AF_IMPLINK 3 /* arpanet imp addresses */
+#define AF_PUP 4 /* pup protocols: e.g. BSP */
+#define AF_CHAOS 5 /* mit CHAOS protocols */
+#define AF_NS 6 /* XEROX NS protocols */
+#define AF_ISO 7 /* ISO protocols */
+#define AF_OSI AF_ISO
+#define AF_ECMA 8 /* European computer manufacturers */
+#define AF_DATAKIT 9 /* datakit protocols */
+#define AF_CCITT 10 /* CCITT protocols, X.25 etc */
+#define AF_SNA 11 /* IBM SNA */
+#define AF_DECnet 12 /* DECnet */
+#define AF_DLI 13 /* DEC Direct data link interface */
+#define AF_LAT 14 /* LAT */
+#define AF_HYLINK 15 /* NSC Hyperchannel */
+#define AF_APPLETALK 16 /* Apple Talk */
+#define AF_ROUTE 17 /* Internal Routing Protocol */
+#define AF_LINK 18 /* Link layer interface */
+#define pseudo_AF_XTP 19 /* eXpress Transfer Protocol (no AF) */
+#define AF_COIP 20 /* connection-oriented IP, aka ST II */
+#define AF_CNT 21 /* Computer Network Technology */
+#define pseudo_AF_RTIP 22 /* Help Identify RTIP packets */
+#define AF_IPX 23 /* Novell Internet Protocol */
+#define AF_SIP 24 /* Simple Internet Protocol */
+#define pseudo_AF_PIP 25 /* Help Identify PIP packets */
+#define AF_ISDN 26 /* Integrated Services Digital Network*/
+#define AF_E164 AF_ISDN /* CCITT E.164 recommendation */
+#define pseudo_AF_KEY 27 /* Internal key-management function */
+#define AF_INET6 28 /* IPv6 */
+#define AF_NATM 29 /* native ATM access */
+#define AF_ATM 30 /* ATM */
+#define pseudo_AF_HDRCMPLT 31 /* Used by BPF to not rewrite headers
+ * in interface output routine
+ */
+#define AF_NETGRAPH 32 /* Netgraph sockets */
+#define AF_SLOW 33 /* 802.3ad slow protocol */
+#define AF_SCLUSTER 34 /* Sitara cluster protocol */
+#define AF_ARP 35
+#define AF_BLUETOOTH 36 /* Bluetooth sockets */
+#define AF_MAX 37
+....
+
+Используемый для IP — это AF_INET. Это символ для константы `2`.
+
+Это _семейство адресов_, указанное в поле `sa_family` структуры `sockaddr`, определяет, как именно будут использоваться нечетко названные байты `sa_data`.
+
+В частности, когда _семейство адресов_ — AF_INET, можно использовать `struct sockaddr_in` из [.filename]#netinet/in.h# везде, где ожидается `sockaddr`:
+
+[.programlisting]
+....
+/*
+ * Socket address, internet style.
+ */
+struct sockaddr_in {
+ uint8_t sin_len;
+ sa_family_t sin_family;
+ in_port_t sin_port;
+ struct in_addr sin_addr;
+ char sin_zero[8];
+};
+....
+
+Мы можем визуализировать его организацию следующим образом:
+
+.Структура `sockaddr_in`
+image::sain.png[]
+
+Три важных поля — это `sin_family`, которое находится в байте 1 структуры, `sin_port`, 16-битное значение, расположенное в байтах 2 и 3, и `sin_addr`, 32-битное целочисленное представление IP-адреса, хранящееся в байтах 4–7.
+
+Теперь попробуем заполнить его. Предположим, мы пытаемся написать клиент для протокола _daytime_, который просто указывает, что его сервер записывает текстовую строку с текущей датой и временем в порт 13. Мы хотим использовать TCP/IP, поэтому нам нужно указать `AF_INET` в поле семейства адресов. `AF_INET` определен как `2`. Давайте используем IP-адрес `192.43.244.18`, который является сервером времени федерального правительства США (`time.nist.gov`).
+
+.Конкретный пример sockaddr_in
+image::sainfill.png[]
+
+Кстати, поле `sin_addr` объявлено как имеющее тип `struct in_addr`, который определён в [.filename]#netinet/in.h#:
+
+[.programlisting]
+....
+/*
+ * Internet address (a structure for historical reasons)
+ */
+struct in_addr {
+ in_addr_t s_addr;
+};
+....
+
+В дополнение, `in_addr_t` является 32-битным целым числом.
+
+`192.43.244.18` — это просто удобная форма записи 32-битного целого числа, в которой перечисляются все его 8-битные байты, начиная с _старшего_.
+
+До сих пор мы рассматривали `sockaddr` как абстракцию. Наш компьютер не хранит `short` целые числа как единую 16-битную сущность, а как последовательность 2 байт. Аналогично, он хранит 32-битные целые числа как последовательность 4 байт.
+
+Предположим, мы написали что-то вроде этого:
+
+[.programlisting]
+....
+sa.sin_family = AF_INET;
+sa.sin_port = 13;
+sa.sin_addr.s_addr = (((((192 << 8) | 43) << 8) | 244) << 8) | 18;
+....
+
+Как будет выглядеть результат?
+
+Ну, это, конечно, зависит от многого. На компьютере с процессором Pentium(R) или другим на базе x86 это будет выглядеть так:
+
+.`sockaddr_in` в системе с архитектурой Intel
+image::sainlsb.png[]
+
+На другой системе это может выглядеть так:
+
+.`sockaddr_in` в системе с порядком байтов от старшего к младшему
+image::sainmsb.png[]
+
+И на PDP это может выглядеть иначе. Однако два приведённых выше варианта являются наиболее распространёнными на сегодняшний день.
+
+Обычно, стремясь писать переносимый код, программисты делают вид, что этих различий не существует. И им это сходит с рук (за исключением случаев, когда они пишут на ассемблере). Увы, при программировании сокетов так легко отделаться не получится.
+
+Почему?
+
+Потому что при обмене данными с другим компьютером вы обычно не знаете, хранит ли он данные, начиная со _старшего байта_ (MSB) или с _младшего байта_ (LSB).
+
+Вы можете задаться вопросом: _"Значит, сокеты не будут это делать за меня?"_
+
+Не будут.
+
+Хотя этот ответ может сначала вас удивить, помните, что общий интерфейс сокетов понимает только поля `sa_len` и `sa_family` структуры `sockaddr`. Вам не нужно беспокоиться о порядке байтов (конечно, в FreeBSD `sa_family` занимает всего 1 байт, но многие другие UNIX(R)-системы не имеют `sa_len` и используют 2 байта для `sa_family`, ожидая данные в том порядке, который является родным для компьютера).
+
+Но остальные данные — это просто `sa_data[14]` с точки зрения сокетов. В зависимости от _семейства адресов_ сокеты просто передают эти данные по назначению.
+
+Действительно, когда мы указываем номер порта, это делается для того, чтобы другая компьютерная система знала, какую службу мы запрашиваем. И, когда мы выступаем в роли сервера, мы считываем номер порта, чтобы понять, какую службу ожидает от нас другая система. В любом случае, сокетам нужно лишь передать номер порта в качестве данных. Они никак его не интерпретируют.
+
+Аналогично, мы указываем IP-адрес, чтобы сообщить всем на пути, куда отправлять наши данные. Сокеты, опять же, просто пересылают их как данные.
+
+Вот почему мы (программисты, а не сокеты) должны различать порядок байтов, используемый нашим компьютером, и условный порядок байтов для отправки данных на другой компьютер.
+
+Мы будем называть порядок байтов, который использует наш компьютер, _порядком байтов хоста_ или просто _хост-порядком_.
+
+Существует соглашение о передаче многобайтовых данных по IP _старшим байтом вперёд_. Это мы будем называть _порядком байтов сети_ или просто _сетевым порядком_.
+
+Вот, если бы мы скомпилировали приведённый выше код для компьютера на базе Intel, наш _порядок байтов хоста_ выдал бы:
+
+.Порядок байтов на хосте в системе Intel
+image::sainlsb.png[]
+
+Но порядок байтов в _сетевом формате_ требует, чтобы данные хранились начиная со старшего байта (MSB):
+
+.Порядок байтов в сети
+image::sainmsb.png[]
+
+К сожалению, наш _порядок хоста_ полностью противоположен _порядку сети_.
+
+У нас есть несколько способов решения этой проблемы. Один из них — _инвертировать_ значения в нашем коде:
+
+[.programlisting]
+....
+sa.sin_family = AF_INET;
+sa.sin_port = 13 << 8;
+sa.sin_addr.s_addr = (((((18 << 8) | 244) << 8) | 43) << 8) | 192;
+....
+
+Это _обманет_ наш компилятор, заставив его сохранить данные в _порядке байтов сети_. В некоторых случаях это именно тот способ, который нужен (например, при программировании на ассемблере). Однако в большинстве случаев это может вызвать проблему.
+
+Предположим, вы написали программу на C, использующую сокеты. Вы знаете, что она будет работать на Pentium(R), поэтому вводите все константы в обратном порядке и приводите их к _порядку байтов сети_. Она работает хорошо.
+
+Затем, однажды, ваш надежный старый Pentium(R) превращается в ржавый старый Pentium(R). Вы заменяете его системой, у которой _порядок байтов хоста_ совпадает с _сетевым порядком байтов_. Вам нужно перекомпилировать все ваше программное обеспечение. Все ваши программы продолжают работать хорошо, кроме той одной программы, которую вы написали.
+
+Вы уже забыли, что принудительно задали все свои константы противоположными _порядку хоста_. Вы проводите некоторое время, яростно рвя на себе волосы, взывая ко всем известным вам богам (и к некоторым, которых вы придумали), стуча нерф-битой по монитору и выполняя прочие традиционные ритуалы в попытке понять, почему то, что работало так хорошо, внезапно перестало работать вообще.
+
+В конце концов, вы разбираетесь в проблеме, произносите пару крепких словечек и начинаете переписывать свой код.
+
+К счастью, вы не первый, кто столкнулся с этой проблемой. Кто-то уже создал функции man:htons[3] и man:htonl[3] на языке C для преобразования `short` и `long` соответственно из _порядка байтов хоста_ в _порядок байтов сети_, а также функции man:ntohs[3] и man:ntohl[3] на языке C для обратного преобразования.
+
+На системах с порядком _старший байт первый_ эти функции не выполняют никаких действий. На системах с порядком _младший байт первый_ они преобразуют значения в правильный порядок.
+
+Итак, независимо от того, на какой системе компилируется ваше программное обеспечение, ваши данные будут в правильном порядке, если вы используете эти функции.
+
+[[sockets-client-functions]]
+==== Функции клиента
+
+Обычно клиент инициирует подключение к серверу. Клиент знает, к какому серверу он собирается обратиться: он знает его IP-адрес и _порт_, на котором работает сервер. Это похоже на то, как вы поднимаете трубку и набираете номер (_адрес_), а затем, когда кто-то отвечает, просите соединить со специалистом по непонятным символам (_порт_).
+
+[[sockets-connect]]
+===== `connect`
+
+Как только клиент создал сокет, ему нужно подключить его к определённому порту на удалённой системе. Для этого используется man:connect[2]:
+
+[.programlisting]
+....
+int connect(int s, const struct sockaddr *name, socklen_t namelen);
+....
+
+Аргумент `s` — это сокет, то есть значение, возвращаемое функцией `socket`. Аргумент `name` — это указатель на структуру `sockaddr`, которую мы подробно обсуждали. Наконец, `namelen` сообщает системе, сколько байт находится в нашей структуре `sockaddr`.
+
+Если `connect` завершается успешно, он возвращает `0`. В противном случае возвращается `-1`, а код ошибки сохраняется в `errno`.
+
+Существует множество причин, по которым `connect` может завершиться неудачей. Например, при попытке подключения к интернету, IP-адрес может не существовать, быть недоступен, перегружен или на указанном порту может не быть сервера. Или же подключение может быть явно _отклонено_ по определённым причинам.
+
+[[sockets-first-client]]
+===== Наш первый клиент
+
+Теперь мы знаем достаточно, чтобы написать очень простого клиента, который получит текущее время от `192.43.244.18` и выведет его в [.filename]#stdout#.
+
+[.programlisting]
+....
+/*
+ * daytime.c
+ *
+ * Programmed by G. Adam Stanislav
+ */
+#include <stdio.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <unistd.h>
+
+int main() {
+ int s, bytes;
+ struct sockaddr_in sa;
+ char buffer[BUFSIZ+1];
+
+ if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("socket");
+ return 1;
+ }
+
+ memset(&sa, '\0', sizeof(sa));
+
+ sa.sin_family = AF_INET;
+ sa.sin_port = htons(13);
+ sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18);
+ if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
+ perror("connect");
+ close(s);
+ return 2;
+ }
+
+ while ((bytes = read(s, buffer, BUFSIZ)) > 0)
+ write(1, buffer, bytes);
+
+ close(s);
+ return 0;
+}
+....
+
+Вперед! Введите это в вашем редакторе, сохраните как [.filename]#daytime.c#, затем скомпилируйте и запустите:
+
+[source, bash]
+....
+% cc -O3 -o daytime daytime.c
+% ./daytime
+
+52079 01-06-19 02:29:25 50 0 1 543.9 UTC(NIST) *
+%
+....
+
+В данном случае дата была 19 июня 2001 года, время — 02:29:25 UTC. Естественно, ваши результаты могут отличаться.
+
+[[sockets-server-functions]]
+==== Функции сервера
+
+Типичный сервер не инициирует соединение. Вместо этого он ожидает, когда клиент обратится к нему и запросит услуги. Он не знает, когда клиент обратится, ни сколько клиентов обратится. В один момент он может просто спокойно ожидать, а в следующий момент он может оказаться перегруженным запросами от множества клиентов, обращающихся одновременно.
+
+Интерфейс сокетов предоставляет три основные функции для обработки этого.
+
+[[sockets-bind]]
+===== `bind`
+
+Порты подобны внутренним номерам телефонной линии: после набора основного номера вы набираете внутренний номер, чтобы связаться с конкретным человеком или отделом.
+
+Существует 65535 IP-портов, но сервер обычно обрабатывает запросы, поступающие только на один из них. Это как сказать оператору телефонной комнаты, что мы сейчас на месте и готовы отвечать на звонки по определённому внутреннему номеру. Мы используем man:bind[2], чтобы указать сокетам, на каком порту мы хотим обслуживать запросы.
+
+[.programlisting]
+....
+int bind(int s, const struct sockaddr *addr, socklen_t addrlen);
+....
+
+Помимо указания порта в `addr`, сервер может включать свой IP-адрес. Однако он может просто использовать символическую константу INADDR_ANY, чтобы указать, что будет обслуживать все запросы на указанный порт, независимо от его IP-адреса. Этот символ, наряду с несколькими аналогичными, объявлен в [.filename]#netinet/in.h#
+
+[.programlisting]
+....
+#define INADDR_ANY (u_int32_t)0x00000000
+....
+
+Предположим, мы пишем сервер для протокола _daytime_ поверх TCP/IP. Напомним, что он использует порт 13. Наша структура `sockaddr_in` будет выглядеть так:
+
+.Пример sockaddr_in сервера
+image::sainserv.png[]
+
+[[sockets-listen]]
+===== `listen`
+
+Продолжая аналогию с офисным телефоном, после того как вы сообщили оператору АТС, на каком внутреннем номере вы будете находиться, вы заходите в свой офис и убеждаетесь, что ваш телефон подключен и звонок включен. Кроме того, вы активируете функцию ожидания вызова, чтобы слышать звонок даже во время разговора с кем-то.
+
+Сервер обеспечивает все это с помощью функции man:listen[2].
+
+[.programlisting]
+....
+int listen(int s, int backlog);
+....
+
+Здесь переменная `backlog` указывает сокетам, сколько входящих запросов принимать, пока вы заняты обработкой последнего запроса. Другими словами, она определяет максимальный размер очереди ожидающих соединений.
+
+[[sockets-accept]]
+===== `accept`
+
+После того как вы услышите телефонный звонок, вы принимаете вызов, отвечая на звонок. Теперь вы установили соединение с вашим клиентом. Это соединение остается активным, пока вы или ваш клиент не повесите трубку.
+
+Сервер принимает соединение, используя функцию man:accept[2].
+
+[.programlisting]
+....
+int accept(int s, struct sockaddr *addr, socklen_t *addrlen);
+....
+
+Обратите внимание, что в этот раз `addrlen` является указателем. Это необходимо, потому что в данном случае именно сокет заполняет структуру `addr` — `sockaddr_in`.
+
+Возвращаемое значение является целым числом. Действительно, `accept` возвращает _новый сокет_. Этот новый сокет будет использоваться для обмена данными с клиентом.
+
+Что происходит со старым сокетом? Он продолжает ожидать новые запросы (помните переменную `backlog`, которую мы передали в `listen`?), пока мы не закроем его (`close`).
+
+Теперь новый сокет предназначен только для обмена данными. Он полностью подключен. Мы не можем снова передать его в `listen`, чтобы принимать дополнительные соединения.
+
+[[sockets-first-server]]
+===== Наш первый сервер
+
+Наш первый сервер будет несколько сложнее, чем первый клиент: нам нужно не только использовать больше функций сокетов, но и написать его как демон.
+
+Это лучше всего достигается созданием _дочернего процесса_ после привязки порта. Затем основной процесс завершается и возвращает управление оболочке (или любой другой программе, которая его вызвала).
+
+Дочерний процесс вызывает `listen`, затем запускает бесконечный цикл, который принимает соединение, обслуживает его и в конечном итоге закрывает свой сокет.
+
+[.programlisting]
+....
+/*
+ * daytimed - a port 13 server
+ *
+ * Programmed by G. Adam Stanislav
+ * June 19, 2001
+ */
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#define BACKLOG 4
+
+int main() {
+ int s, c;
+ socklen_t b;
+ struct sockaddr_in sa;
+ time_t t;
+ struct tm *tm;
+ FILE *client;
+
+ if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("socket");
+ return 1;
+ }
+
+ memset(&sa, '\0', sizeof(sa));
+
+ sa.sin_family = AF_INET;
+ sa.sin_port = htons(13);
+
+ if (INADDR_ANY)
+ sa.sin_addr.s_addr = htonl(INADDR_ANY);
+
+ if (bind(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
+ perror("bind");
+ return 2;
+ }
+
+ switch (fork()) {
+ case -1:
+ perror("fork");
+ return 3;
+ default:
+ close(s);
+ return 0;
+ case 0:
+ break;
+ }
+
+ listen(s, BACKLOG);
+
+ for (;;) {
+ b = sizeof sa;
+
+ if ((c = accept(s, (struct sockaddr *)&sa, &b)) < 0) {
+ perror("daytimed accept");
+ return 4;
+ }
+
+ if ((client = fdopen(c, "w")) == NULL) {
+ perror("daytimed fdopen");
+ return 5;
+ }
+
+ if ((t = time(NULL)) < 0) {
+ perror("daytimed time");
+ return 6;
+ }
+
+ tm = gmtime(&t);
+ fprintf(client, "%.4i-%.2i-%.2iT%.2i:%.2i:%.2iZ\n",
+ tm->tm_year + 1900,
+ tm->tm_mon + 1,
+ tm->tm_mday,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec);
+
+ fclose(client);
+ }
+}
+....
+
+Начинаем с создания сокета. Затем заполняем структуру `sockaddr_in` в `sa`. Обратите внимание на условное использование INADDR_ANY:
+
+[.programlisting]
+....
+if (INADDR_ANY)
+ sa.sin_addr.s_addr = htonl(INADDR_ANY);
+....
+
+Его значение равно `0`. Поскольку мы только что использовали `bzero` для всей структуры, будет избыточным снова устанавливать его в `0`. Но если мы перенесем наш код на другую систему, где INADDR_ANY, возможно, не равен нулю, нам нужно будет присвоить его `sa.sin_addr.s_addr`. Большинство современных компиляторов C достаточно умны, чтобы заметить, что INADDR_ANY — это константа. Пока она равна нулю, они оптимизируют все условное выражение из кода.
+
+После успешного вызова `bind` мы готовы стать _демоном_: используем `fork` для создания дочернего процесса. В обоих процессах, родительском и дочернем, переменная `s` является нашим сокетом. Родительскому процессу он больше не нужен, поэтому он вызывает `close`, затем возвращает `0`, чтобы сообщить своему родителю об успешном завершении.
+
+Между тем, дочерний процесс продолжает работать в фоновом режиме. Он вызывает `listen` и устанавливает размер очереди ожидания (`backlog`) равным `4`. Здесь не требуется большое значение, так как _daytime_ — это не протокол, который часто запрашивают клиенты, и, кроме того, он может мгновенно обрабатывать каждый запрос.
+
+Наконец, демон запускает бесконечный цикл, который выполняет следующие шаги:
+
+[.procedure]
+. Вызовите `accept`. Он ожидает здесь, пока клиент не свяжется с ним. В этот момент он получает новый сокет, `c`, который можно использовать для обмена данными с этим конкретным клиентом.
+. Он использует функцию C `fdopen` для преобразования сокета из низкоуровневого _дескриптора файла_ в указатель типа `FILE` в стиле C. Это позволит в дальнейшем использовать `fprintf`.
+. Он проверяет время и выводит его в формате _ISO 8601_ в «файл» `client`. Затем он использует `fclose` для закрытия файла. Это также автоматически закроет сокет.
+
+Мы можем _обобщить_ это и использовать в качестве модели для многих других серверов:
+
+.Последовательный Сервер
+image::serv.png[]
+
+Эта блок-схема подходит для _последовательных серверов_, то есть серверов, которые могут обслуживать одного клиента за раз, как это было возможно с нашим _daytime_ сервером. Это возможно только в тех случаях, когда между клиентом и сервером не происходит реального "диалога": как только сервер обнаруживает подключение клиента, он отправляет некоторые данные и закрывает соединение. Вся операция может занять наносекунды, и она завершена.
+
+Преимущество этой блок-схемы в том, что, за исключением короткого момента после того, как родительский процесс выполняет ``fork`` и до его завершения, всегда активен только один _процесс_: Наш сервер не занимает много памяти и других системных ресурсов.
+
+Обратите внимание, что мы добавили _инициализацию демона_ в нашу блок-схему. Нам не нужно было инициализировать собственный демон, но это подходящее место в потоке выполнения программы для настройки обработчиков `signal`, открытия необходимых файлов и т. д.
+
+Почти все элементы блок-схемы могут быть использованы буквально на множестве различных серверов. Элемент _serve_ является исключением. Мы рассматриваем его как _"чёрный ящик"_, то есть нечто, что вы проектируете специально для своего сервера и просто "подключаете к остальной системе."
+
+Не все протоколы настолько просты. Многие получают запрос от клиента, отвечают на него, а затем получают ещё один запрос от того же клиента. В результате, они не знают заранее, как долго будут обслуживать клиента. Такие серверы обычно запускают новый процесс для каждого клиента. Пока новый процесс обслуживает своего клиента, демон может продолжать прослушивать новые подключения.
+
+Теперь сохраните приведённый исходный код в файл [.filename]#daytimed.c# (обычно имена демонов оканчиваются буквой `d`). После компиляции попробуйте запустить его:
+
+[source, bash]
+....
+% ./daytimed
+bind: Permission denied
+%
+....
+
+Что произошло? Как вы помните, протокол _daytime_ использует порт 13. Однако все порты ниже 1024 зарезервированы для суперпользователя (в противном случае любой мог бы запустить демон, притворяясь, что обслуживает часто используемый порт, создавая угрозу безопасности).
+
+Попробуйте снова, на этот раз как суперпользователь:
+
+[source, bash]
+....
+# ./daytimed
+#
+....
+
+Что... Ничего? Давайте попробуем еще раз:
+
+[source, bash]
+....
+# ./daytimed
+
+bind: Address already in use
+#
+....
+
+Каждый порт может быть связан только одной программой одновременно. Наша первая попытка действительно была успешной: она запустила дочерний демон и завершилась без ошибок. Он продолжает работать и будет работать до тех пор, пока вы его не завершите командой kill, пока какой-либо из его системных вызовов не завершится с ошибкой или пока вы не перезагрузите систему.
+
+Хорошо, мы знаем, что он работает в фоновом режиме. Но работает ли он? Как мы можем убедиться, что это настоящий сервер _daytime_? Просто:
+
+[source, bash]
+....
+% telnet localhost 13
+
+Trying ::1...
+telnet: connect to address ::1: Connection refused
+Trying 127.0.0.1...
+Connected to localhost.
+Escape character is '^]'.
+2001-06-19T21:04:42Z
+Connection closed by foreign host.
+%
+....
+
+telnet попробовал использовать новый IPv6, но не смог. Затем он повторил попытку с IPv4, и это удалось. Демон работает.
+
+Если у вас есть доступ к другой UNIX(R)-системе через telnet, вы можете использовать её для проверки удалённого доступа к серверу. Мой компьютер не имеет статического IP-адреса, поэтому я сделал следующее:
+
+[source, bash]
+....
+% who
+
+whizkid ttyp0 Jun 19 16:59 (216.127.220.143)
+xxx ttyp1 Jun 19 16:06 (xx.xx.xx.xx)
+% telnet 216.127.220.143 13
+
+Trying 216.127.220.143...
+Connected to r47.bfm.org.
+Escape character is '^]'.
+2001-06-19T21:31:11Z
+Connection closed by foreign host.
+%
+....
+
+Снова, это сработало. Сработает ли это с использованием доменного имени?
+
+[source, bash]
+....
+% telnet r47.bfm.org 13
+
+Trying 216.127.220.143...
+Connected to r47.bfm.org.
+Escape character is '^]'.
+2001-06-19T21:31:40Z
+Connection closed by foreign host.
+%
+....
+
+Кстати, telnet выводит сообщение _Connection closed by foreign host_ после того, как наш демон закрыл сокет. Это показывает, что использование `fclose(client);` в нашем коде действительно работает, как заявлено.
+
+[[sockets-helper-functions]]
+== Вспомогательные функции
+
+Библиотека C в FreeBSD содержит множество вспомогательных функций для программирования сокетов. Например, в нашем примере клиента мы жестко прописали IP-адрес `time.nist.gov`. Но мы не всегда знаем IP-адрес. Даже если знаем, наше программное обеспечение будет более гибким, если позволит пользователю ввести IP-адрес или даже доменное имя.
+
+[[sockets-gethostbyname]]
+=== `gethostbyname`
+
+Хотя нет возможности передать имя домена напрямую в какие-либо функции сокетов, стандартная библиотека C в FreeBSD предоставляет функции man:gethostbyname[3] и man:gethostbyname2[3], объявленные в [.filename]#netdb.h#.
+
+[.programlisting]
+....
+struct hostent * gethostbyname(const char *name);
+struct hostent * gethostbyname2(const char *name, int af);
+....
+
+Оба возвращают указатель на структуру `hostent`, содержащую много информации о домене. Для наших целей поле `h_addr_list[0]` структуры указывает на `h_length` байтов правильного адреса, уже сохранённого в _порядке байтов сети_.
+
+Это позволяет нам создать гораздо более гибкую — и гораздо более полезную — версию нашей программы daytime:
+
+[.programlisting]
+....
+/*
+ * daytime.c
+ *
+ * Programmed by G. Adam Stanislav
+ * 19 June 2001
+ */
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netdb.h>
+
+int main(int argc, char *argv[]) {
+ int s, bytes;
+ struct sockaddr_in sa;
+ struct hostent *he;
+ char buf[BUFSIZ+1];
+ char *host;
+
+ if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
+ perror("socket");
+ return 1;
+ }
+
+ memset(&sa, '\0', sizeof(sa));
+
+ sa.sin_family = AF_INET;
+ sa.sin_port = htons(13);
+
+ host = (argc > 1) ? argv[1] : "time.nist.gov";
+
+ if ((he = gethostbyname(host)) == NULL) {
+ herror(host);
+ return 2;
+ }
+
+ memcpy(&sa.sin_addr, he->h_addr_list[0], he->h_length);
+
+ if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
+ perror("connect");
+ return 3;
+ }
+
+ while ((bytes = read(s, buf, BUFSIZ)) > 0)
+ write(1, buf, bytes);
+
+ close(s);
+ return 0;
+}
+....
+
+Теперь мы можем ввести доменное имя (или IP-адрес, это работает в обоих направлениях) в командной строке, и программа попытается подключиться к его серверу _daytime_. В противном случае, по умолчанию будет использоваться `time.nist.gov`. Однако даже в этом случае мы будем использовать `gethostbyname` вместо жесткого задания `192.43.244.18`. Таким образом, даже если его IP-адрес изменится в будущем, мы всё равно сможем его найти.
+
+Поскольку получение времени от локального сервера занимает практически нулевое время, вы можете запустить daytime дважды подряд: сначала для получения времени от `time.nist.gov`, а затем от вашей собственной системы. После этого вы можете сравнить результаты и увидеть, насколько точны часы вашей системы:
+
+[source, bash]
+....
+% daytime ; daytime localhost
+
+52080 01-06-20 04:02:33 50 0 0 390.2 UTC(NIST) *
+2001-06-20T04:02:35Z
+%
+....
+
+Как видно, моя система опережала время NIST на две секунды.
+
+[[sockets-getservbyname]]
+=== `getservbyname`
+
+Иногда вы можете быть не уверены, какой порт использует определённая служба. В таких случаях очень полезна функция man:getservbyname[3], также объявленная в [.filename]#netdb.h#:
+
+[.programlisting]
+....
+struct servent * getservbyname(const char *name, const char *proto);
+....
+
+Структура `servent` содержит `s_port`, в котором находится соответствующий порт, уже в _порядке байтов сети_.
+
+Если бы мы не знали правильный порт для службы _daytime_, мы могли бы найти его следующим образом:
+
+[.programlisting]
+....
+struct servent *se;
+ ...
+ if ((se = getservbyname("daytime", "tcp")) == NULL {
+ fprintf(stderr, "Cannot determine which port to use.\n");
+ return 7;
+ }
+ sa.sin_port = se->s_port;
+....
+
+Обычно порт известен. Но если вы разрабатываете новый протокол, вы можете тестировать его на неофициальном порту. Когда-нибудь вы зарегистрируете протокол и его порт (если не где-то ещё, то хотя бы в вашем [.filename]#/etc/services#, где `getservbyname` ищет). Вместо возврата ошибки в приведённом выше коде вы просто используете временный номер порта. Как только вы добавите протокол в [.filename]#/etc/services#, ваше программное обеспечение найдёт его порт без необходимости переписывать код.
+
+[[sockets-concurrent-servers]]
+== Многозадачные серверы
+
+В отличие от последовательного сервера, _многозадачный сервер_ должен иметь возможность обслуживать более одного клиента одновременно. Например, _сервер чата_ может обслуживать конкретного клиента часами — он не может ждать, пока закончит обслуживать текущего клиента, прежде чем перейти к следующему.
+
+Это требует значительных изменений в нашей блок-схеме:
+
+.Многозадачный сервер
+image::serv2.png[]
+
+Мы переместили _службу_ из _демона_ в её собственный _серверный процесс_. Однако, поскольку каждый дочерний процесс наследует все открытые файлы (а сокет обрабатывается так же, как файл), новый процесс наследует не только _"принятый дескриптор"_, т.е. сокет, возвращённый вызовом `accept`, но и _главный сокет_, т.е. тот, который был открыт главным процессом в самом начале.
+
+Однако _серверному процессу_ этот сокет не нужен, и он должен немедленно вызвать ему `close`. Аналогично, _демону_ больше не нужен _сокет, принятый вызовом accept_, и он не только должен, но и _обязан_ вызвать ему `close` — в противном случае рано или поздно закончатся доступные _файловые дескрипторы_.
+
+После завершения обслуживания _серверного процесса_ он должен закрыть _принятый сокет_. Вместо возврата к `accept`, процесс теперь завершается.
+
+В UNIX(R) процесс на самом деле не _завершается_. Вместо этого он _возвращается_ к своему родителю. Обычно родительский процесс ``ждёт`` (wait) завершения своего дочернего процесса и получает возвращаемое значение. Однако наш _демон-процесс_ не может просто остановиться и ждать. Это бы свело на нет всю цель создания дополнительных процессов. Но если он никогда не выполняет `wait`, его дочерние процессы станут _зомби_ — более не функционирующими, но всё ещё бродящими вокруг.
+
+По этой причине _демону_ необходимо установить _обработчики сигналов_ на этапе _инициализации демона_. Как минимум, должен обрабатываться сигнал SIGCHLD, чтобы демон мог удалять зомби-процессы из системы и освобождать занимаемые ими системные ресурсы.
+
+Вот почему наша блок-схема теперь содержит блок _обработки сигналов_, который не соединен с другими блоками. Кстати, многие серверы также обрабатывают SIGHUP и обычно интерпретируют его как сигнал от суперпользователя, указывающий на необходимость перечитать конфигурационные файлы. Это позволяет нам изменять настройки без необходимости завершать и перезапускать эти серверы.
diff --git a/documentation/content/ru/books/developers-handbook/sockets/_index.po b/documentation/content/ru/books/developers-handbook/sockets/_index.po
new file mode 100644
index 0000000000..7136478a70
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/sockets/_index.po
@@ -0,0 +1,3021 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbooksockets_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Yaml Front Matter Hash Value: description
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1
+#, no-wrap
+msgid "FreeBSD Sockets"
+msgstr "Сокеты FreeBSD"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1
+#, no-wrap
+msgid "Chapter 7. Sockets"
+msgstr "Глава 7. Сокеты"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:16
+#, no-wrap
+msgid "Sockets"
+msgstr "Сокеты"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:54
+#, no-wrap
+msgid "Synopsis"
+msgstr "Обзор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:59
+msgid ""
+"BSD sockets take interprocess communications to a new level. It is no "
+"longer necessary for the communicating processes to run on the same "
+"machine. They still _can_, but they do not have to."
+msgstr ""
+"Сокеты BSD выводят межпроцессное взаимодействие на новый уровень. Теперь "
+"взаимодействующие процессы не обязательно должны выполняться на одной "
+"машине. Они всё ещё _могут_, но не обязаны."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:62
+msgid ""
+"Not only do these processes not have to run on the same machine, they do not "
+"have to run under the same operating system. Thanks to BSD sockets, your "
+"FreeBSD software can smoothly cooperate with a program running on a "
+"Macintosh(R), another one running on a Sun(TM) workstation, yet another one "
+"running under Windows(R) 2000, all connected with an Ethernet-based local "
+"area network."
+msgstr ""
+"Не только эти процессы не обязаны выполняться на одной машине, они также "
+"могут работать под разными операционными системами. Благодаря BSD-сокетам, "
+"ваше ПО на FreeBSD может легко взаимодействовать с программой, работающей на "
+"Macintosh(R), другой — на рабочей станции Sun(TM), и ещё одной — под "
+"Windows(R) 2000, при этом все они подключены к локальной сети на основе "
+"Ethernet."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:64
+msgid ""
+"But your software can equally well cooperate with processes running in "
+"another building, or on another continent, inside a submarine, or a space "
+"shuttle."
+msgstr ""
+"Но ваше программное обеспечение может так же эффективно взаимодействовать с "
+"процессами, работающими в другом здании, на другом континенте, внутри "
+"подводной лодки или космического челнока."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:67
+msgid ""
+"It can also cooperate with processes that are not part of a computer (at "
+"least not in the strict sense of the word), but of such devices as printers, "
+"digital cameras, medical equipment. Just about anything capable of digital "
+"communications."
+msgstr ""
+"Он также может взаимодействовать с процессами, которые не являются частью "
+"компьютера (по крайней мере, не в строгом смысле этого слова), а таких "
+"устройств, как принтеры, цифровые камеры, медицинское оборудование. "
+"Практически со всем, что способно к цифровой коммуникации."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:69
+#, no-wrap
+msgid "Networking and Diversity"
+msgstr "Сетевое взаимодействие и разнообразие"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:75
+msgid ""
+"We have already hinted on the _diversity_ of networking. Many different "
+"systems have to talk to each other. And they have to speak the same "
+"language. They also have to _understand_ the same language the same way."
+msgstr ""
+"Мы уже упоминали о _разнообразии_ сетевых технологий. Множество различных "
+"систем должны взаимодействовать друг с другом. И они должны говорить на "
+"одном языке. Также они должны _понимать_ этот язык одинаковым образом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:80
+msgid ""
+"People often think that _body language_ is universal. But it is not. Back "
+"in my early teens, my father took me to Bulgaria. We were sitting at a "
+"table in a park in Sofia, when a vendor approached us trying to sell us some "
+"roasted almonds."
+msgstr ""
+"Часто думают, что _язык тела_ универсален. Но это не так. В ранней юности "
+"отец взял меня с собой в Болгарию. Мы сидели за столиком в парке Софии, "
+"когда к нам подошел продавец, предлагая купить жареный миндаль."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:83
+msgid ""
+"I had not learned much Bulgarian by then, so, instead of saying no, I shook "
+"my head from side to side, the \"universal\" body language for _no_. The "
+"vendor quickly started serving us some almonds."
+msgstr ""
+"Я тогда еще не знал болгарского, поэтому вместо словесного отказа я покачал "
+"головой из стороны в сторону — это «универсальный» язык тела для обозначения "
+"_нет_. Продавец тут же начал угощать нас миндалем."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:91
+msgid ""
+"I then remembered I had been told that in Bulgaria shaking your head "
+"sideways meant _yes_. Quickly, I started nodding my head up and down. The "
+"vendor noticed, took his almonds, and walked away. To an uninformed "
+"observer, I did not change the body language: I continued using the language "
+"of shaking and nodding my head. What changed was the _meaning_ of the body "
+"language. At first, the vendor and I interpreted the same language as "
+"having completely different meaning. I had to adjust my own interpretation "
+"of that language so the vendor would understand."
+msgstr ""
+"Затем я вспомнил, что мне говорили, будто в Болгарии покачивание головой из "
+"стороны в сторону означает _да_. Быстро я начал кивать головой вверх-вниз. "
+"Продавец заметил, взял свои миндалины и ушёл. Для непосвящённого наблюдателя "
+"я не изменил язык тела: я продолжал использовать движения головой — "
+"покачивание и кивание. Изменился _смысл_ языка тела. Сначала продавец и я "
+"интерпретировали одни и те же жесты как имеющие совершенно разный смысл. Мне "
+"пришлось скорректировать свою собственную интерпретацию этих жестов, чтобы "
+"продавец меня понял."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:95
+msgid ""
+"It is the same with computers: The same symbols may have different, even "
+"outright opposite meaning. Therefore, for two computers to understand each "
+"other, they must not only agree on the same _language_, but on the same "
+"_interpretation_ of the language."
+msgstr ""
+"То же самое и с компьютерами: одни и те же символы могут иметь разное, даже "
+"полностью противоположное значение. Поэтому, чтобы два компьютера понимали "
+"друг друга, они должны договориться не только об одном _языке_, но и об "
+"одном _толковании_ языка."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:97
+#, no-wrap
+msgid "Protocols"
+msgstr "Протоколы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:104
+msgid ""
+"While various programming languages tend to have complex syntax and use a "
+"number of multi-letter reserved words (which makes them easy for the human "
+"programmer to understand), the languages of data communications tend to be "
+"very terse. Instead of multi-byte words, they often use individual _bits_. "
+"There is a very convincing reason for it: While data travels _inside_ your "
+"computer at speeds approaching the speed of light, it often travels "
+"considerably slower between two computers."
+msgstr ""
+"В то время как различные языки программирования обычно имеют сложный "
+"синтаксис и используют множество многосимвольных зарезервированных слов (что "
+"облегчает их понимание для человека-программиста), языки передачи данных, "
+"как правило, очень лаконичны. Вместо многосимвольных слов они часто "
+"используют отдельные _биты_. Для этого есть очень убедительная причина: хотя "
+"данные внутри вашего компьютера передаются со скоростью, близкой к скорости "
+"света, между двумя компьютерами они часто передаются значительно медленнее."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:106
+msgid ""
+"As the languages used in data communications are so terse, we usually refer "
+"to them as _protocols_ rather than languages."
+msgstr ""
+"Поскольку языки, используемые в передаче данных, настолько лаконичны, мы "
+"обычно называем их _протоколами_, а не языками."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:111
+msgid ""
+"As data travels from one computer to another, it always uses more than one "
+"protocol. These protocols are _layered_. The data can be compared to the "
+"inside of an onion: You have to peel off several layers of \"skin\" to get "
+"to the data. This is best illustrated with a picture:"
+msgstr ""
+"При передаче данных от одного компьютера к другому всегда используется более "
+"одного протокола. Эти протоколы _располагаются слоями_. Данные можно "
+"сравнить с внутренней частью лука: необходимо снять несколько слоёв «кожи», "
+"чтобы добраться до данных. Это лучше всего проиллюстрировано на рисунке:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:112
+#, no-wrap
+msgid "Protocol Layers"
+msgstr "Уровни протоколов"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:113
+#, no-wrap
+msgid "layers.png"
+msgstr "layers.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:116
+msgid ""
+"In this example, we are trying to get an image from a web page we are "
+"connected to via an Ethernet."
+msgstr ""
+"В этом примере мы пытаемся получить изображение с веб-страницы, к которой "
+"подключены через Ethernet."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:119
+msgid ""
+"The image consists of raw data, which is simply a sequence of RGB values "
+"that our software can process, i.e., convert into an image and display on "
+"our monitor."
+msgstr ""
+"Изображение состоит из необработанных данных, которые представляют собой "
+"просто последовательность значений RGB, которые наше программное обеспечение "
+"может обработать, т.е. преобразовать в изображение и отобразить на нашем "
+"мониторе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:124
+msgid ""
+"Alas, our software has no way of knowing how the raw data is organized: Is "
+"it a sequence of RGB values, or a sequence of grayscale intensities, or "
+"perhaps of CMYK encoded colors? Is the data represented by 8-bit quanta, or "
+"are they 16 bits in size, or perhaps 4 bits? How many rows and columns does "
+"the image consist of? Should certain pixels be transparent?"
+msgstr ""
+"Увы, наше программное обеспечение не может определить, как организованы "
+"сырые данные: это последовательность значений RGB, последовательность "
+"интенсивностей в градациях серого или, возможно, цвета в кодировке CMYK? "
+"Представлены ли данные 8-битными квантами, или они имеют размер 16 бит, а "
+"может быть, 4 бита? Из скольких строк и столбцов состоит изображение? Должны "
+"ли определённые пиксели быть прозрачными?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:126
+msgid "I think you get the picture..."
+msgstr "Я думаю, вы поняли..."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:129
+msgid ""
+"To inform our software how to handle the raw data, it is encoded as a PNG "
+"file. It could be a GIF, or a JPEG, but it is a PNG."
+msgstr ""
+"Чтобы наше программное обеспечение понимало, как обрабатывать сырые данные, "
+"они кодируются в формате PNG. Это мог бы быть GIF или JPEG, но выбран PNG."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:131
+msgid "And PNG is a protocol."
+msgstr "И PNG — это протокол."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:133
+msgid ""
+"At this point, I can hear some of you yelling, _\"No, it is not! It is a "
+"file format!\"_"
+msgstr ""
+"В этот момент я слышу, как некоторые из вас кричат: _\"Нет, это не так! Это "
+"формат файла!\"_"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:138
+msgid ""
+"Well, of course it is a file format. But from the perspective of data "
+"communications, a file format is a protocol: The file structure is a "
+"_language_, a terse one at that, communicating to our _process_ how the data "
+"is organized. Ergo, it is a _protocol_."
+msgstr ""
+"Ну что ж, конечно, это формат файла. Но с точки зрения передачи данных, "
+"формат файла — это протокол: структура файла — это _язык_, причем "
+"лаконичный, сообщающий нашему _процессу_, как организованы данные. "
+"Следовательно, это _протокол_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:141
+msgid ""
+"Alas, if all we received was the PNG file, our software would be facing a "
+"serious problem: How is it supposed to know the data is representing an "
+"image, as opposed to some text, or perhaps a sound, or what not? Secondly, "
+"how is it supposed to know the image is in the PNG format as opposed to GIF, "
+"or JPEG, or some other image format?"
+msgstr ""
+"Увы, если бы мы получили только PNG-файл, наше программное обеспечение "
+"столкнулось бы с серьёзной проблемой: как ему узнать, что данные "
+"представляют изображение, а не текст, звук или что-то ещё? Во-вторых, как "
+"ему определить, что изображение сохранено в формате PNG, а не GIF, JPEG или "
+"каком-либо другом формате изображений?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:145
+msgid ""
+"To obtain that information, we are using another protocol: HTTP. This "
+"protocol can tell us exactly that the data represents an image, and that it "
+"uses the PNG protocol. It can also tell us some other things, but let us "
+"stay focused on protocol layers here."
+msgstr ""
+"Для получения этой информации мы используем другой протокол: HTTP. Этот "
+"протокол может точно сообщить нам, что данные представляют изображение и "
+"используют протокол PNG. Он также может сообщить некоторые другие сведения, "
+"но давайте сосредоточимся на уровнях протоколов здесь."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:148
+msgid ""
+"So, now we have some data wrapped in the PNG protocol, wrapped in the HTTP "
+"protocol. How did we get it from the server?"
+msgstr ""
+"Итак, теперь у нас есть некоторые данные, упакованные в протокол PNG, "
+"который в свою очередь упакован в протокол HTTP. Как мы получили их с "
+"сервера?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:152
+msgid ""
+"By using TCP/IP over Ethernet, that is how. Indeed, that is three more "
+"protocols. Instead of continuing inside out, I am now going to talk about "
+"Ethernet, simply because it is easier to explain the rest that way."
+msgstr ""
+"Используя TCP/IP поверх Ethernet, вот как. Действительно, это ещё три "
+"протокола. Вместо того чтобы продолжать изнутри наружу, я теперь расскажу "
+"про Ethernet, просто потому что так проще объяснить остальное."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:156
+msgid ""
+"Ethernet is an interesting system of connecting computers in a _local area "
+"network_ (LAN). Each computer has a _network interface card_ (NIC), which "
+"has a unique 48-bit ID called its _address_. No two Ethernet NICs in the "
+"world have the same address."
+msgstr ""
+"Ethernet — это интересная система соединения компьютеров в _локальной сети_ "
+"(LAN). У каждого компьютера есть _карта сетевого интерфейса_ (NIC — Network "
+"Interface Card) с уникальным 48-битным идентификатором, называемым "
+"_адресом_. Не существует двух сетевых интерфейсов Ethernet в мире с "
+"одинаковым адресом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:162
+msgid ""
+"These NICs are all connected with each other. Whenever one computer wants "
+"to communicate with another in the same Ethernet LAN, it sends a message "
+"over the network. Every NIC sees the message. But as part of the Ethernet "
+"_protocol_, the data contains the address of the destination NIC (among "
+"other things). So, only one of all the network interface cards will pay "
+"attention to it, the rest will ignore it."
+msgstr ""
+"Эти сетевые карты соединены между собой. Когда один компьютер хочет "
+"связаться с другим в той же локальной сети Ethernet, он отправляет сообщение "
+"по сети. Каждая сетевая карта видит это сообщение. Однако, согласно "
+"_протоколу_ Ethernet, данные содержат адрес сетевой карты назначения (среди "
+"прочего). Таким образом, только одна из всех сетевых карт обратит на него "
+"внимание, остальные проигнорируют его."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:166
+msgid ""
+"But not all computers are connected to the same network. Just because we "
+"have received the data over our Ethernet does not mean it originated in our "
+"own local area network. It could have come to us from some other network "
+"(which may not even be Ethernet based) connected with our own network via "
+"the Internet."
+msgstr ""
+"Но не все компьютеры подключены к одной сети. Тот факт, что мы получили "
+"данные через наш Ethernet, не означает, что они возникли в нашей локальной "
+"сети. Они могли попасть к нам из другой сети (которая может быть даже не на "
+"основе Ethernet), соединённой с нашей сетью через Интернет."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:170
+msgid ""
+"All data is transferred over the Internet using IP, which stands for "
+"_Internet Protocol_. Its basic role is to let us know where in the world "
+"the data has arrived from, and where it is supposed to go to. It does not "
+"_guarantee_ we will receive the data, only that we will know where it came "
+"from _if_ we do receive it."
+msgstr ""
+"Все данные передаются через Интернет с использованием IP, что означает "
+"_Internet Protocol_. Его основная роль — сообщать нам, откуда в мире пришли "
+"данные и куда они должны быть направлены. Он не _гарантирует_, что мы "
+"получим данные, только что мы узнаем, откуда они пришли, _если_ мы их "
+"получим."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:173
+msgid ""
+"Even if we do receive the data, IP does not guarantee we will receive "
+"various chunks of data in the same order the other computer has sent it to "
+"us. So, we can receive the center of our image before we receive the upper "
+"left corner and after the lower right, for example."
+msgstr ""
+"Даже если мы получим данные, IP не гарантирует, что различные фрагменты "
+"данных придут в том же порядке, в котором их отправил другой компьютер. "
+"Например, мы можем получить центр нашего изображения до того, как получим "
+"его верхний левый угол, а после — нижний правый."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:175
+msgid ""
+"It is TCP (_Transmission Control Protocol_) that asks the sender to resend "
+"any lost data and that places it all into the proper order."
+msgstr ""
+"Это TCP (_Transmission Control Protocol_), который запрашивает у отправителя "
+"повторную отправку потерянных данных и располагает их в правильном порядке."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:178
+msgid ""
+"All in all, it took _five_ different protocols for one computer to "
+"communicate to another what an image looks like. We received the data "
+"wrapped into the PNG protocol, which was wrapped into the HTTP protocol, "
+"which was wrapped into the TCP protocol, which was wrapped into the IP "
+"protocol, which was wrapped into the Ethernet protocol."
+msgstr ""
+"В итоге потребовалось _пять_ различных протоколов, чтобы один компьютер мог "
+"сообщить другому, как выглядит изображение. Мы получили данные, упакованные "
+"в протокол PNG, который был упакован в протокол HTTP, который был упакован в "
+"протокол TCP, который был упакован в протокол IP, который был упакован в "
+"протокол Ethernet."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:182
+msgid ""
+"Oh, and by the way, there probably were several other protocols involved "
+"somewhere on the way. For example, if our LAN was connected to the Internet "
+"through a dial-up call, it used the PPP protocol over the modem which used "
+"one (or several) of the various modem protocols, et cetera, et cetera, et "
+"cetera..."
+msgstr ""
+"О, и кстати, вероятно, на пути были задействованы и несколько других "
+"протоколов. Например, если наша локальная сеть была подключена к Интернету "
+"через дозвон, то использовался протокол PPP над модемом, который, в свою "
+"очередь, использовал один (или несколько) из различных модемных протоколов, "
+"и так далее, и так далее, и так далее..."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:184
+msgid ""
+"As a developer you should be asking by now, _\"How am I supposed to handle "
+"it all?\"_"
+msgstr ""
+"Как разработчик, вы уже должны задаваться вопросом: _\"Как я должен со всем "
+"этим справляться?\"_"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:189
+msgid ""
+"Luckily for you, you are _not_ supposed to handle it all. You _are_ "
+"supposed to handle some of it, but not all of it. Specifically, you need "
+"not worry about the physical connection (in our case Ethernet and possibly "
+"PPP, etc). Nor do you need to handle the Internet Protocol, or the "
+"Transmission Control Protocol."
+msgstr ""
+"К счастью для вас, вам _не_ нужно разбираться во всём этом. Вам _придётся_ "
+"разобраться в некоторой части, но не во всей. В частности, вам не нужно "
+"беспокоиться о физическом подключении (в нашем случае Ethernet и, возможно, "
+"PPP и т.д.). Также вам не нужно разбираться с протоколом IP или протоколом "
+"TCP."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:192
+msgid ""
+"In other words, you do not have to do anything to receive the data from the "
+"other computer. Well, you do have to _ask_ for it, but that is almost as "
+"simple as opening a file."
+msgstr ""
+"Другими словами, вам не нужно ничего делать, чтобы получить данные с другого "
+"компьютера. Ну, разве что _попросить_ их, но это почти так же просто, как "
+"открыть файл."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:195
+msgid ""
+"Once you have received the data, it is up to you to figure out what to do "
+"with it. In our case, you would need to understand the HTTP protocol and "
+"the PNG file structure."
+msgstr ""
+"Получив данные, вам предстоит решить, что с ними делать. В нашем случае "
+"потребуется понимание протокола HTTP и структуры файла PNG."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:199
+msgid ""
+"To use an analogy, all the internetworking protocols become a gray area: Not "
+"so much because we do not understand how it works, but because we are no "
+"longer concerned about it. The sockets interface takes care of this gray "
+"area for us:"
+msgstr ""
+"Используя аналогию, все межсетевые протоколы становятся серой зоной: не "
+"столько потому, что мы не понимаем, как они работают, а потому, что нас это "
+"больше не беспокоит. Интерфейс сокетов берёт на себя заботу об этой серой "
+"зоне:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:200
+#, no-wrap
+msgid "Sockets Covered Protocol Layers"
+msgstr "Уровни протоколов, покрываемые сокетами"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:201
+#, no-wrap
+msgid "slayers.png"
+msgstr "slayers.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:204
+msgid ""
+"We only need to understand any protocols that tell us how to _interpret the "
+"data_, not how to _receive_ it from another process, nor how to _send_ it to "
+"another process."
+msgstr ""
+"Нам нужно понимать только те протоколы, которые говорят нам, как "
+"_интерпретировать данные_, а не как _получать_ их от другого процесса или "
+"как _передавать_ их другому процессу."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:206
+#, no-wrap
+msgid "The Sockets Model"
+msgstr "Модель сокетов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:211
+msgid ""
+"BSD sockets are built on the basic UNIX(R) model: _Everything is a file._ In "
+"our example, then, sockets would let us receive an _HTTP file_, so to "
+"speak. It would then be up to us to extract the _PNG file_ from it."
+msgstr ""
+"Сокеты BSD построены по базовой модели UNIX(R): _Все является файлом._ Таким "
+"образом, в нашем примере сокеты позволят нам получить, образно говоря, _HTTP-"
+"файл_. Затем нам предстоит извлечь из него _PNG-файл_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:214
+msgid ""
+"Due to the complexity of internetworking, we cannot just use the `open` "
+"system call, or the `open()` C function. Instead, we need to take several "
+"steps to \"opening\" a socket."
+msgstr ""
+"Из-за сложности межсетевого взаимодействия мы не можем просто использовать "
+"системный вызов `open` или функцию `open()` в языке C. Вместо этого "
+"необходимо выполнить несколько шагов для \"открытия\" сокета."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:217
+msgid ""
+"Once we do, however, we can start treating the _socket_ the same way we "
+"treat any _file descriptor_: We can `read` from it, `write` to it, `pipe` "
+"it, and, eventually, `close` it."
+msgstr ""
+"Однако, как только мы это сделаем, мы можем начать обращаться с _сокетом_ "
+"так же, как и с любым _файловым дескриптором_: мы можем `читать` из него, "
+"`писать` в него, передавать его через `канал` и, в конечном итоге, "
+"`закрывать` его."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:219
+#, no-wrap
+msgid "Essential Socket Functions"
+msgstr "Основные функции сокетов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:223
+msgid ""
+"While FreeBSD offers different functions to work with sockets, we only "
+"_need_ four to \"open\" a socket. And in some cases we only need two."
+msgstr ""
+"В то время как FreeBSD предлагает различные функции для работы с сокетами, "
+"нам _требуется_ только четыре, чтобы \"открыть\" сокет. А в некоторых "
+"случаях достаточно двух."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:225
+#, no-wrap
+msgid "The Client-Server Difference"
+msgstr "Разница между клиентом и сервером"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:228
+msgid ""
+"Typically, one of the ends of a socket-based data communication is a "
+"_server_, the other is a _client_."
+msgstr ""
+"Обычно одним из концов связи на основе сокетов является _сервер_, а другой — "
+"_клиент_."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:230
+#, no-wrap
+msgid "The Common Elements"
+msgstr "Общие элементы"
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:233
+#, no-wrap
+msgid "`socket`"
+msgstr "`socket`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:237
+msgid ""
+"The one function used by both, clients and servers, is man:socket[2]. It is "
+"declared this way:"
+msgstr ""
+"Функция, используемая как клиентами, так и серверами, это man:socket[2]. Она "
+"объявляется следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:241
+#, no-wrap
+msgid "int socket(int domain, int type, int protocol);\n"
+msgstr "int socket(int domain, int type, int protocol);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:246
+msgid ""
+"The return value is of the same type as that of `open`, an integer. FreeBSD "
+"allocates its value from the same pool as that of file handles. That is "
+"what allows sockets to be treated the same way as files."
+msgstr ""
+"Возвращаемое значение имеет тот же тип, что и у `open`, целое число. FreeBSD "
+"выделяет его значение из того же пула, что и дескрипторы файлов. Это "
+"позволяет обрабатывать сокеты так же, как файлы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:250
+msgid ""
+"The `domain` argument tells the system what _protocol family_ you want it to "
+"use. Many of them exist, some are vendor specific, others are very common. "
+"They are declared in [.filename]#sys/socket.h#."
+msgstr ""
+"Аргумент `domain` указывает системе, какое _семейство протоколов_ следует "
+"использовать. Существует множество семейств, некоторые из них специфичны для "
+"определённых поставщиков, другие широко распространены. Они объявлены в "
+"[.filename]#sys/socket.h#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:252
+msgid "Use `PF_INET` for UDP, TCP and other Internet protocols (IPv4)."
+msgstr ""
+"Используйте `PF_INET` для UDP, TCP и других интернет-протоколов (IPv4)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:256
+msgid ""
+"Five values are defined for the `type` argument, again, in [.filename]#sys/"
+"socket.h#. All of them start with \"`SOCK_`\". The most common one is "
+"`SOCK_STREAM`, which tells the system you are asking for a _reliable stream "
+"delivery service_ (which is TCP when used with `PF_INET`)."
+msgstr ""
+"Для аргумента `type` определено пять значений, также указанных в "
+"[.filename]#sys/socket.h#. Все они начинаются с \"`SOCK_`\". Наиболее "
+"распространённое — `SOCK_STREAM`, которое указывает системе, что "
+"запрашивается _надёжный сервис потоковой доставки_ (это TCP при "
+"использовании с `PF_INET`)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:258
+msgid ""
+"If you asked for `SOCK_DGRAM`, you would be requesting a _connectionless "
+"datagram delivery service_ (in our case, UDP)."
+msgstr ""
+"Если бы вы запросили `SOCK_DGRAM`, вы бы запросили _сервис доставки "
+"датаграмм без установления соединения_ (в нашем случае, UDP)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:260
+msgid ""
+"If you wanted to be in charge of the low-level protocols (such as IP), or "
+"even network interfaces (e.g., the Ethernet), you would need to specify "
+"`SOCK_RAW`."
+msgstr ""
+"Если вы хотите управлять низкоуровневыми протоколами (такими как IP) или "
+"даже сетевыми интерфейсами (например, Ethernet), вам потребуется указать "
+"`SOCK_RAW`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:263
+msgid ""
+"Finally, the `protocol` argument depends on the previous two arguments, and "
+"is not always meaningful. In that case, use `0` for its value."
+msgstr ""
+"Наконец, аргумент `protocol` зависит от двух предыдущих аргументов и не "
+"всегда имеет смысл. В таком случае используйте значение `0`."
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:265
+#, no-wrap
+msgid "The Unconnected Socket"
+msgstr "Неподключенный сокет"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:269
+msgid ""
+"Nowhere, in the `socket` function have we specified to what other system we "
+"should be connected. Our newly created socket remains _unconnected_."
+msgstr ""
+"Нигде в функции `socket` мы не указали, к какой другой системе должны быть "
+"подключены. Наш только что созданный сокет остаётся _неподключённым_."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:272
+msgid ""
+"This is on purpose: To use a telephone analogy, we have just attached a "
+"modem to the phone line. We have neither told the modem to make a call, nor "
+"to answer if the phone rings."
+msgstr ""
+"Это сделано намеренно: если проводить аналогию с телефоном, мы только что "
+"подключили модем к телефонной линии. Мы не сказали модему совершить звонок "
+"или ответить, если телефон зазвонит."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:275
+#, no-wrap
+msgid "`sockaddr`"
+msgstr "`sockaddr`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:280
+msgid ""
+"Various functions of the sockets family expect the address of (or pointer "
+"to, to use C terminology) a small area of the memory. The various C "
+"declarations in the [.filename]#sys/socket.h# refer to it as `struct "
+"sockaddr`. This structure is declared in the same file:"
+msgstr ""
+"Различные функции семейства сокетов ожидают адрес (или указатель, если "
+"использовать терминологию языка C) небольшой области памяти. Различные "
+"объявления на языке C в файле [.filename]#sys/socket.h# ссылаются на неё как "
+"на `struct sockaddr`. Эта структура объявлена в том же файле:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:293
+#, no-wrap
+msgid ""
+"/*\n"
+" * Structure used by kernel to store most\n"
+" * addresses.\n"
+" */\n"
+"struct sockaddr {\n"
+"\tunsigned char\tsa_len;\t\t/* total length */\n"
+"\tsa_family_t\tsa_family;\t/* address family */\n"
+"\tchar\t\tsa_data[14];\t/* actually longer; address value */\n"
+"};\n"
+"#define\tSOCK_MAXADDRLEN\t255\t\t/* longest possible addresses */\n"
+msgstr ""
+"/*\n"
+" * Structure used by kernel to store most\n"
+" * addresses.\n"
+" */\n"
+"struct sockaddr {\n"
+"\tunsigned char\tsa_len;\t\t/* total length */\n"
+"\tsa_family_t\tsa_family;\t/* address family */\n"
+"\tchar\t\tsa_data[14];\t/* actually longer; address value */\n"
+"};\n"
+"#define\tSOCK_MAXADDRLEN\t255\t\t/* longest possible addresses */\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:297
+msgid ""
+"Please note the _vagueness_ with which the `sa_data` field is declared, just "
+"as an array of `14` bytes, with the comment hinting there can be more than "
+"`14` of them."
+msgstr ""
+"Обратите внимание на _неопределённость_, с которой объявлено поле `sa_data` "
+"— просто как массив из `14` байт, с комментарием, намекающим, что их может "
+"быть больше `14`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:300
+msgid ""
+"This vagueness is quite deliberate. Sockets is a very powerful interface. "
+"While most people perhaps think of it as nothing more than the Internet "
+"interface-and most applications probably use it for that nowadays-sockets "
+"can be used for just about _any_ kind of interprocess communications, of "
+"which the Internet (or, more precisely, IP) is only one."
+msgstr ""
+"Эта неопределенность вполне преднамеренна. Сокеты — это очень мощный "
+"интерфейс. Хотя большинство людей, возможно, считают их не более чем "
+"интерфейсом для Интернета — и большинство приложений, вероятно, используют "
+"их именно для этого в наши дни — сокеты могут быть использованы практически "
+"для _любого_ вида межпроцессного взаимодействия, из которых Интернет (или, "
+"точнее, IP) — лишь один из них."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:303
+msgid ""
+"The [.filename]#sys/socket.h# refers to the various types of protocols "
+"sockets will handle as _address families_, and lists them right before the "
+"definition of `sockaddr`:"
+msgstr ""
+"[.filename]#sys/socket.h# ссылается на различные типы протоколов, с которыми "
+"работают сокеты, как на _семейства адресов_, и перечисляет их "
+"непосредственно перед определением `sockaddr`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:352
+#, no-wrap
+msgid ""
+"/*\n"
+" * Address families.\n"
+" */\n"
+"#define\tAF_UNSPEC\t0\t\t/* unspecified */\n"
+"#define\tAF_LOCAL\t1\t\t/* local to host (pipes, portals) */\n"
+"#define\tAF_UNIX\t\tAF_LOCAL\t/* backward compatibility */\n"
+"#define\tAF_INET\t\t2\t\t/* internetwork: UDP, TCP, etc. */\n"
+"#define\tAF_IMPLINK\t3\t\t/* arpanet imp addresses */\n"
+"#define\tAF_PUP\t\t4\t\t/* pup protocols: e.g. BSP */\n"
+"#define\tAF_CHAOS\t5\t\t/* mit CHAOS protocols */\n"
+"#define\tAF_NS\t\t6\t\t/* XEROX NS protocols */\n"
+"#define\tAF_ISO\t\t7\t\t/* ISO protocols */\n"
+"#define\tAF_OSI\t\tAF_ISO\n"
+"#define\tAF_ECMA\t\t8\t\t/* European computer manufacturers */\n"
+"#define\tAF_DATAKIT\t9\t\t/* datakit protocols */\n"
+"#define\tAF_CCITT\t10\t\t/* CCITT protocols, X.25 etc */\n"
+"#define\tAF_SNA\t\t11\t\t/* IBM SNA */\n"
+"#define AF_DECnet\t12\t\t/* DECnet */\n"
+"#define AF_DLI\t\t13\t\t/* DEC Direct data link interface */\n"
+"#define AF_LAT\t\t14\t\t/* LAT */\n"
+"#define\tAF_HYLINK\t15\t\t/* NSC Hyperchannel */\n"
+"#define\tAF_APPLETALK\t16\t\t/* Apple Talk */\n"
+"#define\tAF_ROUTE\t17\t\t/* Internal Routing Protocol */\n"
+"#define\tAF_LINK\t\t18\t\t/* Link layer interface */\n"
+"#define\tpseudo_AF_XTP\t19\t\t/* eXpress Transfer Protocol (no AF) */\n"
+"#define\tAF_COIP\t\t20\t\t/* connection-oriented IP, aka ST II */\n"
+"#define\tAF_CNT\t\t21\t\t/* Computer Network Technology */\n"
+"#define pseudo_AF_RTIP\t22\t\t/* Help Identify RTIP packets */\n"
+"#define\tAF_IPX\t\t23\t\t/* Novell Internet Protocol */\n"
+"#define\tAF_SIP\t\t24\t\t/* Simple Internet Protocol */\n"
+"#define\tpseudo_AF_PIP\t25\t\t/* Help Identify PIP packets */\n"
+"#define\tAF_ISDN\t\t26\t\t/* Integrated Services Digital Network*/\n"
+"#define\tAF_E164\t\tAF_ISDN\t\t/* CCITT E.164 recommendation */\n"
+"#define\tpseudo_AF_KEY\t27\t\t/* Internal key-management function */\n"
+"#define\tAF_INET6\t28\t\t/* IPv6 */\n"
+"#define\tAF_NATM\t\t29\t\t/* native ATM access */\n"
+"#define\tAF_ATM\t\t30\t\t/* ATM */\n"
+"#define pseudo_AF_HDRCMPLT 31\t\t/* Used by BPF to not rewrite headers\n"
+"\t\t\t\t\t * in interface output routine\n"
+"\t\t\t\t\t */\n"
+"#define\tAF_NETGRAPH\t32\t\t/* Netgraph sockets */\n"
+"#define\tAF_SLOW\t\t33\t\t/* 802.3ad slow protocol */\n"
+"#define\tAF_SCLUSTER\t34\t\t/* Sitara cluster protocol */\n"
+"#define\tAF_ARP\t\t35\n"
+"#define\tAF_BLUETOOTH\t36\t\t/* Bluetooth sockets */\n"
+"#define\tAF_MAX\t\t37\n"
+msgstr ""
+"/*\n"
+" * Address families.\n"
+" */\n"
+"#define\tAF_UNSPEC\t0\t\t/* unspecified */\n"
+"#define\tAF_LOCAL\t1\t\t/* local to host (pipes, portals) */\n"
+"#define\tAF_UNIX\t\tAF_LOCAL\t/* backward compatibility */\n"
+"#define\tAF_INET\t\t2\t\t/* internetwork: UDP, TCP, etc. */\n"
+"#define\tAF_IMPLINK\t3\t\t/* arpanet imp addresses */\n"
+"#define\tAF_PUP\t\t4\t\t/* pup protocols: e.g. BSP */\n"
+"#define\tAF_CHAOS\t5\t\t/* mit CHAOS protocols */\n"
+"#define\tAF_NS\t\t6\t\t/* XEROX NS protocols */\n"
+"#define\tAF_ISO\t\t7\t\t/* ISO protocols */\n"
+"#define\tAF_OSI\t\tAF_ISO\n"
+"#define\tAF_ECMA\t\t8\t\t/* European computer manufacturers */\n"
+"#define\tAF_DATAKIT\t9\t\t/* datakit protocols */\n"
+"#define\tAF_CCITT\t10\t\t/* CCITT protocols, X.25 etc */\n"
+"#define\tAF_SNA\t\t11\t\t/* IBM SNA */\n"
+"#define AF_DECnet\t12\t\t/* DECnet */\n"
+"#define AF_DLI\t\t13\t\t/* DEC Direct data link interface */\n"
+"#define AF_LAT\t\t14\t\t/* LAT */\n"
+"#define\tAF_HYLINK\t15\t\t/* NSC Hyperchannel */\n"
+"#define\tAF_APPLETALK\t16\t\t/* Apple Talk */\n"
+"#define\tAF_ROUTE\t17\t\t/* Internal Routing Protocol */\n"
+"#define\tAF_LINK\t\t18\t\t/* Link layer interface */\n"
+"#define\tpseudo_AF_XTP\t19\t\t/* eXpress Transfer Protocol (no AF) */\n"
+"#define\tAF_COIP\t\t20\t\t/* connection-oriented IP, aka ST II */\n"
+"#define\tAF_CNT\t\t21\t\t/* Computer Network Technology */\n"
+"#define pseudo_AF_RTIP\t22\t\t/* Help Identify RTIP packets */\n"
+"#define\tAF_IPX\t\t23\t\t/* Novell Internet Protocol */\n"
+"#define\tAF_SIP\t\t24\t\t/* Simple Internet Protocol */\n"
+"#define\tpseudo_AF_PIP\t25\t\t/* Help Identify PIP packets */\n"
+"#define\tAF_ISDN\t\t26\t\t/* Integrated Services Digital Network*/\n"
+"#define\tAF_E164\t\tAF_ISDN\t\t/* CCITT E.164 recommendation */\n"
+"#define\tpseudo_AF_KEY\t27\t\t/* Internal key-management function */\n"
+"#define\tAF_INET6\t28\t\t/* IPv6 */\n"
+"#define\tAF_NATM\t\t29\t\t/* native ATM access */\n"
+"#define\tAF_ATM\t\t30\t\t/* ATM */\n"
+"#define pseudo_AF_HDRCMPLT 31\t\t/* Used by BPF to not rewrite headers\n"
+"\t\t\t\t\t * in interface output routine\n"
+"\t\t\t\t\t */\n"
+"#define\tAF_NETGRAPH\t32\t\t/* Netgraph sockets */\n"
+"#define\tAF_SLOW\t\t33\t\t/* 802.3ad slow protocol */\n"
+"#define\tAF_SCLUSTER\t34\t\t/* Sitara cluster protocol */\n"
+"#define\tAF_ARP\t\t35\n"
+"#define\tAF_BLUETOOTH\t36\t\t/* Bluetooth sockets */\n"
+"#define\tAF_MAX\t\t37\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:356
+msgid "The one used for IP is AF_INET. It is a symbol for the constant `2`."
+msgstr "Используемый для IP — это AF_INET. Это символ для константы `2`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:358
+msgid ""
+"It is the _address family_ listed in the `sa_family` field of `sockaddr` "
+"that decides how exactly the vaguely named bytes of `sa_data` will be used."
+msgstr ""
+"Это _семейство адресов_, указанное в поле `sa_family` структуры `sockaddr`, "
+"определяет, как именно будут использоваться нечетко названные байты "
+"`sa_data`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:360
+msgid ""
+"Specifically, whenever the _address family_ is AF_INET, we can use `struct "
+"sockaddr_in` found in [.filename]#netinet/in.h#, wherever `sockaddr` is "
+"expected:"
+msgstr ""
+"В частности, когда _семейство адресов_ — AF_INET, можно использовать `struct "
+"sockaddr_in` из [.filename]#netinet/in.h# везде, где ожидается `sockaddr`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:373
+#, no-wrap
+msgid ""
+"/*\n"
+" * Socket address, internet style.\n"
+" */\n"
+"struct sockaddr_in {\n"
+"\tuint8_t\t\tsin_len;\n"
+"\tsa_family_t\tsin_family;\n"
+"\tin_port_t\tsin_port;\n"
+"\tstruct\tin_addr sin_addr;\n"
+"\tchar\tsin_zero[8];\n"
+"};\n"
+msgstr ""
+"/*\n"
+" * Socket address, internet style.\n"
+" */\n"
+"struct sockaddr_in {\n"
+"\tuint8_t\t\tsin_len;\n"
+"\tsa_family_t\tsin_family;\n"
+"\tin_port_t\tsin_port;\n"
+"\tstruct\tin_addr sin_addr;\n"
+"\tchar\tsin_zero[8];\n"
+"};\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:376
+msgid "We can visualize its organization this way:"
+msgstr "Мы можем визуализировать его организацию следующим образом:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:377
+#, no-wrap
+msgid "sockaddr_in structure"
+msgstr "Структура `sockaddr_in`"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:378
+#, no-wrap
+msgid "sain.png"
+msgstr "sain.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:381
+msgid ""
+"The three important fields are `sin_family`, which is byte 1 of the "
+"structure, `sin_port`, a 16-bit value found in bytes 2 and 3, and "
+"`sin_addr`, a 32-bit integer representation of the IP address, stored in "
+"bytes 4-7."
+msgstr ""
+"Три важных поля — это `sin_family`, которое находится в байте 1 структуры, "
+"`sin_port`, 16-битное значение, расположенное в байтах 2 и 3, и `sin_addr`, "
+"32-битное целочисленное представление IP-адреса, хранящееся в байтах 4–7."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:387
+msgid ""
+"Now, let us try to fill it out. Let us assume we are trying to write a "
+"client for the _daytime_ protocol, which simply states that its server will "
+"write a text string representing the current date and time to port 13. We "
+"want to use TCP/IP, so we need to specify `AF_INET` in the address family "
+"field. `AF_INET` is defined as `2`. Let us use the IP address of "
+"`192.43.244.18`, which is the time server of US federal government "
+"(`time.nist.gov`)."
+msgstr ""
+"Теперь попробуем заполнить его. Предположим, мы пытаемся написать клиент для "
+"протокола _daytime_, который просто указывает, что его сервер записывает "
+"текстовую строку с текущей датой и временем в порт 13. Мы хотим использовать "
+"TCP/IP, поэтому нам нужно указать `AF_INET` в поле семейства адресов. "
+"`AF_INET` определен как `2`. Давайте используем IP-адрес `192.43.244.18`, "
+"который является сервером времени федерального правительства США "
+"(`time.nist.gov`)."
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:388
+#, no-wrap
+msgid "Specific example of sockaddr_in"
+msgstr "Конкретный пример sockaddr_in"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:389
+#, no-wrap
+msgid "sainfill.png"
+msgstr "sainfill.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:392
+msgid ""
+"By the way the `sin_addr` field is declared as being of the `struct in_addr` "
+"type, which is defined in [.filename]#netinet/in.h#:"
+msgstr ""
+"Кстати, поле `sin_addr` объявлено как имеющее тип `struct in_addr`, который "
+"определён в [.filename]#netinet/in.h#:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:401
+#, no-wrap
+msgid ""
+"/*\n"
+" * Internet address (a structure for historical reasons)\n"
+" */\n"
+"struct in_addr {\n"
+"\tin_addr_t s_addr;\n"
+"};\n"
+msgstr ""
+"/*\n"
+" * Internet address (a structure for historical reasons)\n"
+" */\n"
+"struct in_addr {\n"
+"\tin_addr_t s_addr;\n"
+"};\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:404
+msgid "In addition, `in_addr_t` is a 32-bit integer."
+msgstr "В дополнение, `in_addr_t` является 32-битным целым числом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:406
+msgid ""
+"The `192.43.244.18` is just a convenient notation of expressing a 32-bit "
+"integer by listing all of its 8-bit bytes, starting with the _most "
+"significant_ one."
+msgstr ""
+"`192.43.244.18` — это просто удобная форма записи 32-битного целого числа, в "
+"которой перечисляются все его 8-битные байты, начиная с _старшего_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:410
+msgid ""
+"So far, we have viewed `sockaddr` as an abstraction. Our computer does not "
+"store `short` integers as a single 16-bit entity, but as a sequence of 2 "
+"bytes. Similarly, it stores 32-bit integers as a sequence of 4 bytes."
+msgstr ""
+"До сих пор мы рассматривали `sockaddr` как абстракцию. Наш компьютер не "
+"хранит `short` целые числа как единую 16-битную сущность, а как "
+"последовательность 2 байт. Аналогично, он хранит 32-битные целые числа как "
+"последовательность 4 байт."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:412
+msgid "Suppose we coded something like this:"
+msgstr "Предположим, мы написали что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:418
+#, no-wrap
+msgid ""
+"sa.sin_family = AF_INET;\n"
+"sa.sin_port = 13;\n"
+"sa.sin_addr.s_addr = (((((192 << 8) | 43) << 8) | 244) << 8) | 18;\n"
+msgstr ""
+"sa.sin_family = AF_INET;\n"
+"sa.sin_port = 13;\n"
+"sa.sin_addr.s_addr = (((((192 << 8) | 43) << 8) | 244) << 8) | 18;\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:421
+msgid "What would the result look like?"
+msgstr "Как будет выглядеть результат?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:424
+msgid ""
+"Well, that depends, of course. On a Pentium(R), or other x86, based "
+"computer, it would look like this:"
+msgstr ""
+"Ну, это, конечно, зависит от многого. На компьютере с процессором Pentium(R) "
+"или другим на базе x86 это будет выглядеть так:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:425
+#, no-wrap
+msgid "sockaddr_in on an Intel system"
+msgstr "`sockaddr_in` в системе с архитектурой Intel"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:426
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:472
+#, no-wrap
+msgid "sainlsb.png"
+msgstr "sainlsb.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:429
+msgid "On a different system, it might look like this:"
+msgstr "На другой системе это может выглядеть так:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:430
+#, no-wrap
+msgid "sockaddr_in on an MSB system"
+msgstr "`sockaddr_in` в системе с порядком байтов от старшего к младшему"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:431
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:477
+#, no-wrap
+msgid "sainmsb.png"
+msgstr "sainmsb.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:435
+msgid ""
+"And on a PDP it might look different yet. But the above two are the most "
+"common ways in use today."
+msgstr ""
+"И на PDP это может выглядеть иначе. Однако два приведённых выше варианта "
+"являются наиболее распространёнными на сегодняшний день."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:439
+msgid ""
+"Ordinarily, wanting to write portable code, programmers pretend that these "
+"differences do not exist. And they get away with it (except when they code "
+"in assembly language). Alas, you cannot get away with it that easily when "
+"coding for sockets."
+msgstr ""
+"Обычно, стремясь писать переносимый код, программисты делают вид, что этих "
+"различий не существует. И им это сходит с рук (за исключением случаев, когда "
+"они пишут на ассемблере). Увы, при программировании сокетов так легко "
+"отделаться не получится."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:441
+msgid "Why?"
+msgstr "Почему?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:443
+msgid ""
+"Because when communicating with another computer, you usually do not know "
+"whether it stores data _most significant byte_ (MSB) or _least significant "
+"byte_ (LSB) first."
+msgstr ""
+"Потому что при обмене данными с другим компьютером вы обычно не знаете, "
+"хранит ли он данные, начиная со _старшего байта_ (MSB) или с _младшего "
+"байта_ (LSB)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:445
+msgid "You might be wondering, _\"So, will sockets not handle it for me?\"_"
+msgstr ""
+"Вы можете задаться вопросом: _\"Значит, сокеты не будут это делать за меня?"
+"\"_"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:447
+msgid "It will not."
+msgstr "Не будут."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:450
+msgid ""
+"While that answer may surprise you at first, remember that the general "
+"sockets interface only understands the `sa_len` and `sa_family` fields of "
+"the `sockaddr` structure. You do not have to worry about the byte order "
+"there (of course, on FreeBSD `sa_family` is only 1 byte anyway, but many "
+"other UNIX(R) systems do not have `sa_len` and use 2 bytes for `sa_family`, "
+"and expect the data in whatever order is native to the computer)."
+msgstr ""
+"Хотя этот ответ может сначала вас удивить, помните, что общий интерфейс "
+"сокетов понимает только поля `sa_len` и `sa_family` структуры `sockaddr`. "
+"Вам не нужно беспокоиться о порядке байтов (конечно, в FreeBSD `sa_family` "
+"занимает всего 1 байт, но многие другие UNIX(R)-системы не имеют `sa_len` и "
+"используют 2 байта для `sa_family`, ожидая данные в том порядке, который "
+"является родным для компьютера)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:453
+msgid ""
+"But the rest of the data is just `sa_data[14]` as far as sockets goes. "
+"Depending on the _address family_, sockets just forwards that data to its "
+"destination."
+msgstr ""
+"Но остальные данные — это просто `sa_data[14]` с точки зрения сокетов. В "
+"зависимости от _семейства адресов_ сокеты просто передают эти данные по "
+"назначению."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:458
+msgid ""
+"Indeed, when we enter a port number, it is because we want the other "
+"computer to know what service we are asking for. And, when we are the "
+"server, we read the port number so we know what service the other computer "
+"is expecting from us. Either way, sockets only has to forward the port "
+"number as data. It does not interpret it in any way."
+msgstr ""
+"Действительно, когда мы указываем номер порта, это делается для того, чтобы "
+"другая компьютерная система знала, какую службу мы запрашиваем. И, когда мы "
+"выступаем в роли сервера, мы считываем номер порта, чтобы понять, какую "
+"службу ожидает от нас другая система. В любом случае, сокетам нужно лишь "
+"передать номер порта в качестве данных. Они никак его не интерпретируют."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:461
+msgid ""
+"Similarly, we enter the IP address to tell everyone on the way where to send "
+"our data to. Sockets, again, only forwards it as data."
+msgstr ""
+"Аналогично, мы указываем IP-адрес, чтобы сообщить всем на пути, куда "
+"отправлять наши данные. Сокеты, опять же, просто пересылают их как данные."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:463
+msgid ""
+"That is why, we (the _programmers_, not the _sockets_) have to distinguish "
+"between the byte order used by our computer and a conventional byte order to "
+"send the data in to the other computer."
+msgstr ""
+"Вот почему мы (программисты, а не сокеты) должны различать порядок байтов, "
+"используемый нашим компьютером, и условный порядок байтов для отправки "
+"данных на другой компьютер."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:465
+msgid ""
+"We will call the byte order our computer uses the _host byte order_, or just "
+"the _host order_."
+msgstr ""
+"Мы будем называть порядок байтов, который использует наш компьютер, "
+"_порядком байтов хоста_ или просто _хост-порядком_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:468
+msgid ""
+"There is a convention of sending the multi-byte data over IP _MSB first_. "
+"This, we will refer to as the _network byte order_, or simply the _network "
+"order_."
+msgstr ""
+"Существует соглашение о передаче многобайтовых данных по IP _старшим байтом "
+"вперёд_. Это мы будем называть _порядком байтов сети_ или просто _сетевым "
+"порядком_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:470
+msgid ""
+"Now, if we compiled the above code for an Intel based computer, our _host "
+"byte order_ would produce:"
+msgstr ""
+"Вот, если бы мы скомпилировали приведённый выше код для компьютера на базе "
+"Intel, наш _порядок байтов хоста_ выдал бы:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:471
+#, no-wrap
+msgid "Host byte order on an Intel system"
+msgstr "Порядок байтов на хосте в системе Intel"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:475
+msgid "But the _network byte order_ requires that we store the data MSB first:"
+msgstr ""
+"Но порядок байтов в _сетевом формате_ требует, чтобы данные хранились "
+"начиная со старшего байта (MSB):"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:476
+#, no-wrap
+msgid "Network byte order"
+msgstr "Порядок байтов в сети"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:480
+msgid ""
+"Unfortunately, our _host order_ is the exact opposite of the _network order_."
+msgstr ""
+"К сожалению, наш _порядок хоста_ полностью противоположен _порядку сети_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:483
+msgid ""
+"We have several ways of dealing with it. One would be to _reverse_ the "
+"values in our code:"
+msgstr ""
+"У нас есть несколько способов решения этой проблемы. Один из них — "
+"_инвертировать_ значения в нашем коде:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:489
+#, no-wrap
+msgid ""
+"sa.sin_family = AF_INET;\n"
+"sa.sin_port = 13 << 8;\n"
+"sa.sin_addr.s_addr = (((((18 << 8) | 244) << 8) | 43) << 8) | 192;\n"
+msgstr ""
+"sa.sin_family = AF_INET;\n"
+"sa.sin_port = 13 << 8;\n"
+"sa.sin_addr.s_addr = (((((18 << 8) | 244) << 8) | 43) << 8) | 192;\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:494
+msgid ""
+"This will _trick_ our compiler into storing the data in the _network byte "
+"order_. In some cases, this is exactly the way to do it (e.g., when "
+"programming in assembly language). In most cases, however, it can cause a "
+"problem."
+msgstr ""
+"Это _обманет_ наш компилятор, заставив его сохранить данные в _порядке "
+"байтов сети_. В некоторых случаях это именно тот способ, который нужен "
+"(например, при программировании на ассемблере). Однако в большинстве случаев "
+"это может вызвать проблему."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:498
+msgid ""
+"Suppose, you wrote a sockets-based program in C. You know it is going to "
+"run on a Pentium(R), so you enter all your constants in reverse and force "
+"them to the _network byte order_. It works well."
+msgstr ""
+"Предположим, вы написали программу на C, использующую сокеты. Вы знаете, что "
+"она будет работать на Pentium(R), поэтому вводите все константы в обратном "
+"порядке и приводите их к _порядку байтов сети_. Она работает хорошо."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:503
+msgid ""
+"Then, some day, your trusted old Pentium(R) becomes a rusty old Pentium(R). "
+"You replace it with a system whose _host order_ is the same as the _network "
+"order_. You need to recompile all your software. All of your software "
+"continues to perform well, except the one program you wrote."
+msgstr ""
+"Затем, однажды, ваш надежный старый Pentium(R) превращается в ржавый старый "
+"Pentium(R). Вы заменяете его системой, у которой _порядок байтов хоста_ "
+"совпадает с _сетевым порядком байтов_. Вам нужно перекомпилировать все ваше "
+"программное обеспечение. Все ваши программы продолжают работать хорошо, "
+"кроме той одной программы, которую вы написали."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:507
+msgid ""
+"You have since forgotten that you had forced all of your constants to the "
+"opposite of the _host order_. You spend some quality time tearing out your "
+"hair, calling the names of all gods you ever heard of (and some you made "
+"up), hitting your monitor with a nerf bat, and performing all the other "
+"traditional ceremonies of trying to figure out why something that has worked "
+"so well is suddenly not working at all."
+msgstr ""
+"Вы уже забыли, что принудительно задали все свои константы противоположными "
+"_порядку хоста_. Вы проводите некоторое время, яростно рвя на себе волосы, "
+"взывая ко всем известным вам богам (и к некоторым, которых вы придумали), "
+"стуча нерф-битой по монитору и выполняя прочие традиционные ритуалы в "
+"попытке понять, почему то, что работало так хорошо, внезапно перестало "
+"работать вообще."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:509
+msgid ""
+"Eventually, you figure it out, say a couple of swear words, and start "
+"rewriting your code."
+msgstr ""
+"В конце концов, вы разбираетесь в проблеме, произносите пару крепких "
+"словечек и начинаете переписывать свой код."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:512
+msgid ""
+"Luckily, you are not the first one to face the problem. Someone else has "
+"created the man:htons[3] and man:htonl[3] C functions to convert a `short` "
+"and `long` respectively from the _host byte order_ to the _network byte "
+"order_, and the man:ntohs[3] and man:ntohl[3] C functions to go the other "
+"way."
+msgstr ""
+"К счастью, вы не первый, кто столкнулся с этой проблемой. Кто-то уже создал "
+"функции man:htons[3] и man:htonl[3] на языке C для преобразования `short` и "
+"`long` соответственно из _порядка байтов хоста_ в _порядок байтов сети_, а "
+"также функции man:ntohs[3] и man:ntohl[3] на языке C для обратного "
+"преобразования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:515
+msgid ""
+"On _MSB-first_ systems these functions do nothing. On _LSB-first_ systems "
+"they convert values to the proper order."
+msgstr ""
+"На системах с порядком _старший байт первый_ эти функции не выполняют "
+"никаких действий. На системах с порядком _младший байт первый_ они "
+"преобразуют значения в правильный порядок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:517
+msgid ""
+"So, regardless of what system your software is compiled on, your data will "
+"end up in the correct order if you use these functions."
+msgstr ""
+"Итак, независимо от того, на какой системе компилируется ваше программное "
+"обеспечение, ваши данные будут в правильном порядке, если вы используете эти "
+"функции."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:519
+#, no-wrap
+msgid "Client Functions"
+msgstr "Функции клиента"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:524
+msgid ""
+"Typically, the client initiates the connection to the server. The client "
+"knows which server it is about to call: It knows its IP address, and it "
+"knows the _port_ the server resides at. It is akin to you picking up the "
+"phone and dialing the number (the _address_), then, after someone answers, "
+"asking for the person in charge of wingdings (the _port_)."
+msgstr ""
+"Обычно клиент инициирует подключение к серверу. Клиент знает, к какому "
+"серверу он собирается обратиться: он знает его IP-адрес и _порт_, на котором "
+"работает сервер. Это похоже на то, как вы поднимаете трубку и набираете "
+"номер (_адрес_), а затем, когда кто-то отвечает, просите соединить со "
+"специалистом по непонятным символам (_порт_)."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:526
+#, no-wrap
+msgid "`connect`"
+msgstr "`connect`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:529
+msgid ""
+"Once a client has created a socket, it needs to connect it to a specific "
+"port on a remote system. It uses man:connect[2]:"
+msgstr ""
+"Как только клиент создал сокет, ему нужно подключить его к определённому "
+"порту на удалённой системе. Для этого используется man:connect[2]:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:533
+#, no-wrap
+msgid "int connect(int s, const struct sockaddr *name, socklen_t namelen);\n"
+msgstr "int connect(int s, const struct sockaddr *name, socklen_t namelen);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:538
+msgid ""
+"The `s` argument is the socket, i.e., the value returned by the `socket` "
+"function. The `name` is a pointer to `sockaddr`, the structure we have "
+"talked about extensively. Finally, `namelen` informs the system how many "
+"bytes are in our `sockaddr` structure."
+msgstr ""
+"Аргумент `s` — это сокет, то есть значение, возвращаемое функцией `socket`. "
+"Аргумент `name` — это указатель на структуру `sockaddr`, которую мы подробно "
+"обсуждали. Наконец, `namelen` сообщает системе, сколько байт находится в "
+"нашей структуре `sockaddr`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:541
+msgid ""
+"If `connect` is successful, it returns `0`. Otherwise it returns `-1` and "
+"stores the error code in `errno`."
+msgstr ""
+"Если `connect` завершается успешно, он возвращает `0`. В противном случае "
+"возвращается `-1`, а код ошибки сохраняется в `errno`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:545
+msgid ""
+"There are many reasons why `connect` may fail. For example, with an attempt "
+"to an Internet connection, the IP address may not exist, or it may be down, "
+"or just too busy, or it may not have a server listening at the specified "
+"port. Or it may outright _refuse_ any request for specific code."
+msgstr ""
+"Существует множество причин, по которым `connect` может завершиться "
+"неудачей. Например, при попытке подключения к интернету, IP-адрес может не "
+"существовать, быть недоступен, перегружен или на указанном порту может не "
+"быть сервера. Или же подключение может быть явно _отклонено_ по определённым "
+"причинам."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:547
+#, no-wrap
+msgid "Our First Client"
+msgstr "Наш первый клиент"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:550
+msgid ""
+"We now know enough to write a very simple client, one that will get current "
+"time from `192.43.244.18` and print it to [.filename]#stdout#."
+msgstr ""
+"Теперь мы знаем достаточно, чтобы написать очень простого клиента, который "
+"получит текущее время от `192.43.244.18` и выведет его в [.filename]#stdout#."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:564
+#, no-wrap
+msgid ""
+"/*\n"
+" * daytime.c\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+"#include <unistd.h>\n"
+msgstr ""
+"/*\n"
+" * daytime.c\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+"#include <unistd.h>\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:569
+#, no-wrap
+msgid ""
+"int main() {\n"
+" int s, bytes;\n"
+" struct sockaddr_in sa;\n"
+" char buffer[BUFSIZ+1];\n"
+msgstr ""
+"int main() {\n"
+" int s, bytes;\n"
+" struct sockaddr_in sa;\n"
+" char buffer[BUFSIZ+1];\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:574
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:993
+#, no-wrap
+msgid ""
+" if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {\n"
+" perror(\"socket\");\n"
+" return 1;\n"
+" }\n"
+msgstr ""
+" if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {\n"
+" perror(\"socket\");\n"
+" return 1;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:576
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:995
+#, no-wrap
+msgid " memset(&sa, '\\0', sizeof(sa));\n"
+msgstr " memset(&sa, '\\0', sizeof(sa));\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:585
+#, no-wrap
+msgid ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+" sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18);\n"
+" if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"connect\");\n"
+" close(s);\n"
+" return 2;\n"
+" }\n"
+msgstr ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+" sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18);\n"
+" if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"connect\");\n"
+" close(s);\n"
+" return 2;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:588
+#, no-wrap
+msgid ""
+" while ((bytes = read(s, buffer, BUFSIZ)) > 0)\n"
+" write(1, buffer, bytes);\n"
+msgstr ""
+" while ((bytes = read(s, buffer, BUFSIZ)) > 0)\n"
+" write(1, buffer, bytes);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:592
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1019
+#, no-wrap
+msgid ""
+" close(s);\n"
+" return 0;\n"
+"}\n"
+msgstr ""
+" close(s);\n"
+" return 0;\n"
+"}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:595
+msgid ""
+"Go ahead, enter it in your editor, save it as [.filename]#daytime.c#, then "
+"compile and run it:"
+msgstr ""
+"Вперед! Введите это в вашем редакторе, сохраните как [.filename]#daytime.c#, "
+"затем скомпилируйте и запустите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:600
+#, no-wrap
+msgid ""
+"% cc -O3 -o daytime daytime.c\n"
+"% ./daytime\n"
+msgstr ""
+"% cc -O3 -o daytime daytime.c\n"
+"% ./daytime\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:603
+#, no-wrap
+msgid ""
+"52079 01-06-19 02:29:25 50 0 1 543.9 UTC(NIST) *\n"
+"%\n"
+msgstr ""
+"52079 01-06-19 02:29:25 50 0 1 543.9 UTC(NIST) *\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:607
+msgid ""
+"In this case, the date was June 19, 2001, the time was 02:29:25 UTC. "
+"Naturally, your results will vary."
+msgstr ""
+"В данном случае дата была 19 июня 2001 года, время — 02:29:25 UTC. "
+"Естественно, ваши результаты могут отличаться."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:609
+#, no-wrap
+msgid "Server Functions"
+msgstr "Функции сервера"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:615
+msgid ""
+"The typical server does not initiate the connection. Instead, it waits for "
+"a client to call it and request services. It does not know when the client "
+"will call, nor how many clients will call. It may be just sitting there, "
+"waiting patiently, one moment, The next moment, it can find itself swamped "
+"with requests from a number of clients, all calling in at the same time."
+msgstr ""
+"Типичный сервер не инициирует соединение. Вместо этого он ожидает, когда "
+"клиент обратится к нему и запросит услуги. Он не знает, когда клиент "
+"обратится, ни сколько клиентов обратится. В один момент он может просто "
+"спокойно ожидать, а в следующий момент он может оказаться перегруженным "
+"запросами от множества клиентов, обращающихся одновременно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:617
+msgid "The sockets interface offers three basic functions to handle this."
+msgstr ""
+"Интерфейс сокетов предоставляет три основные функции для обработки этого."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:619
+#, no-wrap
+msgid "`bind`"
+msgstr "`bind`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:622
+msgid ""
+"Ports are like extensions to a phone line: After you dial a number, you dial "
+"the extension to get to a specific person or department."
+msgstr ""
+"Порты подобны внутренним номерам телефонной линии: после набора основного "
+"номера вы набираете внутренний номер, чтобы связаться с конкретным человеком "
+"или отделом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:626
+msgid ""
+"There are 65535 IP ports, but a server usually processes requests that come "
+"in on only one of them. It is like telling the phone room operator that we "
+"are now at work and available to answer the phone at a specific extension. "
+"We use man:bind[2] to tell sockets which port we want to serve."
+msgstr ""
+"Существует 65535 IP-портов, но сервер обычно обрабатывает запросы, "
+"поступающие только на один из них. Это как сказать оператору телефонной "
+"комнаты, что мы сейчас на месте и готовы отвечать на звонки по определённому "
+"внутреннему номеру. Мы используем man:bind[2], чтобы указать сокетам, на "
+"каком порту мы хотим обслуживать запросы."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:630
+#, no-wrap
+msgid "int bind(int s, const struct sockaddr *addr, socklen_t addrlen);\n"
+msgstr "int bind(int s, const struct sockaddr *addr, socklen_t addrlen);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:635
+msgid ""
+"Beside specifying the port in `addr`, the server may include its IP "
+"address. However, it can just use the symbolic constant INADDR_ANY to "
+"indicate it will serve all requests to the specified port regardless of what "
+"its IP address is. This symbol, along with several similar ones, is "
+"declared in [.filename]#netinet/in.h#"
+msgstr ""
+"Помимо указания порта в `addr`, сервер может включать свой IP-адрес. Однако "
+"он может просто использовать символическую константу INADDR_ANY, чтобы "
+"указать, что будет обслуживать все запросы на указанный порт, независимо от "
+"его IP-адреса. Этот символ, наряду с несколькими аналогичными, объявлен в "
+"[.filename]#netinet/in.h#"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:639
+#, no-wrap
+msgid "#define\tINADDR_ANY\t\t(u_int32_t)0x00000000\n"
+msgstr "#define\tINADDR_ANY\t\t(u_int32_t)0x00000000\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:644
+msgid ""
+"Suppose we were writing a server for the _daytime_ protocol over TCP/IP. "
+"Recall that it uses port 13. Our `sockaddr_in` structure would look like "
+"this:"
+msgstr ""
+"Предположим, мы пишем сервер для протокола _daytime_ поверх TCP/IP. "
+"Напомним, что он использует порт 13. Наша структура `sockaddr_in` будет "
+"выглядеть так:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:645
+#, no-wrap
+msgid "Example Server sockaddr_in"
+msgstr "Пример sockaddr_in сервера"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:646
+#, no-wrap
+msgid "sainserv.png"
+msgstr "sainserv.png"
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:649
+#, no-wrap
+msgid "`listen`"
+msgstr "`listen`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:653
+msgid ""
+"To continue our office phone analogy, after you have told the phone central "
+"operator what extension you will be at, you now walk into your office, and "
+"make sure your own phone is plugged in and the ringer is turned on. Plus, "
+"you make sure your call waiting is activated, so you can hear the phone ring "
+"even while you are talking to someone."
+msgstr ""
+"Продолжая аналогию с офисным телефоном, после того как вы сообщили оператору "
+"АТС, на каком внутреннем номере вы будете находиться, вы заходите в свой "
+"офис и убеждаетесь, что ваш телефон подключен и звонок включен. Кроме того, "
+"вы активируете функцию ожидания вызова, чтобы слышать звонок даже во время "
+"разговора с кем-то."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:655
+msgid "The server ensures all of that with the man:listen[2] function."
+msgstr "Сервер обеспечивает все это с помощью функции man:listen[2]."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:659
+#, no-wrap
+msgid "int listen(int s, int backlog);\n"
+msgstr "int listen(int s, int backlog);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:663
+msgid ""
+"In here, the `backlog` variable tells sockets how many incoming requests to "
+"accept while you are busy processing the last request. In other words, it "
+"determines the maximum size of the queue of pending connections."
+msgstr ""
+"Здесь переменная `backlog` указывает сокетам, сколько входящих запросов "
+"принимать, пока вы заняты обработкой последнего запроса. Другими словами, "
+"она определяет максимальный размер очереди ожидающих соединений."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:665
+#, no-wrap
+msgid "`accept`"
+msgstr "`accept`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:670
+msgid ""
+"After you hear the phone ringing, you accept the call by answering the "
+"call. You have now established a connection with your client. This "
+"connection remains active until either you or your client hang up."
+msgstr ""
+"После того как вы услышите телефонный звонок, вы принимаете вызов, отвечая "
+"на звонок. Теперь вы установили соединение с вашим клиентом. Это соединение "
+"остается активным, пока вы или ваш клиент не повесите трубку."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:672
+msgid "The server accepts the connection by using the man:accept[2] function."
+msgstr "Сервер принимает соединение, используя функцию man:accept[2]."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:676
+#, no-wrap
+msgid "int accept(int s, struct sockaddr *addr, socklen_t *addrlen);\n"
+msgstr "int accept(int s, struct sockaddr *addr, socklen_t *addrlen);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:680
+msgid ""
+"Note that this time `addrlen` is a pointer. This is necessary because in "
+"this case it is the socket that fills out `addr`, the `sockaddr_in` "
+"structure."
+msgstr ""
+"Обратите внимание, что в этот раз `addrlen` является указателем. Это "
+"необходимо, потому что в данном случае именно сокет заполняет структуру "
+"`addr` — `sockaddr_in`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:684
+msgid ""
+"The return value is an integer. Indeed, the `accept` returns a _new "
+"socket_. You will use this new socket to communicate with the client."
+msgstr ""
+"Возвращаемое значение является целым числом. Действительно, `accept` "
+"возвращает _новый сокет_. Этот новый сокет будет использоваться для обмена "
+"данными с клиентом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:686
+msgid ""
+"What happens to the old socket? It continues to listen for more requests "
+"(remember the `backlog` variable we passed to `listen`?) until we `close` it."
+msgstr ""
+"Что происходит со старым сокетом? Он продолжает ожидать новые запросы "
+"(помните переменную `backlog`, которую мы передали в `listen`?), пока мы не "
+"закроем его (`close`)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:690
+msgid ""
+"Now, the new socket is meant only for communications. It is fully "
+"connected. We cannot pass it to `listen` again, trying to accept additional "
+"connections."
+msgstr ""
+"Теперь новый сокет предназначен только для обмена данными. Он полностью "
+"подключен. Мы не можем снова передать его в `listen`, чтобы принимать "
+"дополнительные соединения."
+
+#. type: Title =====
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:692
+#, no-wrap
+msgid "Our First Server"
+msgstr "Наш первый сервер"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:696
+msgid ""
+"Our first server will be somewhat more complex than our first client was: "
+"Not only do we have more sockets functions to use, but we need to write it "
+"as a daemon."
+msgstr ""
+"Наш первый сервер будет несколько сложнее, чем первый клиент: нам нужно не "
+"только использовать больше функций сокетов, но и написать его как демон."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:699
+msgid ""
+"This is best achieved by creating a _child process_ after binding the port. "
+"The main process then exits and returns control to the shell (or whatever "
+"program invoked it)."
+msgstr ""
+"Это лучше всего достигается созданием _дочернего процесса_ после привязки "
+"порта. Затем основной процесс завершается и возвращает управление оболочке "
+"(или любой другой программе, которая его вызвала)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:701
+msgid ""
+"The child calls `listen`, then starts an endless loop, which accepts a "
+"connection, serves it, and eventually closes its socket."
+msgstr ""
+"Дочерний процесс вызывает `listen`, затем запускает бесконечный цикл, "
+"который принимает соединение, обслуживает его и в конечном итоге закрывает "
+"свой сокет."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:717
+#, no-wrap
+msgid ""
+"/*\n"
+" * daytimed - a port 13 server\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" * June 19, 2001\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <time.h>\n"
+"#include <unistd.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+msgstr ""
+"/*\n"
+" * daytimed - a port 13 server\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" * June 19, 2001\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <time.h>\n"
+"#include <unistd.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:719
+#, no-wrap
+msgid "#define BACKLOG 4\n"
+msgstr "#define BACKLOG 4\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:727
+#, no-wrap
+msgid ""
+"int main() {\n"
+" int s, c;\n"
+" socklen_t b;\n"
+" struct sockaddr_in sa;\n"
+" time_t t;\n"
+" struct tm *tm;\n"
+" FILE *client;\n"
+msgstr ""
+"int main() {\n"
+" int s, c;\n"
+" socklen_t b;\n"
+" struct sockaddr_in sa;\n"
+" time_t t;\n"
+" struct tm *tm;\n"
+" FILE *client;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:732
+#, no-wrap
+msgid ""
+" if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {\n"
+" perror(\"socket\");\n"
+" return 1;\n"
+" }\n"
+msgstr ""
+" if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {\n"
+" perror(\"socket\");\n"
+" return 1;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:734
+#, no-wrap
+msgid " memset(&sa, '\\0', sizeof(sa));\n"
+msgstr " memset(&sa, '\\0', sizeof(sa));\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:737
+#, no-wrap
+msgid ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+msgstr ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:740
+#, no-wrap
+msgid ""
+" if (INADDR_ANY)\n"
+" sa.sin_addr.s_addr = htonl(INADDR_ANY);\n"
+msgstr ""
+" if (INADDR_ANY)\n"
+" sa.sin_addr.s_addr = htonl(INADDR_ANY);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:745
+#, no-wrap
+msgid ""
+" if (bind(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"bind\");\n"
+" return 2;\n"
+" }\n"
+msgstr ""
+" if (bind(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"bind\");\n"
+" return 2;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:756
+#, no-wrap
+msgid ""
+" switch (fork()) {\n"
+" case -1:\n"
+" perror(\"fork\");\n"
+" return 3;\n"
+" default:\n"
+" close(s);\n"
+" return 0;\n"
+" case 0:\n"
+" break;\n"
+" }\n"
+msgstr ""
+" switch (fork()) {\n"
+" case -1:\n"
+" perror(\"fork\");\n"
+" return 3;\n"
+" default:\n"
+" close(s);\n"
+" return 0;\n"
+" case 0:\n"
+" break;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:758
+#, no-wrap
+msgid " listen(s, BACKLOG);\n"
+msgstr " listen(s, BACKLOG);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:761
+#, no-wrap
+msgid ""
+" for (;;) {\n"
+" b = sizeof sa;\n"
+msgstr ""
+" for (;;) {\n"
+" b = sizeof sa;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:766
+#, no-wrap
+msgid ""
+" if ((c = accept(s, (struct sockaddr *)&sa, &b)) < 0) {\n"
+" perror(\"daytimed accept\");\n"
+" return 4;\n"
+" }\n"
+msgstr ""
+" if ((c = accept(s, (struct sockaddr *)&sa, &b)) < 0) {\n"
+" perror(\"daytimed accept\");\n"
+" return 4;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:771
+#, no-wrap
+msgid ""
+" if ((client = fdopen(c, \"w\")) == NULL) {\n"
+" perror(\"daytimed fdopen\");\n"
+" return 5;\n"
+" }\n"
+msgstr ""
+" if ((client = fdopen(c, \"w\")) == NULL) {\n"
+" perror(\"daytimed fdopen\");\n"
+" return 5;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:776
+#, no-wrap
+msgid ""
+" if ((t = time(NULL)) < 0) {\n"
+" perror(\"daytimed time\");\n"
+" return 6;\n"
+" }\n"
+msgstr ""
+" if ((t = time(NULL)) < 0) {\n"
+" perror(\"daytimed time\");\n"
+" return 6;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:785
+#, no-wrap
+msgid ""
+" tm = gmtime(&t);\n"
+" fprintf(client, \"%.4i-%.2i-%.2iT%.2i:%.2i:%.2iZ\\n\",\n"
+" tm->tm_year + 1900,\n"
+" tm->tm_mon + 1,\n"
+" tm->tm_mday,\n"
+" tm->tm_hour,\n"
+" tm->tm_min,\n"
+" tm->tm_sec);\n"
+msgstr ""
+" tm = gmtime(&t);\n"
+" fprintf(client, \"%.4i-%.2i-%.2iT%.2i:%.2i:%.2iZ\\n\",\n"
+" tm->tm_year + 1900,\n"
+" tm->tm_mon + 1,\n"
+" tm->tm_mday,\n"
+" tm->tm_hour,\n"
+" tm->tm_min,\n"
+" tm->tm_sec);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:789
+#, no-wrap
+msgid ""
+" fclose(client);\n"
+" }\n"
+"}\n"
+msgstr ""
+" fclose(client);\n"
+" }\n"
+"}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:794
+msgid ""
+"We start by creating a socket. Then we fill out the `sockaddr_in` structure "
+"in `sa`. Note the conditional use of INADDR_ANY:"
+msgstr ""
+"Начинаем с создания сокета. Затем заполняем структуру `sockaddr_in` в `sa`. "
+"Обратите внимание на условное использование INADDR_ANY:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:799
+#, no-wrap
+msgid ""
+"if (INADDR_ANY)\n"
+" sa.sin_addr.s_addr = htonl(INADDR_ANY);\n"
+msgstr ""
+"if (INADDR_ANY)\n"
+" sa.sin_addr.s_addr = htonl(INADDR_ANY);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:806
+msgid ""
+"Its value is `0`. Since we have just used `bzero` on the entire structure, "
+"it would be redundant to set it to `0` again. But if we port our code to "
+"some other system where INADDR_ANY is perhaps not a zero, we need to assign "
+"it to `sa.sin_addr.s_addr`. Most modern C compilers are clever enough to "
+"notice that INADDR_ANY is a constant. As long as it is a zero, they will "
+"optimize the entire conditional statement out of the code."
+msgstr ""
+"Его значение равно `0`. Поскольку мы только что использовали `bzero` для "
+"всей структуры, будет избыточным снова устанавливать его в `0`. Но если мы "
+"перенесем наш код на другую систему, где INADDR_ANY, возможно, не равен "
+"нулю, нам нужно будет присвоить его `sa.sin_addr.s_addr`. Большинство "
+"современных компиляторов C достаточно умны, чтобы заметить, что INADDR_ANY — "
+"это константа. Пока она равна нулю, они оптимизируют все условное выражение "
+"из кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:810
+msgid ""
+"After we have called `bind` successfully, we are ready to become a _daemon_: "
+"We use `fork` to create a child process. In both, the parent and the child, "
+"the `s` variable is our socket. The parent process will not need it, so it "
+"calls `close`, then it returns `0` to inform its own parent it had "
+"terminated successfully."
+msgstr ""
+"После успешного вызова `bind` мы готовы стать _демоном_: используем `fork` "
+"для создания дочернего процесса. В обоих процессах, родительском и дочернем, "
+"переменная `s` является нашим сокетом. Родительскому процессу он больше не "
+"нужен, поэтому он вызывает `close`, затем возвращает `0`, чтобы сообщить "
+"своему родителю об успешном завершении."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:815
+msgid ""
+"Meanwhile, the child process continues working in the background. It calls "
+"`listen` and sets its backlog to `4`. It does not need a large value here "
+"because _daytime_ is not a protocol many clients request all the time, and "
+"because it can process each request instantly anyway."
+msgstr ""
+"Между тем, дочерний процесс продолжает работать в фоновом режиме. Он "
+"вызывает `listen` и устанавливает размер очереди ожидания (`backlog`) равным "
+"`4`. Здесь не требуется большое значение, так как _daytime_ — это не "
+"протокол, который часто запрашивают клиенты, и, кроме того, он может "
+"мгновенно обрабатывать каждый запрос."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:817
+msgid ""
+"Finally, the daemon starts an endless loop, which performs the following "
+"steps:"
+msgstr ""
+"Наконец, демон запускает бесконечный цикл, который выполняет следующие шаги:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:820
+msgid ""
+"Call `accept`. It waits here until a client contacts it. At that point, it "
+"receives a new socket, `c`, which it can use to communicate with this "
+"particular client."
+msgstr ""
+"Вызовите `accept`. Он ожидает здесь, пока клиент не свяжется с ним. В этот "
+"момент он получает новый сокет, `c`, который можно использовать для обмена "
+"данными с этим конкретным клиентом."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:821
+msgid ""
+"It uses the C function `fdopen` to turn the socket from a low-level _file "
+"descriptor_ to a C-style `FILE` pointer. This will allow the use of "
+"`fprintf` later on."
+msgstr ""
+"Он использует функцию C `fdopen` для преобразования сокета из "
+"низкоуровневого _дескриптора файла_ в указатель типа `FILE` в стиле C. Это "
+"позволит в дальнейшем использовать `fprintf`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:822
+msgid ""
+"It checks the time, and prints it in the _ISO 8601_ format to the `client` "
+"\"file\". It then uses `fclose` to close the file. That will automatically "
+"close the socket as well."
+msgstr ""
+"Он проверяет время и выводит его в формате _ISO 8601_ в «файл» `client`. "
+"Затем он использует `fclose` для закрытия файла. Это также автоматически "
+"закроет сокет."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:824
+msgid "We can _generalize_ this, and use it as a model for many other servers:"
+msgstr ""
+"Мы можем _обобщить_ это и использовать в качестве модели для многих других "
+"серверов:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:825
+#, no-wrap
+msgid "Sequential Server"
+msgstr "Последовательный Сервер"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:826
+#, no-wrap
+msgid "serv.png"
+msgstr "serv.png"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:832
+msgid ""
+"This flowchart is good for _sequential servers_, i.e., servers that can "
+"serve one client at a time, just as we were able to with our _daytime_ "
+"server. This is only possible whenever there is no real \"conversation\" "
+"going on between the client and the server: As soon as the server detects a "
+"connection to the client, it sends out some data and closes the connection. "
+"The entire operation may take nanoseconds, and it is finished."
+msgstr ""
+"Эта блок-схема подходит для _последовательных серверов_, то есть серверов, "
+"которые могут обслуживать одного клиента за раз, как это было возможно с "
+"нашим _daytime_ сервером. Это возможно только в тех случаях, когда между "
+"клиентом и сервером не происходит реального \"диалога\": как только сервер "
+"обнаруживает подключение клиента, он отправляет некоторые данные и закрывает "
+"соединение. Вся операция может занять наносекунды, и она завершена."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:835
+msgid ""
+"The advantage of this flowchart is that, except for the brief moment after "
+"the parent ``fork``s and before it exits, there is always only one _process_ "
+"active: Our server does not take up much memory and other system resources."
+msgstr ""
+"Преимущество этой блок-схемы в том, что, за исключением короткого момента "
+"после того, как родительский процесс выполняет ``fork`` и до его завершения, "
+"всегда активен только один _процесс_: Наш сервер не занимает много памяти и "
+"других системных ресурсов."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:839
+msgid ""
+"Note that we have added _initialize daemon_ in our flowchart. We did not "
+"need to initialize our own daemon, but this is a good place in the flow of "
+"the program to set up any `signal` handlers, open any files we may need, etc."
+msgstr ""
+"Обратите внимание, что мы добавили _инициализацию демона_ в нашу блок-схему. "
+"Нам не нужно было инициализировать собственный демон, но это подходящее "
+"место в потоке выполнения программы для настройки обработчиков `signal`, "
+"открытия необходимых файлов и т. д."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:843
+msgid ""
+"Just about everything in the flow chart can be used literally on many "
+"different servers. The _serve_ entry is the exception. We think of it as a "
+"_\"black box\"_, i.e., something you design specifically for your own "
+"server, and just \"plug it into the rest.\""
+msgstr ""
+"Почти все элементы блок-схемы могут быть использованы буквально на множестве "
+"различных серверов. Элемент _serve_ является исключением. Мы рассматриваем "
+"его как _\"чёрный ящик\"_, то есть нечто, что вы проектируете специально для "
+"своего сервера и просто \"подключаете к остальной системе.\""
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:849
+msgid ""
+"Not all protocols are that simple. Many receive a request from the client, "
+"reply to it, then receive another request from the same client. As a "
+"result, they do not know in advance how long they will be serving the "
+"client. Such servers usually start a new process for each client. While "
+"the new process is serving its client, the daemon can continue listening for "
+"more connections."
+msgstr ""
+"Не все протоколы настолько просты. Многие получают запрос от клиента, "
+"отвечают на него, а затем получают ещё один запрос от того же клиента. В "
+"результате, они не знают заранее, как долго будут обслуживать клиента. Такие "
+"серверы обычно запускают новый процесс для каждого клиента. Пока новый "
+"процесс обслуживает своего клиента, демон может продолжать прослушивать "
+"новые подключения."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:852
+msgid ""
+"Now, go ahead, save the above source code as [.filename]#daytimed.c# (it is "
+"customary to end the names of daemons with the letter `d`). After you have "
+"compiled it, try running it:"
+msgstr ""
+"Теперь сохраните приведённый исходный код в файл [.filename]#daytimed.c# "
+"(обычно имена демонов оканчиваются буквой `d`). После компиляции попробуйте "
+"запустить его:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:858
+#, no-wrap
+msgid ""
+"% ./daytimed\n"
+"bind: Permission denied\n"
+"%\n"
+msgstr ""
+"% ./daytimed\n"
+"bind: Permission denied\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:862
+msgid ""
+"What happened here? As you will recall, the _daytime_ protocol uses port "
+"13. But all ports below 1024 are reserved to the superuser (otherwise, "
+"anyone could start a daemon pretending to serve a commonly used port, while "
+"causing a security breach)."
+msgstr ""
+"Что произошло? Как вы помните, протокол _daytime_ использует порт 13. Однако "
+"все порты ниже 1024 зарезервированы для суперпользователя (в противном "
+"случае любой мог бы запустить демон, притворяясь, что обслуживает часто "
+"используемый порт, создавая угрозу безопасности)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:864
+msgid "Try again, this time as the superuser:"
+msgstr "Попробуйте снова, на этот раз как суперпользователь:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:869
+#, no-wrap
+msgid ""
+"# ./daytimed\n"
+"#\n"
+msgstr ""
+"# ./daytimed\n"
+"#\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:872
+msgid "What... Nothing? Let us try again:"
+msgstr "Что... Ничего? Давайте попробуем еще раз:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:876
+#, no-wrap
+msgid "# ./daytimed\n"
+msgstr "# ./daytimed\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:879
+#, no-wrap
+msgid ""
+"bind: Address already in use\n"
+"#\n"
+msgstr ""
+"bind: Address already in use\n"
+"#\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:884
+msgid ""
+"Every port can only be bound by one program at a time. Our first attempt "
+"was indeed successful: It started the child daemon and returned quietly. It "
+"is still running and will continue to run until you either kill it, or any "
+"of its system calls fail, or you reboot the system."
+msgstr ""
+"Каждый порт может быть связан только одной программой одновременно. Наша "
+"первая попытка действительно была успешной: она запустила дочерний демон и "
+"завершилась без ошибок. Он продолжает работать и будет работать до тех пор, "
+"пока вы его не завершите командой kill, пока какой-либо из его системных "
+"вызовов не завершится с ошибкой или пока вы не перезагрузите систему."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:887
+msgid ""
+"Fine, we know it is running in the background. But is it working? How do we "
+"know it is a proper _daytime_ server? Simple:"
+msgstr ""
+"Хорошо, мы знаем, что он работает в фоновом режиме. Но работает ли он? Как "
+"мы можем убедиться, что это настоящий сервер _daytime_? Просто:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:891
+#, no-wrap
+msgid "% telnet localhost 13\n"
+msgstr "% telnet localhost 13\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:900
+#, no-wrap
+msgid ""
+"Trying ::1...\n"
+"telnet: connect to address ::1: Connection refused\n"
+"Trying 127.0.0.1...\n"
+"Connected to localhost.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:04:42Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+msgstr ""
+"Trying ::1...\n"
+"telnet: connect to address ::1: Connection refused\n"
+"Trying 127.0.0.1...\n"
+"Connected to localhost.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:04:42Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:905
+msgid ""
+"telnet tried the new IPv6, and failed. It retried with IPv4 and succeeded. "
+"The daemon works."
+msgstr ""
+"telnet попробовал использовать новый IPv6, но не смог. Затем он повторил "
+"попытку с IPv4, и это удалось. Демон работает."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:908
+msgid ""
+"If you have access to another UNIX(R) system via telnet, you can use it to "
+"test accessing the server remotely. My computer does not have a static IP "
+"address, so this is what I did:"
+msgstr ""
+"Если у вас есть доступ к другой UNIX(R)-системе через telnet, вы можете "
+"использовать её для проверки удалённого доступа к серверу. Мой компьютер не "
+"имеет статического IP-адреса, поэтому я сделал следующее:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:912
+#, no-wrap
+msgid "% who\n"
+msgstr "% who\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:916
+#, no-wrap
+msgid ""
+"whizkid ttyp0 Jun 19 16:59 (216.127.220.143)\n"
+"xxx ttyp1 Jun 19 16:06 (xx.xx.xx.xx)\n"
+"% telnet 216.127.220.143 13\n"
+msgstr ""
+"whizkid ttyp0 Jun 19 16:59 (216.127.220.143)\n"
+"xxx ttyp1 Jun 19 16:06 (xx.xx.xx.xx)\n"
+"% telnet 216.127.220.143 13\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:923
+#, no-wrap
+msgid ""
+"Trying 216.127.220.143...\n"
+"Connected to r47.bfm.org.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:31:11Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+msgstr ""
+"Trying 216.127.220.143...\n"
+"Connected to r47.bfm.org.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:31:11Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:926
+msgid "Again, it worked. Will it work using the domain name?"
+msgstr ""
+"Снова, это сработало. Сработает ли это с использованием доменного имени?"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:930
+#, no-wrap
+msgid "% telnet r47.bfm.org 13\n"
+msgstr "% telnet r47.bfm.org 13\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:937
+#, no-wrap
+msgid ""
+"Trying 216.127.220.143...\n"
+"Connected to r47.bfm.org.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:31:40Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+msgstr ""
+"Trying 216.127.220.143...\n"
+"Connected to r47.bfm.org.\n"
+"Escape character is '^]'.\n"
+"2001-06-19T21:31:40Z\n"
+"Connection closed by foreign host.\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:941
+msgid ""
+"By the way, telnet prints the _Connection closed by foreign host_ message "
+"after our daemon has closed the socket. This shows us that, indeed, using "
+"`fclose(client);` in our code works as advertised."
+msgstr ""
+"Кстати, telnet выводит сообщение _Connection closed by foreign host_ после "
+"того, как наш демон закрыл сокет. Это показывает, что использование "
+"`fclose(client);` в нашем коде действительно работает, как заявлено."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:943
+#, no-wrap
+msgid "Helper Functions"
+msgstr "Вспомогательные функции"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:949
+msgid ""
+"FreeBSD C library contains many helper functions for sockets programming. "
+"For example, in our sample client we hard coded the `time.nist.gov` IP "
+"address. But we do not always know the IP address. Even if we do, our "
+"software is more flexible if it allows the user to enter the IP address, or "
+"even the domain name."
+msgstr ""
+"Библиотека C в FreeBSD содержит множество вспомогательных функций для "
+"программирования сокетов. Например, в нашем примере клиента мы жестко "
+"прописали IP-адрес `time.nist.gov`. Но мы не всегда знаем IP-адрес. Даже "
+"если знаем, наше программное обеспечение будет более гибким, если позволит "
+"пользователю ввести IP-адрес или даже доменное имя."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:951
+#, no-wrap
+msgid "`gethostbyname`"
+msgstr "`gethostbyname`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:954
+msgid ""
+"While there is no way to pass the domain name directly to any of the sockets "
+"functions, the FreeBSD C library comes with the man:gethostbyname[3] and "
+"man:gethostbyname2[3] functions, declared in [.filename]#netdb.h#."
+msgstr ""
+"Хотя нет возможности передать имя домена напрямую в какие-либо функции "
+"сокетов, стандартная библиотека C в FreeBSD предоставляет функции "
+"man:gethostbyname[3] и man:gethostbyname2[3], объявленные в "
+"[.filename]#netdb.h#."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:959
+#, no-wrap
+msgid ""
+"struct hostent * gethostbyname(const char *name);\n"
+"struct hostent * gethostbyname2(const char *name, int af);\n"
+msgstr ""
+"struct hostent * gethostbyname(const char *name);\n"
+"struct hostent * gethostbyname2(const char *name, int af);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:963
+msgid ""
+"Both return a pointer to the `hostent` structure, with much information "
+"about the domain. For our purposes, the `h_addr_list[0]` field of the "
+"structure points at `h_length` bytes of the correct address, already stored "
+"in the _network byte order_."
+msgstr ""
+"Оба возвращают указатель на структуру `hostent`, содержащую много информации "
+"о домене. Для наших целей поле `h_addr_list[0]` структуры указывает на "
+"`h_length` байтов правильного адреса, уже сохранённого в _порядке байтов "
+"сети_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:965
+msgid ""
+"This allows us to create a much more flexible-and much more useful-version "
+"of our daytime program:"
+msgstr ""
+"Это позволяет нам создать гораздо более гибкую — и гораздо более полезную — "
+"версию нашей программы daytime:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:981
+#, no-wrap
+msgid ""
+"/*\n"
+" * daytime.c\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" * 19 June 2001\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <unistd.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+"#include <netdb.h>\n"
+msgstr ""
+"/*\n"
+" * daytime.c\n"
+" *\n"
+" * Programmed by G. Adam Stanislav\n"
+" * 19 June 2001\n"
+" */\n"
+"#include <stdio.h>\n"
+"#include <string.h>\n"
+"#include <unistd.h>\n"
+"#include <sys/types.h>\n"
+"#include <sys/socket.h>\n"
+"#include <netinet/in.h>\n"
+"#include <netdb.h>\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:988
+#, no-wrap
+msgid ""
+"int main(int argc, char *argv[]) {\n"
+" int s, bytes;\n"
+" struct sockaddr_in sa;\n"
+" struct hostent *he;\n"
+" char buf[BUFSIZ+1];\n"
+" char *host;\n"
+msgstr ""
+"int main(int argc, char *argv[]) {\n"
+" int s, bytes;\n"
+" struct sockaddr_in sa;\n"
+" struct hostent *he;\n"
+" char buf[BUFSIZ+1];\n"
+" char *host;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:998
+#, no-wrap
+msgid ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+msgstr ""
+" sa.sin_family = AF_INET;\n"
+" sa.sin_port = htons(13);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1000
+#, no-wrap
+msgid " host = (argc > 1) ? argv[1] : \"time.nist.gov\";\n"
+msgstr " host = (argc > 1) ? argv[1] : \"time.nist.gov\";\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1005
+#, no-wrap
+msgid ""
+" if ((he = gethostbyname(host)) == NULL) {\n"
+" herror(host);\n"
+" return 2;\n"
+" }\n"
+msgstr ""
+" if ((he = gethostbyname(host)) == NULL) {\n"
+" herror(host);\n"
+" return 2;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1007
+#, no-wrap
+msgid " memcpy(&sa.sin_addr, he->h_addr_list[0], he->h_length);\n"
+msgstr " memcpy(&sa.sin_addr, he->h_addr_list[0], he->h_length);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1012
+#, no-wrap
+msgid ""
+" if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"connect\");\n"
+" return 3;\n"
+" }\n"
+msgstr ""
+" if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {\n"
+" perror(\"connect\");\n"
+" return 3;\n"
+" }\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1015
+#, no-wrap
+msgid ""
+" while ((bytes = read(s, buf, BUFSIZ)) > 0)\n"
+" write(1, buf, bytes);\n"
+msgstr ""
+" while ((bytes = read(s, buf, BUFSIZ)) > 0)\n"
+" write(1, buf, bytes);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1025
+msgid ""
+"We now can type a domain name (or an IP address, it works both ways) on the "
+"command line, and the program will try to connect to its _daytime_ server. "
+"Otherwise, it will still default to `time.nist.gov`. However, even in this "
+"case we will use `gethostbyname` rather than hard coding `192.43.244.18`. "
+"That way, even if its IP address changes in the future, we will still find "
+"it."
+msgstr ""
+"Теперь мы можем ввести доменное имя (или IP-адрес, это работает в обоих "
+"направлениях) в командной строке, и программа попытается подключиться к его "
+"серверу _daytime_. В противном случае, по умолчанию будет использоваться "
+"`time.nist.gov`. Однако даже в этом случае мы будем использовать "
+"`gethostbyname` вместо жесткого задания `192.43.244.18`. Таким образом, даже "
+"если его IP-адрес изменится в будущем, мы всё равно сможем его найти."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1029
+msgid ""
+"Since it takes virtually no time to get the time from your local server, you "
+"could run daytime twice in a row: First to get the time from "
+"`time.nist.gov`, the second time from your own system. You can then compare "
+"the results and see how exact your system clock is:"
+msgstr ""
+"Поскольку получение времени от локального сервера занимает практически "
+"нулевое время, вы можете запустить daytime дважды подряд: сначала для "
+"получения времени от `time.nist.gov`, а затем от вашей собственной системы. "
+"После этого вы можете сравнить результаты и увидеть, насколько точны часы "
+"вашей системы:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1033
+#, no-wrap
+msgid "% daytime ; daytime localhost\n"
+msgstr "% daytime ; daytime localhost\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1037
+#, no-wrap
+msgid ""
+"52080 01-06-20 04:02:33 50 0 0 390.2 UTC(NIST) *\n"
+"2001-06-20T04:02:35Z\n"
+"%\n"
+msgstr ""
+"52080 01-06-20 04:02:33 50 0 0 390.2 UTC(NIST) *\n"
+"2001-06-20T04:02:35Z\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1040
+msgid "As you can see, my system was two seconds ahead of the NIST time."
+msgstr "Как видно, моя система опережала время NIST на две секунды."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1042
+#, no-wrap
+msgid "`getservbyname`"
+msgstr "`getservbyname`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1046
+msgid ""
+"Sometimes you may not be sure what port a certain service uses. The "
+"man:getservbyname[3] function, also declared in [.filename]#netdb.h# comes "
+"in very handy in those cases:"
+msgstr ""
+"Иногда вы можете быть не уверены, какой порт использует определённая служба. "
+"В таких случаях очень полезна функция man:getservbyname[3], также "
+"объявленная в [.filename]#netdb.h#:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1050
+#, no-wrap
+msgid "struct servent * getservbyname(const char *name, const char *proto);\n"
+msgstr "struct servent * getservbyname(const char *name, const char *proto);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1053
+msgid ""
+"The `servent` structure contains the `s_port`, which contains the proper "
+"port, already in _network byte order_."
+msgstr ""
+"Структура `servent` содержит `s_port`, в котором находится соответствующий "
+"порт, уже в _порядке байтов сети_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1055
+msgid ""
+"Had we not known the correct port for the _daytime_ service, we could have "
+"found it this way:"
+msgstr ""
+"Если бы мы не знали правильный порт для службы _daytime_, мы могли бы найти "
+"его следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1065
+#, no-wrap
+msgid ""
+"struct servent *se;\n"
+" ...\n"
+" if ((se = getservbyname(\"daytime\", \"tcp\")) == NULL {\n"
+" fprintf(stderr, \"Cannot determine which port to use.\\n\");\n"
+" return 7;\n"
+" }\n"
+" sa.sin_port = se->s_port;\n"
+msgstr ""
+"struct servent *se;\n"
+" ...\n"
+" if ((se = getservbyname(\"daytime\", \"tcp\")) == NULL {\n"
+" fprintf(stderr, \"Cannot determine which port to use.\\n\");\n"
+" return 7;\n"
+" }\n"
+" sa.sin_port = se->s_port;\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1072
+msgid ""
+"You usually do know the port. But if you are developing a new protocol, you "
+"may be testing it on an unofficial port. Some day, you will register the "
+"protocol and its port (if nowhere else, at least in your [.filename]#/etc/"
+"services#, which is where `getservbyname` looks). Instead of returning an "
+"error in the above code, you just use the temporary port number. Once you "
+"have listed the protocol in [.filename]#/etc/services#, your software will "
+"find its port without you having to rewrite the code."
+msgstr ""
+"Обычно порт известен. Но если вы разрабатываете новый протокол, вы можете "
+"тестировать его на неофициальном порту. Когда-нибудь вы зарегистрируете "
+"протокол и его порт (если не где-то ещё, то хотя бы в вашем [.filename]#/etc/"
+"services#, где `getservbyname` ищет). Вместо возврата ошибки в приведённом "
+"выше коде вы просто используете временный номер порта. Как только вы "
+"добавите протокол в [.filename]#/etc/services#, ваше программное обеспечение "
+"найдёт его порт без необходимости переписывать код."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1074
+#, no-wrap
+msgid "Concurrent Servers"
+msgstr "Многозадачные серверы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1078
+msgid ""
+"Unlike a sequential server, a _concurrent server_ has to be able to serve "
+"more than one client at a time. For example, a _chat server_ may be serving "
+"a specific client for hours-it cannot wait till it stops serving a client "
+"before it serves the next one."
+msgstr ""
+"В отличие от последовательного сервера, _многозадачный сервер_ должен иметь "
+"возможность обслуживать более одного клиента одновременно. Например, _сервер "
+"чата_ может обслуживать конкретного клиента часами — он не может ждать, пока "
+"закончит обслуживать текущего клиента, прежде чем перейти к следующему."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1080
+msgid "This requires a significant change in our flowchart:"
+msgstr "Это требует значительных изменений в нашей блок-схеме:"
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1081
+#, no-wrap
+msgid "Concurrent Server"
+msgstr "Многозадачный сервер"
+
+#. type: Target for macro image
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1082
+#, no-wrap
+msgid "serv2.png"
+msgstr "serv2.png"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1086
+msgid ""
+"We moved the _serve_ from the _daemon process_ to its own _server process_. "
+"However, because each child process inherits all open files (and a socket is "
+"treated just like a file), the new process inherits not only the _\"accepted "
+"handle,\"_ i.e., the socket returned by the `accept` call, but also the _top "
+"socket_, i.e., the one opened by the top process right at the beginning."
+msgstr ""
+"Мы переместили _службу_ из _демона_ в её собственный _серверный процесс_. "
+"Однако, поскольку каждый дочерний процесс наследует все открытые файлы (а "
+"сокет обрабатывается так же, как файл), новый процесс наследует не только "
+"_\"принятый дескриптор\"_, т.е. сокет, возвращённый вызовом `accept`, но и "
+"_главный сокет_, т.е. тот, который был открыт главным процессом в самом "
+"начале."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1089
+msgid ""
+"However, the _server process_ does not need this socket and should `close` "
+"it immediately. Similarly, the _daemon process_ no longer needs the "
+"_accepted socket_, and not only should, but _must_ `close` it-otherwise, it "
+"will run out of available _file descriptors_ sooner or later."
+msgstr ""
+"Однако _серверному процессу_ этот сокет не нужен, и он должен немедленно "
+"вызвать ему `close`. Аналогично, _демону_ больше не нужен _сокет, принятый "
+"вызовом accept_, и он не только должен, но и _обязан_ вызвать ему `close` — "
+"в противном случае рано или поздно закончатся доступные _файловые "
+"дескрипторы_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1092
+msgid ""
+"After the _server process_ is done serving, it should close the _accepted "
+"socket_. Instead of returning to `accept`, it now exits."
+msgstr ""
+"После завершения обслуживания _серверного процесса_ он должен закрыть "
+"_принятый сокет_. Вместо возврата к `accept`, процесс теперь завершается."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1099
+msgid ""
+"Under UNIX(R), a process does not really _exit_. Instead, it _returns_ to "
+"its parent. Typically, a parent process ``wait``s for its child process, "
+"and obtains a return value. However, our _daemon process_ cannot simply "
+"stop and wait. That would defeat the whole purpose of creating additional "
+"processes. But if it never does `wait`, its children will become _zombies_-"
+"no longer functional but still roaming around."
+msgstr ""
+"В UNIX(R) процесс на самом деле не _завершается_. Вместо этого он "
+"_возвращается_ к своему родителю. Обычно родительский процесс ``ждёт`` "
+"(wait) завершения своего дочернего процесса и получает возвращаемое "
+"значение. Однако наш _демон-процесс_ не может просто остановиться и ждать. "
+"Это бы свело на нет всю цель создания дополнительных процессов. Но если он "
+"никогда не выполняет `wait`, его дочерние процессы станут _зомби_ — более не "
+"функционирующими, но всё ещё бродящими вокруг."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1102
+msgid ""
+"For that reason, the _daemon process_ needs to set _signal handlers_ in its "
+"_initialize daemon_ phase. At least a SIGCHLD signal has to be processed, "
+"so the daemon can remove the zombie return values from the system and "
+"release the system resources they are taking up."
+msgstr ""
+"По этой причине _демону_ необходимо установить _обработчики сигналов_ на "
+"этапе _инициализации демона_. Как минимум, должен обрабатываться сигнал "
+"SIGCHLD, чтобы демон мог удалять зомби-процессы из системы и освобождать "
+"занимаемые ими системные ресурсы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/sockets/_index.adoc:1105
+msgid ""
+"That is why our flowchart now contains a _process signals_ box, which is not "
+"connected to any other box. By the way, many servers also process SIGHUP, "
+"and typically interpret as the signal from the superuser that they should "
+"reread their configuration files. This allows us to change settings without "
+"having to kill and restart these servers."
+msgstr ""
+"Вот почему наша блок-схема теперь содержит блок _обработки сигналов_, "
+"который не соединен с другими блоками. Кстати, многие серверы также "
+"обрабатывают SIGHUP и обычно интерпретируют его как сигнал от "
+"суперпользователя, указывающий на необходимость перечитать конфигурационные "
+"файлы. Это позволяет нам изменять настройки без необходимости завершать и "
+"перезапускать эти серверы."
diff --git a/documentation/content/ru/books/developers-handbook/testing/_index.adoc b/documentation/content/ru/books/developers-handbook/testing/_index.adoc
new file mode 100644
index 0000000000..a801c9644f
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/testing/_index.adoc
@@ -0,0 +1,187 @@
+---
+authors:
+description: 'Регрессионное и нагрузочное тестирование'
+next: books/developers-handbook/partii
+params:
+ path: /books/developers-handbook/testing/
+prev: books/developers-handbook/policies
+showBookMenu: true
+tags: ["Regression", "Performance Testing", "Testing", "Tinderbox"]
+title: 'Глава 6. Регрессионное и нагрузочное тестирование'
+weight: 7
+---
+
+[[testing]]
+= Регрессионное и нагрузочное тестирование
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 6
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+Регрессионные тесты используются для проверки определенной части системы, чтобы убедиться, что она работает как ожидается, и для предотвращения повторного появления старых ошибок.
+
+Инструменты для регрессионного тестирования FreeBSD можно найти в дереве исходных кодов FreeBSD в каталоге [.filename]#src/tools/regression#.
+
+[[testing-micro-benchmark]]
+== Контрольный список для бенчмарка низкоуровневых операций
+
+Этот раздел содержит рекомендации по проведению корректного бенчмарка низкоуровненых операций на FreeBSD или самой FreeBSD.
+
+Невозможно использовать все приведенные ниже рекомендации каждый раз, но чем больше их применяется, тем лучше способность теста выявлять небольшие различия.
+
+* Отключить APM и любые другие манипуляции с часами (ACPI ?).
+* Запускайте тесты в однопользовательском режиме. Например, man:cron[8] и другие демоны только добавляют шум. Демон man:sshd[8] также может вызвать проблемы. Если требуется доступ по SSH во время тестирования, либо отключите перегенерацию ключа SSHv1, либо завершите родительский демон `sshd` во время тестов.
+* Не запускайте man:ntpd[8].
+* Если события man:syslog[3] генерируются, запустите man:syslogd[8] с пустым [.filename]#/etc/syslogd.conf#, в противном случае не запускайте его.
+* Минимизируйте дисковые операции ввода-вывода, по возможности избегайте их полностью.
+* Не монтируйте файловые системы, которые не требуются.
+* Смонтируйте [.filename]#/#, [.filename]#/usr# и любые другие файловые системы в режиме только для чтения, если это возможно. Это исключает обновления atime на диске (и т.д.) из общей картины ввода-вывода.
+* Переинициализируйте тестовую файловую систему с возможностью чтения/записи с помощью man:newfs[8] и заполните её из файла man:tar[1] или man:dump[8] перед каждым запуском. Размонтируйте и смонтируйте её перед началом теста. Это обеспечит согласованную структуру файловой системы. Для теста worldstone это применимо к [.filename]#/usr/obj# (просто переинициализируйте с помощью `newfs` и смонтируйте). Для достижения 100% воспроизводимости заполните файловую систему из файла man:dd[1] (например: `dd if=myimage of=/dev/ad0s1h bs=1m`)
+* Используйте разделы man:md[4] с поддержкой malloc или предзагруженные.
+* Перезагружайтесь между отдельными итерациями теста, это обеспечивает более согласованное состояние.
+* Удалите все необязательные драйверы устройств из ядра. Например, если USB не нужен для теста, не включайте поддержку USB в ядре. Драйверы, которые подключаются, часто имеют работающие таймауты.
+* Отключите неиспользуемое оборудование. Отсоедините диски с помощью man:atacontrol[8] и man:camcontrol[8], если диски не используются для тестирования.
+* Не настраивайте сеть, если она не тестируется, или дождитесь завершения тестирования, чтобы отправить результаты на другой компьютер.
+* Отключите "турбо-режимы", так как они делают тактовую частоту явно зависимой от окружающей среды. Это означает, что результаты тестирования на 100% идентичном коде могут зависеть от времени суток, употребления кофе или газировки или даже от количества людей в офисе.
+
+Если система должна быть подключена к общедоступной сети, следите за всплесками широковещательного трафика. Даже если они почти незаметны, они будут занимать циклы процессора. Многоадресная рассылка имеет аналогичные предостережения.
+* Размещайте каждую файловую систему на отдельном диске. Это минимизирует задержки, вызванные оптимизацией перемещения головок диска.
+* Минимизируйте вывод на последовательные или VGA-консоли. Запись вывода в файлы снижает дрожание. (Консоли на последовательном порту легко становятся узким местом.) Не касайтесь клавиатуры во время выполнения теста, даже нажатия kbd:[пробел] или kbd:[back-space] отражаются в числах.
+* Убедитесь, что тест достаточно длинный, но не слишком. Если тест слишком короткий, возникают проблемы с временными метками. Если он слишком длинный, изменения температуры и дрейф повлияют на частоту кварцевых кристаллов в компьютере. Эмпирическое правило: больше минуты, меньше часа.
+* Попытайтесь поддерживать температуру вокруг машины как можно более стабильной. Это влияет как на кварцевые резонаторы, так и на алгоритмы работы дисковых накопителей. Для получения действительно стабильных часов рассмотрите возможность использования стабилизированного тактового сигнала. Например, используйте OCXO + PLL и подавайте выходной сигнал в тактовые схемы вместо кварцевого резонатора на материнской плате. Для получения дополнительной информации по этому вопросу свяжитесь с {phk}.
+* Выполните тест как минимум 3 раза, но лучше запустить более 20 раз как для кода "до", так и для кода "после". По возможности чередуйте запуски (т.е. не следует запускать 20 раз "до", а затем 20 раз "после"), это поможет выявить влияние окружения. Не чередуйте строго 1:1, а лучше 3:3, чтобы можно было обнаружить эффекты взаимодействия.
++
+Хороший шаблон: `bababa{bbbaaa}*`. Это дает подсказку после первых 1+1 прогонов (так что можно остановить тест, если всё идет совсем не так), стандартное отклонение после первых 3+3 (дает хорошее представление, стоит ли проводить длительный прогон), а также тренды и показатели взаимодействия позже.
+* Используйте man:ministat[1], чтобы определить, являются ли числа значимыми. Рекомендуется приобрести книгу "Cartoon guide to statistics" ISBN: 0062731025, особенно если вы забыли или никогда не изучали стандартное отклонение и t-критерий Стьюдента.
+* Не используйте фоновый man:fsck[8], если тест не является бенчмарком фонового `fsck`. Также отключите `background_fsck` в [.filename]#/etc/rc.conf#, если бенчмарк не запускается как минимум через 60+«время работы ``fsck``» секунд после загрузки, так как man:rc[8] пробуждается и проверяет, нужно ли запускать `fsck` для каких-либо файловых систем, когда включен фоновый `fsck`. Аналогично, убедитесь, что нет оставшихся снимков, если только бенчмарк не является тестом со снимками.
+* Если тесты производительности показывают неожиданно низкие результаты, проверьте такие факторы, как высокий объем прерываний из неожиданного источника. Сообщалось, что некоторые версии ACPI могут "вести себя неправильно" и генерировать избыточные прерывания. Для диагностики необычных результатов тестов сделайте несколько снимков `vmstat -i` и поищите что-то необычное.
+* Будьте внимательны к параметрам оптимизации для ядра и пользовательского пространства, а также отладки. Легко упустить что-то и позже понять, что тест сравнивал не одно и то же.
+* Никогда не проводите тестирование производительности с включёнными параметрами ядра `WITNESS` и `INVARIANTS`, если тест не направлен на оценку производительности именно этих функций. `WITNESS` может привести к снижению производительности на 400% и более. Аналогично, параметры userspace man:malloc[3] по умолчанию отличаются в -CURRENT от тех, что поставляются в релизах.
+
+[[testing-tinderbox]]
+== Tinderbox для исходного текста FreeBSD
+
+Исходный Tinderbox состоит из:
+
+* Скрипта сборки [.filename]#tinderbox#, который автоматизирует выгрузку определённой версии исходного кода FreeBSD и её сборку.
+* Скрипта-супервизора [.filename]#tbmaster#, который отслеживает отдельные экземпляры Tinderbox, записывает их вывод и отправляет уведомления о сбоях по электронной почте.
+* Скрипта CGI с именем [.filename]#index.cgi#, который читает набор журналов tbmaster и представляет их в виде удобочитаемой HTML-сводки.
+* Набора серверов сборки, которые постоянно тестируют последние изменения наиболее важных веток кода FreeBSD.
+* Веб-сервера, хранящего полный набор журналов Tinderbox и отображающий актуальную сводку.
+
+Скрипты поддерживаются и были разработаны {des}, и сейчас написаны на Perl, что стало шагом вперед по сравнению с их первоначальной версией в виде shell-скриптов. Все скрипты и конфигурационные файлы хранятся в https://www.freebsd.org/cgi/cvsweb.cgi/projects/tinderbox/[/projects/tinderbox/].
+
+Для получения дополнительной информации о скриптах tinderbox и tbmaster на данном этапе обратитесь к соответствующим руководствам: tinderbox(1) и tbmaster(1).
+
+== Скрипт index.cgi
+
+Скрипт [.filename]#index.cgi# генерирует HTML-сводку журналов tinderbox и tbmaster. Хотя изначально он предназначался для использования в качестве CGI-скрипта, как следует из его названия, этот скрипт также может быть запущен из командной строки или из задачи man:cron[8], в таком случае он будет искать логи в директории, где расположен сам скрипт. Он автоматически определяет контекст, генерируя HTTP-заголовки при запуске в качестве CGI-скрипта. Он соответствует стандартам XHTML и использует CSS для стилизации.
+
+Скрипт начинает работу в блоке `main()`, пытаясь проверить, что он выполняется на официальном сайте Tinderbox. Если это не так, создается страница с указанием, что это не официальный сайт, и предоставляется URL официального сайта.
+
+Далее выполняется сканирование каталога журналов для получения перечня конфигураций, веток и архитектур, для которых существуют файлы журналов, чтобы избежать жесткого задания списка в скрипте и потенциального появления пустых строк или столбцов. Эта информация извлекается из имен файлов журналов, соответствующих следующему шаблону:
+
+[.programlisting]
+....
+tinderbox-$config-$branch-$arch-$machine.{brief,full}
+....
+
+Конфигурации, используемые на официальных серверах сборки Tinderbox, названы в соответствии с ветками, которые они собирают. Например, конфигурация `releng_8` используется для сборки `RELENG_8`, а также всех поддерживаемых веток выпусков.
+
+После успешного завершения всей процедуры запуска для каждой конфигурации вызывается `do_config()`.
+
+Функция `do_config()` генерирует HTML для отдельной конфигурации Tinderbox.
+
+Он работает, сначала создавая строку заголовка, затем перебирая каждую сборку ветки с указанной конфигурацией, формируя одну строку результатов для каждой следующим образом:
+
+* Для каждого элемента:
+
+** Для каждой машины в рамках этой архитектуры:
+
+*** Если существует краткий файл журнала, то:
+
+**** Вызвать `success()`, чтобы определить результат сборки.
+**** Вывести размер изменения.
+**** Вывести размер краткого файла журнала со ссылкой на сам файл журнала.
+**** Если также существует полный файл журнала, то:
+
+***** Вывести размер полного файла журнала со ссылкой на сам файл журнала.
+
+*** В противном случае:
+
+**** Нечего не выводить.
+
+Упомянутая выше функция `success()` проверяет краткий лог-файл на наличие строки "tinderbox run completed", чтобы определить, был ли сборка успешной.
+
+Конфигурации и ветви сортируются в соответствии с их рангом. Это вычисляется следующим образом:
+
+* `HEAD` и `CURRENT` имеют ранг 9999.
+* `RELENG_x` имеет ранг __``xx``__99.
+* `RELENG_x_y` имеет ранг _xxyy_.
+
+Это означает, что `HEAD` всегда имеет наивысший приоритет, а ветви `RELENG` ранжируются в числовом порядке, причём каждая ветвь `STABLE` имеет более высокий приоритет, чем ветви выпусков, ответвлённые от неё. Например, для FreeBSD 8 порядок от наивысшего к низшему будет следующим:
+
+* `RELENG_8` (ранг ветки 899).
+* `RELENG_8_3` (ранг ветки 803).
+* `RELENG_8_2` (ранг ветки 802).
+* `RELENG_8_1` (ранг ветки 801).
+* `RELENG_8_0` (ранг ветки 800).
+
+Цвета, которые Tinderbox использует для каждой ячейки в таблице, определяются CSS. Успешные сборки отображаются зелёным текстом; неудачные сборки отображаются красным текстом. Цвет блекнет со временем с момента соответствующей сборки, приближаясь к серому каждые полчаса.
+
+== Официальные серверы сборки
+
+Официальные серверы сборки Tinderbox размещены на площадке http://www.sentex.ca[Sentex Data Communications], которая также предоставляет хостинг для кластера Netperf FreeBSD.
+
+В настоящее время работают три сервера сборки:
+
+_freebsd-current.sentex.ca_ собирает:
+
+* `HEAD` для amd64, arm, i386, i386/pc98, ia64, mips, powerpc, powerpc64 и sparc64.
+* `RELENG_9` и поддерживаемые ветки 9._X_ для amd64, arm, i386, i386/pc98, ia64, mips, powerpc, powerpc64 и sparc64.
+
+_freebsd-stable.sentex.ca_ собирает:
+
+* `RELENG_8` и поддерживаемые ветки 8._X_ для amd64, i386, i386/pc98, ia64, mips, powerpc и sparc64.
+
+_freebsd-legacy.sentex.ca_ собирает:
+
+* `RELENG_7` и поддерживаемые ветки 7._X_ для amd64, i386, i386/pc98, ia64, powerpc и sparc64.
+
+== Официальный сайт со сводками
+
+Сводки и журналы с официальных серверов сборки доступны в сети по адресу http://tinderbox.FreeBSD.org[http://tinderbox.FreeBSD.org], размещены на {des} и настроены следующим образом:
+
+* Задание man:cron[8] проверяет серверы сборки через регулярные интервалы и загружает все новые файлы журналов с помощью man:rsync[1].
+* Apache настроен на использование [.filename]#index.cgi# в качестве `DirectoryIndex`.
diff --git a/documentation/content/ru/books/developers-handbook/testing/_index.po b/documentation/content/ru/books/developers-handbook/testing/_index.po
new file mode 100644
index 0000000000..220968249a
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/testing/_index.po
@@ -0,0 +1,802 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-06-27 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbooktesting_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:15
+#, no-wrap
+msgid "Regression and Performance Testing"
+msgstr "Регрессионное и нагрузочное тестирование"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:1
+#, no-wrap
+msgid "Chapter 6. Regression and Performance Testing"
+msgstr "Глава 6. Регрессионное и нагрузочное тестирование"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:53
+msgid ""
+"Regression tests are used to exercise a particular bit of the system to "
+"check that it works as expected, and to make sure that old bugs are not "
+"reintroduced."
+msgstr ""
+"Регрессионные тесты используются для проверки определенной части системы, "
+"чтобы убедиться, что она работает как ожидается, и для предотвращения "
+"повторного появления старых ошибок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:55
+msgid ""
+"The FreeBSD regression testing tools can be found in the FreeBSD source tree "
+"in the directory [.filename]#src/tools/regression#."
+msgstr ""
+"Инструменты для регрессионного тестирования FreeBSD можно найти в дереве "
+"исходных кодов FreeBSD в каталоге [.filename]#src/tools/regression#."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:57
+#, no-wrap
+msgid "Micro Benchmark Checklist"
+msgstr "Контрольный список для бенчмарка низкоуровневых операций"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:60
+msgid ""
+"This section contains hints for doing proper micro-benchmarking on FreeBSD "
+"or of FreeBSD itself."
+msgstr ""
+"Этот раздел содержит рекомендации по проведению корректного бенчмарка "
+"низкоуровненых операций на FreeBSD или самой FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:62
+msgid ""
+"It is not possible to use all of the suggestions below every single time, "
+"but the more used, the better the benchmark's ability to test small "
+"differences will be."
+msgstr ""
+"Невозможно использовать все приведенные ниже рекомендации каждый раз, но чем "
+"больше их применяется, тем лучше способность теста выявлять небольшие "
+"различия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:64
+msgid "Disable APM and any other kind of clock fiddling (ACPI ?)."
+msgstr "Отключить APM и любые другие манипуляции с часами (ACPI ?)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:65
+msgid ""
+"Run in single user mode. E.g., man:cron[8], and other daemons only add "
+"noise. The man:sshd[8] daemon can also cause problems. If ssh access is "
+"required during testing either disable the SSHv1 key regeneration, or kill "
+"the parent `sshd` daemon during the tests."
+msgstr ""
+"Запускайте тесты в однопользовательском режиме. Например, man:cron[8] и "
+"другие демоны только добавляют шум. Демон man:sshd[8] также может вызвать "
+"проблемы. Если требуется доступ по SSH во время тестирования, либо отключите "
+"перегенерацию ключа SSHv1, либо завершите родительский демон `sshd` во время "
+"тестов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:66
+msgid "Do not run man:ntpd[8]."
+msgstr "Не запускайте man:ntpd[8]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:67
+msgid ""
+"If man:syslog[3] events are generated, run man:syslogd[8] with an empty "
+"[.filename]#/etc/syslogd.conf#, otherwise, do not run it."
+msgstr ""
+"Если события man:syslog[3] генерируются, запустите man:syslogd[8] с пустым "
+"[.filename]#/etc/syslogd.conf#, в противном случае не запускайте его."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:68
+msgid "Minimize disk-I/O, avoid it entirely if possible."
+msgstr ""
+"Минимизируйте дисковые операции ввода-вывода, по возможности избегайте их "
+"полностью."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:69
+msgid "Do not mount file systems that are not needed."
+msgstr "Не монтируйте файловые системы, которые не требуются."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:70
+msgid ""
+"Mount [.filename]#/#, [.filename]#/usr#, and any other file system as read-"
+"only if possible. This removes atime updates to disk (etc.) from the I/O "
+"picture."
+msgstr ""
+"Смонтируйте [.filename]#/#, [.filename]#/usr# и любые другие файловые "
+"системы в режиме только для чтения, если это возможно. Это исключает "
+"обновления atime на диске (и т.д.) из общей картины ввода-вывода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:71
+msgid ""
+"Reinitialize the read/write test file system with man:newfs[8] and populate "
+"it from a man:tar[1] or man:dump[8] file before every run. Unmount and mount "
+"it before starting the test. This results in a consistent file system "
+"layout. For a worldstone test this would apply to [.filename]#/usr/obj# "
+"(just reinitialize with `newfs` and mount). To get 100% reproducibility, "
+"populate the file system from a man:dd[1] file (i.e.: `dd if=myimage of=/dev/"
+"ad0s1h bs=1m`)"
+msgstr ""
+"Переинициализируйте тестовую файловую систему с возможностью чтения/записи с "
+"помощью man:newfs[8] и заполните её из файла man:tar[1] или man:dump[8] "
+"перед каждым запуском. Размонтируйте и смонтируйте её перед началом теста. "
+"Это обеспечит согласованную структуру файловой системы. Для теста worldstone "
+"это применимо к [.filename]#/usr/obj# (просто переинициализируйте с помощью "
+"`newfs` и смонтируйте). Для достижения 100% воспроизводимости заполните "
+"файловую систему из файла man:dd[1] (например: `dd if=myimage of=/dev/ad0s1h "
+"bs=1m`)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:72
+msgid "Use malloc backed or preloaded man:md[4] partitions."
+msgstr "Используйте разделы man:md[4] с поддержкой malloc или предзагруженные."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:73
+msgid ""
+"Reboot between individual iterations of the test, this gives a more "
+"consistent state."
+msgstr ""
+"Перезагружайтесь между отдельными итерациями теста, это обеспечивает более "
+"согласованное состояние."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:74
+msgid ""
+"Remove all non-essential device drivers from the kernel. For instance if USB "
+"is not needed for the test, do not put USB in the kernel. Drivers which "
+"attach often have timeouts ticking away."
+msgstr ""
+"Удалите все необязательные драйверы устройств из ядра. Например, если USB не "
+"нужен для теста, не включайте поддержку USB в ядре. Драйверы, которые "
+"подключаются, часто имеют работающие таймауты."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:75
+msgid ""
+"Unconfigure hardware that are not in use. Detach disks with "
+"man:atacontrol[8] and man:camcontrol[8] if the disks are not used for the "
+"test."
+msgstr ""
+"Отключите неиспользуемое оборудование. Отсоедините диски с помощью "
+"man:atacontrol[8] и man:camcontrol[8], если диски не используются для "
+"тестирования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:76
+msgid ""
+"Do not configure the network unless it is being tested, or wait until after "
+"the test has been performed to ship the results off to another computer."
+msgstr ""
+"Не настраивайте сеть, если она не тестируется, или дождитесь завершения "
+"тестирования, чтобы отправить результаты на другой компьютер."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:78
+msgid ""
+"Disable \"Turbo-modes\" because they make the clock frequency explicitly "
+"depend on the environment. This means that benchmark runs on 100% identical "
+"code, may depend on time of day, coffee vs. soda or even how many other "
+"people are in the office."
+msgstr ""
+"Отключите \"турбо-режимы\", так как они делают тактовую частоту явно "
+"зависимой от окружающей среды. Это означает, что результаты тестирования на "
+"100% идентичном коде могут зависеть от времени суток, употребления кофе или "
+"газировки или даже от количества людей в офисе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:80
+msgid ""
+"If the system must be connected to a public network, watch out for spikes of "
+"broadcast traffic. Even though it is hardly noticeable, it will take up CPU "
+"cycles. Multicast has similar caveats."
+msgstr ""
+"Если система должна быть подключена к общедоступной сети, следите за "
+"всплесками широковещательного трафика. Даже если они почти незаметны, они "
+"будут занимать циклы процессора. Многоадресная рассылка имеет аналогичные "
+"предостережения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:81
+msgid ""
+"Put each file system on its own disk. This minimizes jitter from head-seek "
+"optimizations."
+msgstr ""
+"Размещайте каждую файловую систему на отдельном диске. Это минимизирует "
+"задержки, вызванные оптимизацией перемещения головок диска."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:82
+msgid ""
+"Minimize output to serial or VGA consoles. Running output into files gives "
+"less jitter. (Serial consoles easily become a bottleneck.) Do not touch "
+"keyboard while the test is running, even kbd:[space] or kbd:[back-space] "
+"shows up in the numbers."
+msgstr ""
+"Минимизируйте вывод на последовательные или VGA-консоли. Запись вывода в "
+"файлы снижает дрожание. (Консоли на последовательном порту легко становятся "
+"узким местом.) Не касайтесь клавиатуры во время выполнения теста, даже "
+"нажатия kbd:[пробел] или kbd:[back-space] отражаются в числах."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:83
+msgid ""
+"Make sure the test is long enough, but not too long. If the test is too "
+"short, timestamping is a problem. If it is too long temperature changes and "
+"drift will affect the frequency of the quartz crystals in the computer. Rule "
+"of thumb: more than a minute, less than an hour."
+msgstr ""
+"Убедитесь, что тест достаточно длинный, но не слишком. Если тест слишком "
+"короткий, возникают проблемы с временными метками. Если он слишком длинный, "
+"изменения температуры и дрейф повлияют на частоту кварцевых кристаллов в "
+"компьютере. Эмпирическое правило: больше минуты, меньше часа."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:84
+msgid ""
+"Try to keep the temperature as stable as possible around the machine. This "
+"affects both quartz crystals and disk drive algorithms. To get real stable "
+"clock, consider stabilized clock injection. E.g., get a OCXO + PLL, inject "
+"output into clock circuits instead of motherboard xtal. Contact {phk} for "
+"more information about this."
+msgstr ""
+"Попытайтесь поддерживать температуру вокруг машины как можно более "
+"стабильной. Это влияет как на кварцевые резонаторы, так и на алгоритмы "
+"работы дисковых накопителей. Для получения действительно стабильных часов "
+"рассмотрите возможность использования стабилизированного тактового сигнала. "
+"Например, используйте OCXO + PLL и подавайте выходной сигнал в тактовые "
+"схемы вместо кварцевого резонатора на материнской плате. Для получения "
+"дополнительной информации по этому вопросу свяжитесь с {phk}."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:85
+msgid ""
+"Run the test at least 3 times but it is better to run more than 20 times "
+"both for \"before\" and \"after\" code. Try to interleave if possible (i.e.: "
+"do not run 20 times before then 20 times after), this makes it possible to "
+"spot environmental effects. Do not interleave 1:1, but 3:3, this makes it "
+"possible to spot interaction effects."
+msgstr ""
+"Выполните тест как минимум 3 раза, но лучше запустить более 20 раз как для "
+"кода \"до\", так и для кода \"после\". По возможности чередуйте запуски "
+"(т.е. не следует запускать 20 раз \"до\", а затем 20 раз \"после\"), это "
+"поможет выявить влияние окружения. Не чередуйте строго 1:1, а лучше 3:3, "
+"чтобы можно было обнаружить эффекты взаимодействия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:88
+msgid ""
+"A good pattern is: `bababa{bbbaaa}*`. This gives hint after the first 1+1 "
+"runs (so it is possible to stop the test if it goes entirely the wrong way), "
+"a standard deviation after the first 3+3 (gives a good indication if it is "
+"going to be worth a long run) and trending and interaction numbers later on."
+msgstr ""
+"Хороший шаблон: `bababa{bbbaaa}*`. Это дает подсказку после первых 1+1 "
+"прогонов (так что можно остановить тест, если всё идет совсем не так), "
+"стандартное отклонение после первых 3+3 (дает хорошее представление, стоит "
+"ли проводить длительный прогон), а также тренды и показатели взаимодействия "
+"позже."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:89
+msgid ""
+"Use man:ministat[1] to see if the numbers are significant. Consider buying "
+"\"Cartoon guide to statistics\" ISBN: 0062731025, highly recommended, if you "
+"have forgotten or never learned about standard deviation and Student's T."
+msgstr ""
+"Используйте man:ministat[1], чтобы определить, являются ли числа значимыми. "
+"Рекомендуется приобрести книгу \"Cartoon guide to statistics\" ISBN: "
+"0062731025, особенно если вы забыли или никогда не изучали стандартное "
+"отклонение и t-критерий Стьюдента."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:90
+msgid ""
+"Do not use background man:fsck[8] unless the test is a benchmark of "
+"background `fsck`. Also, disable `background_fsck` in [.filename]#/etc/"
+"rc.conf# unless the benchmark is not started at least 60+\"``fsck`` "
+"runtime\" seconds after the boot, as man:rc[8] wakes up and checks if `fsck` "
+"needs to run on any file systems when background `fsck` is enabled. "
+"Likewise, make sure there are no snapshots lying around unless the benchmark "
+"is a test with snapshots."
+msgstr ""
+"Не используйте фоновый man:fsck[8], если тест не является бенчмарком "
+"фонового `fsck`. Также отключите `background_fsck` в [.filename]#/etc/"
+"rc.conf#, если бенчмарк не запускается как минимум через 60+«время работы "
+"``fsck``» секунд после загрузки, так как man:rc[8] пробуждается и проверяет, "
+"нужно ли запускать `fsck` для каких-либо файловых систем, когда включен "
+"фоновый `fsck`. Аналогично, убедитесь, что нет оставшихся снимков, если "
+"только бенчмарк не является тестом со снимками."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:91
+msgid ""
+"If the benchmark show unexpected bad performance, check for things like high "
+"interrupt volume from an unexpected source. Some versions of ACPI have been "
+"reported to \"misbehave\" and generate excess interrupts. To help diagnose "
+"odd test results, take a few snapshots of `vmstat -i` and look for anything "
+"unusual."
+msgstr ""
+"Если тесты производительности показывают неожиданно низкие результаты, "
+"проверьте такие факторы, как высокий объем прерываний из неожиданного "
+"источника. Сообщалось, что некоторые версии ACPI могут \"вести себя "
+"неправильно\" и генерировать избыточные прерывания. Для диагностики "
+"необычных результатов тестов сделайте несколько снимков `vmstat -i` и "
+"поищите что-то необычное."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:92
+msgid ""
+"Make sure to be careful about optimization parameters for kernel and "
+"userspace, likewise debugging. It is easy to let something slip through and "
+"realize later the test was not comparing the same thing."
+msgstr ""
+"Будьте внимательны к параметрам оптимизации для ядра и пользовательского "
+"пространства, а также отладки. Легко упустить что-то и позже понять, что "
+"тест сравнивал не одно и то же."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:93
+msgid ""
+"Do not ever benchmark with the `WITNESS` and `INVARIANTS` kernel options "
+"enabled unless the test is interested to benchmarking those features. "
+"`WITNESS` can cause 400%+ drops in performance. Likewise, userspace "
+"man:malloc[3] parameters default differently in -CURRENT from the way they "
+"ship in production releases."
+msgstr ""
+"Никогда не проводите тестирование производительности с включёнными "
+"параметрами ядра `WITNESS` и `INVARIANTS`, если тест не направлен на оценку "
+"производительности именно этих функций. `WITNESS` может привести к снижению "
+"производительности на 400% и более. Аналогично, параметры userspace "
+"man:malloc[3] по умолчанию отличаются в -CURRENT от тех, что поставляются в "
+"релизах."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:95
+#, no-wrap
+msgid "The FreeBSD Source Tinderbox"
+msgstr "Tinderbox для исходного текста FreeBSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:98
+msgid "The source Tinderbox consists of:"
+msgstr "Исходный Tinderbox состоит из:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:100
+msgid ""
+"A build script, [.filename]#tinderbox#, that automates checking out a "
+"specific version of the FreeBSD source tree and building it."
+msgstr ""
+"Скрипта сборки [.filename]#tinderbox#, который автоматизирует выгрузку "
+"определённой версии исходного кода FreeBSD и её сборку."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:101
+msgid ""
+"A supervisor script, [.filename]#tbmaster#, that monitors individual "
+"Tinderbox instances, logs their output, and emails failure notices."
+msgstr ""
+"Скрипта-супервизора [.filename]#tbmaster#, который отслеживает отдельные "
+"экземпляры Tinderbox, записывает их вывод и отправляет уведомления о сбоях "
+"по электронной почте."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:102
+msgid ""
+"A CGI script named [.filename]#index.cgi# that reads a set of tbmaster logs "
+"and presents an easy-to-read HTML summary of them."
+msgstr ""
+"Скрипта CGI с именем [.filename]#index.cgi#, который читает набор журналов "
+"tbmaster и представляет их в виде удобочитаемой HTML-сводки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:103
+msgid ""
+"A set of build servers that continually test the tip of the most important "
+"FreeBSD code branches."
+msgstr ""
+"Набора серверов сборки, которые постоянно тестируют последние изменения "
+"наиболее важных веток кода FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:104
+msgid ""
+"A webserver that keeps a complete set of Tinderbox logs and displays an up-"
+"to-date summary."
+msgstr ""
+"Веб-сервера, хранящего полный набор журналов Tinderbox и отображающий "
+"актуальную сводку."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:107
+msgid ""
+"The scripts are maintained and were developed by {des}, and are now written "
+"in Perl, a move on from their original incarnation as shell scripts. All "
+"scripts and configuration files are kept in https://www.freebsd.org/cgi/"
+"cvsweb.cgi/projects/tinderbox/[/projects/tinderbox/]."
+msgstr ""
+"Скрипты поддерживаются и были разработаны {des}, и сейчас написаны на Perl, "
+"что стало шагом вперед по сравнению с их первоначальной версией в виде shell-"
+"скриптов. Все скрипты и конфигурационные файлы хранятся в https://"
+"www.freebsd.org/cgi/cvsweb.cgi/projects/tinderbox/[/projects/tinderbox/]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:109
+msgid ""
+"For more information about the tinderbox and tbmaster scripts at this stage, "
+"see their respective man pages: tinderbox(1) and tbmaster(1)."
+msgstr ""
+"Для получения дополнительной информации о скриптах tinderbox и tbmaster на "
+"данном этапе обратитесь к соответствующим руководствам: tinderbox(1) и "
+"tbmaster(1)."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:110
+#, no-wrap
+msgid "The index.cgi Script"
+msgstr "Скрипт index.cgi"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:117
+msgid ""
+"The [.filename]#index.cgi# script generates the HTML summary of tinderbox "
+"and tbmaster logs. Although originally intended to be used as a CGI script, "
+"as indicated by its name, this script can also be run from the command line "
+"or from a man:cron[8] job, in which case it will look for logs in the "
+"directory where the script is located. It will automatically detect "
+"context, generating HTTP headers when it is run as a CGI script. It "
+"conforms to XHTML standards and is styled using CSS."
+msgstr ""
+"Скрипт [.filename]#index.cgi# генерирует HTML-сводку журналов tinderbox и "
+"tbmaster. Хотя изначально он предназначался для использования в качестве CGI-"
+"скрипта, как следует из его названия, этот скрипт также может быть запущен "
+"из командной строки или из задачи man:cron[8], в таком случае он будет "
+"искать логи в директории, где расположен сам скрипт. Он автоматически "
+"определяет контекст, генерируя HTTP-заголовки при запуске в качестве CGI-"
+"скрипта. Он соответствует стандартам XHTML и использует CSS для стилизации."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:120
+msgid ""
+"The script starts in the `main()` block by attempting to verify that it is "
+"running on the official Tinderbox website. If it is not, a page indicating "
+"it is not an official website is produced, and a URL to the official site is "
+"provided."
+msgstr ""
+"Скрипт начинает работу в блоке `main()`, пытаясь проверить, что он "
+"выполняется на официальном сайте Tinderbox. Если это не так, создается "
+"страница с указанием, что это не официальный сайт, и предоставляется URL "
+"официального сайта."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:123
+msgid ""
+"Next, it scans the log directory to get an inventory of configurations, "
+"branches and architectures for which log files exist, to avoid hard-coding a "
+"list into the script and potentially ending up with blank rows or columns. "
+"This information is derived from the names of the log files matching the "
+"following pattern:"
+msgstr ""
+"Далее выполняется сканирование каталога журналов для получения перечня "
+"конфигураций, веток и архитектур, для которых существуют файлы журналов, "
+"чтобы избежать жесткого задания списка в скрипте и потенциального появления "
+"пустых строк или столбцов. Эта информация извлекается из имен файлов "
+"журналов, соответствующих следующему шаблону:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:127
+#, no-wrap
+msgid "tinderbox-$config-$branch-$arch-$machine.{brief,full}\n"
+msgstr "tinderbox-$config-$branch-$arch-$machine.{brief,full}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:131
+msgid ""
+"The configurations used on the official Tinderbox build servers are named "
+"for the branches they build. For example, the `releng_8` configuration is "
+"used to build `RELENG_8` as well as all still-supported release branches."
+msgstr ""
+"Конфигурации, используемые на официальных серверах сборки Tinderbox, названы "
+"в соответствии с ветками, которые они собирают. Например, конфигурация "
+"`releng_8` используется для сборки `RELENG_8`, а также всех поддерживаемых "
+"веток выпусков."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:133
+msgid ""
+"Once all of this startup procedure has been successfully completed, "
+"`do_config()` is called for each configuration."
+msgstr ""
+"После успешного завершения всей процедуры запуска для каждой конфигурации "
+"вызывается `do_config()`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:135
+msgid ""
+"The `do_config()` function generates HTML for a single Tinderbox "
+"configuration."
+msgstr ""
+"Функция `do_config()` генерирует HTML для отдельной конфигурации Tinderbox."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:138
+msgid ""
+"It works by first generating a header row, then iterating over each branch "
+"build with the specified configuration, producing a single row of results "
+"for each in the following manner:"
+msgstr ""
+"Он работает, сначала создавая строку заголовка, затем перебирая каждую "
+"сборку ветки с указанной конфигурацией, формируя одну строку результатов для "
+"каждой следующим образом:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:140
+msgid "For each item:"
+msgstr "Для каждого элемента:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:142
+msgid "For each machine within that architecture:"
+msgstr "Для каждой машины в рамках этой архитектуры:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:144
+msgid "If a brief log file exists, then:"
+msgstr "Если существует краткий файл журнала, то:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:146
+msgid "Call `success()` to determine the outcome of the build."
+msgstr "Вызвать `success()`, чтобы определить результат сборки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:147
+msgid "Output the modification size."
+msgstr "Вывести размер изменения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:148
+msgid ""
+"Output the size of the brief log file with a link to the log file itself."
+msgstr "Вывести размер краткого файла журнала со ссылкой на сам файл журнала."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:149
+msgid "If a full log file also exists, then:"
+msgstr "Если также существует полный файл журнала, то:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:151
+msgid ""
+"Output the size of the full log file with a link to the log file itself."
+msgstr "Вывести размер полного файла журнала со ссылкой на сам файл журнала."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:153
+msgid "Otherwise:"
+msgstr "В противном случае:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:155
+msgid "No output."
+msgstr "Нечего не выводить."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:157
+msgid ""
+"The `success()` function mentioned above scans a brief log file for the "
+"string \"tinderbox run completed\" in order to determine whether the build "
+"was successful."
+msgstr ""
+"Упомянутая выше функция `success()` проверяет краткий лог-файл на наличие "
+"строки \"tinderbox run completed\", чтобы определить, был ли сборка успешной."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:160
+msgid ""
+"Configurations and branches are sorted according to their branch rank. This "
+"is computed as follows:"
+msgstr ""
+"Конфигурации и ветви сортируются в соответствии с их рангом. Это вычисляется "
+"следующим образом:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:162
+msgid "`HEAD` and `CURRENT` have rank 9999."
+msgstr "`HEAD` и `CURRENT` имеют ранг 9999."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:163
+msgid "`RELENG_x` has rank __``xx``__99."
+msgstr "`RELENG_x` имеет ранг __``xx``__99."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:164
+msgid "`RELENG_x_y` has rank _xxyy_."
+msgstr "`RELENG_x_y` имеет ранг _xxyy_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:167
+msgid ""
+"This means that `HEAD` always ranks highest, and `RELENG` branches are "
+"ranked in numerical order, with each `STABLE` branch ranking higher than the "
+"release branches forked off of it. For instance, for FreeBSD 8, the order "
+"from highest to lowest would be:"
+msgstr ""
+"Это означает, что `HEAD` всегда имеет наивысший приоритет, а ветви `RELENG` "
+"ранжируются в числовом порядке, причём каждая ветвь `STABLE` имеет более "
+"высокий приоритет, чем ветви выпусков, ответвлённые от неё. Например, для "
+"FreeBSD 8 порядок от наивысшего к низшему будет следующим:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:169
+msgid "`RELENG_8` (branch rank 899)."
+msgstr "`RELENG_8` (ранг ветки 899)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:170
+msgid "`RELENG_8_3` (branch rank 803)."
+msgstr "`RELENG_8_3` (ранг ветки 803)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:171
+msgid "`RELENG_8_2` (branch rank 802)."
+msgstr "`RELENG_8_2` (ранг ветки 802)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:172
+msgid "`RELENG_8_1` (branch rank 801)."
+msgstr "`RELENG_8_1` (ранг ветки 801)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:173
+msgid "`RELENG_8_0` (branch rank 800)."
+msgstr "`RELENG_8_0` (ранг ветки 800)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:177
+msgid ""
+"The colors that Tinderbox uses for each cell in the table are defined by "
+"CSS. Successful builds are displayed with green text; unsuccessful builds "
+"are displayed with red text. The color fades as time passes since the "
+"corresponding build, with every half an hour bringing the color closer to "
+"grey."
+msgstr ""
+"Цвета, которые Tinderbox использует для каждой ячейки в таблице, "
+"определяются CSS. Успешные сборки отображаются зелёным текстом; неудачные "
+"сборки отображаются красным текстом. Цвет блекнет со временем с момента "
+"соответствующей сборки, приближаясь к серому каждые полчаса."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:178
+#, no-wrap
+msgid "Official Build Servers"
+msgstr "Официальные серверы сборки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:181
+msgid ""
+"The official Tinderbox build servers are hosted by http://"
+"www.sentex.ca[Sentex Data Communications], who also host the FreeBSD Netperf "
+"Cluster."
+msgstr ""
+"Официальные серверы сборки Tinderbox размещены на площадке http://"
+"www.sentex.ca[Sentex Data Communications], которая также предоставляет "
+"хостинг для кластера Netperf FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:183
+msgid "Three build servers currently exist:"
+msgstr "В настоящее время работают три сервера сборки:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:185
+msgid "_freebsd-current.sentex.ca_ builds:"
+msgstr "_freebsd-current.sentex.ca_ собирает:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:187
+msgid ""
+"`HEAD` for amd64, arm, i386, i386/pc98, ia64, mips, powerpc, powerpc64, and "
+"sparc64."
+msgstr ""
+"`HEAD` для amd64, arm, i386, i386/pc98, ia64, mips, powerpc, powerpc64 и "
+"sparc64."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:188
+msgid ""
+"`RELENG_9` and supported 9._X_ branches for amd64, arm, i386, i386/pc98, "
+"ia64, mips, powerpc, powerpc64, and sparc64."
+msgstr ""
+"`RELENG_9` и поддерживаемые ветки 9._X_ для amd64, arm, i386, i386/pc98, "
+"ia64, mips, powerpc, powerpc64 и sparc64."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:190
+msgid "_freebsd-stable.sentex.ca_ builds:"
+msgstr "_freebsd-stable.sentex.ca_ собирает:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:192
+msgid ""
+"`RELENG_8` and supported 8._X_ branches for amd64, i386, i386/pc98, ia64, "
+"mips, powerpc and sparc64."
+msgstr ""
+"`RELENG_8` и поддерживаемые ветки 8._X_ для amd64, i386, i386/pc98, ia64, "
+"mips, powerpc и sparc64."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:194
+msgid "_freebsd-legacy.sentex.ca_ builds:"
+msgstr "_freebsd-legacy.sentex.ca_ собирает:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:196
+msgid ""
+"`RELENG_7` and supported 7._X_ branches for amd64, i386, i386/pc98, ia64, "
+"powerpc, and sparc64."
+msgstr ""
+"`RELENG_7` и поддерживаемые ветки 7._X_ для amd64, i386, i386/pc98, ia64, "
+"powerpc и sparc64."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:197
+#, no-wrap
+msgid "Official Summary Site"
+msgstr "Официальный сайт со сводками"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:200
+msgid ""
+"Summaries and logs from the official build servers are available online at "
+"http://tinderbox.FreeBSD.org[http://tinderbox.FreeBSD.org], hosted by {des} "
+"and set up as follows:"
+msgstr ""
+"Сводки и журналы с официальных серверов сборки доступны в сети по адресу "
+"http://tinderbox.FreeBSD.org[http://tinderbox.FreeBSD.org], размещены на "
+"{des} и настроены следующим образом:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:202
+msgid ""
+"A man:cron[8] job checks the build servers at regular intervals and "
+"downloads any new log files using man:rsync[1]."
+msgstr ""
+"Задание man:cron[8] проверяет серверы сборки через регулярные интервалы и "
+"загружает все новые файлы журналов с помощью man:rsync[1]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/testing/_index.adoc:202
+msgid "Apache is set up to use [.filename]#index.cgi# as `DirectoryIndex`."
+msgstr ""
+"Apache настроен на использование [.filename]#index.cgi# в качестве "
+"`DirectoryIndex`."
diff --git a/documentation/content/ru/books/developers-handbook/tools/_index.adoc b/documentation/content/ru/books/developers-handbook/tools/_index.adoc
new file mode 100644
index 0000000000..83dbc7784c
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/tools/_index.adoc
@@ -0,0 +1,1428 @@
+---
+authors:
+ -
+ author: 'James Raynard'
+ -
+ author: 'Murray Stokely'
+description: 'Инструменты разработки'
+next: books/developers-handbook/secure
+params:
+ path: /books/developers-handbook/tools/
+prev: books/developers-handbook/introduction
+showBookMenu: true
+tags: ["tools", "Interpreters", "Compilers", "cc", "make", "Debugging", "lldb", "gdb", "clang", "Emacs"]
+title: 'Глава 2. Инструменты разработки'
+weight: 3
+---
+
+[[tools]]
+= Инструменты разработки
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: 2
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:c-plus-plus-command: c++
+:clang-plus-plus-command: clang++
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+[[tools-synopsis]]
+== Обзор
+
+В этой главе представлено введение в использование некоторых инструментов для программирования, поставляемых с FreeBSD, хотя многое из описанного применимо и к другим версиям UNIX(R). Она _не_ претендует на детальное описание процесса написания кода. Большая часть главы предполагает наличие минимальных или отсутствие знаний в программировании, хотя предполагается, что даже опытные программисты найдут в ней что-то полезное.
+
+[[tools-intro]]
+== Введение
+
+FreeBSD предоставляет отличную среду разработки. Компиляторы для C и C++, а также ассемблер входят в базовую систему, не говоря уже о классических инструментах UNIX(R), таких как `sed` и `awk`. Если этого недостаточно, в коллекции Ports доступно множество других компиляторов и интерпретаторов. В следующем разделе, crossref:tools[tools-programming,Введение в программирование], перечислены некоторые из доступных вариантов. FreeBSD обладает высокой совместимостью со стандартами, такими как POSIX(R) и ANSI C, а также с собственным наследием BSD, что позволяет создавать приложения, которые будут компилироваться и запускаться с минимальными изменениями или без них на широком спектре платформ.
+
+Однако вся эта мощь может поначалу ошеломить, если вы никогда раньше не писали программы на платформе UNIX(R). Этот документ призван помочь вам начать работу, не углубляясь слишком сильно в более сложные темы. Цель заключается в том, чтобы дать вам достаточно базовых знаний для понимания документации.
+
+Большая часть документа не требует или почти не требует знаний программирования, хотя предполагает базовые навыки работы с UNIX(R) и готовность учиться!
+
+[[tools-programming]]
+== Введение в программирование
+
+Программа — это набор инструкций, которые указывают компьютеру выполнять различные действия; иногда выполняемая инструкция зависит от результата предыдущей. В этом разделе представлен обзор двух основных способов передачи таких инструкций, или, как их обычно называют, «команд». Один способ использует _интерпретатор_, другой — _компилятор_. Поскольку человеческие языки слишком сложны для однозначного понимания компьютером, команды обычно записываются на одном из специально разработанных для этого языков.
+
+=== Интерпретаторы
+
+С интерпретатором язык поставляется как среда, в которой вы вводите команды в приглашении, и среда выполняет их для вас. Для более сложных программ вы можете ввести команды в файл и заставить интерпретатор загрузить файл и выполнить команды в нём. Если что-то пойдёт не так, многие интерпретаторы переведут вас в отладчик, чтобы помочь найти проблему.
+
+Преимущество этого подхода в том, что вы сразу видите результаты выполнения команд, а ошибки можно легко исправить. Самый большой недостаток проявляется, когда вы хотите поделиться своими программами с кем-то. У них должен быть такой же интерпретатор, или у вас должен быть способ предоставить его, и они должны понимать, как им пользоваться. Кроме того, пользователям может не понравиться, если они попадут в отладчик при нажатии не той клавиши! С точки зрения производительности интерпретаторы могут потреблять много памяти и обычно генерируют код менее эффективно, чем компиляторы.
+
+По моему мнению, интерпретируемые языки — это лучший способ начать, если вы раньше не занимались программированием. Такая среда обычно встречается в языках вроде Lisp, Smalltalk, Perl и Basic. Можно также утверждать, что UNIX(R) shell (`sh`, `csh`) сам по себе является интерпретатором, и многие часто пишут shell-«скрипты» для помощи в различных «хозяйственных» задачах на своих машинах. Действительно, часть оригинальной философии UNIX(R) заключалась в предоставлении множества небольших утилит, которые можно было связывать вместе в shell-скриптах для выполнения полезных задач.
+
+=== Доступные интерпретаторы в FreeBSD
+
+Вот список интерпретаторов, доступных в Коллекции портов FreeBSD, с кратким обзором некоторых наиболее популярных интерпретируемых языков.
+
+Инструкции по получению и установке приложений из Коллекции портов можно найти в extref:{handbook}[разделе Порты, ports-using] руководства.
+
+BASIC::
+Сокращение от Beginner's All-purpose Symbolic Instruction Code. Разработан в 1950-х годах для обучения студентов университетов программированию и поставлялся с каждым уважающим себя персональным компьютером в 1980-х. BASIC — первый язык программирования для многих программистов. Он также является основой для Visual Basic.
++
+Интерпретатор Bywater Basic можно найти в Коллекции портов как package:lang/bwbasic[], а интерпретатор Phil Cockroft's Basic (ранее известный как Rabbit Basic) доступен как package:lang/pbasic[].
+
+Lisp::
+Язык, разработанный в конце 1950-х годов как альтернатива популярным в то время языкам для «численных расчётов». В отличие от них, Lisp основан на списках; фактически, название является сокращением от «List Processing» (обработка списков). Он очень популярен в кругах, связанных с ИИ (искусственным интеллектом).
++
+Lisp — это чрезвычайно мощный и сложный язык, но он может показаться довольно большим и громоздким.
++
+В Коллекции портов FreeBSD доступны различные реализации Lisp, которые могут работать в системах UNIX(R). CLISP от Bruno Haible и Michael Stoll доступен как package:lang/clisp[]. Более простая реализация Lisp, SLisp, доступна как package:lang/slisp[].
+
+Perl::
+Очень популярен среди системных администраторов для написания скриптов; также часто используется на веб-серверах для написания CGI-скриптов.
++
+Perl доступен в Коллекции портов как package:lang/perl5.36[] для всех выпусков FreeBSD.
+
+Scheme::
+Диалект Lisp, который более компактен и чист по сравнению с Common Lisp. Популярен в университетах, так как достаточно прост для обучения студентов в качестве первого языка, и при этом обладает достаточным уровнем абстракции для использования в исследовательской работе.
++
+Схема доступна из Коллекции Портов как package:lang/elk[] для Интерпретатора Elk Scheme. Интерпретатор MIT Scheme можно найти в package:lang/mit-scheme[], а Интерпретатор SCM Scheme — в package:lang/scm[].
+
+Lua::
+Lua — это легковесный встраиваемый язык сценариев. Он обладает высокой переносимостью и относительно прост. Lua доступен в коллекции портов в пакете package:lang/lua54[]. Он также включен в базовую систему как [.filename]#/usr/libexec/flua# для использования компонентами базовой системы. Стороннее программное обеспечение не должно зависеть от [.filename]#flua#.
+
+Python::
+Python — это объектно-ориентированный интерпретируемый язык. Его сторонники утверждают, что это один из лучших языков для начала программирования, поскольку он относительно прост в освоении, но не уступает другим популярным интерпретируемым языкам, используемым для разработки крупных и сложных приложений (Perl и Tcl — два других языка, популярных для таких задач).
++
+Последняя версия Python доступна в Коллекции портов в пакете package:lang/python[].
+
+Ruby::
+Ruby — это интерпретируемый, чисто объектно-ориентированный язык программирования. Он получил широкую популярность благодаря простому для понимания синтаксису, гибкости при написании кода и возможности легко разрабатывать и поддерживать большие, сложные программы.
++
+Ruby доступен в Коллекции портов как package:lang/ruby32[].
+
+Tcl и Tk::
+Tcl — это встраиваемый интерпретируемый язык, который получил широкое распространение и популярность в основном благодаря своей переносимости на множество платформ. Он может использоваться как для быстрого написания небольших прототипов приложений, так и (в сочетании с Tk, набором инструментов для графического интерфейса) полноценных программ с богатым функционалом.
++
+Различные версии Tcl доступны в качестве портов для FreeBSD. Последняя версия, Tcl 8.7, находится в пакете package:lang/tcl87[].
+
+=== Компиляторы
+
+Компиляторы довольно сильно различаются. Прежде всего, вы пишете свой код в файле (или файлах) с помощью редактора. Затем вы запускаете компилятор и проверяете, принимает ли он вашу программу. Если программа не скомпилировалась, стисните зубы и вернитесь к редактору; если же компиляция прошла успешно и программа была создана, вы можете запустить её либо в командной строке оболочки, либо в отладчике, чтобы проверить её работу.footnote:[Если вы запустите её в оболочке, может произойти дамп памяти.]
+
+Очевидно, это требует больше усилий по сравнению с использованием интерпретатора. Однако это позволяет делать множество вещей, которые очень сложны или даже невозможны с интерпретатором, например, писать код, тесно взаимодействующий с операционной системой — или даже создавать собственную операционную систему! Это также полезно, если требуется написать очень эффективный код, так как компилятор может не спешить и оптимизировать код, что было бы неприемлемо в интерпретаторе. Более того, распространение программы, написанной для компилятора, обычно проще, чем для интерпретатора — можно просто предоставить копию исполняемого файла, предполагая, что у пользователя та же операционная система, что и у вас.
+
+Поскольку цикл редактирования-компиляции-запуска-отладки довольно утомителен при использовании отдельных программ, многие производители коммерческих компиляторов создали интегрированные среды разработки (сокращённо IDE). FreeBSD не включает IDE в базовую систему, но в Коллекции портов доступен package:devel/kdevelop[], и многие используют для этой цели Emacs. Использование Emacs в качестве IDE обсуждается в crossref:tools[emacs, Использование Emacs как среды разработки].
+
+[[tools-compiling]]
+== Компиляция с помощью `cc`
+
+Этот раздел посвящён компилятору clang для языков C и C++, так как он устанавливается вместе с базовой системой FreeBSD. Clang устанавливается как `cc`; пакет GNU-компилятора package:lang/gcc[gcc] доступен в Коллекции портов. Детали создания программы с интерпретатором значительно различаются в зависимости от интерпретатора и обычно хорошо описаны в документации и онлайн-справке интерпретатора.
+
+Как только вы напишете свой шедевр, следующий шаг — преобразовать его во что-то, что (надеюсь!) будет работать на FreeBSD. Обычно это включает несколько шагов, каждый из которых выполняется отдельной программой.
+
+[.procedure]
+. Обработь исходный код, чтобы удалить комментарии и выполнить другие действия, такие как раскрытие макросов в C.
+. Проверить синтаксис вашего кода, чтобы убедиться, что вы соблюдаете правила языка. Если нет, он пожалуется!
+. Преобразовать исходный код в ассемблерный язык — это очень близко к машинному коду, но всё ещё понятно человеку. Как утверждается.
+. Преобразовать язык ассемблера в машинный код — да, здесь речь идет о битах и байтах, единицах и нулях.
+. Проверить, что вы использовали такие элементы, как функции и глобальные переменные, правильно и последовательно. Например, если вы вызвали несуществующую функцию, это будет отмечено.
+. Если вы пытаетесь создать исполняемый файл из нескольких исходных файлов, определить, как объединить их все вместе.
+. Определить, как создать что-то, что загрузчик времени выполнения системы сможет загрузить в память и запустить.
+. Наконец, записать исполняемый файл в файловую систему.
+
+Слово _компиляция_ часто относится только к шагам с 1 по 4, а остальные шаги называются _линковкой_. Иногда шаг 1 называют _препроцессированием_, а шаги 3-4 — _ассемблированием_.
+
+К счастью, почти все эти детали скрыты от вас, так как `cc` — это интерфейс, который управляет вызовом всех этих программ с правильными аргументами за вас; достаточно просто набрать
+
+[source, bash]
+....
+% cc foobar.c
+....
+
+и это вызовет компиляцию файла [.filename]#foobar.c# всеми перечисленными выше шагами. Если у вас несколько файлов для компиляции, просто сделайте что-то вроде
+
+[source, bash]
+....
+% cc foo.c bar.c
+....
+
+Обратите внимание, что проверка синтаксиса — это всего лишь проверка синтаксиса. Она не выявит логических ошибок, которые вы могли допустить, например, создание бесконечного цикла или использование пузырьковой сортировки вместо бинарной.footnote:[На случай, если вы не знали: бинарная сортировка — это эффективный способ упорядочивания элементов, в отличие от пузырьковой.]
+
+Существует множество опций для `cc`, все они описаны в руководстве. Вот несколько наиболее важных из них с примерами использования.
+
+`-o _filename_`::
+Имя выходного файла. Если вы не используете эту опцию, `cc` создаст исполняемый файл с именем [.filename]#a.out#.footnote:[Причины этого кроются в глубинах истории.]
++
+[source, bash]
+....
+% cc foobar.c executable is a.out
+% cc -o foobar foobar.c executable is foobar
+....
+
+`-c`::
+Просто скомпилирует файл, не связывая его. Полезно для небольших программ, где нужно только проверить синтаксис, или если вы используете [.filename]#Makefile#.
++
+[source, bash]
+....
+% cc -c foobar.c
+....
++
+Это создаст _объектный файл_ (не исполняемый) с именем [.filename]#foobar.o#. Его можно скомпоновать с другими объектными файлами в исполняемый файл.
+
+`-g`::
+Создать отладочную версию исполняемого файла. Это заставляет компилятор записывать в исполняемый файл информацию о том, какая строка какого исходного файла соответствует какому вызову функции. Отладчик может использовать эту информацию для отображения исходного кода при пошаговом выполнении программы, что _очень_ полезно; недостатком является то, что вся эта дополнительная информация значительно увеличивает размер программы. Обычно вы компилируете с `-g` во время разработки программы, а затем компилируете "релизную версию" без `-g`, когда убедитесь, что она работает правильно.
++
+
+[source, bash]
+....
+% cc -g foobar.c
+....
++
+Это создаст отладочную версию программы. footnote:[Примечание: мы не использовали флаг -o для указания имени исполняемого файла, поэтому получим исполняемый файл с именем a.out. Создание отладочной версии с именем foobar остается упражнением для читателя!]
+
+`-O`::
+Создает оптимизированную версию исполняемого файла. Компилятор применяет различные хитрые приёмы, чтобы попытаться создать исполняемый файл, который работает быстрее обычного. Вы можете добавить число после `-O`, чтобы указать более высокий уровень оптимизации, но это часто выявляет ошибки в оптимизаторе компилятора.
++
+[source, bash]
+....
+% cc -O -o foobar foobar.c
+....
++
+Это создаст оптимизированную версию [.filename]#foobar#.
+
+Следующие три флага заставят `cc` проверять, что ваш код соответствует соответствующему международному стандарту, часто называемому стандартом ANSI, хотя строго говоря, это стандарт ISO.
+
+`-Wall`::
+Включить все предупреждения, которые разработчики `cc` считают полезными. Несмотря на название, это не включит все предупреждения, которые `cc` способен выдавать.
+
+`-ansi`::
+Отключит большинство, но не все, не-ANSI C функции, предоставляемые `cc`. Несмотря на название, это не гарантирует строгого соответствия вашего кода стандарту.
+
+`-pedantic`::
+Отключит _все_ не-ANSI C возможности ``cc``.
+
+Без этих флагов `cc` позволит вам использовать некоторые из своих нестандартных расширений стандарта. Некоторые из них очень полезны, но не будут работать с другими компиляторами — фактически, одна из основных целей стандарта заключается в том, чтобы позволить людям писать код, который будет работать с любым компилятором на любой системе. Это известно как _переносимый код_.
+
+Обычно следует стремиться к тому, чтобы ваш код был как можно более переносимым, иначе позже вам, возможно, придётся полностью переписать программу для её работы в другом месте — а кто знает, что вы будете использовать через несколько лет?
+
+[source, bash]
+....
+% cc -Wall -ansi -pedantic -o foobar foobar.c
+....
+
+В результате будет создан исполняемый файл [.filename]#foobar# после проверки [.filename]#foobar.c# на соответствие стандартам.
+
+`-l__library__`::
+Укажите библиотеку функций, которая будет использоваться во время компоновки.
++
+Наиболее распространённый пример этого — компиляция программы, использующей некоторые математические функции в C. В отличие от большинства других платформ, они находятся в отдельной библиотеке, отличной от стандартной библиотеки C, и необходимо указать компилятору добавить её.
++
+Правило заключается в том, что если библиотека называется [.filename]#libsomething.a#, то вы передаёте `cc` аргумент `-l__something__`. Например, математическая библиотека называется [.filename]#libm.a#, поэтому вы передаёте `cc` аргумент `-lm`. Типичный подводный камень с математической библиотекой заключается в том, что она должна быть последней библиотекой в командной строке.
++
+[source, bash]
+....
+% cc -o foobar foobar.c -lm
+....
++
+Это приведёт к подключению функций математической библиотеки в [.filename]#foobar#.
++
+Если вы компилируете код на C++, используйте {c-plus-plus-command}. {c-plus-plus-command} также может быть вызван как {clang-plus-plus-command} в FreeBSD.
++
+[source, bash]
+....
+% c++ -o foobar foobar.cc
+....
++
+Это создаст исполняемый файл [.filename]#foobar# из исходного файла на C++
+[.filename]#foobar.cc#.
+
+=== Распространённые вопросы и проблемы `cc`
+
+==== Я скомпилировал файл с именем foobar.c и не могу найти исполняемый файл с именем foobar. Куда он пропал?
+
+Помните, что `cc` вызовет исполняемый файл [.filename]#a.out#, если вы не укажете иное. Используйте опцию `-o _имя_файла_`:
+
+[source, bash]
+....
+% cc -o foobar foobar.c
+....
+
+==== Хорошо, у меня есть исполняемый файл с именем foobar, я вижу его при выполнении команды ls, но когда я ввожу foobar в командной строке, система сообщает, что такого файла нет. Почему он не может его найти?
+
+В отличие от MS-DOS(R), UNIX(R) не ищет в текущем каталоге, когда пытается определить, какую программу нужно запустить, если вы явно не укажете это. Введите `./foobar`, что означает "запустить файл с именем [.filename]#foobar# в текущем каталоге."
+
+=== Я назвал свой исполняемый файл test, но при запуске ничего не происходит. В чем дело?
+
+Большинство UNIX(R) систем имеют программу под названием `test` в [.filename]#/usr/bin#, и оболочка выбирает её, прежде чем проверить текущий каталог. Введите следующее:
+
+[source, bash]
+....
+% ./test
+....
+
+или выберите более подходящее название для вашей программы!
+
+==== Я скомпилировал свою программу, и сначала она работала нормально, но потом произошла ошибка, и было сообщение о core dumped. Что это значит?
+
+Название _core dump_ восходит к самым ранним дням UNIX(R), когда машины использовали ферритовую память для хранения данных. По сути, если программа завершалась сбоем при определённых условиях, система записывала содержимое ферритовой памяти на диск в файл с именем [.filename]#core#, который программист затем мог изучить, чтобы выяснить причину ошибки.
+
+==== Увлекательный материал, но что мне теперь делать?
+
+Используйте отладчик для анализа образа памяти (см. crossref:tools[debugging, Отладка]).
+
+==== Когда моя программа сбросила core, она сообщила что-то о segmentation fault. Что это?
+
+Это означает, что ваша программа попыталась выполнить какую-то недопустимую операцию с памятью; UNIX(R) разработана для защиты операционной системы и других программ от некорректно работающих программ.
+
+Распространенные причины этого:
+
+* Попытка записи в NULL-указатель, например:
++
+[.programlisting]
+....
+char *foo = NULL;
+strcpy(foo, "bang!");
+....
+
+* Использование неинициализированного указателя, например:
++
+[.programlisting]
+....
+char *foo;
+strcpy(foo, "bang!");
+....
++
+Указатель будет иметь случайное значение, которое, возможно, укажет на область памяти, недоступную вашей программе, и ядро завершит вашу программу до того, как она сможет нанести какой-либо ущерб. Если вам не повезет, он укажет внутрь вашей собственной программы и повредит одну из структур данных, что приведет к загадочному сбою программы.
+* Попытка доступа за пределы массива, например
++
+[.programlisting]
+....
+int bar[20];
+bar[27] = 6;
+....
+
+* Попытка сохранить что-то в память только для чтения, например
++
+[.programlisting]
+....
+char *foo = "My string";
+strcpy(foo, "bang!");
+....
++
+Версии UNIX(R) компиляторы часто помещают строковые литералы, такие как `"Моя строка"`, в области памяти только для чтения.
+* Выполнение нежелательных действий с `malloc()` и `free()`, например
++
+[.programlisting]
+....
+char bar[80];
+free(bar);
+....
++
+или
++
+[.programlisting]
+....
+char *foo = malloc(27);
+free(foo);
+free(foo);
+....
+
+Совершение одной из этих ошибок не всегда приведет к сбою, но это всегда плохая практика. Некоторые системы и компиляторы более терпимы, чем другие, поэтому программы, которые хорошо работают на одной системе, могут аварийно завершаться при попытке запустить их на другой.
+
+==== Иногда при получении дампа памяти я вижу сообщение ошибки шины (bus error). В моей книге по UNIX(R) сказано, что это означает аппаратную проблему, но компьютер продолжает работать. Это правда?
+
+Нет, к счастью, нет (если, конечно, у вас действительно нет аппаратной проблемы...). Обычно это означает, что вы обратились к памяти способом, который не следует использовать.
+
+==== Этот процесс создания дампа памяти звучит довольно полезно, если я могу запускать его по своему желанию. Могу ли я это сделать, или нужно ждать возникновения ошибки?
+
+Можете. Просто перейдите на другую консоль или xterm, выполните
+
+[source, bash]
+....
+% ps
+....
+
+чтобы узнать идентификатор процесса вашей программы и выполните
+
+[source, bash]
+....
+% kill -ABRT pid
+....
+
+где `_pid_` — идентификатор процесса, который вы нашли.
+
+Это полезно, если ваша программа зависла в бесконечном цикле, например. Если ваша программа перехватывает SIGABRT, есть несколько других сигналов, которые оказывают аналогичный эффект.
+
+В качестве альтернативы, вы можете создать дамп памяти изнутри вашей программы, вызвав функцию `abort()`. Дополнительную информацию можно найти на man:abort[3].
+
+Если вы хотите создать дамп памяти извне вашей программы, но не хотите завершать процесс, вы можете использовать программу `gcore`. Подробнее см. на странице руководства man:gcore[1].
+
+[[tools-make]]
+== Make
+
+=== Что такое `make`?
+
+Когда вы работаете над простой программой с одним или двумя исходными файлами, вводя
+
+[source, bash]
+....
+% cc file1.c file2.c
+....
+
+это не слишком плохо, но быстро становится очень утомительным, когда есть несколько файлов — и компиляция тоже может занять время.
+
+Один из способов обойти это — использовать объектные файлы и перекомпилировать исходный файл только в случае изменения исходного кода. Таким образом, у нас может получиться что-то вроде:
+
+[source, bash]
+....
+% cc file1.o file2.o … file37.c …
+....
+
+если бы мы изменили файл [.filename]#file37.c#, но не трогали остальные с момента последней компиляции. Это может значительно ускорить компиляцию, но не решает проблему с вводом.
+
+Или мы могли бы написать shell-скрипт для решения проблемы с вводом, но тогда пришлось бы перекомпилировать всё, что сделало бы его очень неэффективным для крупного проекта.
+
+Что произойдет, если у нас есть сотни исходных файлов? Что, если мы работаем в команде с другими людьми, которые забывают сообщить нам, когда они изменили один из своих исходных файлов, которые мы используем?
+
+Возможно, мы могли бы объединить два решения и написать что-то вроде shell-скрипта, который содержал бы какое-то волшебное правило, указывающее, когда исходный файл нужно компилировать. Теперь нам осталось только найти программу, которая сможет понимать эти правила, так как для shell это немного слишком сложно.
+
+Эта программа называется `make`. Она читает файл, называемый _makefile_, который указывает, как различные файлы зависят друг от друга, и определяет, какие файлы нужно перекомпилировать, а какие нет. Например, правило может звучать так: «если [.filename]#fromboz.o# старше, чем [.filename]#fromboz.c#, значит, кто-то изменил [.filename]#fromboz.c#, и его нужно перекомпилировать». В makefile также содержатся правила, указывающие make, _как_ именно перекомпилировать исходный файл, что делает эту программу гораздо более мощным инструментом.
+
+Файлы Makefile обычно хранятся в том же каталоге, что и исходный код, к которому они применяются, и могут называться [.filename]#makefile#, [.filename]#Makefile# или [.filename]#MAKEFILE#. Большинство программистов используют имя [.filename]#Makefile#, так как это помещает его в начало списка файлов в каталоге, где его легко заметить.footnote:[Они не используют форму MAKEFILE, так как заглавные буквы часто применяются для файлов документации, таких как README.]
+
+=== Пример использования `make`
+
+Вот очень простой файл для make:
+
+[.programlisting]
+....
+foo: foo.c
+ cc -o foo foo.c
+....
+
+Он состоит из двух строк: строки зависимости и строки создания.
+
+Строка зависимости здесь состоит из имени программы (известного как _цель_), за которым следует двоеточие, пробел и имя исходного файла. Когда `make` читает эту строку, он проверяет, существует ли файл [.filename]#foo#; если он существует, программа сравнивает время последнего изменения файла [.filename]#foo# с временем последнего изменения файла [.filename]#foo.c#. Если файл [.filename]#foo# не существует или старше файла [.filename]#foo.c#, программа смотрит на строку создания, чтобы выяснить, что делать. Другими словами, это правило для определения, когда файл [.filename]#foo.c# нужно перекомпилировать.
+
+Строка создания начинается с табуляции (нажмите kbd:[tab]), а затем следует команда, которую вы бы ввели для создания [.filename]#foo#, если бы делали это в командной строке. Если [.filename]#foo# устарел или не существует, `make` выполняет эту команду для его создания. Другими словами, это правило, которое сообщает make, как перекомпилировать [.filename]#foo.c#.
+
+Таким образом, при вводе команды `make` система обеспечит актуальность файла [.filename]#foo# относительно последних изменений в [.filename]#foo.c#. Этот принцип можно распространить на [.filename]#Makefile#, содержащие сотни целей — фактически, в FreeBSD можно собрать всю операционную систему, просто введя `make buildworld buildkernel` в корневом каталоге дерева исходных кодов (src).
+
+Еще одно полезное свойство makefile заключается в том, что цели не обязательно должны быть программами. Например, у нас может быть makefile, который выглядит так:
+
+[.programlisting]
+....
+foo: foo.c
+ cc -o foo foo.c
+
+install:
+ cp foo /home/me
+....
+
+Мы можем указать make, какую цель мы хотим собрать, набрав:
+
+[source, bash]
+....
+% make target
+....
+
+`make` будет рассматривать только указанную цель и игнорировать все остальные. Например, если мы введём `make foo` с указанным выше makefile, make проигнорирует цель `install`.
+
+Если мы просто введем `make` без параметров, make всегда будет обращаться к первой цели и затем остановится, не рассматривая остальные. Поэтому если мы введем `make` здесь, он просто перейдет к цели `foo`, перекомпилирует [.filename]#foo# при необходимости и затем остановится, не переходя к цели `install`.
+
+Обратите внимание, что цель `install` не зависит ни от чего! Это означает, что команда в следующей строке всегда выполняется при попытке создать эту цель с помощью команды `make install`. В данном случае она скопирует [.filename]#foo# в домашний каталог пользователя. Это часто используется в makefile приложений, чтобы приложение можно было установить в правильный каталог после успешной компиляции.
+
+Это немного запутанная тема для объяснения. Если вы не до конца понимаете, как работает `make`, лучше всего написать простую программу, например, "hello world", и make-файл, как указано выше, и поэкспериментировать. Затем можно перейти к использованию нескольких исходных файлов или добавлению заголовочного файла в исходный код. В этом случае очень полезен `touch` — он изменяет дату файла без необходимости его редактирования.
+
+=== make и include-файлы
+
+Код на C часто начинается со списка подключаемых файлов, например stdio.h. Некоторые из этих файлов являются системными, а некоторые принадлежат текущему проекту:
+
+[.programlisting]
+....
+#include <stdio.h>
+#include "foo.h"
+
+int main(....
+....
+
+Чтобы убедиться, что этот файл перекомпилируется при изменении [.filename]#foo.h#, необходимо добавить его в [.filename]#Makefile#:
+
+[.programlisting]
+....
+foo: foo.c foo.h
+....
+
+В момент, когда ваш проект становится больше и у вас появляется все больше собственных включаемых файлов для поддержки, отслеживание всех включаемых файлов и файлов, которые от них зависят, становится проблемой. Если вы измените включаемый файл, но забудете перекомпилировать все файлы, которые от него зависят, последствия будут катастрофическими. У `clang` есть опция для анализа ваших файлов и создания списка включаемых файлов и их зависимостей: `-MM`.
+
+Если вы добавите это в ваш Makefile:
+
+[.programlisting]
+....
+depend:
+ cc -E -MM *.c > .depend
+....
+
+и выполните `make depend`, появится файл [.filename]#.depend# со списком объектных файлов, C-файлов и включаемых файлов:
+
+[.programlisting]
+....
+foo.o: foo.c foo.h
+....
+
+Если вы измените файл [.filename]#foo.h#, при следующем запуске `make` все файлы, зависящие от [.filename]#foo.h#, будут перекомпилированы.
+
+Не забудьте выполнить `make depend` каждый раз, когда вы добавляете include-файл в один из своих файлов.
+
+=== Файлы Makefile системы FreeBSD
+
+Makefile-ы могут быть довольно сложными для написания. К счастью, в BSD-системах, таких как FreeBSD, есть очень мощные Makefile-ы, поставляемые в составе системы. Отличным примером этого является система портов FreeBSD. Вот основная часть типичного [.filename]#Makefile# для портов:
+
+[.programlisting]
+....
+MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/
+DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz
+
+.include <bsd.port.mk>
+....
+
+Теперь, если мы перейдем в каталог этого порта и наберем `make`, произойдет следующее:
+
+[.procedure]
+. Проверяется, есть ли исходный код этого порта уже в системе.
+. Если это не так, устанавливается FTP-соединение с URL в MASTER_SITES для загрузки исходного кода.
+. Контрольная сумма исходного кода вычисляется и сравнивается с контрольной суммой известной и хорошей копии исходного кода. Это делается для того, чтобы убедиться, что исходный код не был поврежден во время передачи.
+. Все необходимые изменения для адаптации исходного кода к работе в FreeBSD применяются — это называется применением _патча_.
+. Любая необходимая специальная настройка для исходного кода выполнена. (Многие дистрибутивы программ UNIX(R) пытаются определить, на какой версии UNIX(R) они компилируются и какие дополнительные функции UNIX(R) доступны — именно здесь они получают эту информацию в сценарии портов FreeBSD).
+. Компилируется исходный код программы. По сути, мы переходим в каталог, куда были распакованы исходные файлы, и выполняем `make` — собственный make-файл программы содержит необходимую информацию для сборки программы.
+. Теперь у нас есть скомпилированная версия программы. При желании мы можем протестировать её сейчас; когда мы уверены в программе, можно ввести `make install`. Это приведёт к копированию программы и всех необходимых вспомогательных файлов в нужные места, а также к добавлению записи в `базу данных пакетов`, чтобы позже можно было легко удалить порт, если мы передумаем.
+
+Вот теперь, я думаю, вы согласитесь, что это довольно впечатляюще для скрипта из четырёх строк!
+
+Секрет кроется в последней строке, которая указывает `make` обратиться к системному makefile под названием [.filename]#bsd.port.mk#. Эту строку легко пропустить, но именно здесь начинается вся магия — кто-то написал makefile, который предписывает `make` выполнить все вышеперечисленные действия (плюс несколько других, которые я не упомянул, включая обработку возможных ошибок), и любой может получить доступ к этому функционалу, просто добавив одну строку в свой собственный makefile!
+
+Если вы хотите взглянуть на эти системные makefile-ы, они находятся в [.filename]#/usr/share/mk#, но, вероятно, лучше подождать, пока у вас не появится немного практики с makefile, так как они очень сложные (и если вы всё же решите их посмотреть, убедитесь, что у вас под рукой есть фляга крепкого кофе!)
+
+=== Более сложные способы использования `make`
+
+`Make` — это очень мощный инструмент, способный на гораздо большее, чем показано в простом примере выше. К сожалению, существует несколько различных версий `make`, и все они значительно отличаются друг от друга. Лучший способ узнать, на что они способны, — вероятно, прочитать документацию. Надеюсь, это введение дало вам основу, с которой вы сможете это сделать. В man:make[1] подробно обсуждаются переменные, аргументы и то, как использовать `make`.
+
+Многие приложения в портах используют GNU make, который имеет очень хороший набор страниц "info". Если вы установили любой из этих портов, GNU make будет автоматически установлен как `gmake`. Он также доступен как отдельный порт и пакет.
+
+Для просмотра справочных страниц (info) GNU make вам потребуется отредактировать файл [.filename]#dir# в каталоге [.filename]#/usr/local/info#, добавив соответствующую запись. Добавьте строку
+
+[.programlisting]
+....
+ * Make: (make). The GNU Make utility.
+....
+
+в файл. После этого вы можете ввести `info` и затем выбрать [.guimenuitem]#make# из меню (или в Emacs выполнить `C-h i`).
+
+[[debugging]]
+== Отладка
+
+=== Обзор отладчиков, поставляемых в системе
+
+Использование отладчика позволяет запускать программу в более контролируемых условиях. Обычно можно выполнять программу построчно, проверять значения переменных, изменять их, указывать отладчику выполнение до определённой точки и затем останавливаться и так далее. Также можно подключиться к уже работающей программе или загрузить core-файл, чтобы исследовать причину аварийного завершения программы.
+
+Этот раздел представляет собой краткое введение в использование отладчиков и не затрагивает специализированные темы, такие как отладка ядра. Для получения дополнительной информации по этой теме обратитесь к главе crossref:kerneldebug[kerneldebug,Отладка ядра].
+
+Стандартный отладчик, поставляемый с FreeBSD, называется `lldb` (LLVM debugger). Поскольку он является частью стандартной установки для данного выпуска, нет необходимости выполнять какие-либо дополнительные действия для его использования. Он обладает хорошей справкой по командам, доступной через команду `help`, а также https://lldb.llvm.org/[руководством и документацией в интернете].
+
+[NOTE]
+====
+Команда `lldb` также доступна extref:{handbook}ports/[из портов или пакетов, ports-using] как пакет package:devel/llvm[].
+====
+
+Другой отладчик, доступный в FreeBSD, называется `gdb` (GNU debugger). В отличие от lldb, он не устанавливается по умолчанию в FreeBSD; для его использования необходимо extref:{handbook}#ports-using/[установить] пакет package:devel/gdb[] из портов или пакетов. Он обладает отличной встроенной справкой, а также набором info-страниц.
+
+Два отладчика обладают схожим набором функций, поэтому выбор между ними в основном зависит от личных предпочтений. Если вы знакомы только с одним из них, используйте его. Тем, кто не знаком ни с одним или знаком с обоими, но хочет использовать отладчик внутри Emacs, придётся выбрать `gdb`, так как `lldb` не поддерживается Emacs. В остальных случаях попробуйте оба и решите, какой вам больше нравится.
+
+=== Использование lldb
+
+==== Запуск lldb
+
+Запустите lldb, набрав
+
+[source, bash]
+....
+% lldb -- progname
+....
+
+==== Запуск программы с lldb
+
+Скомпилируйте программу с `-g`, чтобы максимально использовать возможности `lldb`. Без этого флаг она будет работать, но отображать только имя текущей выполняемой функции вместо исходного кода. Если отображается строка вида:
+
+[source, bash]
+....
+Breakpoint 1: where = temp`main, address = …
+....
+
+(без указания имени файла исходного кода и номера строки) при установке точки останова это означает, что программа не была скомпилирована с параметром `-g`.
+
+[TIP]
+====
+Большинство команд `lldb` имеют более короткие формы, которые можно использовать вместо полных. Здесь используются полные формы для ясности.
+====
+
+На строке `lldb` введите `breakpoint set -n main`. Это укажет отладчику не показывать предварительный код настройки в запускаемой программе и остановить выполнение в начале кода программы. Теперь введите `process launch`, чтобы фактически запустить программу — она начнётся с кода настройки, а затем будет остановлена отладчиком при вызове `main()`.
+
+Для пошагового выполнения программы строка за строкой введите `thread step-over`. Когда программа дойдёт до вызова функции, войдите в неё, набрав `thread step-in`. Оказавшись внутри вызова функции, вернитесь из него с помощью команды `thread step-out` или используйте `up` и `down`, чтобы быстро посмотреть на вызывающий код.
+
+Вот простой пример того, как найти ошибку в программе с помощью `lldb`. Это наша программа (с умышленной ошибкой):
+
+[.programlisting]
+....
+#include <stdio.h>
+
+int bazz(int anint);
+
+main() {
+ int i;
+
+ printf("This is my program\n");
+ bazz(i);
+ return 0;
+}
+
+int bazz(int anint) {
+ printf("You gave me %d\n", anint);
+ return anint;
+}
+....
+
+Эта программа устанавливает значение `i` равным `5` и передает его в функцию `bazz()`, которая выводит переданное число.
+
+Компиляция и запуск программы отображают
+
+[source, bash]
+....
+% cc -g -o temp temp.c
+% ./temp
+This is my program
+anint = -5360
+....
+
+Это не то, что ожидалось! Пора разобраться, что происходит!
+
+[source, bash]
+....
+% lldb -- temp
+(lldb) target create "temp"
+Current executable set to 'temp' (x86_64).
+(lldb) breakpoint set -n main Skip the set-up code
+Breakpoint 1: where = temp`main + 15 at temp.c:8:2, address = 0x00000000002012ef lldb puts breakpoint at main()
+(lldb) process launch Run as far as main()
+Process 9992 launching
+Process 9992 launched: '/home/pauamma/tmp/temp' (x86_64) Program starts running
+
+Process 9992 stopped
+* thread #1, name = 'temp', stop reason = breakpoint 1.1 lldb stops at main()
+ frame #0: 0x00000000002012ef temp`main at temp.c:8:2
+ 5 main() {
+ 6 int i;
+ 7
+-> 8 printf("This is my program\n"); Indicates the line where it stopped
+ 9 bazz(i);
+ 10 return 0;
+ 11 }
+(lldb) thread step-over Go to next line
+This is my program Program prints out
+Process 9992 stopped
+* thread #1, name = 'temp', stop reason = step over
+ frame #0: 0x0000000000201300 temp`main at temp.c:9:7
+ 6 int i;
+ 7
+ 8 printf("This is my program\n");
+-> 9 bazz(i);
+ 10 return 0;
+ 11 }
+ 12
+(lldb) thread step-in step into bazz()
+Process 9992 stopped
+* thread #1, name = 'temp', stop reason = step in
+ frame #0: 0x000000000020132b temp`bazz(anint=-5360) at temp.c:14:29 lldb displays stack frame
+ 11 }
+ 12
+ 13 int bazz(int anint) {
+-> 14 printf("You gave me %d\n", anint);
+ 15 return anint;
+ 16 }
+(lldb)
+....
+
+Подождите минуту! Как переменная `int` стала равна `-5360`? Разве она не была установлена в `5` в `main()`? Давайте поднимемся к `main()` и посмотрим.
+
+[source, bash]
+....
+(lldb) up Move up call stack
+frame #1: 0x000000000020130b temp`main at temp.c:9:2 lldb displays stack frame
+ 6 int i;
+ 7
+ 8 printf("This is my program\n");
+-> 9 bazz(i);
+ 10 return 0;
+ 11 }
+ 12
+(lldb) frame variable i Show us the value of i
+(int) i = -5360 lldb displays -5360
+....
+
+О боже! Глядя на код, мы забыли инициализировать i. Мы хотели добавить
+
+[.programlisting]
+....
+...
+main() {
+ int i;
+
+ i = 5;
+ printf("This is my program\n");
+...
+....
+
+но мы пропустили строку `i=5;`. Поскольку мы не инициализировали `i`, она содержала любое число, которое оказалось в той области памяти при запуске программы, и в данном случае это оказалось `-5360`.
+
+[NOTE]
+====
+Команда `lldb` отображает стек вызовов каждый раз, когда мы входим в функцию или выходим из неё, даже если мы используем `up` и `down` для перемещения по стеку вызовов. Это показывает имя функции и значения её аргументов, что помогает отслеживать текущее положение и происходящее. (Стек — это область хранения, где программа сохраняет информацию об аргументах, переданных в функции, и о том, куда возвращаться после вызова функции.)
+====
+
+==== Изучение файла Core с помощью lldb
+
+Файл core — это, по сути, файл, содержащий полное состояние процесса на момент его аварийного завершения. В «старые добрые времена» программистам приходилось распечатывать шестнадцатеричные дампы файлов core и корпеть над руководствами по машинному коду, но сейчас жизнь стала немного проще. Кстати, в FreeBSD и других системах на базе 4.4BSD файл core называется [.filename]#progname.core#, а не просто [.filename]#core#, чтобы было понятнее, какой программе он принадлежит.
+
+Для анализа файла core укажите имя файла core в дополнение к самой программе. Вместо обычного запуска `lldb` введите `lldb -c _имя_программы_.core \-- _имя_программы_`.
+
+Отладчик отобразит что-то вроде этого:
+
+[source, bash, subs="verbatim,quotes"]
+....
+% lldb -c [.filename]#progname.core# -- [.filename]#progname#
+(lldb) target create "[.filename]#progname#" --core "[.filename]#progname#.core"
+Core file '/home/pauamma/tmp/[.filename]#progname.core#' (x86_64) was loaded.
+(lldb)
+....
+
+В этом случае программа называлась [.filename]#progname#, поэтому файл дампа имеет имя [.filename]#progname.core#. Отладчик не показывает, почему программа завершилась аварийно или где это произошло. Для этого используйте команду `thread backtrace all`. Она также покажет, как была вызвана функция, в которой программа завершилась дампом ядра.
+
+[source, bash, subs="verbatim,quotes"]
+....
+(lldb) thread backtrace all
+* thread #1, name = 'progname', stop reason = signal SIGSEGV
+ * frame #0: 0x0000000000201347 progname`bazz(anint=5) at temp2.c:17:10
+ frame #1: 0x0000000000201312 progname`main at temp2.c:10:2
+ frame #2: 0x000000000020110f progname`_start(ap=<unavailable>, cleanup=<unavailable>) at crt1.c:76:7
+(lldb)
+....
+
+`SIGSEGV` указывает, что программа пыталась получить доступ к памяти (обычно выполнить код или прочитать/записать данные) по адресу, который ей не принадлежит, но не предоставляет конкретных деталей. Для этого обратитесь к исходному коду на строке 10 файла temp2.c, в функции `bazz()`. Трассировка также показывает, что в данном случае `bazz()` была вызвана из `main()`.
+
+==== Подключение к работающей программе с помощью lldb
+
+Одной из самых замечательных особенностей `lldb` является возможность подключения к уже работающей программе. Конечно, для этого требуются соответствующие разрешения. Распространённая проблема — пошаговое выполнение программы, которая создаёт ответвления, с необходимостью отслеживать дочерний процесс, но отладчик отслеживает только родительский.
+
+Для этого запустите другой `lldb`, используйте `ps` для поиска идентификатора процесса дочернего процесса и выполните
+
+[source, bash]
+....
+(lldb) process attach -p pid
+....
+
+в `lldb`, а затем отлаживайте как обычно.
+
+Для того чтобы это работало правильно, код, который вызывает `fork` для создания дочернего процесса, должен делать что-то вроде следующего (предоставлено из документации `gdb`):
+
+[.programlisting]
+....
+...
+if ((pid = fork()) < 0) /* _Always_ check this */
+ error();
+else if (pid == 0) { /* child */
+ int PauseMode = 1;
+
+ while (PauseMode)
+ sleep(10); /* Wait until someone attaches to us */
+ ...
+} else { /* parent */
+ ...
+....
+
+Вот все, что нужно сделать: подключиться к дочернему процессу, установить `PauseMode` в `0` с помощью `expr PauseMode = 0` и дождаться возврата из вызова `sleep()`.
+
+=== Удаленная отладка с использованием LLDB
+
+[NOTE]
+====
+Описанная функциональность доступна начиная с версии LLDB 12.0.0. Пользователи релизов FreeBSD, содержащих более раннюю версию LLDB, могут воспользоваться снимком из extref:{handbook}[портов или пакетов, ports-using], как package:devel/llvm-devel[].
+====
+
+Начиная с LLDB 12.0.0, удалённая отладка поддерживается в FreeBSD. Это означает, что `lldb-server` может быть запущен для отладки программы на одном узле, в то время как интерактивный клиент `lldb` подключается к нему с другого.
+
+Чтобы запустить новый процесс для удалённой отладки, выполните `lldb-server` на удалённом сервере, набрав
+
+[source, bash]
+....
+% lldb-server g host:port -- progname
+....
+
+Процесс будет остановлен сразу после запуска, и `lldb-server` будет ожидать подключения клиента.
+
+Запустите `lldb` локально и введите следующую команду для подключения к удалённому серверу:
+
+[source, bash]
+....
+(lldb) gdb-remote host:port
+....
+
+`lldb-server` также может присоединиться к работающему процессу. Для этого введите следующее на удалённом сервере:
+
+[source, bash]
+....
+% lldb-server g host:port --attach pid-or-name
+....
+
+=== Использование gdb
+
+==== Запуск gdb
+
+Запустите gdb, набрав
+
+[source, bash]
+....
+% gdb progname
+....
+
+хотя многие предпочитают запускать его внутри Emacs. Для этого введите:
+
+[source, bash]
+....
+ M-x gdb RET progname RET
+....
+
+Наконец, для тех, кого отпугивает текстовый интерфейс командной строки, существует графический интерфейс (package:devel/xxgdb[]) в Коллекции портов.
+
+==== Запуск программы под отладчиком gdb
+
+Скомпилируйте программу с `-g`, чтобы максимально использовать возможности `gdb`. Она будет работать и без этого, но отобразит только имя текущей выполняемой функции вместо исходного кода. Строка вида:
+
+[source, bash]
+....
+... (no debugging symbols found) ...
+....
+
+когда `gdb` запускается, это означает, что программа не была скомпилирована с опцией `-g`.
+
+На приглашении `gdb` введите `break main`. Это укажет отладчику пропустить предварительный код настройки в выполняемой программе и остановить выполнение в начале кода программы. Теперь введите `run`, чтобы запустить программу — она начнётся с начала кода настройки, а затем будет остановлена отладчиком при вызове `main()`.
+
+Для пошагового выполнения программы нажимайте `n`. При вызове функции войдите в неё, нажав `s`. Оказавшись внутри функции, вернитесь из неё, нажав `f`, или используйте `up` и `down` для быстрого просмотра вызывающего кода.
+
+Вот простой пример того, как найти ошибку в программе с помощью `gdb`. Это наша программа (с умышленной ошибкой):
+
+[.programlisting]
+....
+#include <stdio.h>
+
+int bazz(int anint);
+
+main() {
+ int i;
+
+ printf("This is my program\n");
+ bazz(i);
+ return 0;
+}
+
+int bazz(int anint) {
+ printf("You gave me %d\n", anint);
+ return anint;
+}
+....
+
+Эта программа устанавливает значение `i` равным `5` и передает его в функцию `bazz()`, которая выводит переданное число.
+
+Компиляция и запуск программы отображают
+
+[source, bash]
+....
+% cc -g -o temp temp.c
+% ./temp
+This is my program
+anint = 4231
+....
+
+Это было не то, что мы ожидали! Пора разобраться, что происходит!
+
+[source, bash]
+....
+% gdb temp
+GDB is free software and you are welcome to distribute copies of it
+ under certain conditions; type "show copying" to see the conditions.
+There is absolutely no warranty for GDB; type "show warranty" for details.
+GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
+(gdb) break main Skip the set-up code
+Breakpoint 1 at 0x160f: file temp.c, line 9. gdb puts breakpoint at main()
+(gdb) run Run as far as main()
+Starting program: /home/james/tmp/temp Program starts running
+
+Breakpoint 1, main () at temp.c:9 gdb stops at main()
+(gdb) n Go to next line
+This is my program Program prints out
+(gdb) s step into bazz()
+bazz (anint=4231) at temp.c:17 gdb displays stack frame
+(gdb)
+....
+
+Подождите минуту! Как `int` стал равен `4231`? Разве он не был установлен в `5` в `main()`? Давайте поднимемся к `main()` и посмотрим.
+
+[source, bash]
+....
+(gdb) up Move up call stack
+#1 0x1625 in main () at temp.c:11 gdb displays stack frame
+(gdb) p i Show us the value of i
+$1 = 4231 gdb displays 4231
+....
+
+О боже! Глядя на код, мы забыли инициализировать i. Мы хотели добавить
+
+[.programlisting]
+....
+...
+main() {
+ int i;
+
+ i = 5;
+ printf("This is my program\n");
+...
+....
+
+но мы пропустили строку `i=5;`. Поскольку мы не инициализировали `i`, она содержала любое число, которое оказалось в той области памяти при запуске программы, и в данном случае это оказалось `4231`.
+
+[NOTE]
+====
+Команда `gdb` отображает стек вызовов каждый раз при входе в функцию или выходе из неё, даже при использовании `up` и `down` для перемещения по стеку вызовов. Это показывает имя функции и значения её аргументов, что помогает отслеживать текущее положение и происходящее. (Стек — это область хранения, где программа сохраняет информацию об аргументах, переданных в функции, и о месте, куда нужно вернуться после вызова функции.)
+====
+
+==== Изучение файла core с помощью gdb
+
+Файл core — это, по сути, файл, содержащий полное состояние процесса на момент его аварийного завершения. В «старые добрые времена» программистам приходилось распечатывать шестнадцатеричные дампы файлов core и корпеть над руководствами по машинному коду, но сейчас жизнь стала немного проще. Кстати, в FreeBSD и других системах на базе 4.4BSD файл core называется [.filename]#progname.core#, а не просто [.filename]#core#, чтобы было понятнее, какой программе он принадлежит.
+
+Для анализа файла core запустите `gdb` обычным способом. Вместо ввода команд `break` или `run` введите
+
+[source, bash]
+....
+(gdb) core progname.core
+....
+
+Если файл core отсутствует в текущем каталоге, сначала введите `dir /путь/к/core/файлу`.
+
+Отладчик должен отобразить что-то вроде этого:
+
+[source, bash, subs="verbatim,quotes"]
+....
+% gdb [.filename]#progname#
+GDB is free software and you are welcome to distribute copies of it
+ under certain conditions; type "show copying" to see the conditions.
+There is absolutely no warranty for GDB; type "show warranty" for details.
+GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.
+(gdb) core [.filename]#progname.core#
+Core was generated by `[.filename]#progname#'.
+Program terminated with signal 11, Segmentation fault.
+Cannot access memory at address 0x7020796d.
+#0 0x164a in bazz (anint=0x5) at temp.c:17
+(gdb)
+....
+
+В этом случае программа называлась [.filename]#progname#, поэтому файл дампа памяти называется [.filename]#progname.core#. Мы видим, что программа завершилась аварийно из-за попытки доступа к области памяти, которая ей не доступна, в функции `bazz`.
+
+Иногда полезно увидеть, как была вызвана функция, поскольку проблема могла возникнуть гораздо выше по стеку вызовов в сложной программе. `bt` заставляет `gdb` вывести трассировку стека вызовов:
+
+[source, bash]
+....
+(gdb) bt
+#0 0x164a in bazz (anint=0x5) at temp.c:17
+#1 0xefbfd888 in end ()
+#2 0x162c in main () at temp.c:11
+(gdb)
+....
+
+Функция `end()` вызывается при аварийном завершении программы; в данном случае функция `bazz()` была вызвана из `main()`.
+
+==== Подключение к работающей программе с помощью gdb
+
+Одной из самых удобных функций `gdb` является возможность подключения к уже запущенной программе. Конечно, для этого требуются соответствующие разрешения. Частой проблемой является пошаговое выполнение программы, которая создает дочерний процесс, когда нужно отслеживать дочерний процесс, но отладчик продолжает отслеживать только родительский.
+
+Для этого запустите другой `gdb`, используйте `ps` для поиска идентификатора процесса дочернего элемента и выполните
+
+[source, bash]
+....
+(gdb) attach pid
+....
+
+в `gdb`, а затем отлаживайте как обычно.
+
+Для того чтобы это работало правильно, код, который вызывает `fork` для создания дочернего процесса, должен делать что-то вроде следующего (предоставлено из документации `gdb`):
+
+[.programlisting]
+....
+...
+if ((pid = fork()) < 0) /* _Always_ check this */
+ error();
+else if (pid == 0) { /* child */
+ int PauseMode = 1;
+
+ while (PauseMode)
+ sleep(10); /* Wait until someone attaches to us */
+ ...
+} else { /* parent */
+ ...
+....
+
+Теперь осталось только подключиться к дочернему процессу, установить PauseMode в `0` и дождаться возврата из вызова `sleep()`!
+
+[[emacs]]
+== Использование Emacs в качестве среды разработки
+
+=== Emacs
+
+Emacs — это высоконастраиваемый редактор — настолько, что его можно скорее назвать операционной системой, чем редактором! Многие разработчики и системные администраторы действительно проводят практически всё своё время, работая внутри Emacs, выходя из него только для завершения сеанса.
+
+Невозможно даже кратко описать все, что может делать Emacs, но вот некоторые особенности, которые могут быть интересны разработчикам:
+
+* Очень мощный редактор, позволяющий выполнять поиск и замену как строк, так и регулярных выражений (шаблонов), переход к началу/концу блока выражения и многое другое.
+* Выпадающие меню и встроенная справка.
+* Подсветка синтаксиса и форматирование отступов в зависимости от языка.
+* Полностью настраиваемый.
+* Вы можете компилировать и отлаживать программы из Emacs.
+* При ошибке компиляции можно перейти к проблемной строке исходного кода.
+* Дружелюбный интерфейс для программы `info`, используемой для чтения гипертекстовой документации GNU, включая документацию по самому Emacs.
+* Дружелюбный интерфейс для `gdb`, позволяющий просматривать исходный код во время пошагового выполнения программы.
+
+И, несомненно, множество других, которые были упущены из виду.
+
+Emacs можно установить на FreeBSD с помощью пакета package:editors/emacs[].
+
+После установки запустите его и выполните `C-h t`, чтобы прочитать руководство по Emacs — это означает, что нужно удерживать kbd:[control], нажать kbd:[h], отпустить kbd:[control], а затем нажать kbd:[t]. (Также можно использовать мышь для выбора [.guimenuitem]#Руководство по Emacs# в меню menu:Help[].)
+
+Хотя в Emacs и есть меню, стоит изучить сочетания клавиш, так как редактировать что-либо с их помощью гораздо быстрее, чем искать мышку и кликать в нужное место. Кроме того, общаясь с опытными пользователями Emacs, вы часто услышите выражения вроде «`M-x replace-s RET foo RET bar RET`» — полезно понимать, что они значат. Да и вообще, в Emacs столько полезных функций, что все они просто не поместятся на панелях меню.
+
+К счастью, освоить сочетания клавиш довольно легко, так как они отображаются рядом с пунктами меню. Мой совет — использовать пункты меню для, скажем, открытия файла, пока вы не разберётесь, как это работает, и не почувствуете себя уверенно, а затем попробуйте выполнить `C-x C-f`. Когда освоитесь с этим, переходите к следующей команде меню.
+
+Если вы не можете вспомнить, что делает определённая комбинация клавиш, выберите [.guimenuitem]#Описание Клавиши# в меню menu:Help[] и введите её — Emacs сообщит, что она делает. Вы также можете использовать пункт меню [.guimenuitem]#Command Apropos#, чтобы найти все команды, содержащие определённое слово, с указанием соответствующих клавишных сочетаний.
+
+Между прочим, выражение выше означает: удерживайте клавишу kbd:[Meta], нажмите kbd:[x], отпустите клавишу kbd:[Meta], введите `replace-s` (сокращение от `replace-string` — ещё одна особенность Emacs в том, что команды можно сокращать), нажмите клавишу kbd:[return], введите `foo` (строка, которую нужно заменить), нажмите клавишу kbd:[return], введите `bar` (строка, на которую нужно заменить `foo`) и снова нажмите kbd:[return]. Emacs выполнит операцию поиска и замены, которую вы только что запросили.
+
+Если вам интересно, что такое kbd:[Meta], то это специальная клавиша, которая есть на многих рабочих станциях UNIX(R). К сожалению, на PC её нет, поэтому обычно используется kbd:[alt] (или, если вам не повезло, kbd:[escape]).
+
+Ах да, чтобы выйти из Emacs, нажмите `C-x C-c` (это значит зажмите клавишу kbd:[control], нажмите kbd:[x], затем kbd:[c] и отпустите kbd:[control]). Если у вас есть несохранённые файлы, Emacs спросит, хотите ли вы их сохранить. (Игнорируйте часть документации, где говорится, что `C-z` — это обычный способ выхода из Emacs — это оставляет Emacs работающим в фоне и полезно только на системах без виртуальных терминалов).
+
+=== Настройка Emacs
+
+Emacs делает много замечательных вещей; некоторые из них встроены, некоторые требуют настройки.
+
+Вместо использования проприетарного языка макросов для конфигурации, Emacs применяет версию Lisp, специально адаптированную для редакторов, известную как Emacs Lisp. Работа с Emacs Lisp может быть весьма полезной, если вы хотите продолжить и изучить что-то вроде Common Lisp. Emacs Lisp обладает многими возможностями Common Lisp, хотя и значительно меньше (и, следовательно, проще для освоения).
+
+Лучший способ изучить Emacs Lisp — это прочитать онлайн-руководство link:https://www.gnu.org/software/emacs/manual/elisp.html[Emacs Reference].
+
+Однако для начала настройки Emacs не обязательно знать Lisp, так как я включил пример файла [.filename]#.emacs#, которого должно быть достаточно для старта. Просто скопируйте его в свой домашний каталог и перезапустите Emacs, если он уже запущен; он прочитает команды из файла и (надеюсь) предоставит вам полезную базовую конфигурацию.
+
+=== Пример файла [.filename]#.emacs#
+
+К сожалению, здесь слишком много информации, чтобы объяснять всё подробно; однако есть один или два момента, которые стоит упомянуть.
+
+* Всё, что начинается с `;`, является комментарием и игнорируется Emacs.
+* В первой строке `-*- Emacs-Lisp -*-` нужен для того, чтобы мы могли редактировать сам файл [.filename]#.emacs# в Emacs и использовать все удобные функции для редактирования Emacs Lisp. Обычно Emacs пытается угадать это по имени файла, но может не сделать это правильно для [.filename]#.emacs#.
+* Клавиша kbd:[tab] связана с функцией отступа в некоторых режимах, поэтому при нажатии клавиши tab текущая строка кода будет с отступом. Если вы хотите вставить символ табуляции в текст, удерживайте клавишу kbd:[control] во время нажатия kbd:[tab].
+* Этот файл поддерживает подсветку синтаксиса для C, C++, Perl, Lisp и Scheme, определяя язык по имени файла.
+* В Emacs уже есть предопределённая функция `next-error`. В окне вывода компиляции это позволяет переходить от одной ошибки компиляции к следующей с помощью `M-n`; мы определяем дополнительную функцию `previous-error`, которая позволяет вернуться к предыдущей ошибке с помощью `M-p`. Самое приятное — сочетание `C-c C-c` откроет исходный файл, в котором произошла ошибка, и перейдёт на соответствующую строку.
+* Включаем возможность Emacs работать как сервер, так что если вы заняты чем-то вне Emacs и хотите отредактировать файл, можно просто ввести
++
+[source, bash]
+....
+% emacsclient filename
+....
++
+и затем вы можете редактировать файл в вашем Emacs!footnote:[Многие пользователи Emacs устанавливают переменную окружения EDITOR в emacsclient, так что это происходит каждый раз, когда им нужно отредактировать файл.]
+
+.Пример файла [.filename]#.emacs#
+====
+[.programlisting]
+....
+;; -*-Emacs-Lisp-*-
+
+;; This file is designed to be re-evaled; use the variable first-time
+;; to avoid any problems with this.
+(defvar first-time t
+ "Flag signifying this is the first time that .emacs has been evaled")
+
+;; Meta
+(global-set-key "\M- " 'set-mark-command)
+(global-set-key "\M-\C-h" 'backward-kill-word)
+(global-set-key "\M-\C-r" 'query-replace)
+(global-set-key "\M-r" 'replace-string)
+(global-set-key "\M-g" 'goto-line)
+(global-set-key "\M-h" 'help-command)
+
+;; Function keys
+(global-set-key [f1] 'manual-entry)
+(global-set-key [f2] 'info)
+(global-set-key [f3] 'repeat-complex-command)
+(global-set-key [f4] 'advertised-undo)
+(global-set-key [f5] 'eval-current-buffer)
+(global-set-key [f6] 'buffer-menu)
+(global-set-key [f7] 'other-window)
+(global-set-key [f8] 'find-file)
+(global-set-key [f9] 'save-buffer)
+(global-set-key [f10] 'next-error)
+(global-set-key [f11] 'compile)
+(global-set-key [f12] 'grep)
+(global-set-key [C-f1] 'compile)
+(global-set-key [C-f2] 'grep)
+(global-set-key [C-f3] 'next-error)
+(global-set-key [C-f4] 'previous-error)
+(global-set-key [C-f5] 'display-faces)
+(global-set-key [C-f8] 'dired)
+(global-set-key [C-f10] 'kill-compilation)
+
+;; Keypad bindings
+(global-set-key [up] "\C-p")
+(global-set-key [down] "\C-n")
+(global-set-key [left] "\C-b")
+(global-set-key [right] "\C-f")
+(global-set-key [home] "\C-a")
+(global-set-key [end] "\C-e")
+(global-set-key [prior] "\M-v")
+(global-set-key [next] "\C-v")
+(global-set-key [C-up] "\M-\C-b")
+(global-set-key [C-down] "\M-\C-f")
+(global-set-key [C-left] "\M-b")
+(global-set-key [C-right] "\M-f")
+(global-set-key [C-home] "\M-<")
+(global-set-key [C-end] "\M->")
+(global-set-key [C-prior] "\M-<")
+(global-set-key [C-next] "\M->")
+
+;; Mouse
+(global-set-key [mouse-3] 'imenu)
+
+;; Misc
+(global-set-key [C-tab] "\C-q\t") ; Control tab quotes a tab.
+(setq backup-by-copying-when-mismatch t)
+
+;; Treat 'y' or <CR> as yes, 'n' as no.
+(fset 'yes-or-no-p 'y-or-n-p)
+(define-key query-replace-map [return] 'act)
+(define-key query-replace-map [?\C-m] 'act)
+
+;; Load packages
+(require 'desktop)
+(require 'tar-mode)
+
+;; Pretty diff mode
+(autoload 'ediff-buffers "ediff" "Intelligent Emacs interface to diff" t)
+(autoload 'ediff-files "ediff" "Intelligent Emacs interface to diff" t)
+(autoload 'ediff-files-remote "ediff"
+ "Intelligent Emacs interface to diff")
+
+(if first-time
+ (setq auto-mode-alist
+ (append '(("\\.cpp$" . c++-mode)
+ ("\\.hpp$" . c++-mode)
+ ("\\.lsp$" . lisp-mode)
+ ("\\.scm$" . scheme-mode)
+ ("\\.pl$" . perl-mode)
+ ) auto-mode-alist)))
+
+;; Auto font lock mode
+(defvar font-lock-auto-mode-list
+ (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode)
+ "List of modes to always start in font-lock-mode")
+
+(defvar font-lock-mode-keyword-alist
+ '((c++-c-mode . c-font-lock-keywords)
+ (perl-mode . perl-font-lock-keywords))
+ "Associations between modes and keywords")
+
+(defun font-lock-auto-mode-select ()
+ "Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list"
+ (if (memq major-mode font-lock-auto-mode-list)
+ (progn
+ (font-lock-mode t))
+ )
+ )
+
+(global-set-key [M-f1] 'font-lock-fontify-buffer)
+
+;; New dabbrev stuff
+;(require 'new-dabbrev)
+(setq dabbrev-always-check-other-buffers t)
+(setq dabbrev-abbrev-char-regexp "\\sw\\|\\s_")
+(add-hook 'emacs-lisp-mode-hook
+ '(lambda ()
+ (set (make-local-variable 'dabbrev-case-fold-search) nil)
+ (set (make-local-variable 'dabbrev-case-replace) nil)))
+(add-hook 'c-mode-hook
+ '(lambda ()
+ (set (make-local-variable 'dabbrev-case-fold-search) nil)
+ (set (make-local-variable 'dabbrev-case-replace) nil)))
+(add-hook 'text-mode-hook
+ '(lambda ()
+ (set (make-local-variable 'dabbrev-case-fold-search) t)
+ (set (make-local-variable 'dabbrev-case-replace) t)))
+
+;; C++ and C mode...
+(defun my-c++-mode-hook ()
+ (setq tab-width 4)
+ (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
+ (define-key c++-mode-map "\C-ce" 'c-comment-edit)
+ (setq c++-auto-hungry-initial-state 'none)
+ (setq c++-delete-function 'backward-delete-char)
+ (setq c++-tab-always-indent t)
+ (setq c-indent-level 4)
+ (setq c-continued-statement-offset 4)
+ (setq c++-empty-arglist-indent 4))
+
+(defun my-c-mode-hook ()
+ (setq tab-width 4)
+ (define-key c-mode-map "\C-m" 'reindent-then-newline-and-indent)
+ (define-key c-mode-map "\C-ce" 'c-comment-edit)
+ (setq c-auto-hungry-initial-state 'none)
+ (setq c-delete-function 'backward-delete-char)
+ (setq c-tab-always-indent t)
+;; BSD-ish indentation style
+ (setq c-indent-level 4)
+ (setq c-continued-statement-offset 4)
+ (setq c-brace-offset -4)
+ (setq c-argdecl-indent 0)
+ (setq c-label-offset -4))
+
+;; Perl mode
+(defun my-perl-mode-hook ()
+ (setq tab-width 4)
+ (define-key c++-mode-map "\C-m" 'reindent-then-newline-and-indent)
+ (setq perl-indent-level 4)
+ (setq perl-continued-statement-offset 4))
+
+;; Scheme mode...
+(defun my-scheme-mode-hook ()
+ (define-key scheme-mode-map "\C-m" 'reindent-then-newline-and-indent))
+
+;; Emacs-Lisp mode...
+(defun my-lisp-mode-hook ()
+ (define-key lisp-mode-map "\C-m" 'reindent-then-newline-and-indent)
+ (define-key lisp-mode-map "\C-i" 'lisp-indent-line)
+ (define-key lisp-mode-map "\C-j" 'eval-print-last-sexp))
+
+;; Add all of the hooks...
+(add-hook 'c++-mode-hook 'my-c++-mode-hook)
+(add-hook 'c-mode-hook 'my-c-mode-hook)
+(add-hook 'scheme-mode-hook 'my-scheme-mode-hook)
+(add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook)
+(add-hook 'lisp-mode-hook 'my-lisp-mode-hook)
+(add-hook 'perl-mode-hook 'my-perl-mode-hook)
+
+;; Complement to next-error
+(defun previous-error (n)
+ "Visit previous compilation error message and corresponding source code."
+ (interactive "p")
+ (next-error (- n)))
+
+;; Misc...
+(transient-mark-mode 1)
+(setq mark-even-if-inactive t)
+(setq visible-bell nil)
+(setq next-line-add-newlines nil)
+(setq compile-command "make")
+(setq suggest-key-bindings nil)
+(put 'eval-expression 'disabled nil)
+(put 'narrow-to-region 'disabled nil)
+(put 'set-goal-column 'disabled nil)
+(if (>= emacs-major-version 21)
+ (setq show-trailing-whitespace t))
+
+;; Elisp archive searching
+(autoload 'format-lisp-code-directory "lispdir" nil t)
+(autoload 'lisp-dir-apropos "lispdir" nil t)
+(autoload 'lisp-dir-retrieve "lispdir" nil t)
+(autoload 'lisp-dir-verify "lispdir" nil t)
+
+;; Font lock mode
+(defun my-make-face (face color &optional bold)
+ "Create a face from a color and optionally make it bold"
+ (make-face face)
+ (copy-face 'default face)
+ (set-face-foreground face color)
+ (if bold (make-face-bold face))
+ )
+
+(if (eq window-system 'x)
+ (progn
+ (my-make-face 'blue "blue")
+ (my-make-face 'red "red")
+ (my-make-face 'green "dark green")
+ (setq font-lock-comment-face 'blue)
+ (setq font-lock-string-face 'bold)
+ (setq font-lock-type-face 'bold)
+ (setq font-lock-keyword-face 'bold)
+ (setq font-lock-function-name-face 'red)
+ (setq font-lock-doc-string-face 'green)
+ (add-hook 'find-file-hooks 'font-lock-auto-mode-select)
+
+ (setq baud-rate 1000000)
+ (global-set-key "\C-cmm" 'menu-bar-mode)
+ (global-set-key "\C-cms" 'scroll-bar-mode)
+ (global-set-key [backspace] 'backward-delete-char)
+ ; (global-set-key [delete] 'delete-char)
+ (standard-display-european t)
+ (load-library "iso-transl")))
+
+;; X11 or PC using direct screen writes
+(if window-system
+ (progn
+ ;; (global-set-key [M-f1] 'hilit-repaint-command)
+ ;; (global-set-key [M-f2] [?\C-u M-f1])
+ (setq hilit-mode-enable-list
+ '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode
+ scheme-mode)
+ hilit-auto-highlight nil
+ hilit-auto-rehighlight 'visible
+ hilit-inhibit-hooks nil
+ hilit-inhibit-rebinding t)
+ (require 'hilit19)
+ (require 'paren))
+ (setq baud-rate 2400) ; For slow serial connections
+ )
+
+;; TTY type terminal
+(if (and (not window-system)
+ (not (equal system-type 'ms-dos)))
+ (progn
+ (if first-time
+ (progn
+ (keyboard-translate ?\C-h ?\C-?)
+ (keyboard-translate ?\C-? ?\C-h)))))
+
+;; Under UNIX
+(if (not (equal system-type 'ms-dos))
+ (progn
+ (if first-time
+ (server-start))))
+
+;; Add any face changes here
+(add-hook 'term-setup-hook 'my-term-setup-hook)
+(defun my-term-setup-hook ()
+ (if (eq window-system 'pc)
+ (progn
+;; (set-face-background 'default "red")
+ )))
+
+;; Restore the "desktop" - do this as late as possible
+(if first-time
+ (progn
+ (desktop-load-default)
+ (desktop-read)))
+
+;; Indicate that this file has been read at least once
+(setq first-time nil)
+
+;; No need to debug anything now
+
+(setq debug-on-error nil)
+
+;; All done
+(message "All done, %s%s" (user-login-name) ".")
+....
+====
+
+=== Расширение списка языков, понимаемых Emacs
+
+Вот, это все хорошо, если вы хотите программировать только на языках, уже предусмотренных в [.filename]#.emacs# (C, C++, Perl, Lisp и Scheme), но что произойдет, если появится новый язык под названием "whizbang", полный захватывающих возможностей?
+
+Первое, что нужно сделать, — это выяснить, поставляются ли с whizbang какие-либо файлы, сообщающие Emacs о языке. Обычно они заканчиваются на [.filename]#.el#, что означает "Emacs Lisp". Например, если whizbang является портом FreeBSD, мы можем найти эти файлы, выполнив
+
+[source, bash]
+....
+% find /usr/ports/lang/whizbang -name "*.el" -print
+....
+
+и установите их, скопировав в каталог Emacs, где находятся файлы Lisp (site Lisp). В FreeBSD это [.filename]#/usr/local/share/emacs/site-lisp#.
+
+Вот пример, если вывод команды find был
+
+[source, bash]
+....
+/usr/ports/lang/whizbang/work/misc/whizbang.el
+....
+
+мы бы сделали
+
+[source, bash]
+....
+# cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp
+....
+
+Далее нам нужно решить, какое расширение имеют исходные файлы whizbang. Допустим, для примера, что все они заканчиваются на [.filename]#.wiz#. Нам необходимо добавить запись в наш [.filename]#.emacs#, чтобы убедиться, что Emacs сможет использовать информацию из [.filename]#whizbang.el#.
+
+Найдите запись auto-mode-alist в файле [.filename]#.emacs# и добавьте строку для whizbang, например:
+
+[.programlisting]
+....
+...
+("\\.lsp$" . lisp-mode)
+("\\.wiz$" . whizbang-mode)
+("\\.scm$" . scheme-mode)
+...
+....
+
+Это означает, что Emacs автоматически перейдёт в режим `whizbang-mode` при редактировании файла с расширением [.filename]#.wiz#.
+
+Непосредственно ниже вы найдете запись font-lock-auto-mode-list. Добавьте `whizbang-mode` в нее следующим образом:
+
+[.programlisting]
+....
+;; Auto font lock mode
+(defvar font-lock-auto-mode-list
+ (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode)
+ "List of modes to always start in font-lock-mode")
+....
+
+Это означает, что Emacs всегда будет включать `font-lock-mode` (т.е. подсветку синтаксиса) при редактировании файла [.filename]#.wiz#.
+
+И это всё, что требуется. Если вам нужно, чтобы что-то ещё выполнялось автоматически при открытии [.filename]#.wiz#, вы можете добавить `whizbang-mode hook` (см. `my-scheme-mode-hook` для простого примера, который добавляет `auto-indent`).
+
+[[tools-reading]]
+== Для дальнейшего ознакомления
+
+Для получения информации о настройке среды разработки для внесения исправлений в саму FreeBSD см. man:development[7].
+
+* Brian Harvey and Matthew Wright _Simply Scheme_ MIT 1994. ISBN 0-262-08226-8
+* Randall Schwartz _Learning Perl_ O'Reilly 1993 ISBN 1-56592-042-2
+* Patrick Henry Winston and Berthold Klaus Paul Horn _Lisp (3rd Edition)_ Addison-Wesley 1989 ISBN 0-201-08319-1
+* Brian W. Kernighan and Rob Pike _The Unix Programming Environment_ Prentice-Hall 1984 ISBN 0-13-937681-X
+* Brian W. Kernighan and Dennis M. Ritchie _The C Programming Language (2nd Edition)_ Prentice-Hall 1988 ISBN 0-13-110362-8
+* Bjarne Stroustrup _The C++ Programming Language_ Addison-Wesley 1991 ISBN 0-201-53992-6
+* W. Richard Stevens _Advanced Programming in the Unix Environment_ Addison-Wesley 1992 ISBN 0-201-56317-7
+* W. Richard Stevens _Unix Network Programming_ Prentice-Hall 1990 ISBN 0-13-949876-1
diff --git a/documentation/content/ru/books/developers-handbook/tools/_index.po b/documentation/content/ru/books/developers-handbook/tools/_index.po
new file mode 100644
index 0000000000..47c68c25ff
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/tools/_index.po
@@ -0,0 +1,4483 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-07-05 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbooktools_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:17
+#, no-wrap
+msgid "Programming Tools"
+msgstr "Инструменты разработки"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1
+#, no-wrap
+msgid "Chapter 2. Programming Tools"
+msgstr "Глава 2. Инструменты разработки"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:57
+#, no-wrap
+msgid "Synopsis"
+msgstr "Обзор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:64
+msgid ""
+"This chapter is an introduction to using some of the programming tools "
+"supplied with FreeBSD, although much of it will be applicable to many other "
+"versions of UNIX(R). It does _not_ attempt to describe coding in any "
+"detail. Most of the chapter assumes little or no previous programming "
+"knowledge, although it is hoped that most programmers will find something of "
+"value in it."
+msgstr ""
+"В этой главе представлено введение в использование некоторых инструментов "
+"для программирования, поставляемых с FreeBSD, хотя многое из описанного "
+"применимо и к другим версиям UNIX(R). Она _не_ претендует на детальное "
+"описание процесса написания кода. Большая часть главы предполагает наличие "
+"минимальных или отсутствие знаний в программировании, хотя предполагается, "
+"что даже опытные программисты найдут в ней что-то полезное."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:66
+#, no-wrap
+msgid "Introduction"
+msgstr "Введение"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:73
+msgid ""
+"FreeBSD offers an excellent development environment. Compilers for C and C+"
+"+ and an assembler come with the basic system, not to mention classic "
+"UNIX(R) tools such as `sed` and `awk`. If that is not enough, there are "
+"many more compilers and interpreters in the Ports collection. The following "
+"section, crossref:tools[tools-programming,Introduction to Programming], "
+"lists some of the available options. FreeBSD is very compatible with "
+"standards such as POSIX(R) and ANSI C, as well with its own BSD heritage, so "
+"it is possible to write applications that will compile and run with little "
+"or no modification on a wide range of platforms."
+msgstr ""
+"FreeBSD предоставляет отличную среду разработки. Компиляторы для C и C++, а "
+"также ассемблер входят в базовую систему, не говоря уже о классических "
+"инструментах UNIX(R), таких как `sed` и `awk`. Если этого недостаточно, в "
+"коллекции Ports доступно множество других компиляторов и интерпретаторов. В "
+"следующем разделе, crossref:tools[tools-programming,Введение в "
+"программирование], перечислены некоторые из доступных вариантов. FreeBSD "
+"обладает высокой совместимостью со стандартами, такими как POSIX(R) и ANSI "
+"C, а также с собственным наследием BSD, что позволяет создавать приложения, "
+"которые будут компилироваться и запускаться с минимальными изменениями или "
+"без них на широком спектре платформ."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:77
+msgid ""
+"However, all this power can be rather overwhelming at first if you have "
+"never written programs on a UNIX(R) platform before. This document aims to "
+"help you get up and running, without getting too deeply into more advanced "
+"topics. The intention is that this document should give you enough of the "
+"basics to be able to make some sense of the documentation."
+msgstr ""
+"Однако вся эта мощь может поначалу ошеломить, если вы никогда раньше не "
+"писали программы на платформе UNIX(R). Этот документ призван помочь вам "
+"начать работу, не углубляясь слишком сильно в более сложные темы. Цель "
+"заключается в том, чтобы дать вам достаточно базовых знаний для понимания "
+"документации."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:79
+msgid ""
+"Most of the document requires little or no knowledge of programming, "
+"although it does assume a basic competence with using UNIX(R) and a "
+"willingness to learn!"
+msgstr ""
+"Большая часть документа не требует или почти не требует знаний "
+"программирования, хотя предполагает базовые навыки работы с UNIX(R) и "
+"готовность учиться!"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:81
+#, no-wrap
+msgid "Introduction to Programming"
+msgstr "Введение в программирование"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:87
+msgid ""
+"A program is a set of instructions that tell the computer to do various "
+"things; sometimes the instruction it has to perform depends on what happened "
+"when it performed a previous instruction. This section gives an overview of "
+"the two main ways in which you can give these instructions, or \"commands\" "
+"as they are usually called. One way uses an _interpreter_, the other a "
+"_compiler_. As human languages are too difficult for a computer to "
+"understand in an unambiguous way, commands are usually written in one or "
+"other languages specially designed for the purpose."
+msgstr ""
+"Программа — это набор инструкций, которые указывают компьютеру выполнять "
+"различные действия; иногда выполняемая инструкция зависит от результата "
+"предыдущей. В этом разделе представлен обзор двух основных способов передачи "
+"таких инструкций, или, как их обычно называют, «команд». Один способ "
+"использует _интерпретатор_, другой — _компилятор_. Поскольку человеческие "
+"языки слишком сложны для однозначного понимания компьютером, команды обычно "
+"записываются на одном из специально разработанных для этого языков."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:88
+#, no-wrap
+msgid "Interpreters"
+msgstr "Интерпретаторы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:93
+msgid ""
+"With an interpreter, the language comes as an environment, where you type in "
+"commands at a prompt and the environment executes them for you. For more "
+"complicated programs, you can type the commands into a file and get the "
+"interpreter to load the file and execute the commands in it. If anything "
+"goes wrong, many interpreters will drop you into a debugger to help you "
+"track down the problem."
+msgstr ""
+"С интерпретатором язык поставляется как среда, в которой вы вводите команды "
+"в приглашении, и среда выполняет их для вас. Для более сложных программ вы "
+"можете ввести команды в файл и заставить интерпретатор загрузить файл и "
+"выполнить команды в нём. Если что-то пойдёт не так, многие интерпретаторы "
+"переведут вас в отладчик, чтобы помочь найти проблему."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:98
+msgid ""
+"The advantage of this is that you can see the results of your commands "
+"immediately, and mistakes can be corrected readily. The biggest "
+"disadvantage comes when you want to share your programs with someone. They "
+"must have the same interpreter, or you must have some way of giving it to "
+"them, and they need to understand how to use it. Also users may not "
+"appreciate being thrown into a debugger if they press the wrong key! From a "
+"performance point of view, interpreters can use up a lot of memory, and "
+"generally do not generate code as efficiently as compilers."
+msgstr ""
+"Преимущество этого подхода в том, что вы сразу видите результаты выполнения "
+"команд, а ошибки можно легко исправить. Самый большой недостаток "
+"проявляется, когда вы хотите поделиться своими программами с кем-то. У них "
+"должен быть такой же интерпретатор, или у вас должен быть способ "
+"предоставить его, и они должны понимать, как им пользоваться. Кроме того, "
+"пользователям может не понравиться, если они попадут в отладчик при нажатии "
+"не той клавиши! С точки зрения производительности интерпретаторы могут "
+"потреблять много памяти и обычно генерируют код менее эффективно, чем "
+"компиляторы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:103
+msgid ""
+"In my opinion, interpreted languages are the best way to start if you have "
+"not done any programming before. This kind of environment is typically "
+"found with languages like Lisp, Smalltalk, Perl and Basic. It could also be "
+"argued that the UNIX(R) shell (`sh`, `csh`) is itself an interpreter, and "
+"many people do in fact write shell \"scripts\" to help with various "
+"\"housekeeping\" tasks on their machine. Indeed, part of the original "
+"UNIX(R) philosophy was to provide lots of small utility programs that could "
+"be linked together in shell scripts to perform useful tasks."
+msgstr ""
+"По моему мнению, интерпретируемые языки — это лучший способ начать, если вы "
+"раньше не занимались программированием. Такая среда обычно встречается в "
+"языках вроде Lisp, Smalltalk, Perl и Basic. Можно также утверждать, что "
+"UNIX(R) shell (`sh`, `csh`) сам по себе является интерпретатором, и многие "
+"часто пишут shell-«скрипты» для помощи в различных «хозяйственных» задачах "
+"на своих машинах. Действительно, часть оригинальной философии UNIX(R) "
+"заключалась в предоставлении множества небольших утилит, которые можно было "
+"связывать вместе в shell-скриптах для выполнения полезных задач."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:104
+#, no-wrap
+msgid "Interpreters Available with FreeBSD"
+msgstr "Доступные интерпретаторы в FreeBSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:107
+msgid ""
+"Here is a list of interpreters that are available from the FreeBSD Ports "
+"Collection, with a brief discussion of some of the more popular interpreted "
+"languages."
+msgstr ""
+"Вот список интерпретаторов, доступных в Коллекции портов FreeBSD, с кратким "
+"обзором некоторых наиболее популярных интерпретируемых языков."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:109
+msgid ""
+"Instructions on how to get and install applications from the Ports "
+"Collection can be found in the extref:{handbook}[Ports section, ports-using] "
+"of the handbook."
+msgstr ""
+"Инструкции по получению и установке приложений из Коллекции портов можно "
+"найти в extref:{handbook}[разделе Порты, ports-using] руководства."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:110
+#, no-wrap
+msgid "BASIC"
+msgstr "BASIC"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:114
+msgid ""
+"Short for Beginner's All-purpose Symbolic Instruction Code. Developed in "
+"the 1950s for teaching University students to program and provided with "
+"every self-respecting personal computer in the 1980s, BASIC has been the "
+"first programming language for many programmers. It is also the foundation "
+"for Visual Basic."
+msgstr ""
+"Сокращение от Beginner's All-purpose Symbolic Instruction Code. Разработан в "
+"1950-х годах для обучения студентов университетов программированию и "
+"поставлялся с каждым уважающим себя персональным компьютером в 1980-х. BASIC "
+"— первый язык программирования для многих программистов. Он также является "
+"основой для Visual Basic."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:116
+msgid ""
+"The Bywater Basic Interpreter can be found in the Ports Collection as "
+"package:lang/bwbasic[] and the Phil Cockroft's Basic Interpreter (formerly "
+"Rabbit Basic) is available as package:lang/pbasic[]."
+msgstr ""
+"Интерпретатор Bywater Basic можно найти в Коллекции портов как package:lang/"
+"bwbasic[], а интерпретатор Phil Cockroft's Basic (ранее известный как Rabbit "
+"Basic) доступен как package:lang/pbasic[]."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:117
+#, no-wrap
+msgid "Lisp"
+msgstr "Lisp"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:121
+msgid ""
+"A language that was developed in the late 1950s as an alternative to the "
+"\"number-crunching\" languages that were popular at the time. Instead of "
+"being based on numbers, Lisp is based on lists; in fact, the name is short "
+"for \"List Processing\". It is very popular in AI (Artificial Intelligence) "
+"circles."
+msgstr ""
+"Язык, разработанный в конце 1950-х годов как альтернатива популярным в то "
+"время языкам для «численных расчётов». В отличие от них, Lisp основан на "
+"списках; фактически, название является сокращением от «List Processing» "
+"(обработка списков). Он очень популярен в кругах, связанных с ИИ "
+"(искусственным интеллектом)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:123
+msgid ""
+"Lisp is an extremely powerful and sophisticated language, but can be rather "
+"large and unwieldy."
+msgstr ""
+"Lisp — это чрезвычайно мощный и сложный язык, но он может показаться "
+"довольно большим и громоздким."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:127
+msgid ""
+"Various implementations of Lisp that can run on UNIX(R) systems are "
+"available in the Ports Collection for FreeBSD. CLISP by Bruno Haible and "
+"Michael Stoll is available as package:lang/clisp[]. SLisp, a simpler Lisp "
+"implementations, is available as package:lang/slisp[]."
+msgstr ""
+"В Коллекции портов FreeBSD доступны различные реализации Lisp, которые могут "
+"работать в системах UNIX(R). CLISP от Bruno Haible и Michael Stoll доступен "
+"как package:lang/clisp[]. Более простая реализация Lisp, SLisp, доступна как "
+"package:lang/slisp[]."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:128
+#, no-wrap
+msgid "Perl"
+msgstr "Perl"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:130
+msgid ""
+"Very popular with system administrators for writing scripts; also often used "
+"on World Wide Web servers for writing CGI scripts."
+msgstr ""
+"Очень популярен среди системных администраторов для написания скриптов; "
+"также часто используется на веб-серверах для написания CGI-скриптов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:132
+msgid ""
+"Perl is available in the Ports Collection as package:lang/perl5.36[] for all "
+"FreeBSD releases."
+msgstr ""
+"Perl доступен в Коллекции портов как package:lang/perl5.36[] для всех "
+"выпусков FreeBSD."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:133
+#, no-wrap
+msgid "Scheme"
+msgstr "Scheme"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:137
+msgid ""
+"A dialect of Lisp that is rather more compact and cleaner than Common Lisp. "
+"Popular in Universities as it is simple enough to teach to undergraduates as "
+"a first language, while it has a high enough level of abstraction to be used "
+"in research work."
+msgstr ""
+"Диалект Lisp, который более компактен и чист по сравнению с Common Lisp. "
+"Популярен в университетах, так как достаточно прост для обучения студентов в "
+"качестве первого языка, и при этом обладает достаточным уровнем абстракции "
+"для использования в исследовательской работе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:140
+msgid ""
+"Scheme is available from the Ports Collection as package:lang/elk[] for the "
+"Elk Scheme Interpreter. The MIT Scheme Interpreter can be found in "
+"package:lang/mit-scheme[] and the SCM Scheme Interpreter in package:lang/"
+"scm[]."
+msgstr ""
+"Схема доступна из Коллекции Портов как package:lang/elk[] для Интерпретатора "
+"Elk Scheme. Интерпретатор MIT Scheme можно найти в package:lang/mit-"
+"scheme[], а Интерпретатор SCM Scheme — в package:lang/scm[]."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:141
+#, no-wrap
+msgid "Lua"
+msgstr "Lua"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:147
+msgid ""
+"Lua is a lightweight embeddable scripting language. It is widely portable "
+"and relatively simple. Lua is available in the Ports Collection in "
+"package:lang/lua54[]. It is also included in the base system as "
+"[.filename]#/usr/libexec/flua# for use by base system components. Third "
+"party software should not depend on [.filename]#flua#."
+msgstr ""
+"Lua — это легковесный встраиваемый язык сценариев. Он обладает высокой "
+"переносимостью и относительно прост. Lua доступен в коллекции портов в "
+"пакете package:lang/lua54[]. Он также включен в базовую систему как "
+"[.filename]#/usr/libexec/flua# для использования компонентами базовой "
+"системы. Стороннее программное обеспечение не должно зависеть от "
+"[.filename]#flua#."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:148
+#, no-wrap
+msgid "Python"
+msgstr "Python"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:151
+msgid ""
+"Python is an Object-Oriented, interpreted language. Its advocates argue "
+"that it is one of the best languages to start programming with, since it is "
+"relatively easy to start with, but is not limited in comparison to other "
+"popular interpreted languages that are used for the development of large, "
+"complex applications (Perl and Tcl are two other languages that are popular "
+"for such tasks)."
+msgstr ""
+"Python — это объектно-ориентированный интерпретируемый язык. Его сторонники "
+"утверждают, что это один из лучших языков для начала программирования, "
+"поскольку он относительно прост в освоении, но не уступает другим популярным "
+"интерпретируемым языкам, используемым для разработки крупных и сложных "
+"приложений (Perl и Tcl — два других языка, популярных для таких задач)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:153
+msgid ""
+"The latest version of Python is available from the Ports Collection in "
+"package:lang/python[]."
+msgstr ""
+"Последняя версия Python доступна в Коллекции портов в пакете package:lang/"
+"python[]."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:154
+#, no-wrap
+msgid "Ruby"
+msgstr "Ruby"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:157
+msgid ""
+"Ruby is an interpreter, pure object-oriented programming language. It has "
+"become widely popular because of its easy to understand syntax, flexibility "
+"when writing code, and the ability to easily develop and maintain large, "
+"complex programs."
+msgstr ""
+"Ruby — это интерпретируемый, чисто объектно-ориентированный язык "
+"программирования. Он получил широкую популярность благодаря простому для "
+"понимания синтаксису, гибкости при написании кода и возможности легко "
+"разрабатывать и поддерживать большие, сложные программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:159
+msgid "Ruby is available from the Ports Collection as package:lang/ruby32[]."
+msgstr "Ruby доступен в Коллекции портов как package:lang/ruby32[]."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:160
+#, no-wrap
+msgid "Tcl and Tk"
+msgstr "Tcl и Tk"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:163
+msgid ""
+"Tcl is an embeddable, interpreted language, that has become widely used and "
+"became popular mostly because of its portability to many platforms. It can "
+"be used both for quickly writing small, prototype applications, or (when "
+"combined with Tk, a GUI toolkit) fully-fledged, featureful programs."
+msgstr ""
+"Tcl — это встраиваемый интерпретируемый язык, который получил широкое "
+"распространение и популярность в основном благодаря своей переносимости на "
+"множество платформ. Он может использоваться как для быстрого написания "
+"небольших прототипов приложений, так и (в сочетании с Tk, набором "
+"инструментов для графического интерфейса) полноценных программ с богатым "
+"функционалом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:166
+msgid ""
+"Various versions of Tcl are available as ports for FreeBSD. The latest "
+"version, Tcl 8.7, can be found in package:lang/tcl87[]."
+msgstr ""
+"Различные версии Tcl доступны в качестве портов для FreeBSD. Последняя "
+"версия, Tcl 8.7, находится в пакете package:lang/tcl87[]."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:167
+#, no-wrap
+msgid "Compilers"
+msgstr "Компиляторы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:174
+msgid ""
+"Compilers are rather different. First of all, you write your code in a file "
+"(or files) using an editor. You then run the compiler and see if it accepts "
+"your program. If it did not compile, grit your teeth and go back to the "
+"editor; if it did compile and gave you a program, you can run it either at a "
+"shell command prompt or in a debugger to see if it works properly.footnote:"
+"[If you run it in the shell, you may get a core dump.]"
+msgstr ""
+"Компиляторы довольно сильно различаются. Прежде всего, вы пишете свой код в "
+"файле (или файлах) с помощью редактора. Затем вы запускаете компилятор и "
+"проверяете, принимает ли он вашу программу. Если программа не "
+"скомпилировалась, стисните зубы и вернитесь к редактору; если же компиляция "
+"прошла успешно и программа была создана, вы можете запустить её либо в "
+"командной строке оболочки, либо в отладчике, чтобы проверить её "
+"работу.footnote:[Если вы запустите её в оболочке, может произойти дамп "
+"памяти.]"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:181
+msgid ""
+"Obviously, this is not quite as direct as using an interpreter. However it "
+"allows you to do a lot of things which are very difficult or even impossible "
+"with an interpreter, such as writing code which interacts closely with the "
+"operating system-or even writing your own operating system! It is also "
+"useful if you need to write very efficient code, as the compiler can take "
+"its time and optimize the code, which would not be acceptable in an "
+"interpreter. Moreover, distributing a program written for a compiler is "
+"usually more straightforward than one written for an interpreter-you can "
+"just give them a copy of the executable, assuming they have the same "
+"operating system as you."
+msgstr ""
+"Очевидно, это требует больше усилий по сравнению с использованием "
+"интерпретатора. Однако это позволяет делать множество вещей, которые очень "
+"сложны или даже невозможны с интерпретатором, например, писать код, тесно "
+"взаимодействующий с операционной системой — или даже создавать собственную "
+"операционную систему! Это также полезно, если требуется написать очень "
+"эффективный код, так как компилятор может не спешить и оптимизировать код, "
+"что было бы неприемлемо в интерпретаторе. Более того, распространение "
+"программы, написанной для компилятора, обычно проще, чем для интерпретатора "
+"— можно просто предоставить копию исполняемого файла, предполагая, что у "
+"пользователя та же операционная система, что и у вас."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:185
+msgid ""
+"As the edit-compile-run-debug cycle is rather tedious when using separate "
+"programs, many commercial compiler makers have produced Integrated "
+"Development Environments (IDEs for short). FreeBSD does not include an IDE "
+"in the base system, but package:devel/kdevelop[] is available in the Ports "
+"Collection and many use Emacs for this purpose. Using Emacs as an IDE is "
+"discussed in crossref:tools[emacs, Using Emacs as a Development Environment]."
+msgstr ""
+"Поскольку цикл редактирования-компиляции-запуска-отладки довольно утомителен "
+"при использовании отдельных программ, многие производители коммерческих "
+"компиляторов создали интегрированные среды разработки (сокращённо IDE). "
+"FreeBSD не включает IDE в базовую систему, но в Коллекции портов доступен "
+"package:devel/kdevelop[], и многие используют для этой цели Emacs. "
+"Использование Emacs в качестве IDE обсуждается в crossref:tools[emacs, "
+"Использование Emacs как среды разработки]."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:187
+#, no-wrap
+msgid "Compiling with `cc`"
+msgstr "Компиляция с помощью `cc`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:192
+msgid ""
+"This section deals with the clang compiler for C and C++, as it's installed "
+"with the FreeBSD base system. Clang is installed as `cc`; the GNU compiler "
+"package:lang/gcc[gcc] is available in the Ports Collection. The details of "
+"producing a program with an interpreter vary considerably between "
+"interpreters, and are usually well covered in the documentation and on-line "
+"help for the interpreter."
+msgstr ""
+"Этот раздел посвящён компилятору clang для языков C и C++, так как он "
+"устанавливается вместе с базовой системой FreeBSD. Clang устанавливается как "
+"`cc`; пакет GNU-компилятора package:lang/gcc[gcc] доступен в Коллекции "
+"портов. Детали создания программы с интерпретатором значительно различаются "
+"в зависимости от интерпретатора и обычно хорошо описаны в документации и "
+"онлайн-справке интерпретатора."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:195
+msgid ""
+"Once you have written your masterpiece, the next step is to convert it into "
+"something that will (hopefully!) run on FreeBSD. This usually involves "
+"several steps, each of which is done by a separate program."
+msgstr ""
+"Как только вы напишете свой шедевр, следующий шаг — преобразовать его во что-"
+"то, что (надеюсь!) будет работать на FreeBSD. Обычно это включает несколько "
+"шагов, каждый из которых выполняется отдельной программой."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:198
+msgid ""
+"Pre-process your source code to remove comments and do other tricks like "
+"expanding macros in C."
+msgstr ""
+"Обработь исходный код, чтобы удалить комментарии и выполнить другие "
+"действия, такие как раскрытие макросов в C."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:199
+msgid ""
+"Check the syntax of your code to see if you have obeyed the rules of the "
+"language. If you have not, it will complain!"
+msgstr ""
+"Проверить синтаксис вашего кода, чтобы убедиться, что вы соблюдаете правила "
+"языка. Если нет, он пожалуется!"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:200
+msgid ""
+"Convert the source code into assembly language-this is very close to machine "
+"code, but still understandable by humans. Allegedly."
+msgstr ""
+"Преобразовать исходный код в ассемблерный язык — это очень близко к "
+"машинному коду, но всё ещё понятно человеку. Как утверждается."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:201
+msgid ""
+"Convert the assembly language into machine code-yep, we are talking bits and "
+"bytes, ones and zeros here."
+msgstr ""
+"Преобразовать язык ассемблера в машинный код — да, здесь речь идет о битах и "
+"байтах, единицах и нулях."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:202
+msgid ""
+"Check that you have used things like functions and global variables in a "
+"consistent way. For example, if you have called a non-existent function, it "
+"will complain."
+msgstr ""
+"Проверить, что вы использовали такие элементы, как функции и глобальные "
+"переменные, правильно и последовательно. Например, если вы вызвали "
+"несуществующую функцию, это будет отмечено."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:203
+msgid ""
+"If you are trying to produce an executable from several source code files, "
+"work out how to fit them all together."
+msgstr ""
+"Если вы пытаетесь создать исполняемый файл из нескольких исходных файлов, "
+"определить, как объединить их все вместе."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:204
+msgid ""
+"Work out how to produce something that the system's run-time loader will be "
+"able to load into memory and run."
+msgstr ""
+"Определить, как создать что-то, что загрузчик времени выполнения системы "
+"сможет загрузить в память и запустить."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:205
+msgid "Finally, write the executable on the filesystem."
+msgstr "Наконец, записать исполняемый файл в файловую систему."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:208
+msgid ""
+"The word _compiling_ is often used to refer to just steps 1 to 4-the others "
+"are referred to as _linking_. Sometimes step 1 is referred to as _pre-"
+"processing_ and steps 3-4 as _assembling_."
+msgstr ""
+"Слово _компиляция_ часто относится только к шагам с 1 по 4, а остальные шаги "
+"называются _линковкой_. Иногда шаг 1 называют _препроцессированием_, а шаги "
+"3-4 — _ассемблированием_."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:210
+msgid ""
+"Fortunately, almost all this detail is hidden from you, as `cc` is a front "
+"end that manages calling all these programs with the right arguments for "
+"you; simply typing"
+msgstr ""
+"К счастью, почти все эти детали скрыты от вас, так как `cc` — это интерфейс, "
+"который управляет вызовом всех этих программ с правильными аргументами за "
+"вас; достаточно просто набрать"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:214
+#, no-wrap
+msgid "% cc foobar.c\n"
+msgstr "% cc foobar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:218
+msgid ""
+"will cause [.filename]#foobar.c# to be compiled by all the steps above. If "
+"you have more than one file to compile, just do something like"
+msgstr ""
+"и это вызовет компиляцию файла [.filename]#foobar.c# всеми перечисленными "
+"выше шагами. Если у вас несколько файлов для компиляции, просто сделайте что-"
+"то вроде"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:222
+#, no-wrap
+msgid "% cc foo.c bar.c\n"
+msgstr "% cc foo.c bar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:227
+msgid ""
+"Note that the syntax checking is just that - checking the syntax. It will "
+"not check for any logical mistakes you may have made, like putting the "
+"program into an infinite loop, or using a bubble sort when you meant to use "
+"a binary sort.footnote:[In case you did not know, a binary sort is an "
+"efficient way of sorting things into order and a bubble sort is not.]"
+msgstr ""
+"Обратите внимание, что проверка синтаксиса — это всего лишь проверка "
+"синтаксиса. Она не выявит логических ошибок, которые вы могли допустить, "
+"например, создание бесконечного цикла или использование пузырьковой "
+"сортировки вместо бинарной.footnote:[На случай, если вы не знали: бинарная "
+"сортировка — это эффективный способ упорядочивания элементов, в отличие от "
+"пузырьковой.]"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:230
+msgid ""
+"There are lots and lots of options for `cc`, which are all in the manual "
+"page. Here are a few of the most important ones, with examples of how to "
+"use them."
+msgstr ""
+"Существует множество опций для `cc`, все они описаны в руководстве. Вот "
+"несколько наиболее важных из них с примерами использования."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:231
+#, no-wrap
+msgid "`-o _filename_`"
+msgstr "`-o _filename_`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:233
+msgid ""
+"The output name of the file. If you do not use this option, `cc` will "
+"produce an executable called [.filename]#a.out#.footnote:[The reasons for "
+"this are buried in the mists of history.]"
+msgstr ""
+"Имя выходного файла. Если вы не используете эту опцию, `cc` создаст "
+"исполняемый файл с именем [.filename]#a.out#.footnote:[Причины этого кроются "
+"в глубинах истории.]"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:238
+#, no-wrap
+msgid ""
+"% cc foobar.c executable is a.out\n"
+"% cc -o foobar foobar.c executable is foobar\n"
+msgstr ""
+"% cc foobar.c executable is a.out\n"
+"% cc -o foobar foobar.c executable is foobar\n"
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:240
+#, no-wrap
+msgid "`-c`"
+msgstr "`-c`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:243
+msgid ""
+"Just compile the file, do not link it. Useful for toy programs where you "
+"just want to check the syntax, or if you are using a [.filename]#Makefile#."
+msgstr ""
+"Просто скомпилирует файл, не связывая его. Полезно для небольших программ, "
+"где нужно только проверить синтаксис, или если вы используете "
+"[.filename]#Makefile#."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:247
+#, no-wrap
+msgid "% cc -c foobar.c\n"
+msgstr "% cc -c foobar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:251
+msgid ""
+"This will produce an _object file_ (not an executable) called "
+"[.filename]#foobar.o#. This can be linked together with other object files "
+"into an executable."
+msgstr ""
+"Это создаст _объектный файл_ (не исполняемый) с именем "
+"[.filename]#foobar.o#. Его можно скомпоновать с другими объектными файлами в "
+"исполняемый файл."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:252
+#, no-wrap
+msgid "`-g`"
+msgstr "`-g`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:258
+msgid ""
+"Create a debug version of the executable. This makes the compiler put "
+"information into the executable about which line of which source file "
+"corresponds to which function call. A debugger can use this information to "
+"show the source code as you step through the program, which is _very_ "
+"useful; the disadvantage is that all this extra information makes the "
+"program much bigger. Normally, you compile with `-g` while you are "
+"developing a program and then compile a \"release version\" without `-g` "
+"when you are satisfied it works properly."
+msgstr ""
+"Создать отладочную версию исполняемого файла. Это заставляет компилятор "
+"записывать в исполняемый файл информацию о том, какая строка какого "
+"исходного файла соответствует какому вызову функции. Отладчик может "
+"использовать эту информацию для отображения исходного кода при пошаговом "
+"выполнении программы, что _очень_ полезно; недостатком является то, что вся "
+"эта дополнительная информация значительно увеличивает размер программы. "
+"Обычно вы компилируете с `-g` во время разработки программы, а затем "
+"компилируете \"релизную версию\" без `-g`, когда убедитесь, что она работает "
+"правильно."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:263
+#, no-wrap
+msgid "% cc -g foobar.c\n"
+msgstr "% cc -g foobar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:266
+msgid ""
+"This will produce a debug version of the program. footnote:[Note, we did not "
+"use the -o flag to specify the executable name, so we will get an executable "
+"called a.out. Producing a debug version called foobar is left as an exercise "
+"for the reader!]"
+msgstr ""
+"Это создаст отладочную версию программы. footnote:[Примечание: мы не "
+"использовали флаг -o для указания имени исполняемого файла, поэтому получим "
+"исполняемый файл с именем a.out. Создание отладочной версии с именем foobar "
+"остается упражнением для читателя!]"
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:267
+#, no-wrap
+msgid "`-O`"
+msgstr "`-O`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:271
+msgid ""
+"Create an optimized version of the executable. The compiler performs "
+"various clever tricks to try to produce an executable that runs faster than "
+"normal. You can add a number after the `-O` to specify a higher level of "
+"optimization, but this often exposes bugs in the compiler's optimizer."
+msgstr ""
+"Создает оптимизированную версию исполняемого файла. Компилятор применяет "
+"различные хитрые приёмы, чтобы попытаться создать исполняемый файл, который "
+"работает быстрее обычного. Вы можете добавить число после `-O`, чтобы "
+"указать более высокий уровень оптимизации, но это часто выявляет ошибки в "
+"оптимизаторе компилятора."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:275
+#, no-wrap
+msgid "% cc -O -o foobar foobar.c\n"
+msgstr "% cc -O -o foobar foobar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:278
+msgid "This will produce an optimized version of [.filename]#foobar#."
+msgstr "Это создаст оптимизированную версию [.filename]#foobar#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:281
+msgid ""
+"The following three flags will force `cc` to check that your code complies "
+"to the relevant international standard, often referred to as the ANSI "
+"standard, though strictly speaking it is an ISO standard."
+msgstr ""
+"Следующие три флага заставят `cc` проверять, что ваш код соответствует "
+"соответствующему международному стандарту, часто называемому стандартом "
+"ANSI, хотя строго говоря, это стандарт ISO."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:282
+#, no-wrap
+msgid "`-Wall`"
+msgstr "`-Wall`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:285
+msgid ""
+"Enable all the warnings which the authors of `cc` believe are worthwhile. "
+"Despite the name, it will not enable all the warnings `cc` is capable of."
+msgstr ""
+"Включить все предупреждения, которые разработчики `cc` считают полезными. "
+"Несмотря на название, это не включит все предупреждения, которые `cc` "
+"способен выдавать."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:286
+#, no-wrap
+msgid "`-ansi`"
+msgstr "`-ansi`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:289
+msgid ""
+"Turn off most, but not all, of the non-ANSI C features provided by `cc`. "
+"Despite the name, it does not guarantee strictly that your code will comply "
+"to the standard."
+msgstr ""
+"Отключит большинство, но не все, не-ANSI C функции, предоставляемые `cc`. "
+"Несмотря на название, это не гарантирует строгого соответствия вашего кода "
+"стандарту."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:290
+#, no-wrap
+msgid "`-pedantic`"
+msgstr "`-pedantic`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:292
+msgid "Turn off _all_ ``cc``'s non-ANSI C features."
+msgstr "Отключит _все_ не-ANSI C возможности ``cc``."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:297
+msgid ""
+"Without these flags, `cc` will allow you to use some of its non-standard "
+"extensions to the standard. Some of these are very useful, but will not "
+"work with other compilers - in fact, one of the main aims of the standard is "
+"to allow people to write code that will work with any compiler on any "
+"system. This is known as _portable code_."
+msgstr ""
+"Без этих флагов `cc` позволит вам использовать некоторые из своих "
+"нестандартных расширений стандарта. Некоторые из них очень полезны, но не "
+"будут работать с другими компиляторами — фактически, одна из основных целей "
+"стандарта заключается в том, чтобы позволить людям писать код, который будет "
+"работать с любым компилятором на любой системе. Это известно как "
+"_переносимый код_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:300
+msgid ""
+"Generally, you should try to make your code as portable as possible, as "
+"otherwise you may have to completely rewrite the program later to get it to "
+"work somewhere else - and who knows what you may be using in a few years "
+"time?"
+msgstr ""
+"Обычно следует стремиться к тому, чтобы ваш код был как можно более "
+"переносимым, иначе позже вам, возможно, придётся полностью переписать "
+"программу для её работы в другом месте — а кто знает, что вы будете "
+"использовать через несколько лет?"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:304
+#, no-wrap
+msgid "% cc -Wall -ansi -pedantic -o foobar foobar.c\n"
+msgstr "% cc -Wall -ansi -pedantic -o foobar foobar.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:307
+msgid ""
+"This will produce an executable [.filename]#foobar# after checking "
+"[.filename]#foobar.c# for standard compliance."
+msgstr ""
+"В результате будет создан исполняемый файл [.filename]#foobar# после "
+"проверки [.filename]#foobar.c# на соответствие стандартам."
+
+#. type: Labeled list
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:308
+#, no-wrap
+msgid "`-l__library__`"
+msgstr "`-l__library__`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:310
+msgid "Specify a function library to be used at link time."
+msgstr ""
+"Укажите библиотеку функций, которая будет использоваться во время компоновки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:313
+msgid ""
+"The most common example of this is when compiling a program that uses some "
+"of the mathematical functions in C. Unlike most other platforms, these are "
+"in a separate library from the standard C one and you have to tell the "
+"compiler to add it."
+msgstr ""
+"Наиболее распространённый пример этого — компиляция программы, использующей "
+"некоторые математические функции в C. В отличие от большинства других "
+"платформ, они находятся в отдельной библиотеке, отличной от стандартной "
+"библиотеки C, и необходимо указать компилятору добавить её."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:317
+msgid ""
+"The rule is that if the library is called [.filename]#libsomething.a#, you "
+"give `cc` the argument `-l__something__`. For example, the math library is "
+"[.filename]#libm.a#, so you give `cc` the argument `-lm`. A common "
+"\"gotcha\" with the math library is that it has to be the last library on "
+"the command line."
+msgstr ""
+"Правило заключается в том, что если библиотека называется "
+"[.filename]#libsomething.a#, то вы передаёте `cc` аргумент `-"
+"l__something__`. Например, математическая библиотека называется "
+"[.filename]#libm.a#, поэтому вы передаёте `cc` аргумент `-lm`. Типичный "
+"подводный камень с математической библиотекой заключается в том, что она "
+"должна быть последней библиотекой в командной строке."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:321
+#, no-wrap
+msgid "% cc -o foobar foobar.c -lm\n"
+msgstr "% cc -o foobar foobar.c -lm\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:324
+msgid "This will link the math library functions into [.filename]#foobar#."
+msgstr ""
+"Это приведёт к подключению функций математической библиотеки в "
+"[.filename]#foobar#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:327
+msgid ""
+"If you are compiling C++ code, use {c-plus-plus-command}. {c-plus-plus-"
+"command} can also be invoked as {clang-plus-plus-command} on FreeBSD."
+msgstr ""
+"Если вы компилируете код на C++, используйте {c-plus-plus-command}. {c-plus-"
+"plus-command} также может быть вызван как {clang-plus-plus-command} в "
+"FreeBSD."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:331
+#, no-wrap
+msgid "% c++ -o foobar foobar.cc\n"
+msgstr "% c++ -o foobar foobar.cc\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:334
+msgid ""
+"This will both produce an executable [.filename]#foobar# from the C++ source "
+"file [.filename]#foobar.cc#."
+msgstr ""
+"Это создаст исполняемый файл [.filename]#foobar# из исходного файла на C++ "
+"[.filename]#foobar.cc#."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:335
+#, no-wrap
+msgid "Common `cc` Queries and Problems"
+msgstr "Распространённые вопросы и проблемы `cc`"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:337
+#, no-wrap
+msgid "I compiled a file called foobar.c and I cannot find an executable called foobar. Where has it gone?"
+msgstr "Я скомпилировал файл с именем foobar.c и не могу найти исполняемый файл с именем foobar. Куда он пропал?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:341
+msgid ""
+"Remember, `cc` will call the executable [.filename]#a.out# unless you tell "
+"it differently. Use the `-o _filename_` option:"
+msgstr ""
+"Помните, что `cc` вызовет исполняемый файл [.filename]#a.out#, если вы не "
+"укажете иное. Используйте опцию `-o _имя_файла_`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:345
+#, no-wrap
+msgid "% cc -o foobar foobar.c\n"
+msgstr "% cc -o foobar foobar.c\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:347
+#, no-wrap
+msgid "OK, I have an executable called foobar, I can see it when I run ls, but when I type in foobar at the command prompt it tells me there is no such file. Why can it not find it?"
+msgstr "Хорошо, у меня есть исполняемый файл с именем foobar, я вижу его при выполнении команды ls, но когда я ввожу foobar в командной строке, система сообщает, что такого файла нет. Почему он не может его найти?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:351
+msgid ""
+"Unlike MS-DOS(R), UNIX(R) does not look in the current directory when it is "
+"trying to find out which executable you want it to run, unless you tell it "
+"to. Type `./foobar`, which means \"run the file called [.filename]#foobar# "
+"in the current directory.\""
+msgstr ""
+"В отличие от MS-DOS(R), UNIX(R) не ищет в текущем каталоге, когда пытается "
+"определить, какую программу нужно запустить, если вы явно не укажете это. "
+"Введите `./foobar`, что означает \"запустить файл с именем "
+"[.filename]#foobar# в текущем каталоге.\""
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:352
+#, no-wrap
+msgid "I called my executable test, but nothing happens when I run it. What is going on?"
+msgstr "Я назвал свой исполняемый файл test, но при запуске ничего не происходит. В чем дело?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:356
+msgid ""
+"Most UNIX(R) systems have a program called `test` in [.filename]#/usr/bin# "
+"and the shell is picking that one up before it gets to checking the current "
+"directory. Either type:"
+msgstr ""
+"Большинство UNIX(R) систем имеют программу под названием `test` в "
+"[.filename]#/usr/bin#, и оболочка выбирает её, прежде чем проверить текущий "
+"каталог. Введите следующее:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:360
+#, no-wrap
+msgid "% ./test\n"
+msgstr "% ./test\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:363
+msgid "or choose a better name for your program!"
+msgstr "или выберите более подходящее название для вашей программы!"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:364
+#, no-wrap
+msgid "I compiled my program and it seemed to run all right at first, then there was an error and it said something about core dumped. What does that mean?"
+msgstr "Я скомпилировал свою программу, и сначала она работала нормально, но потом произошла ошибка, и было сообщение о core dumped. Что это значит?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:368
+msgid ""
+"The name _core dump_ dates back to the very early days of UNIX(R), when the "
+"machines used core memory for storing data. Basically, if the program "
+"failed under certain conditions, the system would write the contents of core "
+"memory to disk in a file called [.filename]#core#, which the programmer "
+"could then pore over to find out what went wrong."
+msgstr ""
+"Название _core dump_ восходит к самым ранним дням UNIX(R), когда машины "
+"использовали ферритовую память для хранения данных. По сути, если программа "
+"завершалась сбоем при определённых условиях, система записывала содержимое "
+"ферритовой памяти на диск в файл с именем [.filename]#core#, который "
+"программист затем мог изучить, чтобы выяснить причину ошибки."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:369
+#, no-wrap
+msgid "Fascinating stuff, but what I am supposed to do now?"
+msgstr "Увлекательный материал, но что мне теперь делать?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:372
+msgid ""
+"Use a debugger to analyze the core (see crossref:tools[debugging, "
+"Debugging])."
+msgstr ""
+"Используйте отладчик для анализа образа памяти (см. "
+"crossref:tools[debugging, Отладка])."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:373
+#, no-wrap
+msgid "When my program dumped core, it said something about a segmentation fault. What is that?"
+msgstr "Когда моя программа сбросила core, она сообщила что-то о segmentation fault. Что это?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:377
+msgid ""
+"This basically means that your program tried to perform some sort of illegal "
+"operation on memory; UNIX(R) is designed to protect the operating system and "
+"other programs from rogue programs."
+msgstr ""
+"Это означает, что ваша программа попыталась выполнить какую-то недопустимую "
+"операцию с памятью; UNIX(R) разработана для защиты операционной системы и "
+"других программ от некорректно работающих программ."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:379
+msgid "Common causes for this are:"
+msgstr "Распространенные причины этого:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:381
+msgid "Trying to write to a NULL pointer, eg"
+msgstr "Попытка записи в NULL-указатель, например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:386
+#, no-wrap
+msgid ""
+"char *foo = NULL;\n"
+"strcpy(foo, \"bang!\");\n"
+msgstr ""
+"char *foo = NULL;\n"
+"strcpy(foo, \"bang!\");\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:389
+msgid "Using a pointer that has not been initialized, eg"
+msgstr "Использование неинициализированного указателя, например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:394
+#, no-wrap
+msgid ""
+"char *foo;\n"
+"strcpy(foo, \"bang!\");\n"
+msgstr ""
+"char *foo;\n"
+"strcpy(foo, \"bang!\");\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:398
+msgid ""
+"The pointer will have some random value that, with luck, will point into an "
+"area of memory that is not available to your program and the kernel will "
+"kill your program before it can do any damage. If you are unlucky, it will "
+"point somewhere inside your own program and corrupt one of your data "
+"structures, causing the program to fail mysteriously."
+msgstr ""
+"Указатель будет иметь случайное значение, которое, возможно, укажет на "
+"область памяти, недоступную вашей программе, и ядро завершит вашу программу "
+"до того, как она сможет нанести какой-либо ущерб. Если вам не повезет, он "
+"укажет внутрь вашей собственной программы и повредит одну из структур "
+"данных, что приведет к загадочному сбою программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:399
+msgid "Trying to access past the end of an array, eg"
+msgstr "Попытка доступа за пределы массива, например"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:404
+#, no-wrap
+msgid ""
+"int bar[20];\n"
+"bar[27] = 6;\n"
+msgstr ""
+"int bar[20];\n"
+"bar[27] = 6;\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:407
+msgid "Trying to store something in read-only memory, eg"
+msgstr "Попытка сохранить что-то в память только для чтения, например"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:412
+#, no-wrap
+msgid ""
+"char *foo = \"My string\";\n"
+"strcpy(foo, \"bang!\");\n"
+msgstr ""
+"char *foo = \"My string\";\n"
+"strcpy(foo, \"bang!\");\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:415
+msgid ""
+"UNIX(R) compilers often put string literals like `\"My string\"` into read-"
+"only areas of memory."
+msgstr ""
+"Версии UNIX(R) компиляторы часто помещают строковые литералы, такие как "
+"`\"Моя строка\"`, в области памяти только для чтения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:416
+msgid "Doing naughty things with `malloc()` and `free()`, eg"
+msgstr "Выполнение нежелательных действий с `malloc()` и `free()`, например"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:421
+#, no-wrap
+msgid ""
+"char bar[80];\n"
+"free(bar);\n"
+msgstr ""
+"char bar[80];\n"
+"free(bar);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:424
+msgid "or"
+msgstr "или"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:430
+#, no-wrap
+msgid ""
+"char *foo = malloc(27);\n"
+"free(foo);\n"
+"free(foo);\n"
+msgstr ""
+"char *foo = malloc(27);\n"
+"free(foo);\n"
+"free(foo);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:435
+msgid ""
+"Making one of these mistakes will not always lead to an error, but they are "
+"always bad practice. Some systems and compilers are more tolerant than "
+"others, which is why programs that run well on one system can crash when you "
+"try them on another."
+msgstr ""
+"Совершение одной из этих ошибок не всегда приведет к сбою, но это всегда "
+"плохая практика. Некоторые системы и компиляторы более терпимы, чем другие, "
+"поэтому программы, которые хорошо работают на одной системе, могут аварийно "
+"завершаться при попытке запустить их на другой."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:436
+#, no-wrap
+msgid "Sometimes when I get a core dump it says bus error. It says in my UNIX(R) book that this means a hardware problem, but the computer still seems to be working. Is this true?"
+msgstr "Иногда при получении дампа памяти я вижу сообщение ошибки шины (bus error). В моей книге по UNIX(R) сказано, что это означает аппаратную проблему, но компьютер продолжает работать. Это правда?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:440
+msgid ""
+"No, fortunately not (unless of course you really do have a hardware "
+"problem...). This is usually another way of saying that you accessed memory "
+"in a way you should not have."
+msgstr ""
+"Нет, к счастью, нет (если, конечно, у вас действительно нет аппаратной "
+"проблемы...). Обычно это означает, что вы обратились к памяти способом, "
+"который не следует использовать."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:441
+#, no-wrap
+msgid "This dumping core business sounds as though it could be quite useful, if I can make it happen when I want to. Can I do this, or do I have to wait until there is an error?"
+msgstr "Этот процесс создания дампа памяти звучит довольно полезно, если я могу запускать его по своему желанию. Могу ли я это сделать, или нужно ждать возникновения ошибки?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:444
+msgid "Yes, just go to another console or xterm, do"
+msgstr "Можете. Просто перейдите на другую консоль или xterm, выполните"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:448
+#, no-wrap
+msgid "% ps\n"
+msgstr "% ps\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:451
+msgid "to find out the process ID of your program, and do"
+msgstr "чтобы узнать идентификатор процесса вашей программы и выполните"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:455
+#, no-wrap
+msgid "% kill -ABRT pid\n"
+msgstr "% kill -ABRT pid\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:458
+msgid "where `_pid_` is the process ID you looked up."
+msgstr "где `_pid_` — идентификатор процесса, который вы нашли."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:461
+msgid ""
+"This is useful if your program has got stuck in an infinite loop, for "
+"instance. If your program happens to trap SIGABRT, there are several other "
+"signals which have a similar effect."
+msgstr ""
+"Это полезно, если ваша программа зависла в бесконечном цикле, например. Если "
+"ваша программа перехватывает SIGABRT, есть несколько других сигналов, "
+"которые оказывают аналогичный эффект."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:464
+msgid ""
+"Alternatively, you can create a core dump from inside your program, by "
+"calling the `abort()` function. See the manual page of man:abort[3] to "
+"learn more."
+msgstr ""
+"В качестве альтернативы, вы можете создать дамп памяти изнутри вашей "
+"программы, вызвав функцию `abort()`. Дополнительную информацию можно найти "
+"на man:abort[3]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:467
+msgid ""
+"If you want to create a core dump from outside your program, but do not want "
+"the process to terminate, you can use the `gcore` program. See the manual "
+"page of man:gcore[1] for more information."
+msgstr ""
+"Если вы хотите создать дамп памяти извне вашей программы, но не хотите "
+"завершать процесс, вы можете использовать программу `gcore`. Подробнее см. "
+"на странице руководства man:gcore[1]."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:469
+#, no-wrap
+msgid "Make"
+msgstr "Make"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:471
+#, no-wrap
+msgid "What is `make`?"
+msgstr "Что такое `make`?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:474
+msgid ""
+"When you are working on a simple program with only one or two source files, "
+"typing in"
+msgstr ""
+"Когда вы работаете над простой программой с одним или двумя исходными "
+"файлами, вводя"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:478
+#, no-wrap
+msgid "% cc file1.c file2.c\n"
+msgstr "% cc file1.c file2.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:481
+msgid ""
+"is not too bad, but it quickly becomes very tedious when there are several "
+"files-and it can take a while to compile, too."
+msgstr ""
+"это не слишком плохо, но быстро становится очень утомительным, когда есть "
+"несколько файлов — и компиляция тоже может занять время."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:484
+msgid ""
+"One way to get around this is to use object files and only recompile the "
+"source file if the source code has changed. So we could have something like:"
+msgstr ""
+"Один из способов обойти это — использовать объектные файлы и "
+"перекомпилировать исходный файл только в случае изменения исходного кода. "
+"Таким образом, у нас может получиться что-то вроде:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:488
+#, no-wrap
+msgid "% cc file1.o file2.o … file37.c …\n"
+msgstr "% cc file1.o file2.o … file37.c …\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:492
+msgid ""
+"if we had changed [.filename]#file37.c#, but not any of the others, since "
+"the last time we compiled. This may speed up the compilation quite a bit, "
+"but does not solve the typing problem."
+msgstr ""
+"если бы мы изменили файл [.filename]#file37.c#, но не трогали остальные с "
+"момента последней компиляции. Это может значительно ускорить компиляцию, но "
+"не решает проблему с вводом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:494
+msgid ""
+"Or we could write a shell script to solve the typing problem, but it would "
+"have to re-compile everything, making it very inefficient on a large project."
+msgstr ""
+"Или мы могли бы написать shell-скрипт для решения проблемы с вводом, но "
+"тогда пришлось бы перекомпилировать всё, что сделало бы его очень "
+"неэффективным для крупного проекта."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:496
+msgid ""
+"What happens if we have hundreds of source files lying about? What if we are "
+"working in a team with other people who forget to tell us when they have "
+"changed one of their source files that we use?"
+msgstr ""
+"Что произойдет, если у нас есть сотни исходных файлов? Что, если мы работаем "
+"в команде с другими людьми, которые забывают сообщить нам, когда они "
+"изменили один из своих исходных файлов, которые мы используем?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:499
+msgid ""
+"Perhaps we could put the two solutions together and write something like a "
+"shell script that would contain some kind of magic rule saying when a source "
+"file needs compiling. Now all we need now is a program that can understand "
+"these rules, as it is a bit too complicated for the shell."
+msgstr ""
+"Возможно, мы могли бы объединить два решения и написать что-то вроде shell-"
+"скрипта, который содержал бы какое-то волшебное правило, указывающее, когда "
+"исходный файл нужно компилировать. Теперь нам осталось только найти "
+"программу, которая сможет понимать эти правила, так как для shell это "
+"немного слишком сложно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:504
+msgid ""
+"This program is called `make`. It reads in a file, called a _makefile_, "
+"that tells it how different files depend on each other, and works out which "
+"files need to be re-compiled and which ones do not. For example, a rule "
+"could say something like \"if [.filename]#fromboz.o# is older than "
+"[.filename]#fromboz.c#, that means someone must have changed "
+"[.filename]#fromboz.c#, so it needs to be re-compiled.\" The makefile also "
+"has rules telling make _how_ to re-compile the source file, making it a much "
+"more powerful tool."
+msgstr ""
+"Эта программа называется `make`. Она читает файл, называемый _makefile_, "
+"который указывает, как различные файлы зависят друг от друга, и определяет, "
+"какие файлы нужно перекомпилировать, а какие нет. Например, правило может "
+"звучать так: «если [.filename]#fromboz.o# старше, чем "
+"[.filename]#fromboz.c#, значит, кто-то изменил [.filename]#fromboz.c#, и его "
+"нужно перекомпилировать». В makefile также содержатся правила, указывающие "
+"make, _как_ именно перекомпилировать исходный файл, что делает эту программу "
+"гораздо более мощным инструментом."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:507
+msgid ""
+"Makefiles are typically kept in the same directory as the source they apply "
+"to, and can be called [.filename]#makefile#, [.filename]#Makefile# or "
+"[.filename]#MAKEFILE#. Most programmers use the name [.filename]#Makefile#, "
+"as this puts it near the top of a directory listing, where it can easily be "
+"seen.footnote:[They do not use the MAKEFILE form as block capitals are often "
+"used for documentation files like README.]"
+msgstr ""
+"Файлы Makefile обычно хранятся в том же каталоге, что и исходный код, к "
+"которому они применяются, и могут называться [.filename]#makefile#, "
+"[.filename]#Makefile# или [.filename]#MAKEFILE#. Большинство программистов "
+"используют имя [.filename]#Makefile#, так как это помещает его в начало "
+"списка файлов в каталоге, где его легко заметить.footnote:[Они не используют "
+"форму MAKEFILE, так как заглавные буквы часто применяются для файлов "
+"документации, таких как README.]"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:508
+#, no-wrap
+msgid "Example of Using `make`"
+msgstr "Пример использования `make`"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:511
+msgid "Here is a very simple make file:"
+msgstr "Вот очень простой файл для make:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:516
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:542
+#, no-wrap
+msgid ""
+"foo: foo.c\n"
+"\tcc -o foo foo.c\n"
+msgstr ""
+"foo: foo.c\n"
+"\tcc -o foo foo.c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:519
+msgid "It consists of two lines, a dependency line and a creation line."
+msgstr "Он состоит из двух строк: строки зависимости и строки создания."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:526
+msgid ""
+"The dependency line here consists of the name of the program (known as the "
+"_target_), followed by a colon, then whitespace, then the name of the source "
+"file. When `make` reads this line, it looks to see if [.filename]#foo# "
+"exists; if it exists, it compares the time [.filename]#foo# was last "
+"modified to the time [.filename]#foo.c# was last modified. If "
+"[.filename]#foo# does not exist, or is older than [.filename]#foo.c#, it "
+"then looks at the creation line to find out what to do. In other words, "
+"this is the rule for working out when [.filename]#foo.c# needs to be re-"
+"compiled."
+msgstr ""
+"Строка зависимости здесь состоит из имени программы (известного как _цель_), "
+"за которым следует двоеточие, пробел и имя исходного файла. Когда `make` "
+"читает эту строку, он проверяет, существует ли файл [.filename]#foo#; если "
+"он существует, программа сравнивает время последнего изменения файла "
+"[.filename]#foo# с временем последнего изменения файла [.filename]#foo.c#. "
+"Если файл [.filename]#foo# не существует или старше файла "
+"[.filename]#foo.c#, программа смотрит на строку создания, чтобы выяснить, "
+"что делать. Другими словами, это правило для определения, когда файл "
+"[.filename]#foo.c# нужно перекомпилировать."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:530
+msgid ""
+"The creation line starts with a tab (press kbd:[tab]) and then the command "
+"you would type to create [.filename]#foo# if you were doing it at a command "
+"prompt. If [.filename]#foo# is out of date, or does not exist, `make` then "
+"executes this command to create it. In other words, this is the rule which "
+"tells make how to re-compile [.filename]#foo.c#."
+msgstr ""
+"Строка создания начинается с табуляции (нажмите kbd:[tab]), а затем следует "
+"команда, которую вы бы ввели для создания [.filename]#foo#, если бы делали "
+"это в командной строке. Если [.filename]#foo# устарел или не существует, "
+"`make` выполняет эту команду для его создания. Другими словами, это правило, "
+"которое сообщает make, как перекомпилировать [.filename]#foo.c#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:534
+msgid ""
+"So, when you type `make`, it will make sure that [.filename]#foo# is up to "
+"date with respect to your latest changes to [.filename]#foo.c#. This "
+"principle can be extended to [.filename]#Makefile#'s with hundreds of "
+"targets-in fact, on FreeBSD, it is possible to compile the entire operating "
+"system just by typing `make buildworld buildkernel` at the top level "
+"directory in the src tree."
+msgstr ""
+"Таким образом, при вводе команды `make` система обеспечит актуальность файла "
+"[.filename]#foo# относительно последних изменений в [.filename]#foo.c#. Этот "
+"принцип можно распространить на [.filename]#Makefile#, содержащие сотни "
+"целей — фактически, в FreeBSD можно собрать всю операционную систему, просто "
+"введя `make buildworld buildkernel` в корневом каталоге дерева исходных "
+"кодов (src)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:537
+msgid ""
+"Another useful property of makefiles is that the targets do not have to be "
+"programs. For instance, we could have a make file that looks like this:"
+msgstr ""
+"Еще одно полезное свойство makefile заключается в том, что цели не "
+"обязательно должны быть программами. Например, у нас может быть makefile, "
+"который выглядит так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:545
+#, no-wrap
+msgid ""
+"install:\n"
+"\tcp foo /home/me\n"
+msgstr ""
+"install:\n"
+"\tcp foo /home/me\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:548
+msgid "We can tell make which target we want to make by typing:"
+msgstr "Мы можем указать make, какую цель мы хотим собрать, набрав:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:552
+#, no-wrap
+msgid "% make target\n"
+msgstr "% make target\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:556
+msgid ""
+"`make` will then only look at that target and ignore any others. For "
+"example, if we type `make foo` with the makefile above, make will ignore the "
+"`install` target."
+msgstr ""
+"`make` будет рассматривать только указанную цель и игнорировать все "
+"остальные. Например, если мы введём `make foo` с указанным выше makefile, "
+"make проигнорирует цель `install`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:559
+msgid ""
+"If we just type `make` on its own, make will always look at the first target "
+"and then stop without looking at any others. So if we typed `make` here, it "
+"will just go to the `foo` target, re-compile [.filename]#foo# if necessary, "
+"and then stop without going on to the `install` target."
+msgstr ""
+"Если мы просто введем `make` без параметров, make всегда будет обращаться к "
+"первой цели и затем остановится, не рассматривая остальные. Поэтому если мы "
+"введем `make` здесь, он просто перейдет к цели `foo`, перекомпилирует "
+"[.filename]#foo# при необходимости и затем остановится, не переходя к цели "
+"`install`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:563
+msgid ""
+"Notice that the `install` target does not actually depend on anything! This "
+"means that the command on the following line is always executed when we try "
+"to make that target by typing `make install`. In this case, it will copy "
+"[.filename]#foo# into the user's home directory. This is often used by "
+"application makefiles, so that the application can be installed in the "
+"correct directory when it has been correctly compiled."
+msgstr ""
+"Обратите внимание, что цель `install` не зависит ни от чего! Это означает, "
+"что команда в следующей строке всегда выполняется при попытке создать эту "
+"цель с помощью команды `make install`. В данном случае она скопирует "
+"[.filename]#foo# в домашний каталог пользователя. Это часто используется в "
+"makefile приложений, чтобы приложение можно было установить в правильный "
+"каталог после успешной компиляции."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:568
+msgid ""
+"This is a slightly confusing subject to try to explain. If you do not quite "
+"understand how `make` works, the best thing to do is to write a simple "
+"program like \"hello world\" and a make file like the one above and "
+"experiment. Then progress to using more than one source file, or having the "
+"source file include a header file. `touch` is very useful here-it changes "
+"the date on a file without you having to edit it."
+msgstr ""
+"Это немного запутанная тема для объяснения. Если вы не до конца понимаете, "
+"как работает `make`, лучше всего написать простую программу, например, "
+"\"hello world\", и make-файл, как указано выше, и поэкспериментировать. "
+"Затем можно перейти к использованию нескольких исходных файлов или "
+"добавлению заголовочного файла в исходный код. В этом случае очень полезен "
+"`touch` — он изменяет дату файла без необходимости его редактирования."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:569
+#, no-wrap
+msgid "Make and include-files"
+msgstr "make и include-файлы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:573
+msgid ""
+"C code often starts with a list of files to include, for example stdio.h. "
+"Some of these files are system-include files, some of them are from the "
+"project you are now working on:"
+msgstr ""
+"Код на C часто начинается со списка подключаемых файлов, например stdio.h. "
+"Некоторые из этих файлов являются системными, а некоторые принадлежат "
+"текущему проекту:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:578
+#, no-wrap
+msgid ""
+"#include <stdio.h>\n"
+"#include \"foo.h\"\n"
+msgstr ""
+"#include <stdio.h>\n"
+"#include \"foo.h\"\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:580
+#, no-wrap
+msgid "int main(....\n"
+msgstr "int main(....\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:583
+msgid ""
+"To make sure that this file is recompiled the moment [.filename]#foo.h# is "
+"changed, you have to add it in your [.filename]#Makefile#:"
+msgstr ""
+"Чтобы убедиться, что этот файл перекомпилируется при изменении "
+"[.filename]#foo.h#, необходимо добавить его в [.filename]#Makefile#:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:587
+#, no-wrap
+msgid "foo: foo.c foo.h\n"
+msgstr "foo: foo.c foo.h\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:594
+msgid ""
+"The moment your project is getting bigger and you have more and more own "
+"include-files to maintain, it will be a pain to keep track of all include "
+"files and the files which are depending on it. If you change an include-"
+"file but forget to recompile all the files which are depending on it, the "
+"results will be devastating. `clang` has an option to analyze your files "
+"and to produce a list of include-files and their dependencies: `-MM`."
+msgstr ""
+"В момент, когда ваш проект становится больше и у вас появляется все больше "
+"собственных включаемых файлов для поддержки, отслеживание всех включаемых "
+"файлов и файлов, которые от них зависят, становится проблемой. Если вы "
+"измените включаемый файл, но забудете перекомпилировать все файлы, которые "
+"от него зависят, последствия будут катастрофическими. У `clang` есть опция "
+"для анализа ваших файлов и создания списка включаемых файлов и их "
+"зависимостей: `-MM`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:596
+msgid "If you add this to your Makefile:"
+msgstr "Если вы добавите это в ваш Makefile:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:601
+#, no-wrap
+msgid ""
+"depend:\n"
+"\tcc -E -MM *.c > .depend\n"
+msgstr ""
+"depend:\n"
+"\tcc -E -MM *.c > .depend\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:604
+msgid ""
+"and run `make depend`, the file [.filename]#.depend# will appear with a list "
+"of object-files, C-files and the include-files:"
+msgstr ""
+"и выполните `make depend`, появится файл [.filename]#.depend# со списком "
+"объектных файлов, C-файлов и включаемых файлов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:608
+#, no-wrap
+msgid "foo.o: foo.c foo.h\n"
+msgstr "foo.o: foo.c foo.h\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:611
+msgid ""
+"If you change [.filename]#foo.h#, next time you run `make` all files "
+"depending on [.filename]#foo.h# will be recompiled."
+msgstr ""
+"Если вы измените файл [.filename]#foo.h#, при следующем запуске `make` все "
+"файлы, зависящие от [.filename]#foo.h#, будут перекомпилированы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:613
+msgid ""
+"Do not forget to run `make depend` each time you add an include-file to one "
+"of your files."
+msgstr ""
+"Не забудьте выполнить `make depend` каждый раз, когда вы добавляете include-"
+"файл в один из своих файлов."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:614
+#, no-wrap
+msgid "FreeBSD Makefiles"
+msgstr "Файлы Makefile системы FreeBSD"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:620
+msgid ""
+"Makefiles can be rather complicated to write. Fortunately, BSD-based "
+"systems like FreeBSD come with some very powerful ones as part of the "
+"system. One very good example of this is the FreeBSD ports system. Here is "
+"the essential part of a typical ports [.filename]#Makefile#:"
+msgstr ""
+"Makefile-ы могут быть довольно сложными для написания. К счастью, в BSD-"
+"системах, таких как FreeBSD, есть очень мощные Makefile-ы, поставляемые в "
+"составе системы. Отличным примером этого является система портов FreeBSD. "
+"Вот основная часть типичного [.filename]#Makefile# для портов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:625
+#, no-wrap
+msgid ""
+"MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/\n"
+"DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz\n"
+msgstr ""
+"MASTER_SITES= ftp://freefall.cdrom.com/pub/FreeBSD/LOCAL_PORTS/\n"
+"DISTFILES= scheme-microcode+dist-7.3-freebsd.tgz\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:627
+#, no-wrap
+msgid ".include <bsd.port.mk>\n"
+msgstr ".include <bsd.port.mk>\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:630
+msgid ""
+"Now, if we go to the directory for this port and type `make`, the following "
+"happens:"
+msgstr ""
+"Теперь, если мы перейдем в каталог этого порта и наберем `make`, произойдет "
+"следующее:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:633
+msgid ""
+"A check is made to see if the source code for this port is already on the "
+"system."
+msgstr "Проверяется, есть ли исходный код этого порта уже в системе."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:634
+msgid ""
+"If it is not, an FTP connection to the URL in MASTER_SITES is set up to "
+"download the source."
+msgstr ""
+"Если это не так, устанавливается FTP-соединение с URL в MASTER_SITES для "
+"загрузки исходного кода."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:635
+msgid ""
+"The checksum for the source is calculated and compared it with one for a "
+"known, good, copy of the source. This is to make sure that the source was "
+"not corrupted while in transit."
+msgstr ""
+"Контрольная сумма исходного кода вычисляется и сравнивается с контрольной "
+"суммой известной и хорошей копии исходного кода. Это делается для того, "
+"чтобы убедиться, что исходный код не был поврежден во время передачи."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:636
+msgid ""
+"Any changes required to make the source work on FreeBSD are applied-this is "
+"known as _patching_."
+msgstr ""
+"Все необходимые изменения для адаптации исходного кода к работе в FreeBSD "
+"применяются — это называется применением _патча_."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:637
+msgid ""
+"Any special configuration needed for the source is done. (Many UNIX(R) "
+"program distributions try to work out which version of UNIX(R) they are "
+"being compiled on and which optional UNIX(R) features are present-this is "
+"where they are given the information in the FreeBSD ports scenario)."
+msgstr ""
+"Любая необходимая специальная настройка для исходного кода выполнена. "
+"(Многие дистрибутивы программ UNIX(R) пытаются определить, на какой версии "
+"UNIX(R) они компилируются и какие дополнительные функции UNIX(R) доступны — "
+"именно здесь они получают эту информацию в сценарии портов FreeBSD)."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:638
+msgid ""
+"The source code for the program is compiled. In effect, we change to the "
+"directory where the source was unpacked and do `make`-the program's own make "
+"file has the necessary information to build the program."
+msgstr ""
+"Компилируется исходный код программы. По сути, мы переходим в каталог, куда "
+"были распакованы исходные файлы, и выполняем `make` — собственный make-файл "
+"программы содержит необходимую информацию для сборки программы."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:639
+msgid ""
+"We now have a compiled version of the program. If we wish, we can test it "
+"now; when we feel confident about the program, we can type `make install`. "
+"This will cause the program and any supporting files it needs to be copied "
+"into the correct location; an entry is also made into a `package database`, "
+"so that the port can easily be uninstalled later if we change our mind about "
+"it."
+msgstr ""
+"Теперь у нас есть скомпилированная версия программы. При желании мы можем "
+"протестировать её сейчас; когда мы уверены в программе, можно ввести `make "
+"install`. Это приведёт к копированию программы и всех необходимых "
+"вспомогательных файлов в нужные места, а также к добавлению записи в `базу "
+"данных пакетов`, чтобы позже можно было легко удалить порт, если мы "
+"передумаем."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:641
+msgid ""
+"Now I think you will agree that is rather impressive for a four line script!"
+msgstr ""
+"Вот теперь, я думаю, вы согласитесь, что это довольно впечатляюще для "
+"скрипта из четырёх строк!"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:645
+msgid ""
+"The secret lies in the last line, which tells `make` to look in the system "
+"makefile called [.filename]#bsd.port.mk#. It is easy to overlook this line, "
+"but this is where all the clever stuff comes from-someone has written a "
+"makefile that tells `make` to do all the things above (plus a couple of "
+"other things I did not mention, including handling any errors that may "
+"occur) and anyone can get access to that just by putting a single line in "
+"their own make file!"
+msgstr ""
+"Секрет кроется в последней строке, которая указывает `make` обратиться к "
+"системному makefile под названием [.filename]#bsd.port.mk#. Эту строку легко "
+"пропустить, но именно здесь начинается вся магия — кто-то написал makefile, "
+"который предписывает `make` выполнить все вышеперечисленные действия (плюс "
+"несколько других, которые я не упомянул, включая обработку возможных "
+"ошибок), и любой может получить доступ к этому функционалу, просто добавив "
+"одну строку в свой собственный makefile!"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:649
+msgid ""
+"If you want to have a look at these system makefiles, they are in "
+"[.filename]#/usr/share/mk#, but it is probably best to wait until you have "
+"had a bit of practice with makefiles, as they are very complicated (and if "
+"you do look at them, make sure you have a flask of strong coffee handy!)"
+msgstr ""
+"Если вы хотите взглянуть на эти системные makefile-ы, они находятся в "
+"[.filename]#/usr/share/mk#, но, вероятно, лучше подождать, пока у вас не "
+"появится немного практики с makefile, так как они очень сложные (и если вы "
+"всё же решите их посмотреть, убедитесь, что у вас под рукой есть фляга "
+"крепкого кофе!)"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:650
+#, no-wrap
+msgid "More Advanced Uses of `make`"
+msgstr "Более сложные способы использования `make`"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:656
+msgid ""
+"`Make` is a very powerful tool, and can do much more than the simple example "
+"above shows. Unfortunately, there are several different versions of `make`, "
+"and they all differ considerably. The best way to learn what they can do is "
+"probably to read the documentation-hopefully this introduction will have "
+"given you a base from which you can do this. The man:make[1] manual page "
+"offers a comprehensive discussion of variables, arguments, and how to use "
+"make."
+msgstr ""
+"`Make` — это очень мощный инструмент, способный на гораздо большее, чем "
+"показано в простом примере выше. К сожалению, существует несколько различных "
+"версий `make`, и все они значительно отличаются друг от друга. Лучший способ "
+"узнать, на что они способны, — вероятно, прочитать документацию. Надеюсь, "
+"это введение дало вам основу, с которой вы сможете это сделать. В "
+"man:make[1] подробно обсуждаются переменные, аргументы и то, как "
+"использовать `make`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:660
+msgid ""
+"Many applications in the ports use GNU make, which has a very good set of "
+"\"info\" pages. If you have installed any of these ports, GNU make will "
+"automatically have been installed as `gmake`. It is also available as a "
+"port and package in its own right."
+msgstr ""
+"Многие приложения в портах используют GNU make, который имеет очень хороший "
+"набор страниц \"info\". Если вы установили любой из этих портов, GNU make "
+"будет автоматически установлен как `gmake`. Он также доступен как отдельный "
+"порт и пакет."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:663
+msgid ""
+"To view the info pages for GNU make, you will have to edit [.filename]#dir# "
+"in the [.filename]#/usr/local/info# directory to add an entry for it. This "
+"involves adding a line like"
+msgstr ""
+"Для просмотра справочных страниц (info) GNU make вам потребуется "
+"отредактировать файл [.filename]#dir# в каталоге [.filename]#/usr/local/"
+"info#, добавив соответствующую запись. Добавьте строку"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:667
+#, no-wrap
+msgid " * Make: (make). The GNU Make utility.\n"
+msgstr " * Make: (make). The GNU Make utility.\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:670
+msgid ""
+"to the file. Once you have done this, you can type `info` and then select "
+"[.guimenuitem]#make# from the menu (or in Emacs, do `C-h i`)."
+msgstr ""
+"в файл. После этого вы можете ввести `info` и затем выбрать "
+"[.guimenuitem]#make# из меню (или в Emacs выполнить `C-h i`)."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:672
+#, no-wrap
+msgid "Debugging"
+msgstr "Отладка"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:674
+#, no-wrap
+msgid "Introduction to Available Debuggers"
+msgstr "Обзор отладчиков, поставляемых в системе"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:679
+msgid ""
+"Using a debugger allows running the program under more controlled "
+"circumstances. Typically, it is possible to step through the program a line "
+"at a time, inspect the value of variables, change them, tell the debugger to "
+"run up to a certain point and then stop, and so on. It is also possible to "
+"attach to a program that is already running, or load a core file to "
+"investigate why the program crashed."
+msgstr ""
+"Использование отладчика позволяет запускать программу в более контролируемых "
+"условиях. Обычно можно выполнять программу построчно, проверять значения "
+"переменных, изменять их, указывать отладчику выполнение до определённой "
+"точки и затем останавливаться и так далее. Также можно подключиться к уже "
+"работающей программе или загрузить core-файл, чтобы исследовать причину "
+"аварийного завершения программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:682
+msgid ""
+"This section is intended to be a quick introduction to using debuggers and "
+"does not cover specialized topics such as debugging the kernel. For more "
+"information about that, refer to crossref:kerneldebug[kerneldebug,Kernel "
+"Debugging]."
+msgstr ""
+"Этот раздел представляет собой краткое введение в использование отладчиков и "
+"не затрагивает специализированные темы, такие как отладка ядра. Для "
+"получения дополнительной информации по этой теме обратитесь к главе "
+"crossref:kerneldebug[kerneldebug,Отладка ядра]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:686
+msgid ""
+"The standard debugger supplied with FreeBSD is called `lldb` (LLVM "
+"debugger). As it is part of the standard installation for that release, "
+"there is no need to do anything special to use it. It has good command "
+"help, accessible via the `help` command, as well as https://lldb.llvm.org/[a "
+"web tutorial and documentation]."
+msgstr ""
+"Стандартный отладчик, поставляемый с FreeBSD, называется `lldb` (LLVM "
+"debugger). Поскольку он является частью стандартной установки для данного "
+"выпуска, нет необходимости выполнять какие-либо дополнительные действия для "
+"его использования. Он обладает хорошей справкой по командам, доступной через "
+"команду `help`, а также https://lldb.llvm.org/[руководством и документацией "
+"в интернете]."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:690
+msgid ""
+"The `lldb` command is also available extref:{handbook}ports/[from ports or "
+"packages, ports-using] as package:devel/llvm[]."
+msgstr ""
+"Команда `lldb` также доступна extref:{handbook}ports/[из портов или пакетов, "
+"ports-using] как пакет package:devel/llvm[]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:696
+msgid ""
+"The other debugger available with FreeBSD is called `gdb` (GNU debugger). "
+"Unlike lldb, it is not installed by default on FreeBSD; to use it, extref:"
+"{handbook}#ports-using/[install] package:devel/gdb[] from ports or "
+"packages. It has excellent on-line help, as well as a set of info pages."
+msgstr ""
+"Другой отладчик, доступный в FreeBSD, называется `gdb` (GNU debugger). В "
+"отличие от lldb, он не устанавливается по умолчанию в FreeBSD; для его "
+"использования необходимо extref:{handbook}#ports-using/[установить] пакет "
+"package:devel/gdb[] из портов или пакетов. Он обладает отличной встроенной "
+"справкой, а также набором info-страниц."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:701
+msgid ""
+"The two debuggers have a similar feature set, so which one to use is largely "
+"a matter of taste. If familiar with one only, use that one. People "
+"familiar with neither or both but wanting to use one from inside Emacs will "
+"need to use `gdb` as `lldb` is unsupported by Emacs. Otherwise, try both "
+"and see which one you prefer."
+msgstr ""
+"Два отладчика обладают схожим набором функций, поэтому выбор между ними в "
+"основном зависит от личных предпочтений. Если вы знакомы только с одним из "
+"них, используйте его. Тем, кто не знаком ни с одним или знаком с обоими, но "
+"хочет использовать отладчик внутри Emacs, придётся выбрать `gdb`, так как "
+"`lldb` не поддерживается Emacs. В остальных случаях попробуйте оба и решите, "
+"какой вам больше нравится."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:702
+#, no-wrap
+msgid "Using lldb"
+msgstr "Использование lldb"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:704
+#, no-wrap
+msgid "Starting lldb"
+msgstr "Запуск lldb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:707
+msgid "Start up lldb by typing"
+msgstr "Запустите lldb, набрав"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:711
+#, no-wrap
+msgid "% lldb -- progname\n"
+msgstr "% lldb -- progname\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:713
+#, no-wrap
+msgid "Running a Program with lldb"
+msgstr "Запуск программы с lldb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:718
+msgid ""
+"Compile the program with `-g` to get the most out of using `lldb`. It will "
+"work without, but will only display the name of the function currently "
+"running, instead of the source code. If it displays a line like:"
+msgstr ""
+"Скомпилируйте программу с `-g`, чтобы максимально использовать возможности "
+"`lldb`. Без этого флаг она будет работать, но отображать только имя текущей "
+"выполняемой функции вместо исходного кода. Если отображается строка вида:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:722
+#, no-wrap
+msgid "Breakpoint 1: where = temp`main, address = …\n"
+msgstr "Breakpoint 1: where = temp`main, address = …\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:725
+msgid ""
+"(without an indication of source code filename and line number) when setting "
+"a breakpoint, this means that the program was not compiled with `-g`."
+msgstr ""
+"(без указания имени файла исходного кода и номера строки) при установке "
+"точки останова это означает, что программа не была скомпилирована с "
+"параметром `-g`."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:730
+msgid ""
+"Most `lldb` commands have shorter forms that can be used instead. The "
+"longer forms are used here for clarity."
+msgstr ""
+"Большинство команд `lldb` имеют более короткие формы, которые можно "
+"использовать вместо полных. Здесь используются полные формы для ясности."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:735
+msgid ""
+"At the `lldb` prompt, type `breakpoint set -n main`. This will tell the "
+"debugger not to display the preliminary set-up code in the program being run "
+"and to stop execution at the beginning of the program's code. Now type "
+"`process launch` to actually start the program- it will start at the "
+"beginning of the set-up code and then get stopped by the debugger when it "
+"calls `main()`."
+msgstr ""
+"На строке `lldb` введите `breakpoint set -n main`. Это укажет отладчику не "
+"показывать предварительный код настройки в запускаемой программе и "
+"остановить выполнение в начале кода программы. Теперь введите `process "
+"launch`, чтобы фактически запустить программу — она начнётся с кода "
+"настройки, а затем будет остановлена отладчиком при вызове `main()`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:739
+msgid ""
+"To step through the program a line at a time, type `thread step-over`. When "
+"the program gets to a function call, step into it by typing `thread step-"
+"in`. Once in a function call, return from it by typing `thread step-out` or "
+"use `up` and `down` to take a quick look at the caller."
+msgstr ""
+"Для пошагового выполнения программы строка за строкой введите `thread step-"
+"over`. Когда программа дойдёт до вызова функции, войдите в неё, набрав "
+"`thread step-in`. Оказавшись внутри вызова функции, вернитесь из него с "
+"помощью команды `thread step-out` или используйте `up` и `down`, чтобы "
+"быстро посмотреть на вызывающий код."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:742
+msgid ""
+"Here is a simple example of how to spot a mistake in a program with `lldb`. "
+"This is our program (with a deliberate mistake):"
+msgstr ""
+"Вот простой пример того, как найти ошибку в программе с помощью `lldb`. Это "
+"наша программа (с умышленной ошибкой):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:746
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1020
+#, no-wrap
+msgid "#include <stdio.h>\n"
+msgstr "#include <stdio.h>\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:748
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1022
+#, no-wrap
+msgid "int bazz(int anint);\n"
+msgstr "int bazz(int anint);\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:751
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1025
+#, no-wrap
+msgid ""
+"main() {\n"
+"\tint i;\n"
+msgstr ""
+"main() {\n"
+"\tint i;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:756
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1030
+#, no-wrap
+msgid ""
+"\tprintf(\"This is my program\\n\");\n"
+"\tbazz(i);\n"
+"\treturn 0;\n"
+"}\n"
+msgstr ""
+"\tprintf(\"This is my program\\n\");\n"
+"\tbazz(i);\n"
+"\treturn 0;\n"
+"}\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:761
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1035
+#, no-wrap
+msgid ""
+"int bazz(int anint) {\n"
+"\tprintf(\"You gave me %d\\n\", anint);\n"
+"\treturn anint;\n"
+"}\n"
+msgstr ""
+"int bazz(int anint) {\n"
+"\tprintf(\"You gave me %d\\n\", anint);\n"
+"\treturn anint;\n"
+"}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:764
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1038
+msgid ""
+"This program sets i to be `5` and passes it to a function `bazz()` which "
+"prints out the number we gave it."
+msgstr ""
+"Эта программа устанавливает значение `i` равным `5` и передает его в функцию "
+"`bazz()`, которая выводит переданное число."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:766
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1040
+msgid "Compiling and running the program displays"
+msgstr "Компиляция и запуск программы отображают"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:773
+#, no-wrap
+msgid ""
+"% cc -g -o temp temp.c\n"
+"% ./temp\n"
+"This is my program\n"
+"anint = -5360\n"
+msgstr ""
+"% cc -g -o temp temp.c\n"
+"% ./temp\n"
+"This is my program\n"
+"anint = -5360\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:776
+msgid "That is not what was expected! Time to see what is going on!"
+msgstr "Это не то, что ожидалось! Пора разобраться, что происходит!"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:787
+#, no-wrap
+msgid ""
+"% lldb -- temp\n"
+"(lldb) target create \"temp\"\n"
+"Current executable set to 'temp' (x86_64).\n"
+"(lldb) breakpoint set -n main\t\t\t\tSkip the set-up code\n"
+"Breakpoint 1: where = temp`main + 15 at temp.c:8:2, address = 0x00000000002012ef\tlldb puts breakpoint at main()\n"
+"(lldb) process launch\t\t\t\t\tRun as far as main()\n"
+"Process 9992 launching\n"
+"Process 9992 launched: '/home/pauamma/tmp/temp' (x86_64)\tProgram starts running\n"
+msgstr ""
+"% lldb -- temp\n"
+"(lldb) target create \"temp\"\n"
+"Current executable set to 'temp' (x86_64).\n"
+"(lldb) breakpoint set -n main\t\t\t\tSkip the set-up code\n"
+"Breakpoint 1: where = temp`main + 15 at temp.c:8:2, address = 0x00000000002012ef\tlldb puts breakpoint at main()\n"
+"(lldb) process launch\t\t\t\t\tRun as far as main()\n"
+"Process 9992 launching\n"
+"Process 9992 launched: '/home/pauamma/tmp/temp' (x86_64)\tProgram starts running\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:821
+#, no-wrap
+msgid ""
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = breakpoint 1.1\tlldb stops at main()\n"
+" frame #0: 0x00000000002012ef temp`main at temp.c:8:2\n"
+" 5\tmain() {\n"
+" 6\t\tint i;\n"
+" 7\n"
+"-> 8\t\tprintf(\"This is my program\\n\");\t\t\tIndicates the line where it stopped\n"
+" 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+"(lldb) thread step-over\t\t\tGo to next line\n"
+"This is my program\t\t\t\t\t\tProgram prints out\n"
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = step over\n"
+" frame #0: 0x0000000000201300 temp`main at temp.c:9:7\n"
+" 6\t\tint i;\n"
+" 7\n"
+" 8\t\tprintf(\"This is my program\\n\");\n"
+"-> 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+" 12\n"
+"(lldb) thread step-in\t\t\tstep into bazz()\n"
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = step in\n"
+" frame #0: 0x000000000020132b temp`bazz(anint=-5360) at temp.c:14:29\tlldb displays stack frame\n"
+" 11\t}\n"
+" 12\n"
+" 13\tint bazz(int anint) {\n"
+"-> 14\t\tprintf(\"You gave me %d\\n\", anint);\n"
+" 15\t\treturn anint;\n"
+" 16\t}\n"
+"(lldb)\n"
+msgstr ""
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = breakpoint 1.1\tlldb stops at main()\n"
+" frame #0: 0x00000000002012ef temp`main at temp.c:8:2\n"
+" 5\tmain() {\n"
+" 6\t\tint i;\n"
+" 7\n"
+"-> 8\t\tprintf(\"This is my program\\n\");\t\t\tIndicates the line where it stopped\n"
+" 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+"(lldb) thread step-over\t\t\tGo to next line\n"
+"This is my program\t\t\t\t\t\tProgram prints out\n"
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = step over\n"
+" frame #0: 0x0000000000201300 temp`main at temp.c:9:7\n"
+" 6\t\tint i;\n"
+" 7\n"
+" 8\t\tprintf(\"This is my program\\n\");\n"
+"-> 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+" 12\n"
+"(lldb) thread step-in\t\t\tstep into bazz()\n"
+"Process 9992 stopped\n"
+"* thread #1, name = 'temp', stop reason = step in\n"
+" frame #0: 0x000000000020132b temp`bazz(anint=-5360) at temp.c:14:29\tlldb displays stack frame\n"
+" 11\t}\n"
+" 12\n"
+" 13\tint bazz(int anint) {\n"
+"-> 14\t\tprintf(\"You gave me %d\\n\", anint);\n"
+" 15\t\treturn anint;\n"
+" 16\t}\n"
+"(lldb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:824
+msgid ""
+"Hang on a minute! How did anint get to be `-5360`? Was it not set to `5` in "
+"`main()`? Let us move up to `main()` and have a look."
+msgstr ""
+"Подождите минуту! Как переменная `int` стала равна `-5360`? Разве она не "
+"была установлена в `5` в `main()`? Давайте поднимемся к `main()` и посмотрим."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:838
+#, no-wrap
+msgid ""
+"(lldb) up\t\tMove up call stack\n"
+"frame #1: 0x000000000020130b temp`main at temp.c:9:2\t\tlldb displays stack frame\n"
+" 6\t\tint i;\n"
+" 7\n"
+" 8\t\tprintf(\"This is my program\\n\");\n"
+"-> 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+" 12\n"
+"(lldb) frame variable i\t\t\tShow us the value of i\n"
+"(int) i = -5360\t\t\t\t\t\t\tlldb displays -5360\n"
+msgstr ""
+"(lldb) up\t\tMove up call stack\n"
+"frame #1: 0x000000000020130b temp`main at temp.c:9:2\t\tlldb displays stack frame\n"
+" 6\t\tint i;\n"
+" 7\n"
+" 8\t\tprintf(\"This is my program\\n\");\n"
+"-> 9\t\tbazz(i);\n"
+" 10\t\treturn 0;\n"
+" 11\t}\n"
+" 12\n"
+"(lldb) frame variable i\t\t\tShow us the value of i\n"
+"(int) i = -5360\t\t\t\t\t\t\tlldb displays -5360\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:842
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1083
+msgid ""
+"Oh dear! Looking at the code, we forgot to initialize i. We meant to put"
+msgstr "О боже! Глядя на код, мы забыли инициализировать i. Мы хотели добавить"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:848
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1089
+#, no-wrap
+msgid ""
+"...\n"
+"main() {\n"
+"\tint i;\n"
+msgstr ""
+"...\n"
+"main() {\n"
+"\tint i;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:852
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1093
+#, no-wrap
+msgid ""
+"\ti = 5;\n"
+"\tprintf(\"This is my program\\n\");\n"
+"...\n"
+msgstr ""
+"\ti = 5;\n"
+"\tprintf(\"This is my program\\n\");\n"
+"...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:857
+msgid ""
+"but we left the `i=5;` line out. As we did not initialize i, it had "
+"whatever number happened to be in that area of memory when the program ran, "
+"which in this case happened to be `-5360`."
+msgstr ""
+"но мы пропустили строку `i=5;`. Поскольку мы не инициализировали `i`, она "
+"содержала любое число, которое оказалось в той области памяти при запуске "
+"программы, и в данном случае это оказалось `-5360`."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:863
+msgid ""
+"The `lldb` command displays the stack frame every time we go into or out of "
+"a function, even if we are using `up` and `down` to move around the call "
+"stack. This shows the name of the function and the values of its arguments, "
+"which helps us keep track of where we are and what is going on. (The stack "
+"is a storage area where the program stores information about the arguments "
+"passed to functions and where to go when it returns from a function call.)"
+msgstr ""
+"Команда `lldb` отображает стек вызовов каждый раз, когда мы входим в функцию "
+"или выходим из неё, даже если мы используем `up` и `down` для перемещения по "
+"стеку вызовов. Это показывает имя функции и значения её аргументов, что "
+"помогает отслеживать текущее положение и происходящее. (Стек — это область "
+"хранения, где программа сохраняет информацию об аргументах, переданных в "
+"функции, и о том, куда возвращаться после вызова функции.)"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:865
+#, no-wrap
+msgid "Examining a Core File with lldb"
+msgstr "Изучение файла Core с помощью lldb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:870
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1111
+msgid ""
+"A core file is basically a file which contains the complete state of the "
+"process when it crashed. In \"the good old days\", programmers had to print "
+"out hex listings of core files and sweat over machine code manuals, but now "
+"life is a bit easier. Incidentally, under FreeBSD and other 4.4BSD systems, "
+"a core file is called [.filename]#progname.core# instead of just "
+"[.filename]#core#, to make it clearer which program a core file belongs to."
+msgstr ""
+"Файл core — это, по сути, файл, содержащий полное состояние процесса на "
+"момент его аварийного завершения. В «старые добрые времена» программистам "
+"приходилось распечатывать шестнадцатеричные дампы файлов core и корпеть над "
+"руководствами по машинному коду, но сейчас жизнь стала немного проще. "
+"Кстати, в FreeBSD и других системах на базе 4.4BSD файл core называется "
+"[.filename]#progname.core#, а не просто [.filename]#core#, чтобы было "
+"понятнее, какой программе он принадлежит."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:873
+msgid ""
+"To examine a core file, specify the name of the core file in addition to the "
+"program itself. Instead of starting up `lldb` in the usual way, type `lldb "
+"-c _progname_.core \\-- _progname_`."
+msgstr ""
+"Для анализа файла core укажите имя файла core в дополнение к самой "
+"программе. Вместо обычного запуска `lldb` введите `lldb -c "
+"_имя_программы_.core \\-- _имя_программы_`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:875
+msgid "The debugger will display something like this:"
+msgstr "Отладчик отобразит что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:882
+#, no-wrap
+msgid ""
+"% lldb -c [.filename]#progname.core# -- [.filename]#progname#\n"
+"(lldb) target create \"[.filename]#progname#\" --core \"[.filename]#progname#.core\"\n"
+"Core file '/home/pauamma/tmp/[.filename]#progname.core#' (x86_64) was loaded.\n"
+"(lldb)\n"
+msgstr ""
+"% lldb -c [.filename]#progname.core# -- [.filename]#progname#\n"
+"(lldb) target create \"[.filename]#progname#\" --core \"[.filename]#progname#.core\"\n"
+"Core file '/home/pauamma/tmp/[.filename]#progname.core#' (x86_64) was loaded.\n"
+"(lldb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:888
+msgid ""
+"In this case, the program was called [.filename]#progname#, so the core file "
+"is called [.filename]#progname.core#. The debugger does not display why the "
+"program crashed or where. For this, use `thread backtrace all`. This will "
+"also show how the function where the program dumped core was called."
+msgstr ""
+"В этом случае программа называлась [.filename]#progname#, поэтому файл дампа "
+"имеет имя [.filename]#progname.core#. Отладчик не показывает, почему "
+"программа завершилась аварийно или где это произошло. Для этого используйте "
+"команду `thread backtrace all`. Она также покажет, как была вызвана функция, "
+"в которой программа завершилась дампом ядра."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:897
+#, no-wrap
+msgid ""
+"(lldb) thread backtrace all\n"
+"* thread #1, name = 'progname', stop reason = signal SIGSEGV\n"
+" * frame #0: 0x0000000000201347 progname`bazz(anint=5) at temp2.c:17:10\n"
+" frame #1: 0x0000000000201312 progname`main at temp2.c:10:2\n"
+" frame #2: 0x000000000020110f progname`_start(ap=<unavailable>, cleanup=<unavailable>) at crt1.c:76:7\n"
+"(lldb)\n"
+msgstr ""
+"(lldb) thread backtrace all\n"
+"* thread #1, name = 'progname', stop reason = signal SIGSEGV\n"
+" * frame #0: 0x0000000000201347 progname`bazz(anint=5) at temp2.c:17:10\n"
+" frame #1: 0x0000000000201312 progname`main at temp2.c:10:2\n"
+" frame #2: 0x000000000020110f progname`_start(ap=<unavailable>, cleanup=<unavailable>) at crt1.c:76:7\n"
+"(lldb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:902
+msgid ""
+"`SIGSEGV` indicates that the program tried to access memory (run code or "
+"read/write data usually) at a location that does not belong to it, but does "
+"not give any specifics. For that, look at the source code at line 10 of "
+"file temp2.c, in `bazz()`. The backtrace also says that in this case, "
+"`bazz()` was called from `main()`."
+msgstr ""
+"`SIGSEGV` указывает, что программа пыталась получить доступ к памяти (обычно "
+"выполнить код или прочитать/записать данные) по адресу, который ей не "
+"принадлежит, но не предоставляет конкретных деталей. Для этого обратитесь к "
+"исходному коду на строке 10 файла temp2.c, в функции `bazz()`. Трассировка "
+"также показывает, что в данном случае `bazz()` была вызвана из `main()`."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:903
+#, no-wrap
+msgid "Attaching to a Running Program with lldb"
+msgstr "Подключение к работающей программе с помощью lldb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:908
+msgid ""
+"One of the neatest features about `lldb` is that it can attach to a program "
+"that is already running. Of course, that requires sufficient permissions to "
+"do so. A common problem is stepping through a program that forks and "
+"wanting to trace the child, but the debugger will only trace the parent."
+msgstr ""
+"Одной из самых замечательных особенностей `lldb` является возможность "
+"подключения к уже работающей программе. Конечно, для этого требуются "
+"соответствующие разрешения. Распространённая проблема — пошаговое выполнение "
+"программы, которая создаёт ответвления, с необходимостью отслеживать "
+"дочерний процесс, но отладчик отслеживает только родительский."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:910
+msgid ""
+"To do that, start up another `lldb`, use `ps` to find the process ID for the "
+"child, and do"
+msgstr ""
+"Для этого запустите другой `lldb`, используйте `ps` для поиска "
+"идентификатора процесса дочернего процесса и выполните"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:914
+#, no-wrap
+msgid "(lldb) process attach -p pid\n"
+msgstr "(lldb) process attach -p pid\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:917
+msgid "in `lldb`, and then debug as usual."
+msgstr "в `lldb`, а затем отлаживайте как обычно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:919
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1174
+msgid ""
+"For that to work well, the code that calls `fork` to create the child needs "
+"to do something like the following (courtesy of the `gdb` info pages):"
+msgstr ""
+"Для того чтобы это работало правильно, код, который вызывает `fork` для "
+"создания дочернего процесса, должен делать что-то вроде следующего "
+"(предоставлено из документации `gdb`):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:927
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1182
+#, no-wrap
+msgid ""
+"...\n"
+"if ((pid = fork()) < 0)\t\t/* _Always_ check this */\n"
+"\terror();\n"
+"else if (pid == 0) {\t\t/* child */\n"
+"\tint PauseMode = 1;\n"
+msgstr ""
+"...\n"
+"if ((pid = fork()) < 0)\t\t/* _Always_ check this */\n"
+"\terror();\n"
+"else if (pid == 0) {\t\t/* child */\n"
+"\tint PauseMode = 1;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:933
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1188
+#, no-wrap
+msgid ""
+"\twhile (PauseMode)\n"
+"\t\tsleep(10);\t/* Wait until someone attaches to us */\n"
+"\t...\n"
+"} else {\t\t\t/* parent */\n"
+"\t...\n"
+msgstr ""
+"\twhile (PauseMode)\n"
+"\t\tsleep(10);\t/* Wait until someone attaches to us */\n"
+"\t...\n"
+"} else {\t\t\t/* parent */\n"
+"\t...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:936
+msgid ""
+"Now all that is needed is to attach to the child, set PauseMode to `0` with "
+"`expr PauseMode = 0` and wait for the `sleep()` call to return."
+msgstr ""
+"Вот все, что нужно сделать: подключиться к дочернему процессу, установить "
+"`PauseMode` в `0` с помощью `expr PauseMode = 0` и дождаться возврата из "
+"вызова `sleep()`."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:937
+#, no-wrap
+msgid "Remote Debugging Using LLDB"
+msgstr "Удаленная отладка с использованием LLDB"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:943
+msgid ""
+"The described functionality is available starting with LLDB version 12.0.0. "
+"Users of FreeBSD releases containing an earlier LLDB version may wish to use "
+"the snapshot available in extref:{handbook}[ports or packages, ports-using], "
+"as package:devel/llvm-devel[]."
+msgstr ""
+"Описанная функциональность доступна начиная с версии LLDB 12.0.0. "
+"Пользователи релизов FreeBSD, содержащих более раннюю версию LLDB, могут "
+"воспользоваться снимком из extref:{handbook}[портов или пакетов, ports-"
+"using], как package:devel/llvm-devel[]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:947
+msgid ""
+"Starting with LLDB 12.0.0, remote debugging is supported on FreeBSD. This "
+"means that `lldb-server` can be started to debug a program on one host, "
+"while the interactive `lldb` client connects to it from another one."
+msgstr ""
+"Начиная с LLDB 12.0.0, удалённая отладка поддерживается в FreeBSD. Это "
+"означает, что `lldb-server` может быть запущен для отладки программы на "
+"одном узле, в то время как интерактивный клиент `lldb` подключается к нему с "
+"другого."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:949
+msgid ""
+"To launch a new process to be debugged remotely, run `lldb-server` on the "
+"remote server by typing"
+msgstr ""
+"Чтобы запустить новый процесс для удалённой отладки, выполните `lldb-server` "
+"на удалённом сервере, набрав"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:953
+#, no-wrap
+msgid "% lldb-server g host:port -- progname\n"
+msgstr "% lldb-server g host:port -- progname\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:956
+msgid ""
+"The process will be stopped immediately after launching, and `lldb-server` "
+"will wait for the client to connect."
+msgstr ""
+"Процесс будет остановлен сразу после запуска, и `lldb-server` будет ожидать "
+"подключения клиента."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:958
+msgid ""
+"Start `lldb` locally and type the following command to connect to the remote "
+"server:"
+msgstr ""
+"Запустите `lldb` локально и введите следующую команду для подключения к "
+"удалённому серверу:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:962
+#, no-wrap
+msgid "(lldb) gdb-remote host:port\n"
+msgstr "(lldb) gdb-remote host:port\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:966
+msgid ""
+"`lldb-server` can also attach to a running process. To do that, type the "
+"following on the remote server:"
+msgstr ""
+"`lldb-server` также может присоединиться к работающему процессу. Для этого "
+"введите следующее на удалённом сервере:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:970
+#, no-wrap
+msgid "% lldb-server g host:port --attach pid-or-name\n"
+msgstr "% lldb-server g host:port --attach pid-or-name\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:972
+#, no-wrap
+msgid "Using gdb"
+msgstr "Использование gdb"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:974
+#, no-wrap
+msgid "Starting gdb"
+msgstr "Запуск gdb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:977
+msgid "Start up gdb by typing"
+msgstr "Запустите gdb, набрав"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:981
+#, no-wrap
+msgid "% gdb progname\n"
+msgstr "% gdb progname\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:985
+msgid "although many people prefer to run it inside Emacs. To do this, type:"
+msgstr ""
+"хотя многие предпочитают запускать его внутри Emacs. Для этого введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:989
+#, no-wrap
+msgid " M-x gdb RET progname RET\n"
+msgstr " M-x gdb RET progname RET\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:992
+msgid ""
+"Finally, for those finding its text-based command-prompt style off-putting, "
+"there is a graphical front-end for it (package:devel/xxgdb[]) in the Ports "
+"Collection."
+msgstr ""
+"Наконец, для тех, кого отпугивает текстовый интерфейс командной строки, "
+"существует графический интерфейс (package:devel/xxgdb[]) в Коллекции портов."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:993
+#, no-wrap
+msgid "Running a Program with gdb"
+msgstr "Запуск программы под отладчиком gdb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:998
+msgid ""
+"Compile the program with `-g` to get the most out of using `gdb`. It will "
+"work without, but will only display the name of the function currently "
+"running, instead of the source code. A line like:"
+msgstr ""
+"Скомпилируйте программу с `-g`, чтобы максимально использовать возможности "
+"`gdb`. Она будет работать и без этого, но отобразит только имя текущей "
+"выполняемой функции вместо исходного кода. Строка вида:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1002
+#, no-wrap
+msgid "... (no debugging symbols found) ...\n"
+msgstr "... (no debugging symbols found) ...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1005
+msgid "when `gdb` starts up means that the program was not compiled with `-g`."
+msgstr ""
+"когда `gdb` запускается, это означает, что программа не была скомпилирована "
+"с опцией `-g`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1009
+msgid ""
+"At the `gdb` prompt, type `break main`. This will tell the debugger to skip "
+"the preliminary set-up code in the program being run and to stop execution "
+"at the beginning of the program's code. Now type `run` to start the "
+"program- it will start at the beginning of the set-up code and then get "
+"stopped by the debugger when it calls `main()`."
+msgstr ""
+"На приглашении `gdb` введите `break main`. Это укажет отладчику пропустить "
+"предварительный код настройки в выполняемой программе и остановить "
+"выполнение в начале кода программы. Теперь введите `run`, чтобы запустить "
+"программу — она начнётся с начала кода настройки, а затем будет остановлена "
+"отладчиком при вызове `main()`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1013
+msgid ""
+"To step through the program a line at a time, press `n`. When at a function "
+"call, step into it by pressing `s`. Once in a function call, return from it "
+"by pressing `f`, or use `up` and `down` to take a quick look at the caller."
+msgstr ""
+"Для пошагового выполнения программы нажимайте `n`. При вызове функции "
+"войдите в неё, нажав `s`. Оказавшись внутри функции, вернитесь из неё, нажав "
+"`f`, или используйте `up` и `down` для быстрого просмотра вызывающего кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1016
+msgid ""
+"Here is a simple example of how to spot a mistake in a program with `gdb`. "
+"This is our program (with a deliberate mistake):"
+msgstr ""
+"Вот простой пример того, как найти ошибку в программе с помощью `gdb`. Это "
+"наша программа (с умышленной ошибкой):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1047
+#, no-wrap
+msgid ""
+"% cc -g -o temp temp.c\n"
+"% ./temp\n"
+"This is my program\n"
+"anint = 4231\n"
+msgstr ""
+"% cc -g -o temp temp.c\n"
+"% ./temp\n"
+"This is my program\n"
+"anint = 4231\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1050
+msgid "That was not what we expected! Time to see what is going on!"
+msgstr "Это было не то, что мы ожидали! Пора разобраться, что происходит!"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1062
+#, no-wrap
+msgid ""
+"% gdb temp\n"
+"GDB is free software and you are welcome to distribute copies of it\n"
+" under certain conditions; type \"show copying\" to see the conditions.\n"
+"There is absolutely no warranty for GDB; type \"show warranty\" for details.\n"
+"GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.\n"
+"(gdb) break main\t\t\t\tSkip the set-up code\n"
+"Breakpoint 1 at 0x160f: file temp.c, line 9.\tgdb puts breakpoint at main()\n"
+"(gdb) run\t\t\t\t\tRun as far as main()\n"
+"Starting program: /home/james/tmp/temp\t\tProgram starts running\n"
+msgstr ""
+"% gdb temp\n"
+"GDB is free software and you are welcome to distribute copies of it\n"
+" under certain conditions; type \"show copying\" to see the conditions.\n"
+"There is absolutely no warranty for GDB; type \"show warranty\" for details.\n"
+"GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.\n"
+"(gdb) break main\t\t\t\tSkip the set-up code\n"
+"Breakpoint 1 at 0x160f: file temp.c, line 9.\tgdb puts breakpoint at main()\n"
+"(gdb) run\t\t\t\t\tRun as far as main()\n"
+"Starting program: /home/james/tmp/temp\t\tProgram starts running\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1069
+#, no-wrap
+msgid ""
+"Breakpoint 1, main () at temp.c:9\t\tgdb stops at main()\n"
+"(gdb) n\t\t\t\t\t\tGo to next line\n"
+"This is my program\t\t\t\tProgram prints out\n"
+"(gdb) s\t\t\t\t\t\tstep into bazz()\n"
+"bazz (anint=4231) at temp.c:17\t\t\tgdb displays stack frame\n"
+"(gdb)\n"
+msgstr ""
+"Breakpoint 1, main () at temp.c:9\t\tgdb stops at main()\n"
+"(gdb) n\t\t\t\t\t\tGo to next line\n"
+"This is my program\t\t\t\tProgram prints out\n"
+"(gdb) s\t\t\t\t\t\tstep into bazz()\n"
+"bazz (anint=4231) at temp.c:17\t\t\tgdb displays stack frame\n"
+"(gdb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1072
+msgid ""
+"Hang on a minute! How did anint get to be `4231`? Was it not set to `5` in "
+"`main()`? Let us move up to `main()` and have a look."
+msgstr ""
+"Подождите минуту! Как `int` стал равен `4231`? Разве он не был установлен в "
+"`5` в `main()`? Давайте поднимемся к `main()` и посмотрим."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1079
+#, no-wrap
+msgid ""
+"(gdb) up\t\t\t\t\tMove up call stack\n"
+"#1 0x1625 in main () at temp.c:11\t\tgdb displays stack frame\n"
+"(gdb) p i\t\t\t\t\tShow us the value of i\n"
+"$1 = 4231\t\t\t\t\tgdb displays 4231\n"
+msgstr ""
+"(gdb) up\t\t\t\t\tMove up call stack\n"
+"#1 0x1625 in main () at temp.c:11\t\tgdb displays stack frame\n"
+"(gdb) p i\t\t\t\t\tShow us the value of i\n"
+"$1 = 4231\t\t\t\t\tgdb displays 4231\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1098
+msgid ""
+"but we left the `i=5;` line out. As we did not initialize i, it had "
+"whatever number happened to be in that area of memory when the program ran, "
+"which in this case happened to be `4231`."
+msgstr ""
+"но мы пропустили строку `i=5;`. Поскольку мы не инициализировали `i`, она "
+"содержала любое число, которое оказалось в той области памяти при запуске "
+"программы, и в данном случае это оказалось `4231`."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1104
+msgid ""
+"The `gdb` command displays the stack frame every time we go into or out of a "
+"function, even if we are using `up` and `down` to move around the call "
+"stack. This shows the name of the function and the values of its arguments, "
+"which helps us keep track of where we are and what is going on. (The stack "
+"is a storage area where the program stores information about the arguments "
+"passed to functions and where to go when it returns from a function call.)"
+msgstr ""
+"Команда `gdb` отображает стек вызовов каждый раз при входе в функцию или "
+"выходе из неё, даже при использовании `up` и `down` для перемещения по стеку "
+"вызовов. Это показывает имя функции и значения её аргументов, что помогает "
+"отслеживать текущее положение и происходящее. (Стек — это область хранения, "
+"где программа сохраняет информацию об аргументах, переданных в функции, и о "
+"месте, куда нужно вернуться после вызова функции.)"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1106
+#, no-wrap
+msgid "Examining a Core File with gdb"
+msgstr "Изучение файла core с помощью gdb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1114
+msgid ""
+"To examine a core file, start up `gdb` in the usual way. Instead of typing "
+"`break` or `run`, type"
+msgstr ""
+"Для анализа файла core запустите `gdb` обычным способом. Вместо ввода команд "
+"`break` или `run` введите"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1118
+#, no-wrap
+msgid "(gdb) core progname.core\n"
+msgstr "(gdb) core progname.core\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1121
+msgid ""
+"If the core file is not in the current directory, type `dir /path/to/core/"
+"file` first."
+msgstr ""
+"Если файл core отсутствует в текущем каталоге, сначала введите `dir /путь/к/"
+"core/файлу`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1123
+msgid "The debugger should display something like this:"
+msgstr "Отладчик должен отобразить что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1137
+#, no-wrap
+msgid ""
+"% gdb [.filename]#progname#\n"
+"GDB is free software and you are welcome to distribute copies of it\n"
+" under certain conditions; type \"show copying\" to see the conditions.\n"
+"There is absolutely no warranty for GDB; type \"show warranty\" for details.\n"
+"GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.\n"
+"(gdb) core [.filename]#progname.core#\n"
+"Core was generated by `[.filename]#progname#'.\n"
+"Program terminated with signal 11, Segmentation fault.\n"
+"Cannot access memory at address 0x7020796d.\n"
+"#0 0x164a in bazz (anint=0x5) at temp.c:17\n"
+"(gdb)\n"
+msgstr ""
+"% gdb [.filename]#progname#\n"
+"GDB is free software and you are welcome to distribute copies of it\n"
+" under certain conditions; type \"show copying\" to see the conditions.\n"
+"There is absolutely no warranty for GDB; type \"show warranty\" for details.\n"
+"GDB 4.13 (i386-unknown-freebsd), Copyright 1994 Free Software Foundation, Inc.\n"
+"(gdb) core [.filename]#progname.core#\n"
+"Core was generated by `[.filename]#progname#'.\n"
+"Program terminated with signal 11, Segmentation fault.\n"
+"Cannot access memory at address 0x7020796d.\n"
+"#0 0x164a in bazz (anint=0x5) at temp.c:17\n"
+"(gdb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1141
+msgid ""
+"In this case, the program was called [.filename]#progname#, so the core file "
+"is called [.filename]#progname.core#. We can see that the program crashed "
+"due to trying to access an area in memory that was not available to it in a "
+"function called `bazz`."
+msgstr ""
+"В этом случае программа называлась [.filename]#progname#, поэтому файл дампа "
+"памяти называется [.filename]#progname.core#. Мы видим, что программа "
+"завершилась аварийно из-за попытки доступа к области памяти, которая ей не "
+"доступна, в функции `bazz`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1145
+msgid ""
+"Sometimes it is useful to be able to see how a function was called, as the "
+"problem could have occurred a long way up the call stack in a complex "
+"program. `bt` causes `gdb` to print out a back-trace of the call stack:"
+msgstr ""
+"Иногда полезно увидеть, как была вызвана функция, поскольку проблема могла "
+"возникнуть гораздо выше по стеку вызовов в сложной программе. `bt` "
+"заставляет `gdb` вывести трассировку стека вызовов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1153
+#, no-wrap
+msgid ""
+"(gdb) bt\n"
+"#0 0x164a in bazz (anint=0x5) at temp.c:17\n"
+"#1 0xefbfd888 in end ()\n"
+"#2 0x162c in main () at temp.c:11\n"
+"(gdb)\n"
+msgstr ""
+"(gdb) bt\n"
+"#0 0x164a in bazz (anint=0x5) at temp.c:17\n"
+"#1 0xefbfd888 in end ()\n"
+"#2 0x162c in main () at temp.c:11\n"
+"(gdb)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1157
+msgid ""
+"The `end()` function is called when a program crashes; in this case, the "
+"`bazz()` function was called from `main()`."
+msgstr ""
+"Функция `end()` вызывается при аварийном завершении программы; в данном "
+"случае функция `bazz()` была вызвана из `main()`."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1158
+#, no-wrap
+msgid "Attaching to a Running Program with gdb"
+msgstr "Подключение к работающей программе с помощью gdb"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1163
+msgid ""
+"One of the neatest features about `gdb` is that it can attach to a program "
+"that is already running. Of course, that requires sufficient permissions to "
+"do so. A common problem is stepping through a program that forks and "
+"wanting to trace the child, but the debugger will only trace the parent."
+msgstr ""
+"Одной из самых удобных функций `gdb` является возможность подключения к уже "
+"запущенной программе. Конечно, для этого требуются соответствующие "
+"разрешения. Частой проблемой является пошаговое выполнение программы, "
+"которая создает дочерний процесс, когда нужно отслеживать дочерний процесс, "
+"но отладчик продолжает отслеживать только родительский."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1165
+msgid ""
+"To do that, start up another `gdb`, use `ps` to find the process ID for the "
+"child, and do"
+msgstr ""
+"Для этого запустите другой `gdb`, используйте `ps` для поиска идентификатора "
+"процесса дочернего элемента и выполните"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1169
+#, no-wrap
+msgid "(gdb) attach pid\n"
+msgstr "(gdb) attach pid\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1172
+msgid "in `gdb`, and then debug as usual."
+msgstr "в `gdb`, а затем отлаживайте как обычно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1191
+msgid ""
+"Now all that is needed is to attach to the child, set PauseMode to `0`, and "
+"wait for the `sleep()` call to return!"
+msgstr ""
+"Теперь осталось только подключиться к дочернему процессу, установить "
+"PauseMode в `0` и дождаться возврата из вызова `sleep()`!"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1193
+#, no-wrap
+msgid "Using Emacs as a Development Environment"
+msgstr "Использование Emacs в качестве среды разработки"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1195
+#, no-wrap
+msgid "Emacs"
+msgstr "Emacs"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1199
+msgid ""
+"Emacs is a highly customizable editor-indeed, it has been customized to the "
+"point where it is more like an operating system than an editor! Many "
+"developers and sysadmins do in fact spend practically all their time working "
+"inside Emacs, leaving it only to log out."
+msgstr ""
+"Emacs — это высоконастраиваемый редактор — настолько, что его можно скорее "
+"назвать операционной системой, чем редактором! Многие разработчики и "
+"системные администраторы действительно проводят практически всё своё время, "
+"работая внутри Emacs, выходя из него только для завершения сеанса."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1201
+msgid ""
+"It is impossible even to summarize everything Emacs can do here, but here "
+"are some of the features of interest to developers:"
+msgstr ""
+"Невозможно даже кратко описать все, что может делать Emacs, но вот некоторые "
+"особенности, которые могут быть интересны разработчикам:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1203
+msgid ""
+"Very powerful editor, allowing search-and-replace on both strings and "
+"regular expressions (patterns), jumping to start/end of block expression, "
+"etc, etc."
+msgstr ""
+"Очень мощный редактор, позволяющий выполнять поиск и замену как строк, так и "
+"регулярных выражений (шаблонов), переход к началу/концу блока выражения и "
+"многое другое."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1204
+msgid "Pull-down menus and online help."
+msgstr "Выпадающие меню и встроенная справка."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1205
+msgid "Language-dependent syntax highlighting and indentation."
+msgstr "Подсветка синтаксиса и форматирование отступов в зависимости от языка."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1206
+msgid "Completely customizable."
+msgstr "Полностью настраиваемый."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1207
+msgid "You can compile and debug programs within Emacs."
+msgstr "Вы можете компилировать и отлаживать программы из Emacs."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1208
+msgid ""
+"On a compilation error, you can jump to the offending line of source code."
+msgstr ""
+"При ошибке компиляции можно перейти к проблемной строке исходного кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1209
+msgid ""
+"Friendly-ish front-end to the `info` program used for reading GNU hypertext "
+"documentation, including the documentation on Emacs itself."
+msgstr ""
+"Дружелюбный интерфейс для программы `info`, используемой для чтения "
+"гипертекстовой документации GNU, включая документацию по самому Emacs."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1210
+msgid ""
+"Friendly front-end to `gdb`, allowing you to look at the source code as you "
+"step through your program."
+msgstr ""
+"Дружелюбный интерфейс для `gdb`, позволяющий просматривать исходный код во "
+"время пошагового выполнения программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1212
+msgid "And doubtless many more that have been overlooked."
+msgstr "И, несомненно, множество других, которые были упущены из виду."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1214
+msgid ""
+"Emacs can be installed on FreeBSD using the package:editors/emacs[] port."
+msgstr ""
+"Emacs можно установить на FreeBSD с помощью пакета package:editors/emacs[]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1217
+msgid ""
+"Once it is installed, start it up and do `C-h t` to read an Emacs tutorial-"
+"that means hold down kbd:[control], press kbd:[h], let go of kbd:[control], "
+"and then press kbd:[t]. (Alternatively, you can use the mouse to select "
+"[.guimenuitem]#Emacs Tutorial# from the menu:Help[] menu.)"
+msgstr ""
+"После установки запустите его и выполните `C-h t`, чтобы прочитать "
+"руководство по Emacs — это означает, что нужно удерживать kbd:[control], "
+"нажать kbd:[h], отпустить kbd:[control], а затем нажать kbd:[t]. (Также "
+"можно использовать мышь для выбора [.guimenuitem]#Руководство по Emacs# в "
+"меню menu:Help[].)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1222
+msgid ""
+"Although Emacs does have menus, it is well worth learning the key bindings, "
+"as it is much quicker when you are editing something to press a couple of "
+"keys than to try to find the mouse and then click on the right place. And, "
+"when you are talking to seasoned Emacs users, you will find they often "
+"casually throw around expressions like \"`M-x replace-s RET foo RET bar "
+"RET`\" so it is useful to know what they mean. And in any case, Emacs has "
+"far too many useful functions for them to all fit on the menu bars."
+msgstr ""
+"Хотя в Emacs и есть меню, стоит изучить сочетания клавиш, так как "
+"редактировать что-либо с их помощью гораздо быстрее, чем искать мышку и "
+"кликать в нужное место. Кроме того, общаясь с опытными пользователями Emacs, "
+"вы часто услышите выражения вроде «`M-x replace-s RET foo RET bar RET`» — "
+"полезно понимать, что они значат. Да и вообще, в Emacs столько полезных "
+"функций, что все они просто не поместятся на панелях меню."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1226
+msgid ""
+"Fortunately, it is quite easy to pick up the key-bindings, as they are "
+"displayed next to the menu item. My advice is to use the menu item for, "
+"say, opening a file until you understand how it works and feel confident "
+"with it, then try doing C-x C-f. When you are happy with that, move on to "
+"another menu command."
+msgstr ""
+"К счастью, освоить сочетания клавиш довольно легко, так как они отображаются "
+"рядом с пунктами меню. Мой совет — использовать пункты меню для, скажем, "
+"открытия файла, пока вы не разберётесь, как это работает, и не почувствуете "
+"себя уверенно, а затем попробуйте выполнить `C-x C-f`. Когда освоитесь с "
+"этим, переходите к следующей команде меню."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1229
+msgid ""
+"If you cannot remember what a particular combination of keys does, select "
+"[.guimenuitem]#Describe Key# from the menu:Help[] menu and type it in-Emacs "
+"will tell you what it does. You can also use the [.guimenuitem]#Command "
+"Apropos# menu item to find out all the commands which contain a particular "
+"word in them, with the key binding next to it."
+msgstr ""
+"Если вы не можете вспомнить, что делает определённая комбинация клавиш, "
+"выберите [.guimenuitem]#Описание Клавиши# в меню menu:Help[] и введите её — "
+"Emacs сообщит, что она делает. Вы также можете использовать пункт меню "
+"[.guimenuitem]#Command Apropos#, чтобы найти все команды, содержащие "
+"определённое слово, с указанием соответствующих клавишных сочетаний."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1232
+msgid ""
+"By the way, the expression above means hold down the kbd:[Meta] key, press "
+"kbd:[x], release the kbd:[Meta] key, type `replace-s` (short for `replace-"
+"string`-another feature of Emacs is that you can abbreviate commands), press "
+"the kbd:[return] key, type `foo` (the string you want replaced), press the "
+"kbd:[return] key, type bar (the string you want to replace `foo` with) and "
+"press kbd:[return] again. Emacs will then do the search-and-replace "
+"operation you have just requested."
+msgstr ""
+"Между прочим, выражение выше означает: удерживайте клавишу kbd:[Meta], "
+"нажмите kbd:[x], отпустите клавишу kbd:[Meta], введите `replace-s` "
+"(сокращение от `replace-string` — ещё одна особенность Emacs в том, что "
+"команды можно сокращать), нажмите клавишу kbd:[return], введите `foo` "
+"(строка, которую нужно заменить), нажмите клавишу kbd:[return], введите "
+"`bar` (строка, на которую нужно заменить `foo`) и снова нажмите kbd:"
+"[return]. Emacs выполнит операцию поиска и замены, которую вы только что "
+"запросили."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1235
+msgid ""
+"If you are wondering what on earth kbd:[Meta] is, it is a special key that "
+"many UNIX(R) workstations have. Unfortunately, PC's do not have one, so it "
+"is usually kbd:[alt] (or if you are unlucky, the kbd:[escape] key)."
+msgstr ""
+"Если вам интересно, что такое kbd:[Meta], то это специальная клавиша, "
+"которая есть на многих рабочих станциях UNIX(R). К сожалению, на PC её нет, "
+"поэтому обычно используется kbd:[alt] (или, если вам не повезло, kbd:"
+"[escape])."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1239
+msgid ""
+"Oh, and to get out of Emacs, do `C-x C-c` (that means hold down the kbd:"
+"[control] key, press kbd:[x], press kbd:[c] and release the kbd:[control] "
+"key). If you have any unsaved files open, Emacs will ask you if you want to "
+"save them. (Ignore the bit in the documentation where it says `C-z` is the "
+"usual way to leave Emacs-that leaves Emacs hanging around in the background, "
+"and is only really useful if you are on a system which does not have virtual "
+"terminals)."
+msgstr ""
+"Ах да, чтобы выйти из Emacs, нажмите `C-x C-c` (это значит зажмите клавишу "
+"kbd:[control], нажмите kbd:[x], затем kbd:[c] и отпустите kbd:[control]). "
+"Если у вас есть несохранённые файлы, Emacs спросит, хотите ли вы их "
+"сохранить. (Игнорируйте часть документации, где говорится, что `C-z` — это "
+"обычный способ выхода из Emacs — это оставляет Emacs работающим в фоне и "
+"полезно только на системах без виртуальных терминалов)."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1240
+#, no-wrap
+msgid "Configuring Emacs"
+msgstr "Настройка Emacs"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1243
+msgid ""
+"Emacs does many wonderful things; some of them are built in, some of them "
+"need to be configured."
+msgstr ""
+"Emacs делает много замечательных вещей; некоторые из них встроены, некоторые "
+"требуют настройки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1247
+msgid ""
+"Instead of using a proprietary macro language for configuration, Emacs uses "
+"a version of Lisp specially adapted for editors, known as Emacs Lisp. "
+"Working with Emacs Lisp can be quite helpful if you want to go on and learn "
+"something like Common Lisp. Emacs Lisp has many features of Common Lisp, "
+"although it is considerably smaller (and thus easier to master)."
+msgstr ""
+"Вместо использования проприетарного языка макросов для конфигурации, Emacs "
+"применяет версию Lisp, специально адаптированную для редакторов, известную "
+"как Emacs Lisp. Работа с Emacs Lisp может быть весьма полезной, если вы "
+"хотите продолжить и изучить что-то вроде Common Lisp. Emacs Lisp обладает "
+"многими возможностями Common Lisp, хотя и значительно меньше (и, "
+"следовательно, проще для освоения)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1249
+msgid ""
+"The best way to learn Emacs Lisp is to read the online link:https://"
+"www.gnu.org/software/emacs/manual/elisp.html[Emacs Reference] manual."
+msgstr ""
+"Лучший способ изучить Emacs Lisp — это прочитать онлайн-руководство "
+"link:https://www.gnu.org/software/emacs/manual/elisp.html[Emacs Reference]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1254
+msgid ""
+"However, there is no need to actually know any Lisp to get started with "
+"configuring Emacs, as I have included a sample [.filename]#.emacs#, which "
+"should be enough to get you started. Just copy it into your home directory "
+"and restart Emacs if it is already running; it will read the commands from "
+"the file and (hopefully) give you a useful basic setup."
+msgstr ""
+"Однако для начала настройки Emacs не обязательно знать Lisp, так как я "
+"включил пример файла [.filename]#.emacs#, которого должно быть достаточно "
+"для старта. Просто скопируйте его в свой домашний каталог и перезапустите "
+"Emacs, если он уже запущен; он прочитает команды из файла и (надеюсь) "
+"предоставит вам полезную базовую конфигурацию."
+
+#. type: Block title
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1255
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1273
+#, no-wrap
+msgid "A Sample [.filename]#.emacs#"
+msgstr "Пример файла [.filename]#.emacs#"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1258
+msgid ""
+"Unfortunately, there is far too much here to explain it in detail; however "
+"there are one or two points worth mentioning."
+msgstr ""
+"К сожалению, здесь слишком много информации, чтобы объяснять всё подробно; "
+"однако есть один или два момента, которые стоит упомянуть."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1260
+msgid "Everything beginning with a `;` is a comment and is ignored by Emacs."
+msgstr "Всё, что начинается с `;`, является комментарием и игнорируется Emacs."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1261
+msgid ""
+"In the first line, the `-*- Emacs-Lisp -*-` is so that we can edit "
+"[.filename]#.emacs# itself within Emacs and get all the fancy features for "
+"editing Emacs Lisp. Emacs usually tries to guess this based on the filename, "
+"and may not get it right for [.filename]#.emacs#."
+msgstr ""
+"В первой строке `-*- Emacs-Lisp -*-` нужен для того, чтобы мы могли "
+"редактировать сам файл [.filename]#.emacs# в Emacs и использовать все "
+"удобные функции для редактирования Emacs Lisp. Обычно Emacs пытается угадать "
+"это по имени файла, но может не сделать это правильно для "
+"[.filename]#.emacs#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1262
+msgid ""
+"The kbd:[tab] key is bound to an indentation function in some modes, so when "
+"you press the tab key, it will indent the current line of code. If you want "
+"to put a tab character in whatever you are writing, hold the kbd:[control] "
+"key down while you are pressing the kbd:[tab] key."
+msgstr ""
+"Клавиша kbd:[tab] связана с функцией отступа в некоторых режимах, поэтому "
+"при нажатии клавиши tab текущая строка кода будет с отступом. Если вы хотите "
+"вставить символ табуляции в текст, удерживайте клавишу kbd:[control] во "
+"время нажатия kbd:[tab]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1263
+msgid ""
+"This file supports syntax highlighting for C, C++, Perl, Lisp and Scheme, by "
+"guessing the language from the filename."
+msgstr ""
+"Этот файл поддерживает подсветку синтаксиса для C, C++, Perl, Lisp и Scheme, "
+"определяя язык по имени файла."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1264
+msgid ""
+"Emacs already has a pre-defined function called `next-error`. In a "
+"compilation output window, this allows you to move from one compilation "
+"error to the next by doing `M-n`; we define a complementary function, "
+"`previous-error`, that allows you to go to a previous error by doing `M-p`. "
+"The nicest feature of all is that `C-c C-c` will open up the source file in "
+"which the error occurred and jump to the appropriate line."
+msgstr ""
+"В Emacs уже есть предопределённая функция `next-error`. В окне вывода "
+"компиляции это позволяет переходить от одной ошибки компиляции к следующей с "
+"помощью `M-n`; мы определяем дополнительную функцию `previous-error`, "
+"которая позволяет вернуться к предыдущей ошибке с помощью `M-p`. Самое "
+"приятное — сочетание `C-c C-c` откроет исходный файл, в котором произошла "
+"ошибка, и перейдёт на соответствующую строку."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1265
+msgid ""
+"We enable Emacs's ability to act as a server, so that if you are doing "
+"something outside Emacs and you want to edit a file, you can just type in"
+msgstr ""
+"Включаем возможность Emacs работать как сервер, так что если вы заняты чем-"
+"то вне Emacs и хотите отредактировать файл, можно просто ввести"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1269
+#, no-wrap
+msgid "% emacsclient filename\n"
+msgstr "% emacsclient filename\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1272
+msgid ""
+"and then you can edit the file in your Emacs!footnote:[Many Emacs users set "
+"their EDITOR environment to emacsclient so this happens every time they need "
+"to edit a file.]"
+msgstr ""
+"и затем вы можете редактировать файл в вашем Emacs!footnote:[Многие "
+"пользователи Emacs устанавливают переменную окружения EDITOR в emacsclient, "
+"так что это происходит каждый раз, когда им нужно отредактировать файл.]"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1278
+#, no-wrap
+msgid ";; -*-Emacs-Lisp-*-\n"
+msgstr ";; -*-Emacs-Lisp-*-\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1283
+#, no-wrap
+msgid ""
+";; This file is designed to be re-evaled; use the variable first-time\n"
+";; to avoid any problems with this.\n"
+"(defvar first-time t\n"
+" \"Flag signifying this is the first time that .emacs has been evaled\")\n"
+msgstr ""
+";; This file is designed to be re-evaled; use the variable first-time\n"
+";; to avoid any problems with this.\n"
+"(defvar first-time t\n"
+" \"Flag signifying this is the first time that .emacs has been evaled\")\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1291
+#, no-wrap
+msgid ""
+";; Meta\n"
+"(global-set-key \"\\M- \" 'set-mark-command)\n"
+"(global-set-key \"\\M-\\C-h\" 'backward-kill-word)\n"
+"(global-set-key \"\\M-\\C-r\" 'query-replace)\n"
+"(global-set-key \"\\M-r\" 'replace-string)\n"
+"(global-set-key \"\\M-g\" 'goto-line)\n"
+"(global-set-key \"\\M-h\" 'help-command)\n"
+msgstr ""
+";; Meta\n"
+"(global-set-key \"\\M- \" 'set-mark-command)\n"
+"(global-set-key \"\\M-\\C-h\" 'backward-kill-word)\n"
+"(global-set-key \"\\M-\\C-r\" 'query-replace)\n"
+"(global-set-key \"\\M-r\" 'replace-string)\n"
+"(global-set-key \"\\M-g\" 'goto-line)\n"
+"(global-set-key \"\\M-h\" 'help-command)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1312
+#, no-wrap
+msgid ""
+";; Function keys\n"
+"(global-set-key [f1] 'manual-entry)\n"
+"(global-set-key [f2] 'info)\n"
+"(global-set-key [f3] 'repeat-complex-command)\n"
+"(global-set-key [f4] 'advertised-undo)\n"
+"(global-set-key [f5] 'eval-current-buffer)\n"
+"(global-set-key [f6] 'buffer-menu)\n"
+"(global-set-key [f7] 'other-window)\n"
+"(global-set-key [f8] 'find-file)\n"
+"(global-set-key [f9] 'save-buffer)\n"
+"(global-set-key [f10] 'next-error)\n"
+"(global-set-key [f11] 'compile)\n"
+"(global-set-key [f12] 'grep)\n"
+"(global-set-key [C-f1] 'compile)\n"
+"(global-set-key [C-f2] 'grep)\n"
+"(global-set-key [C-f3] 'next-error)\n"
+"(global-set-key [C-f4] 'previous-error)\n"
+"(global-set-key [C-f5] 'display-faces)\n"
+"(global-set-key [C-f8] 'dired)\n"
+"(global-set-key [C-f10] 'kill-compilation)\n"
+msgstr ""
+";; Function keys\n"
+"(global-set-key [f1] 'manual-entry)\n"
+"(global-set-key [f2] 'info)\n"
+"(global-set-key [f3] 'repeat-complex-command)\n"
+"(global-set-key [f4] 'advertised-undo)\n"
+"(global-set-key [f5] 'eval-current-buffer)\n"
+"(global-set-key [f6] 'buffer-menu)\n"
+"(global-set-key [f7] 'other-window)\n"
+"(global-set-key [f8] 'find-file)\n"
+"(global-set-key [f9] 'save-buffer)\n"
+"(global-set-key [f10] 'next-error)\n"
+"(global-set-key [f11] 'compile)\n"
+"(global-set-key [f12] 'grep)\n"
+"(global-set-key [C-f1] 'compile)\n"
+"(global-set-key [C-f2] 'grep)\n"
+"(global-set-key [C-f3] 'next-error)\n"
+"(global-set-key [C-f4] 'previous-error)\n"
+"(global-set-key [C-f5] 'display-faces)\n"
+"(global-set-key [C-f8] 'dired)\n"
+"(global-set-key [C-f10] 'kill-compilation)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1330
+#, no-wrap
+msgid ""
+";; Keypad bindings\n"
+"(global-set-key [up] \"\\C-p\")\n"
+"(global-set-key [down] \"\\C-n\")\n"
+"(global-set-key [left] \"\\C-b\")\n"
+"(global-set-key [right] \"\\C-f\")\n"
+"(global-set-key [home] \"\\C-a\")\n"
+"(global-set-key [end] \"\\C-e\")\n"
+"(global-set-key [prior] \"\\M-v\")\n"
+"(global-set-key [next] \"\\C-v\")\n"
+"(global-set-key [C-up] \"\\M-\\C-b\")\n"
+"(global-set-key [C-down] \"\\M-\\C-f\")\n"
+"(global-set-key [C-left] \"\\M-b\")\n"
+"(global-set-key [C-right] \"\\M-f\")\n"
+"(global-set-key [C-home] \"\\M-<\")\n"
+"(global-set-key [C-end] \"\\M->\")\n"
+"(global-set-key [C-prior] \"\\M-<\")\n"
+"(global-set-key [C-next] \"\\M->\")\n"
+msgstr ""
+";; Keypad bindings\n"
+"(global-set-key [up] \"\\C-p\")\n"
+"(global-set-key [down] \"\\C-n\")\n"
+"(global-set-key [left] \"\\C-b\")\n"
+"(global-set-key [right] \"\\C-f\")\n"
+"(global-set-key [home] \"\\C-a\")\n"
+"(global-set-key [end] \"\\C-e\")\n"
+"(global-set-key [prior] \"\\M-v\")\n"
+"(global-set-key [next] \"\\C-v\")\n"
+"(global-set-key [C-up] \"\\M-\\C-b\")\n"
+"(global-set-key [C-down] \"\\M-\\C-f\")\n"
+"(global-set-key [C-left] \"\\M-b\")\n"
+"(global-set-key [C-right] \"\\M-f\")\n"
+"(global-set-key [C-home] \"\\M-<\")\n"
+"(global-set-key [C-end] \"\\M->\")\n"
+"(global-set-key [C-prior] \"\\M-<\")\n"
+"(global-set-key [C-next] \"\\M->\")\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1333
+#, no-wrap
+msgid ""
+";; Mouse\n"
+"(global-set-key [mouse-3] 'imenu)\n"
+msgstr ""
+";; Mouse\n"
+"(global-set-key [mouse-3] 'imenu)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1337
+#, no-wrap
+msgid ""
+";; Misc\n"
+"(global-set-key [C-tab] \"\\C-q\\t\")\t; Control tab quotes a tab.\n"
+"(setq backup-by-copying-when-mismatch t)\n"
+msgstr ""
+";; Misc\n"
+"(global-set-key [C-tab] \"\\C-q\\t\")\t; Control tab quotes a tab.\n"
+"(setq backup-by-copying-when-mismatch t)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1342
+#, no-wrap
+msgid ""
+";; Treat 'y' or <CR> as yes, 'n' as no.\n"
+"(fset 'yes-or-no-p 'y-or-n-p)\n"
+"(define-key query-replace-map [return] 'act)\n"
+"(define-key query-replace-map [?\\C-m] 'act)\n"
+msgstr ""
+";; Treat 'y' or <CR> as yes, 'n' as no.\n"
+"(fset 'yes-or-no-p 'y-or-n-p)\n"
+"(define-key query-replace-map [return] 'act)\n"
+"(define-key query-replace-map [?\\C-m] 'act)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1346
+#, no-wrap
+msgid ""
+";; Load packages\n"
+"(require 'desktop)\n"
+"(require 'tar-mode)\n"
+msgstr ""
+";; Load packages\n"
+"(require 'desktop)\n"
+"(require 'tar-mode)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1352
+#, no-wrap
+msgid ""
+";; Pretty diff mode\n"
+"(autoload 'ediff-buffers \"ediff\" \"Intelligent Emacs interface to diff\" t)\n"
+"(autoload 'ediff-files \"ediff\" \"Intelligent Emacs interface to diff\" t)\n"
+"(autoload 'ediff-files-remote \"ediff\"\n"
+" \"Intelligent Emacs interface to diff\")\n"
+msgstr ""
+";; Pretty diff mode\n"
+"(autoload 'ediff-buffers \"ediff\" \"Intelligent Emacs interface to diff\" t)\n"
+"(autoload 'ediff-files \"ediff\" \"Intelligent Emacs interface to diff\" t)\n"
+"(autoload 'ediff-files-remote \"ediff\"\n"
+" \"Intelligent Emacs interface to diff\")\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1361
+#, no-wrap
+msgid ""
+"(if first-time\n"
+" (setq auto-mode-alist\n"
+"\t (append '((\"\\\\.cpp$\" . c++-mode)\n"
+"\t\t (\"\\\\.hpp$\" . c++-mode)\n"
+"\t\t (\"\\\\.lsp$\" . lisp-mode)\n"
+"\t\t (\"\\\\.scm$\" . scheme-mode)\n"
+"\t\t (\"\\\\.pl$\" . perl-mode)\n"
+"\t\t ) auto-mode-alist)))\n"
+msgstr ""
+"(if first-time\n"
+" (setq auto-mode-alist\n"
+"\t (append '((\"\\\\.cpp$\" . c++-mode)\n"
+"\t\t (\"\\\\.hpp$\" . c++-mode)\n"
+"\t\t (\"\\\\.lsp$\" . lisp-mode)\n"
+"\t\t (\"\\\\.scm$\" . scheme-mode)\n"
+"\t\t (\"\\\\.pl$\" . perl-mode)\n"
+"\t\t ) auto-mode-alist)))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1366
+#, no-wrap
+msgid ""
+";; Auto font lock mode\n"
+"(defvar font-lock-auto-mode-list\n"
+" (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode)\n"
+" \"List of modes to always start in font-lock-mode\")\n"
+msgstr ""
+";; Auto font lock mode\n"
+"(defvar font-lock-auto-mode-list\n"
+" (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'lisp-mode 'perl-mode 'scheme-mode)\n"
+" \"List of modes to always start in font-lock-mode\")\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1371
+#, no-wrap
+msgid ""
+"(defvar font-lock-mode-keyword-alist\n"
+" '((c++-c-mode . c-font-lock-keywords)\n"
+" (perl-mode . perl-font-lock-keywords))\n"
+" \"Associations between modes and keywords\")\n"
+msgstr ""
+"(defvar font-lock-mode-keyword-alist\n"
+" '((c++-c-mode . c-font-lock-keywords)\n"
+" (perl-mode . perl-font-lock-keywords))\n"
+" \"Associations between modes and keywords\")\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1379
+#, no-wrap
+msgid ""
+"(defun font-lock-auto-mode-select ()\n"
+" \"Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list\"\n"
+" (if (memq major-mode font-lock-auto-mode-list)\n"
+" (progn\n"
+"\t(font-lock-mode t))\n"
+" )\n"
+" )\n"
+msgstr ""
+"(defun font-lock-auto-mode-select ()\n"
+" \"Automatically select font-lock-mode if the current major mode is in font-lock-auto-mode-list\"\n"
+" (if (memq major-mode font-lock-auto-mode-list)\n"
+" (progn\n"
+"\t(font-lock-mode t))\n"
+" )\n"
+" )\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1381
+#, no-wrap
+msgid "(global-set-key [M-f1] 'font-lock-fontify-buffer)\n"
+msgstr "(global-set-key [M-f1] 'font-lock-fontify-buffer)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1398
+#, no-wrap
+msgid ""
+";; New dabbrev stuff\n"
+";(require 'new-dabbrev)\n"
+"(setq dabbrev-always-check-other-buffers t)\n"
+"(setq dabbrev-abbrev-char-regexp \"\\\\sw\\\\|\\\\s_\")\n"
+"(add-hook 'emacs-lisp-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) nil)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) nil)))\n"
+"(add-hook 'c-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) nil)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) nil)))\n"
+"(add-hook 'text-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) t)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) t)))\n"
+msgstr ""
+";; New dabbrev stuff\n"
+";(require 'new-dabbrev)\n"
+"(setq dabbrev-always-check-other-buffers t)\n"
+"(setq dabbrev-abbrev-char-regexp \"\\\\sw\\\\|\\\\s_\")\n"
+"(add-hook 'emacs-lisp-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) nil)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) nil)))\n"
+"(add-hook 'c-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) nil)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) nil)))\n"
+"(add-hook 'text-mode-hook\n"
+"\t '(lambda ()\n"
+"\t (set (make-local-variable 'dabbrev-case-fold-search) t)\n"
+"\t (set (make-local-variable 'dabbrev-case-replace) t)))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1410
+#, no-wrap
+msgid ""
+";; C++ and C mode...\n"
+"(defun my-c++-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c++-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key c++-mode-map \"\\C-ce\" 'c-comment-edit)\n"
+" (setq c++-auto-hungry-initial-state 'none)\n"
+" (setq c++-delete-function 'backward-delete-char)\n"
+" (setq c++-tab-always-indent t)\n"
+" (setq c-indent-level 4)\n"
+" (setq c-continued-statement-offset 4)\n"
+" (setq c++-empty-arglist-indent 4))\n"
+msgstr ""
+";; C++ and C mode...\n"
+"(defun my-c++-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c++-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key c++-mode-map \"\\C-ce\" 'c-comment-edit)\n"
+" (setq c++-auto-hungry-initial-state 'none)\n"
+" (setq c++-delete-function 'backward-delete-char)\n"
+" (setq c++-tab-always-indent t)\n"
+" (setq c-indent-level 4)\n"
+" (setq c-continued-statement-offset 4)\n"
+" (setq c++-empty-arglist-indent 4))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1424
+#, no-wrap
+msgid ""
+"(defun my-c-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key c-mode-map \"\\C-ce\" 'c-comment-edit)\n"
+" (setq c-auto-hungry-initial-state 'none)\n"
+" (setq c-delete-function 'backward-delete-char)\n"
+" (setq c-tab-always-indent t)\n"
+";; BSD-ish indentation style\n"
+" (setq c-indent-level 4)\n"
+" (setq c-continued-statement-offset 4)\n"
+" (setq c-brace-offset -4)\n"
+" (setq c-argdecl-indent 0)\n"
+" (setq c-label-offset -4))\n"
+msgstr ""
+"(defun my-c-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key c-mode-map \"\\C-ce\" 'c-comment-edit)\n"
+" (setq c-auto-hungry-initial-state 'none)\n"
+" (setq c-delete-function 'backward-delete-char)\n"
+" (setq c-tab-always-indent t)\n"
+";; BSD-ish indentation style\n"
+" (setq c-indent-level 4)\n"
+" (setq c-continued-statement-offset 4)\n"
+" (setq c-brace-offset -4)\n"
+" (setq c-argdecl-indent 0)\n"
+" (setq c-label-offset -4))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1431
+#, no-wrap
+msgid ""
+";; Perl mode\n"
+"(defun my-perl-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c++-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (setq perl-indent-level 4)\n"
+" (setq perl-continued-statement-offset 4))\n"
+msgstr ""
+";; Perl mode\n"
+"(defun my-perl-mode-hook ()\n"
+" (setq tab-width 4)\n"
+" (define-key c++-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (setq perl-indent-level 4)\n"
+" (setq perl-continued-statement-offset 4))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1435
+#, no-wrap
+msgid ""
+";; Scheme mode...\n"
+"(defun my-scheme-mode-hook ()\n"
+" (define-key scheme-mode-map \"\\C-m\" 'reindent-then-newline-and-indent))\n"
+msgstr ""
+";; Scheme mode...\n"
+"(defun my-scheme-mode-hook ()\n"
+" (define-key scheme-mode-map \"\\C-m\" 'reindent-then-newline-and-indent))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1441
+#, no-wrap
+msgid ""
+";; Emacs-Lisp mode...\n"
+"(defun my-lisp-mode-hook ()\n"
+" (define-key lisp-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key lisp-mode-map \"\\C-i\" 'lisp-indent-line)\n"
+" (define-key lisp-mode-map \"\\C-j\" 'eval-print-last-sexp))\n"
+msgstr ""
+";; Emacs-Lisp mode...\n"
+"(defun my-lisp-mode-hook ()\n"
+" (define-key lisp-mode-map \"\\C-m\" 'reindent-then-newline-and-indent)\n"
+" (define-key lisp-mode-map \"\\C-i\" 'lisp-indent-line)\n"
+" (define-key lisp-mode-map \"\\C-j\" 'eval-print-last-sexp))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1449
+#, no-wrap
+msgid ""
+";; Add all of the hooks...\n"
+"(add-hook 'c++-mode-hook 'my-c++-mode-hook)\n"
+"(add-hook 'c-mode-hook 'my-c-mode-hook)\n"
+"(add-hook 'scheme-mode-hook 'my-scheme-mode-hook)\n"
+"(add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook)\n"
+"(add-hook 'lisp-mode-hook 'my-lisp-mode-hook)\n"
+"(add-hook 'perl-mode-hook 'my-perl-mode-hook)\n"
+msgstr ""
+";; Add all of the hooks...\n"
+"(add-hook 'c++-mode-hook 'my-c++-mode-hook)\n"
+"(add-hook 'c-mode-hook 'my-c-mode-hook)\n"
+"(add-hook 'scheme-mode-hook 'my-scheme-mode-hook)\n"
+"(add-hook 'emacs-lisp-mode-hook 'my-lisp-mode-hook)\n"
+"(add-hook 'lisp-mode-hook 'my-lisp-mode-hook)\n"
+"(add-hook 'perl-mode-hook 'my-perl-mode-hook)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1455
+#, no-wrap
+msgid ""
+";; Complement to next-error\n"
+"(defun previous-error (n)\n"
+" \"Visit previous compilation error message and corresponding source code.\"\n"
+" (interactive \"p\")\n"
+" (next-error (- n)))\n"
+msgstr ""
+";; Complement to next-error\n"
+"(defun previous-error (n)\n"
+" \"Visit previous compilation error message and corresponding source code.\"\n"
+" (interactive \"p\")\n"
+" (next-error (- n)))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1468
+#, no-wrap
+msgid ""
+";; Misc...\n"
+"(transient-mark-mode 1)\n"
+"(setq mark-even-if-inactive t)\n"
+"(setq visible-bell nil)\n"
+"(setq next-line-add-newlines nil)\n"
+"(setq compile-command \"make\")\n"
+"(setq suggest-key-bindings nil)\n"
+"(put 'eval-expression 'disabled nil)\n"
+"(put 'narrow-to-region 'disabled nil)\n"
+"(put 'set-goal-column 'disabled nil)\n"
+"(if (>= emacs-major-version 21)\n"
+"\t(setq show-trailing-whitespace t))\n"
+msgstr ""
+";; Misc...\n"
+"(transient-mark-mode 1)\n"
+"(setq mark-even-if-inactive t)\n"
+"(setq visible-bell nil)\n"
+"(setq next-line-add-newlines nil)\n"
+"(setq compile-command \"make\")\n"
+"(setq suggest-key-bindings nil)\n"
+"(put 'eval-expression 'disabled nil)\n"
+"(put 'narrow-to-region 'disabled nil)\n"
+"(put 'set-goal-column 'disabled nil)\n"
+"(if (>= emacs-major-version 21)\n"
+"\t(setq show-trailing-whitespace t))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1474
+#, no-wrap
+msgid ""
+";; Elisp archive searching\n"
+"(autoload 'format-lisp-code-directory \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-apropos \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-retrieve \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-verify \"lispdir\" nil t)\n"
+msgstr ""
+";; Elisp archive searching\n"
+"(autoload 'format-lisp-code-directory \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-apropos \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-retrieve \"lispdir\" nil t)\n"
+"(autoload 'lisp-dir-verify \"lispdir\" nil t)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1483
+#, no-wrap
+msgid ""
+";; Font lock mode\n"
+"(defun my-make-face (face color &optional bold)\n"
+" \"Create a face from a color and optionally make it bold\"\n"
+" (make-face face)\n"
+" (copy-face 'default face)\n"
+" (set-face-foreground face color)\n"
+" (if bold (make-face-bold face))\n"
+" )\n"
+msgstr ""
+";; Font lock mode\n"
+"(defun my-make-face (face color &optional bold)\n"
+" \"Create a face from a color and optionally make it bold\"\n"
+" (make-face face)\n"
+" (copy-face 'default face)\n"
+" (set-face-foreground face color)\n"
+" (if bold (make-face-bold face))\n"
+" )\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1496
+#, no-wrap
+msgid ""
+"(if (eq window-system 'x)\n"
+" (progn\n"
+" (my-make-face 'blue \"blue\")\n"
+" (my-make-face 'red \"red\")\n"
+" (my-make-face 'green \"dark green\")\n"
+" (setq font-lock-comment-face 'blue)\n"
+" (setq font-lock-string-face 'bold)\n"
+" (setq font-lock-type-face 'bold)\n"
+" (setq font-lock-keyword-face 'bold)\n"
+" (setq font-lock-function-name-face 'red)\n"
+" (setq font-lock-doc-string-face 'green)\n"
+" (add-hook 'find-file-hooks 'font-lock-auto-mode-select)\n"
+msgstr ""
+"(if (eq window-system 'x)\n"
+" (progn\n"
+" (my-make-face 'blue \"blue\")\n"
+" (my-make-face 'red \"red\")\n"
+" (my-make-face 'green \"dark green\")\n"
+" (setq font-lock-comment-face 'blue)\n"
+" (setq font-lock-string-face 'bold)\n"
+" (setq font-lock-type-face 'bold)\n"
+" (setq font-lock-keyword-face 'bold)\n"
+" (setq font-lock-function-name-face 'red)\n"
+" (setq font-lock-doc-string-face 'green)\n"
+" (add-hook 'find-file-hooks 'font-lock-auto-mode-select)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1504
+#, no-wrap
+msgid ""
+" (setq baud-rate 1000000)\n"
+" (global-set-key \"\\C-cmm\" 'menu-bar-mode)\n"
+" (global-set-key \"\\C-cms\" 'scroll-bar-mode)\n"
+" (global-set-key [backspace] 'backward-delete-char)\n"
+"\t\t\t\t\t; (global-set-key [delete] 'delete-char)\n"
+" (standard-display-european t)\n"
+" (load-library \"iso-transl\")))\n"
+msgstr ""
+" (setq baud-rate 1000000)\n"
+" (global-set-key \"\\C-cmm\" 'menu-bar-mode)\n"
+" (global-set-key \"\\C-cms\" 'scroll-bar-mode)\n"
+" (global-set-key [backspace] 'backward-delete-char)\n"
+"\t\t\t\t\t; (global-set-key [delete] 'delete-char)\n"
+" (standard-display-european t)\n"
+" (load-library \"iso-transl\")))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1521
+#, no-wrap
+msgid ""
+";; X11 or PC using direct screen writes\n"
+"(if window-system\n"
+" (progn\n"
+" ;; (global-set-key [M-f1] 'hilit-repaint-command)\n"
+" ;; (global-set-key [M-f2] [?\\C-u M-f1])\n"
+" (setq hilit-mode-enable-list\n"
+"\t '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode\n"
+"\t\t scheme-mode)\n"
+"\t hilit-auto-highlight nil\n"
+"\t hilit-auto-rehighlight 'visible\n"
+"\t hilit-inhibit-hooks nil\n"
+"\t hilit-inhibit-rebinding t)\n"
+" (require 'hilit19)\n"
+" (require 'paren))\n"
+" (setq baud-rate 2400)\t\t\t; For slow serial connections\n"
+" )\n"
+msgstr ""
+";; X11 or PC using direct screen writes\n"
+"(if window-system\n"
+" (progn\n"
+" ;; (global-set-key [M-f1] 'hilit-repaint-command)\n"
+" ;; (global-set-key [M-f2] [?\\C-u M-f1])\n"
+" (setq hilit-mode-enable-list\n"
+"\t '(not text-mode c-mode c++-mode emacs-lisp-mode lisp-mode\n"
+"\t\t scheme-mode)\n"
+"\t hilit-auto-highlight nil\n"
+"\t hilit-auto-rehighlight 'visible\n"
+"\t hilit-inhibit-hooks nil\n"
+"\t hilit-inhibit-rebinding t)\n"
+" (require 'hilit19)\n"
+" (require 'paren))\n"
+" (setq baud-rate 2400)\t\t\t; For slow serial connections\n"
+" )\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1530
+#, no-wrap
+msgid ""
+";; TTY type terminal\n"
+"(if (and (not window-system)\n"
+"\t (not (equal system-type 'ms-dos)))\n"
+" (progn\n"
+" (if first-time\n"
+"\t (progn\n"
+"\t (keyboard-translate ?\\C-h ?\\C-?)\n"
+"\t (keyboard-translate ?\\C-? ?\\C-h)))))\n"
+msgstr ""
+";; TTY type terminal\n"
+"(if (and (not window-system)\n"
+"\t (not (equal system-type 'ms-dos)))\n"
+" (progn\n"
+" (if first-time\n"
+"\t (progn\n"
+"\t (keyboard-translate ?\\C-h ?\\C-?)\n"
+"\t (keyboard-translate ?\\C-? ?\\C-h)))))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1536
+#, no-wrap
+msgid ""
+";; Under UNIX\n"
+"(if (not (equal system-type 'ms-dos))\n"
+" (progn\n"
+" (if first-time\n"
+"\t (server-start))))\n"
+msgstr ""
+";; Under UNIX\n"
+"(if (not (equal system-type 'ms-dos))\n"
+" (progn\n"
+" (if first-time\n"
+"\t (server-start))))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1544
+#, no-wrap
+msgid ""
+";; Add any face changes here\n"
+"(add-hook 'term-setup-hook 'my-term-setup-hook)\n"
+"(defun my-term-setup-hook ()\n"
+" (if (eq window-system 'pc)\n"
+" (progn\n"
+";;\t(set-face-background 'default \"red\")\n"
+"\t)))\n"
+msgstr ""
+";; Add any face changes here\n"
+"(add-hook 'term-setup-hook 'my-term-setup-hook)\n"
+"(defun my-term-setup-hook ()\n"
+" (if (eq window-system 'pc)\n"
+" (progn\n"
+";;\t(set-face-background 'default \"red\")\n"
+"\t)))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1550
+#, no-wrap
+msgid ""
+";; Restore the \"desktop\" - do this as late as possible\n"
+"(if first-time\n"
+" (progn\n"
+" (desktop-load-default)\n"
+" (desktop-read)))\n"
+msgstr ""
+";; Restore the \"desktop\" - do this as late as possible\n"
+"(if first-time\n"
+" (progn\n"
+" (desktop-load-default)\n"
+" (desktop-read)))\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1553
+#, no-wrap
+msgid ""
+";; Indicate that this file has been read at least once\n"
+"(setq first-time nil)\n"
+msgstr ""
+";; Indicate that this file has been read at least once\n"
+"(setq first-time nil)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1555
+#, no-wrap
+msgid ";; No need to debug anything now\n"
+msgstr ";; No need to debug anything now\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1557
+#, no-wrap
+msgid "(setq debug-on-error nil)\n"
+msgstr "(setq debug-on-error nil)\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1560
+#, no-wrap
+msgid ""
+";; All done\n"
+"(message \"All done, %s%s\" (user-login-name) \".\")\n"
+msgstr ""
+";; All done\n"
+"(message \"All done, %s%s\" (user-login-name) \".\")\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1563
+#, no-wrap
+msgid "Extending the Range of Languages Emacs Understands"
+msgstr "Расширение списка языков, понимаемых Emacs"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1566
+msgid ""
+"Now, this is all very well if you only want to program in the languages "
+"already catered for in [.filename]#.emacs# (C, C++, Perl, Lisp and Scheme), "
+"but what happens if a new language called \"whizbang\" comes out, full of "
+"exciting features?"
+msgstr ""
+"Вот, это все хорошо, если вы хотите программировать только на языках, уже "
+"предусмотренных в [.filename]#.emacs# (C, C++, Perl, Lisp и Scheme), но что "
+"произойдет, если появится новый язык под названием \"whizbang\", полный "
+"захватывающих возможностей?"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1570
+msgid ""
+"The first thing to do is find out if whizbang comes with any files that tell "
+"Emacs about the language. These usually end in [.filename]#.el#, short for "
+"\"Emacs Lisp\". For example, if whizbang is a FreeBSD port, we can locate "
+"these files by doing"
+msgstr ""
+"Первое, что нужно сделать, — это выяснить, поставляются ли с whizbang какие-"
+"либо файлы, сообщающие Emacs о языке. Обычно они заканчиваются на "
+"[.filename]#.el#, что означает \"Emacs Lisp\". Например, если whizbang "
+"является портом FreeBSD, мы можем найти эти файлы, выполнив"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1574
+#, no-wrap
+msgid "% find /usr/ports/lang/whizbang -name \"*.el\" -print\n"
+msgstr "% find /usr/ports/lang/whizbang -name \"*.el\" -print\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1578
+msgid ""
+"and install them by copying them into the Emacs site Lisp directory. On "
+"FreeBSD, this is [.filename]#/usr/local/share/emacs/site-lisp#."
+msgstr ""
+"и установите их, скопировав в каталог Emacs, где находятся файлы Lisp (site "
+"Lisp). В FreeBSD это [.filename]#/usr/local/share/emacs/site-lisp#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1580
+msgid "So for example, if the output from the find command was"
+msgstr "Вот пример, если вывод команды find был"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1584
+#, no-wrap
+msgid "/usr/ports/lang/whizbang/work/misc/whizbang.el\n"
+msgstr "/usr/ports/lang/whizbang/work/misc/whizbang.el\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1587
+msgid "we would do"
+msgstr "мы бы сделали"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1591
+#, no-wrap
+msgid "# cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp\n"
+msgstr "# cp /usr/ports/lang/whizbang/work/misc/whizbang.el /usr/local/share/emacs/site-lisp\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1596
+msgid ""
+"Next, we need to decide what extension whizbang source files have. Let us "
+"say for the sake of argument that they all end in [.filename]#.wiz#. We "
+"need to add an entry to our [.filename]#.emacs# to make sure Emacs will be "
+"able to use the information in [.filename]#whizbang.el#."
+msgstr ""
+"Далее нам нужно решить, какое расширение имеют исходные файлы whizbang. "
+"Допустим, для примера, что все они заканчиваются на [.filename]#.wiz#. Нам "
+"необходимо добавить запись в наш [.filename]#.emacs#, чтобы убедиться, что "
+"Emacs сможет использовать информацию из [.filename]#whizbang.el#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1598
+msgid ""
+"Find the auto-mode-alist entry in [.filename]#.emacs# and add a line for "
+"whizbang, such as:"
+msgstr ""
+"Найдите запись auto-mode-alist в файле [.filename]#.emacs# и добавьте строку "
+"для whizbang, например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1606
+#, no-wrap
+msgid ""
+"...\n"
+"(\"\\\\.lsp$\" . lisp-mode)\n"
+"(\"\\\\.wiz$\" . whizbang-mode)\n"
+"(\"\\\\.scm$\" . scheme-mode)\n"
+"...\n"
+msgstr ""
+"...\n"
+"(\"\\\\.lsp$\" . lisp-mode)\n"
+"(\"\\\\.wiz$\" . whizbang-mode)\n"
+"(\"\\\\.scm$\" . scheme-mode)\n"
+"...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1609
+msgid ""
+"This means that Emacs will automatically go into `whizbang-mode` when you "
+"edit a file ending in [.filename]#.wiz#."
+msgstr ""
+"Это означает, что Emacs автоматически перейдёт в режим `whizbang-mode` при "
+"редактировании файла с расширением [.filename]#.wiz#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1612
+msgid ""
+"Just below this, you will find the font-lock-auto-mode-list entry. Add "
+"`whizbang-mode` to it like so:"
+msgstr ""
+"Непосредственно ниже вы найдете запись font-lock-auto-mode-list. Добавьте "
+"`whizbang-mode` в нее следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1619
+#, no-wrap
+msgid ""
+";; Auto font lock mode\n"
+"(defvar font-lock-auto-mode-list\n"
+" (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode)\n"
+" \"List of modes to always start in font-lock-mode\")\n"
+msgstr ""
+";; Auto font lock mode\n"
+"(defvar font-lock-auto-mode-list\n"
+" (list 'c-mode 'c++-mode 'c++-c-mode 'emacs-lisp-mode 'whizbang-mode 'lisp-mode 'perl-mode 'scheme-mode)\n"
+" \"List of modes to always start in font-lock-mode\")\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1622
+msgid ""
+"This means that Emacs will always enable `font-lock-mode` (ie syntax "
+"highlighting) when editing a [.filename]#.wiz# file."
+msgstr ""
+"Это означает, что Emacs всегда будет включать `font-lock-mode` (т.е. "
+"подсветку синтаксиса) при редактировании файла [.filename]#.wiz#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1625
+msgid ""
+"And that is all that is needed. If there is anything else you want done "
+"automatically when you open up [.filename]#.wiz#, you can add a `whizbang-"
+"mode hook` (see `my-scheme-mode-hook` for a simple example that adds `auto-"
+"indent`)."
+msgstr ""
+"И это всё, что требуется. Если вам нужно, чтобы что-то ещё выполнялось "
+"автоматически при открытии [.filename]#.wiz#, вы можете добавить `whizbang-"
+"mode hook` (см. `my-scheme-mode-hook` для простого примера, который "
+"добавляет `auto-indent`)."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1627
+#, no-wrap
+msgid "Further Reading"
+msgstr "Для дальнейшего ознакомления"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1630
+msgid ""
+"For information about setting up a development environment for contributing "
+"fixes to FreeBSD itself, please see man:development[7]."
+msgstr ""
+"Для получения информации о настройке среды разработки для внесения "
+"исправлений в саму FreeBSD см. man:development[7]."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1632
+msgid ""
+"Brian Harvey and Matthew Wright _Simply Scheme_ MIT 1994. ISBN 0-262-08226-8"
+msgstr ""
+"Brian Harvey and Matthew Wright _Simply Scheme_ MIT 1994. ISBN 0-262-08226-8"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1633
+msgid "Randall Schwartz _Learning Perl_ O'Reilly 1993 ISBN 1-56592-042-2"
+msgstr "Randall Schwartz _Learning Perl_ O'Reilly 1993 ISBN 1-56592-042-2"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1634
+msgid ""
+"Patrick Henry Winston and Berthold Klaus Paul Horn _Lisp (3rd Edition)_ "
+"Addison-Wesley 1989 ISBN 0-201-08319-1"
+msgstr ""
+"Patrick Henry Winston and Berthold Klaus Paul Horn _Lisp (3rd Edition)_ "
+"Addison-Wesley 1989 ISBN 0-201-08319-1"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1635
+msgid ""
+"Brian W. Kernighan and Rob Pike _The Unix Programming Environment_ Prentice-"
+"Hall 1984 ISBN 0-13-937681-X"
+msgstr ""
+"Brian W. Kernighan and Rob Pike _The Unix Programming Environment_ Prentice-"
+"Hall 1984 ISBN 0-13-937681-X"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1636
+msgid ""
+"Brian W. Kernighan and Dennis M. Ritchie _The C Programming Language (2nd "
+"Edition)_ Prentice-Hall 1988 ISBN 0-13-110362-8"
+msgstr ""
+"Brian W. Kernighan and Dennis M. Ritchie _The C Programming Language (2nd "
+"Edition)_ Prentice-Hall 1988 ISBN 0-13-110362-8"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1637
+msgid ""
+"Bjarne Stroustrup _The C++ Programming Language_ Addison-Wesley 1991 ISBN "
+"0-201-53992-6"
+msgstr ""
+"Bjarne Stroustrup _The C++ Programming Language_ Addison-Wesley 1991 ISBN "
+"0-201-53992-6"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1638
+msgid ""
+"W. Richard Stevens _Advanced Programming in the Unix Environment_ Addison-"
+"Wesley 1992 ISBN 0-201-56317-7"
+msgstr ""
+"W. Richard Stevens _Advanced Programming in the Unix Environment_ Addison-"
+"Wesley 1992 ISBN 0-201-56317-7"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/tools/_index.adoc:1638
+msgid ""
+"W. Richard Stevens _Unix Network Programming_ Prentice-Hall 1990 ISBN "
+"0-13-949876-1"
+msgstr ""
+"W. Richard Stevens _Unix Network Programming_ Prentice-Hall 1990 ISBN "
+"0-13-949876-1"
diff --git a/documentation/content/ru/books/developers-handbook/x86/_index.adoc b/documentation/content/ru/books/developers-handbook/x86/_index.adoc
new file mode 100644
index 0000000000..c44f67bb5c
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/x86/_index.adoc
@@ -0,0 +1,3864 @@
+---
+authors:
+description: 'Программирование на ассемблере x86'
+next: books/developers-handbook/partv
+params:
+ path: /books/developers-handbook/x86/
+prev: books/developers-handbook/partiv
+showBookMenu: true
+tags: ["x86", "guide"]
+title: 'Глава 11. Программирование на языке ассемблера для x86'
+weight: 15
+---
+
+[[x86]]
+= Программирование на ассемблере x86
+:doctype: book
+:toc: macro
+:toclevels: 1
+:icons: font
+:sectnums:
+:sectnumlevels: 6
+:sectnumoffset: A
+:partnums:
+:source-highlighter: rouge
+:experimental:
+:images-path: books/developers-handbook/
+
+ifdef::env-beastie[]
+ifdef::backend-html5[]
+:imagesdir: ../../../../images/{images-path}
+endif::[]
+ifndef::book[]
+include::shared/authors.adoc[]
+include::shared/mirrors.adoc[]
+include::shared/releases.adoc[]
+include::shared/attributes/attributes-{{% lang %}}.adoc[]
+include::shared/{{% lang %}}/teams.adoc[]
+include::shared/{{% lang %}}/mailing-lists.adoc[]
+include::shared/{{% lang %}}/urls.adoc[]
+toc::[]
+endif::[]
+ifdef::backend-pdf,backend-epub3[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+endif::[]
+
+ifndef::env-beastie[]
+toc::[]
+include::../../../../../shared/asciidoctor.adoc[]
+endif::[]
+
+_Эта глава была написана {stanislav}._
+
+[[x86-intro]]
+== Обзор
+
+Программирование на ассемблере в UNIX(R) крайне плохо документировано. Обычно предполагается, что никто не захочет его использовать, поскольку различные системы UNIX(R) работают на разных микропроцессорах, и поэтому всё должно быть написано на C для обеспечения переносимости.
+
+В действительности переносимость программ на C — это скорее миф. Даже программы на C требуют изменений при переносе с одной UNIX(R)-системы на другую, независимо от процессора, на котором они работают. Обычно такая программа содержит множество условных операторов, зависящих от системы, для которой она компилируется.
+
+Даже если мы считаем, что всё программное обеспечение UNIX(R) должно быть написано на C или другом языке высокого уровня, нам всё равно нужны программисты на ассемблере: кто же ещё напишет часть библиотеки C, которая обращается к ядру?
+
+В этой главе я попытаюсь показать вам, как можно использовать язык ассемблера для написания программ под UNIX(R), в частности под FreeBSD.
+
+В этой главе не объясняются основы языка ассемблера. Существует достаточно ресурсов на эту тему (например, полный онлайн-курс по языку ассемблера можно найти в http://webster.cs.ucr.edu/[Искусстве языка ассемблера] Рэндалла Хайда; если вы предпочитаете печатные книги, обратите внимание на «Язык ассемблера шаг за шагом» Джеффа Дантемана (ISBN: 0471375233)). Однако после прочтения этой главы любой программист на языке ассемблера сможет писать программы для FreeBSD быстро и эффективно.
+
+Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved.
+
+[[x86-the-tools]]
+== Инструменты
+
+[[x86-the-assembler]]
+=== Ассемблер
+
+Важнейшим инструментом для программирования на языке ассемблера является ассемблер — программа, преобразующая код на языке ассемблера в машинный код.
+
+Три очень разных ассемблера доступны для FreeBSD. И man:llvm-as[1] (включён в package:devel/llvm[]), и man:as[1] (включён в package:devel/binutils[]) используют традиционный синтаксис ассемблера UNIX(R).
+
+С другой стороны, man:nasm[1] (устанавливаемый через package:devel/nasm[]) использует синтаксис Intel. Его основное преимущество в том, что он может ассемблировать код для многих операционных систем.
+
+В этой главе используется синтаксис nasm, потому что большинство программистов на ассемблере, приходящих в FreeBSD из других операционных систем, найдут его более понятным. Кроме того, если честно, это то, к чему я привык.
+
+[[x86-the-linker]]
+=== Компоновщик
+
+Результат работы ассемблера, как и любого компилятора, необходимо связать, чтобы получить исполняемый файл.
+
+Стандартный компоновщик man:ld[1] поставляется с FreeBSD. Он работает с кодом, собранным любым из ассемблеров.
+
+[[x86-system-calls]]
+== Системные вызовы
+
+[[x86-default-calling-convention]]
+=== Стандартное соглашение о вызовах
+
+По умолчанию ядро FreeBSD использует соглашение о вызовах C. Кроме того, хотя доступ к ядру осуществляется с помощью `int 80h`, предполагается, что программа вызовет функцию, которая выполняет `int 80h`, а не будет выполнять `int 80h` напрямую.
+
+Эта традиция очень удобна и значительно превосходит соглашение Microsoft(R), используемое в MS-DOS(R). Почему? Потому что соглашение UNIX(R) позволяет любой программе, написанной на любом языке, обращаться к ядру.
+
+Программа на ассемблере также может это сделать. Например, мы могли бы открыть файл:
+
+[.programlisting]
+....
+kernel:
+ int 80h ; Call kernel
+ ret
+
+open:
+ push dword mode
+ push dword flags
+ push dword path
+ mov eax, 5
+ call kernel
+ add esp, byte 12
+ ret
+....
+
+Это очень понятный и переносимый способ написания кода. Если вам нужно перенести код на UNIX(R)-систему, которая использует другое прерывание или другой способ передачи параметров, все, что вам нужно изменить, это процедуру kernel.
+
+Но программисты на ассемблере любят экономить такты. Приведённый выше пример требует комбинации `call/ret`. Мы можем исключить её, сделав ``push`` дополнительного двойного слова:
+
+[.programlisting]
+....
+open:
+ push dword mode
+ push dword flags
+ push dword path
+ mov eax, 5
+ push eax ; Or any other dword
+ int 80h
+ add esp, byte 16
+....
+
+Помещённое в `EAX` значение `5` идентифицирует функцию ядра, в данном случае `open`.
+
+[[x86-alternate-calling-convention]]
+=== Альтернативное соглашение о вызовах
+
+FreeBSD — это чрезвычайно гибкая система. Она предлагает другие способы вызова ядра. Однако для работы необходимо, чтобы в системе была установлена эмуляция Linux.
+
+Linux — это система, подобная UNIX(R). Однако ее ядро использует то же соглашение о системных вызовов для передачи параметров в регистрах, что и MS-DOS(R). Как и в соглашении UNIX(R), номер функции помещается в `EAX`. Однако параметры передаются не в стеке, а в регистрах `EBX, ECX, EDX, ESI, EDI, EBP`:
+
+[.programlisting]
+....
+open:
+ mov eax, 5
+ mov ebx, path
+ mov ecx, flags
+ mov edx, mode
+ int 80h
+....
+
+Этот подход имеет значительный недостаток по сравнению с UNIX(R), по крайней мере, в контексте программирования на ассемблере: каждый раз при вызове ядра необходимо сохранять регистры с помощью `push`, а затем восстанавливать их с помощью `pop`. Это делает ваш код более громоздким и медленным. Тем не менее, FreeBSD предоставляет вам выбор.
+
+Если вы решите использовать соглашение Linux, вы должны сообщить об этом системе. После того как ваша программа будет ассемблирована и слинкована, вам нужно пометить исполняемый файл:
+
+[source, shell]
+....
+% brandelf -t Linux filename
+....
+
+[[x86-use-geneva]]
+=== Какое соглашение следует использовать?
+
+Если вы разрабатываете код специально для FreeBSD, всегда следует использовать соглашение UNIX(R): это быстрее, вы можете хранить глобальные переменные в регистрах, вам не нужно маркировать исполняемый файл, и вы не требуете установки пакета эмуляции Linux на целевой системе.
+
+Хотя вы можете хотеть создать переносимый код, который также работает на Linux, вам, вероятно, по-прежнему будет нужен максимально эффективный код для пользователей FreeBSD. Я покажу вам, как этого добиться, после того как объясню основы.
+
+[[x86-call-numbers]]
+=== Номера вызовов
+
+Чтобы сообщить ядру, какую системную службу вы вызываете, поместите её номер в `EAX`. Разумеется, вам необходимо знать, что это за номер.
+
+[[x86-the-syscalls-file]]
+==== Файл [.filename]#syscalls#
+
+Номера перечислены в [.filename]#syscalls#. Команда `locate syscalls` находит этот файл в нескольких различных форматах, все они создаются автоматически из [.filename]#syscalls.master#.
+
+Основной файл для стандартного соглашения о вызовах UNIX(R) можно найти в [.filename]#/usr/src/sys/kern/syscalls.master#. Если вам необходимо использовать другое соглашение, реализованное в режиме эмуляции Linux, обратитесь к [.filename]#/usr/src/sys/i386/linux/syscalls.master#.
+
+[NOTE]
+====
+Не только FreeBSD и Linux используют разные соглашения о вызовах, но иногда они используют разные номера для одних и тех же функций.
+====
+
+[.filename]#syscalls.master# описывает, как должен быть выполнен вызов:
+
+[.programlisting]
+....
+0 STD NOHIDE { int nosys(void); } syscall nosys_args int
+1 STD NOHIDE { void exit(int rval); } exit rexit_args void
+2 STD POSIX { int fork(void); }
+3 STD POSIX { ssize_t read(int fd, void *buf, size_t nbyte); }
+4 STD POSIX { ssize_t write(int fd, const void *buf, size_t nbyte); }
+5 STD POSIX { int open(char *path, int flags, int mode); }
+6 STD POSIX { int close(int fd); }
+etc...
+....
+
+Это крайний левый столбец, который указывает число, которое нужно поместить в `EAX`.
+
+Самый правый столбец указывает, какие параметры нужно `втолкнуть` в стек командой push. Они `вталкиваются` _справа налево_.
+
+Например, чтобы `открыть` файл, нам сначала нужно сделать `push` для `mode`, затем `flags`, а затем адрес, по которому хранится `path`.
+
+[[x86-return-values]]
+== Возвращаемые значения
+
+От системных вызовов не было бы никакой пользы, если бы они не возвращали какое-либо значение: дескриптор открытого файла, количество байтов, прочитанных в буфер, системное время и т.д.
+
+Кроме того, система должна уведомлять нас, если возникает ошибка: файл не существует, системные ресурсы исчерпаны, передан недопустимый параметр и т. д.
+
+[[x86-man-pages]]
+=== Страницы справочника
+
+Традиционным источником информации о различных системных вызовах в UNIX(R)-системах являются страницы Справочника. В FreeBSD системные вызовы описаны в разделе 2, иногда в разделе 3.
+
+Например, man:open[2] говорит:
+
+[.blockquote]
+В случае успеха `open()` возвращает неотрицательное целое число, называемое файловым дескриптором. В случае ошибки возвращается `-1`, а переменной `errno` присваивается код ошибки.
+
+Программист на ассемблере, впервые столкнувшийся с UNIX(R) и FreeBSD, сразу же задастся вопросом: где находится `errno` и как к ней обратиться?
+
+[NOTE]
+====
+Информация, представленная в руководствах, применима к программам на языке C. Программистам на языке ассемблера требуется дополнительная информация.
+====
+
+[[x86-where-return-values]]
+=== Где возвращаемые значения?
+
+К сожалению, это зависит от ситуации... Для большинства системных вызовов возвращаемое значение находится в `EAX`, но не для всех. Хорошее правило при первой работе с системным вызовом — искать возвращаемое значение в `EAX`. Если его там нет, потребуется дополнительное исследование.
+
+[NOTE]
+====
+Я знаю о одном системном вызове, который возвращает значение в `EDX`: `SYS_fork`. Все остальные, с которыми я работал, используют `EAX`. Но я еще не работал со всеми из них.
+====
+
+[TIP]
+====
+Если вы не можете найти ответ здесь или где-либо ещё, изучите исходный код libc и посмотрите, как он взаимодействует с ядром.
+====
+
+[[x86-where-errno]]
+=== Где находится `errno`?
+
+Фактически, нигде...
+
+`errno` является частью языка C, а не ядра UNIX(R). При прямом доступе к сервисам ядра код ошибки возвращается в регистре `EAX` — том же регистре, в котором обычно оказывается корректное возвращаемое значение.
+
+Это совершенно логично. Если нет ошибки, то нет и кода ошибки. Если есть ошибка, то нет возвращаемого значения. Один регистр может содержать либо то, либо другое.
+
+[[x86-how-to-know-error]]
+=== Определение возникновения ошибки
+
+При использовании стандартного соглашения о вызовах FreeBSD флаг `carry flag` сбрасывается при успехе и устанавливается при неудаче.
+
+При использовании режима эмуляции Linux знаковое значение в `EAX` неотрицательно в случае успеха и содержит возвращаемое значение. В случае ошибки значение отрицательное, т.е. `-errno`.
+
+[[x86-portable-code]]
+== Создание переносимого кода
+
+Портативность обычно не является сильной стороной языка ассемблера. Тем не менее, написание программ на ассемблере для разных платформ возможно, особенно с использованием nasm. Я создавал библиотеки на ассемблере, которые можно было собрать для таких разных операционных систем, как Windows(R) и FreeBSD.
+
+Это становится еще более возможным, когда вы хотите, чтобы ваш код работал на двух платформах, которые, хотя и различны, основаны на схожих архитектурах.
+
+Например, FreeBSD — это UNIX(R), а Linux — UNIX(R)-подобная система. Я упомянул лишь три различия между ними (с точки зрения программиста на ассемблере): соглашение о вызовах, номера функций и способ возврата значений.
+
+[[x86-deal-with-function-numbers]]
+=== Работа с номерами функций
+
+Во многих случаях номера функций совпадают. Однако, даже если это не так, проблему легко решить: вместо использования чисел в коде применяйте константы, объявленные по-разному в зависимости от целевой архитектуры:
+
+[.programlisting]
+....
+%ifdef LINUX
+%define SYS_execve 11
+%else
+%define SYS_execve 59
+%endif
+....
+
+[[x86-deal-with-geneva]]
+=== Работа с соглашениями
+
+Оба, соглашение о вызовах и возвращаемое значение (проблема `errno`) могут быть решены с помощью макросов:
+
+[.programlisting]
+....
+%ifdef LINUX
+
+%macro system 0
+ call kernel
+%endmacro
+
+align 4
+kernel:
+ push ebx
+ push ecx
+ push edx
+ push esi
+ push edi
+ push ebp
+
+ mov ebx, [esp+32]
+ mov ecx, [esp+36]
+ mov edx, [esp+40]
+ mov esi, [esp+44]
+ mov ebp, [esp+48]
+ int 80h
+
+ pop ebp
+ pop edi
+ pop esi
+ pop edx
+ pop ecx
+ pop ebx
+
+ or eax, eax
+ js .errno
+ clc
+ ret
+
+.errno:
+ neg eax
+ stc
+ ret
+
+%else
+
+%macro system 0
+ int 80h
+%endmacro
+
+%endif
+....
+
+[[x86-deal-with-other-portability]]
+=== Устранение прочих проблем с переносимостью
+
+Приведённые выше решения могут помочь в большинстве случаев написания кода, переносимого между FreeBSD и Linux. Тем не менее, с некоторыми сервисами ядра различия более глубокие.
+
+В таком случае необходимо написать два разных обработчика для этих конкретных системных вызовов и использовать условную компиляцию. К счастью, большая часть вашего кода выполняет действия, отличные от вызовов ядра, поэтому обычно потребуется лишь несколько таких условных секций в коде.
+
+[[x86-portable-library]]
+=== Использование библиотеки
+
+Вы можете полностью избежать проблем с переносимостью в основном коде, написав библиотеку системных вызовов. Создайте отдельную библиотеку для FreeBSD, другую для Linux и ещё другие библиотеки для дополнительных операционных систем.
+
+В вашей библиотеке напишите отдельную функцию (или процедуру, если вы предпочитаете традиционную терминологию ассемблера) для каждого системного вызова. Используйте соглашение о вызовах C для передачи параметров. Однако по-прежнему передавайте номер вызова через `EAX`. В таком случае ваша библиотека FreeBSD может быть очень простой, так как множество внешне различных функций могут быть просто метками одного и того же кода:
+
+[.programlisting]
+....
+sys.open:
+sys.close:
+[etc...]
+ int 80h
+ ret
+....
+
+Ваша библиотека Linux потребует больше различных функций. Но даже здесь вы можете группировать системные вызовы, используя одинаковое количество параметров:
+
+[.programlisting]
+....
+sys.exit:
+sys.close:
+[etc... one-parameter functions]
+ push ebx
+ mov ebx, [esp+12]
+ int 80h
+ pop ebx
+ jmp sys.return
+
+...
+
+sys.return:
+ or eax, eax
+ js sys.err
+ clc
+ ret
+
+sys.err:
+ neg eax
+ stc
+ ret
+....
+
+Подход с использованием библиотек может показаться неудобным на первый взгляд, так как требует создания отдельного файла, от которого зависит ваш код. Однако у него есть множество преимуществ: во-первых, вам нужно написать его лишь один раз, и затем вы можете использовать его во всех своих программах. Вы даже можете позволить другим программистам на ассемблере использовать его или, возможно, воспользоваться библиотекой, написанной кем-то другим. Но, пожалуй, самое большое преимущество библиотеки заключается в том, что ваш код может быть перенесён на другие системы, даже другими программистами, просто путём написания новой библиотеки без каких-либо изменений в вашем коде.
+
+Если вам не нравится идея использования библиотеки, вы можете хотя бы разместить все системные вызовы в отдельном файле на ассемблере и скомпоновать его с основной программой. Здесь, опять же, все, что нужно сделать переносчикам, — это создать новый объектный файл для компоновки с основной программой.
+
+[[x86-portable-include]]
+=== Использование включаемого файла
+
+Если вы выпускаете своё программное обеспечение в виде исходного кода (или вместе с ним), вы можете использовать макросы и размещать их в отдельном файле, который включается в ваш код.
+
+Портеры вашего программного обеспечения просто напишут новый include-файл. Никакая библиотека или внешний объектный файл не требуются, и ваш код остается переносимым без необходимости редактирования.
+
+[NOTE]
+====
+Это подход, который мы будем использовать на протяжении всей главы. Мы назовем наш включаемый файл [.filename]#system.inc# и будем добавлять в него новые системные вызовы по мере их рассмотрения.
+====
+
+Мы можем начать наш [.filename]#system.inc# с объявления стандартных файловых дескрипторов:
+
+[.programlisting]
+....
+%define stdin 0
+%define stdout 1
+%define stderr 2
+....
+
+Далее мы создаем символическое имя для каждого системного вызова:
+
+[.programlisting]
+....
+%define SYS_nosys 0
+%define SYS_exit 1
+%define SYS_fork 2
+%define SYS_read 3
+%define SYS_write 4
+; [etc...]
+....
+
+Добавляем короткую, неглобальную процедуру с длинным именем, чтобы случайно не использовать это имя в нашем коде:
+
+[.programlisting]
+....
+section .text
+align 4
+access.the.bsd.kernel:
+ int 80h
+ ret
+....
+
+Мы создаем макрос, который принимает один аргумент — номер системного вызова:
+
+[.programlisting]
+....
+%macro system 1
+ mov eax, %1
+ call access.the.bsd.kernel
+%endmacro
+....
+
+Наконец, мы создаем макросы для каждого системного вызова. Эти макросы не принимают аргументов.
+
+[.programlisting]
+....
+%macro sys.exit 0
+ system SYS_exit
+%endmacro
+
+%macro sys.fork 0
+ system SYS_fork
+%endmacro
+
+%macro sys.read 0
+ system SYS_read
+%endmacro
+
+%macro sys.write 0
+ system SYS_write
+%endmacro
+
+; [etc...]
+....
+
+Продолжайте, введите это в ваш редактор и сохраните как [.filename]#system.inc#. Мы добавим больше по мере обсуждения дополнительных системных вызовов.
+
+[[x86-first-program]]
+== Наша первая программа
+
+Мы готовы к нашей первой обязательной программе — Hello, World!
+
+[.programlisting]
+....
+ %include 'system.inc'
+
+ section .data
+ hello db 'Hello, World!', 0Ah
+ hbytes equ $-hello
+
+ section .text
+ global _start
+_start:
+ push dword hbytes
+ push dword hello
+ push dword stdout
+ sys.write
+
+ push dword 0
+ sys.exit
+....
+
+Вот что он делает: Строка 1 включает определения, макросы и код из файла [.filename]#system.inc#.
+
+Строки 3-5 содержат данные: строка 3 начинает раздел/сегмент данных. Строка 4 содержит строку "Hello, World!", за которой следует новая строка (`0Ah`). Строка 5 создает константу, содержащую длину строки из строки 4 в байтах.
+
+Строки 7-16 содержат код. Обратите внимание, что FreeBSD использует формат файлов _elf_ для исполняемых файлов, который требует, чтобы каждая программа запускается с адреса, помеченного как `_start` (или, точнее, компоновщик ожидает этого). Эта метка должна быть глобальной.
+
+Строки 10-13 указывают системе записать `hbytes` байтов строки `hello` в `stdout`.
+
+Строки 15-16 указывают системе завершить программу с возвращаемым значением `0`. Системный вызов `SYS_exit` никогда не возвращает управление, поэтому код завершается в этой точке.
+
+[NOTE]
+====
+Если вы перешли на UNIX(R) с опытом программирования на ассемблере для MS-DOS(R), вы, возможно, привыкли писать напрямую в видеопамять. В FreeBSD или любой другой разновидности UNIX(R) вам не придётся об этом беспокоиться. С вашей точки зрения, вы записываете данные в файл под названием [.filename]#stdout#. Это может быть экран, терминал telnet, обычный файл или даже входные данные другой программы. Определять, что именно это будет, — задача системы.
+====
+
+[[x86-assemble-1]]
+=== Ассемблирование кода
+
+Наберите код в редакторе и сохраните его в файле с именем [.filename]#hello.asm#. Для сборки вам понадобится nasm.
+
+[[x86-get-nasm]]
+==== Установка nasm
+
+Если у вас нет nasm, введите:
+
+[source, shell]
+....
+% su
+Password:your root password
+# cd /usr/ports/devel/nasm
+# make install
+# exit
+%
+....
+
+Вы можете ввести `make install clean` вместо просто `make install`, если не хотите сохранять исходный код nasm.
+
+В любом случае FreeBSD автоматически загрузит nasm из интернета, скомпилирует его и установит в вашу систему.
+
+[NOTE]
+====
+Если ваша система не FreeBSD, вам нужно получить nasm с его https://sourceforge.net/projects/nasm[домашней страницы]. Вы по-прежнему можете использовать его для ассемблирования кода FreeBSD.
+====
+
+Теперь вы можете собрать, скомпоновать и запустить код:
+
+[source, shell]
+....
+% nasm -f elf hello.asm
+% ld -s -o hello hello.o
+% ./hello
+Hello, World!
+%
+....
+
+[[x86-unix-filters]]
+== Написание фильтров UNIX(R)
+
+Распространённым типом приложений в UNIX(R) являются фильтры — программы, которые читают данные из [.filename]#stdin#, обрабатывают их определённым образом, а затем записывают результат в [.filename]#stdout#.
+
+В этой главе мы разработаем простой фильтр и научимся читать из [.filename]#stdin# и писать в [.filename]#stdout#. Этот фильтр будет преобразовывать каждый байт входных данных в шестнадцатеричное число, за которым следует пробел.
+
+[.programlisting]
+....
+%include 'system.inc'
+
+section .data
+hex db '0123456789ABCDEF'
+buffer db 0, 0, ' '
+
+section .text
+global _start
+_start:
+ ; read a byte from stdin
+ push dword 1
+ push dword buffer
+ push dword stdin
+ sys.read
+ add esp, byte 12
+ or eax, eax
+ je .done
+
+ ; convert it to hex
+ movzx eax, byte [buffer]
+ mov edx, eax
+ shr dl, 4
+ mov dl, [hex+edx]
+ mov [buffer], dl
+ and al, 0Fh
+ mov al, [hex+eax]
+ mov [buffer+1], al
+
+ ; print it
+ push dword 3
+ push dword buffer
+ push dword stdout
+ sys.write
+ add esp, byte 12
+ jmp short _start
+
+.done:
+ push dword 0
+ sys.exit
+....
+
+В разделе данных мы создаем массив с именем `hex`. Он содержит 16 шестнадцатеричных цифр в порядке возрастания. За массивом следует буфер, который мы будем использовать как для ввода, так и для вывода. Первые два байта буфера изначально установлены в `0`. Именно сюда мы будем записывать две шестнадцатеричные цифры (первый байт также является местом, откуда мы будем считывать ввод). Третий байт — это пробел.
+
+Фрагмент кода состоит из четырех частей: чтение байта, преобразование его в шестнадцатеричное число, запись результата и завершение программы.
+
+Для чтения байта мы просим систему прочитать один байт из [.filename]#stdin# и сохранить его в первом байте `buffer`. Система возвращает количество прочитанных байтов в `EAX`. Это значение будет `1`, пока поступают данные, или `0`, если больше нет доступных входных данных. Поэтому мы проверяем значение `EAX`. Если оно равно `0`, мы переходим к метке `.done`, в противном случае продолжаем выполнение.
+
+[NOTE]
+====
+Для простоты мы пока игнорируем возможность возникновения ошибки.
+====
+
+Шестнадцатеричное преобразование считывает байт из `buffer` в `EAX`, а точнее только в `AL`, обнуляя остальные биты `EAX`. Мы также копируем байт в `EDX`, потому что нам нужно преобразовать верхние четыре бита (ниббл) отдельно от нижних четырех битов. Результат сохраняется в первых двух байтах буфера.
+
+Далее мы просим систему записать три байта буфера, то есть две шестнадцатеричные цифры и пробел, в [.filename]#stdout#. Затем мы возвращаемся к началу программы и обрабатываем следующий байт.
+
+Когда ввод больше не остаётся, мы просим систему завершить нашу программу, возвращая ноль, что традиционно означает успешное выполнение программы.
+
+Продолжайте и сохраните код в файле с именем [.filename]#hex.asm#, затем введите следующее (символ `^D` означает, что нужно нажать клавишу управления и, удерживая её, ввести `D`):
+
+[source, shell]
+....
+% nasm -f elf hex.asm
+% ld -s -o hex hex.o
+% ./hex
+Hello, World!
+48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come!
+48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D %
+....
+
+[NOTE]
+====
+Если вы переходите на UNIX(R) с MS-DOS(R), вам может быть интересно, почему каждая строка заканчивается на `0A` вместо `0D 0A`. Это связано с тем, что UNIX(R) не использует соглашение cr/lf, а использует соглашение "новая строка", которое в шестнадцатеричном виде представлено как `0A`.
+====
+
+Можем ли мы это улучшить? Что ж, во-первых, это немного запутанно, потому что после преобразования строки текста наш ввод больше не начинается с начала строки. Мы можем изменить это, чтобы после каждого `0A` выводилась новая строка вместо пробела:
+
+[.programlisting]
+....
+%include 'system.inc'
+
+section .data
+hex db '0123456789ABCDEF'
+buffer db 0, 0, ' '
+
+section .text
+global _start
+_start:
+ mov cl, ' '
+
+.loop:
+ ; read a byte from stdin
+ push dword 1
+ push dword buffer
+ push dword stdin
+ sys.read
+ add esp, byte 12
+ or eax, eax
+ je .done
+
+ ; convert it to hex
+ movzx eax, byte [buffer]
+ mov [buffer+2], cl
+ cmp al, 0Ah
+ jne .hex
+ mov [buffer+2], al
+
+.hex:
+ mov edx, eax
+ shr dl, 4
+ mov dl, [hex+edx]
+ mov [buffer], dl
+ and al, 0Fh
+ mov al, [hex+eax]
+ mov [buffer+1], al
+
+ ; print it
+ push dword 3
+ push dword buffer
+ push dword stdout
+ sys.write
+ add esp, byte 12
+ jmp short .loop
+
+.done:
+ push dword 0
+ sys.exit
+....
+
+Мы сохранили пробел в регистре `CL`. Это безопасно, потому что, в отличие от Microsoft(R) Windows(R), вызовы системы UNIX(R) не изменяют значение регистров, которые не используются для возврата значения.
+
+Это означает, что нам нужно установить `CL` только один раз. Поэтому мы добавили новую метку `.loop` и переходим к ней для следующего байта вместо перехода к `_start`. Мы также добавили метку `.hex`, чтобы третий байт `buffer` мог быть либо пробелом, либо новой строкой.
+
+После внесения изменений в файл [.filename]#hex.asm# введите:
+
+[source, shell]
+....
+% nasm -f elf hex.asm
+% ld -s -o hex hex.o
+% ./hex
+Hello, World!
+48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
+Here I come!
+48 65 72 65 20 49 20 63 6F 6D 65 21 0A
+^D %
+....
+
+Выглядит лучше. Но этот код довольно неэффективен! Мы выполняем системный вызов для каждого отдельного байта дважды (один раз для чтения и ещё один для записи вывода).
+
+[[x86-buffered-io]]
+== Буферизованный ввод и вывод
+
+Мы можем повысить эффективность нашего кода, буферизуя ввод и вывод. Мы создаём входной буфер и читаем сразу целую последовательность байтов. Затем мы извлекаем их по одному из буфера.
+
+Мы также создаем выходной буфер. Мы сохраняем наш вывод в нем, пока он не заполнится. В этот момент мы просим ядро записать содержимое буфера в [.filename]#stdout#.
+
+Программа завершается, когда больше нет входных данных. Но нам всё ещё нужно попросить ядро записать содержимое нашего выходного буфера в [.filename]#stdout# в последний раз, иначе часть нашего вывода попадёт в буфер, но так и не будет отправлена. Не забудьте об этом, иначе будете недоумевать, куда пропала часть вывода.
+
+[.programlisting]
+....
+%include 'system.inc'
+
+%define BUFSIZE 2048
+
+section .data
+hex db '0123456789ABCDEF'
+
+section .bss
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+
+section .text
+global _start
+_start:
+ sub eax, eax
+ sub ebx, ebx
+ sub ecx, ecx
+ mov edi, obuffer
+
+.loop:
+ ; read a byte from stdin
+ call getchar
+
+ ; convert it to hex
+ mov dl, al
+ shr al, 4
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, dl
+ and al, 0Fh
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, ' '
+ cmp dl, 0Ah
+ jne .put
+ mov al, dl
+
+.put:
+ call putchar
+ jmp short .loop
+
+align 4
+getchar:
+ or ebx, ebx
+ jne .fetch
+
+ call read
+
+.fetch:
+ lodsb
+ dec ebx
+ ret
+
+read:
+ push dword BUFSIZE
+ mov esi, ibuffer
+ push esi
+ push dword stdin
+ sys.read
+ add esp, byte 12
+ mov ebx, eax
+ or eax, eax
+ je .done
+ sub eax, eax
+ ret
+
+align 4
+.done:
+ call write ; flush output buffer
+ push dword 0
+ sys.exit
+
+align 4
+putchar:
+ stosb
+ inc ecx
+ cmp ecx, BUFSIZE
+ je write
+ ret
+
+align 4
+write:
+ sub edi, ecx ; start of buffer
+ push ecx
+ push edi
+ push dword stdout
+ sys.write
+ add esp, byte 12
+ sub eax, eax
+ sub ecx, ecx ; buffer is empty now
+ ret
+....
+
+Теперь у нас есть третий раздел в исходном коде с именем `.bss`. Этот раздел не включается в исполняемый файл и, следовательно, не может быть инициализирован. Мы используем `resb` вместо `db`. Это просто резервирует запрошенный размер неинициализированной памяти для нашего использования.
+
+Мы используем тот факт, что система не изменяет регистры: мы используем регистры для того, что в противном случае пришлось бы хранить в глобальных переменных в секции `.data`. Именно поэтому соглашение UNIX(R) о передаче параметров системных вызовов через стек превосходит соглашение Microsoft о передаче их в регистрах: мы можем оставить регистры для собственного использования.
+
+Мы используем `EDI` и `ESI` как указатели на следующий байт для чтения или записи. Мы используем `EBX` и `ECX` для отслеживания количества байтов в двух буферах, чтобы знать, когда нужно вывести данные в систему или считать новые данные из системы.
+
+Давайте посмотрим, как это работает сейчас:
+
+[source, shell]
+....
+% nasm -f elf hex.asm
+% ld -s -o hex hex.o
+% ./hex
+Hello, World!
+Here I come!
+48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
+48 65 72 65 20 49 20 63 6F 6D 65 21 0A
+^D %
+....
+
+Не то, что вы ожидали? Программа не выводила результат, пока мы не нажали `^D`. Это легко исправить, добавив три строки кода для вывода результата каждый раз, когда мы преобразуем новую строку в `0A`. Я пометил эти три строки символом > (не копируйте > в ваш [.filename]#hex.asm#).
+
+[.programlisting]
+....
+%include 'system.inc'
+
+%define BUFSIZE 2048
+
+section .data
+hex db '0123456789ABCDEF'
+
+section .bss
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+
+section .text
+global _start
+_start:
+ sub eax, eax
+ sub ebx, ebx
+ sub ecx, ecx
+ mov edi, obuffer
+
+.loop:
+ ; read a byte from stdin
+ call getchar
+
+ ; convert it to hex
+ mov dl, al
+ shr al, 4
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, dl
+ and al, 0Fh
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, ' '
+ cmp dl, 0Ah
+ jne .put
+ mov al, dl
+
+.put:
+ call putchar
+> cmp al, 0Ah
+> jne .loop
+> call write
+ jmp short .loop
+
+align 4
+getchar:
+ or ebx, ebx
+ jne .fetch
+
+ call read
+
+.fetch:
+ lodsb
+ dec ebx
+ ret
+
+read:
+ push dword BUFSIZE
+ mov esi, ibuffer
+ push esi
+ push dword stdin
+ sys.read
+ add esp, byte 12
+ mov ebx, eax
+ or eax, eax
+ je .done
+ sub eax, eax
+ ret
+
+align 4
+.done:
+ call write ; flush output buffer
+ push dword 0
+ sys.exit
+
+align 4
+putchar:
+ stosb
+ inc ecx
+ cmp ecx, BUFSIZE
+ je write
+ ret
+
+align 4
+write:
+ sub edi, ecx ; start of buffer
+ push ecx
+ push edi
+ push dword stdout
+ sys.write
+ add esp, byte 12
+ sub eax, eax
+ sub ecx, ecx ; buffer is empty now
+ ret
+....
+
+Теперь давайте посмотрим, как это работает:
+
+[source, shell]
+....
+% nasm -f elf hex.asm
+% ld -s -o hex hex.o
+% ./hex
+Hello, World!
+48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A
+Here I come!
+48 65 72 65 20 49 20 63 6F 6D 65 21 0A
+^D %
+....
+
+Неплохо для исполняемого файла размером 644 байта, не так ли!
+
+[NOTE]
+====
+Такой подход к буферизированному вводу/выводу всё ещё содержит скрытую опасность. Я расскажу об этом и исправлю её позже, когда речь пойдёт о crossref:x86[x86-buffered-dark-side,тёмной стороне буферизации].
+====
+
+[[x86-ungetc]]
+=== Как отменить чтение символа
+
+[WARNING]
+====
+Это может быть несколько сложной темой, в основном представляющей интерес для программистов, знакомых с теорией компиляторов. Если хотите, вы можете crossref:x86[x86-command-line, перейти к следующему разделу], и, возможно, прочитаете это позже.
+====
+
+Хотя наш пример программы не требует этого, более сложные фильтры часто нуждаются в предварительном просмотре. Другими словами, им может потребоваться узнать, какой следующий символ (или даже несколько символов). Если следующий символ имеет определённое значение, он является частью текущего обрабатываемого токена. В противном случае — нет.
+
+Например, вы можете анализировать входной поток на наличие текстовой строки (например, при реализации компилятора языка): если символ следует за другим символом или, возможно, цифрой, он является частью обрабатываемой лексемы. Если за ним следует пробел или другое значение, то он не является частью текущей лексемы.
+
+Это представляет интересную проблему: как вернуть следующий символ обратно во входной поток, чтобы его можно было прочитать позже?
+
+Одно из возможных решений — сохранить его в символьной переменной, а затем установить флаг. Мы можем изменить `getchar`, чтобы он проверял флаг, и если он установлен, извлекал байт из этой переменной вместо буфера ввода, а затем сбрасывал флаг. Но, конечно, это замедляет работу.
+
+В языке C есть функция `ungetc()`, как раз для этой цели. Есть ли быстрый способ реализовать её в нашем коде? Я хочу, чтобы вы пролистали назад и взглянули на процедуру `getchar`, и попробовали найти красивое и быстрое решение, прежде чем читать следующий абзац. Затем вернитесь сюда и посмотрите моё собственное решение.
+
+Ключом к возвращению символа обратно в поток является то, как мы получаем символы изначально:
+
+Сначала проверяем, пуст ли буфер, проверяя значение `EBX`. Если оно равно нулю, вызываем процедуру `read`.
+
+Если у нас есть доступный символ, мы используем `lodsb`, затем уменьшаем значение `EBX`. Инструкция `lodsb` фактически идентична:
+
+[.programlisting]
+....
+mov al, [esi]
+ inc esi
+....
+
+Байт, который мы извлекли, остается в буфере до следующего вызова `read`. Мы не знаем, когда это произойдет, но знаем, что этого не случится до следующего вызова `getchar`. Следовательно, чтобы "вернуть" последний прочитанный байт обратно в поток, нам достаточно уменьшить значение `ESI` и увеличить значение `EBX`:
+
+[.programlisting]
+....
+ungetc:
+ dec esi
+ inc ebx
+ ret
+....
+
+Но будьте осторожны! Мы в полной безопасности, если заглядываем вперед только на один символ за раз. Если же мы проверяем несколько следующих символов и вызываем `ungetc` несколько раз подряд, это будет работать в большинстве случаев, но не всегда (и ошибки будет сложно отладить). Почему?
+
+Потому что пока `getchar` не вызывает `read`, все предварительно прочитанные байты остаются в буфере, и наш `ungetc` работает без сбоев. Но как только `getchar` вызывает `read`, содержимое буфера изменяется.
+
+Мы всегда можем рассчитывать на корректную работу `ungetc` с последним символом, прочитанным через `getchar`, но не с любым символом, прочитанным до этого.
+
+Если ваша программа читает более одного байта вперед, у вас есть как минимум два варианта:
+
+Если возможно, измените программу так, чтобы она читала только один байт вперед. Это самое простое решение.
+
+Если эта опция недоступна, сначала определите максимальное количество символов, которое вашей программе может потребоваться вернуть во входной поток за один раз. Увеличьте это число немного, чтобы быть уверенным, предпочтительно до кратного 16 — так оно будет лучше выровнено. Затем измените секцию `.bss` в вашем коде и создайте небольшой "запасной" буфер прямо перед вашим входным буфером, примерно так:
+
+[.programlisting]
+....
+section .bss
+ resb 16 ; or whatever the value you came up with
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+....
+
+Вам также необходимо изменить ваш `ungetc`, чтобы передать значение байта для возврата в `AL`:
+
+[.programlisting]
+....
+ungetc:
+ dec esi
+ inc ebx
+ mov [esi], al
+ ret
+....
+
+С этим изменением вы можете безопасно вызывать `ungetc` до 17 раз подряд (первый вызов всё ещё будет в пределах буфера, остальные 16 могут быть либо в пределах буфера, либо в пределах "запасного" пространства).
+
+[[x86-command-line]]
+== Аргументы командной строки
+
+Наша программа hex будет полезнее, если она сможет читать имена входного и выходного файлов из командной строки, т.е. если она сможет обрабатывать аргументы командной строки. Но... Где они?
+
+Прежде чем UNIX(R) система запустит программу, она делает ``push`` для некоторых данных, помещая их в стек, затем переходит к метке `_start` программы. Да, я сказал "переходит", а не "вызывает". Это означает, что данные можно прочитать с помощью `[esp+offset]` или просто сделать ``pop`` для них.
+
+Значение на вершине стека содержит количество аргументов командной строки. Оно традиционно называется `argc`, что означает "argument count".
+
+Далее следуют аргументы командной строки, все `argc` штук. Обычно их называют `argv`, что означает "значение(я) аргумента". То есть мы получаем `argv[0]`, `argv[1]`, `...`, `argv[argc-1]`. Это не сами аргументы, а указатели на аргументы, то есть адреса памяти, где находятся реальные аргументы. Сами аргументы представляют собой строки символов, завершающиеся нулевым символом ('\0').
+
+Список `argv` завершается указателем NULL, который представляет собой просто `0`. Есть и другие детали, но пока этого достаточно для наших целей.
+
+[NOTE]
+====
+Если вы перешли из среды программирования MS-DOS(R), основное различие заключается в том, что каждый аргумент находится в отдельной строке. Второе различие состоит в том, что нет практического ограничения на количество аргументов.
+====
+
+Вооружившись этими знаниями, мы почти готовы к следующей версии [.filename]#hex.asm#. Однако сначала нам нужно добавить несколько строк в [.filename]#system.inc#:
+
+Сначала нам нужно добавить две новые записи в наш список номеров системных вызовов:
+
+[.programlisting]
+....
+%define SYS_open 5
+%define SYS_close 6
+....
+
+Затем мы добавляем два новых макроса в конце файла:
+
+[.programlisting]
+....
+%macro sys.open 0
+ system SYS_open
+%endmacro
+
+%macro sys.close 0
+ system SYS_close
+%endmacro
+....
+
+Вот наш измененный исходный код:
+
+[.programlisting]
+....
+%include 'system.inc'
+
+%define BUFSIZE 2048
+
+section .data
+fd.in dd stdin
+fd.out dd stdout
+hex db '0123456789ABCDEF'
+
+section .bss
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+
+section .text
+align 4
+err:
+ push dword 1 ; return failure
+ sys.exit
+
+align 4
+global _start
+_start:
+ add esp, byte 8 ; discard argc and argv[0]
+
+ pop ecx
+ jecxz .init ; no more arguments
+
+ ; ECX contains the path to input file
+ push dword 0 ; O_RDONLY
+ push ecx
+ sys.open
+ jc err ; open failed
+
+ add esp, byte 8
+ mov [fd.in], eax
+
+ pop ecx
+ jecxz .init ; no more arguments
+
+ ; ECX contains the path to output file
+ push dword 420 ; file mode (644 octal)
+ push dword 0200h | 0400h | 01h
+ ; O_CREAT | O_TRUNC | O_WRONLY
+ push ecx
+ sys.open
+ jc err
+
+ add esp, byte 12
+ mov [fd.out], eax
+
+.init:
+ sub eax, eax
+ sub ebx, ebx
+ sub ecx, ecx
+ mov edi, obuffer
+
+.loop:
+ ; read a byte from input file or stdin
+ call getchar
+
+ ; convert it to hex
+ mov dl, al
+ shr al, 4
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, dl
+ and al, 0Fh
+ mov al, [hex+eax]
+ call putchar
+
+ mov al, ' '
+ cmp dl, 0Ah
+ jne .put
+ mov al, dl
+
+.put:
+ call putchar
+ cmp al, dl
+ jne .loop
+ call write
+ jmp short .loop
+
+align 4
+getchar:
+ or ebx, ebx
+ jne .fetch
+
+ call read
+
+.fetch:
+ lodsb
+ dec ebx
+ ret
+
+read:
+ push dword BUFSIZE
+ mov esi, ibuffer
+ push esi
+ push dword [fd.in]
+ sys.read
+ add esp, byte 12
+ mov ebx, eax
+ or eax, eax
+ je .done
+ sub eax, eax
+ ret
+
+align 4
+.done:
+ call write ; flush output buffer
+
+ ; close files
+ push dword [fd.in]
+ sys.close
+
+ push dword [fd.out]
+ sys.close
+
+ ; return success
+ push dword 0
+ sys.exit
+
+align 4
+putchar:
+ stosb
+ inc ecx
+ cmp ecx, BUFSIZE
+ je write
+ ret
+
+align 4
+write:
+ sub edi, ecx ; start of buffer
+ push ecx
+ push edi
+ push dword [fd.out]
+ sys.write
+ add esp, byte 12
+ sub eax, eax
+ sub ecx, ecx ; buffer is empty now
+ ret
+....
+
+В нашем разделе `.data` теперь есть две новые переменные, `fd.in` и `fd.out`. Здесь мы сохраняем дескрипторы файлов для ввода и вывода.
+
+В разделе `.text` мы заменили ссылки с `stdin` и `stdout` на `[fd.in]` и `[fd.out]`.
+
+Раздел `.text` теперь начинается с простого обработчика ошибок, который просто завершает программу с кодом возврата `1`. Обработчик ошибок расположен перед `_start`, чтобы находиться вблизи от места возникновения ошибок.
+
+Естественно, выполнение программы по-прежнему начинается с `_start`. Сначала мы удаляем `argc` и `argv[0]` из стека: они не представляют для нас интереса (по крайней мере, в этой программе).
+
+Мы помещаем `argv[1]` в `ECX`. Этот регистр особенно подходит для указателей, так как мы можем обрабатывать NULL-указатели с помощью `jecxz`. Если `argv[1]` не равен NULL, мы пытаемся открыть файл с именем, указанным в первом аргументе. В противном случае продолжаем программу как раньше: чтение из `stdin`, запись в `stdout`. Если нам не удаётся открыть входной файл (например, он не существует), мы переходим к обработчику ошибок и завершаем работу.
+
+Если всё прошло успешно, мы проверяем второй аргумент. Если он присутствует, мы открываем выходной файл. В противном случае, мы отправляем вывод в `stdout`. Если нам не удаётся открыть выходной файл (например, он существует и у нас нет прав на запись), мы снова переходим к обработчику ошибок.
+
+Остальная часть кода остается прежней, за исключением того, что мы закрываем входной и выходной файлы перед завершением, и, как упоминалось, используем `[fd.in]` и `[fd.out]`.
+
+Наш исполняемый файл теперь имеет внушительный размер в 768 байт.
+
+Можем ли мы улучшить его еще? Конечно! Каждую программу можно улучшить. Вот несколько идей, что мы могли бы сделать:
+
+* Сделать наш обработчик ошибок, выводящий сообщение в `stderr`.
+* Добавить обработчики ошибок в функции `read` и `write`.
+* Закрывать `stdin` при открытии входного файла, `stdout` при открытии выходного файла.
+* Добавить параметры командной строки, такие как `-i` и `-o`, чтобы можно было перечислять входные и выходные файлы в любом порядке или, возможно, читать из `stdin` и записывать в файл.
+* Выводить сообщение с подсказкой об использовании программы, если аргументы командной строки указаны неверно.
+
+Я оставлю эти улучшения в качестве упражнения для читателя: вы уже знаете всё необходимое для их реализации.
+
+[[x86-environment]]
+== Окружение UNIX(R)
+
+Важным концептом UNIX(R) является окружение, которое определяется _переменными окружения_. Некоторые из них устанавливаются системой, другие — пользователем, третьи — оболочкой или любой программой, которая загружает другую программу.
+
+[[x86-find-environment]]
+=== Как найти переменные окружения
+
+Я говорил ранее, что когда программа начинает выполняться, в стеке находятся `argc`, за которым следует массив `argv`, завершающийся NULL, а затем что-то ещё. Это "что-то ещё" — это _окружение_, или, если быть точнее, массив указателей на _переменные окружения_, завершающийся NULL. Это часто называют `env`.
+
+Структура `env` такая же, как у `argv` — список адресов памяти, заканчивающийся NULL (`0`). В данном случае нет `"envc"` — конец массива определяется поиском последнего NULL.
+
+Переменные обычно имеют формат `name=value`, но иногда часть `=value` может отсутствовать. Необходимо учитывать эту вероятность.
+
+[[x86-webvar]]
+=== webvars
+
+Я мог бы просто показать вам код, который выводит окружение так же, как команда UNIX(R) env. Но я подумал, что будет интереснее написать простую CGI-утилиту на ассемблере.
+
+[[x86-cgi]]
+==== CGI: краткий обзор
+
+У меня есть http://www.whizkidtech.redprince.net/cgi-bin/tutorial[подробное руководство по CGI] на моем веб-сайте, но вот очень краткий обзор CGI:
+
+* Веб-сервер взаимодействует с CGI-программой, устанавливая _переменные окружения_.
+* Программа CGI отправляет свой вывод в [.filename]#stdout#. Веб-сервер считывает его оттуда.
+* Он должен начинаться с HTTP-заголовка, за которым следуют две пустые строки.
+* Затем он выводит HTML-код или любые другие данные, которые он генерирует.
+
+[NOTE]
+====
+В то время как некоторые _переменные окружения_ используют стандартные имена, другие различаются в зависимости от веб-сервера. Это делает программу webvars весьма полезным инструментом для диагностики.
+====
+
+[[x86-webvars-the-code]]
+==== Код
+
+Наша программа webvars, таким образом, должна отправить HTTP-заголовок, за которым следует HTML-разметка. Затем она должна прочитать _переменные окружения_ одну за другой и отправить их как часть HTML-страницы.
+
+Код приведен ниже. Я разместил комментарии и пояснения прямо в коде:
+
+[.programlisting]
+....
+;;;;;;; webvars.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;
+; Copyright (c) 2000 G. Adam Stanislav
+; All rights reserved.
+;
+; Redistribution and use in source and binary forms, with or without
+; modification, are permitted provided that the following conditions
+; are met:
+; 1. Redistributions of source code must retain the above copyright
+; notice, this list of conditions and the following disclaimer.
+; 2. Redistributions in binary form must reproduce the above copyright
+; notice, this list of conditions and the following disclaimer in the
+; documentation and/or other materials provided with the distribution.
+;
+; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+; SUCH DAMAGE.
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;
+; Version 1.0
+;
+; Started: 8-Dec-2000
+; Updated: 8-Dec-2000
+;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+%include 'system.inc'
+
+section .data
+http db 'Content-type: text/html', 0Ah, 0Ah
+ db '<?xml version="1.0" encoding="utf-8"?>', 0Ah
+ db '<!DOCTYPE html PUBLIC "-//W3C/DTD XHTML Strict//EN" '
+ db '"DTD/xhtml1-strict.dtd">', 0Ah
+ db '<html xmlns="http://www.w3.org/1999/xhtml" '
+ db 'xml.lang="en" lang="en">', 0Ah
+ db '<head>', 0Ah
+ db '<title>Web Environment</title>', 0Ah
+ db '<meta name="author" content="G. Adam Stanislav" />', 0Ah
+ db '</head>', 0Ah, 0Ah
+ db '<body bgcolor="#ffffff" text="#000000" link="#0000ff" '
+ db 'vlink="#840084" alink="#0000ff">', 0Ah
+ db '<div class="webvars">', 0Ah
+ db '<h1>Web Environment</h1>', 0Ah
+ db '<p>The following <b>environment variables</b> are defined '
+ db 'on this web server:</p>', 0Ah, 0Ah
+ db '<table align="center" width="80" border="0" cellpadding="10" '
+ db 'cellspacing="0" class="webvars">', 0Ah
+httplen equ $-http
+left db '<tr>', 0Ah
+ db '<td class="name"><tt>'
+leftlen equ $-left
+middle db '</tt></td>', 0Ah
+ db '<td class="value"><tt><b>'
+midlen equ $-middle
+undef db '<i>(undefined)</i>'
+undeflen equ $-undef
+right db '</b></tt></td>', 0Ah
+ db '</tr>', 0Ah
+rightlen equ $-right
+wrap db '</table>', 0Ah
+ db '</div>', 0Ah
+ db '</body>', 0Ah
+ db '</html>', 0Ah, 0Ah
+wraplen equ $-wrap
+
+section .text
+global _start
+_start:
+ ; First, send out all the http and xhtml stuff that is
+ ; needed before we start showing the environment
+ push dword httplen
+ push dword http
+ push dword stdout
+ sys.write
+
+ ; Now find how far on the stack the environment pointers
+ ; are. We have 12 bytes we have pushed before "argc"
+ mov eax, [esp+12]
+
+ ; We need to remove the following from the stack:
+ ;
+ ; The 12 bytes we pushed for sys.write
+ ; The 4 bytes of argc
+ ; The EAX*4 bytes of argv
+ ; The 4 bytes of the NULL after argv
+ ;
+ ; Total:
+ ; 20 + eax * 4
+ ;
+ ; Because stack grows down, we need to ADD that many bytes
+ ; to ESP.
+ lea esp, [esp+20+eax*4]
+ cld ; This should already be the case, but let's be sure.
+
+ ; Loop through the environment, printing it out
+.loop:
+ pop edi
+ or edi, edi ; Done yet?
+ je near .wrap
+
+ ; Print the left part of HTML
+ push dword leftlen
+ push dword left
+ push dword stdout
+ sys.write
+
+ ; It may be tempting to search for the '=' in the env string next.
+ ; But it is possible there is no '=', so we search for the
+ ; terminating NUL first.
+ mov esi, edi ; Save start of string
+ sub ecx, ecx
+ not ecx ; ECX = FFFFFFFF
+ sub eax, eax
+repne scasb
+ not ecx ; ECX = string length + 1
+ mov ebx, ecx ; Save it in EBX
+
+ ; Now is the time to find '='
+ mov edi, esi ; Start of string
+ mov al, '='
+repne scasb
+ not ecx
+ add ecx, ebx ; Length of name
+
+ push ecx
+ push esi
+ push dword stdout
+ sys.write
+
+ ; Print the middle part of HTML table code
+ push dword midlen
+ push dword middle
+ push dword stdout
+ sys.write
+
+ ; Find the length of the value
+ not ecx
+ lea ebx, [ebx+ecx-1]
+
+ ; Print "undefined" if 0
+ or ebx, ebx
+ jne .value
+
+ mov ebx, undeflen
+ mov edi, undef
+
+.value:
+ push ebx
+ push edi
+ push dword stdout
+ sys.write
+
+ ; Print the right part of the table row
+ push dword rightlen
+ push dword right
+ push dword stdout
+ sys.write
+
+ ; Get rid of the 60 bytes we have pushed
+ add esp, byte 60
+
+ ; Get the next variable
+ jmp .loop
+
+.wrap:
+ ; Print the rest of HTML
+ push dword wraplen
+ push dword wrap
+ push dword stdout
+ sys.write
+
+ ; Return success
+ push dword 0
+ sys.exit
+....
+
+Этот код создает исполняемый файл размером 1 396 байт. Большая его часть — это данные, а именно HTML-разметка, которую нам нужно отправить.
+
+Запустите ассемблер и слинкуйте как обычно:
+
+[source, shell]
+....
+% nasm -f elf webvars.asm
+% ld -s -o webvars webvars.o
+....
+
+Для использования необходимо загрузить [.filename]#webvars# на ваш веб-сервер. В зависимости от настроек веб-сервера, возможно, потребуется разместить его в специальном каталоге [.filename]#cgi-bin# или переименовать с расширением [.filename]#.cgi#.
+
+Затем вам нужно использовать браузер для просмотра вывода. Чтобы увидеть вывод на моем веб-сервере, перейдите по ссылке http://www.int80h.org/webvars/[http://www.int80h.org/webvars/]. Если вам интересно узнать о дополнительных переменных окружения в защищенном паролем веб-каталоге, перейдите по адресу http://www.int80h.org/private/[http://www.int80h.org/private/], используя имя `asm` и пароль `programmer`.
+
+[[x86-files]]
+== Работа с файлами
+
+Мы уже выполнили некоторые базовые операции с файлами: мы знаем, как их открывать и закрывать, как читать и записывать их с использованием буферов. Однако UNIX(R) предлагает гораздо больше возможностей при работе с файлами. В этом разделе мы рассмотрим некоторые из них и в итоге создадим удобную утилиту для преобразования файлов.
+
+В самом деле, начнем с конца, то есть с утилиты преобразования файлов. Всегда легче программировать, когда с самого начала известно, каким должен быть конечный продукт.
+
+Одной из первых программ, которые я написал для UNIX(R), была link:ftp://ftp.int80h.org/unix/tuc/[tuc] — конвертер текста в файл UNIX(R). Она преобразует текстовый файл из других операционных систем в текстовый файл UNIX(R). Другими словами, она изменяет различные виды окончаний строк на стандартные для UNIX(R). Результат сохраняется в другом файле. По желанию, она может преобразовать текстовый файл UNIX(R) в текстовый файл DOS.
+
+Я широко использовал `tuc`, но всегда только для преобразования из какой-либо другой ОС в UNIX(R), никогда наоборот. Мне всегда хотелось, чтобы он просто перезаписывал файл, вместо того чтобы мне приходилось отправлять вывод в другой файл. В большинстве случаев я в итоге использую его так:
+
+[source, shell]
+....
+% tuc myfile tempfile
+% mv tempfile myfile
+....
+
+Было бы здорово иметь ftuc, т.е., _быстрый tuc_, и использовать его вот так:
+
+[source, shell]
+....
+% ftuc myfile
+....
+
+В этой главе мы напишем ftuc на языке ассемблера (оригинальный tuc написан на C) и в процессе изучим различные файловые сервисы ядра.
+
+На первый взгляд, такое преобразование файла кажется очень простым: нужно всего лишь удалить символы возврата каретки, верно?
+
+Если вы ответили «да», подумайте ещё раз: такой подход будет работать в большинстве случаев (по крайней мере, с текстовыми файлами MS DOS), но иногда он будет давать сбой.
+
+Проблема в том, что не все текстовые файлы, не относящиеся к UNIX(R), завершают строки последовательностью возврата каретки / перевода строки. Некоторые используют возврат каретки без перевода строки. Другие объединяют несколько пустых строк в один возврат каретки, за которым следует несколько переводов строки. И так далее.
+
+Конвертер текстовых файлов, следовательно, должен уметь обрабатывать любые возможные окончания строк:
+
+* возврат каретки (carriage return) / перевод строки (line feed)
+* возврат каретки
+* перевод строки / возврат каретки
+* перевод строки
+
+Это также должно обрабатывать файлы, использующие комбинации вышеуказанного (например, возврат каретки с последующими несколькими переводами строки).
+
+[[x86-finite-state-machine]]
+=== Конечный автомат
+
+Проблема легко решается с использованием техники, называемой _конечный автомат_, изначально разработанной создателями цифровых электронных схем. _Конечный автомат_ — это цифровая схема, выход которой зависит не только от входа, но и от предыдущего входа, то есть от её состояния. Микропроцессор является примером _конечного автомата_: наш код на языке ассемблера транслируется в машинный язык, где одни инструкции ассемблера превращаются в один байт машинного кода, а другие — в несколько байтов. Когда микропроцессор извлекает байты из памяти один за другим, некоторые из них просто изменяют его состояние, а не производят какой-либо выходной сигнал. После извлечения всех байтов кода операции микропроцессор выдает выходной сигнал, изменяет значение регистра и т. д.
+
+Из-за этого всё программное обеспечение по сути представляет собой последовательность инструкций состояния для микропроцессора. Тем не менее, концепция _конечного автомата_ также полезна при проектировании программного обеспечения.
+
+Наш конвертер текстовых файлов можно представить в виде _конечного автомата_ с тремя возможными состояниями. Мы могли бы назвать их состояниями 0-2, но будет проще, если дадим им символические имена:
+
+* ordinary
+* cr
+* lf
+
+Наша программа начнёт работу в обычном состоянии. В этом состоянии действие программы зависит от её входных данных следующим образом:
+
+* Если ввод представляет собой что-либо, кроме возврата каретки или перевода строки, ввод просто передаётся на вывод. Состояние остаётся неизменным.
+* Если входной символ — возврат каретки, состояние изменяется на cr. Затем входной символ отбрасывается, т.е. вывод не производится.
+* Если входной символ является переводом строки, состояние изменяется на lf. Затем входной символ отбрасывается.
+
+Всякий раз, когда мы находимся в состоянии `cr`, это означает, что последним вводом был символ возврата каретки, который не был обработан. Действия нашего программного обеспечения в этом состоянии снова зависят от текущего ввода:
+
+* Если ввод отличается от возврата каретки или перевода строки, вывести перевод строки, затем вывести ввод, а затем изменить состояние на обычное.
+* Если входной символ — возврат каретки, значит, мы получили два (или более) возврата каретки подряд. Мы отбрасываем ввод, выводим перевод строки и оставляем состояние неизменным.
+* Если входной символ — это перевод строки, мы выводим перевод строки и меняем состояние на обычное. Обратите внимание, что это не то же самое, что в первом случае выше — если бы мы попытались объединить их, мы бы выводили два перевода строки вместо одного.
+
+Наконец, мы находимся в состоянии `lf` после получения перевода строки, которому не предшествовал возврат каретки. Это произойдет, если наш файл уже в формате UNIX(R), или когда несколько строк подряд выражены одним возвратом каретки, за которым следуют несколько переводов строк, или когда строка заканчивается последовательностью перевода строки / возврата каретки. Вот как нам нужно обрабатывать ввод в этом состоянии:
+
+* Если ввод отличается от возврата каретки или перевода строки, мы выводим перевод строки, затем выводим ввод и изменяем состояние на обычное. Это действие полностью совпадает с действием в состоянии `cr` при получении аналогичного ввода.
+* Если ввод представляет собой символ возврата каретки, мы отбрасываем ввод, выводим символ перевода строки, затем изменяем состояние на обычное.
+* Если входной символ — перевод строки, мы выводим перевод строки и оставляем состояние неизменным.
+
+[[x86-final-state]]
+==== Конечное состояние
+
+Приведённый выше _конечный автомат_ работает для всего файла, но оставляет возможность, что последний конец строки будет проигнорирован. Это произойдёт, если файл заканчивается одиночным возвратом каретки или одиночным переводом строки. Я не подумал об этом, когда писал tuc, и лишь позже обнаружил, что иногда он удаляет последний конец строки.
+
+Эта проблема легко решается проверкой состояния после обработки всего файла. Если состояние не является обычным, нам просто нужно вывести последний перевод строки.
+
+[NOTE]
+====
+Теперь, когда мы выразили наш алгоритм в виде _конечного автомата_, мы могли бы легко разработать специализированную цифровую электронную схему («чип») для выполнения преобразования. Конечно, это было бы значительно дороже, чем написание программы на языке ассемблера.
+====
+
+[[x86-tuc-counter]]
+==== Счетчик вывода
+
+Поскольку наша программа преобразования файлов может объединять два символа в один, нам необходимо использовать счётчик вывода. Мы инициализируем его значением `0` и увеличиваем каждый раз, когда отправляем символ на выход. В конце программы счётчик укажет, какой размер необходимо установить для файла.
+
+[[x86-software-fsm]]
+=== Реализация конечного автомата в программном обеспечении
+
+Самая сложная часть работы с _конечным автоматом_ — это анализ задачи и её представление в виде _конечного автомата_. После этого программное обеспечение практически пишется само.
+
+На языке высокого уровня, таком как C, существует несколько основных подходов. Один из них — использование оператора `switch`, который выбирает, какую функцию следует выполнить. Например,
+
+[.programlisting]
+....
+switch (state) {
+ default:
+ case REGULAR:
+ regular(inputchar);
+ break;
+ case CR:
+ cr(inputchar);
+ break;
+ case LF:
+ lf(inputchar);
+ break;
+ }
+....
+
+Еще один подход заключается в использовании массива указателей на функции, например:
+
+[.programlisting]
+....
+(output[state])(inputchar);
+....
+
+Еще один вариант — сделать `state` указателем на функцию, установив его на соответствующую функцию:
+
+[.programlisting]
+....
+(*state)(inputchar);
+....
+
+Это подход, который мы будем использовать в нашей программе, потому что его очень легко реализовать на языке ассемблера, и он также очень быстрый. Мы просто будем хранить адрес нужной процедуры в `EBX`, а затем выполним:
+
+[.programlisting]
+....
+call ebx
+....
+
+Это возможно быстрее, чем жестко задавать адрес в коде, потому что микропроцессору не нужно извлекать адрес из памяти — он уже хранится в одном из его регистров. Я сказал _возможно_, потому что с учетом кэширования, которое выполняют современные микропроцессоры, оба варианта могут быть одинаково быстрыми.
+
+[[memory-mapped-files]]
+=== Отображенные в память файлы
+
+Поскольку наша программа работает с одним файлом, мы не можем использовать подход, который работал ранее, то есть чтение из входного файла и запись в выходной файл.
+
+UNIX(R) позволяет нам отображать файл или его часть в память. Для этого сначала необходимо открыть файл с соответствующими флагами чтения/записи. Затем мы используем системный вызов `mmap`, чтобы отобразить его в память. Одно из преимуществ `mmap` заключается в том, что он автоматически работает с виртуальной памятью: мы можем отобразить в память больше файла, чем имеется физической памяти, и при этом обращаться к нему с помощью обычных команд работы с памятью, таких как `mov`, `lods` и `stos`. Все изменения, внесённые в память, отображённую из файла, будут записаны в файл системой. Нам даже не нужно держать файл открытым: пока он остаётся отображённым, мы можем читать из него и записывать в него.
+
+32-разрядные микропроцессоры Intel могут адресовать до четырёх гигабайт памяти — физической или виртуальной. Система FreeBSD позволяет использовать до половины этого объёма для отображения файлов.
+
+Для упрощения в этом руководстве мы будем преобразовывать только файлы, которые могут быть полностью отображены в памяти. Вероятно, не так много текстовых файлов превышают размер в два гигабайта. Если наша программа встретит такой файл, она просто выведет сообщение с предложением использовать оригинальный tuc.
+
+Если вы изучите свою копию файла [.filename]#syscalls.master#, вы найдёте два отдельных системных вызова с именем `mmap`. Это связано с эволюцией UNIX(R): существовал традиционный BSD `mmap`, системный вызов 71. Он был заменён на POSIX(R) `mmap`, системный вызов 197. Система FreeBSD поддерживает оба, поскольку старые программы были написаны с использованием оригинальной BSD-версии. Но новое программное обеспечение использует версию POSIX(R), которую мы и будем применять.
+
+В [.filename]#syscalls.master# POSIX(R) версия указана следующим образом:
+
+[.programlisting]
+....
+197 STD BSD { caddr_t mmap(caddr_t addr, size_t len, int prot, \
+ int flags, int fd, long pad, off_t pos); }
+....
+
+Это немного отличается от того, что указано в man:mmap[2]. Это связано с тем, что man:mmap[2] описывает версию на языке C.
+
+Разница заключается в аргументе `long pad`, который отсутствует в версии на C. Однако системные вызовы FreeBSD добавляют 32-битный заполнитель после ``push`` 64-битного аргумента. В данном случае `off_t` является 64-битным значением.
+
+Когда мы завершаем работу с файлом, отображённым в память, мы освобождаем его с помощью системного вызова `munmap`:
+
+[TIP]
+====
+Для подробного изучения `mmap` см. http://www.int80h.org/cgi-bin/isbn?isbn=0130810819[Unix Network Programming, Volume 2, Chapter 12] У. Ричарда Стивенса.
+====
+
+[[x86-file-size]]
+=== Определение размера файла
+
+Поскольку нам нужно указать `mmap`, сколько байт файла отобразить в памяти, и поскольку мы хотим отобразить весь файл, нам необходимо определить его размер.
+
+Мы можем использовать системный вызов `fstat` для получения всей информации об открытом файле, которую система может нам предоставить. Это включает в себя размер файла.
+
+Вновь, в [.filename]#syscalls.master# указаны две версии `fstat`: традиционная (системный вызов 62) и POSIX(R) (системный вызов 189). Естественно, мы будем использовать версию POSIX(R):
+
+[.programlisting]
+....
+189 STD POSIX { int fstat(int fd, struct stat *sb); }
+....
+
+Это очень простой вызов: мы передаем ему адрес структуры `stat` и дескриптор открытого файла. Он заполнит содержимое структуры `stat`.
+
+Однако должен сказать, что я пытался объявить структуру `stat` в секции `.bss`, и `fstat` это не понравилось: был установлен флаг переноса, указывающий на ошибку. После того как я изменил код, чтобы разместить структуру в стеке, всё заработало как надо.
+
+[[x86-ftruncate]]
+=== Изменение размера файла
+
+Поскольку наша программа может объединять последовательности возврата каретки / перевода строки в простые переводы строк, наш вывод может быть меньше, чем ввод. Однако, так как мы помещаем вывод в тот же файл, из которого читаем ввод, нам может потребоваться изменить размер файла.
+
+Системный вызов `ftruncate` позволяет нам сделать именно это. Несмотря на название , несколько вводящее в звблуждение, системный вызов `ftruncate` может использоваться как для усечения файла (уменьшения его размера), так и для его увеличения.
+
+И да, мы найдем две версии `ftruncate` в [.filename]#syscalls.master#, старую (130) и новую (201). Мы будем использовать новую:
+
+[.programlisting]
+....
+201 STD BSD { int ftruncate(int fd, int pad, off_t length); }
+....
+
+Обратите внимание, что здесь снова присутствует `int pad`.
+
+[[x86-ftuc]]
+=== ftuc
+
+Теперь мы знаем всё, что нужно для написания ftuc. Начнём с добавления нескольких новых строк в [.filename]#system.inc#. Сначала определим некоторые константы и структуры, где-нибудь в начале или около начала файла:
+
+[.programlisting]
+....
+;;;;;;; open flags
+%define O_RDONLY 0
+%define O_WRONLY 1
+%define O_RDWR 2
+
+;;;;;;; mmap flags
+%define PROT_NONE 0
+%define PROT_READ 1
+%define PROT_WRITE 2
+%define PROT_EXEC 4
+;;
+%define MAP_SHARED 0001h
+%define MAP_PRIVATE 0002h
+
+;;;;;;; stat structure
+struc stat
+st_dev resd 1 ; = 0
+st_ino resd 1 ; = 4
+st_mode resw 1 ; = 8, size is 16 bits
+st_nlink resw 1 ; = 10, ditto
+st_uid resd 1 ; = 12
+st_gid resd 1 ; = 16
+st_rdev resd 1 ; = 20
+st_atime resd 1 ; = 24
+st_atimensec resd 1 ; = 28
+st_mtime resd 1 ; = 32
+st_mtimensec resd 1 ; = 36
+st_ctime resd 1 ; = 40
+st_ctimensec resd 1 ; = 44
+st_size resd 2 ; = 48, size is 64 bits
+st_blocks resd 2 ; = 56, ditto
+st_blksize resd 1 ; = 64
+st_flags resd 1 ; = 68
+st_gen resd 1 ; = 72
+st_lspare resd 1 ; = 76
+st_qspare resd 4 ; = 80
+endstruc
+....
+
+Мы определяем новые системные вызовы:
+
+[.programlisting]
+....
+%define SYS_mmap 197
+%define SYS_munmap 73
+%define SYS_fstat 189
+%define SYS_ftruncate 201
+....
+
+Добавляем макросы для их использования:
+
+[.programlisting]
+....
+%macro sys.mmap 0
+ system SYS_mmap
+%endmacro
+
+%macro sys.munmap 0
+ system SYS_munmap
+%endmacro
+
+%macro sys.ftruncate 0
+ system SYS_ftruncate
+%endmacro
+
+%macro sys.fstat 0
+ system SYS_fstat
+%endmacro
+....
+
+И вот наш код:
+
+[.programlisting]
+....
+;;;;;;; Fast Text-to-Unix Conversion (ftuc.asm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;
+;; Started: 21-Dec-2000
+;; Updated: 22-Dec-2000
+;;
+;; Copyright 2000 G. Adam Stanislav.
+;; All rights reserved.
+;;
+;;;;;;; v.1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+%include 'system.inc'
+
+section .data
+ db 'Copyright 2000 G. Adam Stanislav.', 0Ah
+ db 'All rights reserved.', 0Ah
+usg db 'Usage: ftuc filename', 0Ah
+usglen equ $-usg
+co db "ftuc: Can't open file.", 0Ah
+colen equ $-co
+fae db 'ftuc: File access error.', 0Ah
+faelen equ $-fae
+ftl db 'ftuc: File too long, use regular tuc instead.', 0Ah
+ftllen equ $-ftl
+mae db 'ftuc: Memory allocation error.', 0Ah
+maelen equ $-mae
+
+section .text
+
+align 4
+memerr:
+ push dword maelen
+ push dword mae
+ jmp short error
+
+align 4
+toolong:
+ push dword ftllen
+ push dword ftl
+ jmp short error
+
+align 4
+facerr:
+ push dword faelen
+ push dword fae
+ jmp short error
+
+align 4
+cantopen:
+ push dword colen
+ push dword co
+ jmp short error
+
+align 4
+usage:
+ push dword usglen
+ push dword usg
+
+error:
+ push dword stderr
+ sys.write
+
+ push dword 1
+ sys.exit
+
+align 4
+global _start
+_start:
+ pop eax ; argc
+ pop eax ; program name
+ pop ecx ; file to convert
+ jecxz usage
+
+ pop eax
+ or eax, eax ; Too many arguments?
+ jne usage
+
+ ; Open the file
+ push dword O_RDWR
+ push ecx
+ sys.open
+ jc cantopen
+
+ mov ebp, eax ; Save fd
+
+ sub esp, byte stat_size
+ mov ebx, esp
+
+ ; Find file size
+ push ebx
+ push ebp ; fd
+ sys.fstat
+ jc facerr
+
+ mov edx, [ebx + st_size + 4]
+
+ ; File is too long if EDX != 0 ...
+ or edx, edx
+ jne near toolong
+ mov ecx, [ebx + st_size]
+ ; ... or if it is above 2 GB
+ or ecx, ecx
+ js near toolong
+
+ ; Do nothing if the file is 0 bytes in size
+ jecxz .quit
+
+ ; Map the entire file in memory
+ push edx
+ push edx ; starting at offset 0
+ push edx ; pad
+ push ebp ; fd
+ push dword MAP_SHARED
+ push dword PROT_READ | PROT_WRITE
+ push ecx ; entire file size
+ push edx ; let system decide on the address
+ sys.mmap
+ jc near memerr
+
+ mov edi, eax
+ mov esi, eax
+ push ecx ; for SYS_munmap
+ push edi
+
+ ; Use EBX for state machine
+ mov ebx, ordinary
+ mov ah, 0Ah
+ cld
+
+.loop:
+ lodsb
+ call ebx
+ loop .loop
+
+ cmp ebx, ordinary
+ je .filesize
+
+ ; Output final lf
+ mov al, ah
+ stosb
+ inc edx
+
+.filesize:
+ ; truncate file to new size
+ push dword 0 ; high dword
+ push edx ; low dword
+ push eax ; pad
+ push ebp
+ sys.ftruncate
+
+ ; close it (ebp still pushed)
+ sys.close
+
+ add esp, byte 16
+ sys.munmap
+
+.quit:
+ push dword 0
+ sys.exit
+
+align 4
+ordinary:
+ cmp al, 0Dh
+ je .cr
+
+ cmp al, ah
+ je .lf
+
+ stosb
+ inc edx
+ ret
+
+align 4
+.cr:
+ mov ebx, cr
+ ret
+
+align 4
+.lf:
+ mov ebx, lf
+ ret
+
+align 4
+cr:
+ cmp al, 0Dh
+ je .cr
+
+ cmp al, ah
+ je .lf
+
+ xchg al, ah
+ stosb
+ inc edx
+
+ xchg al, ah
+ ; fall through
+
+.lf:
+ stosb
+ inc edx
+ mov ebx, ordinary
+ ret
+
+align 4
+.cr:
+ mov al, ah
+ stosb
+ inc edx
+ ret
+
+align 4
+lf:
+ cmp al, ah
+ je .lf
+
+ cmp al, 0Dh
+ je .cr
+
+ xchg al, ah
+ stosb
+ inc edx
+
+ xchg al, ah
+ stosb
+ inc edx
+ mov ebx, ordinary
+ ret
+
+align 4
+.cr:
+ mov ebx, ordinary
+ mov al, ah
+ ; fall through
+
+.lf:
+ stosb
+ inc edx
+ ret
+....
+
+[WARNING]
+====
+Не используйте эту программу для файлов, хранящихся на диске, отформатированном в MS-DOS(R) или Windows(R). В коде FreeBSD присутствует неочевидная ошибка при использовании `mmap` на таких дисках, смонтированных в FreeBSD: если размер файла превышает определённое значение, `mmap` заполнит память нулями, а затем запишет их в файл, перезаписав его содержимое.
+====
+
+[[x86-one-pointed-mind]]
+== Спокойствие ума
+
+Как ученик дзэн, мне нравится идея спокойствия ума (экаггата): делай одно дело за раз и делай его хорошо.
+
+Вот именно так, в большинстве случаев, работает и UNIX(R). В то время как типичное приложение Windows(R) пытается сделать всё, что только можно (и поэтому кишит ошибками), типичная программа UNIX(R) делает только одну вещь, но делает её хорошо.
+
+Типичный пользователь UNIX(R) по сути собирает свои собственные приложения, написав shell-скрипт, который объединяет различные существующие программы, передавая вывод одной программы на вход другой.
+
+При написании собственного программного обеспечения для UNIX(R) обычно рекомендуется определить, какие части решаемой задачи могут быть обработаны существующими программами, и создавать собственные программы только для той части задачи, для которой нет готового решения.
+
+[[x86-csv]]
+=== CSV
+
+Я проиллюстрирую этот принцип конкретным примером из реальной жизни, с которым недавно столкнулся:
+
+Мне нужно было извлечь 11-е поле каждой записи из базы данных, которую я загрузил с веб-сайта. База данных представляла собой CSV-файл, то есть список _значений, разделённых запятыми_. Это довольно стандартный формат для обмена данными между людьми, которые могут использовать разное программное обеспечение для работы с базами данных.
+
+Первая строка файла содержит список различных полей, разделенных запятыми. Остальная часть файла содержит данные, перечисленные построчно, со значениями, разделенными запятыми.
+
+Я попробовал awk, используя запятую в качестве разделителя. Но поскольку несколько строк содержали запятую в кавычках, awk извлекал неправильное поле из этих строк.
+
+Следовательно, мне нужно было написать собственное программное обеспечение для извлечения 11-го поля из CSV-файла. Однако, следуя духу UNIX(R), мне нужно было лишь создать простой фильтр, выполняющий следующие действия:
+
+* Удалить первую строку из файла;
+* Заменить все не заключённые в кавычки запятые на другой символ;
+* Удалить все кавычки.
+
+Строго говоря, я мог бы использовать sed для удаления первой строки из файла, но сделать это в моей собственной программе было очень просто, поэтому я решил так поступить и уменьшить размер конвейера.
+
+В любом случае, написание подобной программы заняло у меня около 20 минут. Написание программы, которая извлекает 11-е поле из CSV-файла, заняло бы гораздо больше времени, и я не смог бы повторно использовать её для извлечения другого поля из другой базы данных.
+
+На этот раз я решил позволить ей выполнить немного больше работы, чем обычная учебная программа:
+
+* Она анализирует свою командную строку на наличие опций;
+* Она отображает подсказку, если обнаруживает неверные аргументы;
+* Она выдает понятные сообщения об ошибках.
+
+Вот какое сообщение она выводит о том, как ее использовать:
+
+[source, shell]
+....
+Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]
+....
+
+Все параметры необязательны и могут располагаться в любом порядке.
+
+Параметр `-t` указывает, на что заменить запятые. По умолчанию используется `tab`. Например, `-t;` заменит все незакавыченные запятые на точку с запятой.
+
+Мне не понадобилась опция `-c`, но в будущем она может пригодиться. Она позволяет указать, что я хочу заменить символ, отличный от запятой, на что-то другое. Например, `-c@` заменит все знаки @ (полезно, если нужно разделить список email-адресов на имена пользователей и домены).
+
+Опция `-p` сохраняет первую строку, т.е. не удаляет её. По умолчанию мы удаляем первую строку, потому что в CSV-файле она содержит названия полей, а не данные.
+
+Опции `-i` и `-o` позволяют указать входной и выходной файлы. По умолчанию используются [.filename]#stdin# и [.filename]#stdout#, как обычно работает стандартный фильтр UNIX(R).
+
+Я убедился, что принимаются как `-i filename`, так и `-ifilename`. Также я убедился, что может быть указан только один входной и один выходной файл.
+
+Чтобы получить 11-е поле каждой записи, теперь я могу сделать:
+
+[source, shell]
+....
+% csv '-t;' data.csv | awk '-F;' '{print $11}'
+....
+
+Код сохраняет параметры (за исключением файловых дескрипторов) в `EDX`: запятая в `DH`, новый разделитель в `DL`, а флаг параметра `-p` в старшем бите `EDX`, поэтому проверка его знака даст нам быстрое решение о дальнейших действиях.
+
+Вот код:
+
+[.programlisting]
+....
+;;;;;;; csv.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;
+; Convert a comma-separated file to a something-else separated file.
+;
+; Started: 31-May-2001
+; Updated: 1-Jun-2001
+;
+; Copyright (c) 2001 G. Adam Stanislav
+; All rights reserved.
+;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+%include 'system.inc'
+
+%define BUFSIZE 2048
+
+section .data
+fd.in dd stdin
+fd.out dd stdout
+usg db 'Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]', 0Ah
+usglen equ $-usg
+iemsg db "csv: Can't open input file", 0Ah
+iemlen equ $-iemsg
+oemsg db "csv: Can't create output file", 0Ah
+oemlen equ $-oemsg
+
+section .bss
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+
+section .text
+align 4
+ierr:
+ push dword iemlen
+ push dword iemsg
+ push dword stderr
+ sys.write
+ push dword 1 ; return failure
+ sys.exit
+
+align 4
+oerr:
+ push dword oemlen
+ push dword oemsg
+ push dword stderr
+ sys.write
+ push dword 2
+ sys.exit
+
+align 4
+usage:
+ push dword usglen
+ push dword usg
+ push dword stderr
+ sys.write
+ push dword 3
+ sys.exit
+
+align 4
+global _start
+_start:
+ add esp, byte 8 ; discard argc and argv[0]
+ mov edx, (',' << 8) | 9
+
+.arg:
+ pop ecx
+ or ecx, ecx
+ je near .init ; no more arguments
+
+ ; ECX contains the pointer to an argument
+ cmp byte [ecx], '-'
+ jne usage
+
+ inc ecx
+ mov ax, [ecx]
+
+.o:
+ cmp al, 'o'
+ jne .i
+
+ ; Make sure we are not asked for the output file twice
+ cmp dword [fd.out], stdout
+ jne usage
+
+ ; Find the path to output file - it is either at [ECX+1],
+ ; i.e., -ofile --
+ ; or in the next argument,
+ ; i.e., -o file
+
+ inc ecx
+ or ah, ah
+ jne .openoutput
+ pop ecx
+ jecxz usage
+
+.openoutput:
+ push dword 420 ; file mode (644 octal)
+ push dword 0200h | 0400h | 01h
+ ; O_CREAT | O_TRUNC | O_WRONLY
+ push ecx
+ sys.open
+ jc near oerr
+
+ add esp, byte 12
+ mov [fd.out], eax
+ jmp short .arg
+
+.i:
+ cmp al, 'i'
+ jne .p
+
+ ; Make sure we are not asked twice
+ cmp dword [fd.in], stdin
+ jne near usage
+
+ ; Find the path to the input file
+ inc ecx
+ or ah, ah
+ jne .openinput
+ pop ecx
+ or ecx, ecx
+ je near usage
+
+.openinput:
+ push dword 0 ; O_RDONLY
+ push ecx
+ sys.open
+ jc near ierr ; open failed
+
+ add esp, byte 8
+ mov [fd.in], eax
+ jmp .arg
+
+.p:
+ cmp al, 'p'
+ jne .t
+ or ah, ah
+ jne near usage
+ or edx, 1 << 31
+ jmp .arg
+
+.t:
+ cmp al, 't' ; redefine output delimiter
+ jne .c
+ or ah, ah
+ je near usage
+ mov dl, ah
+ jmp .arg
+
+.c:
+ cmp al, 'c'
+ jne near usage
+ or ah, ah
+ je near usage
+ mov dh, ah
+ jmp .arg
+
+align 4
+.init:
+ sub eax, eax
+ sub ebx, ebx
+ sub ecx, ecx
+ mov edi, obuffer
+
+ ; See if we are to preserve the first line
+ or edx, edx
+ js .loop
+
+.firstline:
+ ; get rid of the first line
+ call getchar
+ cmp al, 0Ah
+ jne .firstline
+
+.loop:
+ ; read a byte from stdin
+ call getchar
+
+ ; is it a comma (or whatever the user asked for)?
+ cmp al, dh
+ jne .quote
+
+ ; Replace the comma with a tab (or whatever the user wants)
+ mov al, dl
+
+.put:
+ call putchar
+ jmp short .loop
+
+.quote:
+ cmp al, '"'
+ jne .put
+
+ ; Print everything until you get another quote or EOL. If it
+ ; is a quote, skip it. If it is EOL, print it.
+.qloop:
+ call getchar
+ cmp al, '"'
+ je .loop
+
+ cmp al, 0Ah
+ je .put
+
+ call putchar
+ jmp short .qloop
+
+align 4
+getchar:
+ or ebx, ebx
+ jne .fetch
+
+ call read
+
+.fetch:
+ lodsb
+ dec ebx
+ ret
+
+read:
+ jecxz .read
+ call write
+
+.read:
+ push dword BUFSIZE
+ mov esi, ibuffer
+ push esi
+ push dword [fd.in]
+ sys.read
+ add esp, byte 12
+ mov ebx, eax
+ or eax, eax
+ je .done
+ sub eax, eax
+ ret
+
+align 4
+.done:
+ call write ; flush output buffer
+
+ ; close files
+ push dword [fd.in]
+ sys.close
+
+ push dword [fd.out]
+ sys.close
+
+ ; return success
+ push dword 0
+ sys.exit
+
+align 4
+putchar:
+ stosb
+ inc ecx
+ cmp ecx, BUFSIZE
+ je write
+ ret
+
+align 4
+write:
+ jecxz .ret ; nothing to write
+ sub edi, ecx ; start of buffer
+ push ecx
+ push edi
+ push dword [fd.out]
+ sys.write
+ add esp, byte 12
+ sub eax, eax
+ sub ecx, ecx ; buffer is empty now
+.ret:
+ ret
+....
+
+Большая часть взята из [.filename]#hex.asm# выше. Однако есть одно важное отличие: я больше не вызываю `write` каждый раз при выводе перевода строки. Тем не менее, код можно использовать интерактивно.
+
+Я нашел лучшее решение для интерактивной проблемы с тех пор, как начал писать эту главу. Я хотел убедиться, что каждая строка выводится отдельно только при необходимости. В конце концов, нет необходимости выводить каждую строку при неинтерактивном использовании.
+
+Новое решение, которое я использую сейчас, заключается в вызове `write` каждый раз, когда обнаруживаю, что входной буфер пуст. Таким образом, при работе в интерактивном режиме программа считывает одну строку с клавиатуры пользователя, обрабатывает её и видит, что входной буфер пуст. Она сбрасывает свой вывод и читает следующую строку.
+
+[[x86-buffered-dark-side]]
+==== Темная сторона буферизации
+
+Это изменение предотвращает загадочную блокировку в очень специфическом случае. Я называю это _тёмной стороной буферизации_, в основном потому, что это представляет опасность, которая не совсем очевидна.
+
+Маловероятно, что это произойдет с такой программой, как csv выше, поэтому рассмотрим еще один фильтр: в этом случае мы ожидаем, что наши входные данные будут представлять собой необработанные данные, описывающие значения цветов, такие как интенсивности _красного_, _зеленого_ и _синего_ для пикселя. На выходе мы получим негатив входных данных.
+
+Такой фильтр было бы очень просто написать. Большая его часть выглядела бы так же, как и все другие фильтры, которые мы уже писали, поэтому я покажу только его внутренний цикл:
+
+[.programlisting]
+....
+.loop:
+ call getchar
+ not al ; Create a negative
+ call putchar
+ jmp short .loop
+....
+
+Поскольку этот фильтр работает с необработанными данными, он вряд ли будет использоваться интерактивно.
+
+Но он может вызываться программным обеспечением для обработки изображений. И, если он не вызывает `write` перед каждым вызовом `read`, высока вероятность, что он зависнет.
+
+Вот что может произойти:
+
+[.procedure]
+. Редактор изображений загрузит наш фильтр, используя функцию `popen()` на языке C.
+. Он прочитает первый ряд пикселей из битовой карты или пиксельной карты.
+. Он запишет первую строку пикселей в _канал_, ведущий к `fd.in` нашего фильтра.
+. Наш фильтр будет читать каждый пиксель из входных данных, преобразовывать его в негатив и записывать в выходной буфер.
+. Наш фильтр будет вызывать `getchar` для получения следующего пикселя.
+. `getchar` обнаружит пустой входной буфер, поэтому вызовет `read`.
+. `read` вызовет системный вызов `SYS_read`.
+. _Ядро_ приостановит работу нашего фильтра до тех пор, пока редактор изображений не отправит больше данных в канал.
+. Редактор изображений будет читать из другого канала, подключенного к `fd.out` нашего фильтра, чтобы он мог установить первую строку выходного изображения _до_ того, как отправит нам вторую строку входного.
+. _Ядро_ приостанавливает работу графического редактора до тех пор, пока не получит какие-либо данные от нашего фильтра, чтобы передать их редактору.
+
+На этом этапе наш фильтр ожидает, что редактор изображений отправит ему больше данных для обработки, в то время как редактор изображений ожидает, что наш фильтр отправит ему результат обработки первой строки. Однако результат находится в нашем выходном буфере.
+
+Фильтр и редактор изображений будут продолжать ждать друг друга вечно (или, по крайней мере, пока их не завершат командой kill). Наше программное обеспечение только что вошло в crossref:secure[secure-race-conditions,состояние гонки].
+
+Эта проблема не возникает, если наш фильтр очищает свой выходной буфер _перед_ запросом к _ядру_ для получения дополнительных входных данных.
+
+[[x86-fpu]]
+== Использование FPU
+
+Как ни странно, большая часть литературы по ассемблеру даже не упоминает о существовании FPU, или _блока обработки чисел с плавающей запятой_, не говоря уже о программировании для него.
+
+Тем не менее, язык ассемблера проявляет себя наилучшим образом, когда мы создаем высокооптимизированный код для FPU, выполняя вещи, которые можно сделать _только_ на языке ассемблера.
+
+[[x86-fpu-organization]]
+=== Организация FPU
+
+FPU состоит из 8 80-битных регистров с плавающей запятой. Они организованы в виде стека — вы можете `push` (поместить) значение на TOS (_вершина стека_) и `pop` (извлечь) его.
+
+Как бы то ни было, мнемоники ассемблера — не `push` и `pop`, потому что они уже заняты.
+
+Вы можете `push` (положить) значение на вершину стека (TOS), используя `fld`, `fild` и `fbld`. Несколько других кодов операций позволяют вам `push` (положить) многие распространённые _константы_ — например, _pi_ — на вершину стека (TOS).
+
+Аналогично, вы можете `извлечь` значение с помощью `fst`, `fstp`, `fist`, `fistp` и `fbstp`. На самом деле только коды операций, оканчивающиеся на _p_, буквально `извлекают` значение, остальные же `сохраняют` его в другом месте, не удаляя с вершины стека (TOS).
+
+Мы можем передавать данные между TOS и памятью компьютера либо как 32-битное, 64-битное или 80-битное _вещественное_ число, 16-битное, 32-битное или 64-битное _целое_ число, либо как 80-битное _упакованное десятичное_ число.
+
+80-битный _упакованный десятичный_ формат является особым случаем _двоично-десятичного кодирования_, который очень удобен при преобразовании между ASCII-представлением данных и внутренними данными FPU. Он позволяет использовать до 18 значащих цифр.
+
+Независимо от того, как мы представляем данные в памяти, FPU всегда хранит их в 80-битном формате _real_ в своих регистрах.
+
+Его внутренняя точность составляет не менее 19 десятичных цифр, поэтому даже если мы решим отображать результаты в формате ASCII с полной 18-значной точностью, мы всё равно будем показывать корректные результаты.
+
+Мы можем выполнять математические операции над TOS: вычислять его _синус_, _масштабировать_ (то есть умножать или делить на степень двойки), вычислять его _логарифм_ по основанию 2 и многое другое.
+
+Мы также можем _умножить_ или _разделить_ его, _прибавить_ к нему или _вычесть_ его из любого из регистров FPU (включая его самого).
+
+Официальный код операции Intel для TOS — `st`, а для _регистров_ — `st(0)`-`st(7)`. Таким образом, `st` и `st(0)` ссылаются на один и тот же регистр.
+
+По каким-то причинам оригинальный автор nasm решил использовать другие коды операций, а именно `st0`-`st7`. Другими словами, скобки отсутствуют, а вершина стека всегда `st0`, но никогда просто `st`.
+
+[[x86-fpu-packed-decimal]]
+==== Формат упакованного десятичного числа
+
+Формат _упакованного десятичного числа_ использует 10 байт (80 бит) памяти для представления 18 цифр. Представленное число всегда является _целым_.
+
+[TIP]
+====
+Вы можете использовать это для получения десятичных знаков, предварительно умножив TOS на степень 10.
+====
+
+Старший бит старшего байта (байт 9) является _знаковым битом_: если он установлен, число _отрицательное_, в противном случае — _положительное_. Остальные биты этого байта не используются/игнорируются.
+
+Оставшиеся 9 байт хранят 18 цифр числа: 2 цифры на байт.
+
+_Старший разряд_ хранится в старшем _полубайте_ (4 бита), _младший разряд_ — в младшем _полубайте_.
+
+Как бы то ни было, вы можете подумать, что `-1234567` будет храниться в памяти следующим образом (в шестнадцатеричной записи):
+
+[.programlisting]
+....
+80 00 00 00 00 00 01 23 45 67
+....
+
+Увы, это не так! Как и все остальное, созданное Intel, даже _упакованное десятичное число_ имеет порядок _от младшего к старшему_.
+
+Это означает, что наш `-1234567` хранится следующим образом:
+
+[.programlisting]
+....
+67 45 23 01 00 00 00 00 00 80
+....
+
+Помните об этом, иначе вы будете рвать на себе волосы в отчаянии!
+
+[NOTE]
+====
+Книга, которую стоит прочитать — если сможете её найти — это книга Ричарда Старца http://www.amazon.com/exec/obidos/ASIN/013246604X/whizkidtechnomag[8087/80287/80387 для IBM PC и совместимых]. Хотя в ней, кажется, факт о little-endian хранении _упакованного десятичного числа_ принимается как данность. Я не шучу насчёт отчаяния, которое испытывал, пытаясь понять, что не так с фильтром, который я привожу ниже, _прежде_ чем мне пришло в голову попробовать little-endian порядок даже для этого типа данных.
+====
+
+[[x86-pinhole-photography]]
+=== Экскурсия в фотографию с помощью камеры-обскуры
+
+Чтобы создавать полезное программное обеспечение, мы должны понимать не только наши инструменты программирования, но и область, для которой разрабатываем ПО.
+
+Наш следующий фильтр поможет нам, когда мы захотим создать _камеру-обскуру_, поэтому нам понадобятся некоторые знания о _фотографии с помощью обскуры_, прежде чем мы сможем продолжить.
+
+[[x86-camera]]
+==== Камера
+
+Самый простой способ описать любую когда-либо созданную камеру — это некоторое пустое пространство, заключённое в светонепроницаемый материал, с небольшим отверстием в корпусе.
+
+Корпус обычно прочный (например, коробка), хотя иногда он гибкий (гофрированная часть). Внутри камеры довольно темно. Однако отверстие пропускает световые лучи через одну точку (хотя в некоторых случаях их может быть несколько). Эти световые лучи формируют изображение — представление того, что находится снаружи камеры, перед отверстием.
+
+Если внутрь камеры поместить светочувствительный материал (например, плёнку), он может зафиксировать изображение.
+
+Отверстие часто содержит _линзу_ или сборку линз, которую часто называют _объективом_.
+
+[[x86-the-pinhole]]
+==== Игольное ушко
+
+Но, строго говоря, линза не обязательна: первые камеры использовали не линзу, а _маленькое отверстие_ размером с игольное ушко. Даже сегодня _маленькие отверстия_ применяются как инструмент для изучения принципов работы камер и для создания особого вида изображений.
+
+Изображение, создаваемое _маленьким отверстием_, одинаково резкое. Или _размытое_. Существует идеальный размер для маленького отверстия: если оно больше или меньше, изображение теряет резкость.
+
+[[x86-focal-length]]
+==== Фокусное расстояние
+
+Идеальный диаметр отверстия является функцией квадратного корня из _фокусного расстояния_, которое представляет собой расстояние от отверстия до плёнки.
+
+[.programlisting]
+....
+D = PC * sqrt(FL)
+....
+
+Здесь `D` — идеальный диаметр отверстия, `FL` — фокусное расстояние, а `PC` — константа отверстия. По данным Джейя Бендера, её значение равно `0,04`, тогда как Кеннет Коннорс определил его как `0,037`. Другие исследователи предложили иные значения. Кроме того, это значение справедливо только для дневного света: другие типы освещения потребуют иной константы, значение которой можно определить только экспериментальным путём.
+
+[[x86-f-number]]
+==== Число f (диафрагменное число)
+
+Число f — это очень полезный показатель того, сколько света попадает на плёнку. Экспонометр может определить, что, например, для экспонирования плёнки определённой чувствительности при f5.6 может потребоваться выдержка 1/1000 сек.
+
+Не имеет значения, 35-мм это камера или камера 6x9 см и т.д. Достаточно знать диафрагменное число, чтобы определить правильную экспозицию.
+
+Число f легко вычислить:
+
+[.programlisting]
+....
+F = FL / D
+....
+
+Другими словами, число f равно фокусному расстоянию, деленному на диаметр отверстия. Это также означает, что большее f-число подразумевает либо меньшее отверстие, либо большее фокусное расстояние, либо и то, и другое. В свою очередь, это означает, что чем больше число f, тем дольше должна быть выдержка.
+
+Кроме того, хотя диаметр отверстия и фокусное расстояние являются одномерными величинами, и плёнка, и отверстие — двумерны. Это означает, что если вы измерили экспозицию при диафрагменном числе `A` как `t`, то экспозиция при диафрагменном числе `B` будет:
+
+[.programlisting]
+....
+t * (B / A)²
+....
+
+[[x86-normalized-f-number]]
+==== Нормализованное число f
+
+Хотя многие современные камеры могут изменять диаметр своего отверстия, а следовательно и свое число f, довольно плавно и постепенно, так было не всегда.
+
+Для обеспечения различных значений диафрагмы в камерах обычно использовалась металлическая пластина с несколькими отверстиями разного размера.
+
+Их размеры были выбраны в соответствии с приведённой выше формулой таким образом, чтобы результирующее f-число было одним из стандартных f-чисел, используемых на всех фотоаппаратах. Например, у моего очень старого фотоаппарата Kodak Duaflex IV есть три таких отверстия для чисел f — 8, 11 и 16.
+
+Более современные камеры могут предлагать значения диафрагменного числа 2.8, 4, 5.6, 8, 11, 16, 22 и 32 (а также другие). Эти числа выбраны не произвольно: все они являются степенями квадратного корня из 2, хотя могут быть немного округлены.
+
+[[x86-f-stop]]
+==== Ступени числа f
+
+Типичная камера устроена так, что установка любого из нормализованных чисел f изменяет ощущение от регулятора. Он естественным образом _останавливается_ в этом положении. Из-за этого такие положения регулятора называются f-ступенями.
+
+Поскольку значения диафрагмы на каждой ступени являются степенями квадратного корня из 2, поворот диска на 1 ступень удваивает количество света, необходимое для правильной экспозиции. Поворот на 2 ступени увеличивает требуемую экспозицию вчетверо. Поворот диска на 3 ступени требует увеличения экспозиции в 8 раз и так далее.
+
+[[x86-pinhole-software]]
+=== Проектирование программного обеспечения камеры-обскуры
+
+Мы готовы решить, что именно должно делать наше программное обеспечение для камер-обскур.
+
+[[xpinhole-processing-input]]
+==== Обработка ввода программы
+
+Поскольку основная цель — помочь нам разработать работающую камеру-обскуру, мы будем использовать _фокусное расстояние_ в качестве входных данных для программы. Это можно определить без программного обеспечения: правильное фокусное расстояние зависит от размера плёнки и необходимости съёмки «обычных» изображений, широкоугольных или телефото.
+
+Большинство написанных нами до сих пор программ работали с отдельными символами или байтами в качестве входных данных: программа hex преобразовывала отдельные байты в шестнадцатеричное число, программа csv либо пропускала символ, либо удаляла его, либо заменяла на другой символ и т.д.
+
+Одна программа, `ftuc`, использовала конечный автомат для обработки не более двух входных байтов за раз.
+
+Но наша программа для камеры-обскуры не может работать только с отдельными символами, ей приходится иметь дело с более крупными синтаксическими единицами.
+
+Например, если мы хотим, чтобы программа рассчитала диаметр отверстия (и другие значения, которые мы обсудим позже) для фокусных расстояний `100 мм`, `150 мм` и `210 мм`, мы можем ввести что-то вроде этого:
+
+[source, shell]
+....
+ 100, 150, 210
+....
+
+Наша программа должна учитывать более одного байта входных данных за раз. Когда она видит первую `1`, она должна понимать, что это первая цифра десятичного числа. Когда она видит `0` и другой `0`, она должна знать, что это следующие цифры того же числа.
+
+Когда он встречает первую запятую, он должен понять, что больше не получает цифры первого числа. Он должен уметь преобразовать цифры первого числа в значение `100`. И цифры второго числа в значение `150`. И, конечно же, цифры третьего числа в числовое значение `210`.
+
+Нам нужно определиться с допустимыми разделителями: должны ли входные числа разделяться запятой? Если да, то как обрабатывать два числа, разделённые чем-то другим?
+
+Лично я предпочитаю простоту. Либо что-то является числом — и тогда я его обрабатываю. Либо не является числом — и тогда я это отбрасываю. Мне не нравится, когда компьютер жалуется на лишний символ, если _очевидно_, что он лишний. Да ладно!
+
+Плюс, это позволяет мне разбавить монотонность вычислений и ввести запрос вместо просто числа:
+
+[source, shell]
+....
+What is the best pinhole diameter for the
+ focal length of 150?
+....
+
+Нет причины, чтобы компьютер выводил множество жалоб:
+
+[source, shell]
+....
+Syntax error: What
+Syntax error: is
+Syntax error: the
+Syntax error: best
+....
+
+И так далее, и так далее, и так далее.
+
+Во-вторых, мне нравится символ `+#+` для обозначения начала комментария, который продолжается до конца строки. Это не требует больших усилий для реализации и позволяет мне рассматривать входные файлы для моего программного обеспечения как исполняемые скрипты.
+
+В нашем случае также необходимо определиться с единицами измерения входных данных: мы выбираем _миллиметры_, так как большинство фотографов измеряют фокусное расстояние именно в них.
+
+Наконец, нам нужно решить, разрешать ли использование десятичной точки (в этом случае мы также должны учитывать тот факт, что во многих странах используется десятичная _запятая_).
+
+В нашем случае разрешение десятичной точки/запятой создало бы ложное ощущение точности: разница между фокусными расстояниями `50` и `51` практически незаметна, поэтому разрешать пользователю вводить что-то вроде `50.5` — не лучшая идея. Это моё мнение, конечно, но программу пишу я. В своей программе вы можете сделать другие выбор, разумеется.
+
+[[x86-pinhole-options]]
+==== Передача параметров программе
+
+Самое важное, что нам нужно знать при создании камеры-обскуры — это диаметр отверстия. Поскольку мы хотим получать чёткие изображения, мы будем использовать приведённую выше формулу для расчёта диаметра отверстия от фокусного расстояния. Поскольку эксперты предлагают несколько различных значений для константы `PC`, нам нужно будет иметь выбор.
+
+В традициях программирования в UNIX(R) предусмотрены два основных способа выбора параметров программы, а также значение по умолчанию на случай, если пользователь не сделает выбор.
+
+Почему есть два способа выбора?
+
+Один из способов — это позволить (относительно) _постоянный_ выбор, который применяется автоматически каждый раз при запуске программы, без необходимости каждый раз указывать, что мы хотим, чтобы она сделала.
+
+Постоянные настройки могут быть сохранены в конфигурационном файле, обычно расположенном в домашнем каталоге пользователя. Файл обычно имеет то же имя, что и приложение, но начинается с точки. Часто к имени файла добавляется _"rc"_. Таким образом, наш файл может называться [.filename]#~/.pinhole# или [.filename]#~/.pinholerc#. (Обозначение [.filename]#~/# означает домашний каталог текущего пользователя.)
+
+Файл конфигурации в основном используется программами, у которых много настраиваемых параметров. Те, у которых он один (или несколько), часто используют другой метод: они ожидают найти параметр в _переменной окружения_. В нашем случае, мы можем посмотреть на переменную окружения с именем `PINHOLE`.
+
+Обычно программа использует один из вышеуказанных методов. В противном случае, если в конфигурационном файле указано одно, а в переменной окружения — другое, программа может запутаться (или стать слишком сложной).
+
+Поскольку нам нужно выбрать только _один_ такой параметр, мы воспользуемся вторым методом и поищем в окружении переменную с именем `PINHOLE`.
+
+Другой способ позволяет нам принимать _ad hoc_ решения: _"Хотя обычно я хочу, чтобы ты использовал 0.039, на этот раз мне нужно 0.03872."_ Другими словами, он позволяет нам _переопределить_ постоянный выбор.
+
+Такой выбор обычно осуществляется с помощью параметров командной строки.
+
+Наконец, программе _всегда_ необходим _значение по умолчанию_. Пользователь может не делать никакого выбора. Возможно, он не знает, что выбрать. Возможно, он «просто просматривает». Предпочтительно, чтобы значением по умолчанию было то, что выбрало бы большинство пользователей. Таким образом, им не нужно выбирать. Или, точнее, они могут выбрать значение по умолчанию без дополнительных усилий.
+
+Учитывая эту систему, программа может обнаружить конфликтующие параметры и обработать их следующим образом:
+
+[.procedure]
+. Если она находит _специальный_ выбор (например, параметр командной строки), она должна принять этот выбор. Она должна игнорировать любой постоянный выбор и значения по умолчанию.
+. _В противном случае_, если будет найден постоянный параметр (например, переменная окружения), он должен быть принят, а значение по умолчанию — проигнорировано.
+. _В противном случае_, следует использовать значение по умолчанию.
+
+Нам также необходимо решить, в каком _формате_ должна быть наша опция `PC`.
+
+На первый взгляд кажется очевидным использовать формат `PINHOLE=0.04` для переменной окружения и `-p0.04` для командной строки.
+
+Разрешение этого на самом деле представляет угрозу безопасности. Константа `PC` — это очень маленькое число. Естественно, мы протестируем наше программное обеспечение, используя различные небольшие значения `PC`. Но что произойдёт, если кто-то запустит программу, выбрав огромное значение?
+
+Это может привести к сбою программы, так как мы не разрабатывали её для обработки огромных чисел.
+
+Или мы можем потратить больше времени на программу, чтобы она могла обрабатывать огромные числа. Мы могли бы сделать это, если бы писали коммерческое программное обеспечение для аудитории, не знакомой с компьютерами.
+
+Или можно сказать: _"Пусть терпит! Пользователь сам должен был разобраться."_
+
+Или мы можем просто сделать невозможным ввод пользователем слишком большого числа. Это подход, который мы выберем: мы будем использовать _подразумеваемый префикс 0._.
+
+Другими словами, если пользователь хочет `0.04`, мы ожидаем, что он введёт `-p04` или установит `PINHOLE=04` в своём окружении. Таким образом, если он укажет `-p9999999`, мы интерпретируем это как ``0.9999999`` — всё ещё нелепо, но по крайней мере безопаснее.
+
+Во-вторых, многие пользователи просто захотят использовать либо константу Бендера, либо константу Коннорса. Чтобы облегчить им задачу, мы будем интерпретировать `-b` как идентичное `-p04`, а `-c` как идентичное `-p037`.
+
+[[x86-pinhole-output]]
+==== Вывод результата
+
+Нам нужно решить, что наше программное обеспечение должно отправлять на вывод и в каком формате.
+
+Поскольку наши входные данные допускают неограниченное количество значений фокусного расстояния, имеет смысл использовать традиционный вывод в стиле базы данных, показывая результат вычислений для каждого фокусного расстояния на отдельной строке, разделяя все значения в строке символом табуляции.
+
+Опционально, мы также должны разрешить пользователю указать использование формата CSV, который мы изучили ранее. В этом случае мы выведем строку с разделёнными запятыми названиями, описывающими каждое поле каждой строки, а затем отобразим результаты как прежде, но заменив `табуляцию` на `запятую`.
+
+Нам нужна опция командной строки для формата CSV. Мы не можем использовать `-c`, потому что это уже означает _использовать константу Коннорса_. По какой-то странной причине многие веб-сайты называют CSV-файлы _"электронными таблицами Excel"_ (хотя формат CSV появился раньше Excel). Поэтому мы будем использовать переключатель `-e`, чтобы указать нашему программному обеспечению, что мы хотим получить вывод в формате CSV.
+
+Мы начнем каждую строку вывода с фокусного расстояния. Это может показаться избыточным сначала, особенно в интерактивном режиме: пользователь вводит фокусное расстояние, а мы его повторяем.
+
+Но пользователь может ввести несколько фокусных расстояний в одной строке. Ввод также может поступать из файла или вывода другой программы. В этом случае пользователь вообще не видит вводимые данные.
+
+Таким же образом, вывод может быть направлен в файл, который мы захотим изучить позже, или на принтер, или стать входными данными для другой программы.
+
+Итак, имеет полный смысл начинать каждую строку с фокусного расстояния, введённого пользователем.
+
+Нет, подождите! Не так, как ввел пользователь. Что, если пользователь введет что-то вроде этого:
+
+[source, shell]
+....
+ 00000000150
+....
+
+Очевидно, нам нужно удалить ведущие нули.
+
+Итак, можно рассмотреть вариант чтения пользовательского ввода как есть, преобразования его в бинарный вид внутри FPU и последующего вывода оттуда.
+
+Но...
+
+Что делать, если пользователь введёт что-то вроде этого:
+
+[source, shell]
+....
+ 17459765723452353453534535353530530534563507309676764423
+....
+
+Ха! Упакованный десятичный формат FPU позволяет нам вводить 18-значные числа. Но пользователь ввёл больше 18 цифр. Как нам обработать это?
+
+Хорошо, мы _могли бы_ изменить наш код, чтобы он читал первые 18 цифр, передавал их в FPU, затем читал ещё, умножал уже имеющееся на вершине стека (TOS) на 10 в степени количества дополнительных цифр, а затем выполнял `сложение` с этим значением.
+
+Да, мы могли бы так поступить. Но в _этой_ программе это было бы нелепо (в другой это могло бы быть как раз тем, что нужно): даже длина окружности Земли, выраженная в миллиметрах, занимает всего 11 цифр. Очевидно, мы не можем построить камеру такого размера (по крайней мере, пока).
+
+Итак, если пользователь вводит такое огромное число, он либо скучает, либо проверяет нас, либо пытается взломать систему, либо играет — делает что угодно, кроме проектирования камеры-обскуры.
+
+Что мы будем делать?
+
+Мы ударим его по лицу, образно говоря:
+
+[source, shell]
+....
+17459765723452353453534535353530530534563507309676764423 ??? ??? ??? ??? ???
+....
+
+Для этого мы просто проигнорируем все ведущие нули. Как только мы найдем ненулевую цифру, мы инициализируем счетчик значением `0` и начнем выполнять три шага:
+
+[.procedure]
+. Отправить цифру на выход.
+. Добавить цифру в буфер, который мы позже используем для создания упакованного десятичного числа, которое можно отправить в FPU.
+. Увеличить счетчик.
+
+Теперь, пока мы выполняем эти три шага, нам также необходимо следить за одним из двух условий:
+
+* Если счётчик превышает 18, мы прекращаем добавление в буфер. Мы продолжаем читать цифры и отправлять их на вывод.
+* Если, или скорее _когда_, следующий вводимый символ не является цифрой, мы завершаем ввод на данный момент.
++
+Между прочим, мы можем просто отбросить нецифровой символ, если это не `+#+`, который необходимо вернуть во входной поток. Он начинает комментарий, поэтому мы должны увидеть его после завершения вывода и начала поиска следующего ввода.
+
+Остается одна непокрытая возможность: если пользователь вводит только ноль (или несколько нулей), мы никогда не найдем ненулевое значение для отображения.
+
+Мы можем определить, что это произошло, когда наш счетчик остается на `0`. В этом случае нам нужно отправить `0` на выход и выполнить еще один "удар по лицу":
+
+[source, shell]
+....
+0 ??? ??? ??? ??? ???
+....
+
+Как только мы определили фокусное расстояние и убедились, что оно корректно (больше `0`, но не превышает 18 цифр), можно рассчитать диаметр отверстия.
+
+Не случайно слово _булавочное ушко_ содержит слово _булавка_. Действительно, многие малые отверстия буквально являются _дырками от булавки_ — отверстиями, аккуратно проделанными остриём булавки.
+
+Вот потому что типичное отверстие очень маленькое. Наша формула дает результат в миллиметрах. Мы умножим его на `1000`, чтобы вывести результат в _микронах_.
+
+На этом этапе нас ожидает ещё одна ловушка: _Излишняя точность._
+
+Да, FPU был разработан для вычислений с высокой точностью. Но мы имеем дело не с вычислениями высокой точности. Мы имеем дело с физикой (конкретно, с оптикой).
+
+Предположим, мы хотим превратить грузовик в камеру-обскуру (мы будем не первыми, кто это сделал!). Допустим, его кузов имеет длину `12` метров, значит, фокусное расстояние равно `12000`. Используя константу Бендера, получаем квадратный корень из `12000`, умноженный на `0.04`, что составляет `4.381780460` миллиметра или `4381.780460` микрона.
+
+Как ни посмотри, результат абсурдно точен. Наш грузовик не имеет _точно_ `12000` миллиметров в длину. Мы не измеряли его длину с такой точностью, поэтому утверждение, что нам нужна отверстие диаметром `4,381780460` миллиметра, мягко говоря, вводит в заблуждение. `4,4` миллиметра будет вполне достаточно.
+
+[NOTE]
+====
+Я "всего лишь" использовал десять цифр в приведенном выше примере. Представьте абсурдность попытки использовать все 18!
+====
+
+Нам нужно ограничить количество значащих цифр в нашем результате. Один из способов сделать это — использовать целое число, представляющее микроны. Таким образом, нашему грузовику потребуется отверстие диаметром `4382` микрона. Глядя на это число, мы всё же решаем, что `4400` микрон, или `4.4` миллиметра, достаточно близко.
+
+Кроме того, мы можем решить, что независимо от размера результата, мы хотим отображать только четыре значащих цифры (или любое другое их количество, конечно). Увы, FPU не поддерживает округление до определенного количества цифр (в конце концов, он воспринимает числа не как десятичные, а как двоичные).
+
+Следовательно, мы должны разработать алгоритм для уменьшения количества значащих цифр.
+
+Вот мой (я думаю, он неуклюжий — если у вас есть вариант лучше, _пожалуйста_, дайте мне знать):
+
+[.procedure]
+. Инициализировать счетчик значением `0`.
+. Пока число больше или равно `10000`, делим его на `10` и увеличиваем счётчик.
+. Вывести результат.
+. Пока счетчик больше `0`, выводить `0` и уменьшать счетчик.
+
+[NOTE]
+====
+`10000` подходит только если вам нужно _четыре_ значащих цифры. Для любого другого количества значащих цифр замените `10000` на `10` в степени, равной количеству значащих цифр.
+====
+
+Мы затем выведем диаметр отверстия в микронах, округлённый до четырёх значащих цифр.
+
+На этом этапе нам известны _фокусное расстояние_ и _диаметр отверстия_. Это означает, что у нас достаточно информации для расчёта _диафрагменного числа_.
+
+Мы отобразим число f, округлённое до четырёх значащих цифр. Скорее всего, само число f мало что нам скажет. Чтобы придать ему больше смысла, мы можем найти ближайшее _нормализованное число f_, то есть ближайшую степень квадратного корня из 2.
+
+Мы делаем это, умножая фактическое значение диафрагмы на само себя, что, конечно же, даст нам его `квадрат`. Затем мы вычислим его логарифм по основанию 2, что намного проще, чем вычисление логарифма по основанию квадратного корня из 2! Мы округлим результат до ближайшего целого числа. Далее мы возведём 2 в полученную степень. На самом деле, FPU предоставляет нам удобный способ сделать это: мы можем использовать код операции `fscale` для "масштабирования" 1, что аналогично ``сдвигу`` целого числа влево. Наконец, мы вычисляем квадратный корень из всего этого и получаем ближайшее нормализованное значение диафрагмы.
+
+Если всё это звучит ошеломляюще — или, возможно, слишком сложно — всё может стать гораздо понятнее, если увидеть код. Вместе это занимает всего 9 инструкций процессора:
+
+[.programlisting]
+....
+fmul st0, st0
+ fld1
+ fld st1
+ fyl2x
+ frndint
+ fld1
+ fscale
+ fsqrt
+ fstp st1
+....
+
+Первая строка, `fmul st0, st0`, возводит в квадрат содержимое TOS (вершина стека, то же что `st`, называется `st0` в nasm). Команда `fld1` помещает `1` на вершину стека.
+
+Следующая строка, `fld st1`, помещает квадрат обратно в TOS. На этом этапе квадрат находится и в `st`, и в `st(2)` (скоро станет ясно, зачем мы оставляем вторую копию в стеке). В `st(1)` содержится `1`.
+
+Далее, `fyl2x` вычисляет логарифм по основанию 2 от `st`, умноженный на `st(1)`. Именно поэтому мы ранее поместили `1` в `st(1)`.
+
+На этом этапе `st` содержит логарифм, который мы только что вычислили, а `st(1)` содержит квадрат фактического значения диафрагменного числа, который мы сохранили для последующего использования.
+
+`frndint` округляет TOS до ближайшего целого числа. `fld1` помещает `1` в стек. `fscale` сдвигает `1`, находящееся на TOS, на значение в `st(1)`, фактически возводя 2 в степень `st(1)`.
+
+Наконец, `fsqrt` вычисляет квадратный корень из результата, т.е. ближайшее нормализованное число f.
+
+У нас теперь есть ближайшее нормализованное число f на вершине стека (TOS), округлённый до ближайшего целого двоичный логарифм в `st(1)` и квадрат фактического число f в `st(2)`. Мы сохраняем значение в `st(2)` для последующего использования.
+
+Но нам больше не нужно содержимое `st(1)`. Последняя строка, `fstp st1`, помещает содержимое `st` в `st(1)` и выполняет извлечение. В результате, то, что было `st(1)`, теперь становится `st`, то, что было `st(2)`, теперь становится `st(1)`, и так далее. Новый `st` содержит нормализованное число f. Новый `st(1)` содержит квадрат фактического число f, который мы сохранили для потомков.
+
+На этом этапе мы готовы вывести нормализованное число f. Поскольку оно нормализовано, мы не будем округлять его до четырёх значащих цифр, а отправим его с полной точностью.
+
+Нормализованное диафрагменное число полезно, пока оно достаточно мало и может быть найдено на нашем экспонометре. В противном случае нам нужен другой метод определения правильной экспозиции.
+
+Ранее мы вывели формулу для расчёта правильной экспозиции при произвольной диафрагме на основе измерений, сделанных при другой диафрагме.
+
+Каждый экспонометр, который я когда-либо видел, может определить правильную экспозицию при f5.6. Поэтому мы рассчитаем _"множитель f5.6"_, то есть насколько нужно умножить экспозицию, измеренную при f5.6, чтобы определить правильную экспозицию для нашей камеры-обскуры.
+
+Из приведённой формулы мы знаем, что этот коэффициент можно вычислить, разделив наше число f (фактическое, а не нормализованное) на `5.6` и возведя результат в квадрат.
+
+Математически, деление квадрата нашего числа f на квадрат `5.6` даст нам тот же результат.
+
+С вычислительной точки зрения, нам не нужно возводить в квадрат два числа, когда можно возвести только одно. Таким образом, первое решение на первый взгляд кажется лучше.
+
+Но...
+
+`5.6` — это _константа_. Нам не нужно заставлять наш FPU тратить драгоценные циклы. Мы можем просто указать ему разделить квадрат f-числа на то, чему равно `5.6²`. Или мы можем разделить f-число на `5.6`, а затем возвести результат в квадрат. Теперь оба способа кажутся равнозначными.
+
+Но они не такие!
+
+Изучив принципы фотографии выше, мы помним, что `5.6` — это квадратный корень из 2, возведённый в пятую степень. Это _иррациональное_ число. Квадрат этого числа _ровно_ `32`.
+
+`32` — это не просто целое число, это степень двойки. Нам не нужно делить квадрат числа f на `32`. Достаточно использовать `fscale` для сдвига вправо на пять позиций. В терминологии FPU это означает, что мы применим `fscale` со значением `st(1)` равным `-5`. Это _гораздо быстрее_, чем деление.
+
+Итак, теперь стало ясно, зачем мы сохранили квадрат числа f на вершине стека FPU. Расчёт множителя для f5.6 — это самое простое вычисление во всей программе! Мы выведем его, округлив до четырёх значащих цифр.
+
+Есть ещё одно полезное число, которое мы можем вычислить: количество ступеней, на которые наше значение диафрагмы отличается от f5.6. Это может помочь, если наше значение диафрагмы находится чуть за пределами диапазона нашего экспонометра, но у нас есть затвор, который позволяет устанавливать различные выдержки, и этот затвор использует ступени.
+
+Предположим, наше число диафрагмы на 5 ступеней отличается от f5.6, а экспонометр показывает, что нужно использовать выдержку 1/1000 сек. Тогда мы можем сначала установить выдержку на 1/1000, а затем повернуть диск на 5 ступеней.
+
+Этот расчет также довольно прост. Все, что нам нужно сделать, это вычислить логарифм по основанию 2 от множителя f5.6, который мы только что рассчитали (хотя нам нужно его значение до округления). Затем мы выводим результат, округленный до ближайшего целого числа. Нам не нужно беспокоиться о наличии более четырех значащих цифр в этом случае: скорее всего, результат будет содержать только одну или две цифры.
+
+[[x86-fpu-optimizations]]
+=== Оптимизации FPU
+
+В ассемблерном коде мы можем оптимизировать инструкции FPU способами, невозможными в языках высокого уровня, включая C.
+
+Всякий раз, когда функции на языке C требуется вычислить значение с плавающей запятой, она загружает все необходимые переменные и константы в регистры FPU. Затем выполняются все необходимые вычисления для получения правильного результата. Хорошие компиляторы C могут очень эффективно оптимизировать эту часть кода.
+
+Он "возвращает" значение, оставляя результат на вершине стека (TOS). Однако перед возвратом он выполняет очистку. Все переменные и константы, использованные в вычислениях, теперь удалены из FPU.
+
+Он не может сделать то, что мы только что сделали выше: мы вычислили квадрат числа f и оставили его в стеке для последующего использования другой функцией.
+
+Мы _знали_, что это значение понадобится позже. Мы также знали, что у нас достаточно места в стеке (в котором помещается только 8 чисел), чтобы сохранить его там.
+
+Компилятор C не может знать, что значение, находящееся в стеке, потребуется снова в ближайшем будущем.
+
+Конечно, программист на C может это знать. Но единственное средство, которое у него есть, — это сохранить значение в переменной памяти.
+
+Это означает, что значение будет изменено с 80-битной точности, используемой внутри FPU, на тип _double_ (64 бита) или даже _single_ (32 бита) в C.
+
+Это также означает, что значение должно быть перемещено из TOS в память, а затем обратно. Увы, среди всех операций с FPU, доступ к памяти компьютера является самым медленным.
+
+Итак, при программировании FPU на языке ассемблера ищите способы хранения промежуточных результатов в стеке FPU.
+
+Мы можем развить эту идею еще дальше! В нашей программе мы используем _константу_ (ту, которую назвали `PC`).
+
+Не имеет значения, сколько диаметров отверстий мы рассчитываем: 1, 10, 20, 1000, мы всегда используем одну и ту же константу. Следовательно, мы можем оптимизировать нашу программу, сохраняя константу в стеке всё время.
+
+В начале нашей программы мы вычисляем значение указанной константы. Нам нужно разделить наш вход на `10` для каждой цифры в константе.
+
+Гораздо быстрее умножать, чем делить. Поэтому в начале нашей программы мы делим `1` на `10`, чтобы получить `0.1`, который затем сохраняем в стеке: вместо того чтобы делить ввод на `10` для каждой цифры, мы умножаем его на `0.1`.
+
+Кстати, мы не вводим `0.1` напрямую, хотя могли бы. У нас есть причина для этого: хотя `0.1` можно выразить всего одним десятичным знаком, мы не знаем, сколько _двоичных_ разрядов для этого потребуется. Поэтому мы позволяем FPU вычислить его двоичное значение с собственной высокой точностью.
+
+Мы используем другие константы: умножаем диаметр отверстия на `1000`, чтобы перевести его из миллиметров в микроны. Мы сравниваем числа с `10000`, когда округляем их до четырёх значащих цифр. Таким образом, мы оставляем и `1000`, и `10000` в стеке. И, конечно же, мы повторно используем `0.1` при округлении чисел до четырёх цифр.
+
+И последнее, но не менее важное: мы оставляем `-5` в стеке. Он нам нужен для масштабирования квадрата числа f вместо деления его на `32`. Не случайно мы загружаем эту константу последней. Это делает её вершиной стека, когда в нём находятся только константы. Таким образом, при масштабировании квадрата число f `-5` находится в `st(1)`, именно там, где `fscale` ожидает его увидеть.
+
+Это обычная ситуация, когда некоторые константы создаются с нуля, вместо загрузки их из памяти. Именно это мы делаем с `-5`:
+
+[.programlisting]
+....
+ fld1 ; TOS = 1
+ fadd st0, st0 ; TOS = 2
+ fadd st0, st0 ; TOS = 4
+ fld1 ; TOS = 1
+ faddp st1, st0 ; TOS = 5
+ fchs ; TOS = -5
+....
+
+Мы можем обобщить все эти оптимизации в одном правиле: _Держите повторяющиеся значения в стеке!_
+
+[TIP]
+====
+_PostScript(R)_ — это стековая язык программирования. Существует гораздо больше книг о PostScript(R), чем о языке ассемблера FPU: освоение PostScript(R) поможет вам овладеть FPU.
+====
+
+[[x86-pinhole-the-code]]
+=== Код pinhole
+
+[.programlisting]
+....
+;;;;;;; pinhole.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;
+; Find various parameters of a pinhole camera construction and use
+;
+; Started: 9-Jun-2001
+; Updated: 10-Jun-2001
+;
+; Copyright (c) 2001 G. Adam Stanislav
+; All rights reserved.
+;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+%include 'system.inc'
+
+%define BUFSIZE 2048
+
+section .data
+align 4
+ten dd 10
+thousand dd 1000
+tthou dd 10000
+fd.in dd stdin
+fd.out dd stdout
+envar db 'PINHOLE=' ; Exactly 8 bytes, or 2 dwords long
+pinhole db '04,', ; Bender's constant (0.04)
+connors db '037', 0Ah ; Connors' constant
+usg db 'Usage: pinhole [-b] [-c] [-e] [-p <value>] [-o <outfile>] [-i <infile>]', 0Ah
+usglen equ $-usg
+iemsg db "pinhole: Can't open input file", 0Ah
+iemlen equ $-iemsg
+oemsg db "pinhole: Can't create output file", 0Ah
+oemlen equ $-oemsg
+pinmsg db "pinhole: The PINHOLE constant must not be 0", 0Ah
+pinlen equ $-pinmsg
+toobig db "pinhole: The PINHOLE constant may not exceed 18 decimal places", 0Ah
+biglen equ $-toobig
+huhmsg db 9, '???'
+separ db 9, '???'
+sep2 db 9, '???'
+sep3 db 9, '???'
+sep4 db 9, '???', 0Ah
+huhlen equ $-huhmsg
+header db 'focal length in millimeters,pinhole diameter in microns,'
+ db 'F-number,normalized F-number,F-5.6 multiplier,stops '
+ db 'from F-5.6', 0Ah
+headlen equ $-header
+
+section .bss
+ibuffer resb BUFSIZE
+obuffer resb BUFSIZE
+dbuffer resb 20 ; decimal input buffer
+bbuffer resb 10 ; BCD buffer
+
+section .text
+align 4
+huh:
+ call write
+ push dword huhlen
+ push dword huhmsg
+ push dword [fd.out]
+ sys.write
+ add esp, byte 12
+ ret
+
+align 4
+perr:
+ push dword pinlen
+ push dword pinmsg
+ push dword stderr
+ sys.write
+ push dword 4 ; return failure
+ sys.exit
+
+align 4
+consttoobig:
+ push dword biglen
+ push dword toobig
+ push dword stderr
+ sys.write
+ push dword 5 ; return failure
+ sys.exit
+
+align 4
+ierr:
+ push dword iemlen
+ push dword iemsg
+ push dword stderr
+ sys.write
+ push dword 1 ; return failure
+ sys.exit
+
+align 4
+oerr:
+ push dword oemlen
+ push dword oemsg
+ push dword stderr
+ sys.write
+ push dword 2
+ sys.exit
+
+align 4
+usage:
+ push dword usglen
+ push dword usg
+ push dword stderr
+ sys.write
+ push dword 3
+ sys.exit
+
+align 4
+global _start
+_start:
+ add esp, byte 8 ; discard argc and argv[0]
+ sub esi, esi
+
+.arg:
+ pop ecx
+ or ecx, ecx
+ je near .getenv ; no more arguments
+
+ ; ECX contains the pointer to an argument
+ cmp byte [ecx], '-'
+ jne usage
+
+ inc ecx
+ mov ax, [ecx]
+ inc ecx
+
+.o:
+ cmp al, 'o'
+ jne .i
+
+ ; Make sure we are not asked for the output file twice
+ cmp dword [fd.out], stdout
+ jne usage
+
+ ; Find the path to output file - it is either at [ECX+1],
+ ; i.e., -ofile --
+ ; or in the next argument,
+ ; i.e., -o file
+
+ or ah, ah
+ jne .openoutput
+ pop ecx
+ jecxz usage
+
+.openoutput:
+ push dword 420 ; file mode (644 octal)
+ push dword 0200h | 0400h | 01h
+ ; O_CREAT | O_TRUNC | O_WRONLY
+ push ecx
+ sys.open
+ jc near oerr
+
+ add esp, byte 12
+ mov [fd.out], eax
+ jmp short .arg
+
+.i:
+ cmp al, 'i'
+ jne .p
+
+ ; Make sure we are not asked twice
+ cmp dword [fd.in], stdin
+ jne near usage
+
+ ; Find the path to the input file
+ or ah, ah
+ jne .openinput
+ pop ecx
+ or ecx, ecx
+ je near usage
+
+.openinput:
+ push dword 0 ; O_RDONLY
+ push ecx
+ sys.open
+ jc near ierr ; open failed
+
+ add esp, byte 8
+ mov [fd.in], eax
+ jmp .arg
+
+.p:
+ cmp al, 'p'
+ jne .c
+ or ah, ah
+ jne .pcheck
+
+ pop ecx
+ or ecx, ecx
+ je near usage
+
+ mov ah, [ecx]
+
+.pcheck:
+ cmp ah, '0'
+ jl near usage
+ cmp ah, '9'
+ ja near usage
+ mov esi, ecx
+ jmp .arg
+
+.c:
+ cmp al, 'c'
+ jne .b
+ or ah, ah
+ jne near usage
+ mov esi, connors
+ jmp .arg
+
+.b:
+ cmp al, 'b'
+ jne .e
+ or ah, ah
+ jne near usage
+ mov esi, pinhole
+ jmp .arg
+
+.e:
+ cmp al, 'e'
+ jne near usage
+ or ah, ah
+ jne near usage
+ mov al, ','
+ mov [huhmsg], al
+ mov [separ], al
+ mov [sep2], al
+ mov [sep3], al
+ mov [sep4], al
+ jmp .arg
+
+align 4
+.getenv:
+ ; If ESI = 0, we did not have a -p argument,
+ ; and need to check the environment for "PINHOLE="
+ or esi, esi
+ jne .init
+
+ sub ecx, ecx
+
+.nextenv:
+ pop esi
+ or esi, esi
+ je .default ; no PINHOLE envar found
+
+ ; check if this envar starts with 'PINHOLE='
+ mov edi, envar
+ mov cl, 2 ; 'PINHOLE=' is 2 dwords long
+rep cmpsd
+ jne .nextenv
+
+ ; Check if it is followed by a digit
+ mov al, [esi]
+ cmp al, '0'
+ jl .default
+ cmp al, '9'
+ jbe .init
+ ; fall through
+
+align 4
+.default:
+ ; We got here because we had no -p argument,
+ ; and did not find the PINHOLE envar.
+ mov esi, pinhole
+ ; fall through
+
+align 4
+.init:
+ sub eax, eax
+ sub ebx, ebx
+ sub ecx, ecx
+ sub edx, edx
+ mov edi, dbuffer+1
+ mov byte [dbuffer], '0'
+
+ ; Convert the pinhole constant to real
+.constloop:
+ lodsb
+ cmp al, '9'
+ ja .setconst
+ cmp al, '0'
+ je .processconst
+ jb .setconst
+
+ inc dl
+
+.processconst:
+ inc cl
+ cmp cl, 18
+ ja near consttoobig
+ stosb
+ jmp short .constloop
+
+align 4
+.setconst:
+ or dl, dl
+ je near perr
+
+ finit
+ fild dword [tthou]
+
+ fld1
+ fild dword [ten]
+ fdivp st1, st0
+
+ fild dword [thousand]
+ mov edi, obuffer
+
+ mov ebp, ecx
+ call bcdload
+
+.constdiv:
+ fmul st0, st2
+ loop .constdiv
+
+ fld1
+ fadd st0, st0
+ fadd st0, st0
+ fld1
+ faddp st1, st0
+ fchs
+
+ ; If we are creating a CSV file,
+ ; print header
+ cmp byte [separ], ','
+ jne .bigloop
+
+ push dword headlen
+ push dword header
+ push dword [fd.out]
+ sys.write
+
+.bigloop:
+ call getchar
+ jc near done
+
+ ; Skip to the end of the line if you got '#'
+ cmp al, '#'
+ jne .num
+ call skiptoeol
+ jmp short .bigloop
+
+.num:
+ ; See if you got a number
+ cmp al, '0'
+ jl .bigloop
+ cmp al, '9'
+ ja .bigloop
+
+ ; Yes, we have a number
+ sub ebp, ebp
+ sub edx, edx
+
+.number:
+ cmp al, '0'
+ je .number0
+ mov dl, 1
+
+.number0:
+ or dl, dl ; Skip leading 0's
+ je .nextnumber
+ push eax
+ call putchar
+ pop eax
+ inc ebp
+ cmp ebp, 19
+ jae .nextnumber
+ mov [dbuffer+ebp], al
+
+.nextnumber:
+ call getchar
+ jc .work
+ cmp al, '#'
+ je .ungetc
+ cmp al, '0'
+ jl .work
+ cmp al, '9'
+ ja .work
+ jmp short .number
+
+.ungetc:
+ dec esi
+ inc ebx
+
+.work:
+ ; Now, do all the work
+ or dl, dl
+ je near .work0
+
+ cmp ebp, 19
+ jae near .toobig
+
+ call bcdload
+
+ ; Calculate pinhole diameter
+
+ fld st0 ; save it
+ fsqrt
+ fmul st0, st3
+ fld st0
+ fmul st5
+ sub ebp, ebp
+
+ ; Round off to 4 significant digits
+.diameter:
+ fcom st0, st7
+ fstsw ax
+ sahf
+ jb .printdiameter
+ fmul st0, st6
+ inc ebp
+ jmp short .diameter
+
+.printdiameter:
+ call printnumber ; pinhole diameter
+
+ ; Calculate F-number
+
+ fdivp st1, st0
+ fld st0
+
+ sub ebp, ebp
+
+.fnumber:
+ fcom st0, st6
+ fstsw ax
+ sahf
+ jb .printfnumber
+ fmul st0, st5
+ inc ebp
+ jmp short .fnumber
+
+.printfnumber:
+ call printnumber ; F number
+
+ ; Calculate normalized F-number
+ fmul st0, st0
+ fld1
+ fld st1
+ fyl2x
+ frndint
+ fld1
+ fscale
+ fsqrt
+ fstp st1
+
+ sub ebp, ebp
+ call printnumber
+
+ ; Calculate time multiplier from F-5.6
+
+ fscale
+ fld st0
+
+ ; Round off to 4 significant digits
+.fmul:
+ fcom st0, st6
+ fstsw ax
+ sahf
+
+ jb .printfmul
+ inc ebp
+ fmul st0, st5
+ jmp short .fmul
+
+.printfmul:
+ call printnumber ; F multiplier
+
+ ; Calculate F-stops from 5.6
+
+ fld1
+ fxch st1
+ fyl2x
+
+ sub ebp, ebp
+ call printnumber
+
+ mov al, 0Ah
+ call putchar
+ jmp .bigloop
+
+.work0:
+ mov al, '0'
+ call putchar
+
+align 4
+.toobig:
+ call huh
+ jmp .bigloop
+
+align 4
+done:
+ call write ; flush output buffer
+
+ ; close files
+ push dword [fd.in]
+ sys.close
+
+ push dword [fd.out]
+ sys.close
+
+ finit
+
+ ; return success
+ push dword 0
+ sys.exit
+
+align 4
+skiptoeol:
+ ; Keep reading until you come to cr, lf, or eof
+ call getchar
+ jc done
+ cmp al, 0Ah
+ jne .cr
+ ret
+
+.cr:
+ cmp al, 0Dh
+ jne skiptoeol
+ ret
+
+align 4
+getchar:
+ or ebx, ebx
+ jne .fetch
+
+ call read
+
+.fetch:
+ lodsb
+ dec ebx
+ clc
+ ret
+
+read:
+ jecxz .read
+ call write
+
+.read:
+ push dword BUFSIZE
+ mov esi, ibuffer
+ push esi
+ push dword [fd.in]
+ sys.read
+ add esp, byte 12
+ mov ebx, eax
+ or eax, eax
+ je .empty
+ sub eax, eax
+ ret
+
+align 4
+.empty:
+ add esp, byte 4
+ stc
+ ret
+
+align 4
+putchar:
+ stosb
+ inc ecx
+ cmp ecx, BUFSIZE
+ je write
+ ret
+
+align 4
+write:
+ jecxz .ret ; nothing to write
+ sub edi, ecx ; start of buffer
+ push ecx
+ push edi
+ push dword [fd.out]
+ sys.write
+ add esp, byte 12
+ sub eax, eax
+ sub ecx, ecx ; buffer is empty now
+.ret:
+ ret
+
+align 4
+bcdload:
+ ; EBP contains the number of chars in dbuffer
+ push ecx
+ push esi
+ push edi
+
+ lea ecx, [ebp+1]
+ lea esi, [dbuffer+ebp-1]
+ shr ecx, 1
+
+ std
+
+ mov edi, bbuffer
+ sub eax, eax
+ mov [edi], eax
+ mov [edi+4], eax
+ mov [edi+2], ax
+
+.loop:
+ lodsw
+ sub ax, 3030h
+ shl al, 4
+ or al, ah
+ mov [edi], al
+ inc edi
+ loop .loop
+
+ fbld [bbuffer]
+
+ cld
+ pop edi
+ pop esi
+ pop ecx
+ sub eax, eax
+ ret
+
+align 4
+printnumber:
+ push ebp
+ mov al, [separ]
+ call putchar
+
+ ; Print the integer at the TOS
+ mov ebp, bbuffer+9
+ fbstp [bbuffer]
+
+ ; Check the sign
+ mov al, [ebp]
+ dec ebp
+ or al, al
+ jns .leading
+
+ ; We got a negative number (should never happen)
+ mov al, '-'
+ call putchar
+
+.leading:
+ ; Skip leading zeros
+ mov al, [ebp]
+ dec ebp
+ or al, al
+ jne .first
+ cmp ebp, bbuffer
+ jae .leading
+
+ ; We are here because the result was 0.
+ ; Print '0' and return
+ mov al, '0'
+ jmp putchar
+
+.first:
+ ; We have found the first non-zero.
+ ; But it is still packed
+ test al, 0F0h
+ jz .second
+ push eax
+ shr al, 4
+ add al, '0'
+ call putchar
+ pop eax
+ and al, 0Fh
+
+.second:
+ add al, '0'
+ call putchar
+
+.next:
+ cmp ebp, bbuffer
+ jb .done
+
+ mov al, [ebp]
+ push eax
+ shr al, 4
+ add al, '0'
+ call putchar
+ pop eax
+ and al, 0Fh
+ add al, '0'
+ call putchar
+
+ dec ebp
+ jmp short .next
+
+.done:
+ pop ebp
+ or ebp, ebp
+ je .ret
+
+.zeros:
+ mov al, '0'
+ call putchar
+ dec ebp
+ jne .zeros
+
+.ret:
+ ret
+....
+
+Код следует тому же формату, что и все остальные фильтры, которые мы видели ранее, с одним небольшим исключением:
+
+____
+Мы больше не предполагаем, что конец ввода означает конец задач, как мы привыкли в фильтрах, _ориентированных на символы_.
+
+Этот фильтр не обрабатывает символы. Он обрабатывает _язык_ (хотя и очень простой, состоящий только из чисел).
+
+Когда у нас больше нет входных данных, это может означать одно из двух:
+
+* Мы закончили и можем выйти. Это то же самое, что и раньше.
+* Последний прочитанный символ был цифрой. Мы сохранили его в конце буфера преобразования ASCII в число с плавающей точкой. Теперь нам нужно преобразовать содержимое этого буфера в число и записать последнюю строку нашего вывода.
+
+По этой причине мы изменили наши подпрограммы `getchar` и `read`, чтобы они возвращались с _сброшенным_ флагом `carry`, когда получают очередной символ из ввода, или с _установленным_ флагом `carry`, когда ввода больше нет.
+
+Конечно, мы по-прежнему используем магию ассемблера для этого! Внимательно посмотрите на `getchar`. Он _всегда_ возвращает _очищенный_ `флаг переноса`.
+
+Тем не менее, наш основной код использует `флаг переноса` для определения момента завершения — и это работает.
+
+Волшебство кроется в `read`. Каждый раз, когда он получает больше входных данных от системы, он просто возвращается к `getchar`, который извлекает символ из входного буфера, _сбрасывает_ флаг переноса (`carry flag`) и возвращает управление.
+
+Но когда `read` больше не получает входных данных от системы, он _не_ возвращается к `getchar` вообще. Вместо этого, инструкция `add esp, byte 4` добавляет `4` к `ESP`, _устанавливает_ флаг переноса (`carry flag`) и возвращает управление.
+
+Итак, куда же она возвращается? Каждый раз, когда программа использует операцию `call`, микропроцессор делает ``push`` для адрес возврата, то есть сохраняет его на вершине стека (не стека FPU, а системного стека, который находится в памяти). Когда программа использует операцию `ret`, микропроцессор делает ``pop`` для значения возврата из стека и переходит по адресу, который там был сохранён.
+
+Но поскольку мы добавили `4` к `ESP` (который является регистром указателя стека), мы фактически вызвали у микропроцессора лёгкий случай _амнезии_: он больше не помнит, что именно `getchar` ``вызвал`` `read`.
+
+И поскольку `getchar` не делал ``push`` ни для чего перед вызовом `read`, верхушка стека теперь содержит адрес возврата к тому, что или кто вызывал `getchar`. С точки зрения этого вызывающего, он вызывал `getchar`, который вызвал ``ret`` с установленным `флагом переноса`!
+____
+
+Помимо этого, процедура `bcdload` оказывается втянута в лилипутский конфликт между Биг-Эндианцами и Литл-Эндианцами.
+
+Он преобразует текстовое представление числа в само число: текст хранится в порядке big-endian, но _упакованный десятичный_ формат имеет порядок little-endian.
+
+Для разрешения конфликта мы используем инструкцию процессора `std` в самом начале. Позже мы отменяем его с помощью `cld`: очень важно не вызывать ничего, что может зависеть от стандартного значения _флага направления_, пока активен `std`.
+
+Всё остальное в этом коде должно быть достаточно понятным, при условии, что вы прочитали всю предшествующую главу.
+
+Это классический пример поговорки о том, что программирование требует много размышлений и лишь немного кодирования. Как только мы продумаем каждую мельчайшую деталь, код практически напишется сам.
+
+[[x86-pinhole-using]]
+=== Использование программы pinhole
+
+Поскольку мы решили сделать так, чтобы программа _игнорировала_ любой ввод, кроме чисел (и даже их внутри комментария), мы можем выполнять _текстовые запросы_. Мы не _обязаны_ этого делать, но _можем_.
+
+По моему скромному мнению, формирование текстового запроса вместо необходимости следовать очень строгому синтаксису делает программное обеспечение гораздо более дружелюбным к пользователю.
+
+Предположим, мы хотим построить камеру-обскуру для использования плёнки размером 4x5 дюймов. Стандартное фокусное расстояние для такой плёнки составляет около 150 мм. Мы хотим _точно настроить_ фокусное расстояние, чтобы диаметр отверстия был как можно более круглым числом. Допустим также, что мы хорошо разбираемся в фотоаппаратах, но немного боимся компьютеров. Вместо того чтобы просто вводить кучу цифр, мы хотим _задать_ пару вопросов.
+
+Наша сессия может выглядеть так:
+
+[source, shell]
+....
+% pinhole
+
+Computer,
+
+What size pinhole do I need for the focal length of 150?
+150 490 306 362 2930 12
+Hmmm... How about 160?
+160 506 316 362 3125 12
+Let's make it 155, please.
+155 498 311 362 3027 12
+Ah, let's try 157...
+157 501 313 362 3066 12
+156?
+156 500 312 362 3047 12
+That's it! Perfect! Thank you very much!
+^D
+....
+
+Мы выяснили, что при фокусном расстоянии 150 мм диаметр отверстия должен составлять 490 микрон, или 0,49 мм, но если взять почти идентичное фокусное расстояние 156 мм, можно использовать отверстие диаметром ровно половину миллиметра.
+
+[[x86-pinhole-scripting]]
+=== Скриптинг
+
+Поскольку мы выбрали символ `+#+` для обозначения начала комментария, мы можем рассматривать наше программное обеспечение pinhole как _скриптовый язык_.
+
+Вы, вероятно, видели _сценарии_ оболочки, которые начинаются с:
+
+[.programlisting]
+....
+#! /bin/sh
+....
+
+...или...
+
+[.programlisting]
+....
+#!/bin/sh
+....
+
+...потому что пробел после `#!` необязателен.
+
+Когда UNIX(R) получает запрос на выполнение исполняемого файла, который начинается с `#!`, он предполагает, что это скрипт. Он добавляет команду к остальной части первой строки скрипта и пытается выполнить её.
+
+Предположим, что мы установили pinhole в /usr/local/bin/, теперь мы можем написать скрипт для расчёта различных диаметров отверстий, подходящих для различных фокусных расстояний, обычно используемых с плёнкой 120.
+
+Скрипт может выглядеть примерно так:
+
+[.programlisting]
+....
+#! /usr/local/bin/pinhole -b -i
+# Find the best pinhole diameter
+# for the 120 film
+
+### Standard
+80
+
+### Wide angle
+30, 40, 50, 60, 70
+
+### Telephoto
+100, 120, 140
+....
+
+Поскольку 120 — это плёнка среднего размера, мы можем назвать этот файл `medium`.
+
+Мы можем установить права на выполнение и запустить его, как если бы это была программа:
+
+[source, shell]
+....
+% chmod 755 medium
+% ./medium
+....
+
+UNIX(R) интерпретирует последнюю команду следующим образом:
+
+[source, shell]
+....
+% /usr/local/bin/pinhole -b -i ./medium
+....
+
+Он выполнит эту команду и отобразит:
+
+[source, shell]
+....
+80 358 224 256 1562 11
+30 219 137 128 586 9
+40 253 158 181 781 10
+50 283 177 181 977 10
+60 310 194 181 1172 10
+70 335 209 181 1367 10
+100 400 250 256 1953 11
+120 438 274 256 2344 11
+140 473 296 256 2734 11
+....
+
+Теперь введем:
+
+[source, shell]
+....
+% ./medium -c
+....
+
+UNIX(R) интерпретирует это следующим образом:
+
+[source, shell]
+....
+% /usr/local/bin/pinhole -b -i ./medium -c
+....
+
+Это дает ему два конфликтующих параметра: `-b` и `-c` (Использовать константу Бендера и использовать константу Коннорса). Мы запрограммировали его так, что более поздние параметры переопределяют ранние — наша программа будет вычислять все, используя константу Коннорса:
+
+[source, shell]
+....
+80 331 242 256 1826 11
+30 203 148 128 685 9
+40 234 171 181 913 10
+50 262 191 181 1141 10
+60 287 209 181 1370 10
+70 310 226 256 1598 11
+100 370 270 256 2283 11
+120 405 296 256 2739 11
+140 438 320 362 3196 12
+....
+
+Мы решаем, что всё же выбираем константу Бендера. Мы хотим сохранить её значения в виде файла с разделителями-запятыми:
+
+[source, shell]
+....
+% ./medium -b -e > bender
+% cat bender
+focal length in millimeters,pinhole diameter in microns,F-number,normalized F-number,F-5.6 multiplier,stops from F-5.6
+80,358,224,256,1562,11
+30,219,137,128,586,9
+40,253,158,181,781,10
+50,283,177,181,977,10
+60,310,194,181,1172,10
+70,335,209,181,1367,10
+100,400,250,256,1953,11
+120,438,274,256,2344,11
+140,473,296,256,2734,11
+%
+....
+
+[[x86-caveats]]
+== Предостережения
+
+Программисты на ассемблере, которые "выросли" на MS-DOS(R) и Windows(R), часто склонны искать короткие пути. Чтение скан-кодов клавиатуры и запись напрямую в видеопамять — это два классических примера подходов, которые в MS-DOS(R) не только не порицаются, но и считаются правильными.
+
+Причина? И BIOS ПК, и MS-DOS(R) печально известны своей медленной работой при выполнении этих операций.
+
+Вас может возникнуть соблазн продолжить подобные практики в среде UNIX(R). Например, я видел веб-сайт, который объясняет, как получить доступ к скан-кодам клавиатуры на популярном клоне UNIX(R).
+
+Это, как правило, *очень плохая идея* в среде UNIX(R)! Позвольте объяснить почему.
+
+[[x86-protected]]
+=== UNIX(R) защищен
+
+Прежде всего, это может быть просто невозможно. UNIX(R) работает в защищённом режиме. Только ядро и драйверы устройств имеют прямой доступ к аппаратному обеспечению. Возможно, какой-то конкретный клон UNIX(R) позволит вам читать скан-коды клавиатуры, но скорее всего настоящая операционная система UNIX(R) этого не допустит. И даже если одна версия разрешает это, следующая может запретить, так что ваше тщательно разработанное программное обеспечение может в одночасье устареть.
+
+[[x86-abstraction]]
+=== UNIX(R) — это работа с абстракциями
+
+Но существует гораздо более важная причина не пытаться обращаться к оборудованию напрямую (если, конечно, вы не пишете драйвер устройства), даже в UNIX(R)-подобных системах, которые позволяют это делать:
+
+_UNIX(R) — это работа с абстракциями!_
+
+Существует фундаментальное различие в философии проектирования между MS-DOS(R) и UNIX(R). MS-DOS(R) разрабатывалась как однопользовательская система. Она работает на компьютере, к которому напрямую подключены клавиатура и монитор. Ввод пользователя практически гарантированно поступает с этой клавиатуры. Вывод вашей программы почти всегда отображается на этом экране.
+
+Это НИКОГДА не гарантируется в UNIX(R). Довольно часто пользователь UNIX(R) перенаправляет ввод и вывод программы с помощью конвейеров и перенаправлений:
+
+[source, shell]
+....
+% program1 | program2 | program3 > file1
+....
+
+Если вы написали program2, ваш ввод поступает не с клавиатуры, а из вывода program1. Аналогично, ваш вывод не выводится на экран, а становится вводом для program3, чей вывод, в свою очередь, отправляется в [.filename]#file1#.
+
+Но это еще не все! Даже если вы убедились, что ваш ввод поступает с терминала, а вывод отправляется на терминал, нет гарантии, что терминал является ПК: его видеопамять может находиться не там, где вы ожидаете, а клавиатура может генерировать не PC-совместимые скан-коды. Это может быть Macintosh(R) или любой другой компьютер.
+
+Вот вы, возможно, покачаете головой: мое программное обеспечение написано на языке ассемблера для ПК, как оно может работать на Macintosh(R)? Но я не говорил, что ваше программное обеспечение будет работать на Macintosh(R), а лишь что его терминалом может быть Macintosh(R).
+
+В UNIX(R) терминал не обязательно должен быть напрямую подключён к компьютеру, на котором работает ваше программное обеспечение — он может находиться даже на другом континенте или, например, на другой планете. Вполне возможно, что пользователь Macintosh(R) в Австралии подключается к системе UNIX(R) в Северной Америке (или где-либо ещё) через telnet. Программное обеспечение работает на одном компьютере, а терминал находится на другом: если попытаться считать скан-коды, будут получены неверные данные!
+
+То же самое относится и к любому другому оборудованию: файл, который вы читаете, может находиться на диске, к которому у вас нет прямого доступа. Камера, с которой вы считываете изображения, может находиться на космическом корабле, соединённом с вами через спутники.
+
+Вот почему в UNIX(R) никогда нельзя делать никаких предположений о том, откуда поступают ваши данные и куда они направляются. Всегда позволяйте системе управлять физическим доступом к оборудованию.
+
+[NOTE]
+====
+Это предостережения, а не абсолютные правила. Возможны исключения. Например, если текстовый редактор определил, что работает на локальной машине, он может захотеть читать скан-коды напрямую для улучшенного управления. Я упоминаю эти предостережения не для того, чтобы сказать вам, что делать или чего не делать, а просто чтобы вы осознавали определённые подводные камни, которые ждут вас, если вы только что перешли с MS-DOS(R) на UNIX(R). Конечно, творческие люди часто нарушают правила, и это нормально, пока они осознают, что нарушают их, и понимают почему.
+====
+
+[[x86-acknowledgements]]
+== Благодарности
+
+Это руководство никогда бы не было создано без помощи многих опытных программистов FreeBSD из {freebsd-hackers}, которые терпеливо отвечали на мои вопросы и направляли меня в моих попытках изучить внутренние механизмы программирования в системе UNIX(R) в целом и в FreeBSD в частности.
+
+Томас М. Соммерс открыл дверь для меня. Его https://web.archive.org/web/20090914064615/http://www.codebreakers-journal.com/content/view/262/27[Как написать "Hello, world" на ассемблере в FreeBSD?] веб-страница стала моей первой встречей с примером программирования на ассемблере под FreeBSD.
+
+Джейк Буркхолдер держал дверь открытой, охотно отвечая на все мои вопросы и предоставляя примеры исходного кода на языке ассемблера.
+
+Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved.
diff --git a/documentation/content/ru/books/developers-handbook/x86/_index.po b/documentation/content/ru/books/developers-handbook/x86/_index.po
new file mode 100644
index 0000000000..325770cdce
--- /dev/null
+++ b/documentation/content/ru/books/developers-handbook/x86/_index.po
@@ -0,0 +1,11160 @@
+# SOME DESCRIPTIVE TITLE
+# Copyright (C) YEAR The FreeBSD Project
+# This file is distributed under the same license as the FreeBSD Documentation package.
+# Vladlen Popolitov <vladlenpopolitov@list.ru>, 2025.
+msgid ""
+msgstr ""
+"Project-Id-Version: FreeBSD Documentation VERSION\n"
+"POT-Creation-Date: 2025-10-12 22:16+0300\n"
+"PO-Revision-Date: 2025-09-26 04:45+0000\n"
+"Last-Translator: Vladlen Popolitov <vladlenpopolitov@list.ru>\n"
+"Language-Team: Russian <https://translate-dev.freebsd.org/projects/"
+"documentation/booksdevelopers-handbookx86_index/ru/>\n"
+"Language: ru\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
+"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
+"X-Generator: Weblate 4.17\n"
+
+#. type: Title =
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:15
+#, no-wrap
+msgid "x86 Assembly Language Programming"
+msgstr "Программирование на ассемблере x86"
+
+#. type: Yaml Front Matter Hash Value: title
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1
+#, no-wrap
+msgid "Chapter 11. x86 Assembly Language Programming"
+msgstr "Глава 11. Программирование на языке ассемблера для x86"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:53
+msgid "_This chapter was written by {stanislav}._"
+msgstr "_Эта глава была написана {stanislav}._"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:55
+#, no-wrap
+msgid "Synopsis"
+msgstr "Обзор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:59
+msgid ""
+"Assembly language programming under UNIX(R) is highly undocumented. It is "
+"generally assumed that no one would ever want to use it because various "
+"UNIX(R) systems run on different microprocessors, so everything should be "
+"written in C for portability."
+msgstr ""
+"Программирование на ассемблере в UNIX(R) крайне плохо документировано. "
+"Обычно предполагается, что никто не захочет его использовать, поскольку "
+"различные системы UNIX(R) работают на разных микропроцессорах, и поэтому всё "
+"должно быть написано на C для обеспечения переносимости."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:63
+msgid ""
+"In reality, C portability is quite a myth. Even C programs need to be "
+"modified when ported from one UNIX(R) to another, regardless of what "
+"processor each runs on. Typically, such a program is full of conditional "
+"statements depending on the system it is compiled for."
+msgstr ""
+"В действительности переносимость программ на C — это скорее миф. Даже "
+"программы на C требуют изменений при переносе с одной UNIX(R)-системы на "
+"другую, независимо от процессора, на котором они работают. Обычно такая "
+"программа содержит множество условных операторов, зависящих от системы, для "
+"которой она компилируется."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:65
+msgid ""
+"Even if we believe that all of UNIX(R) software should be written in C, or "
+"some other high-level language, we still need assembly language programmers: "
+"Who else would write the section of C library that accesses the kernel?"
+msgstr ""
+"Даже если мы считаем, что всё программное обеспечение UNIX(R) должно быть "
+"написано на C или другом языке высокого уровня, нам всё равно нужны "
+"программисты на ассемблере: кто же ещё напишет часть библиотеки C, которая "
+"обращается к ядру?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:67
+msgid ""
+"In this chapter I will attempt to show you how you can use assembly language "
+"writing UNIX(R) programs, specifically under FreeBSD."
+msgstr ""
+"В этой главе я попытаюсь показать вам, как можно использовать язык "
+"ассемблера для написания программ под UNIX(R), в частности под FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:72
+msgid ""
+"This chapter does not explain the basics of assembly language. There are "
+"enough resources about that (for a complete online course in assembly "
+"language, see Randall Hyde's http://webster.cs.ucr.edu/[Art of Assembly "
+"Language]; or if you prefer a printed book, take a look at Jeff Duntemann's "
+"Assembly Language Step-by-Step (ISBN: 0471375233). However, once the "
+"chapter is finished, any assembly language programmer will be able to write "
+"programs for FreeBSD quickly and efficiently."
+msgstr ""
+"В этой главе не объясняются основы языка ассемблера. Существует достаточно "
+"ресурсов на эту тему (например, полный онлайн-курс по языку ассемблера можно "
+"найти в http://webster.cs.ucr.edu/[Искусстве языка ассемблера] Рэндалла "
+"Хайда; если вы предпочитаете печатные книги, обратите внимание на «Язык "
+"ассемблера шаг за шагом» Джеффа Дантемана (ISBN: 0471375233)). Однако после "
+"прочтения этой главы любой программист на языке ассемблера сможет писать "
+"программы для FreeBSD быстро и эффективно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:74
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4311
+msgid "Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved."
+msgstr "Copyright (R) 2000-2001 G. Adam Stanislav. All rights reserved."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:76
+#, no-wrap
+msgid "The Tools"
+msgstr "Инструменты"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:79
+#, no-wrap
+msgid "The Assembler"
+msgstr "Ассемблер"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:82
+msgid ""
+"The most important tool for assembly language programming is the assembler, "
+"the software that converts assembly language code into machine language."
+msgstr ""
+"Важнейшим инструментом для программирования на языке ассемблера является "
+"ассемблер — программа, преобразующая код на языке ассемблера в машинный код."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:85
+msgid ""
+"Three very different assemblers are available for FreeBSD. Both man:llvm-"
+"as[1] (included in package:devel/llvm[]) and man:as[1] (included in "
+"package:devel/binutils[]) use the traditional UNIX(R) assembly language "
+"syntax."
+msgstr ""
+"Три очень разных ассемблера доступны для FreeBSD. И man:llvm-as[1] (включён "
+"в package:devel/llvm[]), и man:as[1] (включён в package:devel/binutils[]) "
+"используют традиционный синтаксис ассемблера UNIX(R)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:88
+msgid ""
+"On the other hand, man:nasm[1] (installed through package:devel/nasm[]) uses "
+"the Intel syntax. Its main advantage is that it can assemble code for many "
+"operating systems."
+msgstr ""
+"С другой стороны, man:nasm[1] (устанавливаемый через package:devel/nasm[]) "
+"использует синтаксис Intel. Его основное преимущество в том, что он может "
+"ассемблировать код для многих операционных систем."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:91
+msgid ""
+"This chapter uses nasm syntax because most assembly language programmers "
+"coming to FreeBSD from other operating systems will find it easier to "
+"understand. And, because, quite frankly, that is what I am used to."
+msgstr ""
+"В этой главе используется синтаксис nasm, потому что большинство "
+"программистов на ассемблере, приходящих в FreeBSD из других операционных "
+"систем, найдут его более понятным. Кроме того, если честно, это то, к чему я "
+"привык."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:93
+#, no-wrap
+msgid "The Linker"
+msgstr "Компоновщик"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:96
+msgid ""
+"The output of the assembler, like that of any compiler, needs to be linked "
+"to form an executable file."
+msgstr ""
+"Результат работы ассемблера, как и любого компилятора, необходимо связать, "
+"чтобы получить исполняемый файл."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:99
+msgid ""
+"The standard man:ld[1] linker comes with FreeBSD. It works with the code "
+"assembled with either assembler."
+msgstr ""
+"Стандартный компоновщик man:ld[1] поставляется с FreeBSD. Он работает с "
+"кодом, собранным любым из ассемблеров."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:101
+#, no-wrap
+msgid "System Calls"
+msgstr "Системные вызовы"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:104
+#, no-wrap
+msgid "Default Calling Convention"
+msgstr "Стандартное соглашение о вызовах"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:108
+msgid ""
+"By default, the FreeBSD kernel uses the C calling convention. Further, "
+"although the kernel is accessed using `int 80h`, it is assumed the program "
+"will call a function that issues `int 80h`, rather than issuing `int 80h` "
+"directly."
+msgstr ""
+"По умолчанию ядро FreeBSD использует соглашение о вызовах C. Кроме того, "
+"хотя доступ к ядру осуществляется с помощью `int 80h`, предполагается, что "
+"программа вызовет функцию, которая выполняет `int 80h`, а не будет выполнять "
+"`int 80h` напрямую."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:111
+msgid ""
+"This convention is very convenient, and quite superior to the Microsoft(R) "
+"convention used by MS-DOS(R). Why? Because the UNIX(R) convention allows "
+"any program written in any language to access the kernel."
+msgstr ""
+"Эта традиция очень удобна и значительно превосходит соглашение Microsoft(R), "
+"используемое в MS-DOS(R). Почему? Потому что соглашение UNIX(R) позволяет "
+"любой программе, написанной на любом языке, обращаться к ядру."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:114
+msgid ""
+"An assembly language program can do that as well. For example, we could "
+"open a file:"
+msgstr ""
+"Программа на ассемблере также может это сделать. Например, мы могли бы "
+"открыть файл:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:120
+#, no-wrap
+msgid ""
+"kernel:\n"
+"\tint\t80h\t; Call kernel\n"
+"\tret\n"
+msgstr ""
+"kernel:\n"
+"\tint\t80h\t; Call kernel\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:129
+#, no-wrap
+msgid ""
+"open:\n"
+"\tpush\tdword mode\n"
+"\tpush\tdword flags\n"
+"\tpush\tdword path\n"
+"\tmov\teax, 5\n"
+"\tcall\tkernel\n"
+"\tadd\tesp, byte 12\n"
+"\tret\n"
+msgstr ""
+"open:\n"
+"\tpush\tdword mode\n"
+"\tpush\tdword flags\n"
+"\tpush\tdword path\n"
+"\tmov\teax, 5\n"
+"\tcall\tkernel\n"
+"\tadd\tesp, byte 12\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:133
+msgid ""
+"This is a very clean and portable way of coding. If you need to port the "
+"code to a UNIX(R) system which uses a different interrupt, or a different "
+"way of passing parameters, all you need to change is the kernel procedure."
+msgstr ""
+"Это очень понятный и переносимый способ написания кода. Если вам нужно "
+"перенести код на UNIX(R)-систему, которая использует другое прерывание или "
+"другой способ передачи параметров, все, что вам нужно изменить, это "
+"процедуру kernel."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:137
+msgid ""
+"But assembly language programmers like to shave off cycles. The above "
+"example requires a `call/ret` combination. We can eliminate it by "
+"``push``ing an extra dword:"
+msgstr ""
+"Но программисты на ассемблере любят экономить такты. Приведённый выше пример "
+"требует комбинации `call/ret`. Мы можем исключить её, сделав ``push`` "
+"дополнительного двойного слова:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:148
+#, no-wrap
+msgid ""
+"open:\n"
+"\tpush\tdword mode\n"
+"\tpush\tdword flags\n"
+"\tpush\tdword path\n"
+"\tmov\teax, 5\n"
+"\tpush\teax\t\t; Or any other dword\n"
+"\tint\t80h\n"
+"\tadd\tesp, byte 16\n"
+msgstr ""
+"open:\n"
+"\tpush\tdword mode\n"
+"\tpush\tdword flags\n"
+"\tpush\tdword path\n"
+"\tmov\teax, 5\n"
+"\tpush\teax\t\t; Or any other dword\n"
+"\tint\t80h\n"
+"\tadd\tesp, byte 16\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:151
+msgid ""
+"The `5` that we have placed in `EAX` identifies the kernel function, in this "
+"case `open`."
+msgstr ""
+"Помещённое в `EAX` значение `5` идентифицирует функцию ядра, в данном случае "
+"`open`."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:153
+#, no-wrap
+msgid "Alternate Calling Convention"
+msgstr "Альтернативное соглашение о вызовах"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:158
+msgid ""
+"FreeBSD is an extremely flexible system. It offers other ways of calling "
+"the kernel. For it to work, however, the system must have Linux emulation "
+"installed."
+msgstr ""
+"FreeBSD — это чрезвычайно гибкая система. Она предлагает другие способы "
+"вызова ядра. Однако для работы необходимо, чтобы в системе была установлена "
+"эмуляция Linux."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:163
+msgid ""
+"Linux is a UNIX(R) like system. However, its kernel uses the same system-"
+"call convention of passing parameters in registers MS-DOS(R) does. As with "
+"the UNIX(R) convention, the function number is placed in `EAX`. The "
+"parameters, however, are not passed on the stack but in `EBX, ECX, EDX, ESI, "
+"EDI, EBP`:"
+msgstr ""
+"Linux — это система, подобная UNIX(R). Однако ее ядро использует то же "
+"соглашение о системных вызовов для передачи параметров в регистрах, что и MS-"
+"DOS(R). Как и в соглашении UNIX(R), номер функции помещается в `EAX`. Однако "
+"параметры передаются не в стеке, а в регистрах `EBX, ECX, EDX, ESI, EDI, "
+"EBP`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:172
+#, no-wrap
+msgid ""
+"open:\n"
+"\tmov\teax, 5\n"
+"\tmov\tebx, path\n"
+"\tmov\tecx, flags\n"
+"\tmov\tedx, mode\n"
+"\tint\t80h\n"
+msgstr ""
+"open:\n"
+"\tmov\teax, 5\n"
+"\tmov\tebx, path\n"
+"\tmov\tecx, flags\n"
+"\tmov\tedx, mode\n"
+"\tint\t80h\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:178
+msgid ""
+"This convention has a great disadvantage over the UNIX(R) way, at least as "
+"far as assembly language programming is concerned: Every time you make a "
+"kernel call you must `push` the registers, then `pop` them later. This "
+"makes your code bulkier and slower. Nevertheless, FreeBSD gives you a "
+"choice."
+msgstr ""
+"Этот подход имеет значительный недостаток по сравнению с UNIX(R), по крайней "
+"мере, в контексте программирования на ассемблере: каждый раз при вызове ядра "
+"необходимо сохранять регистры с помощью `push`, а затем восстанавливать их с "
+"помощью `pop`. Это делает ваш код более громоздким и медленным. Тем не "
+"менее, FreeBSD предоставляет вам выбор."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:181
+msgid ""
+"If you do choose the Linux convention, you must let the system know about "
+"it. After your program is assembled and linked, you need to brand the "
+"executable:"
+msgstr ""
+"Если вы решите использовать соглашение Linux, вы должны сообщить об этом "
+"системе. После того как ваша программа будет ассемблирована и слинкована, "
+"вам нужно пометить исполняемый файл:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:185
+#, no-wrap
+msgid "% brandelf -t Linux filename\n"
+msgstr "% brandelf -t Linux filename\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:188
+#, no-wrap
+msgid "Which Convention Should You Use?"
+msgstr "Какое соглашение следует использовать?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:193
+msgid ""
+"If you are coding specifically for FreeBSD, you should always use the "
+"UNIX(R) convention: It is faster, you can store global variables in "
+"registers, you do not have to brand the executable, and you do not impose "
+"the installation of the Linux emulation package on the target system."
+msgstr ""
+"Если вы разрабатываете код специально для FreeBSD, всегда следует "
+"использовать соглашение UNIX(R): это быстрее, вы можете хранить глобальные "
+"переменные в регистрах, вам не нужно маркировать исполняемый файл, и вы не "
+"требуете установки пакета эмуляции Linux на целевой системе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:196
+msgid ""
+"If you want to create portable code that can also run on Linux, you will "
+"probably still want to give the FreeBSD users as efficient a code as "
+"possible. I will show you how you can accomplish that after I have "
+"explained the basics."
+msgstr ""
+"Хотя вы можете хотеть создать переносимый код, который также работает на "
+"Linux, вам, вероятно, по-прежнему будет нужен максимально эффективный код "
+"для пользователей FreeBSD. Я покажу вам, как этого добиться, после того как "
+"объясню основы."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:198
+#, no-wrap
+msgid "Call Numbers"
+msgstr "Номера вызовов"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:202
+msgid ""
+"To tell the kernel which system service you are calling, place its number in "
+"`EAX`. Of course, you need to know what the number is."
+msgstr ""
+"Чтобы сообщить ядру, какую системную службу вы вызываете, поместите её номер "
+"в `EAX`. Разумеется, вам необходимо знать, что это за номер."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:204
+#, no-wrap
+msgid "The [.filename]#syscalls# File"
+msgstr "Файл [.filename]#syscalls#"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:208
+msgid ""
+"The numbers are listed in [.filename]#syscalls#. `locate syscalls` finds "
+"this file in several different formats, all produced automatically from "
+"[.filename]#syscalls.master#."
+msgstr ""
+"Номера перечислены в [.filename]#syscalls#. Команда `locate syscalls` "
+"находит этот файл в нескольких различных форматах, все они создаются "
+"автоматически из [.filename]#syscalls.master#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:211
+msgid ""
+"You can find the master file for the default UNIX(R) calling convention in "
+"[.filename]#/usr/src/sys/kern/syscalls.master#. If you need to use the "
+"other convention implemented in the Linux emulation mode, read [.filename]#/"
+"usr/src/sys/i386/linux/syscalls.master#."
+msgstr ""
+"Основной файл для стандартного соглашения о вызовах UNIX(R) можно найти в "
+"[.filename]#/usr/src/sys/kern/syscalls.master#. Если вам необходимо "
+"использовать другое соглашение, реализованное в режиме эмуляции Linux, "
+"обратитесь к [.filename]#/usr/src/sys/i386/linux/syscalls.master#."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:215
+msgid ""
+"Not only do FreeBSD and Linux use different calling conventions, they "
+"sometimes use different numbers for the same functions."
+msgstr ""
+"Не только FreeBSD и Linux используют разные соглашения о вызовах, но иногда "
+"они используют разные номера для одних и тех же функций."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:218
+msgid "[.filename]#syscalls.master# describes how the call is to be made:"
+msgstr ""
+"[.filename]#syscalls.master# описывает, как должен быть выполнен вызов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:229
+#, no-wrap
+msgid ""
+"0\tSTD\tNOHIDE\t{ int nosys(void); } syscall nosys_args int\n"
+"1\tSTD\tNOHIDE\t{ void exit(int rval); } exit rexit_args void\n"
+"2\tSTD\tPOSIX\t{ int fork(void); }\n"
+"3\tSTD\tPOSIX\t{ ssize_t read(int fd, void *buf, size_t nbyte); }\n"
+"4\tSTD\tPOSIX\t{ ssize_t write(int fd, const void *buf, size_t nbyte); }\n"
+"5\tSTD\tPOSIX\t{ int open(char *path, int flags, int mode); }\n"
+"6\tSTD\tPOSIX\t{ int close(int fd); }\n"
+"etc...\n"
+msgstr ""
+"0\tSTD\tNOHIDE\t{ int nosys(void); } syscall nosys_args int\n"
+"1\tSTD\tNOHIDE\t{ void exit(int rval); } exit rexit_args void\n"
+"2\tSTD\tPOSIX\t{ int fork(void); }\n"
+"3\tSTD\tPOSIX\t{ ssize_t read(int fd, void *buf, size_t nbyte); }\n"
+"4\tSTD\tPOSIX\t{ ssize_t write(int fd, const void *buf, size_t nbyte); }\n"
+"5\tSTD\tPOSIX\t{ int open(char *path, int flags, int mode); }\n"
+"6\tSTD\tPOSIX\t{ int close(int fd); }\n"
+"etc...\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:232
+msgid "It is the leftmost column that tells us the number to place in `EAX`."
+msgstr ""
+"Это крайний левый столбец, который указывает число, которое нужно поместить "
+"в `EAX`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:235
+msgid ""
+"The rightmost column tells us what parameters to `push`. They are "
+"``push``ed _from right to left_."
+msgstr ""
+"Самый правый столбец указывает, какие параметры нужно `втолкнуть` в стек "
+"командой push. Они `вталкиваются` _справа налево_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:237
+msgid ""
+"For example, to `open` a file, we need to `push` the `mode` first, then "
+"`flags`, then the address at which the `path` is stored."
+msgstr ""
+"Например, чтобы `открыть` файл, нам сначала нужно сделать `push` для `mode`, "
+"затем `flags`, а затем адрес, по которому хранится `path`."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:239
+#, no-wrap
+msgid "Return Values"
+msgstr "Возвращаемые значения"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:243
+msgid ""
+"A system call would not be useful most of the time if it did not return some "
+"kind of a value: The file descriptor of an open file, the number of bytes "
+"read to a buffer, the system time, etc."
+msgstr ""
+"От системных вызовов не было бы никакой пользы, если бы они не возвращали "
+"какое-либо значение: дескриптор открытого файла, количество байтов, "
+"прочитанных в буфер, системное время и т.д."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:246
+msgid ""
+"Additionally, the system needs to inform us if an error occurs: A file does "
+"not exist, system resources are exhausted, we passed an invalid parameter, "
+"etc."
+msgstr ""
+"Кроме того, система должна уведомлять нас, если возникает ошибка: файл не "
+"существует, системные ресурсы исчерпаны, передан недопустимый параметр и т. "
+"д."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:248
+#, no-wrap
+msgid "Man Pages"
+msgstr "Страницы справочника"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:252
+msgid ""
+"The traditional place to look for information about various system calls "
+"under UNIX(R) systems are the manual pages. FreeBSD describes its system "
+"calls in section 2, sometimes in section 3."
+msgstr ""
+"Традиционным источником информации о различных системных вызовах в UNIX(R)-"
+"системах являются страницы Справочника. В FreeBSD системные вызовы описаны в "
+"разделе 2, иногда в разделе 3."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:254
+msgid "For example, man:open[2] says:"
+msgstr "Например, man:open[2] говорит:"
+
+#. type: .blockquote
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:258
+msgid ""
+"If successful, `open()` returns a non-negative integer, termed a file "
+"descriptor. It returns `-1` on failure, and sets `errno` to indicate the "
+"error."
+msgstr ""
+"В случае успеха `open()` возвращает неотрицательное целое число, называемое "
+"файловым дескриптором. В случае ошибки возвращается `-1`, а переменной "
+"`errno` присваивается код ошибки."
+
+#. type: .blockquote
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:260
+msgid ""
+"The assembly language programmer new to UNIX(R) and FreeBSD will immediately "
+"ask the puzzling question: Where is `errno` and how do I get to it?"
+msgstr ""
+"Программист на ассемблере, впервые столкнувшийся с UNIX(R) и FreeBSD, сразу "
+"же задастся вопросом: где находится `errno` и как к ней обратиться?"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:265
+msgid ""
+"The information presented in the manual pages applies to C programs. The "
+"assembly language programmer needs additional information."
+msgstr ""
+"Информация, представленная в руководствах, применима к программам на языке "
+"C. Программистам на языке ассемблера требуется дополнительная информация."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:268
+#, no-wrap
+msgid "Where Are the Return Values?"
+msgstr "Где возвращаемые значения?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:273
+msgid ""
+"Unfortunately, it depends... For most system calls it is in `EAX`, but not "
+"for all. A good rule of thumb, when working with a system call for the "
+"first time, is to look for the return value in `EAX`. If it is not there, "
+"you need further research."
+msgstr ""
+"К сожалению, это зависит от ситуации... Для большинства системных вызовов "
+"возвращаемое значение находится в `EAX`, но не для всех. Хорошее правило при "
+"первой работе с системным вызовом — искать возвращаемое значение в `EAX`. "
+"Если его там нет, потребуется дополнительное исследование."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:279
+msgid ""
+"I am aware of one system call that returns the value in `EDX`: `SYS_fork`. "
+"All others I have worked with use `EAX`. But I have not worked with them "
+"all yet."
+msgstr ""
+"Я знаю о одном системном вызове, который возвращает значение в `EDX`: "
+"`SYS_fork`. Все остальные, с которыми я работал, используют `EAX`. Но я еще "
+"не работал со всеми из них."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:284
+msgid ""
+"If you cannot find the answer here or anywhere else, study libc source code "
+"and see how it interfaces with the kernel."
+msgstr ""
+"Если вы не можете найти ответ здесь или где-либо ещё, изучите исходный код "
+"libc и посмотрите, как он взаимодействует с ядром."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:287
+#, no-wrap
+msgid "Where Is `errno`?"
+msgstr "Где находится `errno`?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:290
+msgid "Actually, nowhere..."
+msgstr "Фактически, нигде..."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:293
+msgid ""
+"`errno` is part of the C language, not the UNIX(R) kernel. When accessing "
+"kernel services directly, the error code is returned in `EAX`, the same "
+"register the proper return value generally ends up in."
+msgstr ""
+"`errno` является частью языка C, а не ядра UNIX(R). При прямом доступе к "
+"сервисам ядра код ошибки возвращается в регистре `EAX` — том же регистре, в "
+"котором обычно оказывается корректное возвращаемое значение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:297
+msgid ""
+"This makes perfect sense. If there is no error, there is no error code. If "
+"there is an error, there is no return value. One register can contain "
+"either."
+msgstr ""
+"Это совершенно логично. Если нет ошибки, то нет и кода ошибки. Если есть "
+"ошибка, то нет возвращаемого значения. Один регистр может содержать либо то, "
+"либо другое."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:299
+#, no-wrap
+msgid "Determining an Error Occurred"
+msgstr "Определение возникновения ошибки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:302
+msgid ""
+"When using the standard FreeBSD calling convention, the `carry flag` is "
+"cleared upon success, set upon failure."
+msgstr ""
+"При использовании стандартного соглашения о вызовах FreeBSD флаг `carry "
+"flag` сбрасывается при успехе и устанавливается при неудаче."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:305
+msgid ""
+"When using the Linux emulation mode, the signed value in `EAX` is non-"
+"negative upon success, and contains the return value. In case of an error, "
+"the value is negative, i.e., `-errno`."
+msgstr ""
+"При использовании режима эмуляции Linux знаковое значение в `EAX` "
+"неотрицательно в случае успеха и содержит возвращаемое значение. В случае "
+"ошибки значение отрицательное, т.е. `-errno`."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:307
+#, no-wrap
+msgid "Creating Portable Code"
+msgstr "Создание переносимого кода"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:312
+msgid ""
+"Portability is generally not one of the strengths of assembly language. "
+"Yet, writing assembly language programs for different platforms is possible, "
+"especially with nasm. I have written assembly language libraries that can "
+"be assembled for such different operating systems as Windows(R) and FreeBSD."
+msgstr ""
+"Портативность обычно не является сильной стороной языка ассемблера. Тем не "
+"менее, написание программ на ассемблере для разных платформ возможно, "
+"особенно с использованием nasm. Я создавал библиотеки на ассемблере, которые "
+"можно было собрать для таких разных операционных систем, как Windows(R) и "
+"FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:314
+msgid ""
+"It is all the more possible when you want your code to run on two platforms "
+"which, while different, are based on similar architectures."
+msgstr ""
+"Это становится еще более возможным, когда вы хотите, чтобы ваш код работал "
+"на двух платформах, которые, хотя и различны, основаны на схожих "
+"архитектурах."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:318
+msgid ""
+"For example, FreeBSD is UNIX(R), Linux is UNIX(R) like. I only mentioned "
+"three differences between them (from an assembly language programmer's "
+"perspective): The calling convention, the function numbers, and the way of "
+"returning values."
+msgstr ""
+"Например, FreeBSD — это UNIX(R), а Linux — UNIX(R)-подобная система. Я "
+"упомянул лишь три различия между ними (с точки зрения программиста на "
+"ассемблере): соглашение о вызовах, номера функций и способ возврата значений."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:320
+#, no-wrap
+msgid "Dealing with Function Numbers"
+msgstr "Работа с номерами функций"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:325
+msgid ""
+"In many cases the function numbers are the same. However, even when they "
+"are not, the problem is easy to deal with: Instead of using numbers in your "
+"code, use constants which you have declared differently depending on the "
+"target architecture:"
+msgstr ""
+"Во многих случаях номера функций совпадают. Однако, даже если это не так, "
+"проблему легко решить: вместо использования чисел в коде применяйте "
+"константы, объявленные по-разному в зависимости от целевой архитектуры:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:333
+#, no-wrap
+msgid ""
+"%ifdef\tLINUX\n"
+"%define\tSYS_execve\t11\n"
+"%else\n"
+"%define\tSYS_execve\t59\n"
+"%endif\n"
+msgstr ""
+"%ifdef\tLINUX\n"
+"%define\tSYS_execve\t11\n"
+"%else\n"
+"%define\tSYS_execve\t59\n"
+"%endif\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:336
+#, no-wrap
+msgid "Dealing with Conventions"
+msgstr "Работа с соглашениями"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:339
+msgid ""
+"Both, the calling convention, and the return value (the `errno` problem) can "
+"be resolved with macros:"
+msgstr ""
+"Оба, соглашение о вызовах и возвращаемое значение (проблема `errno`) могут "
+"быть решены с помощью макросов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:343
+#, no-wrap
+msgid "%ifdef\tLINUX\n"
+msgstr "%ifdef\tLINUX\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:347
+#, no-wrap
+msgid ""
+"%macro\tsystem\t0\n"
+"\tcall\tkernel\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsystem\t0\n"
+"\tcall\tkernel\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:356
+#, no-wrap
+msgid ""
+"align 4\n"
+"kernel:\n"
+"\tpush\tebx\n"
+"\tpush\tecx\n"
+"\tpush\tedx\n"
+"\tpush\tesi\n"
+"\tpush\tedi\n"
+"\tpush\tebp\n"
+msgstr ""
+"align 4\n"
+"kernel:\n"
+"\tpush\tebx\n"
+"\tpush\tecx\n"
+"\tpush\tedx\n"
+"\tpush\tesi\n"
+"\tpush\tedi\n"
+"\tpush\tebp\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:363
+#, no-wrap
+msgid ""
+"\tmov\tebx, [esp+32]\n"
+"\tmov\tecx, [esp+36]\n"
+"\tmov\tedx, [esp+40]\n"
+"\tmov\tesi, [esp+44]\n"
+"\tmov\tebp, [esp+48]\n"
+"\tint\t80h\n"
+msgstr ""
+"\tmov\tebx, [esp+32]\n"
+"\tmov\tecx, [esp+36]\n"
+"\tmov\tedx, [esp+40]\n"
+"\tmov\tesi, [esp+44]\n"
+"\tmov\tebp, [esp+48]\n"
+"\tint\t80h\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:370
+#, no-wrap
+msgid ""
+"\tpop\tebp\n"
+"\tpop\tedi\n"
+"\tpop\tesi\n"
+"\tpop\tedx\n"
+"\tpop\tecx\n"
+"\tpop\tebx\n"
+msgstr ""
+"\tpop\tebp\n"
+"\tpop\tedi\n"
+"\tpop\tesi\n"
+"\tpop\tedx\n"
+"\tpop\tecx\n"
+"\tpop\tebx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:375
+#, no-wrap
+msgid ""
+"\tor\teax, eax\n"
+"\tjs\t.errno\n"
+"\tclc\n"
+"\tret\n"
+msgstr ""
+"\tor\teax, eax\n"
+"\tjs\t.errno\n"
+"\tclc\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:380
+#, no-wrap
+msgid ""
+".errno:\n"
+"\tneg\teax\n"
+"\tstc\n"
+"\tret\n"
+msgstr ""
+".errno:\n"
+"\tneg\teax\n"
+"\tstc\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:382
+#, no-wrap
+msgid "%else\n"
+msgstr "%else\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:386
+#, no-wrap
+msgid ""
+"%macro\tsystem\t0\n"
+"\tint\t80h\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsystem\t0\n"
+"\tint\t80h\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:388
+#, no-wrap
+msgid "%endif\n"
+msgstr "%endif\n"
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:391
+#, no-wrap
+msgid "Dealing with Other Portability Issues"
+msgstr "Устранение прочих проблем с переносимостью"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:395
+msgid ""
+"The above solutions can handle most cases of writing code portable between "
+"FreeBSD and Linux. Nevertheless, with some kernel services the differences "
+"are deeper."
+msgstr ""
+"Приведённые выше решения могут помочь в большинстве случаев написания кода, "
+"переносимого между FreeBSD и Linux. Тем не менее, с некоторыми сервисами "
+"ядра различия более глубокие."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:398
+msgid ""
+"In that case, you need to write two different handlers for those particular "
+"system calls, and use conditional assembly. Luckily, most of your code does "
+"something other than calling the kernel, so usually you will only need a few "
+"such conditional sections in your code."
+msgstr ""
+"В таком случае необходимо написать два разных обработчика для этих "
+"конкретных системных вызовов и использовать условную компиляцию. К счастью, "
+"большая часть вашего кода выполняет действия, отличные от вызовов ядра, "
+"поэтому обычно потребуется лишь несколько таких условных секций в коде."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:400
+#, no-wrap
+msgid "Using a Library"
+msgstr "Использование библиотеки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:404
+msgid ""
+"You can avoid portability issues in your main code altogether by writing a "
+"library of system calls. Create a separate library for FreeBSD, a different "
+"one for Linux, and yet other libraries for more operating systems."
+msgstr ""
+"Вы можете полностью избежать проблем с переносимостью в основном коде, "
+"написав библиотеку системных вызовов. Создайте отдельную библиотеку для "
+"FreeBSD, другую для Linux и ещё другие библиотеки для дополнительных "
+"операционных систем."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:409
+msgid ""
+"In your library, write a separate function (or procedure, if you prefer the "
+"traditional assembly language terminology) for each system call. Use the C "
+"calling convention of passing parameters. But still use `EAX` to pass the "
+"call number in. In that case, your FreeBSD library can be very simple, as "
+"many seemingly different functions can be just labels to the same code:"
+msgstr ""
+"В вашей библиотеке напишите отдельную функцию (или процедуру, если вы "
+"предпочитаете традиционную терминологию ассемблера) для каждого системного "
+"вызова. Используйте соглашение о вызовах C для передачи параметров. Однако "
+"по-прежнему передавайте номер вызова через `EAX`. В таком случае ваша "
+"библиотека FreeBSD может быть очень простой, так как множество внешне "
+"различных функций могут быть просто метками одного и того же кода:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:417
+#, no-wrap
+msgid ""
+"sys.open:\n"
+"sys.close:\n"
+"[etc...]\n"
+"\tint\t80h\n"
+"\tret\n"
+msgstr ""
+"sys.open:\n"
+"sys.close:\n"
+"[etc...]\n"
+"\tint\t80h\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:421
+msgid ""
+"Your Linux library will require more different functions. But even here you "
+"can group system calls using the same number of parameters:"
+msgstr ""
+"Ваша библиотека Linux потребует больше различных функций. Но даже здесь вы "
+"можете группировать системные вызовы, используя одинаковое количество "
+"параметров:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:432
+#, no-wrap
+msgid ""
+"sys.exit:\n"
+"sys.close:\n"
+"[etc... one-parameter functions]\n"
+"\tpush\tebx\n"
+"\tmov\tebx, [esp+12]\n"
+"\tint\t80h\n"
+"\tpop\tebx\n"
+"\tjmp\tsys.return\n"
+msgstr ""
+"sys.exit:\n"
+"sys.close:\n"
+"[etc... one-parameter functions]\n"
+"\tpush\tebx\n"
+"\tmov\tebx, [esp+12]\n"
+"\tint\t80h\n"
+"\tpop\tebx\n"
+"\tjmp\tsys.return\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:434
+#, no-wrap
+msgid "...\n"
+msgstr "...\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:440
+#, no-wrap
+msgid ""
+"sys.return:\n"
+"\tor\teax, eax\n"
+"\tjs\tsys.err\n"
+"\tclc\n"
+"\tret\n"
+msgstr ""
+"sys.return:\n"
+"\tor\teax, eax\n"
+"\tjs\tsys.err\n"
+"\tclc\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:445
+#, no-wrap
+msgid ""
+"sys.err:\n"
+"\tneg\teax\n"
+"\tstc\n"
+"\tret\n"
+msgstr ""
+"sys.err:\n"
+"\tneg\teax\n"
+"\tstc\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:452
+msgid ""
+"The library approach may seem inconvenient at first because it requires you "
+"to produce a separate file your code depends on. But it has many "
+"advantages: For one, you only need to write it once and can use it for all "
+"your programs. You can even let other assembly language programmers use it, "
+"or perhaps use one written by someone else. But perhaps the greatest "
+"advantage of the library is that your code can be ported to other systems, "
+"even by other programmers, by simply writing a new library without any "
+"changes to your code."
+msgstr ""
+"Подход с использованием библиотек может показаться неудобным на первый "
+"взгляд, так как требует создания отдельного файла, от которого зависит ваш "
+"код. Однако у него есть множество преимуществ: во-первых, вам нужно написать "
+"его лишь один раз, и затем вы можете использовать его во всех своих "
+"программах. Вы даже можете позволить другим программистам на ассемблере "
+"использовать его или, возможно, воспользоваться библиотекой, написанной кем-"
+"то другим. Но, пожалуй, самое большое преимущество библиотеки заключается в "
+"том, что ваш код может быть перенесён на другие системы, даже другими "
+"программистами, просто путём написания новой библиотеки без каких-либо "
+"изменений в вашем коде."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:454
+msgid ""
+"If you do not like the idea of having a library, you can at least place all "
+"your system calls in a separate assembly language file and link it with your "
+"main program. Here, again, all porters have to do is create a new object "
+"file to link with your main program."
+msgstr ""
+"Если вам не нравится идея использования библиотеки, вы можете хотя бы "
+"разместить все системные вызовы в отдельном файле на ассемблере и "
+"скомпоновать его с основной программой. Здесь, опять же, все, что нужно "
+"сделать переносчикам, — это создать новый объектный файл для компоновки с "
+"основной программой."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:456
+#, no-wrap
+msgid "Using an Include File"
+msgstr "Использование включаемого файла"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:459
+msgid ""
+"If you are releasing your software as (or with) source code, you can use "
+"macros and place them in a separate file, which you include in your code."
+msgstr ""
+"Если вы выпускаете своё программное обеспечение в виде исходного кода (или "
+"вместе с ним), вы можете использовать макросы и размещать их в отдельном "
+"файле, который включается в ваш код."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:462
+msgid ""
+"Porters of your software will simply write a new include file. No library "
+"or external object file is necessary, yet your code is portable without any "
+"need to edit the code."
+msgstr ""
+"Портеры вашего программного обеспечения просто напишут новый include-файл. "
+"Никакая библиотека или внешний объектный файл не требуются, и ваш код "
+"остается переносимым без необходимости редактирования."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:467
+msgid ""
+"This is the approach we will use throughout this chapter. We will name our "
+"include file [.filename]#system.inc#, and add to it whenever we deal with a "
+"new system call."
+msgstr ""
+"Это подход, который мы будем использовать на протяжении всей главы. Мы "
+"назовем наш включаемый файл [.filename]#system.inc# и будем добавлять в него "
+"новые системные вызовы по мере их рассмотрения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:470
+msgid ""
+"We can start our [.filename]#system.inc# by declaring the standard file "
+"descriptors:"
+msgstr ""
+"Мы можем начать наш [.filename]#system.inc# с объявления стандартных "
+"файловых дескрипторов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:476
+#, no-wrap
+msgid ""
+"%define\tstdin\t0\n"
+"%define\tstdout\t1\n"
+"%define\tstderr\t2\n"
+msgstr ""
+"%define\tstdin\t0\n"
+"%define\tstdout\t1\n"
+"%define\tstderr\t2\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:479
+msgid "Next, we create a symbolic name for each system call:"
+msgstr "Далее мы создаем символическое имя для каждого системного вызова:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:488
+#, no-wrap
+msgid ""
+"%define\tSYS_nosys\t0\n"
+"%define\tSYS_exit\t1\n"
+"%define\tSYS_fork\t2\n"
+"%define\tSYS_read\t3\n"
+"%define\tSYS_write\t4\n"
+"; [etc...]\n"
+msgstr ""
+"%define\tSYS_nosys\t0\n"
+"%define\tSYS_exit\t1\n"
+"%define\tSYS_fork\t2\n"
+"%define\tSYS_read\t3\n"
+"%define\tSYS_write\t4\n"
+"; [etc...]\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:491
+msgid ""
+"We add a short, non-global procedure with a long name, so we do not "
+"accidentally reuse the name in our code:"
+msgstr ""
+"Добавляем короткую, неглобальную процедуру с длинным именем, чтобы случайно "
+"не использовать это имя в нашем коде:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:499
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"align 4\n"
+"access.the.bsd.kernel:\n"
+"\tint\t80h\n"
+"\tret\n"
+msgstr ""
+"section\t.text\n"
+"align 4\n"
+"access.the.bsd.kernel:\n"
+"\tint\t80h\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:502
+msgid "We create a macro which takes one argument, the syscall number:"
+msgstr ""
+"Мы создаем макрос, который принимает один аргумент — номер системного вызова:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:509
+#, no-wrap
+msgid ""
+"%macro\tsystem\t1\n"
+"\tmov\teax, %1\n"
+"\tcall\taccess.the.bsd.kernel\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsystem\t1\n"
+"\tmov\teax, %1\n"
+"\tcall\taccess.the.bsd.kernel\n"
+"%endmacro\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:513
+msgid ""
+"Finally, we create macros for each syscall. These macros take no arguments."
+msgstr ""
+"Наконец, мы создаем макросы для каждого системного вызова. Эти макросы не "
+"принимают аргументов."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:519
+#, no-wrap
+msgid ""
+"%macro\tsys.exit\t0\n"
+"\tsystem\tSYS_exit\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.exit\t0\n"
+"\tsystem\tSYS_exit\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:523
+#, no-wrap
+msgid ""
+"%macro\tsys.fork\t0\n"
+"\tsystem\tSYS_fork\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.fork\t0\n"
+"\tsystem\tSYS_fork\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:527
+#, no-wrap
+msgid ""
+"%macro\tsys.read\t0\n"
+"\tsystem\tSYS_read\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.read\t0\n"
+"\tsystem\tSYS_read\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:531
+#, no-wrap
+msgid ""
+"%macro\tsys.write\t0\n"
+"\tsystem\tSYS_write\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.write\t0\n"
+"\tsystem\tSYS_write\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:533
+#, no-wrap
+msgid "; [etc...]\n"
+msgstr "; [etc...]\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:537
+msgid ""
+"Go ahead, enter it into your editor and save it as [.filename]#system.inc#. "
+"We will add more to it as we discuss more syscalls."
+msgstr ""
+"Продолжайте, введите это в ваш редактор и сохраните как "
+"[.filename]#system.inc#. Мы добавим больше по мере обсуждения дополнительных "
+"системных вызовов."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:539
+#, no-wrap
+msgid "Our First Program"
+msgstr "Наша первая программа"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:542
+msgid "We are now ready for our first program, the mandatory Hello, World!"
+msgstr "Мы готовы к нашей первой обязательной программе — Hello, World!"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:546
+#, no-wrap
+msgid "\t%include\t'system.inc'\n"
+msgstr "\t%include\t'system.inc'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:550
+#, no-wrap
+msgid ""
+"\tsection\t.data\n"
+"\thello\tdb\t'Hello, World!', 0Ah\n"
+"\thbytes\tequ\t$-hello\n"
+msgstr ""
+"\tsection\t.data\n"
+"\thello\tdb\t'Hello, World!', 0Ah\n"
+"\thbytes\tequ\t$-hello\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:558
+#, no-wrap
+msgid ""
+"\tsection\t.text\n"
+"\tglobal\t_start\n"
+"_start:\n"
+"\tpush\tdword hbytes\n"
+"\tpush\tdword hello\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"\tsection\t.text\n"
+"\tglobal\t_start\n"
+"_start:\n"
+"\tpush\tdword hbytes\n"
+"\tpush\tdword hello\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:561
+#, no-wrap
+msgid ""
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:564
+msgid ""
+"Here is what it does: Line 1 includes the defines, the macros, and the code "
+"from [.filename]#system.inc#."
+msgstr ""
+"Вот что он делает: Строка 1 включает определения, макросы и код из файла "
+"[.filename]#system.inc#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:568
+msgid ""
+"Lines 3-5 are the data: Line 3 starts the data section/segment. Line 4 "
+"contains the string \"Hello, World!\" followed by a new line (`0Ah`). Line "
+"5 creates a constant that contains the length of the string from line 4 in "
+"bytes."
+msgstr ""
+"Строки 3-5 содержат данные: строка 3 начинает раздел/сегмент данных. Строка "
+"4 содержит строку \"Hello, World!\", за которой следует новая строка "
+"(`0Ah`). Строка 5 создает константу, содержащую длину строки из строки 4 в "
+"байтах."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:572
+msgid ""
+"Lines 7-16 contain the code. Note that FreeBSD uses the _elf_ file format "
+"for its executables, which requires every program to start at the point "
+"labeled `_start` (or, more precisely, the linker expects that). This label "
+"has to be global."
+msgstr ""
+"Строки 7-16 содержат код. Обратите внимание, что FreeBSD использует формат "
+"файлов _elf_ для исполняемых файлов, который требует, чтобы каждая программа "
+"запускается с адреса, помеченного как `_start` (или, точнее, компоновщик "
+"ожидает этого). Эта метка должна быть глобальной."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:574
+msgid ""
+"Lines 10-13 ask the system to write `hbytes` bytes of the `hello` string to "
+"`stdout`."
+msgstr ""
+"Строки 10-13 указывают системе записать `hbytes` байтов строки `hello` в "
+"`stdout`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:577
+msgid ""
+"Lines 15-16 ask the system to end the program with the return value of `0`. "
+"The `SYS_exit` syscall never returns, so the code ends there."
+msgstr ""
+"Строки 15-16 указывают системе завершить программу с возвращаемым значением "
+"`0`. Системный вызов `SYS_exit` никогда не возвращает управление, поэтому "
+"код завершается в этой точке."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:585
+msgid ""
+"If you have come to UNIX(R) from MS-DOS(R) assembly language background, you "
+"may be used to writing directly to the video hardware. You will never have "
+"to worry about this in FreeBSD, or any other flavor of UNIX(R). As far as "
+"you are concerned, you are writing to a file known as [.filename]#stdout#. "
+"This can be the video screen, or a telnet terminal, or an actual file, or "
+"even the input of another program. Which one it is, is for the system to "
+"figure out."
+msgstr ""
+"Если вы перешли на UNIX(R) с опытом программирования на ассемблере для MS-"
+"DOS(R), вы, возможно, привыкли писать напрямую в видеопамять. В FreeBSD или "
+"любой другой разновидности UNIX(R) вам не придётся об этом беспокоиться. С "
+"вашей точки зрения, вы записываете данные в файл под названием "
+"[.filename]#stdout#. Это может быть экран, терминал telnet, обычный файл или "
+"даже входные данные другой программы. Определять, что именно это будет, — "
+"задача системы."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:588
+#, no-wrap
+msgid "Assembling the Code"
+msgstr "Ассемблирование кода"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:592
+msgid ""
+"Type the code in an editor, and save it in a file named "
+"[.filename]#hello.asm#. You need nasm to assemble it."
+msgstr ""
+"Наберите код в редакторе и сохраните его в файле с именем "
+"[.filename]#hello.asm#. Для сборки вам понадобится nasm."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:594
+#, no-wrap
+msgid "Installing nasm"
+msgstr "Установка nasm"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:597
+msgid "If you do not have nasm, type:"
+msgstr "Если у вас нет nasm, введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:606
+#, no-wrap
+msgid ""
+"% su\n"
+"Password:your root password\n"
+"# cd /usr/ports/devel/nasm\n"
+"# make install\n"
+"# exit\n"
+"%\n"
+msgstr ""
+"% su\n"
+"Password:your root password\n"
+"# cd /usr/ports/devel/nasm\n"
+"# make install\n"
+"# exit\n"
+"%\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:609
+msgid ""
+"You may type `make install clean` instead of just `make install` if you do "
+"not want to keep nasm source code."
+msgstr ""
+"Вы можете ввести `make install clean` вместо просто `make install`, если не "
+"хотите сохранять исходный код nasm."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:611
+msgid ""
+"Either way, FreeBSD will automatically download nasm from the Internet, "
+"compile it, and install it on your system."
+msgstr ""
+"В любом случае FreeBSD автоматически загрузит nasm из интернета, "
+"скомпилирует его и установит в вашу систему."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:616
+msgid ""
+"If your system is not FreeBSD, you need to get nasm from its https://"
+"sourceforge.net/projects/nasm[home page]. You can still use it to assemble "
+"FreeBSD code."
+msgstr ""
+"Если ваша система не FreeBSD, вам нужно получить nasm с его https://"
+"sourceforge.net/projects/nasm[домашней страницы]. Вы по-прежнему можете "
+"использовать его для ассемблирования кода FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:619
+msgid "Now you can assemble, link, and run the code:"
+msgstr "Теперь вы можете собрать, скомпоновать и запустить код:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:627
+#, no-wrap
+msgid ""
+"% nasm -f elf hello.asm\n"
+"% ld -s -o hello hello.o\n"
+"% ./hello\n"
+"Hello, World!\n"
+"%\n"
+msgstr ""
+"% nasm -f elf hello.asm\n"
+"% ld -s -o hello hello.o\n"
+"% ./hello\n"
+"Hello, World!\n"
+"%\n"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:630
+#, no-wrap
+msgid "Writing UNIX(R) Filters"
+msgstr "Написание фильтров UNIX(R)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:633
+msgid ""
+"A common type of UNIX(R) application is a filter-a program that reads data "
+"from the [.filename]#stdin#, processes it somehow, then writes the result to "
+"[.filename]#stdout#."
+msgstr ""
+"Распространённым типом приложений в UNIX(R) являются фильтры — программы, "
+"которые читают данные из [.filename]#stdin#, обрабатывают их определённым "
+"образом, а затем записывают результат в [.filename]#stdout#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:636
+msgid ""
+"In this chapter, we shall develop a simple filter, and learn how to read "
+"from [.filename]#stdin# and write to [.filename]#stdout#. This filter will "
+"convert each byte of its input into a hexadecimal number followed by a blank "
+"space."
+msgstr ""
+"В этой главе мы разработаем простой фильтр и научимся читать из "
+"[.filename]#stdin# и писать в [.filename]#stdout#. Этот фильтр будет "
+"преобразовывать каждый байт входных данных в шестнадцатеричное число, за "
+"которым следует пробел."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:640
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:734
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:824
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:952
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1219
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2337
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3335
+#, no-wrap
+msgid "%include\t'system.inc'\n"
+msgstr "%include\t'system.inc'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:644
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:738
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+"buffer\tdb\t0, 0, ' '\n"
+msgstr ""
+"section\t.data\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+"buffer\tdb\t0, 0, ' '\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:656
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\t; read a byte from stdin\n"
+"\tpush\tdword 1\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+msgstr ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\t; read a byte from stdin\n"
+"\tpush\tdword 1\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:666
+#, no-wrap
+msgid ""
+"\t; convert it to hex\n"
+"\tmovzx\teax, byte [buffer]\n"
+"\tmov\tedx, eax\n"
+"\tshr\tdl, 4\n"
+"\tmov\tdl, [hex+edx]\n"
+"\tmov\t[buffer], dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tmov\t[buffer+1], al\n"
+msgstr ""
+"\t; convert it to hex\n"
+"\tmovzx\teax, byte [buffer]\n"
+"\tmov\tedx, eax\n"
+"\tshr\tdl, 4\n"
+"\tmov\tdl, [hex+edx]\n"
+"\tmov\t[buffer], dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tmov\t[buffer+1], al\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:674
+#, no-wrap
+msgid ""
+"\t; print it\n"
+"\tpush\tdword 3\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tjmp\tshort _start\n"
+msgstr ""
+"\t; print it\n"
+"\tpush\tdword 3\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tjmp\tshort _start\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:678
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:781
+#, no-wrap
+msgid ""
+".done:\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+".done:\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:686
+msgid ""
+"In the data section we create an array called `hex`. It contains the 16 "
+"hexadecimal digits in ascending order. The array is followed by a buffer "
+"which we will use for both input and output. The first two bytes of the "
+"buffer are initially set to `0`. This is where we will write the two "
+"hexadecimal digits (the first byte also is where we will read the input). "
+"The third byte is a space."
+msgstr ""
+"В разделе данных мы создаем массив с именем `hex`. Он содержит 16 "
+"шестнадцатеричных цифр в порядке возрастания. За массивом следует буфер, "
+"который мы будем использовать как для ввода, так и для вывода. Первые два "
+"байта буфера изначально установлены в `0`. Именно сюда мы будем записывать "
+"две шестнадцатеричные цифры (первый байт также является местом, откуда мы "
+"будем считывать ввод). Третий байт — это пробел."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:688
+msgid ""
+"The code section consists of four parts: Reading the byte, converting it to "
+"a hexadecimal number, writing the result, and eventually exiting the program."
+msgstr ""
+"Фрагмент кода состоит из четырех частей: чтение байта, преобразование его в "
+"шестнадцатеричное число, запись результата и завершение программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:694
+msgid ""
+"To read the byte, we ask the system to read one byte from "
+"[.filename]#stdin#, and store it in the first byte of the `buffer`. The "
+"system returns the number of bytes read in `EAX`. This will be `1` while "
+"data is coming, or `0`, when no more input data is available. Therefore, we "
+"check the value of `EAX`. If it is `0`, we jump to `.done`, otherwise we "
+"continue."
+msgstr ""
+"Для чтения байта мы просим систему прочитать один байт из [.filename]#stdin# "
+"и сохранить его в первом байте `buffer`. Система возвращает количество "
+"прочитанных байтов в `EAX`. Это значение будет `1`, пока поступают данные, "
+"или `0`, если больше нет доступных входных данных. Поэтому мы проверяем "
+"значение `EAX`. Если оно равно `0`, мы переходим к метке `.done`, в "
+"противном случае продолжаем выполнение."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:698
+msgid ""
+"For simplicity sake, we are ignoring the possibility of an error condition "
+"at this time."
+msgstr "Для простоты мы пока игнорируем возможность возникновения ошибки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:703
+msgid ""
+"The hexadecimal conversion reads the byte from the `buffer` into `EAX`, or "
+"actually just `AL`, while clearing the remaining bits of `EAX` to zeros. We "
+"also copy the byte to `EDX` because we need to convert the upper four bits "
+"(nibble) separately from the lower four bits. We store the result in the "
+"first two bytes of the buffer."
+msgstr ""
+"Шестнадцатеричное преобразование считывает байт из `buffer` в `EAX`, а "
+"точнее только в `AL`, обнуляя остальные биты `EAX`. Мы также копируем байт в "
+"`EDX`, потому что нам нужно преобразовать верхние четыре бита (ниббл) "
+"отдельно от нижних четырех битов. Результат сохраняется в первых двух байтах "
+"буфера."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:706
+msgid ""
+"Next, we ask the system to write the three bytes of the buffer, i.e., the "
+"two hexadecimal digits and the blank space, to [.filename]#stdout#. We then "
+"jump back to the beginning of the program and process the next byte."
+msgstr ""
+"Далее мы просим систему записать три байта буфера, то есть две "
+"шестнадцатеричные цифры и пробел, в [.filename]#stdout#. Затем мы "
+"возвращаемся к началу программы и обрабатываем следующий байт."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:708
+msgid ""
+"Once there is no more input left, we ask the system to exit our program, "
+"returning a zero, which is the traditional value meaning the program was "
+"successful."
+msgstr ""
+"Когда ввод больше не остаётся, мы просим систему завершить нашу программу, "
+"возвращая ноль, что традиционно означает успешное выполнение программы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:710
+msgid ""
+"Go ahead, and save the code in a file named [.filename]#hex.asm#, then type "
+"the following (the `^D` means press the control key and type `D` while "
+"holding the control key down):"
+msgstr ""
+"Продолжайте и сохраните код в файле с именем [.filename]#hex.asm#, затем "
+"введите следующее (символ `^D` означает, что нужно нажать клавишу управления "
+"и, удерживая её, ввести `D`):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:719
+#, no-wrap
+msgid ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come!\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D %\n"
+msgstr ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A Here I come!\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A ^D %\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:725
+msgid ""
+"If you are migrating to UNIX(R) from MS-DOS(R), you may be wondering why "
+"each line ends with `0A` instead of `0D 0A`. This is because UNIX(R) does "
+"not use the cr/lf convention, but a \"new line\" convention, which is `0A` "
+"in hexadecimal."
+msgstr ""
+"Если вы переходите на UNIX(R) с MS-DOS(R), вам может быть интересно, почему "
+"каждая строка заканчивается на `0A` вместо `0D 0A`. Это связано с тем, что "
+"UNIX(R) не использует соглашение cr/lf, а использует соглашение \"новая "
+"строка\", которое в шестнадцатеричном виде представлено как `0A`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:730
+msgid ""
+"Can we improve this? Well, for one, it is a bit confusing because once we "
+"have converted a line of text, our input no longer starts at the beginning "
+"of the line. We can modify it to print a new line instead of a space after "
+"each `0A`:"
+msgstr ""
+"Можем ли мы это улучшить? Что ж, во-первых, это немного запутанно, потому "
+"что после преобразования строки текста наш ввод больше не начинается с "
+"начала строки. Мы можем изменить это, чтобы после каждого `0A` выводилась "
+"новая строка вместо пробела:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:743
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\tmov\tcl, ' '\n"
+msgstr ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\tmov\tcl, ' '\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:753
+#, no-wrap
+msgid ""
+".loop:\n"
+"\t; read a byte from stdin\n"
+"\tpush\tdword 1\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+msgstr ""
+".loop:\n"
+"\t; read a byte from stdin\n"
+"\tpush\tdword 1\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:760
+#, no-wrap
+msgid ""
+"\t; convert it to hex\n"
+"\tmovzx\teax, byte [buffer]\n"
+"\tmov\t[buffer+2], cl\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.hex\n"
+"\tmov\t[buffer+2], al\n"
+msgstr ""
+"\t; convert it to hex\n"
+"\tmovzx\teax, byte [buffer]\n"
+"\tmov\t[buffer+2], cl\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.hex\n"
+"\tmov\t[buffer+2], al\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:769
+#, no-wrap
+msgid ""
+".hex:\n"
+"\tmov\tedx, eax\n"
+"\tshr\tdl, 4\n"
+"\tmov\tdl, [hex+edx]\n"
+"\tmov\t[buffer], dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tmov\t[buffer+1], al\n"
+msgstr ""
+".hex:\n"
+"\tmov\tedx, eax\n"
+"\tshr\tdl, 4\n"
+"\tmov\tdl, [hex+edx]\n"
+"\tmov\t[buffer], dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tmov\t[buffer+1], al\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:777
+#, no-wrap
+msgid ""
+"\t; print it\n"
+"\tpush\tdword 3\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tjmp\tshort .loop\n"
+msgstr ""
+"\t; print it\n"
+"\tpush\tdword 3\n"
+"\tpush\tdword buffer\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tjmp\tshort .loop\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:785
+msgid ""
+"We have stored the space in the `CL` register. We can do this safely "
+"because, unlike Microsoft(R) Windows(R), UNIX(R) system calls do not modify "
+"the value of any register they do not use to return a value in."
+msgstr ""
+"Мы сохранили пробел в регистре `CL`. Это безопасно, потому что, в отличие от "
+"Microsoft(R) Windows(R), вызовы системы UNIX(R) не изменяют значение "
+"регистров, которые не используются для возврата значения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:789
+msgid ""
+"That means we only need to set `CL` once. We have, therefore, added a new "
+"label `.loop` and jump to it for the next byte instead of jumping at "
+"`_start`. We have also added the `.hex` label so we can either have a blank "
+"space or a new line as the third byte of the `buffer`."
+msgstr ""
+"Это означает, что нам нужно установить `CL` только один раз. Поэтому мы "
+"добавили новую метку `.loop` и переходим к ней для следующего байта вместо "
+"перехода к `_start`. Мы также добавили метку `.hex`, чтобы третий байт "
+"`buffer` мог быть либо пробелом, либо новой строкой."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:791
+msgid ""
+"Once you have changed [.filename]#hex.asm# to reflect these changes, type:"
+msgstr "После внесения изменений в файл [.filename]#hex.asm# введите:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:802
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1061
+#, no-wrap
+msgid ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A\n"
+"Here I come!\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A\n"
+"^D %\n"
+msgstr ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A\n"
+"Here I come!\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A\n"
+"^D %\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:806
+msgid ""
+"That looks better. But this code is quite inefficient! We are making a "
+"system call for every single byte twice (once to read it, another time to "
+"write the output)."
+msgstr ""
+"Выглядит лучше. Но этот код довольно неэффективен! Мы выполняем системный "
+"вызов для каждого отдельного байта дважды (один раз для чтения и ещё один "
+"для записи вывода)."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:808
+#, no-wrap
+msgid "Buffered Input and Output"
+msgstr "Буферизованный ввод и вывод"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:813
+msgid ""
+"We can improve the efficiency of our code by buffering our input and "
+"output. We create an input buffer and read a whole sequence of bytes at one "
+"time. Then we fetch them one by one from the buffer."
+msgstr ""
+"Мы можем повысить эффективность нашего кода, буферизуя ввод и вывод. Мы "
+"создаём входной буфер и читаем сразу целую последовательность байтов. Затем "
+"мы извлекаем их по одному из буфера."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:816
+msgid ""
+"We also create an output buffer. We store our output in it until it is "
+"full. At that time we ask the kernel to write the contents of the buffer to "
+"[.filename]#stdout#."
+msgstr ""
+"Мы также создаем выходной буфер. Мы сохраняем наш вывод в нем, пока он не "
+"заполнится. В этот момент мы просим ядро записать содержимое буфера в "
+"[.filename]#stdout#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:820
+msgid ""
+"The program ends when there is no more input. But we still need to ask the "
+"kernel to write the contents of our output buffer to [.filename]#stdout# one "
+"last time, otherwise some of our output would make it to the output buffer, "
+"but never be sent out. Do not forget that, or you will be wondering why "
+"some of your output is missing."
+msgstr ""
+"Программа завершается, когда больше нет входных данных. Но нам всё ещё нужно "
+"попросить ядро записать содержимое нашего выходного буфера в "
+"[.filename]#stdout# в последний раз, иначе часть нашего вывода попадёт в "
+"буфер, но так и не будет отправлена. Не забудьте об этом, иначе будете "
+"недоумевать, куда пропала часть вывода."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:826
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:954
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1221
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2339
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3337
+#, no-wrap
+msgid "%define\tBUFSIZE\t2048\n"
+msgstr "%define\tBUFSIZE\t2048\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:829
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:957
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+msgstr ""
+"section\t.data\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:833
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:961
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1230
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2353
+#, no-wrap
+msgid ""
+"section .bss\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+msgstr ""
+"section .bss\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:841
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:969
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+msgstr ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:845
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:973
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2501
+#, no-wrap
+msgid ""
+".loop:\n"
+"\t; read a byte from stdin\n"
+"\tcall\tgetchar\n"
+msgstr ""
+".loop:\n"
+"\t; read a byte from stdin\n"
+"\tcall\tgetchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:851
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:979
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1283
+#, no-wrap
+msgid ""
+"\t; convert it to hex\n"
+"\tmov\tdl, al\n"
+"\tshr\tal, 4\n"
+"\tmov\tal, [hex+eax]\n"
+"\tcall\tputchar\n"
+msgstr ""
+"\t; convert it to hex\n"
+"\tmov\tdl, al\n"
+"\tshr\tal, 4\n"
+"\tmov\tal, [hex+eax]\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:856
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:984
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1288
+#, no-wrap
+msgid ""
+"\tmov\tal, dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tcall\tputchar\n"
+msgstr ""
+"\tmov\tal, dl\n"
+"\tand\tal, 0Fh\n"
+"\tmov\tal, [hex+eax]\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:861
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:989
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1293
+#, no-wrap
+msgid ""
+"\tmov\tal, ' '\n"
+"\tcmp\tdl, 0Ah\n"
+"\tjne\t.put\n"
+"\tmov\tal, dl\n"
+msgstr ""
+"\tmov\tal, ' '\n"
+"\tcmp\tdl, 0Ah\n"
+"\tjne\t.put\n"
+"\tmov\tal, dl\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:865
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2512
+#, no-wrap
+msgid ""
+".put:\n"
+"\tcall\tputchar\n"
+"\tjmp\tshort .loop\n"
+msgstr ""
+".put:\n"
+"\tcall\tputchar\n"
+"\tjmp\tshort .loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:870
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1001
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1305
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2534
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3848
+#, no-wrap
+msgid ""
+"align 4\n"
+"getchar:\n"
+"\tor\tebx, ebx\n"
+"\tjne\t.fetch\n"
+msgstr ""
+"align 4\n"
+"getchar:\n"
+"\tor\tebx, ebx\n"
+"\tjne\t.fetch\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:872
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1003
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1307
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2536
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3850
+#, no-wrap
+msgid "\tcall\tread\n"
+msgstr "\tcall\tread\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:877
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1008
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1312
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2541
+#, no-wrap
+msgid ""
+".fetch:\n"
+"\tlodsb\n"
+"\tdec\tebx\n"
+"\tret\n"
+msgstr ""
+".fetch:\n"
+"\tlodsb\n"
+"\tdec\tebx\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:890
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1021
+#, no-wrap
+msgid ""
+"read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+msgstr ""
+"read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword stdin\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:896
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1027
+#, no-wrap
+msgid ""
+"align 4\n"
+".done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+".done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:904
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1035
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1348
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2581
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3887
+#, no-wrap
+msgid ""
+"align 4\n"
+"putchar:\n"
+"\tstosb\n"
+"\tinc\tecx\n"
+"\tcmp\tecx, BUFSIZE\n"
+"\tje\twrite\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+"putchar:\n"
+"\tstosb\n"
+"\tinc\tecx\n"
+"\tcmp\tecx, BUFSIZE\n"
+"\tje\twrite\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:916
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1047
+#, no-wrap
+msgid ""
+"align 4\n"
+"write:\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+"write:\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:922
+msgid ""
+"We now have a third section in the source code, named `.bss`. This section "
+"is not included in our executable file, and, therefore, cannot be "
+"initialized. We use `resb` instead of `db`. It simply reserves the "
+"requested size of uninitialized memory for our use."
+msgstr ""
+"Теперь у нас есть третий раздел в исходном коде с именем `.bss`. Этот раздел "
+"не включается в исполняемый файл и, следовательно, не может быть "
+"инициализирован. Мы используем `resb` вместо `db`. Это просто резервирует "
+"запрошенный размер неинициализированной памяти для нашего использования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:926
+msgid ""
+"We take advantage of the fact that the system does not modify the registers: "
+"We use registers for what, otherwise, would have to be global variables "
+"stored in the `.data` section. This is also why the UNIX(R) convention of "
+"passing parameters to system calls on the stack is superior to the Microsoft "
+"convention of passing them in the registers: We can keep the registers for "
+"our own use."
+msgstr ""
+"Мы используем тот факт, что система не изменяет регистры: мы используем "
+"регистры для того, что в противном случае пришлось бы хранить в глобальных "
+"переменных в секции `.data`. Именно поэтому соглашение UNIX(R) о передаче "
+"параметров системных вызовов через стек превосходит соглашение Microsoft о "
+"передаче их в регистрах: мы можем оставить регистры для собственного "
+"использования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:930
+msgid ""
+"We use `EDI` and `ESI` as pointers to the next byte to be read from or "
+"written to. We use `EBX` and `ECX` to keep count of the number of bytes in "
+"the two buffers, so we know when to dump the output to, or read more input "
+"from, the system."
+msgstr ""
+"Мы используем `EDI` и `ESI` как указатели на следующий байт для чтения или "
+"записи. Мы используем `EBX` и `ECX` для отслеживания количества байтов в "
+"двух буферах, чтобы знать, когда нужно вывести данные в систему или считать "
+"новые данные из системы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:932
+msgid "Let us see how it works now:"
+msgstr "Давайте посмотрим, как это работает сейчас:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:943
+#, no-wrap
+msgid ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"Here I come!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A\n"
+"^D %\n"
+msgstr ""
+"% nasm -f elf hex.asm\n"
+"% ld -s -o hex hex.o\n"
+"% ./hex\n"
+"Hello, World!\n"
+"Here I come!\n"
+"48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A\n"
+"48 65 72 65 20 49 20 63 6F 6D 65 21 0A\n"
+"^D %\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:948
+msgid ""
+"Not what you expected? The program did not print the output until we pressed "
+"`^D`. That is easy to fix by inserting three lines of code to write the "
+"output every time we have converted a new line to `0A`. I have marked the "
+"three lines with > (do not copy the > in your [.filename]#hex.asm#)."
+msgstr ""
+"Не то, что вы ожидали? Программа не выводила результат, пока мы не нажали "
+"`^D`. Это легко исправить, добавив три строки кода для вывода результата "
+"каждый раз, когда мы преобразуем новую строку в `0A`. Я пометил эти три "
+"строки символом > (не копируйте > в ваш [.filename]#hex.asm#)."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:996
+#, no-wrap
+msgid ""
+".put:\n"
+"\tcall\tputchar\n"
+">\tcmp\tal, 0Ah\n"
+">\tjne\t.loop\n"
+">\tcall\twrite\n"
+"\tjmp\tshort .loop\n"
+msgstr ""
+".put:\n"
+"\tcall\tputchar\n"
+">\tcmp\tal, 0Ah\n"
+">\tjne\t.loop\n"
+">\tcall\twrite\n"
+"\tjmp\tshort .loop\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1050
+msgid "Now, let us see how it works:"
+msgstr "Теперь давайте посмотрим, как это работает:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1064
+msgid "Not bad for a 644-byte executable, is it!"
+msgstr "Неплохо для исполняемого файла размером 644 байта, не так ли!"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1069
+msgid ""
+"This approach to buffered input/output still contains a hidden danger. I "
+"will discuss-and fix-it later, when I talk about the crossref:x86[x86-"
+"buffered-dark-side,dark side of buffering]."
+msgstr ""
+"Такой подход к буферизированному вводу/выводу всё ещё содержит скрытую "
+"опасность. Я расскажу об этом и исправлю её позже, когда речь пойдёт о "
+"crossref:x86[x86-buffered-dark-side,тёмной стороне буферизации]."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1072
+#, no-wrap
+msgid "How to Unread a Character"
+msgstr "Как отменить чтение символа"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1078
+msgid ""
+"This may be a somewhat advanced topic, mostly of interest to programmers "
+"familiar with the theory of compilers. If you wish, you may "
+"crossref:x86[x86-command-line,skip to the next section], and perhaps read "
+"this later."
+msgstr ""
+"Это может быть несколько сложной темой, в основном представляющей интерес "
+"для программистов, знакомых с теорией компиляторов. Если хотите, вы можете "
+"crossref:x86[x86-command-line, перейти к следующему разделу], и, возможно, "
+"прочитаете это позже."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1084
+msgid ""
+"While our sample program does not require it, more sophisticated filters "
+"often need to look ahead. In other words, they may need to see what the "
+"next character is (or even several characters). If the next character is of "
+"a certain value, it is part of the token currently being processed. "
+"Otherwise, it is not."
+msgstr ""
+"Хотя наш пример программы не требует этого, более сложные фильтры часто "
+"нуждаются в предварительном просмотре. Другими словами, им может "
+"потребоваться узнать, какой следующий символ (или даже несколько символов). "
+"Если следующий символ имеет определённое значение, он является частью "
+"текущего обрабатываемого токена. В противном случае — нет."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1088
+msgid ""
+"For example, you may be parsing the input stream for a textual string (e.g., "
+"when implementing a language compiler): If a character is followed by "
+"another character, or perhaps a digit, it is part of the token you are "
+"processing. If it is followed by white space, or some other value, then it "
+"is not part of the current token."
+msgstr ""
+"Например, вы можете анализировать входной поток на наличие текстовой строки "
+"(например, при реализации компилятора языка): если символ следует за другим "
+"символом или, возможно, цифрой, он является частью обрабатываемой лексемы. "
+"Если за ним следует пробел или другое значение, то он не является частью "
+"текущей лексемы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1090
+msgid ""
+"This presents an interesting problem: How to return the next character back "
+"to the input stream, so it can be read again later?"
+msgstr ""
+"Это представляет интересную проблему: как вернуть следующий символ обратно "
+"во входной поток, чтобы его можно было прочитать позже?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1094
+msgid ""
+"One possible solution is to store it in a character variable, then set a "
+"flag. We can modify `getchar` to check the flag, and if it is set, fetch "
+"the byte from that variable instead of the input buffer, and reset the "
+"flag. But, of course, that slows us down."
+msgstr ""
+"Одно из возможных решений — сохранить его в символьной переменной, а затем "
+"установить флаг. Мы можем изменить `getchar`, чтобы он проверял флаг, и если "
+"он установлен, извлекал байт из этой переменной вместо буфера ввода, а затем "
+"сбрасывал флаг. Но, конечно, это замедляет работу."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1099
+msgid ""
+"The C language has an `ungetc()` function, just for that purpose. Is there "
+"a quick way to implement it in our code? I would like you to scroll back up "
+"and take a look at the `getchar` procedure and see if you can find a nice "
+"and fast solution before reading the next paragraph. Then come back here "
+"and see my own solution."
+msgstr ""
+"В языке C есть функция `ungetc()`, как раз для этой цели. Есть ли быстрый "
+"способ реализовать её в нашем коде? Я хочу, чтобы вы пролистали назад и "
+"взглянули на процедуру `getchar`, и попробовали найти красивое и быстрое "
+"решение, прежде чем читать следующий абзац. Затем вернитесь сюда и "
+"посмотрите моё собственное решение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1101
+msgid ""
+"The key to returning a character back to the stream is in how we are getting "
+"the characters to start with:"
+msgstr ""
+"Ключом к возвращению символа обратно в поток является то, как мы получаем "
+"символы изначально:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1104
+msgid ""
+"First we check if the buffer is empty by testing the value of `EBX`. If it "
+"is zero, we call the `read` procedure."
+msgstr ""
+"Сначала проверяем, пуст ли буфер, проверяя значение `EBX`. Если оно равно "
+"нулю, вызываем процедуру `read`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1107
+msgid ""
+"If we do have a character available, we use `lodsb`, then decrease the value "
+"of `EBX`. The `lodsb` instruction is effectively identical to:"
+msgstr ""
+"Если у нас есть доступный символ, мы используем `lodsb`, затем уменьшаем "
+"значение `EBX`. Инструкция `lodsb` фактически идентична:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1112
+#, no-wrap
+msgid ""
+"mov\tal, [esi]\n"
+"\tinc\tesi\n"
+msgstr ""
+"mov\tal, [esi]\n"
+"\tinc\tesi\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1117
+msgid ""
+"The byte we have fetched remains in the buffer until the next time `read` is "
+"called. We do not know when that happens, but we do know it will not happen "
+"until the next call to `getchar`. Hence, to \"return\" the last-read byte "
+"back to the stream, all we have to do is decrease the value of `ESI` and "
+"increase the value of `EBX`:"
+msgstr ""
+"Байт, который мы извлекли, остается в буфере до следующего вызова `read`. Мы "
+"не знаем, когда это произойдет, но знаем, что этого не случится до "
+"следующего вызова `getchar`. Следовательно, чтобы \"вернуть\" последний "
+"прочитанный байт обратно в поток, нам достаточно уменьшить значение `ESI` и "
+"увеличить значение `EBX`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1124
+#, no-wrap
+msgid ""
+"ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+"\tret\n"
+msgstr ""
+"ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1128
+msgid ""
+"But, be careful! We are perfectly safe doing this if our look-ahead is at "
+"most one character at a time. If we are examining more than one upcoming "
+"character and call `ungetc` several times in a row, it will work most of the "
+"time, but not all the time (and will be tough to debug). Why?"
+msgstr ""
+"Но будьте осторожны! Мы в полной безопасности, если заглядываем вперед "
+"только на один символ за раз. Если же мы проверяем несколько следующих "
+"символов и вызываем `ungetc` несколько раз подряд, это будет работать в "
+"большинстве случаев, но не всегда (и ошибки будет сложно отладить). Почему?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1131
+msgid ""
+"Because as long as `getchar` does not have to call `read`, all of the pre-"
+"read bytes are still in the buffer, and our `ungetc` works without a "
+"glitch. But the moment `getchar` calls `read`, the contents of the buffer "
+"change."
+msgstr ""
+"Потому что пока `getchar` не вызывает `read`, все предварительно прочитанные "
+"байты остаются в буфере, и наш `ungetc` работает без сбоев. Но как только "
+"`getchar` вызывает `read`, содержимое буфера изменяется."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1133
+msgid ""
+"We can always rely on `ungetc` working properly on the last character we "
+"have read with `getchar`, but not on anything we have read before that."
+msgstr ""
+"Мы всегда можем рассчитывать на корректную работу `ungetc` с последним "
+"символом, прочитанным через `getchar`, но не с любым символом, прочитанным "
+"до этого."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1135
+msgid ""
+"If your program reads more than one byte ahead, you have at least two "
+"choices:"
+msgstr ""
+"Если ваша программа читает более одного байта вперед, у вас есть как минимум "
+"два варианта:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1138
+msgid ""
+"If possible, modify the program so it only reads one byte ahead. This is "
+"the simplest solution."
+msgstr ""
+"Если возможно, измените программу так, чтобы она читала только один байт "
+"вперед. Это самое простое решение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1142
+msgid ""
+"If that option is not available, first of all determine the maximum number "
+"of characters your program needs to return to the input stream at one time. "
+"Increase that number slightly, just to be sure, preferably to a multiple of "
+"16-so it aligns nicely. Then modify the `.bss` section of your code, and "
+"create a small \"spare\" buffer right before your input buffer, something "
+"like this:"
+msgstr ""
+"Если эта опция недоступна, сначала определите максимальное количество "
+"символов, которое вашей программе может потребоваться вернуть во входной "
+"поток за один раз. Увеличьте это число немного, чтобы быть уверенным, "
+"предпочтительно до кратного 16 — так оно будет лучше выровнено. Затем "
+"измените секцию `.bss` в вашем коде и создайте небольшой \"запасной\" буфер "
+"прямо перед вашим входным буфером, примерно так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1149
+#, no-wrap
+msgid ""
+"section\t.bss\n"
+"\tresb\t16\t; or whatever the value you came up with\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+msgstr ""
+"section\t.bss\n"
+"\tresb\t16\t; or whatever the value you came up with\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1152
+msgid ""
+"You also need to modify your `ungetc` to pass the value of the byte to unget "
+"in `AL`:"
+msgstr ""
+"Вам также необходимо изменить ваш `ungetc`, чтобы передать значение байта "
+"для возврата в `AL`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1160
+#, no-wrap
+msgid ""
+"ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+"\tmov\t[esi], al\n"
+"\tret\n"
+msgstr ""
+"ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+"\tmov\t[esi], al\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1163
+msgid ""
+"With this modification, you can call `ungetc` up to 17 times in a row safely "
+"(the first call will still be within the buffer, the remaining 16 may be "
+"either within the buffer or within the \"spare\")."
+msgstr ""
+"С этим изменением вы можете безопасно вызывать `ungetc` до 17 раз подряд "
+"(первый вызов всё ещё будет в пределах буфера, остальные 16 могут быть либо "
+"в пределах буфера, либо в пределах \"запасного\" пространства)."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1165
+#, no-wrap
+msgid "Command Line Arguments"
+msgstr "Аргументы командной строки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1169
+msgid ""
+"Our hex program will be more useful if it can read the names of an input and "
+"output file from its command line, i.e., if it can process the command line "
+"arguments. But... Where are they?"
+msgstr ""
+"Наша программа hex будет полезнее, если она сможет читать имена входного и "
+"выходного файлов из командной строки, т.е. если она сможет обрабатывать "
+"аргументы командной строки. Но... Где они?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1173
+msgid ""
+"Before a UNIX(R) system starts a program, it ``push``es some data on the "
+"stack, then jumps at the `_start` label of the program. Yes, I said jumps, "
+"not calls. That means the data can be accessed by reading `[esp+offset]`, "
+"or by simply ``pop``ping it."
+msgstr ""
+"Прежде чем UNIX(R) система запустит программу, она делает ``push`` для "
+"некоторых данных, помещая их в стек, затем переходит к метке `_start` "
+"программы. Да, я сказал \"переходит\", а не \"вызывает\". Это означает, что "
+"данные можно прочитать с помощью `[esp+offset]` или просто сделать ``pop`` "
+"для них."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1176
+msgid ""
+"The value at the top of the stack contains the number of command line "
+"arguments. It is traditionally called `argc`, for \"argument count.\""
+msgstr ""
+"Значение на вершине стека содержит количество аргументов командной строки. "
+"Оно традиционно называется `argc`, что означает \"argument count\"."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1181
+msgid ""
+"Command line arguments follow next, all `argc` of them. These are typically "
+"referred to as `argv`, for \"argument value(s).\" That is, we get `argv[0]`, "
+"`argv[1]`, `...`, `argv[argc-1]`. These are not the actual arguments, but "
+"pointers to arguments, i.e., memory addresses of the actual arguments. The "
+"arguments themselves are NUL-terminated character strings."
+msgstr ""
+"Далее следуют аргументы командной строки, все `argc` штук. Обычно их "
+"называют `argv`, что означает \"значение(я) аргумента\". То есть мы получаем "
+"`argv[0]`, `argv[1]`, `...`, `argv[argc-1]`. Это не сами аргументы, а "
+"указатели на аргументы, то есть адреса памяти, где находятся реальные "
+"аргументы. Сами аргументы представляют собой строки символов, завершающиеся "
+"нулевым символом ('\\0')."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1183
+msgid ""
+"The `argv` list is followed by a NULL pointer, which is simply a `0`. There "
+"is more, but this is enough for our purposes right now."
+msgstr ""
+"Список `argv` завершается указателем NULL, который представляет собой просто "
+"`0`. Есть и другие детали, но пока этого достаточно для наших целей."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1188
+msgid ""
+"If you have come from the MS-DOS(R) programming environment, the main "
+"difference is that each argument is in a separate string. The second "
+"difference is that there is no practical limit on how many arguments there "
+"can be."
+msgstr ""
+"Если вы перешли из среды программирования MS-DOS(R), основное различие "
+"заключается в том, что каждый аргумент находится в отдельной строке. Второе "
+"различие состоит в том, что нет практического ограничения на количество "
+"аргументов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1192
+msgid ""
+"Armed with this knowledge, we are almost ready for the next version of "
+"[.filename]#hex.asm#. First, however, we need to add a few lines to "
+"[.filename]#system.inc#:"
+msgstr ""
+"Вооружившись этими знаниями, мы почти готовы к следующей версии "
+"[.filename]#hex.asm#. Однако сначала нам нужно добавить несколько строк в "
+"[.filename]#system.inc#:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1194
+msgid ""
+"First, we need to add two new entries to our list of system call numbers:"
+msgstr ""
+"Сначала нам нужно добавить две новые записи в наш список номеров системных "
+"вызовов:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1199
+#, no-wrap
+msgid ""
+"%define\tSYS_open\t5\n"
+"%define\tSYS_close\t6\n"
+msgstr ""
+"%define\tSYS_open\t5\n"
+"%define\tSYS_close\t6\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1202
+msgid "Then we add two new macros at the end of the file:"
+msgstr "Затем мы добавляем два новых макроса в конце файла:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1208
+#, no-wrap
+msgid ""
+"%macro\tsys.open\t0\n"
+"\tsystem\tSYS_open\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.open\t0\n"
+"\tsystem\tSYS_open\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1212
+#, no-wrap
+msgid ""
+"%macro\tsys.close\t0\n"
+"\tsystem\tSYS_close\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.close\t0\n"
+"\tsystem\tSYS_close\n"
+"%endmacro\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1215
+msgid "Here, then, is our modified source code:"
+msgstr "Вот наш измененный исходный код:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1226
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+msgstr ""
+"section\t.data\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"hex\tdb\t'0123456789ABCDEF'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1236
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"align 4\n"
+"err:\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+msgstr ""
+"section\t.text\n"
+"align 4\n"
+"err:\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1241
+#, no-wrap
+msgid ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+msgstr ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1244
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1256
+#, no-wrap
+msgid ""
+"\tpop\tecx\n"
+"\tjecxz\t.init\t\t; no more arguments\n"
+msgstr ""
+"\tpop\tecx\n"
+"\tjecxz\t.init\t\t; no more arguments\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1250
+#, no-wrap
+msgid ""
+"\t; ECX contains the path to input file\n"
+"\tpush\tdword 0\t\t; O_RDONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\terr\t\t; open failed\n"
+msgstr ""
+"\t; ECX contains the path to input file\n"
+"\tpush\tdword 0\t\t; O_RDONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\terr\t\t; open failed\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1253
+#, no-wrap
+msgid ""
+"\tadd\tesp, byte 8\n"
+"\tmov\t[fd.in], eax\n"
+msgstr ""
+"\tadd\tesp, byte 8\n"
+"\tmov\t[fd.in], eax\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1264
+#, no-wrap
+msgid ""
+"\t; ECX contains the path to output file\n"
+"\tpush\tdword 420\t; file mode (644 octal)\n"
+"\tpush\tdword 0200h | 0400h | 01h\n"
+"\t; O_CREAT | O_TRUNC | O_WRONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\terr\n"
+msgstr ""
+"\t; ECX contains the path to output file\n"
+"\tpush\tdword 420\t; file mode (644 octal)\n"
+"\tpush\tdword 0200h | 0400h | 01h\n"
+"\t; O_CREAT | O_TRUNC | O_WRONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\terr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1267
+#, no-wrap
+msgid ""
+"\tadd\tesp, byte 12\n"
+"\tmov\t[fd.out], eax\n"
+msgstr ""
+"\tadd\tesp, byte 12\n"
+"\tmov\t[fd.out], eax\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1273
+#, no-wrap
+msgid ""
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+msgstr ""
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1277
+#, no-wrap
+msgid ""
+".loop:\n"
+"\t; read a byte from input file or stdin\n"
+"\tcall\tgetchar\n"
+msgstr ""
+".loop:\n"
+"\t; read a byte from input file or stdin\n"
+"\tcall\tgetchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1300
+#, no-wrap
+msgid ""
+".put:\n"
+"\tcall\tputchar\n"
+"\tcmp\tal, dl\n"
+"\tjne\t.loop\n"
+"\tcall\twrite\n"
+"\tjmp\tshort .loop\n"
+msgstr ""
+".put:\n"
+"\tcall\tputchar\n"
+"\tcmp\tal, dl\n"
+"\tjne\t.loop\n"
+"\tcall\twrite\n"
+"\tjmp\tshort .loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1325
+#, no-wrap
+msgid ""
+"read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+msgstr ""
+"read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1329
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2562
+#, no-wrap
+msgid ""
+"align 4\n"
+".done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+msgstr ""
+"align 4\n"
+".done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1333
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2566
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3820
+#, no-wrap
+msgid ""
+"\t; close files\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.close\n"
+msgstr ""
+"\t; close files\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.close\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1336
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2569
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3823
+#, no-wrap
+msgid ""
+"\tpush\tdword [fd.out]\n"
+"\tsys.close\n"
+msgstr ""
+"\tpush\tdword [fd.out]\n"
+"\tsys.close\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1340
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2573
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3829
+#, no-wrap
+msgid ""
+"\t; return success\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+"\t; return success\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1360
+#, no-wrap
+msgid ""
+"align 4\n"
+"write:\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+"write:\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1364
+msgid ""
+"In our `.data` section we now have two new variables, `fd.in` and `fd.out`. "
+"We store the input and output file descriptors here."
+msgstr ""
+"В нашем разделе `.data` теперь есть две новые переменные, `fd.in` и "
+"`fd.out`. Здесь мы сохраняем дескрипторы файлов для ввода и вывода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1366
+msgid ""
+"In the `.text` section we have replaced the references to `stdin` and "
+"`stdout` with `[fd.in]` and `[fd.out]`."
+msgstr ""
+"В разделе `.text` мы заменили ссылки с `stdin` и `stdout` на `[fd.in]` и "
+"`[fd.out]`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1369
+msgid ""
+"The `.text` section now starts with a simple error handler, which does "
+"nothing but exit the program with a return value of `1`. The error handler "
+"is before `_start` so we are within a short distance from where the errors "
+"occur."
+msgstr ""
+"Раздел `.text` теперь начинается с простого обработчика ошибок, который "
+"просто завершает программу с кодом возврата `1`. Обработчик ошибок "
+"расположен перед `_start`, чтобы находиться вблизи от места возникновения "
+"ошибок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1372
+msgid ""
+"Naturally, the program execution still begins at `_start`. First, we remove "
+"`argc` and `argv[0]` from the stack: They are of no interest to us (in this "
+"program, that is)."
+msgstr ""
+"Естественно, выполнение программы по-прежнему начинается с `_start`. Сначала "
+"мы удаляем `argc` и `argv[0]` из стека: они не представляют для нас интереса "
+"(по крайней мере, в этой программе)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1378
+msgid ""
+"We pop `argv[1]` to `ECX`. This register is particularly suited for "
+"pointers, as we can handle NULL pointers with `jecxz`. If `argv[1]` is not "
+"NULL, we try to open the file named in the first argument. Otherwise, we "
+"continue the program as before: Reading from `stdin`, writing to `stdout`. "
+"If we fail to open the input file (e.g., it does not exist), we jump to the "
+"error handler and quit."
+msgstr ""
+"Мы помещаем `argv[1]` в `ECX`. Этот регистр особенно подходит для "
+"указателей, так как мы можем обрабатывать NULL-указатели с помощью `jecxz`. "
+"Если `argv[1]` не равен NULL, мы пытаемся открыть файл с именем, указанным в "
+"первом аргументе. В противном случае продолжаем программу как раньше: чтение "
+"из `stdin`, запись в `stdout`. Если нам не удаётся открыть входной файл "
+"(например, он не существует), мы переходим к обработчику ошибок и завершаем "
+"работу."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1383
+msgid ""
+"If all went well, we now check for the second argument. If it is there, we "
+"open the output file. Otherwise, we send the output to `stdout`. If we "
+"fail to open the output file (e.g., it exists and we do not have the write "
+"permission), we, again, jump to the error handler."
+msgstr ""
+"Если всё прошло успешно, мы проверяем второй аргумент. Если он присутствует, "
+"мы открываем выходной файл. В противном случае, мы отправляем вывод в "
+"`stdout`. Если нам не удаётся открыть выходной файл (например, он существует "
+"и у нас нет прав на запись), мы снова переходим к обработчику ошибок."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1385
+msgid ""
+"The rest of the code is the same as before, except we close the input and "
+"output files before exiting, and, as mentioned, we use `[fd.in]` and "
+"`[fd.out]`."
+msgstr ""
+"Остальная часть кода остается прежней, за исключением того, что мы закрываем "
+"входной и выходной файлы перед завершением, и, как упоминалось, используем "
+"`[fd.in]` и `[fd.out]`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1387
+msgid "Our executable is now a whopping 768 bytes long."
+msgstr "Наш исполняемый файл теперь имеет внушительный размер в 768 байт."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1390
+msgid ""
+"Can we still improve it? Of course! Every program can be improved. Here are "
+"a few ideas of what we could do:"
+msgstr ""
+"Можем ли мы улучшить его еще? Конечно! Каждую программу можно улучшить. Вот "
+"несколько идей, что мы могли бы сделать:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1392
+msgid "Have our error handler print a message to `stderr`."
+msgstr "Сделать наш обработчик ошибок, выводящий сообщение в `stderr`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1393
+msgid "Add error handlers to the `read` and `write` functions."
+msgstr "Добавить обработчики ошибок в функции `read` и `write`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1394
+msgid ""
+"Close `stdin` when we open an input file, `stdout` when we open an output "
+"file."
+msgstr ""
+"Закрывать `stdin` при открытии входного файла, `stdout` при открытии "
+"выходного файла."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1395
+msgid ""
+"Add command line switches, such as `-i` and `-o`, so we can list the input "
+"and output files in any order, or perhaps read from `stdin` and write to a "
+"file."
+msgstr ""
+"Добавить параметры командной строки, такие как `-i` и `-o`, чтобы можно было "
+"перечислять входные и выходные файлы в любом порядке или, возможно, читать "
+"из `stdin` и записывать в файл."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1396
+msgid "Print a usage message if command line arguments are incorrect."
+msgstr ""
+"Выводить сообщение с подсказкой об использовании программы, если аргументы "
+"командной строки указаны неверно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1398
+msgid ""
+"I shall leave these enhancements as an exercise to the reader: You already "
+"know everything you need to know to implement them."
+msgstr ""
+"Я оставлю эти улучшения в качестве упражнения для читателя: вы уже знаете "
+"всё необходимое для их реализации."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1400
+#, no-wrap
+msgid "UNIX(R) Environment"
+msgstr "Окружение UNIX(R)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1404
+msgid ""
+"An important UNIX(R) concept is the environment, which is defined by "
+"_environment variables_. Some are set by the system, others by you, yet "
+"others by the shell, or any program that loads another program."
+msgstr ""
+"Важным концептом UNIX(R) является окружение, которое определяется "
+"_переменными окружения_. Некоторые из них устанавливаются системой, другие — "
+"пользователем, третьи — оболочкой или любой программой, которая загружает "
+"другую программу."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1406
+#, no-wrap
+msgid "How to Find Environment Variables"
+msgstr "Как найти переменные окружения"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1411
+msgid ""
+"I said earlier that when a program starts executing, the stack contains "
+"`argc` followed by the NULL-terminated `argv` array, followed by something "
+"else. The \"something else\" is the _environment_, or, to be more precise, "
+"a NULL-terminated array of pointers to _environment variables_. This is "
+"often referred to as `env`."
+msgstr ""
+"Я говорил ранее, что когда программа начинает выполняться, в стеке находятся "
+"`argc`, за которым следует массив `argv`, завершающийся NULL, а затем что-то "
+"ещё. Это \"что-то ещё\" — это _окружение_, или, если быть точнее, массив "
+"указателей на _переменные окружения_, завершающийся NULL. Это часто называют "
+"`env`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1414
+msgid ""
+"The structure of `env` is the same as that of `argv`, a list of memory "
+"addresses followed by a NULL (`0`). In this case, there is no `\"envc\"`-we "
+"figure out where the array ends by searching for the final NULL."
+msgstr ""
+"Структура `env` такая же, как у `argv` — список адресов памяти, "
+"заканчивающийся NULL (`0`). В данном случае нет `\"envc\"` — конец массива "
+"определяется поиском последнего NULL."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1417
+msgid ""
+"The variables usually come in the `name=value` format, but sometimes the "
+"`=value` part may be missing. We need to account for that possibility."
+msgstr ""
+"Переменные обычно имеют формат `name=value`, но иногда часть `=value` может "
+"отсутствовать. Необходимо учитывать эту вероятность."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1419
+#, no-wrap
+msgid "webvars"
+msgstr "webvars"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1423
+msgid ""
+"I could just show you some code that prints the environment the same way the "
+"UNIX(R) env command does. But I thought it would be more interesting to "
+"write a simple assembly language CGI utility."
+msgstr ""
+"Я мог бы просто показать вам код, который выводит окружение так же, как "
+"команда UNIX(R) env. Но я подумал, что будет интереснее написать простую CGI-"
+"утилиту на ассемблере."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1425
+#, no-wrap
+msgid "CGI: a Quick Overview"
+msgstr "CGI: краткий обзор"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1428
+msgid ""
+"I have a http://www.whizkidtech.redprince.net/cgi-bin/tutorial[detailed CGI "
+"tutorial] on my web site, but here is a very quick overview of CGI:"
+msgstr ""
+"У меня есть http://www.whizkidtech.redprince.net/cgi-bin/tutorial[подробное "
+"руководство по CGI] на моем веб-сайте, но вот очень краткий обзор CGI:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1430
+msgid ""
+"The web server communicates with the CGI program by setting _environment "
+"variables_."
+msgstr ""
+"Веб-сервер взаимодействует с CGI-программой, устанавливая _переменные "
+"окружения_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1431
+msgid ""
+"The CGI program sends its output to [.filename]#stdout#. The web server "
+"reads it from there."
+msgstr ""
+"Программа CGI отправляет свой вывод в [.filename]#stdout#. Веб-сервер "
+"считывает его оттуда."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1432
+msgid "It must start with an HTTP header followed by two blank lines."
+msgstr ""
+"Он должен начинаться с HTTP-заголовка, за которым следуют две пустые строки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1433
+msgid ""
+"It then prints the HTML code, or whatever other type of data it is producing."
+msgstr ""
+"Затем он выводит HTML-код или любые другие данные, которые он генерирует."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1438
+msgid ""
+"While certain _environment variables_ use standard names, others vary, "
+"depending on the web server. That makes webvars quite a useful diagnostic "
+"tool."
+msgstr ""
+"В то время как некоторые _переменные окружения_ используют стандартные "
+"имена, другие различаются в зависимости от веб-сервера. Это делает программу "
+"webvars весьма полезным инструментом для диагностики."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1441
+#, no-wrap
+msgid "The Code"
+msgstr "Код"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1445
+msgid ""
+"Our webvars program, then, must send out the HTTP header followed by some "
+"HTML mark-up. It then must read the _environment variables_ one by one and "
+"send them out as part of the HTML page."
+msgstr ""
+"Наша программа webvars, таким образом, должна отправить HTTP-заголовок, за "
+"которым следует HTML-разметка. Затем она должна прочитать _переменные "
+"окружения_ одну за другой и отправить их как часть HTML-страницы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1448
+msgid ""
+"The code follows. I placed comments and explanations right inside the code:"
+msgstr "Код приведен ниже. Я разместил комментарии и пояснения прямо в коде:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1485
+#, no-wrap
+msgid ""
+";;;;;;; webvars.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Copyright (c) 2000 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+"; Redistribution and use in source and binary forms, with or without\n"
+"; modification, are permitted provided that the following conditions\n"
+"; are met:\n"
+"; 1. Redistributions of source code must retain the above copyright\n"
+"; notice, this list of conditions and the following disclaimer.\n"
+"; 2. Redistributions in binary form must reproduce the above copyright\n"
+"; notice, this list of conditions and the following disclaimer in the\n"
+"; documentation and/or other materials provided with the distribution.\n"
+";\n"
+"; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n"
+"; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"
+"; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"
+"; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n"
+"; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n"
+"; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n"
+"; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n"
+"; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n"
+"; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
+"; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
+"; SUCH DAMAGE.\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Version 1.0\n"
+";\n"
+"; Started:\t 8-Dec-2000\n"
+"; Updated:\t 8-Dec-2000\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+"%include\t'system.inc'\n"
+msgstr ""
+";;;;;;; webvars.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Copyright (c) 2000 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+"; Redistribution and use in source and binary forms, with or without\n"
+"; modification, are permitted provided that the following conditions\n"
+"; are met:\n"
+"; 1. Redistributions of source code must retain the above copyright\n"
+"; notice, this list of conditions and the following disclaimer.\n"
+"; 2. Redistributions in binary form must reproduce the above copyright\n"
+"; notice, this list of conditions and the following disclaimer in the\n"
+"; documentation and/or other materials provided with the distribution.\n"
+";\n"
+"; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n"
+"; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n"
+"; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n"
+"; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n"
+"; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n"
+"; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n"
+"; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n"
+"; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n"
+"; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
+"; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
+"; SUCH DAMAGE.\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Version 1.0\n"
+";\n"
+"; Started:\t 8-Dec-2000\n"
+"; Updated:\t 8-Dec-2000\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+"%include\t'system.inc'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1522
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"http\tdb\t'Content-type: text/html', 0Ah, 0Ah\n"
+"\tdb\t'<?xml version=\"1.0\" encoding=\"utf-8\"?>', 0Ah\n"
+"\tdb\t'<!DOCTYPE html PUBLIC \"-//W3C/DTD XHTML Strict//EN\" '\n"
+"\tdb\t'\"DTD/xhtml1-strict.dtd\">', 0Ah\n"
+"\tdb\t'<html xmlns=\"http://www.w3.org/1999/xhtml\" '\n"
+"\tdb\t'xml.lang=\"en\" lang=\"en\">', 0Ah\n"
+"\tdb\t'<head>', 0Ah\n"
+"\tdb\t'<title>Web Environment</title>', 0Ah\n"
+"\tdb\t'<meta name=\"author\" content=\"G. Adam Stanislav\" />', 0Ah\n"
+"\tdb\t'</head>', 0Ah, 0Ah\n"
+"\tdb\t'<body bgcolor=\"#ffffff\" text=\"#000000\" link=\"#0000ff\" '\n"
+"\tdb\t'vlink=\"#840084\" alink=\"#0000ff\">', 0Ah\n"
+"\tdb\t'<div class=\"webvars\">', 0Ah\n"
+"\tdb\t'<h1>Web Environment</h1>', 0Ah\n"
+"\tdb\t'<p>The following <b>environment variables</b> are defined '\n"
+"\tdb\t'on this web server:</p>', 0Ah, 0Ah\n"
+"\tdb\t'<table align=\"center\" width=\"80\" border=\"0\" cellpadding=\"10\" '\n"
+"\tdb\t'cellspacing=\"0\" class=\"webvars\">', 0Ah\n"
+"httplen\tequ\t$-http\n"
+"left\tdb\t'<tr>', 0Ah\n"
+"\tdb\t'<td class=\"name\"><tt>'\n"
+"leftlen\tequ\t$-left\n"
+"middle\tdb\t'</tt></td>', 0Ah\n"
+"\tdb\t'<td class=\"value\"><tt><b>'\n"
+"midlen\tequ\t$-middle\n"
+"undef\tdb\t'<i>(undefined)</i>'\n"
+"undeflen\tequ\t$-undef\n"
+"right\tdb\t'</b></tt></td>', 0Ah\n"
+"\tdb\t'</tr>', 0Ah\n"
+"rightlen\tequ\t$-right\n"
+"wrap\tdb\t'</table>', 0Ah\n"
+"\tdb\t'</div>', 0Ah\n"
+"\tdb\t'</body>', 0Ah\n"
+"\tdb\t'</html>', 0Ah, 0Ah\n"
+"wraplen\tequ\t$-wrap\n"
+msgstr ""
+"section\t.data\n"
+"http\tdb\t'Content-type: text/html', 0Ah, 0Ah\n"
+"\tdb\t'<?xml version=\"1.0\" encoding=\"utf-8\"?>', 0Ah\n"
+"\tdb\t'<!DOCTYPE html PUBLIC \"-//W3C/DTD XHTML Strict//EN\" '\n"
+"\tdb\t'\"DTD/xhtml1-strict.dtd\">', 0Ah\n"
+"\tdb\t'<html xmlns=\"http://www.w3.org/1999/xhtml\" '\n"
+"\tdb\t'xml.lang=\"en\" lang=\"en\">', 0Ah\n"
+"\tdb\t'<head>', 0Ah\n"
+"\tdb\t'<title>Web Environment</title>', 0Ah\n"
+"\tdb\t'<meta name=\"author\" content=\"G. Adam Stanislav\" />', 0Ah\n"
+"\tdb\t'</head>', 0Ah, 0Ah\n"
+"\tdb\t'<body bgcolor=\"#ffffff\" text=\"#000000\" link=\"#0000ff\" '\n"
+"\tdb\t'vlink=\"#840084\" alink=\"#0000ff\">', 0Ah\n"
+"\tdb\t'<div class=\"webvars\">', 0Ah\n"
+"\tdb\t'<h1>Web Environment</h1>', 0Ah\n"
+"\tdb\t'<p>The following <b>environment variables</b> are defined '\n"
+"\tdb\t'on this web server:</p>', 0Ah, 0Ah\n"
+"\tdb\t'<table align=\"center\" width=\"80\" border=\"0\" cellpadding=\"10\" '\n"
+"\tdb\t'cellspacing=\"0\" class=\"webvars\">', 0Ah\n"
+"httplen\tequ\t$-http\n"
+"left\tdb\t'<tr>', 0Ah\n"
+"\tdb\t'<td class=\"name\"><tt>'\n"
+"leftlen\tequ\t$-left\n"
+"middle\tdb\t'</tt></td>', 0Ah\n"
+"\tdb\t'<td class=\"value\"><tt><b>'\n"
+"midlen\tequ\t$-middle\n"
+"undef\tdb\t'<i>(undefined)</i>'\n"
+"undeflen\tequ\t$-undef\n"
+"right\tdb\t'</b></tt></td>', 0Ah\n"
+"\tdb\t'</tr>', 0Ah\n"
+"rightlen\tequ\t$-right\n"
+"wrap\tdb\t'</table>', 0Ah\n"
+"\tdb\t'</div>', 0Ah\n"
+"\tdb\t'</body>', 0Ah\n"
+"\tdb\t'</html>', 0Ah, 0Ah\n"
+"wraplen\tequ\t$-wrap\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1532
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\t; First, send out all the http and xhtml stuff that is\n"
+"\t; needed before we start showing the environment\n"
+"\tpush\tdword httplen\n"
+"\tpush\tdword http\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"section\t.text\n"
+"global\t_start\n"
+"_start:\n"
+"\t; First, send out all the http and xhtml stuff that is\n"
+"\t; needed before we start showing the environment\n"
+"\tpush\tdword httplen\n"
+"\tpush\tdword http\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1536
+#, no-wrap
+msgid ""
+"\t; Now find how far on the stack the environment pointers\n"
+"\t; are. We have 12 bytes we have pushed before \"argc\"\n"
+"\tmov\teax, [esp+12]\n"
+msgstr ""
+"\t; Now find how far on the stack the environment pointers\n"
+"\t; are. We have 12 bytes we have pushed before \"argc\"\n"
+"\tmov\teax, [esp+12]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1551
+#, no-wrap
+msgid ""
+"\t; We need to remove the following from the stack:\n"
+"\t;\n"
+"\t;\tThe 12 bytes we pushed for sys.write\n"
+"\t;\tThe 4 bytes of argc\n"
+"\t;\tThe EAX*4 bytes of argv\n"
+"\t;\tThe 4 bytes of the NULL after argv\n"
+"\t;\n"
+"\t; Total:\n"
+"\t;\t20 + eax * 4\n"
+"\t;\n"
+"\t; Because stack grows down, we need to ADD that many bytes\n"
+"\t; to ESP.\n"
+"\tlea\tesp, [esp+20+eax*4]\n"
+"\tcld\t\t; This should already be the case, but let's be sure.\n"
+msgstr ""
+"\t; We need to remove the following from the stack:\n"
+"\t;\n"
+"\t;\tThe 12 bytes we pushed for sys.write\n"
+"\t;\tThe 4 bytes of argc\n"
+"\t;\tThe EAX*4 bytes of argv\n"
+"\t;\tThe 4 bytes of the NULL after argv\n"
+"\t;\n"
+"\t; Total:\n"
+"\t;\t20 + eax * 4\n"
+"\t;\n"
+"\t; Because stack grows down, we need to ADD that many bytes\n"
+"\t; to ESP.\n"
+"\tlea\tesp, [esp+20+eax*4]\n"
+"\tcld\t\t; This should already be the case, but let's be sure.\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1557
+#, no-wrap
+msgid ""
+"\t; Loop through the environment, printing it out\n"
+".loop:\n"
+"\tpop\tedi\n"
+"\tor\tedi, edi\t; Done yet?\n"
+"\tje\tnear .wrap\n"
+msgstr ""
+"\t; Loop through the environment, printing it out\n"
+".loop:\n"
+"\tpop\tedi\n"
+"\tor\tedi, edi\t; Done yet?\n"
+"\tje\tnear .wrap\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1563
+#, no-wrap
+msgid ""
+"\t; Print the left part of HTML\n"
+"\tpush\tdword leftlen\n"
+"\tpush\tdword left\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"\t; Print the left part of HTML\n"
+"\tpush\tdword leftlen\n"
+"\tpush\tdword left\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1574
+#, no-wrap
+msgid ""
+"\t; It may be tempting to search for the '=' in the env string next.\n"
+"\t; But it is possible there is no '=', so we search for the\n"
+"\t; terminating NUL first.\n"
+"\tmov\tesi, edi\t; Save start of string\n"
+"\tsub\tecx, ecx\n"
+"\tnot\tecx\t\t; ECX = FFFFFFFF\n"
+"\tsub\teax, eax\n"
+"repne\tscasb\n"
+"\tnot\tecx\t\t; ECX = string length + 1\n"
+"\tmov\tebx, ecx\t; Save it in EBX\n"
+msgstr ""
+"\t; It may be tempting to search for the '=' in the env string next.\n"
+"\t; But it is possible there is no '=', so we search for the\n"
+"\t; terminating NUL first.\n"
+"\tmov\tesi, edi\t; Save start of string\n"
+"\tsub\tecx, ecx\n"
+"\tnot\tecx\t\t; ECX = FFFFFFFF\n"
+"\tsub\teax, eax\n"
+"repne\tscasb\n"
+"\tnot\tecx\t\t; ECX = string length + 1\n"
+"\tmov\tebx, ecx\t; Save it in EBX\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1581
+#, no-wrap
+msgid ""
+"\t; Now is the time to find '='\n"
+"\tmov\tedi, esi\t; Start of string\n"
+"\tmov\tal, '='\n"
+"repne\tscasb\n"
+"\tnot\tecx\n"
+"\tadd\tecx, ebx\t; Length of name\n"
+msgstr ""
+"\t; Now is the time to find '='\n"
+"\tmov\tedi, esi\t; Start of string\n"
+"\tmov\tal, '='\n"
+"repne\tscasb\n"
+"\tnot\tecx\n"
+"\tadd\tecx, ebx\t; Length of name\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1586
+#, no-wrap
+msgid ""
+"\tpush\tecx\n"
+"\tpush\tesi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"\tpush\tecx\n"
+"\tpush\tesi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1592
+#, no-wrap
+msgid ""
+"\t; Print the middle part of HTML table code\n"
+"\tpush\tdword midlen\n"
+"\tpush\tdword middle\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"\t; Print the middle part of HTML table code\n"
+"\tpush\tdword midlen\n"
+"\tpush\tdword middle\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1596
+#, no-wrap
+msgid ""
+"\t; Find the length of the value\n"
+"\tnot\tecx\n"
+"\tlea\tebx, [ebx+ecx-1]\n"
+msgstr ""
+"\t; Find the length of the value\n"
+"\tnot\tecx\n"
+"\tlea\tebx, [ebx+ecx-1]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1600
+#, no-wrap
+msgid ""
+"\t; Print \"undefined\" if 0\n"
+"\tor\tebx, ebx\n"
+"\tjne\t.value\n"
+msgstr ""
+"\t; Print \"undefined\" if 0\n"
+"\tor\tebx, ebx\n"
+"\tjne\t.value\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1603
+#, no-wrap
+msgid ""
+"\tmov\tebx, undeflen\n"
+"\tmov\tedi, undef\n"
+msgstr ""
+"\tmov\tebx, undeflen\n"
+"\tmov\tedi, undef\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1609
+#, no-wrap
+msgid ""
+".value:\n"
+"\tpush\tebx\n"
+"\tpush\tedi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+".value:\n"
+"\tpush\tebx\n"
+"\tpush\tedi\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1615
+#, no-wrap
+msgid ""
+"\t; Print the right part of the table row\n"
+"\tpush\tdword rightlen\n"
+"\tpush\tdword right\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+"\t; Print the right part of the table row\n"
+"\tpush\tdword rightlen\n"
+"\tpush\tdword right\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1618
+#, no-wrap
+msgid ""
+"\t; Get rid of the 60 bytes we have pushed\n"
+"\tadd\tesp, byte 60\n"
+msgstr ""
+"\t; Get rid of the 60 bytes we have pushed\n"
+"\tadd\tesp, byte 60\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1621
+#, no-wrap
+msgid ""
+"\t; Get the next variable\n"
+"\tjmp\t.loop\n"
+msgstr ""
+"\t; Get the next variable\n"
+"\tjmp\t.loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1628
+#, no-wrap
+msgid ""
+".wrap:\n"
+"\t; Print the rest of HTML\n"
+"\tpush\tdword wraplen\n"
+"\tpush\tdword wrap\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+msgstr ""
+".wrap:\n"
+"\t; Print the rest of HTML\n"
+"\tpush\tdword wraplen\n"
+"\tpush\tdword wrap\n"
+"\tpush\tdword stdout\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1632
+#, no-wrap
+msgid ""
+"\t; Return success\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+"\t; Return success\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1636
+msgid ""
+"This code produces a 1,396-byte executable. Most of it is data, i.e., the "
+"HTML mark-up we need to send out."
+msgstr ""
+"Этот код создает исполняемый файл размером 1 396 байт. Большая его часть — "
+"это данные, а именно HTML-разметка, которую нам нужно отправить."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1638
+msgid "Assemble and link it as usual:"
+msgstr "Запустите ассемблер и слинкуйте как обычно:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1643
+#, no-wrap
+msgid ""
+"% nasm -f elf webvars.asm\n"
+"% ld -s -o webvars webvars.o\n"
+msgstr ""
+"% nasm -f elf webvars.asm\n"
+"% ld -s -o webvars webvars.o\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1647
+msgid ""
+"To use it, you need to upload [.filename]#webvars# to your web server. "
+"Depending on how your web server is set up, you may have to store it in a "
+"special [.filename]#cgi-bin# directory, or perhaps rename it with a "
+"[.filename]#.cgi# extension."
+msgstr ""
+"Для использования необходимо загрузить [.filename]#webvars# на ваш веб-"
+"сервер. В зависимости от настроек веб-сервера, возможно, потребуется "
+"разместить его в специальном каталоге [.filename]#cgi-bin# или переименовать "
+"с расширением [.filename]#.cgi#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1651
+msgid ""
+"Then you need to use your browser to view its output. To see its output on "
+"my web server, please go to http://www.int80h.org/webvars/[http://"
+"www.int80h.org/webvars/]. If curious about the additional environment "
+"variables present in a password protected web directory, go to http://"
+"www.int80h.org/private/[http://www.int80h.org/private/], using the name "
+"`asm` and password `programmer`."
+msgstr ""
+"Затем вам нужно использовать браузер для просмотра вывода. Чтобы увидеть "
+"вывод на моем веб-сервере, перейдите по ссылке http://www.int80h.org/webvars/"
+"[http://www.int80h.org/webvars/]. Если вам интересно узнать о дополнительных "
+"переменных окружения в защищенном паролем веб-каталоге, перейдите по адресу "
+"http://www.int80h.org/private/[http://www.int80h.org/private/], используя "
+"имя `asm` и пароль `programmer`."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1653
+#, no-wrap
+msgid "Working with Files"
+msgstr "Работа с файлами"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1658
+msgid ""
+"We have already done some basic file work: We know how to open and close "
+"them, how to read and write them using buffers. But UNIX(R) offers much "
+"more functionality when it comes to files. We will examine some of it in "
+"this section, and end up with a nice file conversion utility."
+msgstr ""
+"Мы уже выполнили некоторые базовые операции с файлами: мы знаем, как их "
+"открывать и закрывать, как читать и записывать их с использованием буферов. "
+"Однако UNIX(R) предлагает гораздо больше возможностей при работе с файлами. "
+"В этом разделе мы рассмотрим некоторые из них и в итоге создадим удобную "
+"утилиту для преобразования файлов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1661
+msgid ""
+"Indeed, let us start at the end, that is, with the file conversion utility. "
+"It always makes programming easier when we know from the start what the end "
+"product is supposed to do."
+msgstr ""
+"В самом деле, начнем с конца, то есть с утилиты преобразования файлов. "
+"Всегда легче программировать, когда с самого начала известно, каким должен "
+"быть конечный продукт."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1667
+msgid ""
+"One of the first programs I wrote for UNIX(R) was link:ftp://ftp.int80h.org/"
+"unix/tuc/[tuc], a text-to-UNIX(R) file converter. It converts a text file "
+"from other operating systems to a UNIX(R) text file. In other words, it "
+"changes from different kind of line endings to the newline convention of "
+"UNIX(R). It saves the output in a different file. Optionally, it converts "
+"a UNIX(R) text file to a DOS text file."
+msgstr ""
+"Одной из первых программ, которые я написал для UNIX(R), была link:ftp://"
+"ftp.int80h.org/unix/tuc/[tuc] — конвертер текста в файл UNIX(R). Она "
+"преобразует текстовый файл из других операционных систем в текстовый файл "
+"UNIX(R). Другими словами, она изменяет различные виды окончаний строк на "
+"стандартные для UNIX(R). Результат сохраняется в другом файле. По желанию, "
+"она может преобразовать текстовый файл UNIX(R) в текстовый файл DOS."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1671
+msgid ""
+"I have used tuc extensively, but always only to convert from some other OS "
+"to UNIX(R), never the other way. I have always wished it would just "
+"overwrite the file instead of me having to send the output to a different "
+"file. Most of the time, I end up using it like this:"
+msgstr ""
+"Я широко использовал `tuc`, но всегда только для преобразования из какой-"
+"либо другой ОС в UNIX(R), никогда наоборот. Мне всегда хотелось, чтобы он "
+"просто перезаписывал файл, вместо того чтобы мне приходилось отправлять "
+"вывод в другой файл. В большинстве случаев я в итоге использую его так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1676
+#, no-wrap
+msgid ""
+"% tuc myfile tempfile\n"
+"% mv tempfile myfile\n"
+msgstr ""
+"% tuc myfile tempfile\n"
+"% mv tempfile myfile\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1679
+msgid ""
+"It would be nice to have a ftuc, i.e., _fast tuc_, and use it like this:"
+msgstr ""
+"Было бы здорово иметь ftuc, т.е., _быстрый tuc_, и использовать его вот так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1683
+#, no-wrap
+msgid "% ftuc myfile\n"
+msgstr "% ftuc myfile\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1686
+msgid ""
+"In this chapter, then, we will write ftuc in assembly language (the original "
+"tuc is in C), and study various file-oriented kernel services in the process."
+msgstr ""
+"В этой главе мы напишем ftuc на языке ассемблера (оригинальный tuc написан "
+"на C) и в процессе изучим различные файловые сервисы ядра."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1688
+msgid ""
+"At first sight, such a file conversion is very simple: All you have to do is "
+"strip the carriage returns, right?"
+msgstr ""
+"На первый взгляд, такое преобразование файла кажется очень простым: нужно "
+"всего лишь удалить символы возврата каретки, верно?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1690
+msgid ""
+"If you answered yes, think again: That approach will work most of the time "
+"(at least with MS DOS text files), but will fail occasionally."
+msgstr ""
+"Если вы ответили «да», подумайте ещё раз: такой подход будет работать в "
+"большинстве случаев (по крайней мере, с текстовыми файлами MS DOS), но "
+"иногда он будет давать сбой."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1695
+msgid ""
+"The problem is that not all non UNIX(R) text files end their line with the "
+"carriage return / line feed sequence. Some use carriage returns without "
+"line feeds. Others combine several blank lines into a single carriage "
+"return followed by several line feeds. And so on."
+msgstr ""
+"Проблема в том, что не все текстовые файлы, не относящиеся к UNIX(R), "
+"завершают строки последовательностью возврата каретки / перевода строки. "
+"Некоторые используют возврат каретки без перевода строки. Другие объединяют "
+"несколько пустых строк в один возврат каретки, за которым следует несколько "
+"переводов строки. И так далее."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1697
+msgid ""
+"A text file converter, then, must be able to handle any possible line "
+"endings:"
+msgstr ""
+"Конвертер текстовых файлов, следовательно, должен уметь обрабатывать любые "
+"возможные окончания строк:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1699
+msgid "carriage return / line feed"
+msgstr "возврат каретки (carriage return) / перевод строки (line feed)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1700
+msgid "carriage return"
+msgstr "возврат каретки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1701
+msgid "line feed / carriage return"
+msgstr "перевод строки / возврат каретки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1702
+msgid "line feed"
+msgstr "перевод строки"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1704
+msgid ""
+"It should also handle files that use some kind of a combination of the above "
+"(e.g., carriage return followed by several line feeds)."
+msgstr ""
+"Это также должно обрабатывать файлы, использующие комбинации вышеуказанного "
+"(например, возврат каретки с последующими несколькими переводами строки)."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1706
+#, no-wrap
+msgid "Finite State Machine"
+msgstr "Конечный автомат"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1713
+msgid ""
+"The problem is easily solved by the use of a technique called _finite state "
+"machine_, originally developed by the designers of digital electronic "
+"circuits. A _finite state machine_ is a digital circuit whose output is "
+"dependent not only on its input but on its previous input, i.e., on its "
+"state. The microprocessor is an example of a _finite state machine_: Our "
+"assembly language code is assembled to machine language in which some "
+"assembly language code produces a single byte of machine language, while "
+"others produce several bytes. As the microprocessor fetches the bytes from "
+"the memory one by one, some of them simply change its state rather than "
+"produce some output. When all the bytes of the op code are fetched, the "
+"microprocessor produces some output, or changes the value of a register, etc."
+msgstr ""
+"Проблема легко решается с использованием техники, называемой _конечный "
+"автомат_, изначально разработанной создателями цифровых электронных схем. "
+"_Конечный автомат_ — это цифровая схема, выход которой зависит не только от "
+"входа, но и от предыдущего входа, то есть от её состояния. Микропроцессор "
+"является примером _конечного автомата_: наш код на языке ассемблера "
+"транслируется в машинный язык, где одни инструкции ассемблера превращаются в "
+"один байт машинного кода, а другие — в несколько байтов. Когда "
+"микропроцессор извлекает байты из памяти один за другим, некоторые из них "
+"просто изменяют его состояние, а не производят какой-либо выходной сигнал. "
+"После извлечения всех байтов кода операции микропроцессор выдает выходной "
+"сигнал, изменяет значение регистра и т. д."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1716
+msgid ""
+"Because of that, all software is essentially a sequence of state "
+"instructions for the microprocessor. Nevertheless, the concept of _finite "
+"state machine_ is useful in software design as well."
+msgstr ""
+"Из-за этого всё программное обеспечение по сути представляет собой "
+"последовательность инструкций состояния для микропроцессора. Тем не менее, "
+"концепция _конечного автомата_ также полезна при проектировании программного "
+"обеспечения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1719
+msgid ""
+"Our text file converter can be designer as a _finite state machine_ with "
+"three possible states. We could call them states 0-2, but it will make our "
+"life easier if we give them symbolic names:"
+msgstr ""
+"Наш конвертер текстовых файлов можно представить в виде _конечного автомата_ "
+"с тремя возможными состояниями. Мы могли бы назвать их состояниями 0-2, но "
+"будет проще, если дадим им символические имена:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1721
+msgid "ordinary"
+msgstr "ordinary"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1722
+msgid "cr"
+msgstr "cr"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1723
+msgid "lf"
+msgstr "lf"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1725
+msgid ""
+"Our program will start in the ordinary state. During this state, the program "
+"action depends on its input as follows:"
+msgstr ""
+"Наша программа начнёт работу в обычном состоянии. В этом состоянии действие "
+"программы зависит от её входных данных следующим образом:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1728
+msgid ""
+"If the input is anything other than a carriage return or line feed, the "
+"input is simply passed on to the output. The state remains unchanged."
+msgstr ""
+"Если ввод представляет собой что-либо, кроме возврата каретки или перевода "
+"строки, ввод просто передаётся на вывод. Состояние остаётся неизменным."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1730
+msgid ""
+"If the input is a carriage return, the state is changed to cr. The input is "
+"then discarded, i.e., no output is made."
+msgstr ""
+"Если входной символ — возврат каретки, состояние изменяется на cr. Затем "
+"входной символ отбрасывается, т.е. вывод не производится."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1732
+msgid ""
+"If the input is a line feed, the state is changed to lf. The input is then "
+"discarded."
+msgstr ""
+"Если входной символ является переводом строки, состояние изменяется на lf. "
+"Затем входной символ отбрасывается."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1735
+msgid ""
+"Whenever we are in the cr state, it is because the last input was a carriage "
+"return, which was unprocessed. What our software does in this state again "
+"depends on the current input:"
+msgstr ""
+"Всякий раз, когда мы находимся в состоянии `cr`, это означает, что последним "
+"вводом был символ возврата каретки, который не был обработан. Действия "
+"нашего программного обеспечения в этом состоянии снова зависят от текущего "
+"ввода:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1737
+msgid ""
+"If the input is anything other than a carriage return or line feed, output a "
+"line feed, then output the input, then change the state to ordinary."
+msgstr ""
+"Если ввод отличается от возврата каретки или перевода строки, вывести "
+"перевод строки, затем вывести ввод, а затем изменить состояние на обычное."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1738
+msgid ""
+"If the input is a carriage return, we have received two (or more) carriage "
+"returns in a row. We discard the input, we output a line feed, and leave the "
+"state unchanged."
+msgstr ""
+"Если входной символ — возврат каретки, значит, мы получили два (или более) "
+"возврата каретки подряд. Мы отбрасываем ввод, выводим перевод строки и "
+"оставляем состояние неизменным."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1739
+msgid ""
+"If the input is a line feed, we output the line feed and change the state to "
+"ordinary. Note that this is not the same as the first case above - if we "
+"tried to combine them, we would be outputting two line feeds instead of one."
+msgstr ""
+"Если входной символ — это перевод строки, мы выводим перевод строки и меняем "
+"состояние на обычное. Обратите внимание, что это не то же самое, что в "
+"первом случае выше — если бы мы попытались объединить их, мы бы выводили два "
+"перевода строки вместо одного."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1743
+msgid ""
+"Finally, we are in the lf state after we have received a line feed that was "
+"not preceded by a carriage return. This will happen when our file already "
+"is in UNIX(R) format, or whenever several lines in a row are expressed by a "
+"single carriage return followed by several line feeds, or when line ends "
+"with a line feed / carriage return sequence. Here is how we need to handle "
+"our input in this state:"
+msgstr ""
+"Наконец, мы находимся в состоянии `lf` после получения перевода строки, "
+"которому не предшествовал возврат каретки. Это произойдет, если наш файл уже "
+"в формате UNIX(R), или когда несколько строк подряд выражены одним возвратом "
+"каретки, за которым следуют несколько переводов строк, или когда строка "
+"заканчивается последовательностью перевода строки / возврата каретки. Вот "
+"как нам нужно обрабатывать ввод в этом состоянии:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1745
+msgid ""
+"If the input is anything other than a carriage return or line feed, we "
+"output a line feed, then output the input, then change the state to "
+"ordinary. This is exactly the same action as in the cr state upon receiving "
+"the same kind of input."
+msgstr ""
+"Если ввод отличается от возврата каретки или перевода строки, мы выводим "
+"перевод строки, затем выводим ввод и изменяем состояние на обычное. Это "
+"действие полностью совпадает с действием в состоянии `cr` при получении "
+"аналогичного ввода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1746
+msgid ""
+"If the input is a carriage return, we discard the input, we output a line "
+"feed, then change the state to ordinary."
+msgstr ""
+"Если ввод представляет собой символ возврата каретки, мы отбрасываем ввод, "
+"выводим символ перевода строки, затем изменяем состояние на обычное."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1747
+msgid ""
+"If the input is a line feed, we output the line feed, and leave the state "
+"unchanged."
+msgstr ""
+"Если входной символ — перевод строки, мы выводим перевод строки и оставляем "
+"состояние неизменным."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1749
+#, no-wrap
+msgid "The Final State"
+msgstr "Конечное состояние"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1754
+msgid ""
+"The above _finite state machine_ works for the entire file, but leaves the "
+"possibility that the final line end will be ignored. That will happen "
+"whenever the file ends with a single carriage return or a single line feed. "
+"I did not think of it when I wrote tuc, just to discover that occasionally "
+"it strips the last line ending."
+msgstr ""
+"Приведённый выше _конечный автомат_ работает для всего файла, но оставляет "
+"возможность, что последний конец строки будет проигнорирован. Это "
+"произойдёт, если файл заканчивается одиночным возвратом каретки или "
+"одиночным переводом строки. Я не подумал об этом, когда писал tuc, и лишь "
+"позже обнаружил, что иногда он удаляет последний конец строки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1757
+msgid ""
+"This problem is easily fixed by checking the state after the entire file was "
+"processed. If the state is not ordinary, we simply need to output one last "
+"line feed."
+msgstr ""
+"Эта проблема легко решается проверкой состояния после обработки всего файла. "
+"Если состояние не является обычным, нам просто нужно вывести последний "
+"перевод строки."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1763
+msgid ""
+"Now that we have expressed our algorithm as a _finite state machine_, we "
+"could easily design a dedicated digital electronic circuit (a \"chip\") to "
+"do the conversion for us. Of course, doing so would be considerably more "
+"expensive than writing an assembly language program."
+msgstr ""
+"Теперь, когда мы выразили наш алгоритм в виде _конечного автомата_, мы могли "
+"бы легко разработать специализированную цифровую электронную схему («чип») "
+"для выполнения преобразования. Конечно, это было бы значительно дороже, чем "
+"написание программы на языке ассемблера."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1766
+#, no-wrap
+msgid "The Output Counter"
+msgstr "Счетчик вывода"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1771
+msgid ""
+"Because our file conversion program may be combining two characters into "
+"one, we need to use an output counter. We initialize it to `0`, and "
+"increase it every time we send a character to the output. At the end of the "
+"program, the counter will tell us what size we need to set the file to."
+msgstr ""
+"Поскольку наша программа преобразования файлов может объединять два символа "
+"в один, нам необходимо использовать счётчик вывода. Мы инициализируем его "
+"значением `0` и увеличиваем каждый раз, когда отправляем символ на выход. В "
+"конце программы счётчик укажет, какой размер необходимо установить для файла."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1773
+#, no-wrap
+msgid "Implementing FSM in Software"
+msgstr "Реализация конечного автомата в программном обеспечении"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1777
+msgid ""
+"The hardest part of working with a _finite state machine_ is analyzing the "
+"problem and expressing it as a _finite state machine_. That accomplished, "
+"the software almost writes itself."
+msgstr ""
+"Самая сложная часть работы с _конечным автоматом_ — это анализ задачи и её "
+"представление в виде _конечного автомата_. После этого программное "
+"обеспечение практически пишется само."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1780
+msgid ""
+"In a high-level language, such as C, there are several main approaches. One "
+"is to use a `switch` statement which chooses what function should be run. "
+"For example,"
+msgstr ""
+"На языке высокого уровня, таком как C, существует несколько основных "
+"подходов. Один из них — использование оператора `switch`, который выбирает, "
+"какую функцию следует выполнить. Например,"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1795
+#, no-wrap
+msgid ""
+"switch (state) {\n"
+"\tdefault:\n"
+"\tcase REGULAR:\n"
+"\t\tregular(inputchar);\n"
+"\t\tbreak;\n"
+"\tcase CR:\n"
+"\t\tcr(inputchar);\n"
+"\t\tbreak;\n"
+"\tcase LF:\n"
+"\t\tlf(inputchar);\n"
+"\t\tbreak;\n"
+"\t}\n"
+msgstr ""
+"switch (state) {\n"
+"\tdefault:\n"
+"\tcase REGULAR:\n"
+"\t\tregular(inputchar);\n"
+"\t\tbreak;\n"
+"\tcase CR:\n"
+"\t\tcr(inputchar);\n"
+"\t\tbreak;\n"
+"\tcase LF:\n"
+"\t\tlf(inputchar);\n"
+"\t\tbreak;\n"
+"\t}\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1798
+msgid ""
+"Another approach is by using an array of function pointers, something like "
+"this:"
+msgstr ""
+"Еще один подход заключается в использовании массива указателей на функции, "
+"например:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1802
+#, no-wrap
+msgid "(output[state])(inputchar);\n"
+msgstr "(output[state])(inputchar);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1805
+msgid ""
+"Yet another is to have `state` be a function pointer, set to point at the "
+"appropriate function:"
+msgstr ""
+"Еще один вариант — сделать `state` указателем на функцию, установив его на "
+"соответствующую функцию:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1809
+#, no-wrap
+msgid "(*state)(inputchar);\n"
+msgstr "(*state)(inputchar);\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1813
+msgid ""
+"This is the approach we will use in our program because it is very easy to "
+"do in assembly language, and very fast, too. We will simply keep the "
+"address of the right procedure in `EBX`, and then just issue:"
+msgstr ""
+"Это подход, который мы будем использовать в нашей программе, потому что его "
+"очень легко реализовать на языке ассемблера, и он также очень быстрый. Мы "
+"просто будем хранить адрес нужной процедуры в `EBX`, а затем выполним:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1817
+#, no-wrap
+msgid "call\tebx\n"
+msgstr "call\tebx\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1821
+msgid ""
+"This is possibly faster than hardcoding the address in the code because the "
+"microprocessor does not have to fetch the address from the memory-it is "
+"already stored in one of its registers. I said _possibly_ because with the "
+"caching modern microprocessors do, either way may be equally fast."
+msgstr ""
+"Это возможно быстрее, чем жестко задавать адрес в коде, потому что "
+"микропроцессору не нужно извлекать адрес из памяти — он уже хранится в одном "
+"из его регистров. Я сказал _возможно_, потому что с учетом кэширования, "
+"которое выполняют современные микропроцессоры, оба варианта могут быть "
+"одинаково быстрыми."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1823
+#, no-wrap
+msgid "Memory Mapped Files"
+msgstr "Отображенные в память файлы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1827
+msgid ""
+"Because our program works on a single file, we cannot use the approach that "
+"worked for us before, i.e., to read from an input file and to write to an "
+"output file."
+msgstr ""
+"Поскольку наша программа работает с одним файлом, мы не можем использовать "
+"подход, который работал ранее, то есть чтение из входного файла и запись в "
+"выходной файл."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1835
+msgid ""
+"UNIX(R) allows us to map a file, or a section of a file, into memory. To do "
+"that, we first need to open the file with the appropriate read/write flags. "
+"Then we use the `mmap` system call to map it into the memory. One nice "
+"thing about `mmap` is that it automatically works with virtual memory: We "
+"can map more of the file into the memory than we have physical memory "
+"available, yet still access it through regular memory op codes, such as "
+"`mov`, `lods`, and `stos`. Whatever changes we make to the memory image of "
+"the file will be written to the file by the system. We do not even have to "
+"keep the file open: As long as it stays mapped, we can read from it and "
+"write to it."
+msgstr ""
+"UNIX(R) позволяет нам отображать файл или его часть в память. Для этого "
+"сначала необходимо открыть файл с соответствующими флагами чтения/записи. "
+"Затем мы используем системный вызов `mmap`, чтобы отобразить его в память. "
+"Одно из преимуществ `mmap` заключается в том, что он автоматически работает "
+"с виртуальной памятью: мы можем отобразить в память больше файла, чем "
+"имеется физической памяти, и при этом обращаться к нему с помощью обычных "
+"команд работы с памятью, таких как `mov`, `lods` и `stos`. Все изменения, "
+"внесённые в память, отображённую из файла, будут записаны в файл системой. "
+"Нам даже не нужно держать файл открытым: пока он остаётся отображённым, мы "
+"можем читать из него и записывать в него."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1838
+msgid ""
+"The 32-bit Intel microprocessors can access up to four gigabytes of memory - "
+"physical or virtual. The FreeBSD system allows us to use up to a half of it "
+"for file mapping."
+msgstr ""
+"32-разрядные микропроцессоры Intel могут адресовать до четырёх гигабайт "
+"памяти — физической или виртуальной. Система FreeBSD позволяет использовать "
+"до половины этого объёма для отображения файлов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1842
+msgid ""
+"For simplicity sake, in this tutorial we will only convert files that can be "
+"mapped into the memory in their entirety. There are probably not too many "
+"text files that exceed two gigabytes in size. If our program encounters "
+"one, it will simply display a message suggesting we use the original tuc "
+"instead."
+msgstr ""
+"Для упрощения в этом руководстве мы будем преобразовывать только файлы, "
+"которые могут быть полностью отображены в памяти. Вероятно, не так много "
+"текстовых файлов превышают размер в два гигабайта. Если наша программа "
+"встретит такой файл, она просто выведет сообщение с предложением "
+"использовать оригинальный tuc."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1848
+msgid ""
+"If you examine your copy of [.filename]#syscalls.master#, you will find two "
+"separate syscalls named `mmap`. This is because of evolution of UNIX(R): "
+"There was the traditional BSD `mmap`, syscall 71. That one was superseded "
+"by the POSIX(R) `mmap`, syscall 197. The FreeBSD system supports both "
+"because older programs were written by using the original BSD version. But "
+"new software uses the POSIX(R) version, which is what we will use."
+msgstr ""
+"Если вы изучите свою копию файла [.filename]#syscalls.master#, вы найдёте "
+"два отдельных системных вызова с именем `mmap`. Это связано с эволюцией "
+"UNIX(R): существовал традиционный BSD `mmap`, системный вызов 71. Он был "
+"заменён на POSIX(R) `mmap`, системный вызов 197. Система FreeBSD "
+"поддерживает оба, поскольку старые программы были написаны с использованием "
+"оригинальной BSD-версии. Но новое программное обеспечение использует версию "
+"POSIX(R), которую мы и будем применять."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1850
+msgid "The [.filename]#syscalls.master# lists the POSIX(R) version like this:"
+msgstr ""
+"В [.filename]#syscalls.master# POSIX(R) версия указана следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1855
+#, no-wrap
+msgid ""
+"197\tSTD\tBSD\t{ caddr_t mmap(caddr_t addr, size_t len, int prot, \\\n"
+"\t\t\t int flags, int fd, long pad, off_t pos); }\n"
+msgstr ""
+"197\tSTD\tBSD\t{ caddr_t mmap(caddr_t addr, size_t len, int prot, \\\n"
+"\t\t\t int flags, int fd, long pad, off_t pos); }\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1859
+msgid ""
+"This differs slightly from what man:mmap[2] says. That is because "
+"man:mmap[2] describes the C version."
+msgstr ""
+"Это немного отличается от того, что указано в man:mmap[2]. Это связано с "
+"тем, что man:mmap[2] описывает версию на языке C."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1863
+msgid ""
+"The difference is in the `long pad` argument, which is not present in the C "
+"version. However, the FreeBSD syscalls add a 32-bit pad after ``push``ing a "
+"64-bit argument. In this case, `off_t` is a 64-bit value."
+msgstr ""
+"Разница заключается в аргументе `long pad`, который отсутствует в версии на "
+"C. Однако системные вызовы FreeBSD добавляют 32-битный заполнитель после "
+"``push`` 64-битного аргумента. В данном случае `off_t` является 64-битным "
+"значением."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1865
+msgid ""
+"When we are finished working with a memory-mapped file, we unmap it with the "
+"`munmap` syscall:"
+msgstr ""
+"Когда мы завершаем работу с файлом, отображённым в память, мы освобождаем "
+"его с помощью системного вызова `munmap`:"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1869
+msgid ""
+"For an in-depth treatment of `mmap`, see W. Richard Stevens' http://"
+"www.int80h.org/cgi-bin/isbn?isbn=0130810819[Unix Network Programming, Volume "
+"2, Chapter 12]."
+msgstr ""
+"Для подробного изучения `mmap` см. http://www.int80h.org/cgi-bin/isbn?"
+"isbn=0130810819[Unix Network Programming, Volume 2, Chapter 12] У. Ричарда "
+"Стивенса."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1872
+#, no-wrap
+msgid "Determining File Size"
+msgstr "Определение размера файла"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1875
+msgid ""
+"Because we need to tell `mmap` how many bytes of the file to map into the "
+"memory, and because we want to map the entire file, we need to determine the "
+"size of the file."
+msgstr ""
+"Поскольку нам нужно указать `mmap`, сколько байт файла отобразить в памяти, "
+"и поскольку мы хотим отобразить весь файл, нам необходимо определить его "
+"размер."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1878
+msgid ""
+"We can use the `fstat` syscall to get all the information about an open file "
+"that the system can give us. That includes the file size."
+msgstr ""
+"Мы можем использовать системный вызов `fstat` для получения всей информации "
+"об открытом файле, которую система может нам предоставить. Это включает в "
+"себя размер файла."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1881
+msgid ""
+"Again, [.filename]#syscalls.master# lists two versions of `fstat`, a "
+"traditional one (syscall 62), and a POSIX(R) one (syscall 189). Naturally, "
+"we will use the POSIX(R) version:"
+msgstr ""
+"Вновь, в [.filename]#syscalls.master# указаны две версии `fstat`: "
+"традиционная (системный вызов 62) и POSIX(R) (системный вызов 189). "
+"Естественно, мы будем использовать версию POSIX(R):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1885
+#, no-wrap
+msgid "189\tSTD\tPOSIX\t{ int fstat(int fd, struct stat *sb); }\n"
+msgstr "189\tSTD\tPOSIX\t{ int fstat(int fd, struct stat *sb); }\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1889
+msgid ""
+"This is a very straightforward call: We pass to it the address of a `stat` "
+"structure and the descriptor of an open file. It will fill out the contents "
+"of the `stat` structure."
+msgstr ""
+"Это очень простой вызов: мы передаем ему адрес структуры `stat` и дескриптор "
+"открытого файла. Он заполнит содержимое структуры `stat`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1892
+msgid ""
+"I do, however, have to say that I tried to declare the `stat` structure in "
+"the `.bss` section, and `fstat` did not like it: It set the carry flag "
+"indicating an error. After I changed the code to allocate the structure on "
+"the stack, everything was working fine."
+msgstr ""
+"Однако должен сказать, что я пытался объявить структуру `stat` в секции "
+"`.bss`, и `fstat` это не понравилось: был установлен флаг переноса, "
+"указывающий на ошибку. После того как я изменил код, чтобы разместить "
+"структуру в стеке, всё заработало как надо."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1894
+#, no-wrap
+msgid "Changing the File Size"
+msgstr "Изменение размера файла"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1898
+msgid ""
+"Because our program may combine carriage return / line feed sequences into "
+"straight line feeds, our output may be smaller than our input. However, "
+"since we are placing our output into the same file we read the input from, "
+"we may have to change the size of the file."
+msgstr ""
+"Поскольку наша программа может объединять последовательности возврата "
+"каретки / перевода строки в простые переводы строк, наш вывод может быть "
+"меньше, чем ввод. Однако, так как мы помещаем вывод в тот же файл, из "
+"которого читаем ввод, нам может потребоваться изменить размер файла."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1901
+msgid ""
+"The `ftruncate` system call allows us to do just that. Despite its somewhat "
+"misleading name, the `ftruncate` system call can be used to both truncate "
+"the file (make it smaller) and to grow it."
+msgstr ""
+"Системный вызов `ftruncate` позволяет нам сделать именно это. Несмотря на "
+"название , несколько вводящее в звблуждение, системный вызов `ftruncate` "
+"может использоваться как для усечения файла (уменьшения его размера), так и "
+"для его увеличения."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1904
+msgid ""
+"And yes, we will find two versions of `ftruncate` in "
+"[.filename]#syscalls.master#, an older one (130), and a newer one (201). We "
+"will use the newer one:"
+msgstr ""
+"И да, мы найдем две версии `ftruncate` в [.filename]#syscalls.master#, "
+"старую (130) и новую (201). Мы будем использовать новую:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1908
+#, no-wrap
+msgid "201\tSTD\tBSD\t{ int ftruncate(int fd, int pad, off_t length); }\n"
+msgstr "201\tSTD\tBSD\t{ int ftruncate(int fd, int pad, off_t length); }\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1911
+msgid "Please note that this one contains a `int pad` again."
+msgstr "Обратите внимание, что здесь снова присутствует `int pad`."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1913
+#, no-wrap
+msgid "ftuc"
+msgstr "ftuc"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1918
+msgid ""
+"We now know everything we need to write ftuc. We start by adding some new "
+"lines in [.filename]#system.inc#. First, we define some constants and "
+"structures, somewhere at or near the beginning of the file:"
+msgstr ""
+"Теперь мы знаем всё, что нужно для написания ftuc. Начнём с добавления "
+"нескольких новых строк в [.filename]#system.inc#. Сначала определим "
+"некоторые константы и структуры, где-нибудь в начале или около начала файла:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1925
+#, no-wrap
+msgid ""
+";;;;;;; open flags\n"
+"%define\tO_RDONLY\t0\n"
+"%define\tO_WRONLY\t1\n"
+"%define\tO_RDWR\t2\n"
+msgstr ""
+";;;;;;; open flags\n"
+"%define\tO_RDONLY\t0\n"
+"%define\tO_WRONLY\t1\n"
+"%define\tO_RDWR\t2\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1934
+#, no-wrap
+msgid ""
+";;;;;;; mmap flags\n"
+"%define\tPROT_NONE\t0\n"
+"%define\tPROT_READ\t1\n"
+"%define\tPROT_WRITE\t2\n"
+"%define\tPROT_EXEC\t4\n"
+";;\n"
+"%define\tMAP_SHARED\t0001h\n"
+"%define\tMAP_PRIVATE\t0002h\n"
+msgstr ""
+";;;;;;; mmap flags\n"
+"%define\tPROT_NONE\t0\n"
+"%define\tPROT_READ\t1\n"
+"%define\tPROT_WRITE\t2\n"
+"%define\tPROT_EXEC\t4\n"
+";;\n"
+"%define\tMAP_SHARED\t0001h\n"
+"%define\tMAP_PRIVATE\t0002h\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1958
+#, no-wrap
+msgid ""
+";;;;;;; stat structure\n"
+"struc\tstat\n"
+"st_dev\t\tresd\t1\t; = 0\n"
+"st_ino\t\tresd\t1\t; = 4\n"
+"st_mode\t\tresw\t1\t; = 8, size is 16 bits\n"
+"st_nlink\tresw\t1\t; = 10, ditto\n"
+"st_uid\t\tresd\t1\t; = 12\n"
+"st_gid\t\tresd\t1\t; = 16\n"
+"st_rdev\t\tresd\t1\t; = 20\n"
+"st_atime\tresd\t1\t; = 24\n"
+"st_atimensec\tresd\t1\t; = 28\n"
+"st_mtime\tresd\t1\t; = 32\n"
+"st_mtimensec\tresd\t1\t; = 36\n"
+"st_ctime\tresd\t1\t; = 40\n"
+"st_ctimensec\tresd\t1\t; = 44\n"
+"st_size\t\tresd\t2\t; = 48, size is 64 bits\n"
+"st_blocks\tresd\t2\t; = 56, ditto\n"
+"st_blksize\tresd\t1\t; = 64\n"
+"st_flags\tresd\t1\t; = 68\n"
+"st_gen\t\tresd\t1\t; = 72\n"
+"st_lspare\tresd\t1\t; = 76\n"
+"st_qspare\tresd\t4\t; = 80\n"
+"endstruc\n"
+msgstr ""
+";;;;;;; stat structure\n"
+"struc\tstat\n"
+"st_dev\t\tresd\t1\t; = 0\n"
+"st_ino\t\tresd\t1\t; = 4\n"
+"st_mode\t\tresw\t1\t; = 8, size is 16 bits\n"
+"st_nlink\tresw\t1\t; = 10, ditto\n"
+"st_uid\t\tresd\t1\t; = 12\n"
+"st_gid\t\tresd\t1\t; = 16\n"
+"st_rdev\t\tresd\t1\t; = 20\n"
+"st_atime\tresd\t1\t; = 24\n"
+"st_atimensec\tresd\t1\t; = 28\n"
+"st_mtime\tresd\t1\t; = 32\n"
+"st_mtimensec\tresd\t1\t; = 36\n"
+"st_ctime\tresd\t1\t; = 40\n"
+"st_ctimensec\tresd\t1\t; = 44\n"
+"st_size\t\tresd\t2\t; = 48, size is 64 bits\n"
+"st_blocks\tresd\t2\t; = 56, ditto\n"
+"st_blksize\tresd\t1\t; = 64\n"
+"st_flags\tresd\t1\t; = 68\n"
+"st_gen\t\tresd\t1\t; = 72\n"
+"st_lspare\tresd\t1\t; = 76\n"
+"st_qspare\tresd\t4\t; = 80\n"
+"endstruc\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1961
+msgid "We define the new syscalls:"
+msgstr "Мы определяем новые системные вызовы:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1968
+#, no-wrap
+msgid ""
+"%define\tSYS_mmap\t197\n"
+"%define\tSYS_munmap\t73\n"
+"%define\tSYS_fstat\t189\n"
+"%define\tSYS_ftruncate\t201\n"
+msgstr ""
+"%define\tSYS_mmap\t197\n"
+"%define\tSYS_munmap\t73\n"
+"%define\tSYS_fstat\t189\n"
+"%define\tSYS_ftruncate\t201\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1971
+msgid "We add the macros for their use:"
+msgstr "Добавляем макросы для их использования:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1977
+#, no-wrap
+msgid ""
+"%macro\tsys.mmap\t0\n"
+"\tsystem\tSYS_mmap\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.mmap\t0\n"
+"\tsystem\tSYS_mmap\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1981
+#, no-wrap
+msgid ""
+"%macro\tsys.munmap\t0\n"
+"\tsystem\tSYS_munmap\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.munmap\t0\n"
+"\tsystem\tSYS_munmap\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1985
+#, no-wrap
+msgid ""
+"%macro\tsys.ftruncate\t0\n"
+"\tsystem\tSYS_ftruncate\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.ftruncate\t0\n"
+"\tsystem\tSYS_ftruncate\n"
+"%endmacro\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1989
+#, no-wrap
+msgid ""
+"%macro\tsys.fstat\t0\n"
+"\tsystem\tSYS_fstat\n"
+"%endmacro\n"
+msgstr ""
+"%macro\tsys.fstat\t0\n"
+"\tsystem\tSYS_fstat\n"
+"%endmacro\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:1992
+msgid "And here is our code:"
+msgstr "И вот наш код:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2005
+#, no-wrap
+msgid ""
+";;;;;;; Fast Text-to-Unix Conversion (ftuc.asm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";;\n"
+";; Started:\t21-Dec-2000\n"
+";; Updated:\t22-Dec-2000\n"
+";;\n"
+";; Copyright 2000 G. Adam Stanislav.\n"
+";; All rights reserved.\n"
+";;\n"
+";;;;;;; v.1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+"%include\t'system.inc'\n"
+msgstr ""
+";;;;;;; Fast Text-to-Unix Conversion (ftuc.asm) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";;\n"
+";; Started:\t21-Dec-2000\n"
+";; Updated:\t22-Dec-2000\n"
+";;\n"
+";; Copyright 2000 G. Adam Stanislav.\n"
+";; All rights reserved.\n"
+";;\n"
+";;;;;;; v.1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+"%include\t'system.inc'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2019
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"\tdb\t'Copyright 2000 G. Adam Stanislav.', 0Ah\n"
+"\tdb\t'All rights reserved.', 0Ah\n"
+"usg\tdb\t'Usage: ftuc filename', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"co\tdb\t\"ftuc: Can't open file.\", 0Ah\n"
+"colen\tequ\t$-co\n"
+"fae\tdb\t'ftuc: File access error.', 0Ah\n"
+"faelen\tequ\t$-fae\n"
+"ftl\tdb\t'ftuc: File too long, use regular tuc instead.', 0Ah\n"
+"ftllen\tequ\t$-ftl\n"
+"mae\tdb\t'ftuc: Memory allocation error.', 0Ah\n"
+"maelen\tequ\t$-mae\n"
+msgstr ""
+"section\t.data\n"
+"\tdb\t'Copyright 2000 G. Adam Stanislav.', 0Ah\n"
+"\tdb\t'All rights reserved.', 0Ah\n"
+"usg\tdb\t'Usage: ftuc filename', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"co\tdb\t\"ftuc: Can't open file.\", 0Ah\n"
+"colen\tequ\t$-co\n"
+"fae\tdb\t'ftuc: File access error.', 0Ah\n"
+"faelen\tequ\t$-fae\n"
+"ftl\tdb\t'ftuc: File too long, use regular tuc instead.', 0Ah\n"
+"ftllen\tequ\t$-ftl\n"
+"mae\tdb\t'ftuc: Memory allocation error.', 0Ah\n"
+"maelen\tequ\t$-mae\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2021
+#, no-wrap
+msgid "section\t.text\n"
+msgstr "section\t.text\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2027
+#, no-wrap
+msgid ""
+"align 4\n"
+"memerr:\n"
+"\tpush\tdword maelen\n"
+"\tpush\tdword mae\n"
+"\tjmp\tshort error\n"
+msgstr ""
+"align 4\n"
+"memerr:\n"
+"\tpush\tdword maelen\n"
+"\tpush\tdword mae\n"
+"\tjmp\tshort error\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2033
+#, no-wrap
+msgid ""
+"align 4\n"
+"toolong:\n"
+"\tpush\tdword ftllen\n"
+"\tpush\tdword ftl\n"
+"\tjmp\tshort error\n"
+msgstr ""
+"align 4\n"
+"toolong:\n"
+"\tpush\tdword ftllen\n"
+"\tpush\tdword ftl\n"
+"\tjmp\tshort error\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2039
+#, no-wrap
+msgid ""
+"align 4\n"
+"facerr:\n"
+"\tpush\tdword faelen\n"
+"\tpush\tdword fae\n"
+"\tjmp\tshort error\n"
+msgstr ""
+"align 4\n"
+"facerr:\n"
+"\tpush\tdword faelen\n"
+"\tpush\tdword fae\n"
+"\tjmp\tshort error\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2045
+#, no-wrap
+msgid ""
+"align 4\n"
+"cantopen:\n"
+"\tpush\tdword colen\n"
+"\tpush\tdword co\n"
+"\tjmp\tshort error\n"
+msgstr ""
+"align 4\n"
+"cantopen:\n"
+"\tpush\tdword colen\n"
+"\tpush\tdword co\n"
+"\tjmp\tshort error\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2050
+#, no-wrap
+msgid ""
+"align 4\n"
+"usage:\n"
+"\tpush\tdword usglen\n"
+"\tpush\tdword usg\n"
+msgstr ""
+"align 4\n"
+"usage:\n"
+"\tpush\tdword usglen\n"
+"\tpush\tdword usg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2054
+#, no-wrap
+msgid ""
+"error:\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+msgstr ""
+"error:\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2057
+#, no-wrap
+msgid ""
+"\tpush\tdword 1\n"
+"\tsys.exit\n"
+msgstr ""
+"\tpush\tdword 1\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2065
+#, no-wrap
+msgid ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tpop\teax\t\t; argc\n"
+"\tpop\teax\t\t; program name\n"
+"\tpop\tecx\t\t; file to convert\n"
+"\tjecxz\tusage\n"
+msgstr ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tpop\teax\t\t; argc\n"
+"\tpop\teax\t\t; program name\n"
+"\tpop\tecx\t\t; file to convert\n"
+"\tjecxz\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2069
+#, no-wrap
+msgid ""
+"\tpop\teax\n"
+"\tor\teax, eax\t; Too many arguments?\n"
+"\tjne\tusage\n"
+msgstr ""
+"\tpop\teax\n"
+"\tor\teax, eax\t; Too many arguments?\n"
+"\tjne\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2075
+#, no-wrap
+msgid ""
+"\t; Open the file\n"
+"\tpush\tdword O_RDWR\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tcantopen\n"
+msgstr ""
+"\t; Open the file\n"
+"\tpush\tdword O_RDWR\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tcantopen\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2077
+#, no-wrap
+msgid "\tmov\tebp, eax\t; Save fd\n"
+msgstr "\tmov\tebp, eax\t; Save fd\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2080
+#, no-wrap
+msgid ""
+"\tsub\tesp, byte stat_size\n"
+"\tmov\tebx, esp\n"
+msgstr ""
+"\tsub\tesp, byte stat_size\n"
+"\tmov\tebx, esp\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2086
+#, no-wrap
+msgid ""
+"\t; Find file size\n"
+"\tpush\tebx\n"
+"\tpush\tebp\t\t; fd\n"
+"\tsys.fstat\n"
+"\tjc\tfacerr\n"
+msgstr ""
+"\t; Find file size\n"
+"\tpush\tebx\n"
+"\tpush\tebp\t\t; fd\n"
+"\tsys.fstat\n"
+"\tjc\tfacerr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2088
+#, no-wrap
+msgid "\tmov\tedx, [ebx + st_size + 4]\n"
+msgstr "\tmov\tedx, [ebx + st_size + 4]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2096
+#, no-wrap
+msgid ""
+"\t; File is too long if EDX != 0 ...\n"
+"\tor\tedx, edx\n"
+"\tjne\tnear toolong\n"
+"\tmov\tecx, [ebx + st_size]\n"
+"\t; ... or if it is above 2 GB\n"
+"\tor\tecx, ecx\n"
+"\tjs\tnear toolong\n"
+msgstr ""
+"\t; File is too long if EDX != 0 ...\n"
+"\tor\tedx, edx\n"
+"\tjne\tnear toolong\n"
+"\tmov\tecx, [ebx + st_size]\n"
+"\t; ... or if it is above 2 GB\n"
+"\tor\tecx, ecx\n"
+"\tjs\tnear toolong\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2099
+#, no-wrap
+msgid ""
+"\t; Do nothing if the file is 0 bytes in size\n"
+"\tjecxz\t.quit\n"
+msgstr ""
+"\t; Do nothing if the file is 0 bytes in size\n"
+"\tjecxz\t.quit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2111
+#, no-wrap
+msgid ""
+"\t; Map the entire file in memory\n"
+"\tpush\tedx\n"
+"\tpush\tedx\t\t; starting at offset 0\n"
+"\tpush\tedx\t\t; pad\n"
+"\tpush\tebp\t\t; fd\n"
+"\tpush\tdword MAP_SHARED\n"
+"\tpush\tdword PROT_READ | PROT_WRITE\n"
+"\tpush\tecx\t\t; entire file size\n"
+"\tpush\tedx\t\t; let system decide on the address\n"
+"\tsys.mmap\n"
+"\tjc\tnear memerr\n"
+msgstr ""
+"\t; Map the entire file in memory\n"
+"\tpush\tedx\n"
+"\tpush\tedx\t\t; starting at offset 0\n"
+"\tpush\tedx\t\t; pad\n"
+"\tpush\tebp\t\t; fd\n"
+"\tpush\tdword MAP_SHARED\n"
+"\tpush\tdword PROT_READ | PROT_WRITE\n"
+"\tpush\tecx\t\t; entire file size\n"
+"\tpush\tedx\t\t; let system decide on the address\n"
+"\tsys.mmap\n"
+"\tjc\tnear memerr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2116
+#, no-wrap
+msgid ""
+"\tmov\tedi, eax\n"
+"\tmov\tesi, eax\n"
+"\tpush\tecx\t\t; for SYS_munmap\n"
+"\tpush\tedi\n"
+msgstr ""
+"\tmov\tedi, eax\n"
+"\tmov\tesi, eax\n"
+"\tpush\tecx\t\t; for SYS_munmap\n"
+"\tpush\tedi\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2121
+#, no-wrap
+msgid ""
+"\t; Use EBX for state machine\n"
+"\tmov\tebx, ordinary\n"
+"\tmov\tah, 0Ah\n"
+"\tcld\n"
+msgstr ""
+"\t; Use EBX for state machine\n"
+"\tmov\tebx, ordinary\n"
+"\tmov\tah, 0Ah\n"
+"\tcld\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2126
+#, no-wrap
+msgid ""
+".loop:\n"
+"\tlodsb\n"
+"\tcall\tebx\n"
+"\tloop\t.loop\n"
+msgstr ""
+".loop:\n"
+"\tlodsb\n"
+"\tcall\tebx\n"
+"\tloop\t.loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2129
+#, no-wrap
+msgid ""
+"\tcmp\tebx, ordinary\n"
+"\tje\t.filesize\n"
+msgstr ""
+"\tcmp\tebx, ordinary\n"
+"\tje\t.filesize\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2134
+#, no-wrap
+msgid ""
+"\t; Output final lf\n"
+"\tmov\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+msgstr ""
+"\t; Output final lf\n"
+"\tmov\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2142
+#, no-wrap
+msgid ""
+".filesize:\n"
+"\t; truncate file to new size\n"
+"\tpush\tdword 0\t\t; high dword\n"
+"\tpush\tedx\t\t; low dword\n"
+"\tpush\teax\t\t; pad\n"
+"\tpush\tebp\n"
+"\tsys.ftruncate\n"
+msgstr ""
+".filesize:\n"
+"\t; truncate file to new size\n"
+"\tpush\tdword 0\t\t; high dword\n"
+"\tpush\tedx\t\t; low dword\n"
+"\tpush\teax\t\t; pad\n"
+"\tpush\tebp\n"
+"\tsys.ftruncate\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2145
+#, no-wrap
+msgid ""
+"\t; close it (ebp still pushed)\n"
+"\tsys.close\n"
+msgstr ""
+"\t; close it (ebp still pushed)\n"
+"\tsys.close\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2148
+#, no-wrap
+msgid ""
+"\tadd\tesp, byte 16\n"
+"\tsys.munmap\n"
+msgstr ""
+"\tadd\tesp, byte 16\n"
+"\tsys.munmap\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2152
+#, no-wrap
+msgid ""
+".quit:\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+msgstr ""
+".quit:\n"
+"\tpush\tdword 0\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2157
+#, no-wrap
+msgid ""
+"align 4\n"
+"ordinary:\n"
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+msgstr ""
+"align 4\n"
+"ordinary:\n"
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2160
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2182
+#, no-wrap
+msgid ""
+"\tcmp\tal, ah\n"
+"\tje\t.lf\n"
+msgstr ""
+"\tcmp\tal, ah\n"
+"\tje\t.lf\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2164
+#, no-wrap
+msgid ""
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+msgstr ""
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2169
+#, no-wrap
+msgid ""
+"align 4\n"
+".cr:\n"
+"\tmov\tebx, cr\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+".cr:\n"
+"\tmov\tebx, cr\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2174
+#, no-wrap
+msgid ""
+"align 4\n"
+".lf:\n"
+"\tmov\tebx, lf\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+".lf:\n"
+"\tmov\tebx, lf\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2179
+#, no-wrap
+msgid ""
+"align 4\n"
+"cr:\n"
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+msgstr ""
+"align 4\n"
+"cr:\n"
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2186
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2214
+#, no-wrap
+msgid ""
+"\txchg\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+msgstr ""
+"\txchg\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2189
+#, no-wrap
+msgid ""
+"\txchg\tal, ah\n"
+"\t; fall through\n"
+msgstr ""
+"\txchg\tal, ah\n"
+"\t; fall through\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2195
+#, no-wrap
+msgid ""
+".lf:\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tmov\tebx, ordinary\n"
+"\tret\n"
+msgstr ""
+".lf:\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tmov\tebx, ordinary\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2202
+#, no-wrap
+msgid ""
+"align 4\n"
+".cr:\n"
+"\tmov\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+".cr:\n"
+"\tmov\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2207
+#, no-wrap
+msgid ""
+"align 4\n"
+"lf:\n"
+"\tcmp\tal, ah\n"
+"\tje\t.lf\n"
+msgstr ""
+"align 4\n"
+"lf:\n"
+"\tcmp\tal, ah\n"
+"\tje\t.lf\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2210
+#, no-wrap
+msgid ""
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+msgstr ""
+"\tcmp\tal, 0Dh\n"
+"\tje\t.cr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2220
+#, no-wrap
+msgid ""
+"\txchg\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tmov\tebx, ordinary\n"
+"\tret\n"
+msgstr ""
+"\txchg\tal, ah\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tmov\tebx, ordinary\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2226
+#, no-wrap
+msgid ""
+"align 4\n"
+".cr:\n"
+"\tmov\tebx, ordinary\n"
+"\tmov\tal, ah\n"
+"\t; fall through\n"
+msgstr ""
+"align 4\n"
+".cr:\n"
+"\tmov\tebx, ordinary\n"
+"\tmov\tal, ah\n"
+"\t; fall through\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2231
+#, no-wrap
+msgid ""
+".lf:\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+msgstr ""
+".lf:\n"
+"\tstosb\n"
+"\tinc\tedx\n"
+"\tret\n"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2238
+msgid ""
+"Do not use this program on files stored on a disk formatted by MS-DOS(R) or "
+"Windows(R). There seems to be a subtle bug in the FreeBSD code when using "
+"`mmap` on these drives mounted under FreeBSD: If the file is over a certain "
+"size, `mmap` will just fill the memory with zeros, and then copy them to the "
+"file overwriting its contents."
+msgstr ""
+"Не используйте эту программу для файлов, хранящихся на диске, "
+"отформатированном в MS-DOS(R) или Windows(R). В коде FreeBSD присутствует "
+"неочевидная ошибка при использовании `mmap` на таких дисках, смонтированных "
+"в FreeBSD: если размер файла превышает определённое значение, `mmap` "
+"заполнит память нулями, а затем запишет их в файл, перезаписав его "
+"содержимое."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2241
+#, no-wrap
+msgid "One-Pointed Mind"
+msgstr "Спокойствие ума"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2244
+msgid ""
+"As a student of Zen, I like the idea of a one-pointed mind: Do one thing at "
+"a time, and do it well."
+msgstr ""
+"Как ученик дзэн, мне нравится идея спокойствия ума (экаггата): делай одно "
+"дело за раз и делай его хорошо."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2247
+msgid ""
+"This, indeed, is very much how UNIX(R) works as well. While a typical "
+"Windows(R) application is attempting to do everything imaginable (and is, "
+"therefore, riddled with bugs), a typical UNIX(R) program does only one "
+"thing, and it does it well."
+msgstr ""
+"Вот именно так, в большинстве случаев, работает и UNIX(R). В то время как "
+"типичное приложение Windows(R) пытается сделать всё, что только можно (и "
+"поэтому кишит ошибками), типичная программа UNIX(R) делает только одну вещь, "
+"но делает её хорошо."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2249
+msgid ""
+"The typical UNIX(R) user then essentially assembles his own applications by "
+"writing a shell script which combines the various existing programs by "
+"piping the output of one program to the input of another."
+msgstr ""
+"Типичный пользователь UNIX(R) по сути собирает свои собственные приложения, "
+"написав shell-скрипт, который объединяет различные существующие программы, "
+"передавая вывод одной программы на вход другой."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2251
+msgid ""
+"When writing your own UNIX(R) software, it is generally a good idea to see "
+"what parts of the problem you need to solve can be handled by existing "
+"programs, and only write your own programs for that part of the problem that "
+"you do not have an existing solution for."
+msgstr ""
+"При написании собственного программного обеспечения для UNIX(R) обычно "
+"рекомендуется определить, какие части решаемой задачи могут быть обработаны "
+"существующими программами, и создавать собственные программы только для той "
+"части задачи, для которой нет готового решения."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2253
+#, no-wrap
+msgid "CSV"
+msgstr "CSV"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2256
+msgid ""
+"I will illustrate this principle with a specific real-life example I was "
+"faced with recently:"
+msgstr ""
+"Я проиллюстрирую этот принцип конкретным примером из реальной жизни, с "
+"которым недавно столкнулся:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2260
+msgid ""
+"I needed to extract the 11th field of each record from a database I "
+"downloaded from a web site. The database was a CSV file, i.e., a list of "
+"_comma-separated values_. That is quite a standard format for sharing data "
+"among people who may be using different database software."
+msgstr ""
+"Мне нужно было извлечь 11-е поле каждой записи из базы данных, которую я "
+"загрузил с веб-сайта. База данных представляла собой CSV-файл, то есть "
+"список _значений, разделённых запятыми_. Это довольно стандартный формат для "
+"обмена данными между людьми, которые могут использовать разное программное "
+"обеспечение для работы с базами данных."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2263
+msgid ""
+"The first line of the file contains the list of various fields separated by "
+"commas. The rest of the file contains the data listed line by line, with "
+"values separated by commas."
+msgstr ""
+"Первая строка файла содержит список различных полей, разделенных запятыми. "
+"Остальная часть файла содержит данные, перечисленные построчно, со "
+"значениями, разделенными запятыми."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2265
+msgid ""
+"I tried awk, using the comma as a separator. But because several lines "
+"contained a quoted comma, awk was extracting the wrong field from those "
+"lines."
+msgstr ""
+"Я попробовал awk, используя запятую в качестве разделителя. Но поскольку "
+"несколько строк содержали запятую в кавычках, awk извлекал неправильное поле "
+"из этих строк."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2268
+msgid ""
+"Therefore, I needed to write my own software to extract the 11th field from "
+"the CSV file. However, going with the UNIX(R) spirit, I only needed to "
+"write a simple filter that would do the following:"
+msgstr ""
+"Следовательно, мне нужно было написать собственное программное обеспечение "
+"для извлечения 11-го поля из CSV-файла. Однако, следуя духу UNIX(R), мне "
+"нужно было лишь создать простой фильтр, выполняющий следующие действия:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2270
+msgid "Remove the first line from the file;"
+msgstr "Удалить первую строку из файла;"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2271
+msgid "Change all unquoted commas to a different character;"
+msgstr "Заменить все не заключённые в кавычки запятые на другой символ;"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2272
+msgid "Remove all quotation marks."
+msgstr "Удалить все кавычки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2274
+msgid ""
+"Strictly speaking, I could use sed to remove the first line from the file, "
+"but doing so in my own program was very easy, so I decided to do it and "
+"reduce the size of the pipeline."
+msgstr ""
+"Строго говоря, я мог бы использовать sed для удаления первой строки из "
+"файла, но сделать это в моей собственной программе было очень просто, "
+"поэтому я решил так поступить и уменьшить размер конвейера."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2278
+msgid ""
+"At any rate, writing a program like this took me about 20 minutes. Writing "
+"a program that extracts the 11th field from the CSV file would take a lot "
+"longer, and I could not reuse it to extract some other field from some other "
+"database."
+msgstr ""
+"В любом случае, написание подобной программы заняло у меня около 20 минут. "
+"Написание программы, которая извлекает 11-е поле из CSV-файла, заняло бы "
+"гораздо больше времени, и я не смог бы повторно использовать её для "
+"извлечения другого поля из другой базы данных."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2280
+msgid ""
+"This time I decided to let it do a little more work than a typical tutorial "
+"program would:"
+msgstr ""
+"На этот раз я решил позволить ей выполнить немного больше работы, чем "
+"обычная учебная программа:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2282
+msgid "It parses its command line for options;"
+msgstr "Она анализирует свою командную строку на наличие опций;"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2283
+msgid "It displays proper usage if it finds wrong arguments;"
+msgstr "Она отображает подсказку, если обнаруживает неверные аргументы;"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2284
+msgid "It produces meaningful error messages."
+msgstr "Она выдает понятные сообщения об ошибках."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2286
+msgid "Here is its usage message:"
+msgstr "Вот какое сообщение она выводит о том, как ее использовать:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2290
+#, no-wrap
+msgid "Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]\n"
+msgstr "Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2293
+msgid "All parameters are optional, and can appear in any order."
+msgstr "Все параметры необязательны и могут располагаться в любом порядке."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2297
+msgid ""
+"The `-t` parameter declares what to replace the commas with. The `tab` is "
+"the default here. For example, `-t;` will replace all unquoted commas with "
+"semicolons."
+msgstr ""
+"Параметр `-t` указывает, на что заменить запятые. По умолчанию используется "
+"`tab`. Например, `-t;` заменит все незакавыченные запятые на точку с запятой."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2301
+msgid ""
+"I did not need the `-c` option, but it may come in handy in the future. It "
+"lets me declare that I want a character other than a comma replaced with "
+"something else. For example, `-c@` will replace all at signs (useful if you "
+"want to split a list of email addresses to their user names and domains)."
+msgstr ""
+"Мне не понадобилась опция `-c`, но в будущем она может пригодиться. Она "
+"позволяет указать, что я хочу заменить символ, отличный от запятой, на что-"
+"то другое. Например, `-c@` заменит все знаки @ (полезно, если нужно "
+"разделить список email-адресов на имена пользователей и домены)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2304
+msgid ""
+"The `-p` option preserves the first line, i.e., it does not delete it. By "
+"default, we delete the first line because in a CSV file it contains the "
+"field names rather than data."
+msgstr ""
+"Опция `-p` сохраняет первую строку, т.е. не удаляет её. По умолчанию мы "
+"удаляем первую строку, потому что в CSV-файле она содержит названия полей, а "
+"не данные."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2307
+msgid ""
+"The `-i` and `-o` options let me specify the input and the output files. "
+"Defaults are [.filename]#stdin# and [.filename]#stdout#, so this is a "
+"regular UNIX(R) filter."
+msgstr ""
+"Опции `-i` и `-o` позволяют указать входной и выходной файлы. По умолчанию "
+"используются [.filename]#stdin# и [.filename]#stdout#, как обычно работает "
+"стандартный фильтр UNIX(R)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2310
+msgid ""
+"I made sure that both `-i filename` and `-ifilename` are accepted. I also "
+"made sure that only one input and one output files may be specified."
+msgstr ""
+"Я убедился, что принимаются как `-i filename`, так и `-ifilename`. Также я "
+"убедился, что может быть указан только один входной и один выходной файл."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2312
+msgid "To get the 11th field of each record, I can now do:"
+msgstr "Чтобы получить 11-е поле каждой записи, теперь я могу сделать:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2316
+#, no-wrap
+msgid "% csv '-t;' data.csv | awk '-F;' '{print $11}'\n"
+msgstr "% csv '-t;' data.csv | awk '-F;' '{print $11}'\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2319
+msgid ""
+"The code stores the options (except for the file descriptors) in `EDX`: The "
+"comma in `DH`, the new separator in `DL`, and the flag for the `-p` option "
+"in the highest bit of `EDX`, so a check for its sign will give us a quick "
+"decision what to do."
+msgstr ""
+"Код сохраняет параметры (за исключением файловых дескрипторов) в `EDX`: "
+"запятая в `DH`, новый разделитель в `DL`, а флаг параметра `-p` в старшем "
+"бите `EDX`, поэтому проверка его знака даст нам быстрое решение о дальнейших "
+"действиях."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2321
+msgid "Here is the code:"
+msgstr "Вот код:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2335
+#, no-wrap
+msgid ""
+";;;;;;; csv.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Convert a comma-separated file to a something-else separated file.\n"
+";\n"
+"; Started:\t31-May-2001\n"
+"; Updated:\t 1-Jun-2001\n"
+";\n"
+"; Copyright (c) 2001 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+msgstr ""
+";;;;;;; csv.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Convert a comma-separated file to a something-else separated file.\n"
+";\n"
+"; Started:\t31-May-2001\n"
+"; Updated:\t 1-Jun-2001\n"
+";\n"
+"; Copyright (c) 2001 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2349
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"usg\tdb\t'Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"iemsg\tdb\t\"csv: Can't open input file\", 0Ah\n"
+"iemlen\tequ\t$-iemsg\n"
+"oemsg\tdb\t\"csv: Can't create output file\", 0Ah\n"
+"oemlen\tequ\t$-oemsg\n"
+msgstr ""
+"section\t.data\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"usg\tdb\t'Usage: csv [-t<delim>] [-c<comma>] [-p] [-o <outfile>] [-i <infile>]', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"iemsg\tdb\t\"csv: Can't open input file\", 0Ah\n"
+"iemlen\tequ\t$-iemsg\n"
+"oemsg\tdb\t\"csv: Can't create output file\", 0Ah\n"
+"oemlen\tequ\t$-oemsg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2363
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"align 4\n"
+"ierr:\n"
+"\tpush\tdword iemlen\n"
+"\tpush\tdword iemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+msgstr ""
+"section\t.text\n"
+"align 4\n"
+"ierr:\n"
+"\tpush\tdword iemlen\n"
+"\tpush\tdword iemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2372
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3421
+#, no-wrap
+msgid ""
+"align 4\n"
+"oerr:\n"
+"\tpush\tdword oemlen\n"
+"\tpush\tdword oemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 2\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+"oerr:\n"
+"\tpush\tdword oemlen\n"
+"\tpush\tdword oemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 2\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2381
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3430
+#, no-wrap
+msgid ""
+"align 4\n"
+"usage:\n"
+"\tpush\tdword usglen\n"
+"\tpush\tdword usg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 3\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+"usage:\n"
+"\tpush\tdword usglen\n"
+"\tpush\tdword usg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 3\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2387
+#, no-wrap
+msgid ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+"\tmov\tedx, (',' << 8) | 9\n"
+msgstr ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+"\tmov\tedx, (',' << 8) | 9\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2392
+#, no-wrap
+msgid ""
+".arg:\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear .init\t\t; no more arguments\n"
+msgstr ""
+".arg:\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear .init\t\t; no more arguments\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2396
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3445
+#, no-wrap
+msgid ""
+"\t; ECX contains the pointer to an argument\n"
+"\tcmp\tbyte [ecx], '-'\n"
+"\tjne\tusage\n"
+msgstr ""
+"\t; ECX contains the pointer to an argument\n"
+"\tcmp\tbyte [ecx], '-'\n"
+"\tjne\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2399
+#, no-wrap
+msgid ""
+"\tinc\tecx\n"
+"\tmov\tax, [ecx]\n"
+msgstr ""
+"\tinc\tecx\n"
+"\tmov\tax, [ecx]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2403
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3453
+#, no-wrap
+msgid ""
+".o:\n"
+"\tcmp\tal, 'o'\n"
+"\tjne\t.i\n"
+msgstr ""
+".o:\n"
+"\tcmp\tal, 'o'\n"
+"\tjne\t.i\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2407
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3457
+#, no-wrap
+msgid ""
+"\t; Make sure we are not asked for the output file twice\n"
+"\tcmp\tdword [fd.out], stdout\n"
+"\tjne\tusage\n"
+msgstr ""
+"\t; Make sure we are not asked for the output file twice\n"
+"\tcmp\tdword [fd.out], stdout\n"
+"\tjne\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2412
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3462
+#, no-wrap
+msgid ""
+"\t; Find the path to output file - it is either at [ECX+1],\n"
+"\t; i.e., -ofile --\n"
+"\t; or in the next argument,\n"
+"\t; i.e., -o file\n"
+msgstr ""
+"\t; Find the path to output file - it is either at [ECX+1],\n"
+"\t; i.e., -ofile --\n"
+"\t; or in the next argument,\n"
+"\t; i.e., -o file\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2418
+#, no-wrap
+msgid ""
+"\tinc\tecx\n"
+"\tor\tah, ah\n"
+"\tjne\t.openoutput\n"
+"\tpop\tecx\n"
+"\tjecxz\tusage\n"
+msgstr ""
+"\tinc\tecx\n"
+"\tor\tah, ah\n"
+"\tjne\t.openoutput\n"
+"\tpop\tecx\n"
+"\tjecxz\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2426
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3475
+#, no-wrap
+msgid ""
+".openoutput:\n"
+"\tpush\tdword 420\t; file mode (644 octal)\n"
+"\tpush\tdword 0200h | 0400h | 01h\n"
+"\t; O_CREAT | O_TRUNC | O_WRONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tnear oerr\n"
+msgstr ""
+".openoutput:\n"
+"\tpush\tdword 420\t; file mode (644 octal)\n"
+"\tpush\tdword 0200h | 0400h | 01h\n"
+"\t; O_CREAT | O_TRUNC | O_WRONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tnear oerr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2430
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3479
+#, no-wrap
+msgid ""
+"\tadd\tesp, byte 12\n"
+"\tmov\t[fd.out], eax\n"
+"\tjmp\tshort .arg\n"
+msgstr ""
+"\tadd\tesp, byte 12\n"
+"\tmov\t[fd.out], eax\n"
+"\tjmp\tshort .arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2434
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3483
+#, no-wrap
+msgid ""
+".i:\n"
+"\tcmp\tal, 'i'\n"
+"\tjne\t.p\n"
+msgstr ""
+".i:\n"
+"\tcmp\tal, 'i'\n"
+"\tjne\t.p\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2438
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3487
+#, no-wrap
+msgid ""
+"\t; Make sure we are not asked twice\n"
+"\tcmp\tdword [fd.in], stdin\n"
+"\tjne\tnear usage\n"
+msgstr ""
+"\t; Make sure we are not asked twice\n"
+"\tcmp\tdword [fd.in], stdin\n"
+"\tjne\tnear usage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2446
+#, no-wrap
+msgid ""
+"\t; Find the path to the input file\n"
+"\tinc\tecx\n"
+"\tor\tah, ah\n"
+"\tjne\t.openinput\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje near usage\n"
+msgstr ""
+"\t; Find the path to the input file\n"
+"\tinc\tecx\n"
+"\tor\tah, ah\n"
+"\tjne\t.openinput\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje near usage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2452
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3500
+#, no-wrap
+msgid ""
+".openinput:\n"
+"\tpush\tdword 0\t\t; O_RDONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tnear ierr\t\t; open failed\n"
+msgstr ""
+".openinput:\n"
+"\tpush\tdword 0\t\t; O_RDONLY\n"
+"\tpush\tecx\n"
+"\tsys.open\n"
+"\tjc\tnear ierr\t\t; open failed\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2456
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3504
+#, no-wrap
+msgid ""
+"\tadd\tesp, byte 8\n"
+"\tmov\t[fd.in], eax\n"
+"\tjmp\t.arg\n"
+msgstr ""
+"\tadd\tesp, byte 8\n"
+"\tmov\t[fd.in], eax\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2464
+#, no-wrap
+msgid ""
+".p:\n"
+"\tcmp\tal, 'p'\n"
+"\tjne\t.t\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tor\tedx, 1 << 31\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".p:\n"
+"\tcmp\tal, 'p'\n"
+"\tjne\t.t\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tor\tedx, 1 << 31\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2472
+#, no-wrap
+msgid ""
+".t:\n"
+"\tcmp\tal, 't'\t\t; redefine output delimiter\n"
+"\tjne\t.c\n"
+"\tor\tah, ah\n"
+"\tje\tnear usage\n"
+"\tmov\tdl, ah\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".t:\n"
+"\tcmp\tal, 't'\t\t; redefine output delimiter\n"
+"\tjne\t.c\n"
+"\tor\tah, ah\n"
+"\tje\tnear usage\n"
+"\tmov\tdl, ah\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2480
+#, no-wrap
+msgid ""
+".c:\n"
+"\tcmp\tal, 'c'\n"
+"\tjne\tnear usage\n"
+"\tor\tah, ah\n"
+"\tje\tnear usage\n"
+"\tmov\tdh, ah\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".c:\n"
+"\tcmp\tal, 'c'\n"
+"\tjne\tnear usage\n"
+"\tor\tah, ah\n"
+"\tje\tnear usage\n"
+"\tmov\tdh, ah\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2487
+#, no-wrap
+msgid ""
+"align 4\n"
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+msgstr ""
+"align 4\n"
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tmov\tedi, obuffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2491
+#, no-wrap
+msgid ""
+"\t; See if we are to preserve the first line\n"
+"\tor\tedx, edx\n"
+"\tjs\t.loop\n"
+msgstr ""
+"\t; See if we are to preserve the first line\n"
+"\tor\tedx, edx\n"
+"\tjs\t.loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2497
+#, no-wrap
+msgid ""
+".firstline:\n"
+"\t; get rid of the first line\n"
+"\tcall\tgetchar\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.firstline\n"
+msgstr ""
+".firstline:\n"
+"\t; get rid of the first line\n"
+"\tcall\tgetchar\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.firstline\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2505
+#, no-wrap
+msgid ""
+"\t; is it a comma (or whatever the user asked for)?\n"
+"\tcmp\tal, dh\n"
+"\tjne\t.quote\n"
+msgstr ""
+"\t; is it a comma (or whatever the user asked for)?\n"
+"\tcmp\tal, dh\n"
+"\tjne\t.quote\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2508
+#, no-wrap
+msgid ""
+"\t; Replace the comma with a tab (or whatever the user wants)\n"
+"\tmov\tal, dl\n"
+msgstr ""
+"\t; Replace the comma with a tab (or whatever the user wants)\n"
+"\tmov\tal, dl\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2516
+#, no-wrap
+msgid ""
+".quote:\n"
+"\tcmp\tal, '\"'\n"
+"\tjne\t.put\n"
+msgstr ""
+".quote:\n"
+"\tcmp\tal, '\"'\n"
+"\tjne\t.put\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2523
+#, no-wrap
+msgid ""
+"\t; Print everything until you get another quote or EOL. If it\n"
+"\t; is a quote, skip it. If it is EOL, print it.\n"
+".qloop:\n"
+"\tcall\tgetchar\n"
+"\tcmp\tal, '\"'\n"
+"\tje\t.loop\n"
+msgstr ""
+"\t; Print everything until you get another quote or EOL. If it\n"
+"\t; is a quote, skip it. If it is EOL, print it.\n"
+".qloop:\n"
+"\tcall\tgetchar\n"
+"\tcmp\tal, '\"'\n"
+"\tje\t.loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2526
+#, no-wrap
+msgid ""
+"\tcmp\tal, 0Ah\n"
+"\tje\t.put\n"
+msgstr ""
+"\tcmp\tal, 0Ah\n"
+"\tje\t.put\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2529
+#, no-wrap
+msgid ""
+"\tcall\tputchar\n"
+"\tjmp\tshort .qloop\n"
+msgstr ""
+"\tcall\tputchar\n"
+"\tjmp\tshort .qloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2545
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3860
+#, no-wrap
+msgid ""
+"read:\n"
+"\tjecxz\t.read\n"
+"\tcall\twrite\n"
+msgstr ""
+"read:\n"
+"\tjecxz\t.read\n"
+"\tcall\twrite\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2558
+#, no-wrap
+msgid ""
+".read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+msgstr ""
+".read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.done\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2595
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3901
+#, no-wrap
+msgid ""
+"align 4\n"
+"write:\n"
+"\tjecxz\t.ret\t; nothing to write\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+".ret:\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+"write:\n"
+"\tjecxz\t.ret\t; nothing to write\n"
+"\tsub\tedi, ecx\t; start of buffer\n"
+"\tpush\tecx\n"
+"\tpush\tedi\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tsub\teax, eax\n"
+"\tsub\tecx, ecx\t; buffer is empty now\n"
+".ret:\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2600
+msgid ""
+"Much of it is taken from [.filename]#hex.asm# above. But there is one "
+"important difference: I no longer call `write` whenever I am outputting a "
+"line feed. Yet, the code can be used interactively."
+msgstr ""
+"Большая часть взята из [.filename]#hex.asm# выше. Однако есть одно важное "
+"отличие: я больше не вызываю `write` каждый раз при выводе перевода строки. "
+"Тем не менее, код можно использовать интерактивно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2604
+msgid ""
+"I have found a better solution for the interactive problem since I first "
+"started writing this chapter. I wanted to make sure each line is printed "
+"out separately only when needed. After all, there is no need to flush out "
+"every line when used non-interactively."
+msgstr ""
+"Я нашел лучшее решение для интерактивной проблемы с тех пор, как начал "
+"писать эту главу. Я хотел убедиться, что каждая строка выводится отдельно "
+"только при необходимости. В конце концов, нет необходимости выводить каждую "
+"строку при неинтерактивном использовании."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2608
+msgid ""
+"The new solution I use now is to call `write` every time I find the input "
+"buffer empty. That way, when running in the interactive mode, the program "
+"reads one line from the user's keyboard, processes it, and sees its input "
+"buffer is empty. It flushes its output and reads the next line."
+msgstr ""
+"Новое решение, которое я использую сейчас, заключается в вызове `write` "
+"каждый раз, когда обнаруживаю, что входной буфер пуст. Таким образом, при "
+"работе в интерактивном режиме программа считывает одну строку с клавиатуры "
+"пользователя, обрабатывает её и видит, что входной буфер пуст. Она "
+"сбрасывает свой вывод и читает следующую строку."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2610
+#, no-wrap
+msgid "The Dark Side of Buffering"
+msgstr "Темная сторона буферизации"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2614
+msgid ""
+"This change prevents a mysterious lockup in a very specific case. I refer "
+"to it as the _dark side of buffering_, mostly because it presents a danger "
+"that is not quite obvious."
+msgstr ""
+"Это изменение предотвращает загадочную блокировку в очень специфическом "
+"случае. Я называю это _тёмной стороной буферизации_, в основном потому, что "
+"это представляет опасность, которая не совсем очевидна."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2618
+msgid ""
+"It is unlikely to happen with a program like the csv above, so let us "
+"consider yet another filter: In this case we expect our input to be raw data "
+"representing color values, such as the _red_, _green_, and _blue_ "
+"intensities of a pixel. Our output will be the negative of our input."
+msgstr ""
+"Маловероятно, что это произойдет с такой программой, как csv выше, поэтому "
+"рассмотрим еще один фильтр: в этом случае мы ожидаем, что наши входные "
+"данные будут представлять собой необработанные данные, описывающие значения "
+"цветов, такие как интенсивности _красного_, _зеленого_ и _синего_ для "
+"пикселя. На выходе мы получим негатив входных данных."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2621
+msgid ""
+"Such a filter would be very simple to write. Most of it would look just "
+"like all the other filters we have written so far, so I am only going to "
+"show you its inner loop:"
+msgstr ""
+"Такой фильтр было бы очень просто написать. Большая его часть выглядела бы "
+"так же, как и все другие фильтры, которые мы уже писали, поэтому я покажу "
+"только его внутренний цикл:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2629
+#, no-wrap
+msgid ""
+".loop:\n"
+"\tcall\tgetchar\n"
+"\tnot\tal\t\t; Create a negative\n"
+"\tcall\tputchar\n"
+"\tjmp\tshort .loop\n"
+msgstr ""
+".loop:\n"
+"\tcall\tgetchar\n"
+"\tnot\tal\t\t; Create a negative\n"
+"\tcall\tputchar\n"
+"\tjmp\tshort .loop\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2632
+msgid ""
+"Because this filter works with raw data, it is unlikely to be used "
+"interactively."
+msgstr ""
+"Поскольку этот фильтр работает с необработанными данными, он вряд ли будет "
+"использоваться интерактивно."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2635
+msgid ""
+"But it could be called by image manipulation software. And, unless it calls "
+"`write` before each call to `read`, chances are it will lock up."
+msgstr ""
+"Но он может вызываться программным обеспечением для обработки изображений. "
+"И, если он не вызывает `write` перед каждым вызовом `read`, высока "
+"вероятность, что он зависнет."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2637
+msgid "Here is what might happen:"
+msgstr "Вот что может произойти:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2640
+msgid "The image editor will load our filter using the C function `popen()`."
+msgstr ""
+"Редактор изображений загрузит наш фильтр, используя функцию `popen()` на "
+"языке C."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2641
+msgid "It will read the first row of pixels from a bitmap or pixmap."
+msgstr ""
+"Он прочитает первый ряд пикселей из битовой карты или пиксельной карты."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2642
+msgid ""
+"It will write the first row of pixels to the _pipe_ leading to the `fd.in` "
+"of our filter."
+msgstr ""
+"Он запишет первую строку пикселей в _канал_, ведущий к `fd.in` нашего "
+"фильтра."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2643
+msgid ""
+"Our filter will read each pixel from its input, turn it to a negative, and "
+"write it to its output buffer."
+msgstr ""
+"Наш фильтр будет читать каждый пиксель из входных данных, преобразовывать "
+"его в негатив и записывать в выходной буфер."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2644
+msgid "Our filter will call `getchar` to fetch the next pixel."
+msgstr "Наш фильтр будет вызывать `getchar` для получения следующего пикселя."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2645
+msgid "`getchar` will find an empty input buffer, so it will call `read`."
+msgstr "`getchar` обнаружит пустой входной буфер, поэтому вызовет `read`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2646
+msgid "`read` will call the `SYS_read` system call."
+msgstr "`read` вызовет системный вызов `SYS_read`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2647
+msgid ""
+"The _kernel_ will suspend our filter until the image editor sends more data "
+"to the pipe."
+msgstr ""
+"_Ядро_ приостановит работу нашего фильтра до тех пор, пока редактор "
+"изображений не отправит больше данных в канал."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2648
+msgid ""
+"The image editor will read from the other pipe, connected to the `fd.out` of "
+"our filter so it can set the first row of the output image _before_ it sends "
+"us the second row of the input."
+msgstr ""
+"Редактор изображений будет читать из другого канала, подключенного к "
+"`fd.out` нашего фильтра, чтобы он мог установить первую строку выходного "
+"изображения _до_ того, как отправит нам вторую строку входного."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2649
+msgid ""
+"The _kernel_ suspends the image editor until it receives some output from "
+"our filter, so it can pass it on to the image editor."
+msgstr ""
+"_Ядро_ приостанавливает работу графического редактора до тех пор, пока не "
+"получит какие-либо данные от нашего фильтра, чтобы передать их редактору."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2653
+msgid ""
+"At this point our filter waits for the image editor to send it more data to "
+"process, while the image editor is waiting for our filter to send it the "
+"result of the processing of the first row. But the result sits in our "
+"output buffer."
+msgstr ""
+"На этом этапе наш фильтр ожидает, что редактор изображений отправит ему "
+"больше данных для обработки, в то время как редактор изображений ожидает, "
+"что наш фильтр отправит ему результат обработки первой строки. Однако "
+"результат находится в нашем выходном буфере."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2656
+msgid ""
+"The filter and the image editor will continue waiting for each other forever "
+"(or, at least, until they are killed). Our software has just entered a "
+"crossref:secure[secure-race-conditions,race condition]."
+msgstr ""
+"Фильтр и редактор изображений будут продолжать ждать друг друга вечно (или, "
+"по крайней мере, пока их не завершат командой kill). Наше программное "
+"обеспечение только что вошло в crossref:secure[secure-race-"
+"conditions,состояние гонки]."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2658
+msgid ""
+"This problem does not exist if our filter flushes its output buffer _before_ "
+"asking the _kernel_ for more input data."
+msgstr ""
+"Эта проблема не возникает, если наш фильтр очищает свой выходной буфер "
+"_перед_ запросом к _ядру_ для получения дополнительных входных данных."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2660
+#, no-wrap
+msgid "Using the FPU"
+msgstr "Использование FPU"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2663
+msgid ""
+"Strangely enough, most of assembly language literature does not even mention "
+"the existence of the FPU, or _floating point unit_, let alone discuss "
+"programming it."
+msgstr ""
+"Как ни странно, большая часть литературы по ассемблеру даже не упоминает о "
+"существовании FPU, или _блока обработки чисел с плавающей запятой_, не "
+"говоря уже о программировании для него."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2665
+msgid ""
+"Yet, never does assembly language shine more than when we create highly "
+"optimized FPU code by doing things that can be done _only_ in assembly "
+"language."
+msgstr ""
+"Тем не менее, язык ассемблера проявляет себя наилучшим образом, когда мы "
+"создаем высокооптимизированный код для FPU, выполняя вещи, которые можно "
+"сделать _только_ на языке ассемблера."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2667
+#, no-wrap
+msgid "Organization of the FPU"
+msgstr "Организация FPU"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2671
+msgid ""
+"The FPU consists of 8 80-bit floating-point registers. These are organized "
+"in a stack fashion-you can `push` a value on TOS (_top of stack_) and you "
+"can `pop` it."
+msgstr ""
+"FPU состоит из 8 80-битных регистров с плавающей запятой. Они организованы в "
+"виде стека — вы можете `push` (поместить) значение на TOS (_вершина стека_) "
+"и `pop` (извлечь) его."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2673
+msgid ""
+"That said, the assembly language op codes are not `push` and `pop` because "
+"those are already taken."
+msgstr ""
+"Как бы то ни было, мнемоники ассемблера — не `push` и `pop`, потому что они "
+"уже заняты."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2676
+msgid ""
+"You can `push` a value on TOS by using `fld`, `fild`, and `fbld`. Several "
+"other op codes let you `push` many common _constants_-such as _pi_-on the "
+"TOS."
+msgstr ""
+"Вы можете `push` (положить) значение на вершину стека (TOS), используя "
+"`fld`, `fild` и `fbld`. Несколько других кодов операций позволяют вам `push` "
+"(положить) многие распространённые _константы_ — например, _pi_ — на вершину "
+"стека (TOS)."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2679
+msgid ""
+"Similarly, you can `pop` a value by using `fst`, `fstp`, `fist`, `fistp`, "
+"and `fbstp`. Actually, only the op codes that end with a _p_ will literally "
+"`pop` the value, the rest will `store` it somewhere else without removing it "
+"from the TOS."
+msgstr ""
+"Аналогично, вы можете `извлечь` значение с помощью `fst`, `fstp`, `fist`, "
+"`fistp` и `fbstp`. На самом деле только коды операций, оканчивающиеся на "
+"_p_, буквально `извлекают` значение, остальные же `сохраняют` его в другом "
+"месте, не удаляя с вершины стека (TOS)."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2681
+msgid ""
+"We can transfer the data between the TOS and the computer memory either as a "
+"32-bit, 64-bit, or 80-bit _real_, a 16-bit, 32-bit, or 64-bit _integer_, or "
+"an 80-bit _packed decimal_."
+msgstr ""
+"Мы можем передавать данные между TOS и памятью компьютера либо как 32-"
+"битное, 64-битное или 80-битное _вещественное_ число, 16-битное, 32-битное "
+"или 64-битное _целое_ число, либо как 80-битное _упакованное десятичное_ "
+"число."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2684
+msgid ""
+"The 80-bit _packed decimal_ is a special case of _binary coded decimal_ "
+"which is very convenient when converting between the ASCII representation of "
+"data and the internal data of the FPU. It allows us to use 18 significant "
+"digits."
+msgstr ""
+"80-битный _упакованный десятичный_ формат является особым случаем _двоично-"
+"десятичного кодирования_, который очень удобен при преобразовании между "
+"ASCII-представлением данных и внутренними данными FPU. Он позволяет "
+"использовать до 18 значащих цифр."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2686
+msgid ""
+"No matter how we represent data in the memory, the FPU always stores it in "
+"the 80-bit _real_ format in its registers."
+msgstr ""
+"Независимо от того, как мы представляем данные в памяти, FPU всегда хранит "
+"их в 80-битном формате _real_ в своих регистрах."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2688
+msgid ""
+"Its internal precision is at least 19 decimal digits, so even if we choose "
+"to display results as ASCII in the full 18-digit precision, we are still "
+"showing correct results."
+msgstr ""
+"Его внутренняя точность составляет не менее 19 десятичных цифр, поэтому даже "
+"если мы решим отображать результаты в формате ASCII с полной 18-значной "
+"точностью, мы всё равно будем показывать корректные результаты."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2690
+msgid ""
+"We can perform mathematical operations on the TOS: We can calculate its "
+"_sine_, we can _scale_ it (i.e., we can multiply or divide it by a power of "
+"2), we can calculate its base-2 _logarithm_, and many other things."
+msgstr ""
+"Мы можем выполнять математические операции над TOS: вычислять его _синус_, "
+"_масштабировать_ (то есть умножать или делить на степень двойки), вычислять "
+"его _логарифм_ по основанию 2 и многое другое."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2692
+msgid ""
+"We can also _multiply_ or _divide_ it by, _add_ it to, or _subtract_ it "
+"from, any of the FPU registers (including itself)."
+msgstr ""
+"Мы также можем _умножить_ или _разделить_ его, _прибавить_ к нему или "
+"_вычесть_ его из любого из регистров FPU (включая его самого)."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2695
+msgid ""
+"The official Intel op code for the TOS is `st`, and for the _registers_ "
+"`st(0)`-`st(7)`. `st` and `st(0)`, then, refer to the same register."
+msgstr ""
+"Официальный код операции Intel для TOS — `st`, а для _регистров_ — `st(0)`-"
+"`st(7)`. Таким образом, `st` и `st(0)` ссылаются на один и тот же регистр."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2698
+msgid ""
+"For whatever reasons, the original author of nasm has decided to use "
+"different op codes, namely `st0`-`st7`. In other words, there are no "
+"parentheses, and the TOS is always `st0`, never just `st`."
+msgstr ""
+"По каким-то причинам оригинальный автор nasm решил использовать другие коды "
+"операций, а именно `st0`-`st7`. Другими словами, скобки отсутствуют, а "
+"вершина стека всегда `st0`, но никогда просто `st`."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2700
+#, no-wrap
+msgid "The Packed Decimal Format"
+msgstr "Формат упакованного десятичного числа"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2704
+msgid ""
+"The _packed decimal_ format uses 10 bytes (80 bits) of memory to represent "
+"18 digits. The number represented there is always an _integer_."
+msgstr ""
+"Формат _упакованного десятичного числа_ использует 10 байт (80 бит) памяти "
+"для представления 18 цифр. Представленное число всегда является _целым_."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2708
+msgid ""
+"You can use it to get decimal places by multiplying the TOS by a power of 10 "
+"first."
+msgstr ""
+"Вы можете использовать это для получения десятичных знаков, предварительно "
+"умножив TOS на степень 10."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2712
+msgid ""
+"The highest bit of the highest byte (byte 9) is the _sign bit_: If it is "
+"set, the number is _negative_, otherwise, it is _positive_. The rest of the "
+"bits of this byte are unused/ignored."
+msgstr ""
+"Старший бит старшего байта (байт 9) является _знаковым битом_: если он "
+"установлен, число _отрицательное_, в противном случае — _положительное_. "
+"Остальные биты этого байта не используются/игнорируются."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2714
+msgid ""
+"The remaining 9 bytes store the 18 digits of the number: 2 digits per byte."
+msgstr "Оставшиеся 9 байт хранят 18 цифр числа: 2 цифры на байт."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2716
+msgid ""
+"The _more significant digit_ is stored in the high _nibble_ (4 bits), the "
+"_less significant digit_ in the low _nibble_."
+msgstr ""
+"_Старший разряд_ хранится в старшем _полубайте_ (4 бита), _младший разряд_ — "
+"в младшем _полубайте_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2718
+msgid ""
+"That said, you might think that `-1234567` would be stored in the memory "
+"like this (using hexadecimal notation):"
+msgstr ""
+"Как бы то ни было, вы можете подумать, что `-1234567` будет храниться в "
+"памяти следующим образом (в шестнадцатеричной записи):"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2722
+#, no-wrap
+msgid "80 00 00 00 00 00 01 23 45 67\n"
+msgstr "80 00 00 00 00 00 01 23 45 67\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2725
+msgid ""
+"Alas it is not! As with everything else of Intel make, even the _packed "
+"decimal_ is _little-endian_."
+msgstr ""
+"Увы, это не так! Как и все остальное, созданное Intel, даже _упакованное "
+"десятичное число_ имеет порядок _от младшего к старшему_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2727
+msgid "That means our `-1234567` is stored like this:"
+msgstr "Это означает, что наш `-1234567` хранится следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2731
+#, no-wrap
+msgid "67 45 23 01 00 00 00 00 00 80\n"
+msgstr "67 45 23 01 00 00 00 00 00 80\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2734
+msgid "Remember that, or you will be pulling your hair out in desperation!"
+msgstr "Помните об этом, иначе вы будете рвать на себе волосы в отчаянии!"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2740
+msgid ""
+"The book to read-if you can find it-is Richard Startz' http://www.amazon.com/"
+"exec/obidos/ASIN/013246604X/whizkidtechnomag[8087/80287/80387 for the IBM PC "
+"& Compatibles]. Though it does seem to take the fact about the little-"
+"endian storage of the _packed decimal_ for granted. I kid you not about the "
+"desperation of trying to figure out what was wrong with the filter I show "
+"below _before_ it occurred to me I should try the little-endian order even "
+"for this type of data."
+msgstr ""
+"Книга, которую стоит прочитать — если сможете её найти — это книга Ричарда "
+"Старца http://www.amazon.com/exec/obidos/ASIN/013246604X/"
+"whizkidtechnomag[8087/80287/80387 для IBM PC и совместимых]. Хотя в ней, "
+"кажется, факт о little-endian хранении _упакованного десятичного числа_ "
+"принимается как данность. Я не шучу насчёт отчаяния, которое испытывал, "
+"пытаясь понять, что не так с фильтром, который я привожу ниже, _прежде_ чем "
+"мне пришло в голову попробовать little-endian порядок даже для этого типа "
+"данных."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2743
+#, no-wrap
+msgid "Excursion to Pinhole Photography"
+msgstr "Экскурсия в фотографию с помощью камеры-обскуры"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2746
+msgid ""
+"To write meaningful software, we must not only understand our programming "
+"tools, but also the field we are creating software for."
+msgstr ""
+"Чтобы создавать полезное программное обеспечение, мы должны понимать не "
+"только наши инструменты программирования, но и область, для которой "
+"разрабатываем ПО."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2748
+msgid ""
+"Our next filter will help us whenever we want to build a _pinhole camera_, "
+"so, we need some background in _pinhole photography_ before we can continue."
+msgstr ""
+"Наш следующий фильтр поможет нам, когда мы захотим создать _камеру-обскуру_, "
+"поэтому нам понадобятся некоторые знания о _фотографии с помощью обскуры_, "
+"прежде чем мы сможем продолжить."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2750
+#, no-wrap
+msgid "The Camera"
+msgstr "Камера"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2753
+msgid ""
+"The easiest way to describe any camera ever built is as some empty space "
+"enclosed in some lightproof material, with a small hole in the enclosure."
+msgstr ""
+"Самый простой способ описать любую когда-либо созданную камеру — это "
+"некоторое пустое пространство, заключённое в светонепроницаемый материал, с "
+"небольшим отверстием в корпусе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2758
+msgid ""
+"The enclosure is usually sturdy (e.g., a box), though sometimes it is "
+"flexible (the bellows). It is quite dark inside the camera. However, the "
+"hole lets light rays in through a single point (though in some cases there "
+"may be several). These light rays form an image, a representation of "
+"whatever is outside the camera, in front of the hole."
+msgstr ""
+"Корпус обычно прочный (например, коробка), хотя иногда он гибкий "
+"(гофрированная часть). Внутри камеры довольно темно. Однако отверстие "
+"пропускает световые лучи через одну точку (хотя в некоторых случаях их может "
+"быть несколько). Эти световые лучи формируют изображение — представление "
+"того, что находится снаружи камеры, перед отверстием."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2760
+msgid ""
+"If some light sensitive material (such as film) is placed inside the camera, "
+"it can capture the image."
+msgstr ""
+"Если внутрь камеры поместить светочувствительный материал (например, "
+"плёнку), он может зафиксировать изображение."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2762
+msgid ""
+"The hole often contains a _lens_, or a lens assembly, often called the "
+"_objective_."
+msgstr ""
+"Отверстие часто содержит _линзу_ или сборку линз, которую часто называют "
+"_объективом_."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2764
+#, no-wrap
+msgid "The Pinhole"
+msgstr "Игольное ушко"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2768
+msgid ""
+"But, strictly speaking, the lens is not necessary: The original cameras did "
+"not use a lens but a _pinhole_. Even today, _pinholes_ are used, both as a "
+"tool to study how cameras work, and to achieve a special kind of image."
+msgstr ""
+"Но, строго говоря, линза не обязательна: первые камеры использовали не "
+"линзу, а _маленькое отверстие_ размером с игольное ушко. Даже сегодня "
+"_маленькие отверстия_ применяются как инструмент для изучения принципов "
+"работы камер и для создания особого вида изображений."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2772
+msgid ""
+"The image produced by the _pinhole_ is all equally sharp. Or _blurred_. "
+"There is an ideal size for a pinhole: If it is either larger or smaller, the "
+"image loses its sharpness."
+msgstr ""
+"Изображение, создаваемое _маленьким отверстием_, одинаково резкое. Или "
+"_размытое_. Существует идеальный размер для маленького отверстия: если оно "
+"больше или меньше, изображение теряет резкость."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2774
+#, no-wrap
+msgid "Focal Length"
+msgstr "Фокусное расстояние"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2777
+msgid ""
+"This ideal pinhole diameter is a function of the square root of _focal "
+"length_, which is the distance of the pinhole from the film."
+msgstr ""
+"Идеальный диаметр отверстия является функцией квадратного корня из "
+"_фокусного расстояния_, которое представляет собой расстояние от отверстия "
+"до плёнки."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2781
+#, no-wrap
+msgid "D = PC * sqrt(FL)\n"
+msgstr "D = PC * sqrt(FL)\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2787
+msgid ""
+"In here, `D` is the ideal diameter of the pinhole, `FL` is the focal length, "
+"and `PC` is a pinhole constant. According to Jay Bender, its value is "
+"`0.04`, while Kenneth Connors has determined it to be `0.037`. Others have "
+"proposed other values. Plus, this value is for the daylight only: Other "
+"types of light will require a different constant, whose value can only be "
+"determined by experimentation."
+msgstr ""
+"Здесь `D` — идеальный диаметр отверстия, `FL` — фокусное расстояние, а `PC` "
+"— константа отверстия. По данным Джейя Бендера, её значение равно `0,04`, "
+"тогда как Кеннет Коннорс определил его как `0,037`. Другие исследователи "
+"предложили иные значения. Кроме того, это значение справедливо только для "
+"дневного света: другие типы освещения потребуют иной константы, значение "
+"которой можно определить только экспериментальным путём."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2789
+#, no-wrap
+msgid "The F-Number"
+msgstr "Число f (диафрагменное число)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2793
+msgid ""
+"The f-number is a very useful measure of how much light reaches the film. A "
+"light meter can determine that, for example, to expose a film of specific "
+"sensitivity with f5.6 mkay require the exposure to last 1/1000 sec."
+msgstr ""
+"Число f — это очень полезный показатель того, сколько света попадает на "
+"плёнку. Экспонометр может определить, что, например, для экспонирования "
+"плёнки определённой чувствительности при f5.6 может потребоваться выдержка "
+"1/1000 сек."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2796
+msgid ""
+"It does not matter whether it is a 35-mm camera, or a 6x9cm camera, etc. As "
+"long as we know the f-number, we can determine the proper exposure."
+msgstr ""
+"Не имеет значения, 35-мм это камера или камера 6x9 см и т.д. Достаточно "
+"знать диафрагменное число, чтобы определить правильную экспозицию."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2798
+msgid "The f-number is easy to calculate:"
+msgstr "Число f легко вычислить:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2802
+#, no-wrap
+msgid "F = FL / D\n"
+msgstr "F = FL / D\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2807
+msgid ""
+"In other words, the f-number equals the focal length divided by the diameter "
+"of the pinhole. It also means a higher f-number either implies a smaller "
+"pinhole or a larger focal distance, or both. That, in turn, implies, the "
+"higher the f-number, the longer the exposure has to be."
+msgstr ""
+"Другими словами, число f равно фокусному расстоянию, деленному на диаметр "
+"отверстия. Это также означает, что большее f-число подразумевает либо "
+"меньшее отверстие, либо большее фокусное расстояние, либо и то, и другое. В "
+"свою очередь, это означает, что чем больше число f, тем дольше должна быть "
+"выдержка."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2810
+msgid ""
+"Furthermore, while pinhole diameter and focal distance are one-dimensional "
+"measurements, both, the film and the pinhole, are two-dimensional. That "
+"means that if you have measured the exposure at f-number `A` as `t`, then "
+"the exposure at f-number `B` is:"
+msgstr ""
+"Кроме того, хотя диаметр отверстия и фокусное расстояние являются "
+"одномерными величинами, и плёнка, и отверстие — двумерны. Это означает, что "
+"если вы измерили экспозицию при диафрагменном числе `A` как `t`, то "
+"экспозиция при диафрагменном числе `B` будет:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2814
+#, no-wrap
+msgid "t * (B / A)²\n"
+msgstr "t * (B / A)²\n"
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2817
+#, no-wrap
+msgid "Normalized F-Number"
+msgstr "Нормализованное число f"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2820
+msgid ""
+"While many modern cameras can change the diameter of their pinhole, and thus "
+"their f-number, quite smoothly and gradually, such was not always the case."
+msgstr ""
+"Хотя многие современные камеры могут изменять диаметр своего отверстия, а "
+"следовательно и свое число f, довольно плавно и постепенно, так было не "
+"всегда."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2822
+msgid ""
+"To allow for different f-numbers, cameras typically contained a metal plate "
+"with several holes of different sizes drilled to them."
+msgstr ""
+"Для обеспечения различных значений диафрагмы в камерах обычно использовалась "
+"металлическая пластина с несколькими отверстиями разного размера."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2825
+msgid ""
+"Their sizes were chosen according to the above formula in such a way that "
+"the resultant f-number was one of standard f-numbers used on all cameras "
+"everywhere. For example, a very old Kodak Duaflex IV camera in my "
+"possession has three such holes for f-numbers 8, 11, and 16."
+msgstr ""
+"Их размеры были выбраны в соответствии с приведённой выше формулой таким "
+"образом, чтобы результирующее f-число было одним из стандартных f-чисел, "
+"используемых на всех фотоаппаратах. Например, у моего очень старого "
+"фотоаппарата Kodak Duaflex IV есть три таких отверстия для чисел f — 8, 11 и "
+"16."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2828
+msgid ""
+"A more recently made camera may offer f-numbers of 2.8, 4, 5.6, 8, 11, 16, "
+"22, and 32 (as well as others). These numbers were not chosen arbitrarily: "
+"They all are powers of the square root of 2, though they may be rounded "
+"somewha."
+msgstr ""
+"Более современные камеры могут предлагать значения диафрагменного числа 2.8, "
+"4, 5.6, 8, 11, 16, 22 и 32 (а также другие). Эти числа выбраны не "
+"произвольно: все они являются степенями квадратного корня из 2, хотя могут "
+"быть немного округлены."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2830
+#, no-wrap
+msgid "The F-Stop"
+msgstr "Ступени числа f"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2834
+msgid ""
+"A typical camera is designed in such a way that setting any of the "
+"normalized f-numbers changes the feel of the dial. It will naturally _stop_ "
+"in that position. Because of that, these positions of the dial are called f-"
+"stops."
+msgstr ""
+"Типичная камера устроена так, что установка любого из нормализованных чисел "
+"f изменяет ощущение от регулятора. Он естественным образом _останавливается_ "
+"в этом положении. Из-за этого такие положения регулятора называются f-"
+"ступенями."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2838
+msgid ""
+"Since the f-numbers at each stop are powers of the square root of 2, moving "
+"the dial by 1 stop will double the amount of light required for proper "
+"exposure. Moving it by 2 stops will quadruple the required exposure. "
+"Moving the dial by 3 stops will require the increase in exposure 8 times, "
+"etc."
+msgstr ""
+"Поскольку значения диафрагмы на каждой ступени являются степенями "
+"квадратного корня из 2, поворот диска на 1 ступень удваивает количество "
+"света, необходимое для правильной экспозиции. Поворот на 2 ступени "
+"увеличивает требуемую экспозицию вчетверо. Поворот диска на 3 ступени "
+"требует увеличения экспозиции в 8 раз и так далее."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2840
+#, no-wrap
+msgid "Designing the Pinhole Software"
+msgstr "Проектирование программного обеспечения камеры-обскуры"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2843
+msgid ""
+"We are now ready to decide what exactly we want our pinhole software to do."
+msgstr ""
+"Мы готовы решить, что именно должно делать наше программное обеспечение для "
+"камер-обскур."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2845
+#, no-wrap
+msgid "Processing Program Input"
+msgstr "Обработка ввода программы"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2849
+msgid ""
+"Since its main purpose is to help us design a working pinhole camera, we "
+"will use the _focal length_ as the input to the program. This is something "
+"we can determine without software: Proper focal length is determined by the "
+"size of the film and by the need to shoot \"regular\" pictures, wide angle "
+"pictures, or telephoto pictures."
+msgstr ""
+"Поскольку основная цель — помочь нам разработать работающую камеру-обскуру, "
+"мы будем использовать _фокусное расстояние_ в качестве входных данных для "
+"программы. Это можно определить без программного обеспечения: правильное "
+"фокусное расстояние зависит от размера плёнки и необходимости съёмки "
+"«обычных» изображений, широкоугольных или телефото."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2851
+msgid ""
+"Most of the programs we have written so far worked with individual "
+"characters, or bytes, as their input: The hex program converted individual "
+"bytes into a hexadecimal number, the csv program either let a character "
+"through, or deleted it, or changed it to a different character, etc."
+msgstr ""
+"Большинство написанных нами до сих пор программ работали с отдельными "
+"символами или байтами в качестве входных данных: программа hex "
+"преобразовывала отдельные байты в шестнадцатеричное число, программа csv "
+"либо пропускала символ, либо удаляла его, либо заменяла на другой символ и "
+"т.д."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2853
+msgid ""
+"One program, ftuc used the state machine to consider at most two input bytes "
+"at a time."
+msgstr ""
+"Одна программа, `ftuc`, использовала конечный автомат для обработки не более "
+"двух входных байтов за раз."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2855
+msgid ""
+"But our pinhole program cannot just work with individual characters, it has "
+"to deal with larger syntactic units."
+msgstr ""
+"Но наша программа для камеры-обскуры не может работать только с отдельными "
+"символами, ей приходится иметь дело с более крупными синтаксическими "
+"единицами."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2857
+msgid ""
+"For example, if we want the program to calculate the pinhole diameter (and "
+"other values we will discuss later) at the focal lengths of `100 mm`, `150 "
+"mm`, and `210 mm`, we may want to enter something like this:"
+msgstr ""
+"Например, если мы хотим, чтобы программа рассчитала диаметр отверстия (и "
+"другие значения, которые мы обсудим позже) для фокусных расстояний `100 мм`, "
+"`150 мм` и `210 мм`, мы можем ввести что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2861
+#, no-wrap
+msgid " 100, 150, 210\n"
+msgstr " 100, 150, 210\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2866
+msgid ""
+"Our program needs to consider more than a single byte of input at a time. "
+"When it sees the first `1`, it must understand it is seeing the first digit "
+"of a decimal number. When it sees the `0` and the other `0`, it must know "
+"it is seeing more digits of the same number."
+msgstr ""
+"Наша программа должна учитывать более одного байта входных данных за раз. "
+"Когда она видит первую `1`, она должна понимать, что это первая цифра "
+"десятичного числа. Когда она видит `0` и другой `0`, она должна знать, что "
+"это следующие цифры того же числа."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2871
+msgid ""
+"When it encounters the first comma, it must know it is no longer receiving "
+"the digits of the first number. It must be able to convert the digits of "
+"the first number into the value of `100`. And the digits of the second "
+"number into the value of `150`. And, of course, the digits of the third "
+"number into the numeric value of `210`."
+msgstr ""
+"Когда он встречает первую запятую, он должен понять, что больше не получает "
+"цифры первого числа. Он должен уметь преобразовать цифры первого числа в "
+"значение `100`. И цифры второго числа в значение `150`. И, конечно же, цифры "
+"третьего числа в числовое значение `210`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2873
+msgid ""
+"We need to decide what delimiters to accept: Do the input numbers have to be "
+"separated by a comma? If so, how do we treat two numbers separated by "
+"something else?"
+msgstr ""
+"Нам нужно определиться с допустимыми разделителями: должны ли входные числа "
+"разделяться запятой? Если да, то как обрабатывать два числа, разделённые чем-"
+"то другим?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2878
+msgid ""
+"Personally, I like to keep it simple. Something either is a number, so I "
+"process it. Or it is not a number, so I discard it. I do not like the "
+"computer complaining about me typing in an extra character when it is "
+"_obvious_ that it is an extra character. Duh!"
+msgstr ""
+"Лично я предпочитаю простоту. Либо что-то является числом — и тогда я его "
+"обрабатываю. Либо не является числом — и тогда я это отбрасываю. Мне не "
+"нравится, когда компьютер жалуется на лишний символ, если _очевидно_, что он "
+"лишний. Да ладно!"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2880
+msgid ""
+"Plus, it allows me to break up the monotony of computing and type in a query "
+"instead of just a number:"
+msgstr ""
+"Плюс, это позволяет мне разбавить монотонность вычислений и ввести запрос "
+"вместо просто числа:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2885
+#, no-wrap
+msgid ""
+"What is the best pinhole diameter for the\n"
+"\t focal length of 150?\n"
+msgstr ""
+"What is the best pinhole diameter for the\n"
+"\t focal length of 150?\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2888
+msgid "There is no reason for the computer to spit out a number of complaints:"
+msgstr "Нет причины, чтобы компьютер выводил множество жалоб:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2895
+#, no-wrap
+msgid ""
+"Syntax error: What\n"
+"Syntax error: is\n"
+"Syntax error: the\n"
+"Syntax error: best\n"
+msgstr ""
+"Syntax error: What\n"
+"Syntax error: is\n"
+"Syntax error: the\n"
+"Syntax error: best\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2898
+msgid "Et cetera, et cetera, et cetera."
+msgstr "И так далее, и так далее, и так далее."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2901
+msgid ""
+"Secondly, I like the `+#+` character to denote the start of a comment which "
+"extends to the end of the line. This does not take too much effort to code, "
+"and lets me treat input files for my software as executable scripts."
+msgstr ""
+"Во-вторых, мне нравится символ `+#+` для обозначения начала комментария, "
+"который продолжается до конца строки. Это не требует больших усилий для "
+"реализации и позволяет мне рассматривать входные файлы для моего "
+"программного обеспечения как исполняемые скрипты."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2903
+msgid ""
+"In our case, we also need to decide what units the input should come in: We "
+"choose _millimeters_ because that is how most photographers measure the "
+"focus length."
+msgstr ""
+"В нашем случае также необходимо определиться с единицами измерения входных "
+"данных: мы выбираем _миллиметры_, так как большинство фотографов измеряют "
+"фокусное расстояние именно в них."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2905
+msgid ""
+"Finally, we need to decide whether to allow the use of the decimal point (in "
+"which case we must also consider the fact that much of the world uses a "
+"decimal _comma_)."
+msgstr ""
+"Наконец, нам нужно решить, разрешать ли использование десятичной точки (в "
+"этом случае мы также должны учитывать тот факт, что во многих странах "
+"используется десятичная _запятая_)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2909
+msgid ""
+"In our case allowing for the decimal point/comma would offer a false sense "
+"of precision: There is little if any noticeable difference between the focus "
+"lengths of `50` and `51`, so allowing the user to input something like "
+"`50.5` is not a good idea. This is my opinion, mind you, but I am the one "
+"writing this program. You can make other choices in yours, of course."
+msgstr ""
+"В нашем случае разрешение десятичной точки/запятой создало бы ложное "
+"ощущение точности: разница между фокусными расстояниями `50` и `51` "
+"практически незаметна, поэтому разрешать пользователю вводить что-то вроде "
+"`50.5` — не лучшая идея. Это моё мнение, конечно, но программу пишу я. В "
+"своей программе вы можете сделать другие выбор, разумеется."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2911
+#, no-wrap
+msgid "Offering Options"
+msgstr "Передача параметров программе"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2916
+msgid ""
+"The most important thing we need to know when building a pinhole camera is "
+"the diameter of the pinhole. Since we want to shoot sharp images, we will "
+"use the above formula to calculate the pinhole diameter from focal length. "
+"As experts are offering several different values for the `PC` constant, we "
+"will need to have the choice."
+msgstr ""
+"Самое важное, что нам нужно знать при создании камеры-обскуры — это диаметр "
+"отверстия. Поскольку мы хотим получать чёткие изображения, мы будем "
+"использовать приведённую выше формулу для расчёта диаметра отверстия от "
+"фокусного расстояния. Поскольку эксперты предлагают несколько различных "
+"значений для константы `PC`, нам нужно будет иметь выбор."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2918
+msgid ""
+"It is traditional in UNIX(R) programming to have two main ways of choosing "
+"program parameters, plus to have a default for the time the user does not "
+"make a choice."
+msgstr ""
+"В традициях программирования в UNIX(R) предусмотрены два основных способа "
+"выбора параметров программы, а также значение по умолчанию на случай, если "
+"пользователь не сделает выбор."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2920
+msgid "Why have two ways of choosing?"
+msgstr "Почему есть два способа выбора?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2922
+msgid ""
+"One is to allow a (relatively) _permanent_ choice that applies automatically "
+"each time the software is run without us having to tell it over and over "
+"what we want it to do."
+msgstr ""
+"Один из способов — это позволить (относительно) _постоянный_ выбор, который "
+"применяется автоматически каждый раз при запуске программы, без "
+"необходимости каждый раз указывать, что мы хотим, чтобы она сделала."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2927
+msgid ""
+"The permanent choices may be stored in a configuration file, typically found "
+"in the user's home directory. The file usually has the same name as the "
+"application but is started with a dot. Often _\"rc\"_ is added to the file "
+"name. So, ours could be [.filename]#~/.pinhole# or "
+"[.filename]#~/.pinholerc#. (The [.filename]#~/# means current user's home "
+"directory.)"
+msgstr ""
+"Постоянные настройки могут быть сохранены в конфигурационном файле, обычно "
+"расположенном в домашнем каталоге пользователя. Файл обычно имеет то же имя, "
+"что и приложение, но начинается с точки. Часто к имени файла добавляется "
+"_\"rc\"_. Таким образом, наш файл может называться [.filename]#~/.pinhole# "
+"или [.filename]#~/.pinholerc#. (Обозначение [.filename]#~/# означает "
+"домашний каталог текущего пользователя.)"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2932
+msgid ""
+"The configuration file is used mostly by programs that have many "
+"configurable parameters. Those that have only one (or a few) often use a "
+"different method: They expect to find the parameter in an _environment "
+"variable_. In our case, we might look at an environment variable named "
+"`PINHOLE`."
+msgstr ""
+"Файл конфигурации в основном используется программами, у которых много "
+"настраиваемых параметров. Те, у которых он один (или несколько), часто "
+"используют другой метод: они ожидают найти параметр в _переменной "
+"окружения_. В нашем случае, мы можем посмотреть на переменную окружения с "
+"именем `PINHOLE`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2935
+msgid ""
+"Usually, a program uses one or the other of the above methods. Otherwise, "
+"if a configuration file said one thing, but an environment variable another, "
+"the program might get confused (or just too complicated)."
+msgstr ""
+"Обычно программа использует один из вышеуказанных методов. В противном "
+"случае, если в конфигурационном файле указано одно, а в переменной окружения "
+"— другое, программа может запутаться (или стать слишком сложной)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2937
+msgid ""
+"Because we only need to choose _one_ such parameter, we will go with the "
+"second method and search the environment for a variable named `PINHOLE`."
+msgstr ""
+"Поскольку нам нужно выбрать только _один_ такой параметр, мы воспользуемся "
+"вторым методом и поищем в окружении переменную с именем `PINHOLE`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2940
+msgid ""
+"The other way allows us to make _ad hoc_ decisions: _\"Though I usually want "
+"you to use 0.039, this time I want 0.03872.\"_ In other words, it allows us "
+"to _override_ the permanent choice."
+msgstr ""
+"Другой способ позволяет нам принимать _ad hoc_ решения: _\"Хотя обычно я "
+"хочу, чтобы ты использовал 0.039, на этот раз мне нужно 0.03872.\"_ Другими "
+"словами, он позволяет нам _переопределить_ постоянный выбор."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2942
+msgid "This type of choice is usually done with command line parameters."
+msgstr ""
+"Такой выбор обычно осуществляется с помощью параметров командной строки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2950
+msgid ""
+"Finally, a program _always_ needs a _default_. The user may not make any "
+"choices. Perhaps he does not know what to choose. Perhaps he is \"just "
+"browsing.\" Preferably, the default will be the value most users would "
+"choose anyway. That way they do not need to choose. Or, rather, they can "
+"choose the default without an additional effort."
+msgstr ""
+"Наконец, программе _всегда_ необходим _значение по умолчанию_. Пользователь "
+"может не делать никакого выбора. Возможно, он не знает, что выбрать. "
+"Возможно, он «просто просматривает». Предпочтительно, чтобы значением по "
+"умолчанию было то, что выбрало бы большинство пользователей. Таким образом, "
+"им не нужно выбирать. Или, точнее, они могут выбрать значение по умолчанию "
+"без дополнительных усилий."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2952
+msgid ""
+"Given this system, the program may find conflicting options, and handle them "
+"this way:"
+msgstr ""
+"Учитывая эту систему, программа может обнаружить конфликтующие параметры и "
+"обработать их следующим образом:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2955
+msgid ""
+"If it finds an _ad hoc_ choice (e.g., command line parameter), it should "
+"accept that choice. It must ignore any permanent choice and any default."
+msgstr ""
+"Если она находит _специальный_ выбор (например, параметр командной строки), "
+"она должна принять этот выбор. Она должна игнорировать любой постоянный "
+"выбор и значения по умолчанию."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2956
+msgid ""
+"_Otherwise_, if it finds a permanent option (e.g., an environment variable), "
+"it should accept it, and ignore the default."
+msgstr ""
+"_В противном случае_, если будет найден постоянный параметр (например, "
+"переменная окружения), он должен быть принят, а значение по умолчанию — "
+"проигнорировано."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2957
+msgid "_Otherwise_, it should use the default."
+msgstr "_В противном случае_, следует использовать значение по умолчанию."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2959
+msgid "We also need to decide what _format_ our `PC` option should have."
+msgstr ""
+"Нам также необходимо решить, в каком _формате_ должна быть наша опция `PC`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2961
+msgid ""
+"At first site, it seems obvious to use the `PINHOLE=0.04` format for the "
+"environment variable, and `-p0.04` for the command line."
+msgstr ""
+"На первый взгляд кажется очевидным использовать формат `PINHOLE=0.04` для "
+"переменной окружения и `-p0.04` для командной строки."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2965
+msgid ""
+"Allowing that is actually a security risk. The `PC` constant is a very small "
+"number. Naturally, we will test our software using various small values of "
+"`PC`. But what will happen if someone runs the program choosing a huge "
+"value?"
+msgstr ""
+"Разрешение этого на самом деле представляет угрозу безопасности. Константа "
+"`PC` — это очень маленькое число. Естественно, мы протестируем наше "
+"программное обеспечение, используя различные небольшие значения `PC`. Но что "
+"произойдёт, если кто-то запустит программу, выбрав огромное значение?"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2967
+msgid ""
+"It may crash the program because we have not designed it to handle huge "
+"numbers."
+msgstr ""
+"Это может привести к сбою программы, так как мы не разрабатывали её для "
+"обработки огромных чисел."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2970
+msgid ""
+"Or, we may spend more time on the program so it can handle huge numbers. We "
+"might do that if we were writing commercial software for computer illiterate "
+"audience."
+msgstr ""
+"Или мы можем потратить больше времени на программу, чтобы она могла "
+"обрабатывать огромные числа. Мы могли бы сделать это, если бы писали "
+"коммерческое программное обеспечение для аудитории, не знакомой с "
+"компьютерами."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2972
+msgid "Or, we might say, _\"Tough! The user should know better.\"\"_"
+msgstr ""
+"Или можно сказать: _\"Пусть терпит! Пользователь сам должен был разобраться."
+"\"_"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2975
+msgid ""
+"Or, we just may make it impossible for the user to enter a huge number. "
+"This is the approach we will take: We will use an _implied 0._ prefix."
+msgstr ""
+"Или мы можем просто сделать невозможным ввод пользователем слишком большого "
+"числа. Это подход, который мы выберем: мы будем использовать "
+"_подразумеваемый префикс 0._."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2978
+msgid ""
+"In other words, if the user wants `0.04`, we will expect him to type `-p04`, "
+"or set `PINHOLE=04` in his environment. So, if he says `-p9999999`, we will "
+"interpret it as ``0.9999999``-still ridiculous but at least safer."
+msgstr ""
+"Другими словами, если пользователь хочет `0.04`, мы ожидаем, что он введёт `-"
+"p04` или установит `PINHOLE=04` в своём окружении. Таким образом, если он "
+"укажет `-p9999999`, мы интерпретируем это как ``0.9999999`` — всё ещё "
+"нелепо, но по крайней мере безопаснее."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2981
+msgid ""
+"Secondly, many users will just want to go with either Bender's constant or "
+"Connors' constant. To make it easier on them, we will interpret `-b` as "
+"identical to `-p04`, and `-c` as identical to `-p037`."
+msgstr ""
+"Во-вторых, многие пользователи просто захотят использовать либо константу "
+"Бендера, либо константу Коннорса. Чтобы облегчить им задачу, мы будем "
+"интерпретировать `-b` как идентичное `-p04`, а `-c` как идентичное `-p037`."
+
+#. type: Title ====
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2983
+#, no-wrap
+msgid "The Output"
+msgstr "Вывод результата"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2986
+msgid ""
+"We need to decide what we want our software to send to the output, and in "
+"what format."
+msgstr ""
+"Нам нужно решить, что наше программное обеспечение должно отправлять на "
+"вывод и в каком формате."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2988
+msgid ""
+"Since our input allows for an unspecified number of focal length entries, it "
+"makes sense to use a traditional database-style output of showing the result "
+"of the calculation for each focal length on a separate line, while "
+"separating all values on one line by a `tab` character."
+msgstr ""
+"Поскольку наши входные данные допускают неограниченное количество значений "
+"фокусного расстояния, имеет смысл использовать традиционный вывод в стиле "
+"базы данных, показывая результат вычислений для каждого фокусного расстояния "
+"на отдельной строке, разделяя все значения в строке символом табуляции."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2991
+msgid ""
+"Optionally, we should also allow the user to specify the use of the CSV "
+"format we have studied earlier. In this case, we will print out a line of "
+"comma-separated names describing each field of every line, then show our "
+"results as before, but substituting a `comma` for the `tab`."
+msgstr ""
+"Опционально, мы также должны разрешить пользователю указать использование "
+"формата CSV, который мы изучили ранее. В этом случае мы выведем строку с "
+"разделёнными запятыми названиями, описывающими каждое поле каждой строки, а "
+"затем отобразим результаты как прежде, но заменив `табуляцию` на `запятую`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:2996
+msgid ""
+"We need a command line option for the CSV format. We cannot use `-c` "
+"because that already means _use Connors' constant_. For some strange "
+"reason, many web sites refer to CSV files as _\"Excel spreadsheet\"_ (though "
+"the CSV format predates Excel). We will, therefore, use the `-e` switch to "
+"inform our software we want the output in the CSV format."
+msgstr ""
+"Нам нужна опция командной строки для формата CSV. Мы не можем использовать `-"
+"c`, потому что это уже означает _использовать константу Коннорса_. По какой-"
+"то странной причине многие веб-сайты называют CSV-файлы _\"электронными "
+"таблицами Excel\"_ (хотя формат CSV появился раньше Excel). Поэтому мы будем "
+"использовать переключатель `-e`, чтобы указать нашему программному "
+"обеспечению, что мы хотим получить вывод в формате CSV."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3000
+msgid ""
+"We will start each line of the output with the focal length. This may sound "
+"repetitious at first, especially in the interactive mode: The user types in "
+"the focal length, and we are repeating it."
+msgstr ""
+"Мы начнем каждую строку вывода с фокусного расстояния. Это может показаться "
+"избыточным сначала, особенно в интерактивном режиме: пользователь вводит "
+"фокусное расстояние, а мы его повторяем."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3004
+msgid ""
+"But the user can type several focal lengths on one line. The input can also "
+"come in from a file or from the output of another program. In that case the "
+"user does not see the input at all."
+msgstr ""
+"Но пользователь может ввести несколько фокусных расстояний в одной строке. "
+"Ввод также может поступать из файла или вывода другой программы. В этом "
+"случае пользователь вообще не видит вводимые данные."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3006
+msgid ""
+"By the same token, the output can go to a file which we will want to examine "
+"later, or it could go to the printer, or become the input of another program."
+msgstr ""
+"Таким же образом, вывод может быть направлен в файл, который мы захотим "
+"изучить позже, или на принтер, или стать входными данными для другой "
+"программы."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3008
+msgid ""
+"So, it makes perfect sense to start each line with the focal length as "
+"entered by the user."
+msgstr ""
+"Итак, имеет полный смысл начинать каждую строку с фокусного расстояния, "
+"введённого пользователем."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3011
+msgid ""
+"No, wait! Not as entered by the user. What if the user types in something "
+"like this:"
+msgstr ""
+"Нет, подождите! Не так, как ввел пользователь. Что, если пользователь "
+"введет что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3015
+#, no-wrap
+msgid " 00000000150\n"
+msgstr " 00000000150\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3018
+msgid "Clearly, we need to strip those leading zeros."
+msgstr "Очевидно, нам нужно удалить ведущие нули."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3020
+msgid ""
+"So, we might consider reading the user input as is, converting it to binary "
+"inside the FPU, and printing it out from there."
+msgstr ""
+"Итак, можно рассмотреть вариант чтения пользовательского ввода как есть, "
+"преобразования его в бинарный вид внутри FPU и последующего вывода оттуда."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3022
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3207
+msgid "But..."
+msgstr "Но..."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3024
+msgid "What if the user types something like this:"
+msgstr "Что делать, если пользователь введёт что-то вроде этого:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3028
+#, no-wrap
+msgid " 17459765723452353453534535353530530534563507309676764423\n"
+msgstr " 17459765723452353453534535353530530534563507309676764423\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3033
+msgid ""
+"Ha! The packed decimal FPU format lets us input 18-digit numbers. But the "
+"user has entered more than 18 digits. How do we handle that?"
+msgstr ""
+"Ха! Упакованный десятичный формат FPU позволяет нам вводить 18-значные "
+"числа. Но пользователь ввёл больше 18 цифр. Как нам обработать это?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3035
+msgid ""
+"Well, we _could_ modify our code to read the first 18 digits, enter it to "
+"the FPU, then read more, multiply what we already have on the TOS by 10 "
+"raised to the number of additional digits, then `add` to it."
+msgstr ""
+"Хорошо, мы _могли бы_ изменить наш код, чтобы он читал первые 18 цифр, "
+"передавал их в FPU, затем читал ещё, умножал уже имеющееся на вершине стека "
+"(TOS) на 10 в степени количества дополнительных цифр, а затем выполнял "
+"`сложение` с этим значением."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3039
+msgid ""
+"Yes, we could do that. But in _this_ program it would be ridiculous (in a "
+"different one it may be just the thing to do): Even the circumference of the "
+"Earth expressed in millimeters only takes 11 digits. Clearly, we cannot "
+"build a camera that large (not yet, anyway)."
+msgstr ""
+"Да, мы могли бы так поступить. Но в _этой_ программе это было бы нелепо (в "
+"другой это могло бы быть как раз тем, что нужно): даже длина окружности "
+"Земли, выраженная в миллиметрах, занимает всего 11 цифр. Очевидно, мы не "
+"можем построить камеру такого размера (по крайней мере, пока)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3041
+msgid ""
+"So, if the user enters such a huge number, he is either bored, or testing "
+"us, or trying to break into the system, or playing games-doing anything but "
+"designing a pinhole camera."
+msgstr ""
+"Итак, если пользователь вводит такое огромное число, он либо скучает, либо "
+"проверяет нас, либо пытается взломать систему, либо играет — делает что "
+"угодно, кроме проектирования камеры-обскуры."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3043
+msgid "What will we do?"
+msgstr "Что мы будем делать?"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3045
+msgid "We will slap him in the face, in a manner of speaking:"
+msgstr "Мы ударим его по лицу, образно говоря:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3049
+#, no-wrap
+msgid "17459765723452353453534535353530530534563507309676764423\t???\t???\t???\t???\t???\n"
+msgstr "17459765723452353453534535353530530534563507309676764423\t???\t???\t???\t???\t???\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3053
+msgid ""
+"To achieve that, we will simply ignore any leading zeros. Once we find a "
+"non-zero digit, we will initialize a counter to `0` and start taking three "
+"steps:"
+msgstr ""
+"Для этого мы просто проигнорируем все ведущие нули. Как только мы найдем "
+"ненулевую цифру, мы инициализируем счетчик значением `0` и начнем выполнять "
+"три шага:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3056
+msgid "Send the digit to the output."
+msgstr "Отправить цифру на выход."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3057
+msgid ""
+"Append the digit to a buffer we will use later to produce the packed decimal "
+"we can send to the FPU."
+msgstr ""
+"Добавить цифру в буфер, который мы позже используем для создания "
+"упакованного десятичного числа, которое можно отправить в FPU."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3058
+msgid "Increase the counter."
+msgstr "Увеличить счетчик."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3060
+msgid ""
+"Now, while we are taking these three steps, we also need to watch out for "
+"one of two conditions:"
+msgstr ""
+"Теперь, пока мы выполняем эти три шага, нам также необходимо следить за "
+"одним из двух условий:"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3062
+msgid ""
+"If the counter grows above 18, we stop appending to the buffer. We continue "
+"reading the digits and sending them to the output."
+msgstr ""
+"Если счётчик превышает 18, мы прекращаем добавление в буфер. Мы продолжаем "
+"читать цифры и отправлять их на вывод."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3063
+msgid ""
+"If, or rather _when_, the next input character is not a digit, we are done "
+"inputting for now."
+msgstr ""
+"Если, или скорее _когда_, следующий вводимый символ не является цифрой, мы "
+"завершаем ввод на данный момент."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3066
+msgid ""
+"Incidentally, we can simply discard the non-digit, unless it is a `+#+`, "
+"which we must return to the input stream. It starts a comment, so we must "
+"see it after we are done producing output and start looking for more input."
+msgstr ""
+"Между прочим, мы можем просто отбросить нецифровой символ, если это не "
+"`+#+`, который необходимо вернуть во входной поток. Он начинает комментарий, "
+"поэтому мы должны увидеть его после завершения вывода и начала поиска "
+"следующего ввода."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3068
+msgid ""
+"That still leaves one possibility uncovered: If all the user enters is a "
+"zero (or several zeros), we will never find a non-zero to display."
+msgstr ""
+"Остается одна непокрытая возможность: если пользователь вводит только ноль "
+"(или несколько нулей), мы никогда не найдем ненулевое значение для "
+"отображения."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3071
+msgid ""
+"We can determine this has happened whenever our counter stays at `0`. In "
+"that case we need to send `0` to the output, and perform another \"slap in "
+"the face\":"
+msgstr ""
+"Мы можем определить, что это произошло, когда наш счетчик остается на `0`. В "
+"этом случае нам нужно отправить `0` на выход и выполнить еще один \"удар по "
+"лицу\":"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3075
+#, no-wrap
+msgid "0\t???\t???\t???\t???\t???\n"
+msgstr "0\t???\t???\t???\t???\t???\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3078
+msgid ""
+"Once we have displayed the focal length and determined it is valid (greater "
+"than `0` but not exceeding 18 digits), we can calculate the pinhole diameter."
+msgstr ""
+"Как только мы определили фокусное расстояние и убедились, что оно корректно "
+"(больше `0`, но не превышает 18 цифр), можно рассчитать диаметр отверстия."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3081
+msgid ""
+"It is not by coincidence that _pinhole_ contains the word _pin_. Indeed, "
+"many a pinhole literally is a _pin hole_, a hole carefully punched with the "
+"tip of a pin."
+msgstr ""
+"Не случайно слово _булавочное ушко_ содержит слово _булавка_. Действительно, "
+"многие малые отверстия буквально являются _дырками от булавки_ — "
+"отверстиями, аккуратно проделанными остриём булавки."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3084
+msgid ""
+"That is because a typical pinhole is very small. Our formula gets the result "
+"in millimeters. We will multiply it by `1000`, so we can output the result "
+"in _microns_."
+msgstr ""
+"Вот потому что типичное отверстие очень маленькое. Наша формула дает "
+"результат в миллиметрах. Мы умножим его на `1000`, чтобы вывести результат в "
+"_микронах_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3086
+msgid "At this point we have yet another trap to face: _Too much precision._"
+msgstr "На этом этапе нас ожидает ещё одна ловушка: _Излишняя точность._"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3090
+msgid ""
+"Yes, the FPU was designed for high precision mathematics. But we are not "
+"dealing with high precision mathematics. We are dealing with physics "
+"(optics, specifically)."
+msgstr ""
+"Да, FPU был разработан для вычислений с высокой точностью. Но мы имеем дело "
+"не с вычислениями высокой точности. Мы имеем дело с физикой (конкретно, с "
+"оптикой)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3094
+msgid ""
+"Suppose we want to convert a truck into a pinhole camera (we would not be "
+"the first ones to do that!). Suppose its box is `12` meters long, so we "
+"have the focal length of `12000`. Well, using Bender's constant, it gives "
+"us square root of `12000` multiplied by `0.04`, which is `4.381780460` "
+"millimeters, or `4381.780460` microns."
+msgstr ""
+"Предположим, мы хотим превратить грузовик в камеру-обскуру (мы будем не "
+"первыми, кто это сделал!). Допустим, его кузов имеет длину `12` метров, "
+"значит, фокусное расстояние равно `12000`. Используя константу Бендера, "
+"получаем квадратный корень из `12000`, умноженный на `0.04`, что составляет "
+"`4.381780460` миллиметра или `4381.780460` микрона."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3099
+msgid ""
+"Put either way, the result is absurdly precise. Our truck is not _exactly_ "
+"`12000` millimeters long. We did not measure its length with such a "
+"precision, so stating we need a pinhole with the diameter of `4.381780460` "
+"millimeters is, well, deceiving. `4.4` millimeters would do just fine."
+msgstr ""
+"Как ни посмотри, результат абсурдно точен. Наш грузовик не имеет _точно_ "
+"`12000` миллиметров в длину. Мы не измеряли его длину с такой точностью, "
+"поэтому утверждение, что нам нужна отверстие диаметром `4,381780460` "
+"миллиметра, мягко говоря, вводит в заблуждение. `4,4` миллиметра будет "
+"вполне достаточно."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3104
+msgid ""
+"I \"only\" used ten digits in the above example. Imagine the absurdity of "
+"going for all 18!"
+msgstr ""
+"Я \"всего лишь\" использовал десять цифр в приведенном выше примере. "
+"Представьте абсурдность попытки использовать все 18!"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3110
+msgid ""
+"We need to limit the number of significant digits of our result. One way of "
+"doing it is by using an integer representing microns. So, our truck would "
+"need a pinhole with the diameter of `4382` microns. Looking at that number, "
+"we still decide that `4400` microns, or `4.4` millimeters is close enough."
+msgstr ""
+"Нам нужно ограничить количество значащих цифр в нашем результате. Один из "
+"способов сделать это — использовать целое число, представляющее микроны. "
+"Таким образом, нашему грузовику потребуется отверстие диаметром `4382` "
+"микрона. Глядя на это число, мы всё же решаем, что `4400` микрон, или `4.4` "
+"миллиметра, достаточно близко."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3113
+msgid ""
+"Additionally, we can decide that no matter how big a result we get, we only "
+"want to display four significant digits (or any other number of them, of "
+"course). Alas, the FPU does not offer rounding to a specific number of "
+"digits (after all, it does not view the numbers as decimal but as binary)."
+msgstr ""
+"Кроме того, мы можем решить, что независимо от размера результата, мы хотим "
+"отображать только четыре значащих цифры (или любое другое их количество, "
+"конечно). Увы, FPU не поддерживает округление до определенного количества "
+"цифр (в конце концов, он воспринимает числа не как десятичные, а как "
+"двоичные)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3115
+msgid ""
+"We, therefore, must devise an algorithm to reduce the number of significant "
+"digits."
+msgstr ""
+"Следовательно, мы должны разработать алгоритм для уменьшения количества "
+"значащих цифр."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3117
+msgid ""
+"Here is mine (I think it is awkward-if you know a better one, _please_, let "
+"me know):"
+msgstr ""
+"Вот мой (я думаю, он неуклюжий — если у вас есть вариант лучше, "
+"_пожалуйста_, дайте мне знать):"
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3120
+msgid "Initialize a counter to `0`."
+msgstr "Инициализировать счетчик значением `0`."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3121
+msgid ""
+"While the number is greater than or equal to `10000`, divide it by `10` and "
+"increase the counter."
+msgstr ""
+"Пока число больше или равно `10000`, делим его на `10` и увеличиваем счётчик."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3122
+msgid "Output the result."
+msgstr "Вывести результат."
+
+#. type: .procedure
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3123
+msgid ""
+"While the counter is greater than `0`, output `0` and decrease the counter."
+msgstr "Пока счетчик больше `0`, выводить `0` и уменьшать счетчик."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3128
+msgid ""
+"The `10000` is only good if you want _four_ significant digits. For any "
+"other number of significant digits, replace `10000` with `10` raised to the "
+"number of significant digits."
+msgstr ""
+"`10000` подходит только если вам нужно _четыре_ значащих цифры. Для любого "
+"другого количества значащих цифр замените `10000` на `10` в степени, равной "
+"количеству значащих цифр."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3131
+msgid ""
+"We will, then, output the pinhole diameter in microns, rounded off to four "
+"significant digits."
+msgstr ""
+"Мы затем выведем диаметр отверстия в микронах, округлённый до четырёх "
+"значащих цифр."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3134
+msgid ""
+"At this point, we know the _focal length_ and the _pinhole diameter_. That "
+"means we have enough information to also calculate the _f-number_."
+msgstr ""
+"На этом этапе нам известны _фокусное расстояние_ и _диаметр отверстия_. Это "
+"означает, что у нас достаточно информации для расчёта _диафрагменного числа_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3138
+msgid ""
+"We will display the f-number, rounded to four significant digits. Chances "
+"are the f-number will tell us very little. To make it more meaningful, we "
+"can find the nearest _normalized f-number_, i.e., the nearest power of the "
+"square root of 2."
+msgstr ""
+"Мы отобразим число f, округлённое до четырёх значащих цифр. Скорее всего, "
+"само число f мало что нам скажет. Чтобы придать ему больше смысла, мы можем "
+"найти ближайшее _нормализованное число f_, то есть ближайшую степень "
+"квадратного корня из 2."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3144
+msgid ""
+"We do that by multiplying the actual f-number by itself, which, of course, "
+"will give us its `square`. We will then calculate its base-2 logarithm, "
+"which is much easier to do than calculating the base-square-root-of-2 "
+"logarithm! We will round the result to the nearest integer. Next, we will "
+"raise 2 to the result. Actually, the FPU gives us a good shortcut to do "
+"that: We can use the `fscale` op code to \"scale\" 1, which is analogous to "
+"``shift``ing an integer left. Finally, we calculate the square root of it "
+"all, and we have the nearest normalized f-number."
+msgstr ""
+"Мы делаем это, умножая фактическое значение диафрагмы на само себя, что, "
+"конечно же, даст нам его `квадрат`. Затем мы вычислим его логарифм по "
+"основанию 2, что намного проще, чем вычисление логарифма по основанию "
+"квадратного корня из 2! Мы округлим результат до ближайшего целого числа. "
+"Далее мы возведём 2 в полученную степень. На самом деле, FPU предоставляет "
+"нам удобный способ сделать это: мы можем использовать код операции `fscale` "
+"для \"масштабирования\" 1, что аналогично ``сдвигу`` целого числа влево. "
+"Наконец, мы вычисляем квадратный корень из всего этого и получаем ближайшее "
+"нормализованное значение диафрагмы."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3147
+msgid ""
+"If all that sounds overwhelming-or too much work, perhaps-it may become much "
+"clearer if you see the code. It takes 9 op codes altogether:"
+msgstr ""
+"Если всё это звучит ошеломляюще — или, возможно, слишком сложно — всё может "
+"стать гораздо понятнее, если увидеть код. Вместе это занимает всего 9 "
+"инструкций процессора:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3159
+#, no-wrap
+msgid ""
+"fmul\tst0, st0\n"
+"\tfld1\n"
+"\tfld\tst1\n"
+"\tfyl2x\n"
+"\tfrndint\n"
+"\tfld1\n"
+"\tfscale\n"
+"\tfsqrt\n"
+"\tfstp\tst1\n"
+msgstr ""
+"fmul\tst0, st0\n"
+"\tfld1\n"
+"\tfld\tst1\n"
+"\tfyl2x\n"
+"\tfrndint\n"
+"\tfld1\n"
+"\tfscale\n"
+"\tfsqrt\n"
+"\tfstp\tst1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3163
+msgid ""
+"The first line, `fmul st0, st0`, squares the contents of the TOS (top of the "
+"stack, same as `st`, called `st0` by nasm). The `fld1` pushes `1` on the "
+"TOS."
+msgstr ""
+"Первая строка, `fmul st0, st0`, возводит в квадрат содержимое TOS (вершина "
+"стека, то же что `st`, называется `st0` в nasm). Команда `fld1` помещает `1` "
+"на вершину стека."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3167
+msgid ""
+"The next line, `fld st1`, pushes the square back to the TOS. At this point "
+"the square is both in `st` and `st(2)` (it will become clear why we leave a "
+"second copy on the stack in a moment). `st(1)` contains `1`."
+msgstr ""
+"Следующая строка, `fld st1`, помещает квадрат обратно в TOS. На этом этапе "
+"квадрат находится и в `st`, и в `st(2)` (скоро станет ясно, зачем мы "
+"оставляем вторую копию в стеке). В `st(1)` содержится `1`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3170
+msgid ""
+"Next, `fyl2x` calculates base-2 logarithm of `st` multiplied by `st(1)`. "
+"That is why we placed `1` on `st(1)` before."
+msgstr ""
+"Далее, `fyl2x` вычисляет логарифм по основанию 2 от `st`, умноженный на "
+"`st(1)`. Именно поэтому мы ранее поместили `1` в `st(1)`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3172
+msgid ""
+"At this point, `st` contains the logarithm we have just calculated, `st(1)` "
+"contains the square of the actual f-number we saved for later."
+msgstr ""
+"На этом этапе `st` содержит логарифм, который мы только что вычислили, а "
+"`st(1)` содержит квадрат фактического значения диафрагменного числа, который "
+"мы сохранили для последующего использования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3176
+msgid ""
+"`frndint` rounds the TOS to the nearest integer. `fld1` pushes a `1`. "
+"`fscale` shifts the `1` we have on the TOS by the value in `st(1)`, "
+"effectively raising 2 to `st(1)`."
+msgstr ""
+"`frndint` округляет TOS до ближайшего целого числа. `fld1` помещает `1` в "
+"стек. `fscale` сдвигает `1`, находящееся на TOS, на значение в `st(1)`, "
+"фактически возводя 2 в степень `st(1)`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3178
+msgid ""
+"Finally, `fsqrt` calculates the square root of the result, i.e., the nearest "
+"normalized f-number."
+msgstr ""
+"Наконец, `fsqrt` вычисляет квадратный корень из результата, т.е. ближайшее "
+"нормализованное число f."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3181
+msgid ""
+"We now have the nearest normalized f-number on the TOS, the base-2 logarithm "
+"rounded to the nearest integer in `st(1)`, and the square of the actual f-"
+"number in `st(2)`. We are saving the value in `st(2)` for later."
+msgstr ""
+"У нас теперь есть ближайшее нормализованное число f на вершине стека (TOS), "
+"округлённый до ближайшего целого двоичный логарифм в `st(1)` и квадрат "
+"фактического число f в `st(2)`. Мы сохраняем значение в `st(2)` для "
+"последующего использования."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3187
+msgid ""
+"But we do not need the contents of `st(1)` anymore. The last line, `fstp "
+"st1`, places the contents of `st` to `st(1)`, and pops. As a result, what "
+"was `st(1)` is now `st`, what was `st(2)` is now `st(1)`, etc. The new `st` "
+"contains the normalized f-number. The new `st(1)` contains the square of "
+"the actual f-number we have stored there for posterity."
+msgstr ""
+"Но нам больше не нужно содержимое `st(1)`. Последняя строка, `fstp st1`, "
+"помещает содержимое `st` в `st(1)` и выполняет извлечение. В результате, то, "
+"что было `st(1)`, теперь становится `st`, то, что было `st(2)`, теперь "
+"становится `st(1)`, и так далее. Новый `st` содержит нормализованное число "
+"f. Новый `st(1)` содержит квадрат фактического число f, который мы сохранили "
+"для потомков."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3190
+msgid ""
+"At this point, we are ready to output the normalized f-number. Because it "
+"is normalized, we will not round it off to four significant digits, but will "
+"send it out in its full precision."
+msgstr ""
+"На этом этапе мы готовы вывести нормализованное число f. Поскольку оно "
+"нормализовано, мы не будем округлять его до четырёх значащих цифр, а "
+"отправим его с полной точностью."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3193
+msgid ""
+"The normalized f-number is useful as long as it is reasonably small and can "
+"be found on our light meter. Otherwise we need a different method of "
+"determining proper exposure."
+msgstr ""
+"Нормализованное диафрагменное число полезно, пока оно достаточно мало и "
+"может быть найдено на нашем экспонометре. В противном случае нам нужен "
+"другой метод определения правильной экспозиции."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3195
+msgid ""
+"Earlier we have figured out the formula of calculating proper exposure at an "
+"arbitrary f-number from that measured at a different f-number."
+msgstr ""
+"Ранее мы вывели формулу для расчёта правильной экспозиции при произвольной "
+"диафрагме на основе измерений, сделанных при другой диафрагме."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3198
+msgid ""
+"Every light meter I have ever seen can determine proper exposure at f5.6. "
+"We will, therefore, calculate an _\"f5.6 multiplier,\"_ i.e., by how much we "
+"need to multiply the exposure measured at f5.6 to determine the proper "
+"exposure for our pinhole camera."
+msgstr ""
+"Каждый экспонометр, который я когда-либо видел, может определить правильную "
+"экспозицию при f5.6. Поэтому мы рассчитаем _\"множитель f5.6\"_, то есть "
+"насколько нужно умножить экспозицию, измеренную при f5.6, чтобы определить "
+"правильную экспозицию для нашей камеры-обскуры."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3200
+msgid ""
+"From the above formula we know this factor can be calculated by dividing our "
+"f-number (the actual one, not the normalized one) by `5.6`, and squaring the "
+"result."
+msgstr ""
+"Из приведённой формулы мы знаем, что этот коэффициент можно вычислить, "
+"разделив наше число f (фактическое, а не нормализованное) на `5.6` и возведя "
+"результат в квадрат."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3202
+msgid ""
+"Mathematically, dividing the square of our f-number by the square of `5.6` "
+"will give us the same result."
+msgstr ""
+"Математически, деление квадрата нашего числа f на квадрат `5.6` даст нам тот "
+"же результат."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3205
+msgid ""
+"Computationally, we do not want to square two numbers when we can only "
+"square one. So, the first solution seems better at first."
+msgstr ""
+"С вычислительной точки зрения, нам не нужно возводить в квадрат два числа, "
+"когда можно возвести только одно. Таким образом, первое решение на первый "
+"взгляд кажется лучше."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3213
+msgid ""
+"`5.6` is a _constant_. We do not have to have our FPU waste precious "
+"cycles. We can just tell it to divide the square of the f-number by "
+"whatever `5.6²` equals to. Or we can divide the f-number by `5.6`, and then "
+"square the result. The two ways now seem equal."
+msgstr ""
+"`5.6` — это _константа_. Нам не нужно заставлять наш FPU тратить драгоценные "
+"циклы. Мы можем просто указать ему разделить квадрат f-числа на то, чему "
+"равно `5.6²`. Или мы можем разделить f-число на `5.6`, а затем возвести "
+"результат в квадрат. Теперь оба способа кажутся равнозначными."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3215
+msgid "But, they are not!"
+msgstr "Но они не такие!"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3219
+msgid ""
+"Having studied the principles of photography above, we remember that the "
+"`5.6` is actually square root of 2 raised to the fifth power. An "
+"_irrational_ number. The square of this number is _exactly_ `32`."
+msgstr ""
+"Изучив принципы фотографии выше, мы помним, что `5.6` — это квадратный "
+"корень из 2, возведённый в пятую степень. Это _иррациональное_ число. "
+"Квадрат этого числа _ровно_ `32`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3225
+msgid ""
+"Not only is `32` an integer, it is a power of 2. We do not need to divide "
+"the square of the f-number by `32`. We only need to use `fscale` to shift "
+"it right by five positions. In the FPU lingo it means we will `fscale` it "
+"with `st(1)` equal to `-5`. That is _much faster_ than a division."
+msgstr ""
+"`32` — это не просто целое число, это степень двойки. Нам не нужно делить "
+"квадрат числа f на `32`. Достаточно использовать `fscale` для сдвига вправо "
+"на пять позиций. В терминологии FPU это означает, что мы применим `fscale` "
+"со значением `st(1)` равным `-5`. Это _гораздо быстрее_, чем деление."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3228
+msgid ""
+"So, now it has become clear why we have saved the square of the f-number on "
+"the top of the FPU stack. The calculation of the f5.6 multiplier is the "
+"easiest calculation of this entire program! We will output it rounded to "
+"four significant digits."
+msgstr ""
+"Итак, теперь стало ясно, зачем мы сохранили квадрат числа f на вершине стека "
+"FPU. Расчёт множителя для f5.6 — это самое простое вычисление во всей "
+"программе! Мы выведем его, округлив до четырёх значащих цифр."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3231
+msgid ""
+"There is one more useful number we can calculate: The number of stops our f-"
+"number is from f5.6. This may help us if our f-number is just outside the "
+"range of our light meter, but we have a shutter which lets us set various "
+"speeds, and this shutter uses stops."
+msgstr ""
+"Есть ещё одно полезное число, которое мы можем вычислить: количество "
+"ступеней, на которые наше значение диафрагмы отличается от f5.6. Это может "
+"помочь, если наше значение диафрагмы находится чуть за пределами диапазона "
+"нашего экспонометра, но у нас есть затвор, который позволяет устанавливать "
+"различные выдержки, и этот затвор использует ступени."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3234
+msgid ""
+"Say, our f-number is 5 stops from f5.6, and the light meter says we should "
+"use 1/1000 sec. Then we can set our shutter speed to 1/1000 first, then "
+"move the dial by 5 stops."
+msgstr ""
+"Предположим, наше число диафрагмы на 5 ступеней отличается от f5.6, а "
+"экспонометр показывает, что нужно использовать выдержку 1/1000 сек. Тогда мы "
+"можем сначала установить выдержку на 1/1000, а затем повернуть диск на 5 "
+"ступеней."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3239
+msgid ""
+"This calculation is quite easy as well. All we have to do is to calculate "
+"the base-2 logarithm of the f5.6 multiplier we had just calculated (though "
+"we need its value from before we rounded it off). We then output the result "
+"rounded to the nearest integer. We do not need to worry about having more "
+"than four significant digits in this one: The result is most likely to have "
+"only one or two digits anyway."
+msgstr ""
+"Этот расчет также довольно прост. Все, что нам нужно сделать, это вычислить "
+"логарифм по основанию 2 от множителя f5.6, который мы только что рассчитали "
+"(хотя нам нужно его значение до округления). Затем мы выводим результат, "
+"округленный до ближайшего целого числа. Нам не нужно беспокоиться о наличии "
+"более четырех значащих цифр в этом случае: скорее всего, результат будет "
+"содержать только одну или две цифры."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3241
+#, no-wrap
+msgid "FPU Optimizations"
+msgstr "Оптимизации FPU"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3244
+msgid ""
+"In assembly language we can optimize the FPU code in ways impossible in high "
+"languages, including C."
+msgstr ""
+"В ассемблерном коде мы можем оптимизировать инструкции FPU способами, "
+"невозможными в языках высокого уровня, включая C."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3248
+msgid ""
+"Whenever a C function needs to calculate a floating-point value, it loads "
+"all necessary variables and constants into FPU registers. It then does "
+"whatever calculation is required to get the correct result. Good C "
+"compilers can optimize that part of the code really well."
+msgstr ""
+"Всякий раз, когда функции на языке C требуется вычислить значение с "
+"плавающей запятой, она загружает все необходимые переменные и константы в "
+"регистры FPU. Затем выполняются все необходимые вычисления для получения "
+"правильного результата. Хорошие компиляторы C могут очень эффективно "
+"оптимизировать эту часть кода."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3252
+msgid ""
+"It \"returns\" the value by leaving the result on the TOS. However, before "
+"it returns, it cleans up. Any variables and constants it used in its "
+"calculation are now gone from the FPU."
+msgstr ""
+"Он \"возвращает\" значение, оставляя результат на вершине стека (TOS). "
+"Однако перед возвратом он выполняет очистку. Все переменные и константы, "
+"использованные в вычислениях, теперь удалены из FPU."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3254
+msgid ""
+"It cannot do what we just did above: We calculated the square of the f-"
+"number and kept it on the stack for later use by another function."
+msgstr ""
+"Он не может сделать то, что мы только что сделали выше: мы вычислили квадрат "
+"числа f и оставили его в стеке для последующего использования другой "
+"функцией."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3257
+msgid ""
+"We _knew_ we would need that value later on. We also knew we had enough "
+"room on the stack (which only has room for 8 numbers) to store it there."
+msgstr ""
+"Мы _знали_, что это значение понадобится позже. Мы также знали, что у нас "
+"достаточно места в стеке (в котором помещается только 8 чисел), чтобы "
+"сохранить его там."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3259
+msgid ""
+"A C compiler has no way of knowing that a value it has on the stack will be "
+"required again in the very near future."
+msgstr ""
+"Компилятор C не может знать, что значение, находящееся в стеке, потребуется "
+"снова в ближайшем будущем."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3262
+msgid ""
+"Of course, the C programmer may know it. But the only recourse he has is to "
+"store the value in a memory variable."
+msgstr ""
+"Конечно, программист на C может это знать. Но единственное средство, которое "
+"у него есть, — это сохранить значение в переменной памяти."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3264
+msgid ""
+"That means, for one, the value will be changed from the 80-bit precision "
+"used internally by the FPU to a C _double_ (64 bits) or even _single_ (32 "
+"bits)."
+msgstr ""
+"Это означает, что значение будет изменено с 80-битной точности, используемой "
+"внутри FPU, на тип _double_ (64 бита) или даже _single_ (32 бита) в C."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3267
+msgid ""
+"That also means that the value must be moved from the TOS into the memory, "
+"and then back again. Alas, of all FPU operations, the ones that access the "
+"computer memory are the slowest."
+msgstr ""
+"Это также означает, что значение должно быть перемещено из TOS в память, а "
+"затем обратно. Увы, среди всех операций с FPU, доступ к памяти компьютера "
+"является самым медленным."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3269
+msgid ""
+"So, whenever programming the FPU in assembly language, look for the ways of "
+"keeping intermediate results on the FPU stack."
+msgstr ""
+"Итак, при программировании FPU на языке ассемблера ищите способы хранения "
+"промежуточных результатов в стеке FPU."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3271
+msgid ""
+"We can take that idea even further! In our program we are using a _constant_ "
+"(the one we named `PC`)."
+msgstr ""
+"Мы можем развить эту идею еще дальше! В нашей программе мы используем "
+"_константу_ (ту, которую назвали `PC`)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3274
+msgid ""
+"It does not matter how many pinhole diameters we are calculating: 1, 10, 20, "
+"1000, we are always using the same constant. Therefore, we can optimize our "
+"program by keeping the constant on the stack all the time."
+msgstr ""
+"Не имеет значения, сколько диаметров отверстий мы рассчитываем: 1, 10, 20, "
+"1000, мы всегда используем одну и ту же константу. Следовательно, мы можем "
+"оптимизировать нашу программу, сохраняя константу в стеке всё время."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3277
+msgid ""
+"Early on in our program, we are calculating the value of the above "
+"constant. We need to divide our input by `10` for every digit in the "
+"constant."
+msgstr ""
+"В начале нашей программы мы вычисляем значение указанной константы. Нам "
+"нужно разделить наш вход на `10` для каждой цифры в константе."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3280
+msgid ""
+"It is much faster to multiply than to divide. So, at the start of our "
+"program, we divide `10` into `1` to obtain `0.1`, which we then keep on the "
+"stack: Instead of dividing the input by `10` for every digit, we multiply it "
+"by `0.1`."
+msgstr ""
+"Гораздо быстрее умножать, чем делить. Поэтому в начале нашей программы мы "
+"делим `1` на `10`, чтобы получить `0.1`, который затем сохраняем в стеке: "
+"вместо того чтобы делить ввод на `10` для каждой цифры, мы умножаем его на "
+"`0.1`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3284
+msgid ""
+"By the way, we do not input `0.1` directly, even though we could. We have a "
+"reason for that: While `0.1` can be expressed with just one decimal place, "
+"we do not know how many _binary_ places it takes. We, therefore, let the "
+"FPU calculate its binary value to its own high precision."
+msgstr ""
+"Кстати, мы не вводим `0.1` напрямую, хотя могли бы. У нас есть причина для "
+"этого: хотя `0.1` можно выразить всего одним десятичным знаком, мы не знаем, "
+"сколько _двоичных_ разрядов для этого потребуется. Поэтому мы позволяем FPU "
+"вычислить его двоичное значение с собственной высокой точностью."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3289
+msgid ""
+"We are using other constants: We multiply the pinhole diameter by `1000` to "
+"convert it from millimeters to microns. We compare numbers to `10000` when "
+"we are rounding them off to four significant digits. So, we keep both, "
+"`1000` and `10000`, on the stack. And, of course, we reuse the `0.1` when "
+"rounding off numbers to four digits."
+msgstr ""
+"Мы используем другие константы: умножаем диаметр отверстия на `1000`, чтобы "
+"перевести его из миллиметров в микроны. Мы сравниваем числа с `10000`, когда "
+"округляем их до четырёх значащих цифр. Таким образом, мы оставляем и `1000`, "
+"и `10000` в стеке. И, конечно же, мы повторно используем `0.1` при "
+"округлении чисел до четырёх цифр."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3295
+msgid ""
+"Last but not least, we keep `-5` on the stack. We need it to scale the "
+"square of the f-number, instead of dividing it by `32`. It is not by "
+"coincidence we load this constant last. That makes it the top of the stack "
+"when only the constants are on it. So, when the square of the f-number is "
+"being scaled, the `-5` is at `st(1)`, precisely where `fscale` expects it to "
+"be."
+msgstr ""
+"И последнее, но не менее важное: мы оставляем `-5` в стеке. Он нам нужен для "
+"масштабирования квадрата числа f вместо деления его на `32`. Не случайно мы "
+"загружаем эту константу последней. Это делает её вершиной стека, когда в нём "
+"находятся только константы. Таким образом, при масштабировании квадрата "
+"число f `-5` находится в `st(1)`, именно там, где `fscale` ожидает его "
+"увидеть."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3298
+msgid ""
+"It is common to create certain constants from scratch instead of loading "
+"them from the memory. That is what we are doing with `-5`:"
+msgstr ""
+"Это обычная ситуация, когда некоторые константы создаются с нуля, вместо "
+"загрузки их из памяти. Именно это мы делаем с `-5`:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3307
+#, no-wrap
+msgid ""
+"\tfld1\t\t\t; TOS = 1\n"
+"\tfadd\tst0, st0\t; TOS = 2\n"
+"\tfadd\tst0, st0\t; TOS = 4\n"
+"\tfld1\t\t\t; TOS = 1\n"
+"\tfaddp\tst1, st0\t; TOS = 5\n"
+"\tfchs\t\t\t; TOS = -5\n"
+msgstr ""
+"\tfld1\t\t\t; TOS = 1\n"
+"\tfadd\tst0, st0\t; TOS = 2\n"
+"\tfadd\tst0, st0\t; TOS = 4\n"
+"\tfld1\t\t\t; TOS = 1\n"
+"\tfaddp\tst1, st0\t; TOS = 5\n"
+"\tfchs\t\t\t; TOS = -5\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3310
+msgid ""
+"We can generalize all these optimizations into one rule: _Keep repeat values "
+"on the stack!_"
+msgstr ""
+"Мы можем обобщить все эти оптимизации в одном правиле: _Держите "
+"повторяющиеся значения в стеке!_"
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3315
+msgid ""
+"_PostScript(R)_ is a stack-oriented programming language. There are many "
+"more books available about PostScript(R) than about the FPU assembly "
+"language: Mastering PostScript(R) will help you master the FPU."
+msgstr ""
+"_PostScript(R)_ — это стековая язык программирования. Существует гораздо "
+"больше книг о PostScript(R), чем о языке ассемблера FPU: освоение "
+"PostScript(R) поможет вам овладеть FPU."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3318
+#, no-wrap
+msgid "pinhole-The Code"
+msgstr "Код pinhole"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3333
+#, no-wrap
+msgid ""
+";;;;;;; pinhole.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Find various parameters of a pinhole camera construction and use\n"
+";\n"
+"; Started:\t 9-Jun-2001\n"
+"; Updated:\t10-Jun-2001\n"
+";\n"
+"; Copyright (c) 2001 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+msgstr ""
+";;;;;;; pinhole.asm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+";\n"
+"; Find various parameters of a pinhole camera construction and use\n"
+";\n"
+"; Started:\t 9-Jun-2001\n"
+"; Updated:\t10-Jun-2001\n"
+";\n"
+"; Copyright (c) 2001 G. Adam Stanislav\n"
+"; All rights reserved.\n"
+";\n"
+";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3368
+#, no-wrap
+msgid ""
+"section\t.data\n"
+"align 4\n"
+"ten\tdd\t10\n"
+"thousand\tdd\t1000\n"
+"tthou\tdd\t10000\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"envar\tdb\t'PINHOLE='\t; Exactly 8 bytes, or 2 dwords long\n"
+"pinhole\tdb\t'04,', \t\t; Bender's constant (0.04)\n"
+"connors\tdb\t'037', 0Ah\t; Connors' constant\n"
+"usg\tdb\t'Usage: pinhole [-b] [-c] [-e] [-p <value>] [-o <outfile>] [-i <infile>]', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"iemsg\tdb\t\"pinhole: Can't open input file\", 0Ah\n"
+"iemlen\tequ\t$-iemsg\n"
+"oemsg\tdb\t\"pinhole: Can't create output file\", 0Ah\n"
+"oemlen\tequ\t$-oemsg\n"
+"pinmsg\tdb\t\"pinhole: The PINHOLE constant must not be 0\", 0Ah\n"
+"pinlen\tequ\t$-pinmsg\n"
+"toobig\tdb\t\"pinhole: The PINHOLE constant may not exceed 18 decimal places\", 0Ah\n"
+"biglen\tequ\t$-toobig\n"
+"huhmsg\tdb\t9, '???'\n"
+"separ\tdb\t9, '???'\n"
+"sep2\tdb\t9, '???'\n"
+"sep3\tdb\t9, '???'\n"
+"sep4\tdb\t9, '???', 0Ah\n"
+"huhlen\tequ\t$-huhmsg\n"
+"header\tdb\t'focal length in millimeters,pinhole diameter in microns,'\n"
+"\tdb\t'F-number,normalized F-number,F-5.6 multiplier,stops '\n"
+"\tdb\t'from F-5.6', 0Ah\n"
+"headlen\tequ\t$-header\n"
+msgstr ""
+"section\t.data\n"
+"align 4\n"
+"ten\tdd\t10\n"
+"thousand\tdd\t1000\n"
+"tthou\tdd\t10000\n"
+"fd.in\tdd\tstdin\n"
+"fd.out\tdd\tstdout\n"
+"envar\tdb\t'PINHOLE='\t; Exactly 8 bytes, or 2 dwords long\n"
+"pinhole\tdb\t'04,', \t\t; Bender's constant (0.04)\n"
+"connors\tdb\t'037', 0Ah\t; Connors' constant\n"
+"usg\tdb\t'Usage: pinhole [-b] [-c] [-e] [-p <value>] [-o <outfile>] [-i <infile>]', 0Ah\n"
+"usglen\tequ\t$-usg\n"
+"iemsg\tdb\t\"pinhole: Can't open input file\", 0Ah\n"
+"iemlen\tequ\t$-iemsg\n"
+"oemsg\tdb\t\"pinhole: Can't create output file\", 0Ah\n"
+"oemlen\tequ\t$-oemsg\n"
+"pinmsg\tdb\t\"pinhole: The PINHOLE constant must not be 0\", 0Ah\n"
+"pinlen\tequ\t$-pinmsg\n"
+"toobig\tdb\t\"pinhole: The PINHOLE constant may not exceed 18 decimal places\", 0Ah\n"
+"biglen\tequ\t$-toobig\n"
+"huhmsg\tdb\t9, '???'\n"
+"separ\tdb\t9, '???'\n"
+"sep2\tdb\t9, '???'\n"
+"sep3\tdb\t9, '???'\n"
+"sep4\tdb\t9, '???', 0Ah\n"
+"huhlen\tequ\t$-huhmsg\n"
+"header\tdb\t'focal length in millimeters,pinhole diameter in microns,'\n"
+"\tdb\t'F-number,normalized F-number,F-5.6 multiplier,stops '\n"
+"\tdb\t'from F-5.6', 0Ah\n"
+"headlen\tequ\t$-header\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3374
+#, no-wrap
+msgid ""
+"section .bss\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+"dbuffer\tresb\t20\t\t; decimal input buffer\n"
+"bbuffer\tresb\t10\t\t; BCD buffer\n"
+msgstr ""
+"section .bss\n"
+"ibuffer\tresb\tBUFSIZE\n"
+"obuffer\tresb\tBUFSIZE\n"
+"dbuffer\tresb\t20\t\t; decimal input buffer\n"
+"bbuffer\tresb\t10\t\t; BCD buffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3385
+#, no-wrap
+msgid ""
+"section\t.text\n"
+"align 4\n"
+"huh:\n"
+"\tcall\twrite\n"
+"\tpush\tdword huhlen\n"
+"\tpush\tdword huhmsg\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tret\n"
+msgstr ""
+"section\t.text\n"
+"align 4\n"
+"huh:\n"
+"\tcall\twrite\n"
+"\tpush\tdword huhlen\n"
+"\tpush\tdword huhmsg\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+"\tadd\tesp, byte 12\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3394
+#, no-wrap
+msgid ""
+"align 4\n"
+"perr:\n"
+"\tpush\tdword pinlen\n"
+"\tpush\tdword pinmsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 4\t\t; return failure\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+"perr:\n"
+"\tpush\tdword pinlen\n"
+"\tpush\tdword pinmsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 4\t\t; return failure\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3403
+#, no-wrap
+msgid ""
+"align 4\n"
+"consttoobig:\n"
+"\tpush\tdword biglen\n"
+"\tpush\tdword toobig\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 5\t\t; return failure\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+"consttoobig:\n"
+"\tpush\tdword biglen\n"
+"\tpush\tdword toobig\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 5\t\t; return failure\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3412
+#, no-wrap
+msgid ""
+"align 4\n"
+"ierr:\n"
+"\tpush\tdword iemlen\n"
+"\tpush\tdword iemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+msgstr ""
+"align 4\n"
+"ierr:\n"
+"\tpush\tdword iemlen\n"
+"\tpush\tdword iemsg\n"
+"\tpush\tdword stderr\n"
+"\tsys.write\n"
+"\tpush\tdword 1\t\t; return failure\n"
+"\tsys.exit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3436
+#, no-wrap
+msgid ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+"\tsub\tesi, esi\n"
+msgstr ""
+"align 4\n"
+"global\t_start\n"
+"_start:\n"
+"\tadd\tesp, byte 8\t; discard argc and argv[0]\n"
+"\tsub\tesi, esi\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3441
+#, no-wrap
+msgid ""
+".arg:\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear .getenv\t\t; no more arguments\n"
+msgstr ""
+".arg:\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear .getenv\t\t; no more arguments\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3449
+#, no-wrap
+msgid ""
+"\tinc\tecx\n"
+"\tmov\tax, [ecx]\n"
+"\tinc\tecx\n"
+msgstr ""
+"\tinc\tecx\n"
+"\tmov\tax, [ecx]\n"
+"\tinc\tecx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3467
+#, no-wrap
+msgid ""
+"\tor\tah, ah\n"
+"\tjne\t.openoutput\n"
+"\tpop\tecx\n"
+"\tjecxz\tusage\n"
+msgstr ""
+"\tor\tah, ah\n"
+"\tjne\t.openoutput\n"
+"\tpop\tecx\n"
+"\tjecxz\tusage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3494
+#, no-wrap
+msgid ""
+"\t; Find the path to the input file\n"
+"\tor\tah, ah\n"
+"\tjne\t.openinput\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje near usage\n"
+msgstr ""
+"\t; Find the path to the input file\n"
+"\tor\tah, ah\n"
+"\tjne\t.openinput\n"
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje near usage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3510
+#, no-wrap
+msgid ""
+".p:\n"
+"\tcmp\tal, 'p'\n"
+"\tjne\t.c\n"
+"\tor\tah, ah\n"
+"\tjne\t.pcheck\n"
+msgstr ""
+".p:\n"
+"\tcmp\tal, 'p'\n"
+"\tjne\t.c\n"
+"\tor\tah, ah\n"
+"\tjne\t.pcheck\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3514
+#, no-wrap
+msgid ""
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear usage\n"
+msgstr ""
+"\tpop\tecx\n"
+"\tor\tecx, ecx\n"
+"\tje\tnear usage\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3516
+#, no-wrap
+msgid "\tmov\tah, [ecx]\n"
+msgstr "\tmov\tah, [ecx]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3524
+#, no-wrap
+msgid ""
+".pcheck:\n"
+"\tcmp\tah, '0'\n"
+"\tjl\tnear usage\n"
+"\tcmp\tah, '9'\n"
+"\tja\tnear usage\n"
+"\tmov\tesi, ecx\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".pcheck:\n"
+"\tcmp\tah, '0'\n"
+"\tjl\tnear usage\n"
+"\tcmp\tah, '9'\n"
+"\tja\tnear usage\n"
+"\tmov\tesi, ecx\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3532
+#, no-wrap
+msgid ""
+".c:\n"
+"\tcmp\tal, 'c'\n"
+"\tjne\t.b\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tesi, connors\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".c:\n"
+"\tcmp\tal, 'c'\n"
+"\tjne\t.b\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tesi, connors\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3540
+#, no-wrap
+msgid ""
+".b:\n"
+"\tcmp\tal, 'b'\n"
+"\tjne\t.e\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tesi, pinhole\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".b:\n"
+"\tcmp\tal, 'b'\n"
+"\tjne\t.e\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tesi, pinhole\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3553
+#, no-wrap
+msgid ""
+".e:\n"
+"\tcmp\tal, 'e'\n"
+"\tjne\tnear usage\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tal, ','\n"
+"\tmov\t[huhmsg], al\n"
+"\tmov\t[separ], al\n"
+"\tmov\t[sep2], al\n"
+"\tmov\t[sep3], al\n"
+"\tmov\t[sep4], al\n"
+"\tjmp\t.arg\n"
+msgstr ""
+".e:\n"
+"\tcmp\tal, 'e'\n"
+"\tjne\tnear usage\n"
+"\tor\tah, ah\n"
+"\tjne\tnear usage\n"
+"\tmov\tal, ','\n"
+"\tmov\t[huhmsg], al\n"
+"\tmov\t[separ], al\n"
+"\tmov\t[sep2], al\n"
+"\tmov\t[sep3], al\n"
+"\tmov\t[sep4], al\n"
+"\tjmp\t.arg\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3560
+#, no-wrap
+msgid ""
+"align 4\n"
+".getenv:\n"
+"\t; If ESI = 0, we did not have a -p argument,\n"
+"\t; and need to check the environment for \"PINHOLE=\"\n"
+"\tor\tesi, esi\n"
+"\tjne\t.init\n"
+msgstr ""
+"align 4\n"
+".getenv:\n"
+"\t; If ESI = 0, we did not have a -p argument,\n"
+"\t; and need to check the environment for \"PINHOLE=\"\n"
+"\tor\tesi, esi\n"
+"\tjne\t.init\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3562
+#, no-wrap
+msgid "\tsub\tecx, ecx\n"
+msgstr "\tsub\tecx, ecx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3567
+#, no-wrap
+msgid ""
+".nextenv:\n"
+"\tpop\tesi\n"
+"\tor\tesi, esi\n"
+"\tje\t.default\t; no PINHOLE envar found\n"
+msgstr ""
+".nextenv:\n"
+"\tpop\tesi\n"
+"\tor\tesi, esi\n"
+"\tje\t.default\t; no PINHOLE envar found\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3573
+#, no-wrap
+msgid ""
+"\t; check if this envar starts with 'PINHOLE='\n"
+"\tmov\tedi, envar\n"
+"\tmov\tcl, 2\t\t; 'PINHOLE=' is 2 dwords long\n"
+"rep\tcmpsd\n"
+"\tjne\t.nextenv\n"
+msgstr ""
+"\t; check if this envar starts with 'PINHOLE='\n"
+"\tmov\tedi, envar\n"
+"\tmov\tcl, 2\t\t; 'PINHOLE=' is 2 dwords long\n"
+"rep\tcmpsd\n"
+"\tjne\t.nextenv\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3581
+#, no-wrap
+msgid ""
+"\t; Check if it is followed by a digit\n"
+"\tmov\tal, [esi]\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.default\n"
+"\tcmp\tal, '9'\n"
+"\tjbe\t.init\n"
+"\t; fall through\n"
+msgstr ""
+"\t; Check if it is followed by a digit\n"
+"\tmov\tal, [esi]\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.default\n"
+"\tcmp\tal, '9'\n"
+"\tjbe\t.init\n"
+"\t; fall through\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3588
+#, no-wrap
+msgid ""
+"align 4\n"
+".default:\n"
+"\t; We got here because we had no -p argument,\n"
+"\t; and did not find the PINHOLE envar.\n"
+"\tmov\tesi, pinhole\n"
+"\t; fall through\n"
+msgstr ""
+"align 4\n"
+".default:\n"
+"\t; We got here because we had no -p argument,\n"
+"\t; and did not find the PINHOLE envar.\n"
+"\tmov\tesi, pinhole\n"
+"\t; fall through\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3597
+#, no-wrap
+msgid ""
+"align 4\n"
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tsub\tedx, edx\n"
+"\tmov\tedi, dbuffer+1\n"
+"\tmov\tbyte [dbuffer], '0'\n"
+msgstr ""
+"align 4\n"
+".init:\n"
+"\tsub\teax, eax\n"
+"\tsub\tebx, ebx\n"
+"\tsub\tecx, ecx\n"
+"\tsub\tedx, edx\n"
+"\tmov\tedi, dbuffer+1\n"
+"\tmov\tbyte [dbuffer], '0'\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3606
+#, no-wrap
+msgid ""
+"\t; Convert the pinhole constant to real\n"
+".constloop:\n"
+"\tlodsb\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.setconst\n"
+"\tcmp\tal, '0'\n"
+"\tje\t.processconst\n"
+"\tjb\t.setconst\n"
+msgstr ""
+"\t; Convert the pinhole constant to real\n"
+".constloop:\n"
+"\tlodsb\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.setconst\n"
+"\tcmp\tal, '0'\n"
+"\tje\t.processconst\n"
+"\tjb\t.setconst\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3608
+#, no-wrap
+msgid "\tinc\tdl\n"
+msgstr "\tinc\tdl\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3615
+#, no-wrap
+msgid ""
+".processconst:\n"
+"\tinc\tcl\n"
+"\tcmp\tcl, 18\n"
+"\tja\tnear consttoobig\n"
+"\tstosb\n"
+"\tjmp\tshort .constloop\n"
+msgstr ""
+".processconst:\n"
+"\tinc\tcl\n"
+"\tcmp\tcl, 18\n"
+"\tja\tnear consttoobig\n"
+"\tstosb\n"
+"\tjmp\tshort .constloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3620
+#, no-wrap
+msgid ""
+"align 4\n"
+".setconst:\n"
+"\tor\tdl, dl\n"
+"\tje\tnear perr\n"
+msgstr ""
+"align 4\n"
+".setconst:\n"
+"\tor\tdl, dl\n"
+"\tje\tnear perr\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3623
+#, no-wrap
+msgid ""
+"\tfinit\n"
+"\tfild\tdword [tthou]\n"
+msgstr ""
+"\tfinit\n"
+"\tfild\tdword [tthou]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3627
+#, no-wrap
+msgid ""
+"\tfld1\n"
+"\tfild\tdword [ten]\n"
+"\tfdivp\tst1, st0\n"
+msgstr ""
+"\tfld1\n"
+"\tfild\tdword [ten]\n"
+"\tfdivp\tst1, st0\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3630
+#, no-wrap
+msgid ""
+"\tfild\tdword [thousand]\n"
+"\tmov\tedi, obuffer\n"
+msgstr ""
+"\tfild\tdword [thousand]\n"
+"\tmov\tedi, obuffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3633
+#, no-wrap
+msgid ""
+"\tmov\tebp, ecx\n"
+"\tcall\tbcdload\n"
+msgstr ""
+"\tmov\tebp, ecx\n"
+"\tcall\tbcdload\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3637
+#, no-wrap
+msgid ""
+".constdiv:\n"
+"\tfmul\tst0, st2\n"
+"\tloop\t.constdiv\n"
+msgstr ""
+".constdiv:\n"
+"\tfmul\tst0, st2\n"
+"\tloop\t.constdiv\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3644
+#, no-wrap
+msgid ""
+"\tfld1\n"
+"\tfadd\tst0, st0\n"
+"\tfadd\tst0, st0\n"
+"\tfld1\n"
+"\tfaddp\tst1, st0\n"
+"\tfchs\n"
+msgstr ""
+"\tfld1\n"
+"\tfadd\tst0, st0\n"
+"\tfadd\tst0, st0\n"
+"\tfld1\n"
+"\tfaddp\tst1, st0\n"
+"\tfchs\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3649
+#, no-wrap
+msgid ""
+"\t; If we are creating a CSV file,\n"
+"\t; print header\n"
+"\tcmp\tbyte [separ], ','\n"
+"\tjne\t.bigloop\n"
+msgstr ""
+"\t; If we are creating a CSV file,\n"
+"\t; print header\n"
+"\tcmp\tbyte [separ], ','\n"
+"\tjne\t.bigloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3654
+#, no-wrap
+msgid ""
+"\tpush\tdword headlen\n"
+"\tpush\tdword header\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+msgstr ""
+"\tpush\tdword headlen\n"
+"\tpush\tdword header\n"
+"\tpush\tdword [fd.out]\n"
+"\tsys.write\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3658
+#, no-wrap
+msgid ""
+".bigloop:\n"
+"\tcall\tgetchar\n"
+"\tjc\tnear done\n"
+msgstr ""
+".bigloop:\n"
+"\tcall\tgetchar\n"
+"\tjc\tnear done\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3664
+#, no-wrap
+msgid ""
+"\t; Skip to the end of the line if you got '#'\n"
+"\tcmp\tal, '#'\n"
+"\tjne\t.num\n"
+"\tcall\tskiptoeol\n"
+"\tjmp\tshort .bigloop\n"
+msgstr ""
+"\t; Skip to the end of the line if you got '#'\n"
+"\tcmp\tal, '#'\n"
+"\tjne\t.num\n"
+"\tcall\tskiptoeol\n"
+"\tjmp\tshort .bigloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3671
+#, no-wrap
+msgid ""
+".num:\n"
+"\t; See if you got a number\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.bigloop\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.bigloop\n"
+msgstr ""
+".num:\n"
+"\t; See if you got a number\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.bigloop\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.bigloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3675
+#, no-wrap
+msgid ""
+"\t; Yes, we have a number\n"
+"\tsub\tebp, ebp\n"
+"\tsub\tedx, edx\n"
+msgstr ""
+"\t; Yes, we have a number\n"
+"\tsub\tebp, ebp\n"
+"\tsub\tedx, edx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3680
+#, no-wrap
+msgid ""
+".number:\n"
+"\tcmp\tal, '0'\n"
+"\tje\t.number0\n"
+"\tmov\tdl, 1\n"
+msgstr ""
+".number:\n"
+"\tcmp\tal, '0'\n"
+"\tje\t.number0\n"
+"\tmov\tdl, 1\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3691
+#, no-wrap
+msgid ""
+".number0:\n"
+"\tor\tdl, dl\t\t; Skip leading 0's\n"
+"\tje\t.nextnumber\n"
+"\tpush\teax\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tinc\tebp\n"
+"\tcmp\tebp, 19\n"
+"\tjae\t.nextnumber\n"
+"\tmov\t[dbuffer+ebp], al\n"
+msgstr ""
+".number0:\n"
+"\tor\tdl, dl\t\t; Skip leading 0's\n"
+"\tje\t.nextnumber\n"
+"\tpush\teax\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tinc\tebp\n"
+"\tcmp\tebp, 19\n"
+"\tjae\t.nextnumber\n"
+"\tmov\t[dbuffer+ebp], al\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3702
+#, no-wrap
+msgid ""
+".nextnumber:\n"
+"\tcall\tgetchar\n"
+"\tjc\t.work\n"
+"\tcmp\tal, '#'\n"
+"\tje\t.ungetc\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.work\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.work\n"
+"\tjmp\tshort .number\n"
+msgstr ""
+".nextnumber:\n"
+"\tcall\tgetchar\n"
+"\tjc\t.work\n"
+"\tcmp\tal, '#'\n"
+"\tje\t.ungetc\n"
+"\tcmp\tal, '0'\n"
+"\tjl\t.work\n"
+"\tcmp\tal, '9'\n"
+"\tja\t.work\n"
+"\tjmp\tshort .number\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3706
+#, no-wrap
+msgid ""
+".ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+msgstr ""
+".ungetc:\n"
+"\tdec\tesi\n"
+"\tinc\tebx\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3711
+#, no-wrap
+msgid ""
+".work:\n"
+"\t; Now, do all the work\n"
+"\tor\tdl, dl\n"
+"\tje\tnear .work0\n"
+msgstr ""
+".work:\n"
+"\t; Now, do all the work\n"
+"\tor\tdl, dl\n"
+"\tje\tnear .work0\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3714
+#, no-wrap
+msgid ""
+"\tcmp\tebp, 19\n"
+"\tjae\tnear .toobig\n"
+msgstr ""
+"\tcmp\tebp, 19\n"
+"\tjae\tnear .toobig\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3716
+#, no-wrap
+msgid "\tcall\tbcdload\n"
+msgstr "\tcall\tbcdload\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3718
+#, no-wrap
+msgid "\t; Calculate pinhole diameter\n"
+msgstr "\t; Calculate pinhole diameter\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3725
+#, no-wrap
+msgid ""
+"\tfld\tst0\t; save it\n"
+"\tfsqrt\n"
+"\tfmul\tst0, st3\n"
+"\tfld\tst0\n"
+"\tfmul\tst5\n"
+"\tsub\tebp, ebp\n"
+msgstr ""
+"\tfld\tst0\t; save it\n"
+"\tfsqrt\n"
+"\tfmul\tst0, st3\n"
+"\tfld\tst0\n"
+"\tfmul\tst5\n"
+"\tsub\tebp, ebp\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3735
+#, no-wrap
+msgid ""
+"\t; Round off to 4 significant digits\n"
+".diameter:\n"
+"\tfcom\tst0, st7\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+"\tjb\t.printdiameter\n"
+"\tfmul\tst0, st6\n"
+"\tinc\tebp\n"
+"\tjmp\tshort .diameter\n"
+msgstr ""
+"\t; Round off to 4 significant digits\n"
+".diameter:\n"
+"\tfcom\tst0, st7\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+"\tjb\t.printdiameter\n"
+"\tfmul\tst0, st6\n"
+"\tinc\tebp\n"
+"\tjmp\tshort .diameter\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3738
+#, no-wrap
+msgid ""
+".printdiameter:\n"
+"\tcall\tprintnumber\t; pinhole diameter\n"
+msgstr ""
+".printdiameter:\n"
+"\tcall\tprintnumber\t; pinhole diameter\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3740
+#, no-wrap
+msgid "\t; Calculate F-number\n"
+msgstr "\t; Calculate F-number\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3743
+#, no-wrap
+msgid ""
+"\tfdivp\tst1, st0\n"
+"\tfld\tst0\n"
+msgstr ""
+"\tfdivp\tst1, st0\n"
+"\tfld\tst0\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3745
+#, no-wrap
+msgid "\tsub\tebp, ebp\n"
+msgstr "\tsub\tebp, ebp\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3754
+#, no-wrap
+msgid ""
+".fnumber:\n"
+"\tfcom\tst0, st6\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+"\tjb\t.printfnumber\n"
+"\tfmul\tst0, st5\n"
+"\tinc\tebp\n"
+"\tjmp\tshort .fnumber\n"
+msgstr ""
+".fnumber:\n"
+"\tfcom\tst0, st6\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+"\tjb\t.printfnumber\n"
+"\tfmul\tst0, st5\n"
+"\tinc\tebp\n"
+"\tjmp\tshort .fnumber\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3757
+#, no-wrap
+msgid ""
+".printfnumber:\n"
+"\tcall\tprintnumber\t; F number\n"
+msgstr ""
+".printfnumber:\n"
+"\tcall\tprintnumber\t; F number\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3768
+#, no-wrap
+msgid ""
+"\t; Calculate normalized F-number\n"
+"\tfmul\tst0, st0\n"
+"\tfld1\n"
+"\tfld\tst1\n"
+"\tfyl2x\n"
+"\tfrndint\n"
+"\tfld1\n"
+"\tfscale\n"
+"\tfsqrt\n"
+"\tfstp\tst1\n"
+msgstr ""
+"\t; Calculate normalized F-number\n"
+"\tfmul\tst0, st0\n"
+"\tfld1\n"
+"\tfld\tst1\n"
+"\tfyl2x\n"
+"\tfrndint\n"
+"\tfld1\n"
+"\tfscale\n"
+"\tfsqrt\n"
+"\tfstp\tst1\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3771
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3799
+#, no-wrap
+msgid ""
+"\tsub\tebp, ebp\n"
+"\tcall\tprintnumber\n"
+msgstr ""
+"\tsub\tebp, ebp\n"
+"\tcall\tprintnumber\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3773
+#, no-wrap
+msgid "\t; Calculate time multiplier from F-5.6\n"
+msgstr "\t; Calculate time multiplier from F-5.6\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3776
+#, no-wrap
+msgid ""
+"\tfscale\n"
+"\tfld\tst0\n"
+msgstr ""
+"\tfscale\n"
+"\tfld\tst0\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3782
+#, no-wrap
+msgid ""
+"\t; Round off to 4 significant digits\n"
+".fmul:\n"
+"\tfcom\tst0, st6\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+msgstr ""
+"\t; Round off to 4 significant digits\n"
+".fmul:\n"
+"\tfcom\tst0, st6\n"
+"\tfstsw\tax\n"
+"\tsahf\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3787
+#, no-wrap
+msgid ""
+"\tjb\t.printfmul\n"
+"\tinc\tebp\n"
+"\tfmul\tst0, st5\n"
+"\tjmp\tshort .fmul\n"
+msgstr ""
+"\tjb\t.printfmul\n"
+"\tinc\tebp\n"
+"\tfmul\tst0, st5\n"
+"\tjmp\tshort .fmul\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3790
+#, no-wrap
+msgid ""
+".printfmul:\n"
+"\tcall\tprintnumber\t; F multiplier\n"
+msgstr ""
+".printfmul:\n"
+"\tcall\tprintnumber\t; F multiplier\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3792
+#, no-wrap
+msgid "\t; Calculate F-stops from 5.6\n"
+msgstr "\t; Calculate F-stops from 5.6\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3796
+#, no-wrap
+msgid ""
+"\tfld1\n"
+"\tfxch\tst1\n"
+"\tfyl2x\n"
+msgstr ""
+"\tfld1\n"
+"\tfxch\tst1\n"
+"\tfyl2x\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3803
+#, no-wrap
+msgid ""
+"\tmov\tal, 0Ah\n"
+"\tcall\tputchar\n"
+"\tjmp\t.bigloop\n"
+msgstr ""
+"\tmov\tal, 0Ah\n"
+"\tcall\tputchar\n"
+"\tjmp\t.bigloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3807
+#, no-wrap
+msgid ""
+".work0:\n"
+"\tmov\tal, '0'\n"
+"\tcall\tputchar\n"
+msgstr ""
+".work0:\n"
+"\tmov\tal, '0'\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3812
+#, no-wrap
+msgid ""
+"align 4\n"
+".toobig:\n"
+"\tcall\thuh\n"
+"\tjmp\t.bigloop\n"
+msgstr ""
+"align 4\n"
+".toobig:\n"
+"\tcall\thuh\n"
+"\tjmp\t.bigloop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3816
+#, no-wrap
+msgid ""
+"align 4\n"
+"done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+msgstr ""
+"align 4\n"
+"done:\n"
+"\tcall\twrite\t\t; flush output buffer\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3825
+#, no-wrap
+msgid "\tfinit\n"
+msgstr "\tfinit\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3838
+#, no-wrap
+msgid ""
+"align 4\n"
+"skiptoeol:\n"
+"\t; Keep reading until you come to cr, lf, or eof\n"
+"\tcall\tgetchar\n"
+"\tjc\tdone\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.cr\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+"skiptoeol:\n"
+"\t; Keep reading until you come to cr, lf, or eof\n"
+"\tcall\tgetchar\n"
+"\tjc\tdone\n"
+"\tcmp\tal, 0Ah\n"
+"\tjne\t.cr\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3843
+#, no-wrap
+msgid ""
+".cr:\n"
+"\tcmp\tal, 0Dh\n"
+"\tjne\tskiptoeol\n"
+"\tret\n"
+msgstr ""
+".cr:\n"
+"\tcmp\tal, 0Dh\n"
+"\tjne\tskiptoeol\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3856
+#, no-wrap
+msgid ""
+".fetch:\n"
+"\tlodsb\n"
+"\tdec\tebx\n"
+"\tclc\n"
+"\tret\n"
+msgstr ""
+".fetch:\n"
+"\tlodsb\n"
+"\tdec\tebx\n"
+"\tclc\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3873
+#, no-wrap
+msgid ""
+".read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.empty\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+msgstr ""
+".read:\n"
+"\tpush\tdword BUFSIZE\n"
+"\tmov\tesi, ibuffer\n"
+"\tpush\tesi\n"
+"\tpush\tdword [fd.in]\n"
+"\tsys.read\n"
+"\tadd\tesp, byte 12\n"
+"\tmov\tebx, eax\n"
+"\tor\teax, eax\n"
+"\tje\t.empty\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3879
+#, no-wrap
+msgid ""
+"align 4\n"
+".empty:\n"
+"\tadd\tesp, byte 4\n"
+"\tstc\n"
+"\tret\n"
+msgstr ""
+"align 4\n"
+".empty:\n"
+"\tadd\tesp, byte 4\n"
+"\tstc\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3908
+#, no-wrap
+msgid ""
+"align 4\n"
+"bcdload:\n"
+"\t; EBP contains the number of chars in dbuffer\n"
+"\tpush\tecx\n"
+"\tpush\tesi\n"
+"\tpush\tedi\n"
+msgstr ""
+"align 4\n"
+"bcdload:\n"
+"\t; EBP contains the number of chars in dbuffer\n"
+"\tpush\tecx\n"
+"\tpush\tesi\n"
+"\tpush\tedi\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3912
+#, no-wrap
+msgid ""
+"\tlea\tecx, [ebp+1]\n"
+"\tlea\tesi, [dbuffer+ebp-1]\n"
+"\tshr\tecx, 1\n"
+msgstr ""
+"\tlea\tecx, [ebp+1]\n"
+"\tlea\tesi, [dbuffer+ebp-1]\n"
+"\tshr\tecx, 1\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3914
+#, no-wrap
+msgid "\tstd\n"
+msgstr "\tstd\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3920
+#, no-wrap
+msgid ""
+"\tmov\tedi, bbuffer\n"
+"\tsub\teax, eax\n"
+"\tmov\t[edi], eax\n"
+"\tmov\t[edi+4], eax\n"
+"\tmov\t[edi+2], ax\n"
+msgstr ""
+"\tmov\tedi, bbuffer\n"
+"\tsub\teax, eax\n"
+"\tmov\t[edi], eax\n"
+"\tmov\t[edi+4], eax\n"
+"\tmov\t[edi+2], ax\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3929
+#, no-wrap
+msgid ""
+".loop:\n"
+"\tlodsw\n"
+"\tsub\tax, 3030h\n"
+"\tshl\tal, 4\n"
+"\tor\tal, ah\n"
+"\tmov\t[edi], al\n"
+"\tinc\tedi\n"
+"\tloop\t.loop\n"
+msgstr ""
+".loop:\n"
+"\tlodsw\n"
+"\tsub\tax, 3030h\n"
+"\tshl\tal, 4\n"
+"\tor\tal, ah\n"
+"\tmov\t[edi], al\n"
+"\tinc\tedi\n"
+"\tloop\t.loop\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3931
+#, no-wrap
+msgid "\tfbld\t[bbuffer]\n"
+msgstr "\tfbld\t[bbuffer]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3938
+#, no-wrap
+msgid ""
+"\tcld\n"
+"\tpop\tedi\n"
+"\tpop\tesi\n"
+"\tpop\tecx\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+msgstr ""
+"\tcld\n"
+"\tpop\tedi\n"
+"\tpop\tesi\n"
+"\tpop\tecx\n"
+"\tsub\teax, eax\n"
+"\tret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3944
+#, no-wrap
+msgid ""
+"align 4\n"
+"printnumber:\n"
+"\tpush\tebp\n"
+"\tmov\tal, [separ]\n"
+"\tcall\tputchar\n"
+msgstr ""
+"align 4\n"
+"printnumber:\n"
+"\tpush\tebp\n"
+"\tmov\tal, [separ]\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3948
+#, no-wrap
+msgid ""
+"\t; Print the integer at the TOS\n"
+"\tmov\tebp, bbuffer+9\n"
+"\tfbstp\t[bbuffer]\n"
+msgstr ""
+"\t; Print the integer at the TOS\n"
+"\tmov\tebp, bbuffer+9\n"
+"\tfbstp\t[bbuffer]\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3954
+#, no-wrap
+msgid ""
+"\t; Check the sign\n"
+"\tmov\tal, [ebp]\n"
+"\tdec\tebp\n"
+"\tor\tal, al\n"
+"\tjns\t.leading\n"
+msgstr ""
+"\t; Check the sign\n"
+"\tmov\tal, [ebp]\n"
+"\tdec\tebp\n"
+"\tor\tal, al\n"
+"\tjns\t.leading\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3958
+#, no-wrap
+msgid ""
+"\t; We got a negative number (should never happen)\n"
+"\tmov\tal, '-'\n"
+"\tcall\tputchar\n"
+msgstr ""
+"\t; We got a negative number (should never happen)\n"
+"\tmov\tal, '-'\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3967
+#, no-wrap
+msgid ""
+".leading:\n"
+"\t; Skip leading zeros\n"
+"\tmov\tal, [ebp]\n"
+"\tdec\tebp\n"
+"\tor\tal, al\n"
+"\tjne\t.first\n"
+"\tcmp\tebp, bbuffer\n"
+"\tjae\t.leading\n"
+msgstr ""
+".leading:\n"
+"\t; Skip leading zeros\n"
+"\tmov\tal, [ebp]\n"
+"\tdec\tebp\n"
+"\tor\tal, al\n"
+"\tjne\t.first\n"
+"\tcmp\tebp, bbuffer\n"
+"\tjae\t.leading\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3972
+#, no-wrap
+msgid ""
+"\t; We are here because the result was 0.\n"
+"\t; Print '0' and return\n"
+"\tmov\tal, '0'\n"
+"\tjmp\tputchar\n"
+msgstr ""
+"\t; We are here because the result was 0.\n"
+"\t; Print '0' and return\n"
+"\tmov\tal, '0'\n"
+"\tjmp\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3984
+#, no-wrap
+msgid ""
+".first:\n"
+"\t; We have found the first non-zero.\n"
+"\t; But it is still packed\n"
+"\ttest\tal, 0F0h\n"
+"\tjz\t.second\n"
+"\tpush\teax\n"
+"\tshr\tal, 4\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tand\tal, 0Fh\n"
+msgstr ""
+".first:\n"
+"\t; We have found the first non-zero.\n"
+"\t; But it is still packed\n"
+"\ttest\tal, 0F0h\n"
+"\tjz\t.second\n"
+"\tpush\teax\n"
+"\tshr\tal, 4\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tand\tal, 0Fh\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3988
+#, no-wrap
+msgid ""
+".second:\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+msgstr ""
+".second:\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:3992
+#, no-wrap
+msgid ""
+".next:\n"
+"\tcmp\tebp, bbuffer\n"
+"\tjb\t.done\n"
+msgstr ""
+".next:\n"
+"\tcmp\tebp, bbuffer\n"
+"\tjb\t.done\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4002
+#, no-wrap
+msgid ""
+"\tmov\tal, [ebp]\n"
+"\tpush\teax\n"
+"\tshr\tal, 4\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tand\tal, 0Fh\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+msgstr ""
+"\tmov\tal, [ebp]\n"
+"\tpush\teax\n"
+"\tshr\tal, 4\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tpop\teax\n"
+"\tand\tal, 0Fh\n"
+"\tadd\tal, '0'\n"
+"\tcall\tputchar\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4005
+#, no-wrap
+msgid ""
+"\tdec\tebp\n"
+"\tjmp\tshort .next\n"
+msgstr ""
+"\tdec\tebp\n"
+"\tjmp\tshort .next\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4010
+#, no-wrap
+msgid ""
+".done:\n"
+"\tpop\tebp\n"
+"\tor\tebp, ebp\n"
+"\tje\t.ret\n"
+msgstr ""
+".done:\n"
+"\tpop\tebp\n"
+"\tor\tebp, ebp\n"
+"\tje\t.ret\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4016
+#, no-wrap
+msgid ""
+".zeros:\n"
+"\tmov\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tdec\tebp\n"
+"\tjne\t.zeros\n"
+msgstr ""
+".zeros:\n"
+"\tmov\tal, '0'\n"
+"\tcall\tputchar\n"
+"\tdec\tebp\n"
+"\tjne\t.zeros\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4019
+#, no-wrap
+msgid ""
+".ret:\n"
+"\tret\n"
+msgstr ""
+".ret:\n"
+"\tret\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4022
+msgid ""
+"The code follows the same format as all the other filters we have seen "
+"before, with one subtle exception:"
+msgstr ""
+"Код следует тому же формату, что и все остальные фильтры, которые мы видели "
+"ранее, с одним небольшим исключением:"
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4025
+msgid ""
+"We are no longer assuming that the end of input implies the end of things to "
+"do, something we took for granted in the _character-oriented_ filters."
+msgstr ""
+"Мы больше не предполагаем, что конец ввода означает конец задач, как мы "
+"привыкли в фильтрах, _ориентированных на символы_."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4027
+msgid ""
+"This filter does not process characters. It processes a _language_ (albeit a "
+"very simple one, consisting only of numbers)."
+msgstr ""
+"Этот фильтр не обрабатывает символы. Он обрабатывает _язык_ (хотя и очень "
+"простой, состоящий только из чисел)."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4029
+msgid "When we have no more input, it can mean one of two things:"
+msgstr ""
+"Когда у нас больше нет входных данных, это может означать одно из двух:"
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4031
+msgid "We are done and can quit. This is the same as before."
+msgstr "Мы закончили и можем выйти. Это то же самое, что и раньше."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4032
+msgid ""
+"The last character we have read was a digit. We have stored it at the end of "
+"our ASCII-to-float conversion buffer. We now need to convert the contents of "
+"that buffer into a number and write the last line of our output."
+msgstr ""
+"Последний прочитанный символ был цифрой. Мы сохранили его в конце буфера "
+"преобразования ASCII в число с плавающей точкой. Теперь нам нужно "
+"преобразовать содержимое этого буфера в число и записать последнюю строку "
+"нашего вывода."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4034
+msgid ""
+"For that reason, we have modified our `getchar` and our `read` routines to "
+"return with the `carry flag` _clear_ whenever we are fetching another "
+"character from the input, or the `carry flag` _set_ whenever there is no "
+"more input."
+msgstr ""
+"По этой причине мы изменили наши подпрограммы `getchar` и `read`, чтобы они "
+"возвращались с _сброшенным_ флагом `carry`, когда получают очередной символ "
+"из ввода, или с _установленным_ флагом `carry`, когда ввода больше нет."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4037
+msgid ""
+"Of course, we are still using assembly language magic to do that! Take a "
+"good look at `getchar`. It _always_ returns with the `carry flag` _clear_."
+msgstr ""
+"Конечно, мы по-прежнему используем магию ассемблера для этого! Внимательно "
+"посмотрите на `getchar`. Он _всегда_ возвращает _очищенный_ `флаг переноса`."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4039
+msgid ""
+"Yet, our main code relies on the `carry flag` to tell it when to quit-and it "
+"works."
+msgstr ""
+"Тем не менее, наш основной код использует `флаг переноса` для определения "
+"момента завершения — и это работает."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4042
+msgid ""
+"The magic is in `read`. Whenever it receives more input from the system, it "
+"just returns to `getchar`, which fetches a character from the input buffer, "
+"_clears_ the `carry flag` and returns."
+msgstr ""
+"Волшебство кроется в `read`. Каждый раз, когда он получает больше входных "
+"данных от системы, он просто возвращается к `getchar`, который извлекает "
+"символ из входного буфера, _сбрасывает_ флаг переноса (`carry flag`) и "
+"возвращает управление."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4045
+msgid ""
+"But when `read` receives no more input from the system, it does _not_ return "
+"to `getchar` at all. Instead, the `add esp, byte 4` op code adds `4` to "
+"`ESP`, _sets_ the `carry flag`, and returns."
+msgstr ""
+"Но когда `read` больше не получает входных данных от системы, он _не_ "
+"возвращается к `getchar` вообще. Вместо этого, инструкция `add esp, byte 4` "
+"добавляет `4` к `ESP`, _устанавливает_ флаг переноса (`carry flag`) и "
+"возвращает управление."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4049
+msgid ""
+"So, where does it return to? Whenever a program uses the `call` op code, the "
+"microprocessor ``push``es the return address, i.e., it stores it on the top "
+"of the stack (not the FPU stack, the system stack, which is in the memory). "
+"When a program uses the `ret` op code, the microprocessor ``pop``s the "
+"return value from the stack, and jumps to the address that was stored there."
+msgstr ""
+"Итак, куда же она возвращается? Каждый раз, когда программа использует "
+"операцию `call`, микропроцессор делает ``push`` для адрес возврата, то есть "
+"сохраняет его на вершине стека (не стека FPU, а системного стека, который "
+"находится в памяти). Когда программа использует операцию `ret`, "
+"микропроцессор делает ``pop`` для значения возврата из стека и переходит по "
+"адресу, который там был сохранён."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4051
+msgid ""
+"But since we added `4` to `ESP` (which is the stack pointer register), we "
+"have effectively given the microprocessor a minor case of _amnesia_: It no "
+"longer remembers it was `getchar` that ``call``ed `read`."
+msgstr ""
+"Но поскольку мы добавили `4` к `ESP` (который является регистром указателя "
+"стека), мы фактически вызвали у микропроцессора лёгкий случай _амнезии_: он "
+"больше не помнит, что именно `getchar` ``вызвал`` `read`."
+
+#. type: delimited block _ 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4053
+msgid ""
+"And since `getchar` never ``push``ed anything before ``call``ing `read`, the "
+"top of the stack now contains the return address to whatever or whoever "
+"``call``ed `getchar`. As far as that caller is concerned, he ``call``ed "
+"`getchar`, which ``ret``urned with the `carry flag` set!"
+msgstr ""
+"И поскольку `getchar` не делал ``push`` ни для чего перед вызовом `read`, "
+"верхушка стека теперь содержит адрес возврата к тому, что или кто вызывал "
+"`getchar`. С точки зрения этого вызывающего, он вызывал `getchar`, который "
+"вызвал ``ret`` с установленным `флагом переноса`!"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4056
+msgid ""
+"Other than that, the `bcdload` routine is caught up in the middle of a "
+"Lilliputian conflict between the Big-Endians and the Little-Endians."
+msgstr ""
+"Помимо этого, процедура `bcdload` оказывается втянута в лилипутский конфликт "
+"между Биг-Эндианцами и Литл-Эндианцами."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4058
+msgid ""
+"It is converting the text representation of a number into that number: The "
+"text is stored in the big-endian order, but the _packed decimal_ is little-"
+"endian."
+msgstr ""
+"Он преобразует текстовое представление числа в само число: текст хранится в "
+"порядке big-endian, но _упакованный десятичный_ формат имеет порядок little-"
+"endian."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4061
+msgid ""
+"To solve the conflict, we use the `std` op code early on. We cancel it with "
+"`cld` later on: It is quite important we do not `call` anything that may "
+"depend on the default setting of the _direction flag_ while `std` is active."
+msgstr ""
+"Для разрешения конфликта мы используем инструкцию процессора `std` в самом "
+"начале. Позже мы отменяем его с помощью `cld`: очень важно не вызывать "
+"ничего, что может зависеть от стандартного значения _флага направления_, "
+"пока активен `std`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4063
+msgid ""
+"Everything else in this code should be quit eclear, providing you have read "
+"the entire chapter that precedes it."
+msgstr ""
+"Всё остальное в этом коде должно быть достаточно понятным, при условии, что "
+"вы прочитали всю предшествующую главу."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4066
+msgid ""
+"It is a classical example of the adage that programming requires a lot of "
+"thought and only a little coding. Once we have thought through every tiny "
+"detail, the code almost writes itself."
+msgstr ""
+"Это классический пример поговорки о том, что программирование требует много "
+"размышлений и лишь немного кодирования. Как только мы продумаем каждую "
+"мельчайшую деталь, код практически напишется сам."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4068
+#, no-wrap
+msgid "Using pinhole"
+msgstr "Использование программы pinhole"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4072
+msgid ""
+"Because we have decided to make the program _ignore_ any input except for "
+"numbers (and even those inside a comment), we can actually perform _textual "
+"queries_. We do not _have to_, but we _can_."
+msgstr ""
+"Поскольку мы решили сделать так, чтобы программа _игнорировала_ любой ввод, "
+"кроме чисел (и даже их внутри комментария), мы можем выполнять _текстовые "
+"запросы_. Мы не _обязаны_ этого делать, но _можем_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4074
+msgid ""
+"In my humble opinion, forming a textual query, instead of having to follow a "
+"very strict syntax, makes software much more user friendly."
+msgstr ""
+"По моему скромному мнению, формирование текстового запроса вместо "
+"необходимости следовать очень строгому синтаксису делает программное "
+"обеспечение гораздо более дружелюбным к пользователю."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4080
+msgid ""
+"Suppose we want to build a pinhole camera to use the 4x5 inch film. The "
+"standard focal length for that film is about 150mm. We want to _fine-tune_ "
+"our focal length so the pinhole diameter is as round a number as possible. "
+"Let us also suppose we are quite comfortable with cameras but somewhat "
+"intimidated by computers. Rather than just have to type in a bunch of "
+"numbers, we want to _ask_ a couple of questions."
+msgstr ""
+"Предположим, мы хотим построить камеру-обскуру для использования плёнки "
+"размером 4x5 дюймов. Стандартное фокусное расстояние для такой плёнки "
+"составляет около 150 мм. Мы хотим _точно настроить_ фокусное расстояние, "
+"чтобы диаметр отверстия был как можно более круглым числом. Допустим также, "
+"что мы хорошо разбираемся в фотоаппаратах, но немного боимся компьютеров. "
+"Вместо того чтобы просто вводить кучу цифр, мы хотим _задать_ пару вопросов."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4082
+msgid "Our session might look like this:"
+msgstr "Наша сессия может выглядеть так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4086
+#, no-wrap
+msgid "% pinhole\n"
+msgstr "% pinhole\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4088
+#, no-wrap
+msgid "Computer,\n"
+msgstr "Computer,\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4101
+#, no-wrap
+msgid ""
+"What size pinhole do I need for the focal length of 150?\n"
+"150\t490\t306\t362\t2930\t12\n"
+"Hmmm... How about 160?\n"
+"160\t506\t316\t362\t3125\t12\n"
+"Let's make it 155, please.\n"
+"155\t498\t311\t362\t3027\t12\n"
+"Ah, let's try 157...\n"
+"157\t501\t313\t362\t3066\t12\n"
+"156?\n"
+"156\t500\t312\t362\t3047\t12\n"
+"That's it! Perfect! Thank you very much!\n"
+"^D\n"
+msgstr ""
+"What size pinhole do I need for the focal length of 150?\n"
+"150\t490\t306\t362\t2930\t12\n"
+"Hmmm... How about 160?\n"
+"160\t506\t316\t362\t3125\t12\n"
+"Let's make it 155, please.\n"
+"155\t498\t311\t362\t3027\t12\n"
+"Ah, let's try 157...\n"
+"157\t501\t313\t362\t3066\t12\n"
+"156?\n"
+"156\t500\t312\t362\t3047\t12\n"
+"That's it! Perfect! Thank you very much!\n"
+"^D\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4104
+msgid ""
+"We have found that while for the focal length of 150, our pinhole diameter "
+"should be 490 microns, or 0.49 mm, if we go with the almost identical focal "
+"length of 156 mm, we can get away with a pinhole diameter of exactly one "
+"half of a millimeter."
+msgstr ""
+"Мы выяснили, что при фокусном расстоянии 150 мм диаметр отверстия должен "
+"составлять 490 микрон, или 0,49 мм, но если взять почти идентичное фокусное "
+"расстояние 156 мм, можно использовать отверстие диаметром ровно половину "
+"миллиметра."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4106
+#, no-wrap
+msgid "Scripting"
+msgstr "Скриптинг"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4109
+msgid ""
+"Because we have chosen the `+#+` character to denote the start of a comment, "
+"we can treat our pinhole software as a _scripting language_."
+msgstr ""
+"Поскольку мы выбрали символ `+#+` для обозначения начала комментария, мы "
+"можем рассматривать наше программное обеспечение pinhole как _скриптовый "
+"язык_."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4111
+msgid "You have probably seen shell _scripts_ that start with:"
+msgstr "Вы, вероятно, видели _сценарии_ оболочки, которые начинаются с:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4115
+#, no-wrap
+msgid "#! /bin/sh\n"
+msgstr "#! /bin/sh\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4118
+msgid "...or..."
+msgstr "...или..."
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4122
+#, no-wrap
+msgid "#!/bin/sh\n"
+msgstr "#!/bin/sh\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4125
+msgid "...because the blank space after the `#!` is optional."
+msgstr "...потому что пробел после `#!` необязателен."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4128
+msgid ""
+"Whenever UNIX(R) is asked to run an executable file which starts with the `#!"
+"`, it assumes the file is a script. It adds the command to the rest of the "
+"first line of the script, and tries to execute that."
+msgstr ""
+"Когда UNIX(R) получает запрос на выполнение исполняемого файла, который "
+"начинается с `#!`, он предполагает, что это скрипт. Он добавляет команду к "
+"остальной части первой строки скрипта и пытается выполнить её."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4130
+msgid ""
+"Suppose now that we have installed pinhole in /usr/local/bin/, we can now "
+"write a script to calculate various pinhole diameters suitable for various "
+"focal lengths commonly used with the 120 film."
+msgstr ""
+"Предположим, что мы установили pinhole в /usr/local/bin/, теперь мы можем "
+"написать скрипт для расчёта различных диаметров отверстий, подходящих для "
+"различных фокусных расстояний, обычно используемых с плёнкой 120."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4132
+msgid "The script might look something like this:"
+msgstr "Скрипт может выглядеть примерно так:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4138
+#, no-wrap
+msgid ""
+"#! /usr/local/bin/pinhole -b -i\n"
+"# Find the best pinhole diameter\n"
+"# for the 120 film\n"
+msgstr ""
+"#! /usr/local/bin/pinhole -b -i\n"
+"# Find the best pinhole diameter\n"
+"# for the 120 film\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4141
+#, no-wrap
+msgid ""
+"### Standard\n"
+"80\n"
+msgstr ""
+"### Standard\n"
+"80\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4144
+#, no-wrap
+msgid ""
+"### Wide angle\n"
+"30, 40, 50, 60, 70\n"
+msgstr ""
+"### Wide angle\n"
+"30, 40, 50, 60, 70\n"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4147
+#, no-wrap
+msgid ""
+"### Telephoto\n"
+"100, 120, 140\n"
+msgstr ""
+"### Telephoto\n"
+"100, 120, 140\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4150
+msgid "Because 120 is a medium size film, we may name this file medium."
+msgstr ""
+"Поскольку 120 — это плёнка среднего размера, мы можем назвать этот файл "
+"`medium`."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4152
+msgid ""
+"We can set its permissions to execute, and run it as if it were a program:"
+msgstr ""
+"Мы можем установить права на выполнение и запустить его, как если бы это "
+"была программа:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4157
+#, no-wrap
+msgid ""
+"% chmod 755 medium\n"
+"% ./medium\n"
+msgstr ""
+"% chmod 755 medium\n"
+"% ./medium\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4160
+msgid "UNIX(R) will interpret that last command as:"
+msgstr "UNIX(R) интерпретирует последнюю команду следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4164
+#, no-wrap
+msgid "% /usr/local/bin/pinhole -b -i ./medium\n"
+msgstr "% /usr/local/bin/pinhole -b -i ./medium\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4167
+msgid "It will run that command and display:"
+msgstr "Он выполнит эту команду и отобразит:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4179
+#, no-wrap
+msgid ""
+"80\t358\t224\t256\t1562\t11\n"
+"30\t219\t137\t128\t586\t9\n"
+"40\t253\t158\t181\t781\t10\n"
+"50\t283\t177\t181\t977\t10\n"
+"60\t310\t194\t181\t1172\t10\n"
+"70\t335\t209\t181\t1367\t10\n"
+"100\t400\t250\t256\t1953\t11\n"
+"120\t438\t274\t256\t2344\t11\n"
+"140\t473\t296\t256\t2734\t11\n"
+msgstr ""
+"80\t358\t224\t256\t1562\t11\n"
+"30\t219\t137\t128\t586\t9\n"
+"40\t253\t158\t181\t781\t10\n"
+"50\t283\t177\t181\t977\t10\n"
+"60\t310\t194\t181\t1172\t10\n"
+"70\t335\t209\t181\t1367\t10\n"
+"100\t400\t250\t256\t1953\t11\n"
+"120\t438\t274\t256\t2344\t11\n"
+"140\t473\t296\t256\t2734\t11\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4182
+msgid "Now, let us enter:"
+msgstr "Теперь введем:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4186
+#, no-wrap
+msgid "% ./medium -c\n"
+msgstr "% ./medium -c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4189
+msgid "UNIX(R) will treat that as:"
+msgstr "UNIX(R) интерпретирует это следующим образом:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4193
+#, no-wrap
+msgid "% /usr/local/bin/pinhole -b -i ./medium -c\n"
+msgstr "% /usr/local/bin/pinhole -b -i ./medium -c\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4197
+msgid ""
+"That gives it two conflicting options: `-b` and `-c` (Use Bender's constant "
+"and use Connors' constant). We have programmed it so later options override "
+"early ones-our program will calculate everything using Connors' constant:"
+msgstr ""
+"Это дает ему два конфликтующих параметра: `-b` и `-c` (Использовать "
+"константу Бендера и использовать константу Коннорса). Мы запрограммировали "
+"его так, что более поздние параметры переопределяют ранние — наша программа "
+"будет вычислять все, используя константу Коннорса:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4209
+#, no-wrap
+msgid ""
+"80\t331\t242\t256\t1826\t11\n"
+"30\t203\t148\t128\t685\t9\n"
+"40\t234\t171\t181\t913\t10\n"
+"50\t262\t191\t181\t1141\t10\n"
+"60\t287\t209\t181\t1370\t10\n"
+"70\t310\t226\t256\t1598\t11\n"
+"100\t370\t270\t256\t2283\t11\n"
+"120\t405\t296\t256\t2739\t11\n"
+"140\t438\t320\t362\t3196\t12\n"
+msgstr ""
+"80\t331\t242\t256\t1826\t11\n"
+"30\t203\t148\t128\t685\t9\n"
+"40\t234\t171\t181\t913\t10\n"
+"50\t262\t191\t181\t1141\t10\n"
+"60\t287\t209\t181\t1370\t10\n"
+"70\t310\t226\t256\t1598\t11\n"
+"100\t370\t270\t256\t2283\t11\n"
+"120\t405\t296\t256\t2739\t11\n"
+"140\t438\t320\t362\t3196\t12\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4213
+msgid ""
+"We decide we want to go with Bender's constant after all. We want to save "
+"its values as a comma-separated file:"
+msgstr ""
+"Мы решаем, что всё же выбираем константу Бендера. Мы хотим сохранить её "
+"значения в виде файла с разделителями-запятыми:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4229
+#, no-wrap
+msgid ""
+"% ./medium -b -e > bender\n"
+"% cat bender\n"
+"focal length in millimeters,pinhole diameter in microns,F-number,normalized F-number,F-5.6 multiplier,stops from F-5.6\n"
+"80,358,224,256,1562,11\n"
+"30,219,137,128,586,9\n"
+"40,253,158,181,781,10\n"
+"50,283,177,181,977,10\n"
+"60,310,194,181,1172,10\n"
+"70,335,209,181,1367,10\n"
+"100,400,250,256,1953,11\n"
+"120,438,274,256,2344,11\n"
+"140,473,296,256,2734,11\n"
+"%\n"
+msgstr ""
+"% ./medium -b -e > bender\n"
+"% cat bender\n"
+"focal length in millimeters,pinhole diameter in microns,F-number,normalized F-number,F-5.6 multiplier,stops from F-5.6\n"
+"80,358,224,256,1562,11\n"
+"30,219,137,128,586,9\n"
+"40,253,158,181,781,10\n"
+"50,283,177,181,977,10\n"
+"60,310,194,181,1172,10\n"
+"70,335,209,181,1367,10\n"
+"100,400,250,256,1953,11\n"
+"120,438,274,256,2344,11\n"
+"140,473,296,256,2734,11\n"
+"%\n"
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4232
+#, no-wrap
+msgid "Caveats"
+msgstr "Предостережения"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4236
+msgid ""
+"Assembly language programmers who \"grew up\" under MS-DOS(R) and Windows(R) "
+"often tend to take shortcuts. Reading the keyboard scan codes and writing "
+"directly to video memory are two classical examples of practices which, "
+"under MS-DOS(R) are not frowned upon but considered the right thing to do."
+msgstr ""
+"Программисты на ассемблере, которые \"выросли\" на MS-DOS(R) и Windows(R), "
+"часто склонны искать короткие пути. Чтение скан-кодов клавиатуры и запись "
+"напрямую в видеопамять — это два классических примера подходов, которые в MS-"
+"DOS(R) не только не порицаются, но и считаются правильными."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4238
+msgid ""
+"The reason? Both the PC BIOS and MS-DOS(R) are notoriously slow when "
+"performing these operations."
+msgstr ""
+"Причина? И BIOS ПК, и MS-DOS(R) печально известны своей медленной работой "
+"при выполнении этих операций."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4241
+msgid ""
+"You may be tempted to continue similar practices in the UNIX(R) "
+"environment. For example, I have seen a web site which explains how to "
+"access the keyboard scan codes on a popular UNIX(R) clone."
+msgstr ""
+"Вас может возникнуть соблазн продолжить подобные практики в среде UNIX(R). "
+"Например, я видел веб-сайт, который объясняет, как получить доступ к скан-"
+"кодам клавиатуры на популярном клоне UNIX(R)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4243
+msgid ""
+"That is generally a _very bad idea_ in UNIX(R) environment! Let me explain "
+"why."
+msgstr ""
+"Это, как правило, *очень плохая идея* в среде UNIX(R)! Позвольте объяснить "
+"почему."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4245
+#, no-wrap
+msgid "UNIX(R) Is Protected"
+msgstr "UNIX(R) защищен"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4252
+msgid ""
+"For one thing, it may simply not be possible. UNIX(R) runs in protected "
+"mode. Only the kernel and device drivers are allowed to access hardware "
+"directly. Perhaps a particular UNIX(R) clone will let you read the keyboard "
+"scan codes, but chances are a real UNIX(R) operating system will not. And "
+"even if one version may let you do it, the next one may not, so your "
+"carefully crafted software may become a dinosaur overnight."
+msgstr ""
+"Прежде всего, это может быть просто невозможно. UNIX(R) работает в "
+"защищённом режиме. Только ядро и драйверы устройств имеют прямой доступ к "
+"аппаратному обеспечению. Возможно, какой-то конкретный клон UNIX(R) позволит "
+"вам читать скан-коды клавиатуры, но скорее всего настоящая операционная "
+"система UNIX(R) этого не допустит. И даже если одна версия разрешает это, "
+"следующая может запретить, так что ваше тщательно разработанное программное "
+"обеспечение может в одночасье устареть."
+
+#. type: Title ===
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4254
+#, no-wrap
+msgid "UNIX(R) Is an Abstraction"
+msgstr "UNIX(R) — это работа с абстракциями"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4257
+msgid ""
+"But there is a much more important reason not to try accessing the hardware "
+"directly (unless, of course, you are writing a device driver), even on the "
+"UNIX(R) like systems that let you do it:"
+msgstr ""
+"Но существует гораздо более важная причина не пытаться обращаться к "
+"оборудованию напрямую (если, конечно, вы не пишете драйвер устройства), даже "
+"в UNIX(R)-подобных системах, которые позволяют это делать:"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4259
+msgid "_UNIX(R) is an abstraction!_"
+msgstr "_UNIX(R) — это работа с абстракциями!_"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4265
+msgid ""
+"There is a major difference in the philosophy of design between MS-DOS(R) "
+"and UNIX(R). MS-DOS(R) was designed as a single-user system. It is run on "
+"a computer with a keyboard and a video screen attached directly to that "
+"computer. User input is almost guaranteed to come from that keyboard. Your "
+"program's output virtually always ends up on that screen."
+msgstr ""
+"Существует фундаментальное различие в философии проектирования между MS-"
+"DOS(R) и UNIX(R). MS-DOS(R) разрабатывалась как однопользовательская "
+"система. Она работает на компьютере, к которому напрямую подключены "
+"клавиатура и монитор. Ввод пользователя практически гарантированно поступает "
+"с этой клавиатуры. Вывод вашей программы почти всегда отображается на этом "
+"экране."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4268
+msgid ""
+"This is NEVER guaranteed under UNIX(R). It is quite common for a UNIX(R) "
+"user to pipe and redirect program input and output:"
+msgstr ""
+"Это НИКОГДА не гарантируется в UNIX(R). Довольно часто пользователь UNIX(R) "
+"перенаправляет ввод и вывод программы с помощью конвейеров и перенаправлений:"
+
+#. type: delimited block . 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4272
+#, no-wrap
+msgid "% program1 | program2 | program3 > file1\n"
+msgstr "% program1 | program2 | program3 > file1\n"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4276
+msgid ""
+"If you have written program2, your input does not come from the keyboard but "
+"from the output of program1. Similarly, your output does not go to the "
+"screen but becomes the input for program3 whose output, in turn, goes to "
+"[.filename]#file1#."
+msgstr ""
+"Если вы написали program2, ваш ввод поступает не с клавиатуры, а из вывода "
+"program1. Аналогично, ваш вывод не выводится на экран, а становится вводом "
+"для program3, чей вывод, в свою очередь, отправляется в [.filename]#file1#."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4279
+msgid ""
+"But there is more! Even if you made sure that your input comes from, and "
+"your output goes to, the terminal, there is no guarantee the terminal is a "
+"PC: It may not have its video memory where you expect it, nor may its "
+"keyboard be producing PC-style scan codes. It may be a Macintosh(R), or any "
+"other computer."
+msgstr ""
+"Но это еще не все! Даже если вы убедились, что ваш ввод поступает с "
+"терминала, а вывод отправляется на терминал, нет гарантии, что терминал "
+"является ПК: его видеопамять может находиться не там, где вы ожидаете, а "
+"клавиатура может генерировать не PC-совместимые скан-коды. Это может быть "
+"Macintosh(R) или любой другой компьютер."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4281
+msgid ""
+"Now you may be shaking your head: My software is in PC assembly language, "
+"how can it run on a Macintosh(R)? But I did not say your software would be "
+"running on a Macintosh(R), only that its terminal may be a Macintosh(R)."
+msgstr ""
+"Вот вы, возможно, покачаете головой: мое программное обеспечение написано на "
+"языке ассемблера для ПК, как оно может работать на Macintosh(R)? Но я не "
+"говорил, что ваше программное обеспечение будет работать на Macintosh(R), а "
+"лишь что его терминалом может быть Macintosh(R)."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4285
+msgid ""
+"Under UNIX(R), the terminal does not have to be directly attached to the "
+"computer that runs your software, it can even be on another continent, or, "
+"for that matter, on another planet. It is perfectly possible that a "
+"Macintosh(R) user in Australia connects to a UNIX(R) system in North America "
+"(or anywhere else) via telnet. The software then runs on one computer, "
+"while the terminal is on a different computer: If you try to read the scan "
+"codes, you will get the wrong input!"
+msgstr ""
+"В UNIX(R) терминал не обязательно должен быть напрямую подключён к "
+"компьютеру, на котором работает ваше программное обеспечение — он может "
+"находиться даже на другом континенте или, например, на другой планете. "
+"Вполне возможно, что пользователь Macintosh(R) в Австралии подключается к "
+"системе UNIX(R) в Северной Америке (или где-либо ещё) через telnet. "
+"Программное обеспечение работает на одном компьютере, а терминал находится "
+"на другом: если попытаться считать скан-коды, будут получены неверные данные!"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4288
+msgid ""
+"Same holds true about any other hardware: A file you are reading may be on a "
+"disk you have no direct access to. A camera you are reading images from may "
+"be on a space shuttle, connected to you via satellites."
+msgstr ""
+"То же самое относится и к любому другому оборудованию: файл, который вы "
+"читаете, может находиться на диске, к которому у вас нет прямого доступа. "
+"Камера, с которой вы считываете изображения, может находиться на космическом "
+"корабле, соединённом с вами через спутники."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4291
+msgid ""
+"That is why under UNIX(R) you must never make any assumptions about where "
+"your data is coming from and going to. Always let the system handle the "
+"physical access to the hardware."
+msgstr ""
+"Вот почему в UNIX(R) никогда нельзя делать никаких предположений о том, "
+"откуда поступают ваши данные и куда они направляются. Всегда позволяйте "
+"системе управлять физическим доступом к оборудованию."
+
+#. type: delimited block = 4
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4299
+msgid ""
+"These are caveats, not absolute rules. Exceptions are possible. For "
+"example, if a text editor has determined it is running on a local machine, "
+"it may want to read the scan codes directly for improved control. I am not "
+"mentioning these caveats to tell you what to do or what not to do, just to "
+"make you aware of certain pitfalls that await you if you have just arrived "
+"to UNIX(R) form MS-DOS(R). Of course, creative people often break rules, "
+"and it is OK as long as they know they are breaking them and why."
+msgstr ""
+"Это предостережения, а не абсолютные правила. Возможны исключения. Например, "
+"если текстовый редактор определил, что работает на локальной машине, он "
+"может захотеть читать скан-коды напрямую для улучшенного управления. Я "
+"упоминаю эти предостережения не для того, чтобы сказать вам, что делать или "
+"чего не делать, а просто чтобы вы осознавали определённые подводные камни, "
+"которые ждут вас, если вы только что перешли с MS-DOS(R) на UNIX(R). "
+"Конечно, творческие люди часто нарушают правила, и это нормально, пока они "
+"осознают, что нарушают их, и понимают почему."
+
+#. type: Title ==
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4302
+#, no-wrap
+msgid "Acknowledgements"
+msgstr "Благодарности"
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4305
+msgid ""
+"This tutorial would never have been possible without the help of many "
+"experienced FreeBSD programmers from the {freebsd-hackers}, many of whom "
+"have patiently answered my questions, and pointed me in the right direction "
+"in my attempts to explore the inner workings of UNIX(R) system programming "
+"in general and FreeBSD in particular."
+msgstr ""
+"Это руководство никогда бы не было создано без помощи многих опытных "
+"программистов FreeBSD из {freebsd-hackers}, которые терпеливо отвечали на "
+"мои вопросы и направляли меня в моих попытках изучить внутренние механизмы "
+"программирования в системе UNIX(R) в целом и в FreeBSD в частности."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4308
+msgid ""
+"Thomas M. Sommers opened the door for me . His https://web.archive.org/web/"
+"20090914064615/http://www.codebreakers-journal.com/content/view/262/27[How "
+"do I write \"Hello, world\" in FreeBSD assembler?] web page was my first "
+"encounter with an example of assembly language programming under FreeBSD."
+msgstr ""
+"Томас М. Соммерс открыл дверь для меня. Его https://web.archive.org/web/"
+"20090914064615/http://www.codebreakers-journal.com/content/view/262/27[Как "
+"написать \"Hello, world\" на ассемблере в FreeBSD?] веб-страница стала моей "
+"первой встречей с примером программирования на ассемблере под FreeBSD."
+
+#. type: Plain text
+#: documentation/content/en/books/developers-handbook/x86/_index.adoc:4310
+msgid ""
+"Jake Burkholder has kept the door open by willingly answering all of my "
+"questions and supplying me with example assembly language source code."
+msgstr ""
+"Джейк Буркхолдер держал дверь открытой, охотно отвечая на все мои вопросы и "
+"предоставляя примеры исходного кода на языке ассемблера."