58516940
58516940
com
https://ebooknice.com/product/rust-in-action-meap-
ver-16-29258470
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebooknice.com/product/rust-in-action-23285108
ebooknice.com
(Ebook) Rust in Action: Systems programming concepts and techniques by Tim McNamara
ISBN 9781617294556, 1617294551
https://ebooknice.com/product/rust-in-action-systems-programming-concepts-and-
techniques-42970346
ebooknice.com
(Ebook) Refactoring to Rust, MEAP V05 by Lily Mara ISBN 9781617299018, 1617299014
https://ebooknice.com/product/refactoring-to-rust-meap-v05-47531982
ebooknice.com
(Ebook) Rust Design Patterns (MEAP V02) by Brenden Matthews ISBN 9781633437463,
1633437469
https://ebooknice.com/product/rust-design-patterns-meap-v02-54294038
ebooknice.com
(Ebook) Rust Web Development (MEAP V06) by Bastian Gruber ISBN 9781617299001,
1617299006
https://ebooknice.com/product/rust-web-development-meap-v06-42603006
ebooknice.com
https://ebooknice.com/product/quantum-computing-in-action-meap-v09-23285606
ebooknice.com
https://ebooknice.com/product/refactoring-to-rust-meap-version-5-43786000
ebooknice.com
(Ebook) Rust Power Tools (MEAP V01) by Sam Van Overmeire ISBN 9781633437494,
1633437493
https://ebooknice.com/product/rust-power-tools-meap-v01-51048494
ebooknice.com
https://ebooknice.com/product/elasticsearch-in-action-second-edition-
meap-v13-50699840
ebooknice.com
MEAP VERSION 16
ABOUT THIS MEAP
https://livebook.manning.com/#!/book/rust-in-action/discussion
WELCOME
Dear Reader,
Thanks for taking a chance and buying this early release book on the
Rust programming language and the internals of computer systems.
I hope that you'll be rewarded with a fun, informative read!
Thank you once again for choosing to purchase the book. It's a
privilege to ride a short way with you along your computing journey.
—Tim McNamara
BRIEF TABLE OF CONTENTS
1 Introducing Rust
6 Memory
7 Files & Storage
8 Networking
9 Time and Time Keeping
When you begin to program in Rust, it’s likely that you will want to
continue to do so. And this book, Rust in Action, will build your
confidence as a Rust programmer. But, it will not teach you how to
program from the beginning. This book is intended to be read by
people who are considering Rust as their next language, and for
those who enjoy implementing practical working examples. Here is a
list of some of the larger examples this book covers:
As you may gather from scanning through that list, reading this book
will teach you more than Rust. It also introduces you to systems
programming and low-level programming. Learning some of the
concepts from these areas will benefit your Rust programming
journey because much of the Rust community assumes that you
already have that knowledge. As you work through Rust in Action,
you’ll learn about the role of an operating system (OS), how a CPU
works, how computers keep time, what pointers are, and what a
data type is. You will gain an understanding of how the computer’s
internal systems interoperate. Learning more than syntax, you will
also see why Rust was created and the challenges that it addresses.
[1] See “Firecracker: Secure and fast microVMs for serverless computing,”
https://firecracker-microvm.github.io/
[3] See “The Epic Story of Dropbox’s Exodus From the Amazon Cloud Empire,”
https://www.wired.com/2016/03/epic-story-dropboxs-exodus-amazon-cloud-
empire/
[7] See "`Rust Case Study: Community makes Rust an easy choice for npm,”
https://www.rust-lang.org/static/pdfs/Rust-npm-Whitepaper.pdf
[11] See “The fast, light, and robust EVM and WASM client,”
https://github.com/paritytech/parity-ethereum
[12]
Excerpt from a Hacker News comment thread
That being said, there was a ton of work getting Rust to play nice
within the Chrome OS build environment. The Rust folks have been super
helpful in answering my questions though.
I wrote the code in Rust, and then I used 'cargo fuzz' to try
and find vulnerabilities. After running a billion(!) fuzz
iterations, I found 5 bugs (see the 'vobsub' section of the
trophy case for a list https://github.com/rust-fuzz/trophy-case).
From this excerpt, we can see that language adoption has been
“bottom up” by engineers looking to overcome technical challenges.
Skepticism with using Rust for internal side-projects from colleagues
has been overcome, thus gaining in first-hand experience and
measurable performance data. And in the time since late 2017, Rust
has continued to mature and strengthen. It has become an accepted
part of Google’s technology landscape; it is now an officially
sanctioned language within the Fuchsia OS project.
Note
To install Rust, use the official installers provided at
https://rustup.rs/.
1.3.1 Cheating your way to “Hello, world!”
The first thing that most programmers do when they reach for a new
programming language is to learn how to print “Hello, world!” to the
console. You’ll do that too, but with flair. You’ll verify that everything
is in working order before you encounter annoying syntax errors.
C:\> cd %TMP%
$ cd $TMP
From this point forward, the commands for all operating systems
should be the same. If you installed Rust correctly, the following
three commands will display “Hello, world!” on the screen (as well as
a bunch of other output):
Here is an example of what the entire code looks like for Windows:
C:\> cd %TMP%
C:\Users\Tim\AppData\Local\Temp\> cd hello
C:\Users\Tim\AppData\Local\Temp\hello\> cargo run
Compiling hello v0.1.0 (file:///C:/Users/Tim/AppData/Local/Temp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
Running `target\debug\hello.exe`
Hello, world!
$ cd $TMP
$ cd hello
$ cargo run
Compiling hello v0.1.0 (/home/tsm/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.26s
Running `target/debug/hello`
Hello, world!
If you have reached this far, fantastic! You have run your first Rust
code without needing to write any Rust. Let’s take a look at what’s
just happened.
$ tree hello
hello
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
All Rust crates begin with the same structure. In the base directory,
a file called Cargo.toml describes the project’s metadata, such as the
project’s name, its version, and its dependencies. Source code
appears in the src directory. Rust source code files use the .rs
filename extension.
The next command that you executed was cargo run. This line is
much simpler to grasp, but cargo actually did much more work than
you realized. You asked cargo to run the project. As there was
nothing to actually run when you invoked the command, it decided
to compile the code in debug mode on your behalf to provide
maximal error information. As it happens, the src/main.rs file always
includes a “Hello, world!” stub. The result of that compilation was a
file called hello (or hello.exe). The hello file was executed, and the
result printed to your screen.
For the curious, our project’s directory structure has changed a great
deal. We now have a Cargo.lock file in the base of our project and a
target/ directory. Both that file and the directory are managed by
cargo. Because these are artifacts of the compilation process, we
won’t need to touch these. Cargo.lock is a file that specifies the
exact version numbers of all the dependencies so that future builds
are reliably built the same way until Cargo.toml is modified.
Hello, world!
Grüß Gott!
ハロー・ワールド
You have probably seen the first line in your travels. The other two
are there to highlight few of Rust’s features: easy iteration and built-
in support for Unicode.
Now open the file hello2/src/main.rs in a text editor. Replace the text
in that file with the text in the following listing. You’ll find the source
code for this listing in the file ch1/ch1-hello2.rs (see section 1.4 for
access to this book’s source files).
fn greet_world() {
println!("Hello, world!"); ①
fn main() {
greet_world(); ⑦
}
Now that our code is updated, execute cargo run from the hello2/
directory. You should see three greetings. Let’s take a few moments
to touch on some of the elements in listing 1.1.
One of the first things that you are likely to notice is that strings in
Rust are able to include a wide range of characters. Strings are UTF-
8. This means that you can use non-English languages with relative
ease.
The one character that might look out of place is the exclamation
mark after println. If you have programmed in Ruby, you may be
used to thinking that it is used to signal a destructive operation. In
Rust, it signals the use of a macro. Macros can be thought of as sort
of fancy functions for now. These offer the ability to avoid boilerplate
code. In the case of println!, there is a lot of type detection going
on under the hood so that arbitrary data types can be printed to the
screen.
https://manning.com/books/rust-in-action
https://github.com/rust-in-action/code
Note
The source code for this listing is in the ch1/ch1-
penguins/src/main.rs file.
fn main() { ①
let penguin_data ="\
common name,length (cm)
Little penguin,33
Yellow-eyed penguin,65
Fiordland penguin,60
Invalid,data
";
if cfg!(debug_assertions) { ⑦
// following line should not exceed 55 chars; please add a line break
and move annotation marker as needed
eprintln!("debug: {:?} -> {:?}", record, fields); ⑧
}
// following line should not exceed 55 chars; please add a line break
and move annotation marker as needed
let maybe_length: Result<f32, _> = fields[1].parse(); ⑩
if maybe_length.is_err() { ⑪
continue;
}
Listing 1.3. Output from listing 1.2 after running cargo run
$ cargo run
// code lines without annotations are limited to 76 chars in order to fit
the
printed page. Following line needs a line break
Compiling ch1-penguins v0.1.0 (/path/to/rust-in-action/code/ch1/ch1-
penguins)
Finished dev [unoptimized + debuginfo] target(s) in 0.40s
Running `target/debug/ch1-penguins`
debug: " Little penguin,33" -> ["Little penguin", "33"]
Little penguin, 33cm
debug: " Yellow-eyed penguin,65" -> ["Yellow-eyed penguin", "65"]
Yellow-eyed penguin, 65cm
debug: " Fiordland penguin,60" -> ["Fiordland penguin", "60"]
Fiordland penguin, 60cm
debug: " Invalid,data" -> ["Invalid", "data"]
You probably noticed the distracting lines starting with debug:. We
can eliminate these by compiling a release build using cargo’s --
release flag. This conditional compilation functionality is provided by
the cfg!(debug_assertions) { … } block within lines 22-24 of the
following listing.
It’s possible to further reduce the output by adding the -q flag (-q is
shorthand for “quiet”). The following snippet shows the syntax:
In a strict sense, rustc is the Rust compiler. The preceding examples don’t use it
though. Instead, the examples interact with cargo. cargo provides a simple
interface, invoking rustc on our behalf.
To see what cargo passes to rustc, add the --verbose flag:
$ cd code/ch1/ch1-penguins
$ cargo run --verbose
Compiling ch1-penguins v0.1.0 (rust-in-action/code/ch1/ch1-penguins)
// line breaks needed in following; 76 max characters including spaces per
each line
Running `rustc --crate-name ch1_penguins --edition=2018 src/main.rs
--error-format=json --json=diagnostic-rendered-ansi --crate-type bin
--emit=dep-info,link -Cbitcode-in-rlib=no -C debuginfo=2 -C
metadata=390c3b75f851c687 -C extra-filename=-390c3b75f851c687
--out-dir rust-in-action/code/ch1/ch1-penguins/target/debug/deps
-C incremental=rust-in-action/code/ch1/ch1-penguins/target/debug
/incremental
-L dependency=rust-in-action/code/ch1/ch1-penguins/target/debug/deps`
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/ch1-penguins`
debug: " Little penguin,33" -> ["Little penguin", "33"]
Little penguin, 33cm
debug: " Yellow-eyed penguin,65" -> ["Yellow-eyed penguin", "65"]
Yellow-eyed penguin, 65cm
debug: " Fiordland penguin,60" -> ["Fiordland penguin", "60"]
Fiordland penguin, 60cm
debug: " Invalid,data" -> ["Invalid", "data"]
Until late 2018, visitors to the Rust homepage were greeted with the
(technically heavy) message, “Rust is a systems programming
language that runs blazingly fast, prevents segfaults and guarantees
thread safety.” At that point, the community implemented a change
to its wording to put its users (and its potential users) at the center
(table 1.1).
Table 1.1. Rust slogans over time. As Rust has developed its
confidence, it has increasingly embraced the idea of acting
as a facilitator and supporter of everyone wanting to
achieve their programming aspirations.
Until late 2018 From that point onward
Let’s flesh out those three goals: safety, productivity, and control.
What are these and why do these matter?
The following listing shows a dangling pointer. Note that you’ll find
this source code in the ch1/ch1-cereals/src/main.rs file.
#[derive(Debug)] ①
enum Cereal { ②
Barley, Millet, Rice,
Rye, Spelt, Wheat,
}
fn main() {
let mut grains: Vec<Cereal> = vec![]; ③
grains.push(Cereal::Rye); ④
drop(grains); ⑤
println!("{:?}", grains); ⑥
}
$ cargo run
Compiling ch1-cereals v0.1.0 (/rust-in-action/code/ch1/ch1-cereals)
error[E0382]: borrow of moved value: `grains`
--> src/main.rs:12:22
|
8 | let mut grains: Vec<Cereal> = vec![];
// following line needs a line break (76 char max)
| ---------- move occurs because `grains` has type
`std::vec::Vec<Cereal>`,
which does not implement the `Copy` trait
9 | grains.push(Cereal::Rye);
10 | drop(grains);
| ------ value moved here
11 |
12 | println!("{:?}", grains);
| ^^^^^^ value borrowed here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ch1-cereals`.
Listing 1.6 shows an example of a data race condition. If you
remember, this condition results from the inability to determine how
a program behaves from run to run due to external factors changing.
You’ll find this code in the ch1/ch1-race/src/main.rs file.
use std::thread; ①
fn main() {
let mut data = 100;
println!("{}", data);
}
If you are unfamiliar with the term “thread,” the upshot is that this
code is not deterministic. It’s impossible to know what data will be
like when main() exits. In the listing, the closure for thread::spawn()
is denoted by vertical bars and curly braces (e.g., || {…}), limiting
the returned data calls to 500 and 1,000, respectively.
... ①
fn main() {
let fruit = vec!['🥝', '🍌', '🍇'];
let buffer_overflow = fruit[4]; ①
assert_eq!(buffer_overflow, '🍉') ②
}
// added extra line spaces above for longish annotations
$ cargo run
Compiling ch1-fruit v0.1.0 (/rust-in-action/code/ch1/ch1-fruit)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/ch1-fruit`
// the following two lines need line breaks (76 char max per line)
thread 'main' panicked at 'index out of bounds: the len is 3 but the index
is 4',
src/main.rs:3:25
note: run with `RUST_BACKTRACE=1` environment variable to display a
backtrace
fn main() {
let mut letters = vec![ ①
"a", "b", "b"
];
Listing 1.8 fails to compile because Rust will not allow letters to be
modified within the iteration block. Here’s the error message:
$ cargo run
Compiling ch1-letters v0.1.0 (/rust-in-action/code/ch1/ch1-letters)
error[E0382]: borrow of moved value: `letters`
--> src/main.rs:8:7
|
2 | let mut letters = vec![
// add line break below (76 char max)
| ----------- move occurs because `letters` has type
`std::vec::Vec<&str>`,
which does not implement the `Copy` trait
...
6 | for letter in letters {
| -------
| |
| value moved here
// add line breaks below (55 char max for line with <1>)
| help: consider borrowing to avoid moving into the for
loop:
`&letters` ①
7 | println!("{}", letter);
8 | letters.push(letter.clone());
| ^^^^^^^ value borrowed here after move
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ch1-letters`.
fn main() {
let a = 10;
if a = 10 {
println!("a equals ten");
}
}
In Rust, the preceding code would fail to compile. The Rust compiler
generates the following message:
error[E0308]: mismatched types
--> src/main.rs:4:8
|
4 | if a = 10 {
| ^^^^^^
| |
| expected `bool`, found `()`
| help: try comparing for equality: `a == 10`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.
fn main() {
let a = 10;
if a == 10 { ①
println!("a equals ten");
}
}
The following code snippet prints the line a: 10, b: 20, c: 30, d:
Mutex { data: 40 }. Each representation is another way to store an
integer. As we progress through the next few chapters, the trade-
offs related to each level become apparent. For the moment, the
important thing to remember is that the menu is comprehensive.
You are welcome to choose exactly what’s right for your specific use
case.
use std::rc::Rc;
use std::sync::{Arc, Mutex};
fn main() {
let a = 10; ①
let b = Box::new(20); ②
let c = Rc::new(Box::new(30)); ③
let d = Arc::new(Mutex::new(40)); ④
[13] See the articles “We need a safer systems programming language,”
https://msrc-blog.microsoft.com/2019/07/18/we-need-a-safer-systems-
programming-language/ and “Memory safety,”
https://www.chromium.org/Home/chromium-security/memory-safety for more
information.
[14] The name "`unit” reveals some of Rust’s heritage as a descendant of the ML
family of programming languages. Theoretically, a unit type only has a single
value, itself. Compare this with Boolean types that have two values, truth or
falsehood.
[15] If these terms are unfamiliar, do keep reading. These are explained
throughout the book.
Performance
Concurrency
Memory efficiency
1.7.1 Performance
Rust offers you all of your computer’s available performance.
Famously, Rust does not rely on a garbage collector to provide its
memory safety.
1.7.2 Concurrency
Asking a computer to do more than one thing at the same time has
proven difficult for software engineers. As far as an operating system
is concerned, two independent threads of execution are at liberty to
destroy each other if a programmer makes a serious mistake. Yet
Rust has spawned the saying “fearless concurrency.” Its emphasis on
safety crosses the bounds of independent threads. There is no global
interpreter lock (GIL) to constrain a thread’s speed. We explore
some of the implications of this in part 2.
These slogans (sometimes overstated) are great. But for all of its
merits, Rust does have some disadvantages.
1.8.1 Cyclic data structures
It is difficult to model cyclic data like an arbitrary graph structure in
Rust. Implementing a doubly-linked list is an undergraduate-level
computer science problem. Yet Rust’s safety checks do hamper
progress here. If you’re learning the language, avoid implementing
these sorts of data structures until you’re more familiar with Rust.
1.8.3 Strictness
It’s impossible—well, difficult—to be lazy when programming with
Rust. Programs won’t compile until everything is just right. The
compiler is strict, but helpful.
Over time, it’s likely that you’ll come to appreciate this feature. If
you’ve ever programmed in a dynamic language, then you may have
encountered the frustration of your program crashing because of a
misnamed variable. Rust brings that frustration forward so that your
users don’t have to experience the frustration of things crashing.
1.8.4 Size of the language
The language is large! It has a complex type system with multiple
ways to gain access to values and an ownership system that is
paired with enforced object lifetimes. The following snippet, shown
before as listing 1.9, probably causes a degree of anxiety. It’s fairly
overwhelming.
use std::rc::Rc;
use std::sync::{Arc, Mutex};
fn main() {
let a = 10; ①
let b = Box::new(20); ②
let c = Rc::new(Box::new(30)); ③
let d = Arc::new(Mutex::new(40)); ④
HEARTBLEED
Heartbleed was caused by re-using a buffer incorrectly. A buffer is a
space set aside in memory for receiving input. Data can leak from
one read to the next if the buffer’s contents are not cleared between
writes.
read_secrets(&user1, buffer); ②
store_secrets(buffer);
read_secrets(&user2, buffer); ③
store_secrets(buffer);
Rust does not protect you from logical errors. Rust ensures that your
data is never able to be written in two places at the same time. It
does not ensure that your program is free from all security issues.
GOTO FAIL
The “goto fail” bug is caused by programmer error coupled with C
design issues (and potentially its compiler for not pointing out the
flaw). A function that was designed to verify a cryptographic key pair
ended up skipping all checks. Here is a selected extract from the
function with a fair amount of obfuscatory syntax retained:
static OSStatus
// line break OK below? original exceeded 76 char limit
SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa,
SSLBuffer signedParams,
uint8_t *signature, UInt16 signatureLen)
{
OSStatus err; ①
...
// need line break below at 55 char max (because line contains annotation)
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) ②
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail; ③
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;
err = sslRawVerify(ctx,
ctx->peerPubKey,
dataToSign, /* plaintext \*/
dataToSignLen, /* plaintext length \*/
signature,
signatureLen);
if(err) {
sslErrorLog("SSLDecodeSignedServerKeyExchange: sslRawVerify "
"returned %d\n", (int)err);
goto fail;
}
fail:
SSLFreeBuffer(&signedHashes);
SSLFreeBuffer(&hashCtx);
return err; ④
In the example code, the issue lies between lines 12 and 14. In C,
logical tests do not require curly braces. C compilers interpret those
three lines like this:
Tip
Code with caution.
The man who had charge of the prison at Andersonville, and who
was responsible for the barbarities practiced there, more than any
other man, was Gen. John H. Winder.
I had not the honor(?) of a personal acquaintance with that fiend in
human shape, but Comrade John McElroy of the 16 Illinois Cavalry,
the author of “Andersonville,” gives his readers a description of the
man. I quote from that work.
“There rode in among us, a few days after our arrival, an old man
whose collar bore the wreathed stars of a Major General. Heavy
white locks fell from beneath his slouched hat, nearly to shoulders.
Sunken gray eyes too dull and cold to light up, marked a hard,
stony face, the salient features of which was a thin lipped,
compressed mouth, with corners drawn down deeply—the mouth
which seems the world over to be the index of selfish, cruel, sulky
malignance. It is such a mouth as has the school boy—the coward
of the play ground, who delights in pulling off the wings of flies. It
is such a mouth as we can imagine some remorseless inquisitor to
have had—that is, not an inquisitor filled with holy zeal for what he
mistakenly thought the cause of Christ demanded, but a spleeny,
envious, rancorous shaveling, who tortured men from hatred of
their superiority to him, and sheer love of inflicting pain.
The rider was John H. Winder, Commissary General of Prisoners,
Baltimorean renegade and the malign genius to whose account
should be charged the deaths of more gallant men than the
inquisitors of the world ever slew by the less dreadful rack and
wheel. It was he who in August could point to three thousand and
eighty-one new made graves for that month, and exultingly tell his
hearer that he was “doing more for the Confederacy than twenty
regiments.”
His lineage was in accordance with his character. His father was
that General William H. Winder, whose poltroonery at Bladensburg,
in 1814 nullified the resistance of the gallant Commodore Barney,
and gave Washington to the British.
The father was a coward and incompetent; the son, always
cautiously distant from the scene of hostilities, was the tormentor
of those whom fortunes of war and the arms of brave men threw
into his hands.“
Of his personal appearance I have no recollection, but the above is a
true picture of his character. He filled a place in the Confederacy
which no brave officer of equal rank would have accepted. Hill,
Longstreet, Early, Polk, Hardee, even Forrest and Mosby would have
spurned with contempt an offer of assignment to the position
occupied by the cowardly John H. Winder.
Of Captain Henry Wirz I can write of my own knowledge. In personal
appearance he was about five feet nine or ten inches in height,
slightly built with stooping shoulders. He had a small peaked head,
small twinkling eyes, grisly, frowsy whiskers, and the general contour
of his features and expression of eyes reminded one of a rodent.
In character he was pusillanimous, vindictive, mean and irritable to
those beneath him, or who had the misfortune to be in his power;
while to his superiors he was humble and cringing, an Uriah Heep; a
person who would “Crook the pregnant hinges of his knee, that thrift
might follow fawning.”
As a specimen of the contemptible meanness of these two persons, I
was told by a prisoner who attempted to escape, but was recaptured
and put in the stocks, that while at their head-quarters he saw a
large dry-goods box nearly full of letters written by prisoners to their
friends; and by friends to them, which had accumulated, and which
they had neglected to forward or distribute. The paper upon which
some of these letters was written, and the envelope in which it was
enclosed had cost the prisoner, perhaps, his last cent of money, or
mouthful of food. The failure to receive those letters had deprived
many a mother or wife of the last chance to hear from a loved one,
or a prisoner of his last chance to hear from those he loved more
than life itself.
Wirz was Commandant of the inner prison and in this capacity, had
charge of calling the roll, organization of prisoners, issuing rations,
the sanitary condition of the prison, the punishment of prisoners; in
fact the complete control of the inner prison.
Winder had control of all the guards, could control the amount of
rations to be issued, make the rules and regulations of the prison,
and had, in fact, complete control of the whole economy of the
prison; all men and officers connected therewith being subordinate
to him.
Wirz’ favorite punishment for infringement of prison rules, was the
chain-gang, and stocks. Sometimes twelve or fifteen men were
fastened together by shackles attached to a long chain. These
unfortunate men were left to broil in a semi-tropical sun, or left to
shiver in the dews and pelting rains, without shelter as long as Wirz’
caprice or malignity lasted. The stocks were usually for punishment
of the more flagrant offenses, or when Wirz was in his worst humor.
Just below my tent, two members of a New York regiment put up a
little shelter. They always lay in their tent during the day, but at
night one might see a few men marching away from their “shack”
carrying haversacks full of dirt, and emptying them along the edge
of the swamp. One morning the tent was gone, and a hole in the
ground marked the spot, and told the tale of their route, which was
underground through a tunnel. About 8 o’clock in the morning Wirz
came in accompanied by a squad of soldiers, and a gang of negroes
armed with shovels, who began to dig up the tunnel. I went to Wirz
and asked him what was up. He was always ready to “blow” when
he thought he could scare anybody, so he replied, “By Gott, tem
tamned Yanks has got oudt alrety, but nefer mints, I prings tem pack
all derights; I haf sent te ploothounts after dem. I tell you vat I
does, I gifs any Yank swoluf hours de shtart, undt oaf he gits avay,
all deright; put oaf I catches him I gif him hell.” Some one offered to
take the chances. “Allderights.” said he, “you come to de nort cate in
der mornick undt I lets you co.”
The next day we heard that the blood-hounds had found the trail of
the escaped prisoners, but that all but one had been foiled by
cayenne pepper, and that one, was found dead with a bullet hole in
his head. We never heard from our New York friends and infer that
that they got to “God’s Country.”
Many attempts were made to tunnel out that summer, but so far as I
know that was the only successful one. All sorts of ways were
resorted to, the favorite way being to start a well and dig down ten
or twelve feet, then start a tunnel in it near the surface of the
ground. By this means the fresh dirt would be accounted for, as well
digging was within the limits of the prison rules. But before the
“gopher-hole,” as the tunnels were called by the western boys, was
far advanced, a gang of negroes appeared upon the scene and dug
it up. We always believed there were spies among us. Some thought
the spies were some of our own men who were playing traitor to
curry favor with Wirz. Others believed Wirz kept rebel spies among
us. I incline to the former opinion.
Among those who were suspected was a one-legged soldier named
Hubbard. He hailed from Chicago and was a perfect pest. He was
quarrelsome and impudent and would say things that a sound man
would have got a broken head for saying. His squawking querulous
tones, and hooked nose secured for him the name of “Poll Parrott.”
He was a sort of privileged character, being allowed to go outside,
which caused many to believe he was in league with Wirz, though I
believe there was no direct proof of it. One day he came to where I
was cooking my grub and wanted me to take him in. He said all his
comrades were down on him and called him a spy, and he could not
stand it with them. As a further inducement he said he could go out
when he had a mind, and get wood and extra rations, which he
would divide with me. I consulted my “pard” and we agreed to take
him in. He then asked me to cook him some dinner, and gave me his
frying-pan and some meat. While I was cooking his dinner he
commenced finding fault with me, upon which I suggested that he
had better do his own cooking. He then showered upon my devoted
head some of the choicest epithets found in the Billingsgate dialect,
he raved and swore like a mad-man. I was pretty good natured
naturally, and besides I pitied the poor unfortunate fellow, but this
presuming on my good nature a little too much, I fired his frying-pan
at his head and told him to “get”; and he “got.”
Two days afterwards he went under the Dead-line and began to
abuse the guard, a member of an Alabama regiment, who ordered
him to go back, or he would shoot him. “Poll” then opened on the
guard in about the same style as he had on me, winding up by
daring the guard to fire. This was too much and the guard fired a
plunging shot, the ball striking him in the chin and passing down into
his body, killing him instantly.
A few days before this, a “fresh fish,” or “tender foot,” as the cow
boys would call him nowadays, started to cross the swamp south of
my tent. In one place in the softest part of the swamp the railing
which composed the Dead-line was gone, this man stepped over
where the line should have been, and the guard fired at him but he
fired too high and missed his mark, but the bullet struck an Ohio
man who was sitting in front of a tent near mine. He was badly, but
not fatally wounded, but died in a few days from the effects of
gangrene in his wound.
The author of “Andersonville” makes a wide distinction between the
members of the 29th Alabama and the 55th Georgia regiments,
which guarded us, in relation to treatment of prisoners, claiming that
Alabama troops were more humane than the Georgia “crackers.”
This was undoubtedly true in this instance, but I am of the opinion
that state lines had nothing to do with the matter.
The 29th Alabama was an old regiment and had been to the front
and seen war, had fired at Yankees, and had been fired at by
Yankees in return; they had no need to shoot defenseless prisoners
in order to establish the enviable reputation of having killed a
“damned Yank;” while the 55th Georgia was a new regiment, or at
least one which had not faced the music of bullets and shells on the
field of battle, they had a reputation to make yet, and they made
one as guards at Andersonville, but the devil himself would not be
proud of it, while the 5th Georgia Home Guards, another regiment of
guards, was worse than the 55th.
In making up the 5th Geo. H. G. the officers had “robbed the cradle
and the grave,” as one of my comrades facetiously remarked.
Old men with long white locks and beards, with palsied, trembling
limbs, vied with boys, who could not look into the muzzles of their
guns when they stood on the ground, who were just out of the
sugar pap and swaddling clothes period of their existence, in killing a
Yank. It was currently reported that they received a thirty days
furlough for every prisoner they shot; besides the distinguished
“honah.”
In marked contrast with these two Georgia regiments was the 5th
Georgia regulars. This regiment guarded us at Charleston, S. C., the
following September, and during our three weeks stay at that place I
have no recollection of the guards firing on us, although we were
camped in an open field with nothing to prevent our escape but
sickness, starvation, and a thin line of guards of the 5th Ga.
regulars. But this regiment too had seen service at the front. They
had been on the Perryville Campaign, had stood opposed to my
regiment at the battle of Perryville and had received the
concentrated volleys of Simonson’s battery and the 10th Wisconsin
Infantry, and in return had placed 146 of my comrades HORS DE
COMBAT. They had fought at Murfresboro and Chickamauga, at
Lookout and Missionary Ridge and had seen grim visaged war in
front of Sherman’s steadily advancing columns in the Atlanta
campaign. Surely they had secured a record without needlessly
shooting helpless prisoners.
I believe all ex-prisoners will agree with me, that FIGHTING regiments
furnished humane guards.
For the purpose of tracking escaped prisoners, an aggregate of
seventy blood-hounds were kept at Andersonville. They were run in
packs of five or six, unless a number of prisoners had escaped, in
which case a larger number were used. They were in charge of a
genuine “nigger driver” whose delight it was to follow their loud
baying, as they tracked fugitive negroes, or escaped Yanks through
the forests and swamps of southern Georgia.
These blood-hounds were trained to track human beings, and with
their keen scent they held to the track as steadily, relentlessly as
death itself; and woe betide the fugitive when overtaken, they tore
and lacerated him with the blood-thirsty fierceness of a Numidian
lion.
These willing beasts and more willing guards were efficient factors in
the hands of Winder and Wirz in keeping in subjection the prisoners
entrusted to their care. But these are outside forces. Within the
wooden walls of that prison were more subtile and enervating forces
at work than Georgia militia or fierce blood-hound.
Diarrhea, scurvy and its concomitant, gangrene, the result of
insufficient and unsuitable food and the crowded and filthy state of
the prison, were doing their deadly work, swiftly, surely and
relentlessly.
CHAPTER VIII.
The cook-house, which I have already spoken of, had a capacity for
cooking rations for 10,000 men. Our rations consisted, during the
latter part of April and through May, of about a pound of corn bread,
of about the same quality as that at Danville, a piece of meat about
the size of two fingers, and a little salt per day. This was varied by
issuing rice or cow peas in the place of meat, but meat and rice, or
peas, were never issued together. We had no more bug soup, nor
soup of any kind from the cook-house. We got our bugs in the peas,
so that we were not entirely destitute of meat when we had peas.
The rice was filled with weevil, so that that too, was stronger, if not
more nutritious. But when our numbers were increased by the
prisoners who had been captured at Dalton, Resaca, Alatoona, New
Hope Church and Kenesaw, from Sherman’s army, and from the
Wilderness, from Meade’s army, our numbers had far outgrown the
capacity of the cook-house and our rations were issued to us raw.
Then commenced real, downright misery and suffering. These men
were turned into the prison after being robbed of everything of
value, without shelter, without cooking utensils, without wood,
except in the most meager quantities, and in most cases without
blankets.
Raw meal, raw rice and peas, and no dish to cook them in, and no
wood to cook them with, and yet there were thousands of acres of
timber in sight of the prison, and these men would have been too
glad to cut their own wood and bring it into the prison on their
shoulders. But this would have been a luxury, and Winder did not
furnish prisoners with luxuries. There was an abortive attempt made
at cooking more rations, by cooking them less, and the result was,
meal simply scalded and called “mush,” and rice not half cooked,
and burned black wherever it touched the kettle it was boiled in.
The effects of this unwholesome, half cooked, and in thousands of
cases raw diet, was an increase of diarrhea, and dysentery, and
scurvy.
In thousands of cases of scurvy where scorbutic ulcers had broken
out, gangrene supervened and the poor prisoner soon found
surcease of pain, and misery, and starvation, in the grave.
Amputation of a limb was not a cure for these cases; new scorbutic
ulcers appeared, again gangrene supervened, and death was the
almost inevitable result.
The prison was filled with sick and dying men, indeed well men were
the exception, and sick men the rule. The hospital was filled to
overflowing; the prison itself, was a vast hospital, with no physicians,
and no nurses.
Thousands of men had become too sick and weak to go to the sinks
to stool, and they voided their excrement in little holes dug near
their tents. The result of this was, a prison covered with maggots,
and the air so polluted with the foul stench, that it created an
artificial atmosphere, which excluded malaria, and in a country
peculiarly adapted to malarial diseases, there were no cases of
Malarial, Typhus or Typhoid fevers.
Your true Yankee is an ingenious fellow, and is always trying to
better his situation. Many cooking dishes were manufactured by the
prisoners out of tin cans, pieces of sheet iron, or car roofing, which
had been picked up on the road to prison.
Knives and spoons were made from pieces of hoop iron, and a
superannuated oyster or fruit can, was a whole cooking
establishment, while a tin pail or coffee pot caused its owner to be
looked upon as a nabob.
Fortunately for myself I was joint owner with six men of my
company, of a six quart tin pail. This we loaned at times to the more
unfortunate, thus helping them somewhat in their misery. Besides
this mine of wealth, I had an interest in the wooden bucket
purloined from the Danville prison, and as Sergeant of the mess, it
was in my care. To this bucket I owe, in a great measure, my life;
for I used it for a bath tub during my confinement in Andersonville.
Another cause of suffering was the extreme scarcity of water. When
the Richmond and Belle Isle prisoners arrived in Andersonville in
February and March, they had procured their water from Dead-run;
but by the time our squad arrived this little stream had become so
polluted that it was not fit for the wallowing place of a hog.
Our first work after building a shelter was to procure water. We first
dug a hole in the edge of the swamp, but this soon became too
warm and filthy for use, so we started a well in an open space in
front of my tent, and close to the Dead-line. We found water at a
depth of six feet, but it was in quicksand and we thought our well
was a failure; but again luck was on our side. One of the prisoners
near us, had got hold of a piece of board while marching from the
cars to the prison, this he offered to give us in exchange for stock in
our well.
We completed the bargain, and with our Danville sawknife cut up
the board into water-curbing, which we sank into the quicksand,
thus completing a well which furnished more water than any well in
the whole prison.
To the credit of my mess, who owned all the right, title and interest,
in and to this well, I will say, we never turned a man away thirsty.
After we had supplied ourselves, we gave all the water the well
would furnish to the more unfortunate prisoners who lived on the
hill, and who could procure no water elsewhere.
After we had demonstrated the fact that clean water could be
procured even in Andersonville, a perfect mania for well digging
prevailed in prison; wells were started all over, but the most of them
proved failures for different reasons, some were discouraged at the
great depth, others had no boards for water-curbing, and their wells
caved in, and were a failure. There were, however, some wells dug
on the hill, to a depth of thirty or forty feet. They furnished water of
a good quality, but the quantity was very limited.
The digging of these deep wells was proof of the ingenuity and
daring of the prisoners. The only digging tool was a half canteen,
procured by unsoldering a canteen. The dirt was drawn up in a
haversack, or bucket, attached to a rope twisted out of rags, from
the lining of coat sleeves or strips of shelter tents. The well diggers
were lowered into, and drawn out of, the wells by means of these
slight, rotten ropes, and yet, I never heard of an accident as a result
of this work.
But the wells were not capable of supplying one-fourth of the men
with water. Those who had no interest in a well, and could not beg
water from those who had, were compelled to go to Dead-run for a
supply.
A bridge crossed this stream on the west side of the prison, and
here the water was not quite so filthy as farther down stream. This
bridge was the slaughter pen of the 55th Georgians, and the 5th
Georgia Home Guards.
Here the prisoners would reach under the Dead-line to procure clean
water, and the crack of a Georgian’s musket, was the prisoner’s
death knell.
During the early part of August Providence furnished what Winder
and Wirz refused to furnish. After a terrible rain storm, a spring
broke out under the walls of the stockade about ten or fifteen rods
north of this bridge. Boards were furnished, out of which a trough
was made which carried the water into the prison. The water was of
good quality, and of sufficient quantity to have supplied the
prisoners, could it have been saved by means of a tank or reservoir.
This was the historical “Providence Spring” known and worshiped by
all ex-Andersonville prisoners.
The same rain storm which caused Providence Spring to break out,
gullied and washed out the ground between our well and the
stockade to a depth of four feet, and so saturated the ground that
the well caved in. We were a sad squad of men, as we gathered
around the hole where our hopes of life were buried, for without
pure water, we knew we could not survive long in Andersonville.
Two days after the accident to our well, we held a legislative session,
and resolved ourselves into a committee of the whole, on ways and
means to restore our treasure. No one could think of any way to fix
up the well, boards were out of the question, stones there were
none, and barrels:—we had not seen a barrel since we left “God’s
Country.” As chairman, ex-officio, of the committee, I proposed that
we steal a board from the Dead-line. This was voted down by the
committee as soon as proposed, the principle was all right, but the
risk was too great; death would be the penalty for the act. The
committee then rose and the session was adjourned. After
considering the matter for a time, I resolved to steal a board from
the Dead-line at any risk. I then proceeded to mature a plan which I
soon put into execution. One of my “pards,” Rouse, had a good silver
watch, I told him to go up to the Dead-line in front of the first guard
north of our tent, and show his watch, and talk watch trade with the
guard. I sent Ole Gilbert, my other pard, to the first guard south,
with the same instructions, but minus a watch. I kept my eyes on
the guards and watched results; soon I saw that my plan was
working. I picked up a stick of wood and going to a post of the
Dead-line, where one end of a board was nailed, I pried off the end
of the board, but O horror! how it squealed, it was fastened to a
pitch pine post with a twelve penny nail and when I pried it loose, it
squeaked like a horse fiddle at a charivari party. I made a sudden
dive for my tent, which was about sixteen feet away, and when I
had got under cover I looked out to see the result. The guards were
peering around to see what was up, their quick ears had caught the
sound, but their dull brain could not account for the cause.
After waiting until the guards had become again interested in the
mercantile transaction under consideration, I crawled out of my tent
and as stealthily as a panther crawled to my board again. This time I
caught it at the loose end, and with one mighty effort I wrenched it
from the remaining posts, dropped it on the ground, and again dove
into my tent.
The guards were aroused, but not soon enough to see what had
been done, and I had secured a board twenty feet long by four
inches wide, lumber enough to curb our well.
Another meeting of the mess was held, the saw-knife was brought
out, the board, after great labor, was sawed up, and our well was
restored to its usefulness.
This same storm, which occurred on the 12th of August, was the
cause of a quite an episode in our otherwise dull life in prison. It was
one of those terrible rains which occur sometimes in that region, and
had the appearance of a cloud-burst. The rain fell in sheets, the
ground in the prison was completely washed, and much good was
done in the way of purifying this foul hole. The rapid rush of water
down the opposing hills, filled the little stream, which I have called
Dead-run, to overflowing, and as there was not sufficient outlet
through the stockade, for the fast accumulating water, the pressure
became so great that about twenty feet of the stockade toppled and
fell over.
Thousands of prisoners were out looking at the downfall of our
prison walls and when it went over we sent up such a shout and
hurrah that we made old Andersonville ring.
But the rebel guard had witnessed the break as well as we. The
guard near the creek called out “copeler of the gyaad! post numbah
fo’teen! hurry up, the stockade is goin to h—l.” The guards, about
3,000 in number, came hurrying to the scene and formed line of
battle to prevent a rush of prisoners, while the cannoneers in the
forts sprang to their guns. We saw them ram home the charges in
their guns, then we gave another shout, when BANG went one of the
guns from the south-western fort, and we heard a solid shot go
shrieking over our heads. It began to look as though the Johnies
were going to get the most fun out of this thing after all. Just at this
time Wirz came up to the gap and shrieked, “co pack to your
quarters, you tammed Yanks, or I vill open de cuns of de forts on
you.”
I needed no second invitation after that shot went over our heads,
and I hurried to my quarters and laid low. I don’t think I am
naturally more cowardly than the average of men, but that shot
made me tired. I was sick and weak and had no courage, and knew
Winder and Wirz so well that I had perfect faith that they would be
only too glad of an excuse to carry out the threat.
But let us go back to the month of May. Soon after my arrival, there
was marched into the prison about two thousand of the finest
dressed soldiers I ever saw. Their uniforms were new and of a better
quality than we had ever seen in the western army. They wore on
their heads cocked hats, with brass and feather accompaniments.
Their feet were shod with the best boots and shoes we had seen
since antebellum days, their shirts were of the best “lady’s cloth”
variety, and the chevrons on the sleeves of the non-commissioned
officers coats, were showy enough for members of the Queen’s
Guards.
Poor fellows, how I pitied them. The mingled look of surprise, horror,
disgust, and sorrow that was depicted on their faces as they
marched between crowds of prisoners who had been unwilling
guests of the Confederacy for, from four to nine months, told but too
plainly how our appearance affected them. As they passed along the
mass of ragged, ghastly, dirt begrimed prisoners, I could hear the
remark, “My God! have I got to come to this?” “I can’t live here a
month,” “I had rather die, than to live in such a place as this,” and
similar expressions. I say that I pitied them, for I knew that the sight
of such specimens of humanity as we were, had completely
unnerved them, that their blood had been chilled with horror at sight
of us, and that they would never recover from the shock; and they
never did.
Yes they had to come to this; many of them did not live a month,
and not many of those two thousand fine looking men ever lived to
see “God’s Country” again.
These were the “Plymouth Pilgrims.” They were a brigade, composed
of the 85th New York, the 101st and 103d Pennsylvania, 16th
Connecticut, 24th New York Battery, two companies of
Massachusetts heavy artillery and a company of the 12th New York
cavalry.
They were the garrison of a fort at Plymouth, North Carolina, which
had been compelled to surrender, on account of the combined attack
of land and naval forces, on the 20th day of May, 1864.
Some of the regiments composing this band of Pilgrims had
“veteranized” and were soon going home on a veteran furlough
when the attack was made, but they came to Andersonville instead.
Their service had been most entirely in garrisons, where they had
always been well supplied with rations and clothing, and exempt
from hard marches and exposures, and as a natural sequence, were
not as well fitted to endure the hardships of prison life, as soldiers
who had seen more active service.
They were turned into the prison without shelter, and they did not
seem to think they could, in any way, provide one; without cooking
utensils, and they thought they must eat their food raw. They began
to die off in a few days after their arrival, they seemed never to have
recovered from their first shock.
Comrade McElroy tells in “Andersonville,” a pathetic story of a
Pennsylvanian who went crazy from the effects of confinement. He
had a picture of his wife and children and he used to sit hour after
hour looking at them, and sometimes imagined he was with them
serving them at the home table. He would, in his imagination, pass
food to wife and children, calling each by name, and urging them to
eat more. He died in a month after his entrance.
I observed a similar case near my quarters. One of this same band
came to our well for a drink of water which we gave him. He was
well dressed, at first, but seemed to be a simple-minded man. Day
after day he came for water, sometimes many times a day. Soon he
began to talk incoherently, then to mutter something about home
and food. One day his hat was gone; the next day his boots were
missing, and so on, day after day, until he was perfectly nude,
wandering about in the hot sun, by day, and shivering in the cold
dews at night, until at last we found him one morning lying in a ditch
at the edge of the swamp,—dead.
God only knows how many of those poor fellows were chilled in
heart and brain, at their first introduction to Andersonville.
The coming of the Pilgrims into prison was the beginning of a new
era in its history. Before they came, there was no money among the
prisoners, or so little as to amount to nothing; but at the time of
their surrender they had been paid off, and those who had
“veteranized” had been paid a veteran bounty, so that they brought
a large sum of money into prison.
The reader may inquire how it was that they were not searched, and
their money and valuables taken from them by Winder and Wirz? It
is a natural inquiry, as it was the only instance in the record of
Andersonville, so far as I ever heard, when such rich plunder
escaped those commissioned robbers. The reason they escaped
robbery of all their money, clothing, blankets and good boots and
shoes, was, they had surrendered with the agreement that they
should be allowed to keep all their personal belongings, and in this
instance the Confederate authorities had kept their agreement.
Thus several thousand dollars were brought into prison, and the old
prisoners were eager to get a share. All sorts of gambling devices
were used, the favorite being the old army Chuc-a-luck board. When
these men came in, the old prisoners had preempted all the vacant
land adjoining their quarters, and they sold their right to it, to these
tender-feet for large sums, for the purpose of putting up shelters on.
This they had no right to do, but the Pilgrims did not know it.
As the money began to circulate, trade began to flourish. Sutler, and
soup stands sprung up all over the prison, where vegetables and
soup were sold at rates that would seem exorbitant in any other
place than the Confederacy. The result of all this gambling and
trading, together with another cause which I will mention, was, that
the Pilgrims were soon relieved of all their money, and then began to
trade their clothing. Thus these well supplied, well dressed prisoners
were soon reduced to a level with the older prisoners; but there was
a compensation in this, as well as in nature, for what the former lost
the latter gained and they were the better off by that much.
The supplies of vegetables and food which were sold by the sutlers
and restaurateurs, were procured of the guards at the gate, they
purchasing of the “Crackers” in the vicinity, causing a lively trade to
flourish, not only in prison, but with the surrounding country.
CHAPTER IX.
THE RAIDERS.
“There must be government in all society—
Bees have their Queen, and stag herds have their leader;
Rome had her Consuls, Athens had her Archons,
And we, sir, have our Managing Committee.”
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com