Computer Architecture with Python and ARM - Alan Clements - E-Book

Computer Architecture with Python and ARM E-Book

Alan Clements

0,0
28,79 €

oder
-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This comprehensive guide offers a unique and immersive learning experience by combining Python programming with ARM architecture.
Starting with an introduction to computer architecture and the flow of data within a computer system, you’ll progress to building your own interpreter using Python. You’ll see how this foundation enables the simulation of computer operations and learn ways to enhance a simulator by adding new instructions and displaying improved results.
As you advance, you’ll explore the TC1 Assembler and Simulator Program to gain insights into instruction analysis and explore practical examples of simulators. This will help you build essential skills in understanding complex computer instructions, strengthening your grasp of computer architecture. Moreover, you’ll be introduced to the Raspberry Pi operating system, preparing you to delve into the detailed language of the ARM computer. This includes exploring the ARM instruction set architecture, data-processing instructions, subroutines, and the stack.
With clear explanations, practical examples, and coding exercises, this resource will enable you to design and construct your own computer simulator, simulate assembly language programs, and leverage the Raspberry Pi for ARM programming.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Computer Architecture with Python and ARM

Learn how computers work, program your own, and explore assembly language on Raspberry Pi

Alan Clements

BIRMINGHAM—MUMBAI

Computer Architecture with Python and ARM

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Kunal Sawant

Publishing Product Manager: Akash Sharma

Senior Editor: Nisha Cleetus

Technical Editor: Jubit Pincy

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Shankar Kalbhor

Business Development Executive: Kriti Sharma

Developer Relations Marketing Executive: Sonia Chauhan

First published: July 2023

Production reference: 2281123

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-667-9

www.packtpub.com

Writing the dedication is the hardest part of writing a book. Of all the people you have known, who do you honor? I would like to dedicate this book to four people who have smoothed my path through life, have been my friends, have set an example, and have made my life worth living.

To my wife, Sue, who has been my companion and soulmate for over half a century and has provided so much help with my writing.

To Samuel Gatley, my oldest school friend, who provides me with inspiration and, like all good friends, is always there to speak to.

To Derek Simpson, who was my Dean at Teesside University for many years and continues to be a friend. Derek is the most selfless person I’ve ever met and is always willing to help anyone and everyone.

To Patricia Egerton, a former colleague and friend who had faith in me when I lacked it and propelled me to make a career decision that changed the course of my life.

Contributors

About the author

Dr. Alan Clements taught computer architecture for over 30 years at The University of Teesside. Alan has written several major university texts on computer architecture. He was also an active member of the IEEE Computer Society for two decades and ran its Computer Society International Design Competition for over 10 years. Alan was second vice president of the society for a year.

Since retiring, Alan has thrown himself into photography and has exhibited his work several times in the UK, Spain, and Venice.

About the reviewers

Sri Manikanta Palakollu is a proficient full-stack developer who has acquired expertise in various technologies, such as Java, AEM, Python, C++, C, JavaScript, TypeScript, MERN, databases, machine learning, and deep learning. He has also authored many articles on diverse domains such as AI, machine learning, programming, data science, and cybersecurity. He has published his articles on various platforms, such as Medium, HackerNoon, and Analytics Vidhya. He has offered technical guidance for many books from well-known publishers, such as Packt and Apress, and penned a book named Practical System Programming with C. He has also mentored more than 5,000 students in various coding hackathons hosted by different organizations and institutions.

Aleksei Goriachikh is a mathematics master’s degree holder with a diverse professional background. Prior to entering the semiconductor industry, he conducted research in computational mathematics and optimization and participated in the development of a geometric kernel for CAD systems. Throughout his time in the semiconductor industry, Aleksei has been involved in performance optimization, library development, and autonomous driving projects. His current professional interest lies in pre-silicon modeling, where he leverages virtual simulations to optimize semiconductor devices before fabrication.

Table of Contents

Preface

Part 1: Using Python to Simulate a Computer

1

From Finite State Machines to Computers

Technical requirements

The finite state machine

Traffic lights example

Solving a simple problem algorithmically

Constructing an algorithm

Summary

2

High-Speed Introduction to Python

Technical requirements

Reading programs

Getting started with Python

Python’s data types

Mathematical operators

Names, values, and variables

Comments

The list – a Python key data structure

Slicing lists and strings

Functions in Python

Conditional operations and decision-making

Using a conditional expression in Python

Python’s if … else

Reading data from a file

Computer memory

Register transfer language

Summary

3

Data Flow in a Computer

Technical requirements

The Instruction Architecture Level (ISA)

ISAs – the Naming of Parts

The von Neumann architecture

The address path

Reading the instruction

The CPU’s data paths

Typical data movement instructions

Data processing instructions

Another look at the data flow

An assembly-level program

Executing conditional instructions

Dealing with literal operands

The machine-level instruction

Instruction types and formats

CISC and RISC

Two ways of representing literals

Summary

4

Crafting an Interpreter – First Steps

Technical Requirements

Building a simple computer interpreter in Python

Python code for a primitive simulator

The TC1 instruction set

Bit-handling in Python

Operator precedence in Python

Decoding and executing an instruction

Arithmetic and logical operations

Functions in Python

Branches and flow control

Summary

5

A Little More Python

Technical requirements

More string features

String processing

Example – text Input

List comprehensions

The tuple

Repetition and looping

Repetition and Iterables

Lists of lists

Indenting in python

The dictionary

Functions revisited

Imports

Summary

6

TC1 Assembler and Simulator Design

Technical requirements

Analyzing instructions

Processing the input

Dealing with assembler directives

Using the dictionary

Labels

Building the binary instruction

Extracting the instruction and its parameters

Intermission: The Pre-TC1

The Simulator

The TC1 simulator program

Single-stepping

File input

Example of a TC1 assembly language program

Testing the assembler

Testing flow control operations

Testing shift operations

TC1 postscript

The classDecode function

The testLine function

The testIndex() function

General comments

The TC1tiny code listing

TC1 postscript mark II

Summary

7

Extending the TC1

Technical requirements

Another look at python’s input and output

Displaying data

Input validation

Validating data

Adding new instructions

First example – putting two memory locations in ascending order

Second example – adding a bit-reversal instruction

A new comparison operation

Variable-length instructions

A variable-length instruction machine

Summary

8

Simulators for Other Architectures

Technical requirements

TC0: A stack-based calculator

TC0: A python stack machine

TC2: A one-address accumulator machine

Enhancing the TC2 Simulator

TC3: A CISC machine with a register-to-memory architecture

The TC3 instruction set architecture

Features of the simulator

The complete TC3 code

A sample run of TC3

Arithmetic and Logic Unit (ALU)

Testing the ALU

A final example: TC4

Comments on TC4

Summary

Part 2: Using Raspberry Pi to Study a Real Computer Architecture

9

Raspberry Pi: An Introduction

Technical requirements

Raspberry Pi basics

Basics of the Raspberry Pi operating system

Directory navigation

File operations

Installing and updating programs and packages

Creating and editing an assembly language program

Assembling ARM code

Debugging assembly language

Using the Raspberry Pi debugger

Accessing memory

Features of the GCC ARM assembler

Dealing with 32-bit literals

A note on endianism

Bringing everything together – a final example

Summary

10

A Closer Look at the ARM

Technical requirements

Introducing the ARM

Overview of the ARM’s architecture

Arm register set

Arithmetic instructions

Flow control instructions

Unconditional branches

Conditional branch

Conditional executions

Sequential conditional execution

Summary

11

ARM Addressing Modes

Literal addressing

Scaled literals

Register indirect addressing

Pointer-based addressing with an offset

Two pointers are better than one

Automatic indexing of pointer registers

Example of string-copying

Program counter-relative addressing

Demonstration of program counter relative addressing

Summary

12

Subroutines and the Stack

The Branch with link instruction

The stack

A subroutine call and return

Block move instructions

Disassembling the code

Block moves and stack operations

Summary

Appendices – Summary of Key Concepts

Index

Other Books You May Enjoy

Preface

A fundamental thread of computer science is computer architecture. This topic was once called computer hardware and is concerned with the physical computer itself; that is, the central processing unit (CPU), memory, buses, and peripherals. Computer hardware contrasts with computer software, which applies to the programs, applications, and operating systems that computers execute.

Most users are no more concerned with computer hardware and architecture than drivers worry about the operation of their vehicles’ carburetors. However, a knowledge of computer architecture is useful in many ways, ranging from how efficiently you operate your computer to maximizing its security. A good analogy is with pilots. They learn how to fly an aircraft, and a knowledge of how its engines operate is considered absolutely vital in handling abnormal situations, prolonging the engine life, and minimizing fuel consumption.

Computer architecture is a large subject and is broadly divided into three interrelated areas: instruction set architecture (ISA), computer organization, and computer hardware. The ISA represents the programmer’s view of the computer; that is, it’s an abstract model of what a computer does (rather than how it does it). For example, the programmer is interested in a computer’s instruction set, which includes operations such as add P,A,B, which adds A to B and puts the sum in P. This book explains computer architecture by demonstrating how you can write a program that simulates a computer.

The part of computer science that deals with how a computer implements the actions of its architecture is called computer organization and is largely beyond the scope of this text. Computer organization is concerned with the gates and circuits of the computer.

An author can’t do justice to all the aspects of a computer in one book. Here, I am interested in tackling one topic: the ISA. I am going to introduce the computer’s instruction set and explain what it does. I will also discuss different types of instruction sets; for example, the ARM processor found in most mobile phones is very different from the Intel and AMD processors at the heart of PCs and laptops. In the second part of this book, we will concentrate on a specific computer and look at a real-world architecture, the ARM processor.

This book is different. There are books on computer architecture. There are books on Python. There are books on the Raspberry Pi computer. Here, we combine all three of these topics. However, I don’t do this in a superficial way leaving the reader with a shallow and unsatisfactory knowledge of each topic.

My intention is to introduce a computer architecture and its instruction set. That is, I am going to explain how a computer works at the level of its native instructions (called assembly language). I describe what an instruction does and how it is read, interpreted (i.e., decoded), and then executed (implemented). I will also discuss the type of operations computers implement.

So, how does Python fit into this scheme? Python is a popular high-level programming language that is freely available for use on the PC, Apple Mac, and Raspberry Pi. Moreover, Python is probably the easiest computer language to learn, and it is remarkably powerful.

People learn by doing. I have decided to include sufficient Python for the reader to construct a simple computer simulator that can read a machine-level computer instruction and execute it. Because I will show how this Python simulator works, students can build computers to their own specifications. They can experiment with instruction sets, addressing modes, instruction formats, and so on. They can even build different types of computers to their own specifications, for example, by using complex instruction set computer (CISC) or reduced instruction set computer (RISC) architectures. CISC and RISC offer two different philosophies of computer design. Essentially, RISC computers have fixed-length instructions that permit only register load and store memory operations, whereas CISC computers can have variable-length instructions and permit direct data operations on memory. In reality, the distinction between RISC and CISC is more complex. The first generation of microprocesses all conformed to CISC philosophy.

Readers can build computers because they can write a program in Python that will execute the target language of a specific computer architecture and they can design that target language themselves.

One of the most popular computer architectures is the ARM processor found in countless mobile applications and even Apple laptops. Not only is this an economically dominant processor family but it’s also very popular in education because of its interesting and innovative architecture and its relatively gentle learning curve. Even better, this is the processor used by the low-cost Raspberry Pi computer. You can run ARM code on Raspberry Pi using software tools that come with the computer. You can also run Python programs on Raspberry Pi with free software. Consequently, Raspberry Pi provides students with an excellent low-cost machine that lets them study core hardware topics with no further investment in hardware or software.

Who this book is for

For many years, I have taught computer architecture and have used simulators to teach assembly language. This approach demonstrates what instructions do but not how they do it or how they are designed, decoded, and executed. I decided to create a simple instruction simulator for class use. This book evolved from that project.

My target audience can be divided into four main groups, as follows:

Students who are taking a computer architecture course and would like to enhance their experience of computer architecture by experimenting with their own CPUs by means of simulation. This approach would increase the depth of their knowledge of computer architecture and enhance their understanding of the trade-offs that the computer designer faces.The non-computer specialist, the layperson, and the enthusiast who would like to know how computers work. By using Python as the design language and providing an introductory course on Python, I have attempted to make the book accessible to those with little or no experience in programming.The Raspberry Pi user. Raspberry Pi has had an immense impact on computer science education. This book provides a brief introduction to Raspberry Pi and shows how it is possible to write assembly language programs in the ARM’s native language. Moreover, Raspberry Pi also provides an environment (Python and its tools) that allows the reader to understand and simulate computers.The reader wanting to learn Python. Although this is not a formal course on Python, it provides a goal-oriented introduction to Python; that is, it applies Python to an actual example. This approach avoids the breadth of a conventional course and enables the reader to construct a practical application with a relatively shallow learning curve.I have not assumed that a beginner reader has absolutely no knowledge of computers at all. This book assumes a very basic knowledge of binary arithmetic and number bases and the basic concepts of Boolean variables.

What this book covers

Chapter 1, From Finite State Machines to the Computers, introduces the notion of digital computers via the finite state machine that is used to model simple control systems. From there, we introduce the concept of algorithms and programs. Once we know what we want a computer to do, we can think about what we need to implement a computer.Chapter 2, High-Speed Introduction to Python, provides the initial background in Python that is required to take the first steps on the way to implementing a computer using Python.Chapter 3, Data Flow in a Computer, demonstrates how information flows around a computer during the execution of a program. It is this data flow that we have to implement when we are simulating a program in software.Chapter 4, Crafting an Interpreter – First Steps, begins the journey to a simulator. Now that we have been introduced to the concept of a computer and a little Python, we can go further and describe the fundamental ideas behind a computer simulator. In this chapter, we also look at the nature of computer instructions.Chapter 5, A Little More Python, expands our knowledge of Python and introduces us to vital topics such as Python’s dictionaries, which provide tools that greatly simplify the design of a computer simulator.Chapter 6, TC1 Assembler and Simulator Design, is the heart of this book. Here, we discuss the components of a simulator and then provide a program that can simulate a hypothetical teaching computer, TC1.Chapter 7, Extending the TC1, adds further facilities to the simulator, such as data checking and creating new instructions.Chapter 8, Simulators for Other Architectures, looks at different types of computer architecture and describes alternative simulators.Chapter 9, Raspberry Pi – An Introduction, changes course. Here, we look at the popular Raspberry Pi and the ARM processor at its core. In particular, we learn how to enter a program in ARM assembly language and run it in debugging mode.Chapter 10, A Closer Look at the ARM, examines ARM’s instruction set in greater detail and provides a foundation for writing programs in assembly language.Chapter 11, ARM Addressing Modes, looks at the addressing modes of the ARM in greater detail and explains some of its special features.Chapter 12, Subroutines and the Stack, is really an extension of the previous chapter because we look at the way in which the ARM uses its addressing modes to implement stack operations, which are so important in assembly language programming.

To get the most out of this book

This book is split into two parts. The first part develops a computer simulator in Python and the second part provides a brief introduction to Raspberry Pi and uses it as a vehicle to teach ARM assembly language programming.

I used a PC with Windows to develop the Python programs. The reader may use a Windows-based system, an Apple Mac, or any Linux-based computer to develop Python. All the necessary software is freely available.

You can, of course, use Raspberry Pi itself to develop Python.

In order to write ARM assembly language programs and debug them, you need a Raspberry Pi. This is a single-board computer and requires a power supply, keyboard, mouse, and monitor. I have used both the Raspberry Pi 3 Model A+ and Raspberry Pi 4 Model B versions.

The software required to develop Python programs is freely available from https://www.python.org. The Raspberry Pi single-board computer is not sold with an operating system. You must either buy an SD card with the operating system installed or download it yourself. Details are given at https://www.raspberrypi.com/documentation/computers/getting-started.html.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Computer-Architecture-with-Python-and-ARM. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates that words in text are not plain English words, but are words belonging to a program.

The break instruction breaks out of the while loop (that is, execution continues beyond the end of the loop - it’s a sort of short-circuit mechanism).

In order to draw your attention to features in code, we sometimes use bold font or shading to highlight features. Consider the following example:

The text following # is in a non-monospaced font and is a comment ignored by the computer:

for i in range (0,6):         # Repeat six times

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Computer Architecture with Python and ARM, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily.

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837636679

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Using Python to Simulate a Computer

In this part, you will be introduced to two threads: the digital computer and the programming language Python. The purpose of this book is to explain how a computer works by constructing a computer in software. Because we assume that the reader will not have a knowledge of Python, we will provide an introduction to Python. However, we will cover only those topics relevant to building a computer simulator are explored. The topics of the structure and organization of a computer and Python programming are interleaved. Once we have introduced theTC1 (Teaching Computer 1) simulator, the two final chapters will first explore ways of enhancing the simulator's functionality, and then look at simulators for alternative architectures.

This section comprises the following chapters:

Chapter 1, From Finite State Machines to ComputersChapter 2, High-Speed Introduction to PythonChapter 3, Data Flow in a Computer Chapter 4, Crafting an Interpreter – First StepsChapter 5, A Little More PythonChapter 6, TC1 Assembler and Simulator DesignChapter 7, Extending the TC1 Chapter 8, Simulators for Other Architectures