0% found this document useful (0 votes)
8 views65 pages

75498

The document provides information about various eBooks available for download at ebookmeta.com, including titles related to Linux debugging, ARM64, history, and more. It features works by authors such as Dmitry Vostokov and Benjamin Harrison, along with links to access these eBooks. Additionally, it includes details about the contents and structure of the book 'Foundations of Linux Debugging, Disassembling, and Reversing' by Dmitry Vostokov.

Uploaded by

vijewaifai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views65 pages

75498

The document provides information about various eBooks available for download at ebookmeta.com, including titles related to Linux debugging, ARM64, history, and more. It features works by authors such as Dmitry Vostokov and Benjamin Harrison, along with links to access these eBooks. Additionally, it includes details about the contents and structure of the book 'Foundations of Linux Debugging, Disassembling, and Reversing' by Dmitry Vostokov.

Uploaded by

vijewaifai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Foundations of Linux Debugging, Disassembling, and


Reversing: Analyze Binary Code, Understand Stack
Memory Usage, and Reconstruct C/C++ Code with
Intel x64 1st Edition Dmitry Vostokov
https://ebookmeta.com/product/foundations-of-linux-
debugging-disassembling-and-reversing-analyze-binary-code-
understand-stack-memory-usage-and-reconstruct-c-c-code-with-
intel-x64-1st-edition-dmitry-vostokov/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Foundations of ARM64 Linux Debugging, Disassembling, and


Reversing: Analyze Code, Understand Stack Memory Usage,
and Reconstruct Original C/C++ Code with ARM64 1st Edition
Dmitry Vostokov
https://ebookmeta.com/product/foundations-of-arm64-linux-debugging-
disassembling-and-reversing-analyze-code-understand-stack-memory-
usage-and-reconstruct-original-c-c-code-with-arm64-1st-edition-dmitry-
vostokov/
ebookmeta.com

Cambridge IGCSE and O Level History Workbook 2C - Depth


Study: the United States, 1919-41 2nd Edition Benjamin
Harrison
https://ebookmeta.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-
benjamin-harrison/
ebookmeta.com

Accelerated Linux Core Dump Analysis Third Edition Dmitry


Vostokov

https://ebookmeta.com/product/accelerated-linux-core-dump-analysis-
third-edition-dmitry-vostokov/

ebookmeta.com

The Archive Project Archival Research in the Social


Sciences 1st Edition Niamh Moore

https://ebookmeta.com/product/the-archive-project-archival-research-
in-the-social-sciences-1st-edition-niamh-moore/

ebookmeta.com
The Silver Crown: An Alien Sci-Fi Harem Adventure (The
Makalang Book 8) 1st Edition Michael Dalton

https://ebookmeta.com/product/the-silver-crown-an-alien-sci-fi-harem-
adventure-the-makalang-book-8-1st-edition-michael-dalton-2/

ebookmeta.com

Love Unfu*ked 1st Edition Gary John Bishop

https://ebookmeta.com/product/love-unfuked-1st-edition-gary-john-
bishop/

ebookmeta.com

The Tundzha Regional Archaeology Project Surface Survey


Palaeoecology and Associated Studies in Central and
Southeast Bulgaria 2009 2015 Final Report Shawn A Ross
Editor Adela Sobotkova Editor Julia Tzvetkova Editor
https://ebookmeta.com/product/the-tundzha-regional-archaeology-
Georgi Nekhrizov Editor Simon Connor Editor
project-surface-survey-palaeoecology-and-associated-studies-in-
central-and-southeast-bulgaria-2009-2015-final-report-shawn-a-ross-
editor-adela-sobotkova-editor-julia-t/
ebookmeta.com

DEVELOPING HOSPITALITY PROPERTIES AND FACILITIES 3rd


Edition Developing Hospitality Properties And Facilities

https://ebookmeta.com/product/developing-hospitality-properties-and-
facilities-3rd-edition-developing-hospitality-properties-and-
facilities/
ebookmeta.com

Managerial Economics 12th Edition Christopher Thomas

https://ebookmeta.com/product/managerial-economics-12th-edition-
christopher-thomas/

ebookmeta.com
Special Delivery Friends to Lovers Love After Romance
Divorce Romance Forever Stamps Book 3 1st Edition Piper
Cook
https://ebookmeta.com/product/special-delivery-friends-to-lovers-love-
after-romance-divorce-romance-forever-stamps-book-3-1st-edition-piper-
cook/
ebookmeta.com
Foundations of Linux
Debugging, Disassembling,
and Reversing
Analyze Binary Code, Understand
Stack Memory Usage, and Reconstruct
C/C++ Code with Intel x64

Dmitry Vostokov
Foundations of Linux
Debugging,
Disassembling, and
Reversing
Analyze Binary Code,
Understand Stack Memory
Usage, and Reconstruct C/C++
Code with Intel x64

Dmitry Vostokov
Foundations of Linux Debugging, Disassembling, and Reversing: Analyze
Binary Code, Understand Stack Memory Usage, and Reconstruct C/C++
Code with Intel x64
Dmitry Vostokov
Dublin, Ireland

ISBN-13 (pbk): 978-1-4842-9152-8 ISBN-13 (electronic): 978-1-4842-9153-5


https://doi.org/10.1007/978-1-4842-9153-5

Copyright © 2023 by Dmitry Vostokov


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin Suresh John
Development Editor: James Markham
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image by Eugene Golovesov on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY
10004, U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected],
or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance
Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for
reprint, paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub (https://github.com/Apress). For more detailed information,
please visit http://www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author���������������������������������������������������������������������������������ix

About the Technical Reviewer�������������������������������������������������������������xi

Preface����������������������������������������������������������������������������������������������xiii

Chapter 1: Memory, Registers, and Simple Arithmetic�������������������������1


Memory and Registers Inside an Idealized Computer������������������������������������������1
Memory and Registers Inside Intel 64-Bit PC�������������������������������������������������������2
“Arithmetic” Project: Memory Layout and Registers��������������������������������������������3
“Arithmetic” Project: A Computer Program�����������������������������������������������������������5
“Arithmetic” Project: Assigning Numbers to Memory Locations���������������������������5
Assigning Numbers to Registers���������������������������������������������������������������������������8
“Arithmetic” Project: Adding Numbers to Memory Cells���������������������������������������8
Incrementing/Decrementing Numbers in Memory and Registers�����������������������11
Multiplying Numbers�������������������������������������������������������������������������������������������14
Summary������������������������������������������������������������������������������������������������������������17

Chapter 2: Code Optimization�������������������������������������������������������������19


“Arithmetic” Project: C/C++ Program�����������������������������������������������������������������19
Downloading GDB�����������������������������������������������������������������������������������������������20
GDB Disassembly Output – No Optimization�������������������������������������������������������20
GDB Disassembly Output – Optimization������������������������������������������������������������25
Summary������������������������������������������������������������������������������������������������������������26

iii
Table of Contents

Chapter 3: Number Representations��������������������������������������������������27


Numbers and Their Representations�������������������������������������������������������������������27
Decimal Representation (Base Ten)��������������������������������������������������������������������28
Ternary Representation (Base Three)������������������������������������������������������������������29
Binary Representation (Base Two)����������������������������������������������������������������������29
Hexadecimal Representation (Base Sixteen)������������������������������������������������������30
Why Are Hexadecimals Used?�����������������������������������������������������������������������������30
Summary������������������������������������������������������������������������������������������������������������32

Chapter 4: Pointers�����������������������������������������������������������������������������33
A Definition���������������������������������������������������������������������������������������������������������33
“Pointers” Project: Memory Layout and Registers����������������������������������������������34
“Pointers” Project: Calculations��������������������������������������������������������������������������36
Using Pointers to Assign Numbers to Memory Cells�������������������������������������������36
Adding Numbers Using Pointers�������������������������������������������������������������������������42
Incrementing Numbers Using Pointers���������������������������������������������������������������45
Multiplying Numbers Using Pointers�������������������������������������������������������������������48
Summary������������������������������������������������������������������������������������������������������������51

Chapter 5: Bytes, Words, Double, and Quad Words�����������������������������53


Using Hexadecimal Numbers������������������������������������������������������������������������������53
Byte Granularity��������������������������������������������������������������������������������������������������53
Bit Granularity�����������������������������������������������������������������������������������������������������54
Memory Layout���������������������������������������������������������������������������������������������������55
Summary������������������������������������������������������������������������������������������������������������58

Chapter 6: Pointers to Memory�����������������������������������������������������������59


Pointers Revisited�����������������������������������������������������������������������������������������������59
Addressing Types������������������������������������������������������������������������������������������������59

iv
Table of Contents

Registers Revisited���������������������������������������������������������������������������������������������65
NULL Pointers�����������������������������������������������������������������������������������������������������65
Invalid Pointers���������������������������������������������������������������������������������������������������65
Variables As Pointers������������������������������������������������������������������������������������������66
Pointer Initialization��������������������������������������������������������������������������������������������67
Initialized and Uninitialized Data�������������������������������������������������������������������������67
More Pseudo Notation�����������������������������������������������������������������������������������������68
“MemoryPointers” Project: Memory Layout�������������������������������������������������������68
Summary������������������������������������������������������������������������������������������������������������79

Chapter 7: Logical Instructions and RIP���������������������������������������������81


Instruction Format����������������������������������������������������������������������������������������������81
Logical Shift Instructions������������������������������������������������������������������������������������82
Logical Operations����������������������������������������������������������������������������������������������82
Zeroing Memory or Registers�����������������������������������������������������������������������������83
Instruction Pointer�����������������������������������������������������������������������������������������������84
Code Section�������������������������������������������������������������������������������������������������������85
Summary������������������������������������������������������������������������������������������������������������86

Chapter 8: Reconstructing a Program with Pointers��������������������������87


Example of Disassembly Output: No Optimization����������������������������������������������87
Reconstructing C/C++ Code: Part 1��������������������������������������������������������������������90
Reconstructing C/C++ Code: Part 2��������������������������������������������������������������������92
Reconstructing C/C++ Code: Part 3��������������������������������������������������������������������93
Reconstructing C/C++ Code: C/C++ Program����������������������������������������������������94
Example of Disassembly Output: Optimized Program�����������������������������������������95
Summary������������������������������������������������������������������������������������������������������������96

v
Table of Contents

Chapter 9: Memory and Stacks����������������������������������������������������������97


Stack: A Definition�����������������������������������������������������������������������������������������������97
Stack Implementation in Memory�����������������������������������������������������������������������98
Things to Remember�����������������������������������������������������������������������������������������100
PUSH Instruction�����������������������������������������������������������������������������������������������101
POP Instruction�������������������������������������������������������������������������������������������������101
Register Review������������������������������������������������������������������������������������������������102
Application Memory Simplified�������������������������������������������������������������������������105
Stack Overflow��������������������������������������������������������������������������������������������������105
Jumps���������������������������������������������������������������������������������������������������������������106
Calls������������������������������������������������������������������������������������������������������������������108
Call Stack����������������������������������������������������������������������������������������������������������110
Exploring Stack in GDB�������������������������������������������������������������������������������������112
Summary����������������������������������������������������������������������������������������������������������115

Chapter 10: Frame Pointer and Local Variables�������������������������������117


Stack Usage������������������������������������������������������������������������������������������������������117
Register Review������������������������������������������������������������������������������������������������118
Addressing Array Elements�������������������������������������������������������������������������������118
Stack Structure (No Function Parameters)�������������������������������������������������������119
Function Prolog�������������������������������������������������������������������������������������������������121
Raw Stack (No Local Variables and Function Parameters)�������������������������������121
Function Epilog�������������������������������������������������������������������������������������������������123
“Local Variables” Project����������������������������������������������������������������������������������124
Disassembly of Optimized Executable��������������������������������������������������������������127
Summary����������������������������������������������������������������������������������������������������������128

vi
Table of Contents

Chapter 11: Function Parameters�����������������������������������������������������129


“FunctionParameters” Project��������������������������������������������������������������������������129
Stack Structure�������������������������������������������������������������������������������������������������130
Function Prolog and Epilog�������������������������������������������������������������������������������132
Project Disassembled Code with Comments����������������������������������������������������133
Parameter Mismatch Problem��������������������������������������������������������������������������137
Summary����������������������������������������������������������������������������������������������������������138

Chapter 12: More Instructions����������������������������������������������������������139


CPU Flags Register��������������������������������������������������������������������������������������������139
The Fast Way to Fill Memory�����������������������������������������������������������������������������140
Testing for 0������������������������������������������������������������������������������������������������������141
TEST – Logical Compare�����������������������������������������������������������������������������������142
CMP – Compare Two Operands�������������������������������������������������������������������������143
TEST or CMP?���������������������������������������������������������������������������������������������������144
Conditional Jumps��������������������������������������������������������������������������������������������144
The Structure of Registers��������������������������������������������������������������������������������145
Function Return Value���������������������������������������������������������������������������������������146
Using Byte Registers�����������������������������������������������������������������������������������������146
Summary����������������������������������������������������������������������������������������������������������147

Chapter 13: Function Pointer Parameters����������������������������������������149


“FunctionPointerParameters” Project���������������������������������������������������������������149
Commented Disassembly���������������������������������������������������������������������������������150
Summary����������������������������������������������������������������������������������������������������������159

vii
Table of Contents

Chapter 14: Summary of Code Disassembly Patterns����������������������161


Function Prolog/Epilog��������������������������������������������������������������������������������������161
LEA (Load Effective Address)����������������������������������������������������������������������������164
Passing Parameters������������������������������������������������������������������������������������������164
Accessing Parameters and Local Variables������������������������������������������������������165
Summary����������������������������������������������������������������������������������������������������������166

Index�������������������������������������������������������������������������������������������������167

viii
About the Author
Dmitry Vostokov is an internationally
recognized expert, speaker, educator, scientist,
and author. He is the founder of the pattern-
oriented software diagnostics, forensics,
and prognostics discipline and Software
Diagnostics Institute (DA+TA: DumpAnalysis.
org + TraceAnalysis.org). Vostokov has also
authored more than 50 books on software
diagnostics, anomaly detection and analysis,
software and memory forensics, root cause analysis and problem solving,
memory dump analysis, debugging, software trace and log analysis,
reverse engineering, and malware analysis. He has more than 25 years
of experience in software architecture, design, development, and
maintenance in various industries, including leadership, technical, and
people management roles. Dmitry also founded Syndromatix, Anolog.
io, BriteTrace, DiaThings, Logtellect, OpenTask Iterative and Incremental
Publishing (OpenTask.com), Software Diagnostics Technology and
Services (former Memory Dump Analysis Services; PatternDiagnostics.
com), and Software Prognostics. In his spare time, he presents various
topics on Debugging TV and explores Software Narratology, its further
development as Narratology of Things and Diagnostics of Things (DoT),
and Software Pathology. His current areas of interest are theoretical
software diagnostics and its mathematical and computer science
foundations, application of artificial intelligence, machine learning and

ix
About the Author

data mining to diagnostics and anomaly detection, software diagnostics


engineering and diagnostics-driven development, and diagnostics
workflow and interaction. Recent areas of interest also include cloud
native computing, security, automation, functional programming, and
applications of category theory to software development and big data.

x
About the Technical Reviewer
Vikas Talan is a senior engineer at Qualcomm
(an American multinational corporation). He is
the founder of S.M.A.R.T Solutions, a technical
company. He also worked at MediaTek and
Cadence in core technical domains. He has
in-depth experience in Linux kernel
programming, Linux device drivers, ARM 64,
ARM, and porting of Android OS and Linux
drivers on chipsets. He hails from Delhi
NCR, India.

xi
Preface
The book covers topics ranging from Intel x64 assembly language
instructions and writing programs in assembly language to pointers, live
debugging, and static binary analysis of compiled C and C++ code.
Diagnostics of core memory dumps, live and postmortem debugging
of Linux applications, services, and systems, memory forensics, malware,
and vulnerability analysis require an understanding of x64 Intel assembly
language and how C and C++ compilers generate code, including
memory layout and pointers. This book is about background knowledge
and practical foundations that are needed to understand internal Linux
program structure and behavior, start working with the GDB debugger, and
use it for disassembly and reversing. It consists of practical step-by-step
exercises of increasing complexity with explanations and many diagrams,
including some necessary background topics.
By the end of the book, you will have a solid understanding of how
Linux C and C++ compilers generate binary code. In addition, you will be
able to analyze such code confidently, understand stack memory usage,
and reconstruct original C/C++ code.
The book will be useful for

• Software technical support and escalation engineers

• Software engineers coming from JVM background

• Software testers

• Engineers coming from non-Linux environments, for


example, Windows or Mac OS X

xiii
Preface

• Linux C/C++ software engineers without assembly


language background

• Security researchers without assembly language


background

• Beginners learning Linux software reverse engineering


techniques

This book can also be used as an x64 assembly language and Linux
debugging supplement for relevant undergraduate-level courses.

Source Code
All source code used in this book can be downloaded from github.com/
apress/linux-debugging-disassembling-reversing.

xiv
CHAPTER 1

Memory, Registers,
and Simple Arithmetic
 emory and Registers Inside
M
an Idealized Computer
Computer memory consists of a sequence of memory cells, and each cell
has a unique address (location). Every cell contains a “number.” We refer
to these “numbers” as contents at addresses (locations). Because memory
access is slower than arithmetic instructions, there are so-called registers
to speed up complex operations that require memory to store temporary
results. We can also think about them as stand-alone memory cells. The
name of a register is its address. Figure 1-1 illustrates this concept.

© Dmitry Vostokov 2023 1


D. Vostokov, Foundations of Linux Debugging, Disassembling, and Reversing,
https://doi.org/10.1007/978-1-4842-9153-5_1
Chapter 1 Memory, Registers, and Simple Arithmetic

Figure 1-1. Computer memory represented as a sequence of memory


cells and locations

 emory and Registers Inside Intel


M
64-Bit PC
Figure 1-2 shows addresses for memory locations containing integer
values usually differ by four or eight, and we also show two registers called
%RAX and %RDX. The first halves of them are called %EAX and %EDX.

2
Chapter 1 Memory, Registers, and Simple Arithmetic

Figure 1-2. Typical Intel x64 memory and register layout

Because memory cells contain “numbers,” we start with simple


arithmetic and ask a PC to compute the sum of two numbers to see how
memory and registers change their values.

“ Arithmetic” Project: Memory Layout


and Registers
For our project, we have two memory addresses (locations) that we call
“a” and “b.” We can think about “a” and “b” as names of their respective
addresses (locations). Now we introduce a special notation where (a) means

3
Chapter 1 Memory, Registers, and Simple Arithmetic

contents at the memory address (location) “a.” If we use the C or C++


language to write our project, we declare and define memory locations “a”
and “b” as

static int a, b;

By default, when we load a program, static memory locations are filled


with zeroes, and we can depict our initial memory layout after loading the
program, as shown in Figure 1-3.

Figure 1-3. Initial memory layout after loading the program

4
Chapter 1 Memory, Registers, and Simple Arithmetic

“Arithmetic” Project: A Computer Program


We can think of a computer program as a sequence of instructions for
the manipulation of contents of memory cells and registers. For example,
addition operation: add the contents of memory cell №12 to the contents
of memory cell №14. In our pseudo-code, we can write

(14) + (12) -> (14)

Our first program in pseudo-code is shown on the left of the table:

1 -> (a) Here, we put assembly instructions corresponding


1 -> (b) to pseudo-code.
(b) + (a) -> (b)
(a) + 1 -> (a)
(b) * (a) -> (b)

“->” means moving (assigning) the new value to the contents of a


memory location (address). “;” is a comment sign, and the rest of the line is
a comment. “=” shows the current value at a memory location (address).
To remind, a code written in a high-level programming language is
translated to a machine language by a compiler. However, the machine
language can be readable if its digital codes are represented in some
mnemonic system called assembly language. For example, INC a is
increment by one of what is stored at a memory location “a.”

“ Arithmetic” Project: Assigning Numbers


to Memory Locations
We remind that “a” means location (address) of the memory cell, and it is
also the name of the location (address) 000055555555802c (see Figure 1-3).
(a) means the contents (number) stored at the address “a.”

5
Chapter 1 Memory, Registers, and Simple Arithmetic

If we use the C or C++ language, “a” is called “the variable a,” and we
write the assignment as

a = 1;

In the Intel assembly language, we write

mov $1, a

In the GDB disassembly output, we see the following code where the
variable “a” and address are shown in comments:

movl   $0x1,0x2ef2(%rip)        # 0x55555555802c <a>

We show the translation of our pseudo-code into assembly language in


the right column:

1 -> (a)          ; (a) = 1 movl $1, a


1 -> (b)          ; (b) = 1 movl $1, b
(b) + (a) -> (b)
(a) + 1 -> (a)
(b) * (a) -> (b)

Notice movl instructions instead of mov. This is because “a” and “b”
can point to both 32-bit (like %EAX or %EDX registers) and 64-bit memory
cells (like %RAX and %RDX registers). In the registers’ case, it is clear from
their names whether we use 64-bit %RAX or 32-bit %EAX. But in the case
of memory addresses “a” and “b,” it is not clear whether they refer to 64-bit
or 32-bit cells. We use movl to disambiguate and show that we use 32-bit
memory cells that are enough to hold integers from 0 to 4294967295.
0x2ef2(%rip) is how the compiler generates code to calculate the
address “a” instead of specifying it directly. Such code requires less
memory space. We explain this in later chapters.

6
Chapter 1 Memory, Registers, and Simple Arithmetic

Literal constants have the $ prefix, for example, $0x1. The 0x prefix
means the following number is hexadecimal. The leading four zeroes of
the address are also omitted in the comment. We explain such numbers in
Chapter 3. Please also notice that the movement direction is the same in
both the disassembly output and the pseudo-code: from left to right.
After executing the first two assembly language instructions, we have
the memory layout shown in Figure 1-4.

Figure 1-4. Memory layout after executing the first two assembly
language instructions

7
Chapter 1 Memory, Registers, and Simple Arithmetic

Assigning Numbers to Registers


This is similar to memory assignments. We can write in pseudo-code:

1 -> register
(a) -> register

Note that we do not use brackets when we refer to register contents.


The latter instruction means assigning (copying) the number at the
location (address) “a” to a register.
In assembly language, we write

mov  $1, %eax   # 1 is copied to the first half of %RAX


register
mov  $1, %rax   # full contents of %RAX register are
replaced with 1
mov  a, %eax
mov  a, %rax

In the GDB disassembly output, we may see the following code:

mov    $0x0,%eax

“ Arithmetic” Project: Adding Numbers


to Memory Cells
Now let’s look at the following pseudo-code statement in more detail:

(b) + (a) -> (b)

To recall, “a” and “b” mean the names of locations (addresses)


000055555555802c and 0000555555558030, respectively (see Figure 1-4).
(a) and (b) mean contents at addresses “a” and “b,” respectively, simply
some numbers stored there.

8
Chapter 1 Memory, Registers, and Simple Arithmetic

In the C or C++ language, we write the following statement:

b = b + a;
b += a;

In assembly language, we use the instruction ADD. Because of AMD64


and Intel EM64T architecture’s limitations, we cannot use both memory
addresses in one step (instruction), for example, add a, b. We can only use
the add register, b instruction to add the value stored in the register to
the contents of the memory cell b. Recall that a register is like a temporary
memory cell itself here:

(a) -> register


(b) + register -> (b)

Alternatively, we can use two registers:

(a) -> register1


(b) -> register2
register2 + register1 -> register2
register2 -> (b)

In assembly language, we write

mov a, %eax
add %eax, b

or we can add two registers and move the result to the memory cell b:

mov b, %edx
mov a, %eax
add %edx, %eax
mov %eax, b

9
Chapter 1 Memory, Registers, and Simple Arithmetic

In the GDB disassembly output, we may see the following code:

mov    0x2ee6(%rip),%edx        # 0x555555558030 <b>


mov    0x2edc(%rip),%eax        # 0x55555555802c <a>
add    %edx,%eax
mov    %eax,0x2ed8(%rip)        # 0x555555558030 <b>

Now we can translate our pseudo-code into assembly language:

1 -> (a)          ; (a) = 1 movl $1, a


1 -> (b)          ; (b) = 1 movl $1, b
(b) + (a) -> (b)  ; %eax = 1 mov a, %eax
; %edx = 1     mov  b, %edx
; %eax = 2
   add  %edx, %eax
; (b) = 2
   mov %eax, b
(a) + 1 -> (a)
(b) * (a) -> (b)

After the execution of ADD and MOV instructions, we have the


memory layout illustrated in Figure 1-5.

10
Chapter 1 Memory, Registers, and Simple Arithmetic

Figure 1-5. Memory layout after executing ADD and MOV


instructions

Incrementing/Decrementing Numbers
in Memory and Registers
In pseudo-code, it looks simple and means increment (decrement) a
number stored at the location (address) “a”:

(a) + 1 -> (a)


(a) – 1 -> (a)

11
Chapter 1 Memory, Registers, and Simple Arithmetic

In the C or C++ language, we can write this using three possible ways:

a = a + 1;
++a;
a++;
b = b – 1;
--b;
b--;

In assembly language, we use instructions INC and DEC and write

incl    a
inc     %eax
decl    a
dec     %eax

We use incl when we need to specify the 32-bit memory cell. It is


ambiguous when we use “a.” However, using %eax implies using 32-bit
values, so inc is unambiguous.
In the GDB disassembly output, we may see the same instruction:

inc    %eax

or

add    $0x1,%eax   # a compiler may decide to use ADD


instead of INC

12
Chapter 1 Memory, Registers, and Simple Arithmetic

Now we add the assembly language translation of increment:

1 -> (a)          ; (a) = 1 movl $1, a


1 -> (b)          ; (b) = 1 movl $1, b
(b) + (a) -> (b)  ; %eax = 1 mov a, %eax
; %edx = 1 mov  b, %edx
; %eax = 2 add  %edx, %eax
; (b) = 2 mov %eax, b
(a) + 1 -> (a)    ; %eax = 1 mov  a, %eax
; %eax = 2 add  $1, %eax
; (a) = 2 mov  %eax, a
(b) * (a) -> (b)

After the execution of INC or ADD instruction, we have the memory


layout illustrated in Figure 1-6.

13
Chapter 1 Memory, Registers, and Simple Arithmetic

Figure 1-6. Memory layout after the execution of INC or ADD


instruction

Multiplying Numbers
In pseudo-code, we write

(b) * (a) -> (b)

It means that we multiply the number at the location (address) “b” by


the number at the location (address) “a.”
In the C or C++ language, we can write that using two ways:

b =  b * a;
b *= a;

14
Chapter 1 Memory, Registers, and Simple Arithmetic

In assembly language, we use instruction IMUL (Integer MULtiply)


and write

mov  a, %eax
imul b, %eax
mov  %eax, b

The multiplication instruction means (b) * %eax -> %eax, and we


must put the contents of “a” into %EAX. The multiplication result is put
into the register %EAX, and its contents are saved at the location (address)
“b.” Alternatively, we may put all multiplication operands into registers:

mov  a, %eax
mov  b, %edx
imul %edx, %eax
mov  %eax, b

In the GDB disassembly output, we may see the following code:

mov    0x2ec3(%rip),%edx        # 0x555555558030 <b>


mov    0x2eb9(%rip),%eax        # 0x55555555802c <a>
imul   %edx,%eax
mov    %eax,0x2eb4(%rip)        # 0x555555558030 <b>

15
Chapter 1 Memory, Registers, and Simple Arithmetic

Now we add two additional assembly instructions to our pseudo-code


assembly language translation:

1 -> (a)          ; (a) = 1 movl $1, a


1 -> (b)          ; (b) = 1 movl $1, b
(b) + (a) -> (b)  ; %eax = 1 mov a, %eax
; %edx = 1 mov  b, %edx
; %eax = 2 add  %edx, %eax
; (b) = 2 mov %eax, b
(a) + 1 -> (a)    ; %eax = 1 mov  a, %eax
; %eax = 2 add  $1, %eax
; (a) = 2 mov  %eax, a
(b) * (a) -> (b)  ; %edx = 2 mov  b, %edx
; %eax = 2 mov  a, %eax
; %eax = 4 imul %edx, %eax
; (b) = 4 mov  %eax, b

After the execution of IMUL and MOV instructions, we have the


memory layout illustrated in Figure 1-7.

16
Chapter 1 Memory, Registers, and Simple Arithmetic

Figure 1-7. Memory layout after the execution of IMUL and MOV
instructions

Summary
This chapter introduced CPU registers and explained the memory layout
of a simple arithmetic program. We learned basic x64 instructions and
manually translated simple C and C++ code to assembly language.
The next chapter looks at assembly language code produced by a
debugger via disassembling binary code. Then, we reverse it to C and C++
code. We also compare the disassembly output of nonoptimized code to
optimized code.

17
CHAPTER 2

Code Optimization
“Arithmetic” Project: C/C++ Program
Let’s rewrite our “Arithmetic” program in C/C++. Corresponding assembly
language instructions are put in comments:

int a, b;

int main(int argc, char* argv[])


{
      a = 1;               // movl $1, a

      b = 1;               // movl $1, b

      b = b + a;           // mov  a, %eax


                           // mov  b, %edx
                           // add  %edx, %eax
                           // mov  %eax, b

      ++a;                 // mov  a, %eax


                           // add  $1, %eax
                           // mov  %eax, a

© Dmitry Vostokov 2023 19


D. Vostokov, Foundations of Linux Debugging, Disassembling, and Reversing,
https://doi.org/10.1007/978-1-4842-9153-5_2
Chapter 2 Code Optimization

      b = b * a;           // mov  b, %edx


                           // mov  a, %eax
                           // imul %edx, %eax
                           // mov  %eax, b

                           // results: (a) = 2 and (b) = 4


      return 0;
}

Downloading GDB
We used WSL2 and "Debian GNU/Linux 10 (buster)" as a working
environment. We chose Debian because we used it for the “Accelerated
Linux Core Dump Analysis” training course.1 After installing Debian, we
need to install essential build tools and GDB:

sudo apt install build-essential


sudo apt install gdb

You may also need to download git to clone source code:

sudo apt install git


cd ~
git clone github.com/apress/linux-debugging-disassembling-­
reversing .

GDB Disassembly Output – No Optimization


The source code can be downloaded from the following location:
github.com/apress/linux-debugging-disassembling-reversing/
Chapter2/

1
www.dumpanalysis.org/accelerated-linux-core-dump-analysis-book

20
Chapter 2 Code Optimization

If we compile and link the program in no optimization mode (default):

coredump@DESKTOP-IS6V2L0:~/pflddr/x64/Chapter2$ gcc
ArithmeticProjectC.cpp -o ArithmeticProjectC

we get the binary executable module we can load in GDB and inspect
assembly code.
First, we run GDB with the program as a parameter:

coredump@DESKTOP-IS6V2L0:~/pflddr/x64/Chapter2$ gdb ./
ArithmeticProjectC
GNU gdb (Debian 8.2.1-2+b3) 8.2.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/
licenses/gpl.html>
This is free software: you are free to change and
redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources
online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".


Type "apropos word" to search for commands related to "word"...
Reading symbols from ./ArithmeticProjectC...(no debugging
symbols found)...done.
(gdb)

21
Chapter 2 Code Optimization

Next, we put a breakpoint at our main C/C++ function to allow the


program execution to stop at that point and give us a chance to inspect
memory and registers. Symbolic names/function names like "main" can be
used instead of code memory locations:

(gdb) break main


Breakpoint 1 at 0x1129

Then we start execution of the program (let it run). The program then
stops at the previously set breakpoint:

(gdb) run
Starting program: /home/coredump/pflddr/x64/Chapter2/
ArithmeticProjectC

Breakpoint 1, 0x0000555555555129 in main ()

Now we disassemble the main function:

(gdb) disass main


Dump of assembler code for function main:
   0x0000555555555125 <+0>:     push   %rbp
   0x0000555555555126 <+1>:     mov    %rsp,%rbp
=> 0x0000555555555129 <+4>:     mov    %edi,-0x4(%rbp)
   0x000055555555512c <+7>:     mov    %rsi,-0x10(%rbp)
   0x0000555555555130 <+11>:    movl   $0x1,0x2ef2(%rip)        
# 0x55555555802c <a>
   0x000055555555513a <+21>:    movl   $0x1,0x2eec(%rip)        
# 0x555555558030 <b>
   0x0000555555555144 <+31>:    mov    0x2ee6(%rip),%edx        
# 0x555555558030 <b>
   0x000055555555514a <+37>:    mov    0x2edc(%rip),%eax        
# 0x55555555802c <a>
   0x0000555555555150 <+43>:    add    %edx,%eax

22
Chapter 2 Code Optimization

   0x0000555555555152 <+45>:    mov    %eax,0x2ed8(%rip)        
# 0x555555558030 <b>
   0x0000555555555158 <+51>:    mov    0x2ece(%rip),%eax        
# 0x55555555802c <a>
   0x000055555555515e <+57>:    add    $0x1,%eax
   0x0000555555555161 <+60>:    mov    %eax,0x2ec5(%rip)        
# 0x55555555802c <a>
   0x0000555555555167 <+66>:    mov    0x2ec3(%rip),%edx        
# 0x555555558030 <b>
   0x000055555555516d <+72>:    mov    0x2eb9(%rip),%eax        
# 0x55555555802c <a>
   0x0000555555555173 <+78>:    imul   %edx,%eax
   0x0000555555555176 <+81>:    mov    %eax,0x2eb4(%rip)        
# 0x555555558030 <b>
   0x000055555555517c <+87>:    mov    $0x0,%eax
   0x0000555555555181 <+92>:    pop    %rbp
   0x0000555555555182 <+93>:    retq
End of assembler dump.

We repeat the part of the formatted disassembly output here that


corresponds to our C/C++ code:

   0x0000555555555130 <+11>:    movl   $0x1,0x2ef2(%rip)        
# 0x55555555802c <a>
   0x000055555555513a <+21>:    movl   $0x1,0x2eec(%rip)        
# 0x555555558030 <b>
   0x0000555555555144 <+31>:    mov    0x2ee6(%rip),%edx        
# 0x555555558030 <b>
   0x000055555555514a <+37>:    mov    0x2edc(%rip),%eax        
# 0x55555555802c <a>
   0x0000555555555150 <+43>:    add    %edx,%eax

23
Chapter 2 Code Optimization

   0x0000555555555152 <+45>:    mov    %eax,0x2ed8(%rip)        
# 0x555555558030 <b>
   0x0000555555555158 <+51>:    mov    0x2ece(%rip),%eax        
# 0x55555555802c <a>
   0x000055555555515e <+57>:    add    $0x1,%eax
   0x0000555555555161 <+60>:    mov    %eax,0x2ec5(%rip)        
# 0x55555555802c <a>
   0x0000555555555167 <+66>:    mov    0x2ec3(%rip),%edx        
# 0x555555558030 <b>
   0x000055555555516d <+72>:    mov    0x2eb9(%rip),%eax        
# 0x55555555802c <a>
   0x0000555555555173 <+78>:    imul   %edx,%eax
   0x0000555555555176 <+81>:    mov    %eax,0x2eb4(%rip)        
# 0x555555558030 <b>

We can directly translate it to bare assembly code we used in the


previous chapter and put corresponding pseudo-code in comments:

movl   $1, a              # 1 -> (a)


movl   $1, b              # 1 -> (b)
mov    b, %edx            # (b) + (a) -> (b)
mov    a, %eax
add    %edx, %eax
mov    %eax, b
mov    a, %eax            # (a) + 1 -> (a)
add    $1, %eax
mov    %eax, a
mov    b, %edx            # (b) * (a) -> (b)
mov    a, %eax
imul   %edx, %eax
mov    %eax, b

24
Chapter 2 Code Optimization

Now we can exit GDB:

(gdb) q
A debugging session is active.

        Inferior 1 [process 2249] will be killed.

Quit anyway? (y or n) y
coredump@DESKTOP-IS6V2L0:~/pflddr/x64/Chapter2$

GDB Disassembly Output – Optimization


If we compile and link the program in optimization mode:

coredump@DESKTOP-IS6V2L0:~/pflddr/x64/Chapter2$ gcc
ArithmeticProjectC.cpp -O1 -o ArithmeticProjectC

and after repeating the same steps in GDB, we get the following output:

(gdb) disass main


Dump of assembler code for function main:
=> 0x0000555555555125 <+0>:     movl   $0x2,0x2f01(%rip)        
# 0x555555558030 <a>
   0x000055555555512f <+10>:    movl   $0x4,0x2ef3(%rip)        
# 0x55555555802c <b>
   0x0000555555555139 <+20>:    mov    $0x0,%eax
   0x000055555555513e <+25>:    retq
End of assembler dump.

This corresponds to the following pseudo-code:

mov $2, a   # 2 -> (a)


mov $4, b   # 4 -> (b)

Please note that the compiler also chose to put memory cell “b” first
(000055555555802c) and then memory cell “a” (0000555555558030).

25
Chapter 2 Code Optimization

What happened to all our assembly code in this executable? This code
seems to be directly placing the end result into the “b” memory cell if we
observe. Why is this happening? The answer lies in compiler optimization.
When the code is compiled in optimization mode, the compiler can
calculate the final result from the simple C/C++ source code itself and
generate only the necessary code to update corresponding memory
locations.

Summary
In this chapter, we looked at assembly language code produced by a
debugger via disassembling binary code. Then, we reversed it to C and C++
code. We also compared the disassembly output of nonoptimized code to
optimized code and understood why.
The next chapter refreshes number representations, especially the
hexadecimal one.

26
CHAPTER 3

Number
Representations
Numbers and Their Representations
Imagine a herder in ancient times trying to count his sheep. He has a
certain number of stones (twelve):

However, he can only count up to three and arranges the total into
groups of three:

© Dmitry Vostokov 2023 27


D. Vostokov, Foundations of Linux Debugging, Disassembling, and Reversing,
https://doi.org/10.1007/978-1-4842-9153-5_3
Another Random Scribd Document
with Unrelated Content
Mrs. Marlow sank into a rocking-chair, and began to cry dismally. Her
plans had miscarried for a certainty, and she felt angry with herself.
"Why didn't I put the purse in my trunk?" she asked herself. "Then
he wouldn't have found out. Sure I cheated myself."
Rupert went upstairs with a light heart.
"Well, did you hear anything of the purse?" asked his mother.
For answer he held it up.
"Where did you get it?"
"It came from Mrs. Marlow's pocket."
"What a wicked woman!" exclaimed Grace. "She must have taken it
when I was asleep."
"Did she give it up willingly? I thought she would have denied it."
"So she did, mother, but your son is a detective. I'll tell you how I
managed it," and he told the story.
"There's only a dollar gone," he said in conclusion. "Don't leave it in
the bureau drawer again, though I don't think Mrs. Marlow will
trouble you with another call."
A day or two later the rent came due, and eight dollars had to be
taken from the scanty fund, which left the family again very near
destitution.
Rupert did not relax his efforts to secure a place, but when business
is dull the difficulty of securing a position is much increased. He
became anxious, and the prospect seemed very dark.
"I must do something," he said to himself, "if it's only selling papers.
That will be better than blacking boots, though that is an honest
business."
To make matters worse, his mother was unable to procure vests to
make from any of the readymade clothing establishments.
"We've got all the hands we need," was the invariable answer to her
applications.
They tried to economize more closely, but there was small chance
for that. They had not eaten meat for three days, and remained
contented with bread and tea, leaving out sugar, for they felt that
this was a superfluity in their circumstances. It was emphatically a
dull time, and there seemed no chance to earn anything.
"Rupert," said his mother, drawing a ring from her finger, "take this
ring and pawn it. There seems no other way."
"Isn't it your wedding ring, mother?"
"Yes, Rupert, but I cannot afford to keep it while we are so poor."
Rupert took the ring, and bent his steps towards Simpson's, for he
felt that there he would be likely to meet fair treatment.
CHAPTER VII.
A LUCKY MEETING.

It saddened Rupert to think his mother's wedding ring must be


sacrificed, but when they were actually in need of food sentiment
must not be considered. After that, when they had no longer
anything to pawn except articles of clothing, Rupert shuddered to
think what might lay before them.
He entered Simpson's with a slow step. A woman was ahead of him
and he waited for his turn.
"Well," said an attendant, courteously, "what can I do for you?"
"What will you give me on this ring?"
"What do you want on it?"
"Two dollars," answered Rupert.
"No doubt it is worth that, but we have so many rings in stock that
we are not anxious to receive more. We will give you a dollar and a
quarter."
Rupert hesitated, when to his surprise some one tapped him on the
shoulder.
"What brings you here, Rupert?" were the words that reached his
ear.
He turned round in surprise.
"Mr. Sylvester!" he exclaimed.
"I see you have not forgotten me. What brings you here?"
"Sad necessity, Mr. Sylvester. But—I didn't expect to find you here.
Surely you——"
"No, I have not come here to pawn anything," said the young man,
smiling. "On the contrary, I want to redeem a watch for an old
schoolmate who was obliged to pawn it. He has a wife and child and
was thrown out of employment four weeks since. Fortunately I ran
across him, and have got him a place."
"I will wait till you have attended to your business."
Soon a gold watch was placed in Mr. Sylvester's hands, and he paid
the pawnbroker twenty dollars and sixty cents. It had been pledged
not quite a month for twenty dollars. The sixty cents represented the
three per cent. a month interest allowed by the laws regulating
pawn shops.
"Now, young man," said the attendant, "do you want the dollar and
a quarter I offered you on your ring?"
"Yes," answered Rupert.
"No," interposed Frank Sylvester, quietly. "What ring is this, Rupert?"
"My mother's wedding ring."
"And you are actually reduced to pawning it?"
"Yes, Mr. Sylvester, I can't get anything to do, and we are out of
money."
"You have a mother and sister, I think you told me?"
"Yes, sir."
"I think we can do better than pawn the ring. Where do you live?"
"In Elizabeth Street."
"Does your mother prefer the city to the country?"
"No, sir; but she has no choice."
"Suppose I obtain for her a position as housekeeper in the family of
an elderly gentleman in Rutherford, about ten miles out on the Erie
Railroad, would she accept?"
"She would be glad to do so but for Grace. She could not be
separated from her."
"There would be no occasion. My uncle lives alone in a large house,
and a child would make the house pleasanter."
"Some gentlemen don't like children."
"That is not the case with Uncle Ben. But let us go out. You have no
further business here. We will go into the Astor House reading room
and have a chat."
Rupert followed his friend to the Astor House and they ascended to
the reading room on the second floor. Taking adjoining armchairs,
Mr. Sylvester drew from his pocket the following letter which he
showed to Rupert. It ran thus:

"My housekeeper is about to leave me, to join her married


daughter in Wisconsin. I must supply her place, but I know of
no one in Rutherford who would suit me. Can't you find me
some one—a pleasant, ladylike person, who would make my
house homelike and attractive? I think you know my tastes.
Please give this matter your early attention.
Benjamin Strathmore."

"Now," continued Mr. Sylvester, "I was quite at a loss whom to


recommend, but I think your mother would suit Uncle Ben."
"Suppose you call and make her acquaintance, Mr. Sylvester. Then
you can tell better. That is, if you don't object to visiting our poor
home."
"My dear Rupert, I shall be delighted to meet your mother. One
thing I am sure of in advance, she is a lady."
"She is, Mr. Sylvester," said Rupert, warmly.
Mrs. Rollins was a good deal surprised when Rupert entered the
room, followed by a handsomely-dressed young man, and she rose
from her seat in some trepidation.
"Mother," said Rupert, "this is Mr. Sylvester, who was kind enough to
give us the money and provisions I brought home the other day."
"I am glad to meet so kind a friend," said the widow, with simple
dignity. "Ask him to take a seat."
"I came to make you a business proposal," began Mr. Sylvester, who
was already favorably impressed with Rupert's mother. "Your son
thinks you might be willing to accept the position of housekeeper in
my uncle's family, in Rutherford."
Mrs. Rollins instinctively looked towards Grace.
"I see what you are thinking of," interposed her caller. "There will be
no difficulty about taking your daughter with you."
"Then I shall be glad to accept. And Rupert——"
"Rupert, I am sure, will prefer to remain in the city. I will find him a
place. Till then he can stay with me."
Rupert brightened up at this suggestion. He had no desire to go to
the country, but would like nothing more than a place in some city
establishment.
"How soon could you arrange to go, Mrs. Rollins?"
"Next Monday."
"That will answer. I will apprise my uncle. Now as to the
compensation."
"If I have Grace with me I shall hardly feel justified in asking
compensation."
"My uncle would not think of making any account of the little girl's
board. I think he paid your predecessor twenty-five dollars a month.
Will that be satisfactory?"
"It is very liberal, sir."
"You will allow me to offer you a month's salary in advance. I can
settle it with Uncle Ben."
This relieved Mrs. Rollins from a great embarrassment, as she
needed to replenish her wardrobe to some extent.
"I will go out with you on Monday, and take Rupert with me, as he
will wish to see how his mother and sister are situated."
"How kind you are, Mr. Sylvester!" said Rupert, gratefully.
"Don't give me too much credit, Rupert. You have helped me out of
an embarrassment. I expected to have a long hunt for a
housekeeper. Thanks to your mother I have escaped all that."
"You don't know how much it means to us, Mr. Sylvester."
"Well, perhaps, I have some idea. It seems a good arrangement for
all of us. Well, good morning. Oh, by the way, you meet me at the
Astor House to-morrow morning at eleven o'clock."
"Yes, sir, with pleasure."
Mrs. Marlow was a very observing woman. She always kept her door
ajar, and saw every one who went upstairs. Her curiosity was
considerably excited when she saw Rupert's companion.
"My stars!" she said to herself. "What a fine-looking young man! He
looks like a real gentleman—I wonder does he know them Rollinses."
Mrs. Marlow would liked to have listened at the door and heard the
conversation between her neighbors and the distinguished-looking
visitor. But this was not practicable. However, as Mr. Sylvester came
down stairs she ventured out and intercepted him.
"Sure, you've been callin' on my friend, Mrs. Rollins," she said.
"Is she a friend of yours?" asked Sylvester, looking at her curiously.
"Indeed she is, and she's a fine lady. But she's been very
unfortunate. I would like to have helped her, but I am poor myself,
and——"
"Won't you accept this?" said Sylvester, offering her a dollar as the
easiest way of getting rid of her.
"Thank you, sir," said Mrs. Marlow, with a profound courtesy. "It's
easy to see you're a kindhearted man."
"What a curious woman! I should hardly think Mrs. Rollins would
have made choice of her as a friend!" soliloquized the young man as
he pushed on to the street.
"I wonder what his name is and where he lives," speculated Mrs.
Marlow. "He must be the young man that gave the Rollinses the
purse and the basket of provisions. If I knew where he lived I'd go
and see him often."
There is very little doubt that Mrs. Marlow would have kept her
word, but unfortunately she had no clew to the residence of her new
acquaintance.
When Rupert came downstairs, she put herself in his way.
"You had a call from a nice gentleman this morning," she said,
insinuatingly.
Rupert felt too happy to slight even Mrs. Marlow, and he answered,
courteously,
"Yes."
"I hope he brought a present for your mother."
"No, Mrs. Marlow, but he brought something better."
"And what can that be?" asked the widow, with intense curiosity.
"He engaged mother to take a place as housekeeper for a
gentleman in the country."
"You don't say! And what'll be done with your sister? I'll board her
cheap, and be like a mother to her."
Rupert could not help smiling at the idea of leaving his sister in such
hands. He explained that Grace would go with her mother.
"Sure your mother's a lucky woman! I'd like to be a housekeeper
myself. Wouldn't you speak to the gentleman for me?"
"I'll mention it if you like."
Rupert could promise this safely, for he would take care that Mr.
Sylvester understood the character of their unscrupulous neighbor.
"If you'll do it, Rupert, dear, I'll pay you back the dollar I borrowed
the other day, when I get my first week's wages."
"Some folks is lucky!" soliloquized Mrs. Marlow. "The young man
ought to have taken me. I'm much stronger than Mrs. Rollins, and I
would have made a better housekeeper, but maybe my turn will
come next."
CHAPTER VIII.
JULIAN LORIMER.

On Monday Rupert saw his mother and sister established at


Rutherford. Their new home was a large old-fashioned mansion,
exceedingly comfortable. One of the best chambers was assigned to
Mrs. Rollins, with a small room opening out of it for Grace.
Benjamin Strathmore was a stout old gentleman of seventy, tall, and
patriarchal-looking with his abundant white hair.
"How do you like my selection of housekeeper, Uncle Ben?" asked
Sylvester, when he had a chance to be alone with the old gentleman.
"She will just suit me," said Mr. Strathmore, emphatically. "She is
evidently a lady, and she will be an agreeable companion if I am not
mistaken. Mrs. Martin was a good housekeeper, but she had no idea
outside of her duties. I could not chat with her unless I talked about
cooking. My evenings were solitary. She spent the time in the
kitchen or in her own room. Now the house will be really social."
"I am delighted to have suited you, Uncle Ben."
"Where in the world did you come across Mrs. Rollins? Have you
known her long?"
"I became acquainted through her son Rupert, to whom I introduced
you."
"He seems a fine, manly boy. He can stay here, too. I will find
something for him to do."
"Thank you, Uncle Ben, but I shall find him a place in New York. He
prefers the city, and it will afford him more opportunities of
advancement. Rupert is ambitious, and I predict that he will rise in
time to an excellent position."
"Just as you think best, Frank; but remember that if ever there is
need, or he becomes sick, there is room for him here."
To anticipate a little. Mr. Strathmore was not disappointed in Mrs.
Rollins. It came to be her custom to spend the evenings with her
employer. Sometimes she read aloud to him. At others, while she
was engaged in needlework, and Grace, now restored to health, was
occupied with her books, the old gentleman sat back in his easy
chair, and with calm content watched his companions. He no longer
felt his former burden of solitude.
"I have never been happier," he wrote later on to his nephew. "I
regretted the loss of Mrs. Martin, but now I feel that it was for my
happiness, since it has opened the way for such an acceptable
substitute."
Rupert went at first to the house of Mr. Sylvester, where their
acquaintance soon ripened into friendship.
They were walking down Broadway one day, when Frank Sylvester
noticed a sudden start on the part of his young companion.
"What is the matter, Rupert?" he asked.
"Do you see that stout man on the opposite side of the street, Mr.
Sylvester?" said Rupert.
"Yes. What of him?"
"He was the cause of my poor father's failure and death."
"How was that?"
"My father was a merchant in Buffalo, and that man was his partner.
During a three months' absence in California, where he went partly
for his health, the business was managed by Mr. Lorimer in such a
way that the firm became deeply involved and was brought to the
brink of failure.
"My father was greatly astonished at the sudden change, for when
he left all was prosperous. He could not account for the
disappearance of assets and the accumulation of claims against the
firm except on the theory that large sums had been appropriated by
his partner. He could prove nothing, however, and the firm was
dissolved. When the business was closed there was barely enough
money left to pay the creditors. My father found himself with
nothing, and soon died of grief and mortification."
"What became of Lorimer?"
"I have not seen him till to-day. I heard that he had come to New
York and established himself on Third Avenue somewhere, in the
same business. If so, he must have had capital, and this must have
been the sum of which he defrauded my father."
"The story is a sad one, Rupert. You and your mother must have
suffered from the change in circumstances."
"We did. We did not care to stay in Buffalo, where we had been
accustomed to live in good style, so we came to New York, where
we could live according to our change in circumstances among those
who had never known us. I thought I might get employment that
would enable me to support my mother and sister in tolerable
comfort. I did get a place with Tenney & Rhodes, but I only earned
five dollars a week. Just before meeting you I lost that, and had you
not come to our assistance I don't know what would have become of
us."
"I feel repaid for whatever I have done for you," said Frank
Sylvester, kindly. "Has this Mr. Lorimer a family?"
"He has a wife and one son."
"Were your families intimate?"
"Yes. We occupied adjoining houses. Julian Lorimer was about my
age, and attended the same school. I never liked him, however. He
had a very high opinion of himself, and put on airs which made him
generally unpopular."
"Did he put on airs with you?"
"Not till after the failure. My father moved out of his house, but Mr.
Lorimer remained in his, and appeared to live in about the same
style as before, while we moved into a few rooms in an
unfashionable part of the city. After this Julian took very little notice
of me."
"You haven't met him since you came to New York?"
"No; I rather wonder I haven't, but I suppose I shall some day."
The time came sooner than he anticipated.
Rupert was crossing Eighth Avenue near Forty-second Street one
day, when he came near being run into by a bicycle. The rider gave
a note of warning, and then stopped short in surprise.
"Rupert Rollins!" he said, in a half tone of inquiry.
"Is it you, Julian?" asked Rupert, recognizing his former schoolmate.
"Yes. Are you living in New York?"
"Yes."
"Whereabouts?"
"At present I am staying in Harlem."
"I heard you and your mother were living in a tenement house down
town."
"My mother is not living in the city," returned Rupert, coldly.
He did not care to give Julian any more information than was
absolutely necessary.
"Where is she, then?"
"In Rutherford, New Jersey."
"Why don't you live there, too?"
"Because I expect to be employed in New York."
"Then you are out of work now?"
"Yes."
"Why don't you live in the Newsboys' Lodge? That is cheap."
"Have you ever lived there?"
"Do you mean to insult me? I live in a nice house on One Hundred
and Sixteenth Street."
"So do I."
"You are bluffing."
"Why should I? What good would it do me?"
Further inquiry developed the fact that they lived in neighboring
blocks.
"I don't see how you can afford to live on such a street."
"I am at present visiting a friend—Mr. Sylvester."
"Is he rich?"
"Yes. I believe so."
"I suppose you know that my father has a nice new store on Third
Avenue, near Forty-second Street?"
"I heard something of the kind," said Rupert, briefly.
"He's doing a staving business—a good deal larger than he did in
Buffalo."
Rupert made no comment.
"You said you were out of employment, didn't you?"
"Yes."
"You might call round at the store. Perhaps pa can find a place for
you as a cash boy, though you would be rather large for that."
"How much does he pay his cash boys?"
"Two and a half a week."
"I hardly think I could live on that," said Rupert, smiling.
"It is better than being out of work."
"That is true, but I shouldn't like to be getting more and more
behindhand every week. Are you attending school?"
"Yes, but I think of going into business soon."
"Perhaps," suggested Rupert, "you will take one of the cash boys'
places."
"You must be crazy. When I go into business it won't be into a retail
store. I will get a place in some wholesale establishment. There's a
better chance to rise there."
"I didn't know but you would go to college."
"I am not very fond of study. Pa would send me to Columbia College
or to Harvard, if I wanted to go, but I prefer a life of business. I
want to become a merchant prince."
"It would certainly be agreeable. I shall be satisfied if I can be
successful enough to support my mother and sister in comfort. That
is my ambition."
"Oh, I dare say. You are a poor boy, you know."
"Look here, Julian, there's one thing I don't understand. Your father
and mine were partners, and I supposed in the same circumstances.
Both failed together. Yet your father now has a large store of his
own, and we are poor. Can you tell me why?"
"I'm not good at conundrums. I'll have to be going. If you want a
place as cash boy I'll ask pa to fit you out. Ta ta!" And Julian dashed
off on his wheel.
"I hope some time to be a successful and honorable man of
business," thought Rupert, as he followed his former schoolfellow
with his glance. "My ambition would not be satisfied with anything
short of this."
CHAPTER IX.
RUPERT BECOMES A BELL-BOY.

Rupert found a pleasant home at the house of Mr. Sylvester, but he


was anxious as soon as possible to secure employment. His friend
was active in his behalf, but the general depression in business was
such that there seemed to be no opening anywhere.
One evening at supper Mr. Sylvester said: "I have been hoping to
find you a place in a wholesale establishment in Pearl Street. I
learned that one of the younger clerks was about to leave, but he
has decided to stay six months longer, and, of course, we can't wait
as long as that."
"No, Mr. Sylvester, it would seem like six years to me."
"Even if your wants were all provided for in that time?"
"I feel that I ought to be at work, and not depending on your
generosity. I would rather work for two dollars a week than remain
idle."
"That is the right spirit, Rupert. You will be glad, then, to hear that I
have at last found employment for you."
"But I thought you just said——"
"That I could not get you a place in Pearl Street. True, but this is a
different position—very different. It is that of bell-boy in a hotel."
"What are the duties, Mr. Sylvester?"
"You will be at the command of the clerk, and will have to run up
and downstairs, answering calls from the guests, or carrying
messages from the office. In fact, you will be a general utility clerk,
and I have no doubt will get terribly tired the first few days."
"Never mind. I can stand that. If I make enough to pay my way I
shall be satisfied."
"You will be better paid than if you were in a mercantile house. You
will receive five dollars a week and get your meals at the hotel."
Rupert's face brightened.
"Why, that is excellent," he said. "When I was at Tenney & Rhodes' I
only received five dollars weekly and had to furnish my own meals."
"True, but you were then in the line of promotion. Here you cannot
expect to rise any higher unless you qualify yourself to be a hotel
man."
"At any rate I am willing to try it. Where is the hotel?"
"It is the Somerset House, on lower Broadway. It is not a fashionable
hotel, but comfortable and of good reputation. I am somewhat
acquainted with the office clerk, who was an old schoolmate of
mine, and at my request he has given you this position."
"I hope I shall give satisfaction. I shall be a green hand."
"The duties are easily understood and learned. If you show that you
are desirous of succeeding you will make a good impression, and
you will get on well."
"When am I to commence work?" asked Rupert.
"I will take you down town with me to-morrow morning, and
introduce you to Mr. Malcolm, the clerk. I suppose you will be
expected to go to work directly."
"I should prefer that."
"One thing I must tell you. You will have to secure a room outside,
as the employees are not expected to sleep in the hotel. All the
rooms are reserved for guests."
"What will my hours be?"
"From seven in the morning till seven in the evening. By this
arrangement you will have your evenings to yourself."
Rupert went to bed in good spirits. He was of an active
temperament, and enjoyed occupation. It would be pleasant to him
also to feel that he was earning his own living.
In the morning Mr. Sylvester went down town with him.
The Somerset House was a hotel of moderate size, only five stories
in height, which is low for a city hotel. I may as well say here that I
have not given the correct name of the hotel for obvious reasons. So
far as our story is concerned, the name I have chosen will do as well
as any other.
"Those who frequent this hotel are not of the fashionable class,"
explained Mr. Sylvester, "but it is largely patronized by traveling
salesmen and people from the country. The rates are moderate, and
those come here who would not feel able to afford the Fifth Avenue
or hotels of that grade."
The entrance was neat, and Rupert was well pleased with the aspect
of his new place of employment.
At some distance from the doorway was the office, and behind the
reading room.
"Mr. Malcolm," said Sylvester to a pleasant-looking man of thirty-five,
who stood behind a counter, "this is the young man I mentioned to
you. He will be glad to fill the position of bell-boy, and from my
acquaintance with him I feel quite sure he will suit you. His name is
Rupert Rollins."
The clerk smiled pleasantly.
"We shall soon know each other better," he said. "I hope you are
strong, for you will have a good deal of exercise here."
"I think I can stand it," said Rupert. "I shall soon get used to it."
"I have a plan of the rooms here," went on the clerk. "Take it and go
upstairs and look about you on the different floors. It will be
necessary that you should learn the location of the rooms."
"I will leave you now, Rupert," said Mr. Sylvester. "You can come
back to my house to-night, and to-morrow you can look up a room
near the hotel."
For the first few days Rupert got very tired. He would have to go
upstairs perhaps thirty or forty times during the day, sometimes to
the fifth floor. There was an elevator in the Somerset Hotel, but the
bell-boys were not allowed to use it.
When a guest registered and was assigned to a room on one of the
upper floors he was conducted to the elevator, but the bell-boy,
carrying his valise, was obliged to walk upstairs, and meet him at
the landing-place. Often Rupert felt that there was an injustice in
this, and that no harm would be done if he were also allowed to use
the elevator. However, he was not foolish enough make any
complaint, but by his pleasant manners and cheerful alacrity won the
good opinion of Mr. Malcolm, the clerk.
The Somerset Hotel was on the European and American systems
combined. If a guest preferred simply to lodge at the hotel he could
do so, and take his meals either at the hotel restaurant or in any
other.
One day a guest registered who was assigned to No. 143, on the
fifth floor.
To Rupert was assigned the duty of carrying up the valise. He found
it unusually heavy, and more than once as he climbed the stairs he

You might also like