30 KiB
Universidade de Programação em Baixo Nível
Nota 1: Por favor, não copie o conteúdo dessa página para o seu blog. Você pode compartilhar essa página, mas, por favor, compartilhe com o link original. Essa é a forma que nós elogiamos os autores de bons documentos e projetos open source.
Nota 2: Por favor, note que programação de baixo nível está fora de moda e atualente não há muitas companhias contratando desenvolvedores de baixo nível. Está ficando mais difícil para eu encontrar um trabalho. Se você ainda não começou a sua carreira profissional, eu recomendaria considerar outros campos cuidadosamente.
Nota 3: Se você quer ir direto ao ponto, vá para Como começar?.
Sumário
- O que é esse repositório?
- O que é programação de baixo nível?
- Teoria
- Linguagens
- Aplicações
- Futuro da programação em baixo nível
- Como começar?
- Traduções
- Quem eu sou?
O que é esse repositório?
Eu me inspirei na google-interview-university. Eu gostaria de compartilhar minha experiência e um roteiro de como se tornar um programador de baixo nível porque acredito que essas habilidades não são tão comuns quanto antigamente. Além disso, muitos iniciantes e estudantes me perguntam como poderiam se tornar desenvolvedores de baixo nível e engenheiros do kernel Linux.
Essa página não inclui todos os links, livros ou cursos. Por exemplo, essa página introduz Arduino, mas não tem informações detalhados sobre Arduino de sistemas embarcados. Você deve se aprofundar por si mesmo. Você tem a palavra-chave "Arduino" para começar, então seu próximo passo é provalmente pesquisar sobre Arduino, comprar um kit e fazer alguma coisa você mesmo, e não colecionar links e livros. Por favor, lembre que essa página é apenas um roteiro para iniciantes.
Programação de baixo nível é uma parte de Ciências da Computação, de tal forma que, é certamente muito melhor ter esse conhecimento primeiro.
O que é programação de baixo nível?
Eu classifico programação de baixo nível como uma programação que é muito próxima da máquina. Usa-se uma linguagem de programação de mais baixo nível, como C ou assembly, diferentimente de linguagens de programação de alto nível, típicas de aplicações do espaço de usuário, como Python ou Java.
Sim, o conceito de programação de sistemas é bem próximo do de programação de baixo nível. Esse roteiro inclui o desenvolvimento de hardware e firmware que não estão inclusos no desenvolvimento de sistemas.
Finalmente, esse roteiro inclui tópicos indo de componentes de hardware até o kernel Linux. Isso é uma variedade enorme de camadas. Um documento de uma página nunca conseguiria cobrir detalhadamente todas elas, então o foco deste é servir de ponto inicial para programação de baixo nível.
Teoria
Existem dois conhecimentos teóricos para se programar em baixo nível:
- Arquitetura de Computadores
- Sistemas Operacinais
Acredito que a melhor maneira de aprender teoria é fazendo um curso. Ler livros não é ruim, mas consome muito tempo e esforço. Você pode achar várias aulas em univerisades online, por exemplo: Coursera e edX.
Teoria é teoria. Eu não acho que você necessite de uma 10 em uma matéria, apenas entenda seu conteúdo geral; você evoluirá com experiência.
Irei apresentar vários livros que li. Eles são comumente usados como livros-texto em universidades. Se não existe uma matéria com esses livros na sua universidade, vale a pena gastar um pouco de tempo os lendo.
- Arquitetura de Computadores
- Organização e Projeto de Computadores, 5ª edição. HENNESSY, John. 2021.
- Arquitetura de Computadores: Uma Abordagem Quantitativa, 6ª edição. HENNESSY, John. 2019.
- Computer Systems: A Programmer's Perspective, 3rd Edition. BRYANT, Randal; O'HALLARON, David. 2015.
- Sistemas Operacionais
- The Magic Garden Explained: The Internals of UNIX System V Release 4 an Open Systems Design. GOODHEART, Berny; COX, James. 1994.
- The Design of the UNIX Operating System. BACH, Maurice. 1986.
- Operating Systems: Internals and Design Principles, 9th Edition. STALLINGS, William. 2017.
- Adicionado pelo tradutor: Operating Systems: Three Easy Pieces. ARPACI-DUSSEAU, Remzi H.; ARPACI-DUSSEAU, Andrea C.. E-book online e gratuito sendo mantido atualizado constantemente. Se encontra na versão 1.10 no momento do lançamento desta tradução.
- Cursos Recomendados
- Habilidades Gerais de Programação
- Structure and Interpretation of Computer Programs
- É sobre como se tornar um bom desenvolvedor de softwares. Você precisa de não somente teoria, mas também técnica, pois programação é como um trabalho artesanal.
- Se você aprender Lisp/Scheme, você deve ser capaz de aprender qualquer outra linguagem rapidamente.
- Eu resolvi 80% dos exercícios e vale a pena tentar cada um deles.
- Structure and Interpretation of Computer Programs
- Design de Hardware
- Faça seu próprio kit do microprocessador 8086.
- Se você não fizer seu próprio hardware, você não entenderá o que é um dispositivo físico de memória mapeada.
- Pontos de acesso modernos incluem muitos IPs, então você não tem a chance de entender como a CPU e os periféricos estão conectados.
- Fazendo seu próprio kit 8086, você tem uma oportunidade de colocar cada dispositivo periférico na memória física e definir como os componentes de hardware principais (barramentos, interrupções do sistema, clock, alimentação, etc.) funcionam com seus próprios olhos.
- Eu montei o meu kit na universidade. Foi uma das mais valiosas atividades que eu fiz. Tente fazer seu próprio kit, sendo melhor que o hardware seja mais velho e simples, porque deve lhe dar mais trabalho.
- Pesquise "kit 8086", você deve achar alguns sites em que pode comprar uma esquema de hardware, partes e manuais.
- Faça seu próprio kit do microprocessador 8086.
Existe uma lista infinita de bons livros, e eu não quero dizer que você deve ler todos; leia um com cuidado: fazendo marcações, anotações e pesquisas. Sempre que aprender uma teoria, implemente um código simulando isso. Implementar algo é melhor do que saber 100 teorias.
Linguagens
Assembly
Escolha uma entre x86 e ARM, não precisa saber as duas. Não importa tanto saber assembly a princípio, o essencial é entender o funcionamento interno de uma CPU e um computador, logo não há necessidade de praticar com assembly das CPU mais recentes. Apenas escolha entre 8086 ou Cortex-M.
- 8086 assembly programming with emu8086
- conceitos básicos de arquitetura de processadores e computadores
- conceitos básicos de C TODO: check owner's response
- 64 bit assembly programming(translation in progress)
- conceitos básicos de arquitetura de CPUs e computadores modernos.
- conceitos básicos de disassembling e debugging em C
- need help for translation
- Learning assembly for Linux x64
- programação em puro assembly 64 bits com NASM e inline assembly com GCC
- ARM Architecture Reference Manual, 2nd Edition
- referência completa em programação ARM
- Organização e Arquitetura de Computadores
- MIPS Edition
- ARM Edition
- RISC-V Edition
- estes são livros acadêmicos que explicam como cada componente do computador funciona desde o começo
- explicam em detalhe os diferentes conceitos que compõem a arquitetura de computadores
- o público-alvo não são leitores que desejam desejam proficiência em assembly
- a versão MIPS e ARM cobrem os mesmos tópicos, mas dissecando as diferentes arquiteturas
- ambas edições contêm exemplos no universo x86
C
Aqui não existe atalho: leia o livro todo e resolva todos os exercícios.
- C Programming: A Modern Approach, 2nd Edition
- The C Programming Language, 2nd Edition
- Modern C: Jens Gustedt. Modern C. Manning, 2019, 9781617295812. ffhal-02383654f
- nova convenção/novo padrão de C
- Is Parallel Programming Hard? And If So, What Can You Do About It?
- implementação real de sincronização em C
- essencial para programas C de larga escala (especialmente kernels)
- Projetos em C
- se você leu um ou dois livros sobre C, então você DEVE programar algo
- escolha qualquer coisa que lhe agrade
- primeiro faça o seu e depois compare com o código de outra pessoa
- é muito impotante comparar seu código, pois você só melhora suas habilidades quando você vê o código de alguém e aprende métodos melhores
- livros são mortos e códigos são vivos
- Projetos em C e em outras linguagens
- mais projetos interessantes
- Michael Abrash’s Graphics Programming Black Book, Special Edition
- referência em otimização usando C e assembly x86
- começa do 8088 até hoje em dia
- foco especial em otimização de gráficos em baixo nível
- Frameworks e plugins em C
- como desenvolver frameworks e plugins em C para programas de larga escala
- dicas bem básicas sobre como ler o kernel Linux
Se quiser ser um especialista em C, visite LeetCode. Boa sorte!
Rust
Tenho convicção que a próxima linguagem para programação de sistemas vai ser Rust. Farei uma lista do que fiz para aprender esta linguagem.
Linus Torvalds sobre entrada do Rust na versão 6.1 do Linux.
- The Rust Programming Language
- livro online e gratuito da própria Rust Foundation
- boa introdução, mas falta exemplos e exercícios
- Rust by Example
- enquanto lê o livro anterior, você pode encontrar exemplos aqui
- não há muitos exercícios, mas você pode fazer alguma coisa você mesmo
- Adicionado pelo tradutor: Rustlings
- repositório da própria Rust Foundation contendo alguns exercícios e com indicação de acerto ou erro
- Programming Rust, 2nd
- introdução mais aprofundada, porém ainda com falta de exercícios
- Exercism
- bons exercícios para praticar características individuais da linguagem
- não tenho certeza se os Mentors estão trabalhando ativamente, mas comparar sua solução com a de outros deve ser o suficiente
- depois de submeter sua solução, você pode ver a solução de outros na aba "Community Solutions"
- vários exercícios de nível fácil são voltados para o aspecto funcional da linguagem, usando métodos como:
map,filterefold
- Easy rust
- um livro escrito em um inglês simples e com material adicional no YouTube
- Let's Get Rusty
- há muitos youtubers fazendo cursos de Rust, mas esse foi o meu preferido
- ele também tem upado vídeos sobre as últimas notícias envolvendo Rust, então acredito que valha sua inscrição
- Adicionado pelo tradutor: Rust for Rustaceans: Idiomatic Programming for Experienced Developers. GJENGSET, Jon. 2021.
- livro de um ex-mantenedor da insfraestrutura em Rust da AWS
- atualmente fazendo uma pesquisa relacionada a um banco de dados escrito em Rust
- comumente faz lives no YouTube cobrindo tópicos como detalhes de implementação da biblioteca padrão do Rust, contribuindo para projetos de código aberto ou desenvolvendo algum projeto próprio
- este livro é um complemento para quando você já conhecer um pouco melhor a sintaxe e como programas são escritos em Rust; ele NÃO é um livro para iniciantes na linguagem
- Rust for Linux
- veja os exemplos e dê uma olhada em como Rust entrou no kernel Linux
Applications
Hardware && Firmware
If you want to be an embedded systems engineer, it would be best to start from a simple hardware kit, rather than starting with the latest ARM chipset.
- Arduino Start Kit
- There are many series of Arduinos but "Arduino Start Kit" has the most simple processor(Atmega328P) and guide book
- Atmega328P has an 8-bit core which is a good place to start digital circuit design and firmware development.
- You don't need to know how to draw schematics and layouts and assemble the chips.
- But you do need to know how to read schematics and understand how the chips are connected.
- Firmware developers should be able to read the schematics and figure out how to send data to the target device.
- Follow the guide book!
- 8086 manual
- If you're a beginner to x86 architecture, 8086 is also very good guide for processor architecture and 80x86 assembly
- 80386 manual
- Best guide for protected mode and paging mechanism of 80x86 processor
- Web version: https://pdos.csail.mit.edu/6.828/2011/readings/i386/toc.htm
At this point, you should be good to start the latest ARM or x86 processor.
- https://www.raspberrypi.org/
- https://beagleboard.org/
- https://www.arduino.cc/en/ArduinoCertified/IntelEdison
For example, the Raspberry Pi board has a Cortex-A53 Processor that supports a 64-bit instruction set. This allows you to experience a modern processor architecture with rPi. Yes, you can buy it... but... what are you going to do with it? If you have no target project, you would be likely to throw the board into a drawer and forget it like other gadgets you may have bought before.
So, I recommend one project for you.
- Making your own kernel
- Good references: https://www.reddit.com/r/osdev/
- Learning operating system development using Linux kernel and Raspberry Pi
- (description of the project) This repository contains a step-by-step guide that teaches how to create a simple operating system (OS) kernel from scratch...(skip)...Each lesson is designed in such a way that it first explains how some kernel feature is implemented in the RPi OS, and then it tries to demonstrate how the same functionality works in the Linux kernel.
I've made a toy kernel that supports 64-bit long mode, paging and very simple context switching. Making a toy kernel is good way to understand modern computer architecture and hardware control.
In fact, you have already the latest processor and the latest hardware devices. Your laptop! Your desktop! You already have all that you need in order to start! You don't need to buy anything. The qemu emulator can emulate the latest ARM processors and Intel processors. So everything you need is already on hand. There are many toy kernels and documents you can refer to. Just install qemu emulator and make a tiny kernel that just boots, turns on paging, and prints some messages.
Other toy kernels:
Linux kernel and device driver
You don't need to make a complete operating system. Join the Linux community and participate in development.
Some resources for Linux kernel and device driver development from beginner to advanced.
- Books: Read the following in order
- The Design of the Unix Operating System
- The basic concepts of Unix are applied into all operating systems.
- This book is a very good place to learn the core concepts of operating systems.
- Linux Device Drivers
- Make all examples for yourself
- Linux Kernel Development
- Understand the design of the Linux Kernel
- Understanding the Linux Kernel
- Read this book and the kernel source v2.6 at the same time
- Never start with the latest version, v2.6 is enough!
- Use qemu and gdb to run the kernel source line by line
- Use busybox to make the simplest filesystem that takes only one second to boot
- The Design of the Unix Operating System
- Other resources: Free resources I recommend
- Linux device driver labs
- Practical guide and excellent exercises making Linux device drivers with essential kernel APIs
- I think this document introduces almost all essential kernel APIs.
- The Eudyptula Challenge
- Sadly, this challenge does not accept new challengers because there is no challenge anymore. The maintainer said he/she is planning a new format. I hope it comes back ASAP.
- But you can find the questions of the challenge with Google. Some people already uploaded what they did. Find the questions and try to solve them on your own, and compare your solution with others.
- This is like an awesome private teacher who guides you on what to do.
- If you don't know what to do, just start this.
- Sadly, this challenge does not accept new challengers because there is no challenge anymore. The maintainer said he/she is planning a new format. I hope it comes back ASAP.
- Learning operating system development using Linux kernel and Raspberry Pi
- This project is not completed yet.
- I always think making a kernel similar to the Linux kernel is the best way to understand the Linux kernel.
- Block layer and device driver
- start from a simple block device driver example (Ramdisk) with multi-queue mode
- go forward to block layer
- I completed translation into English. Please send me your feedback.
- md driver of Linux kernel(Korean)
- how mdadm tool works and how it calls md driver
- how md driver works
- A Heavily Commemted Linux Kernel Source Code
- Heavy comments for the ancient Linux v0.12.
- It would be good to start with old and simple OS.
- Unix version: Lions' Commentary on UNIX 6th Edition, with Source Code
- Linux device driver labs
References
Check when you need something
- Free-electrons homepage
- many slide files introducing good topics, specially ARM-linux
- Julia Evans's posting: You can be a kernel hacker!
- guide to start kernel programming
Other application
Yes, you might not be interested in Linux or firmware. If so, you can find other applications:
- Windows systems programming & device drivers
- Security
- Reverse engineering
I don't have any knowledge about those applications. Please send me any information for beginners.
Kernels and drivers are not all of low-level programming. One more important application of low-level programming is the software-defined storage or distributed filesystem. Detailed descriptions of them is beyond the scope of this document but there is an excellent course where you can try a simple distributed filesystem.
- Course: https://pdos.csail.mit.edu/archive/6.824-2012/
- reference Source: https://github.com/srned/yfs
Future of low-level programming
I do not know the future, but I keep my eye on Rust.
If I could have one week free and alone, I would learn Rust. That is because Rust is the latest language with which I can develop Linux device drivers.
IoT is new trend, so it's worth to check what OSs are for IoT. ARM, Samsung and some companies has their own realtime OS but sadly many of them are closed source. But Linux Foundation also has a solution: Zephyr
Typical cloud servers have many layers; for instance, host OS, kvm driver, qemu process, guest OS and service application. A container has been developed to provide light virtualization. In the near future, a new concept of OS, a so-called library OS or Unikernel, would replace the typical stack of SW for virtualization.
Big data and cloud computing require bigger and bigger storage. Some disks directly attached to server machines cannot satisfy the required capacity, stability and performance. Therefore there has been research to make huge storage systems with many storage machines connected by a high speed network. It used to be focused on making one huge storage volume. But currently they are providing many volumes dedicated for many virtual machines.
- https://en.wikipedia.org/wiki/Software-defined_storage
- https://en.wikipedia.org/wiki/Clustered_file_system
- https://en.wikipedia.org/wiki/Ceph_(software)
How to start?
I received an email asking how to start. There are many information about books, courses and projects in this page. It is my mistake to forget to write how to start. Unfortunately, there is no King's Road to King's Landing. I will just write what I did in order. If you have already done something, please skip it. AGAIN, this is just an example that you could do in order, just in case if you do not know how to start or what to do.
- Reading OS theory books: at least "The Design of the UNIX Operating System by Maurice J. Bach"
- Learn assembly and C
- 8086 assembly programming with emu8086
- It is enough if you understand the concept of assembly programming. You do not need to do something practical.
- The C Programming Language 2nd Edition
- DO YOUR BEST TO solve every single exercise!
- C Programming: A Modern Approach, 2nd Edition
- 8086 assembly programming with emu8086
- Do something practical with C
- C Project Based Tutorials?: Find one or two interesting projects and make your own project.
- leetcode.com: If you cannot find an interesting project, it would be also good to focus on data structure and algorithm.
- Do a hardware project
- Raspberrypi or Arduino does not matter. You need experience to control a hardware directly with only C. ONLY C!
- I recommend to buy a Atmega128 kit and make a firmware to turn on/off LEDs, detect switch input and display message on the text LCD. Motor control program is also a very good project: for instance, the line tracer.
- DO NOT use any library. You should make everything on your own, except program downloader.
- Basic of the Linux kernel
- Low-level programming is very close to the operating system. You should know inside of the OS.
- Start with drivers
- Read Linux Kernel Development to understand the internal of Linux kernel.
- Go to the professional field
- If you want to be a professional Linux Kernel Developer
- must read Understanding the Linux Kernel
- Then try to make a toy kernel
- Learn operating system development using Linux kernel and Raspberry Pi
- Making your own kernel
- Write the github link to your kernel on your resume (Don't forget to write the detailed description in commit message)
- Check the latest issues at https://lwn.net/ and join it.
- Check "Recent kernel patches" at "https://lwn.net/Kernel/" or direct link https://lwn.net/Kernel/Patches
- Find an interesting patch to you. Try to understand the source code. Of course it would be really difficult but try. You will be closer and closer whenever you try.
- Build kernel and test it on your system. For example, performance test, stability test with LTP(https://linux-test-project.github.io/) or static code analysis tools inside of kernel.
- Report any problem if you find any: compile warnings/errors, performance drop, kernel panic/oops or any problem
- If it works well, report that with the spec of your system. The patch owner would write a "Reviewed-by" tag with your name.
- Find your name in kernel git log
- must read Understanding the Linux Kernel
- Or find other topics
- There are many fields where the low-level engineer can work: security, Compiler, Firmware, robot/car and so on
- If you want to be a professional Linux Kernel Developer
Translation
Please send me the pull request if you'd like to translate this page. I'll list it here.
- Chinese(Traditional)
- Chinese(Simplified)
- Portuguese (Brazilian)
- Italian
- Czech
- Russian
- Turkish
- Persian
- Spanish
Who am I?
I'm inspired by google-interview-university. I'd like to share my experience and show a roadmap to becoming a low-level programmer because I have found that these skills are not as common as they once were. In addition, many students and beginners ask me how they could become low-level programmers and Linux kernel engineers.
FYI, I have over 10 years of experience as a low-level programmer:
- 80x86 Assembly programming
- Hardware device with Atmel chip and firmware
- C language system programming for Unix
- Device driver in Linux
- Linux kernel: page allocation
- Linux kernel: block device driver and md module