17/12/2024

The real «Hello World» from embedder (1): preface, theory

Chapter 1

Preface, theory 

Preface

Any learning process eventually comes up to some examples, some practice. In the case of software development, practice starts from so-called «Hello World». «Hello World» is the very first code every software developer on every platform, API, or framework should do on his very first days as his very first steps. Embedded software engineers are not an exception.

There is a lot of «Hello Worlds» out there on the Internet and in books. Those «Hello Worlds» are in any kind of programmings languages, APIs, and frameworks. But the vast majority of those «any kinds» are in pure software — Java, JavaScript, C++, etc. Thus, embedded software developers, those of them who want to study machine architecture, get in touch and play with it, suffer from a lack of examples — they have no starting point.

You can argue with that — there are examples in assembly language for all types of architectures, assembly language should let us study machine architecture and its behaviour. Yes, there is a lot of examples in assembly language, but those examples are for very high (more precisely — top) levels of runtime environment — Linux and Mac user-space. This approach to learning machine architecture doesn't lead to understanding of how it works and how it is organised.

Actually, it gives us a very narrow slit to machine architecture. Even in kernel-space, we are very limited in abilities to learn the machine. That's because all the hardware initialisation is already done for (and before) us by bootloader and kernel itself. The second problem is so-called «concepts and abstractions of operating systems». Those «abstractions» hide a lot of machine architecture from us while «concepts» arise a lot of software that serve an OS itself and make it what it is from user's point of view. Thus, even working in kernel-space, we learn more about these concepts and principles rather than about a machine.

Let's go on and discuss our last chance — MCUs (Micro-Controller Unit), which are cheap, popular, easy to start up and do let us be as close to the machine as possible. MCUs always had a crucial difference with full-fledged CPUs and SoCs (System on Chip) — they have no MMU (Memory Management Unit) and usually are single-core ALUs. After the beginning of the ARM64-era — the times when not only phones and tablets but also desktops (and even servers) and laptops are running on ARM64, MCUs eventually have got another one drawback ARM32 (the most common architecture of worth anything at all MCUs) architecture became outdated even as a single-core platform for studying. Now we are living in the days when it's almost useless to learn ARM32 architecture. It's more a waste of time because the difference between actual and almost omnipresent ARM64 and rapidly becoming obsolete ARM32 is enormous.

Thus, we come to the point where we need a comfortable, big enough window (let's say — better a door or a nice gate) to the machine that represents modern ARM64 architecture. Usually it is done by programming for an emulator. Developing for an emulator is like a game because of its abstraction. Games (and gaming) give you minimal or even zero risks by the price of insignificant wins. To get real valuable practice and results, as well as satisfaction, we need a real «Hello World» on real hardware.

Learning a machine architecture (and its behaviour) is done by so-called «Bare Metal» development. «Bare» means that we are working on a machine without an OS, without a kernel, and even without a bootloader. Actually, we develop code that works instead of a bootloader or runs where and when the very first part of user bootloader (SPL — Second Platform Loader) usually does. «Metal» stands for hardware or machine and means that we work on a real hardware — not a virtual machine or an emulator.

In these topics we'll cut a good window for studying modern ARM64 machine. This will be the «Hello World» from embedded engineer and a nice toy for embedded developer.

Theory

Let's start with a little overview of a computing machine, specifically about its heart — CPU or SoC. SoC provides a set of functions (functionalities); each functionality is provided by an according and separate hardware-block. Thus, SoC consists of hardware-blocks or represents a set of hardware-blocks. Each hardware-block is driven by a clock; each clock is derived from PLL, Phase Lock Loop — a small circuit that generates one or more frequencies from an input clock source — an oscillator. So, turning a hardware-block on, besides powering it, is just enabling the clock it is connected to. Actually, you will not find such element like «clock» on your board. «Clock», as an element — is just a concept of embedded developers. Really, «clock» — is one of the outputs of PLL, which can be enabled or disabled by software. Real clocking sources are oscillators and outputs of PLLs. You can see overview of clock generating scheme below.

Clock generating scheme

But enabling clock is not enough to start using functionality of hardware-block. In most cases there are two more things. The first — usually, SoCs provide more functionalities than they have pins, or, in terms of embedded software, more often we say — pads. It leads to so-called «alternative function» (AF) concept. This means that some pads, as we say in software theory — can be configured to specific (alternative) function — I2C SDA or UART TX, for example. Configuring of AFs is done by Input/Output Multiplexing Controller (IOMUXC) or, more commonly called Pin Multiplexer (PINMUX). PINMUX is a built-in hardware-block. So, it has to be turned on (clocked) too, like other hardware-blocks. From the hardware point of view, PINMUX simply routes signals from SoC's pads to inputs/outputs of specified internal hardware-block — to I2C bus controller or to UART controller in example above. In other words, PINMUX switches signals between hardware-blocks inside of a SoC on one end and SoCs pins/balls (or pads) that we can see on the chip package. You can see example of alternative functions multiplexing scheme below.

Alternative functions multiplexing scheme

Second thing is configuration of hardware-block. This is done by code. After hardware-block is clocked (enabled) it stays in some default condition. We need to write specific values to specific registers to make it function according to our needs.

Clocks for hardware-blocks and corresponding PLLs are enabled by code. Hardware-blocks are configured by code too. But no program can run on a non-clocked CPU. So who and how starts the main PLLs and clocks that drive the ALU? This functionality is hardcoded into so-called BootROM, or BROM. BROM is microcode of SoC itself; it is located inside SoC. BROM initialises the essential hardware minimum required to start user code. It starts up a minimal amount of hardware-blocks and after that performs as FPL (see below). BROMs are very different in functionality — some of them just start code from built-in memory, not even loading it into RAM (like BROMs of MCUs do), some of them initialise a bunch of hardware-blocks and can even operate filesystems (like BROM of Raspberry's Broadcom does). The most common condition BROM leaves SoCs in is: one ALU core is started, SRAM (or OCRAM — OnChip RAM) initialised, and one of the boot sources initialised. Initialisation of the rest functionality is left for user code.

Any SoC uses its own, proprietary FPL (First Platform Loader). FPL is a part of BROM we've discussed earlier. To run our code on a SoC we need so-called «boot image», which is made out of our code. We need to say few words about contents of boot image. It is not a regular file we get from compiler. And the architecture mismatch is not the only reason. Usually compiler builds ELF (Executable and Linkable Format) file. ELF-file contains a lot of extra information which is used by OS or some other environment code is run in. For example, ELF-file can include debug information, symbol names, etc. But while working on bare-metal we have to get rid of all OS-specific, debug and other environmental information. This is because SoC will execute raw code only and treat any data as straight, linear stream of code (with some addition of data). Bare-metal needs raw code to function correctly. If we try to load whole ELF-file as a bare-metal application, most probably we'll get some kind of illegal instruction exception because that extra information in ELF-file will not match with correct instructions codes. The process of making raw code, or raw binary from ELF-file is called stripping.

Now, let's proceed with FPL. Any FPL expects boot-image in a specific format and in a specific place. Thus, after we've compiled our source code to (set of) object files, linked that objects into single binary, and stripped it down to pure machine code, we have to pack it and make it comply with specific requirements of a particular SoC and its BROM. This is done by a tool, which usually is named «mkimage», sometimes like «mkimage_XXX», where XXX is replaced by the name of SoC or the name of a family of SoCs. Usually, mkimage adds some headers, which BROM reads, and sometimes CRCs, to machine code. BROM uses this information to verify the boot image. Then we have to put this image in a particular place — usually on a SD-Card or eMMC with some offset from zero. Offset is needed to make bootable media also usable as storage media — it leaves space for partition table and filesystems.

This is what we have about hardware. Let's proceed to software. There's not too much to do and discuss here. We can work in assembly language forever — this is interesting and can be useful. By limiting ourself to assembly language only we can omit using stack. But anyway, at some point we want to dive out into C-code. At this point we'll need stack because C-compiler will use it intensively. Thus, we have to initialise it — that's all we need to know at the moment. Initialisation of the stack is done by setting the stack pointer register to a value representing a valid memory address. Stack (more often) grows down, so we have to choose an address for it according to its behaviour — to prevent it from touching the bottom of RAM and from destroying our application in case it is set above. And, of course, we can't set it higher than the top of accessible RAM.

Now let's proceed to our specific task. Let's say we want to make our SBC (Single-Board Computer) output a «Hello World». How can we do that? Let's confess that outputting (drawing) strings on a display is a little complicated task for a bare-metal beginner. So we'll output our «Hello World» via the most common debug interface all over the world — UART. UART functionality is provided by a particular hardware-block. So we need to start clocking that hardware-block, set its pads and configure it.

First, to enable a clock for UART we have to know which clock exactly we need to enable on the exact SoC. As we mentioned earlier, every clock is derived from a particular PLL. Hence, we need to find out what PLL provides the clock we need. All this information is presented in a datasheet and is rigidly tied to a certain SoC. The second part is to set AF — to configure pads for UART — its TX and RX. Here we need to turn on PINMUX (PLL, clock) and configure pads we need to functions we need. And the last part — configuration is done by writing values to a memory location mapped to an address of hardware-block — PINMUX (pads) and UART (baud rate, parity, etc.) in our case. What configuration must be written is described in a datasheet and, again, is rigidly tied to a certain SoC.

After writing this code we have to compile, link and strip the resulting file to raw machine code, make boot-image by forming out BROM header and adding it to machine code we've got on the previous stage. Then put our boot-image to specific place on a specific media and power on SBC.

Theory ends at this point. In the next part, we'll choose specific SoC, gather information needed to design the «Hello World» for the chosen SoC. With this information we will form out the plan of steps for third part.

28/07/2024

Kernel-Space: asm _ko Hello!

Long time no see, confreres.

This time we will do some crazy (or maybe even mad) things.

As we all know, Linux kernel is a cross-platform software. It supports a very large variety of hardware platforms. Thus it’s written in the most «inter-platform» language in the world — Plain C. The secret of cross-platformness is a compiler used to build the kernel itself and its modules. Exceptions are small parts that provide the only hardware specific functionality that cannot be written in C — SoCs/CPUs start-up and configuration routines. These small parts of kernel are written in assembly languages.


But today I’ll present some sort of skeleton of the whole kernel module written in assembly language — not a single .c-file is used. I had this idea for a long time, I’ve searched the Internet a lot of times for some examples or at least a starting point or a discussion. But had no luck — no examples for ARM nor x86 or any other architecture. This fact proves the craziness of my idea (possibly also it explains why you should not do this in your practice). But I’ve managed to do this.


This module’s functionality will be limited to some kind of «Hello World» — it will be able to be loaded and unloaded correctly and do the only thing — print messages on these events. I’ve mentioned that no .c-files are used in this module, but this module looks like a usual kernel module (except the language it is written in) and is built and works like any other module — thus it is a regular code which you can work with like your everyday routine — no any sort of magic nor discomfort. We will talk about ARM64 (or AArch64) but it can be easily rewritten for any other architecture.


I said that there is no magic in this module, but… we know that any object file must have some sections, information and has to be built — compiled and linked according to strict rules. Kernel module is no exception. That was the «magic» I had to reveal to achieve the goal of my idea — regular-looking and developer-friendly kernel module in assembly language.


There is a lot of «magic» in kernel build system. But my idea was to write a template of a kernel module that will look, feel, act and work like a regular one, as regular part of kernel source tree. Thus today we will not talk about kernel’s build system, differences between linking user-space objects and linking kernel-space objects — but about template of a kernel module in assembly language only (and Makefile for it, of course). Building — compiling and linking will be done by standard kernel build system.


Kernel module project consists of two parts — Makefile and source code. Let's start with Makefile. Everything is clear enough here — you just set source file name to your assembly (.s or .S) file and set obj-m variable. That's all — the rest of the job will be done by kernel build system. Here is our Makefile:


ifeq ($(KERNEL_SRC),)
$(error Specify KERNEL_SRC directory)
endif

export ARCH := arm64
export CROSS_COMPILE ?= aarch64-linux-gnu-
PWD := $(shell pwd)

PROJECT_NAME := asm_ko_hello
$(PROJECT_NAME)-src := $(PROJECT_NAME).S
obj-m += $(PROJECT_NAME).o
AFLAGS_$(PROJECT_NAME).o := -DPROJECT_NAME=$(PROJECT_NAME)

all:
	make -C $(KERNEL_SRC) M=$(PWD) modules

clean:
	make -C $(KERNEL_SRC) M=$(PWD) clean


Now, let's have a look at asm_ko_hello.S (capitalised extension means that this file will be passed via preprocessor):


#include "linux/kern_levels.h"

Here you can see something familiar to kernel modules you have worked with and guess that we will have standard levels of output and you are right — we will have all that standard KERN_XXXX output levels in our assembly code.

#if !defined (PROJECT_NAME)
	#error You must define project name for this template. Stopping build.
#endif

#define MAKE_FN_NAME(x, y) x##_##y
#define FN_NAME(project, func) MAKE_FN_NAME(project, func)


The above lines serve project's template and are not related to today's topic.

.section .text
FN_NAME(PROJECT_NAME, init):
	stp x29, x30, [sp, -16]!
	adrp x0, .loaded
	mov x29, sp
	add x0, x0, :lo12:.loaded
	bl _printk
	mov w0, 0
	ldp x29, x30, [sp], 16
	ret

FN_NAME(PROJECT_NAME, exit):
	stp x29, x30, [sp, -16]!
	adrp x0, .unloaded
	mov x29, sp
	add x0, x0, :lo12:.unloaded
	bl _printk
	ldp x29, x30, [sp], 16
	ret


This is the code of common «Hello World» kernel module. It is put into standard .text section. FN_NAME macro will produce functions names. And after go two functions bodies in standard/usual ARM64 assembly language. As you can see we preserve registers, load string address and call (in term of ARM it's called «branch with link») printk() function, restore registers and, in case of _init(), return value (which actually is an abstraction).

The code looks clear and familiar, but this is kernel module and there is a little difference with user-space program. We should let the system know where are the entry and leave points (or load/unload functions) of our module. In C it's done by two macros module_init() and module_exit(). In our case it would look like:

module_init(asm_ko_init);
module_exit(asm_ko_exit);


But how should we specify these functions in assembly language? What's covered under those macros? Actually nothing too complicated. We just need to declare global functions (symbols) init_module and cleanup_module. To give them proper payload (symbol itself is just a symbol in object file) we specify aliases to our _init() and _exit() functions with .set directive. The whole part of this code is in snippet below:

.global init_module
.global cleanup_module
.set init_module, FN_NAME(PROJECT_NAME, init)
.set cleanup_module, FN_NAME(PROJECT_NAME, exit)


We can't omit the .data section. This one is absolutely standard. Here is our section with strings used for our output:

.section .data
.unloaded:
	.string KERN_INFO MODULE_NAME": unloaded.\n"

.loaded:
	.string KERN_INFO MODULE_NAME": successfully loaded.\n"


There is something that the kernel will not accept our module without. This is something new for developers working in user-space and familiar for kernel-space developers. For Linux kernel we have to specify one mandatory parameter that cannot be omitted — the license. In C it is done by MODULE_LICENSE() macro and would look like:

MODULE_LICENSE("GPL");


Let's see how it is done in assembly language. Maybe you've expected something serious here — some special codes or sequences. But it's easy too — this is just .modinfo section containing information about module in a very simple (and unexpectedly ridiculous) format. See self-explaining snippet below:

#define MODULE_NAME	"Kernel Module in Assembly"
#define MODULE_VER	"1.0"
#define MODULE_AUTHOR	"Daft Soft, 2024"

.section .modinfo, "a"
	.string "author=" MODULE_AUTHOR
	.string "version=" MODULE_VER
	.string "description=" MODULE_NAME
	.string "license=GPL"


That's all about code. The repository is here. According to our Makefile, if you cross-compiler is aarch64-linux-gnu-, you build module as follows:

make KERNEL_SRC="PATAH/TO/YOUR/KERNEL/lib/modules/VERSION/build" clean all


Test it:

modinfo ./asm_ko_hello.ko  
filename:       ./asm_ko_hello.ko 
author:         Daft Soft, 2024
version:        1.0
description:    Kernel Module in Assembly
license:        GPL
srcversion:     48259120F9222D4D7B9D8E7
depends:         
name:           asm_ko_hello
vermagic:       6.1.55 SMP preempt mod_unload modversions aarch64

insmod ./asm_ko_hello.ko  
Kernel Module in Assembly: successfully loaded. 

lsmod 
Module                  Size  Used by 
asm_ko_hello           16384  0 

rmmod asm_ko_hello
Kernel Module in Assembly: unloaded.



P.S.
High level programming languages do a lot of job for developer and prevent a lot of mistakes. Actually not prevent but don't allow to make mistakes — you don't have enough tools to do most dummy things. When you write in assembly language in user-space it's a risk, but it's a funny walk in comparison to working in kernel-space. So you have to be extremely cautious working in assembly language in kernel-space because your any typo will be compiled and executed. For example, slight shift of stack pointer may lead to huge troubles — broken file system is a case. You have been warned — it's your decision how hard you wanna play.

18/10/2022

Оптимизация кода (1): О вызовах функций

Недавно я увидел следующую рекомендацию по рефакторингу кода с целью оптимизации:

Изначальный вариантОптимизированный вариант
return pow (base, exp/2) * pow (base, exp/2);let result = pow (base, exp/2); return result * result;

В книге было написано, что результатом такого рефакторинга будет увеличение скорости работы представленного участка кода. Но почему такой рефакторинг должен привести к ускорению работы этого кода? Большинство авторов/советчиков/специалистов не раскрывают суть своих советов и не дают понимания почему что-либо нужно делать так или иначе. Если вам интересно действительно ли здесь произошло ускорение работы и за счёт чего, то читайте — эта заметка для вас. В ней я рассмотрю, что происходит на вычислительной машине в данной ситуации, чем достигается результат, поясню как именно происходит оптимизация и дам информацию для некоторого понимания «масштаба» этой оптимизации. Пояснения в этой заметке раскрывают суть подобной оптимизации не только в данном случае — а в общем. Вы сможете применять это во множестве подобных ситуаций в вашей практике.

По синтаксису можно предположить, что представленный участок кода написан на JavaScript'е. Я же буду работать на общепринятых языках ИТ/ВТ — С, Aseembler x86_64 и стандартном ABI x86_64.

Для начала мы видим, что автор, ценой добавления ещё одной переменной, сократила вызовы функции pow () в два раза. Рассмотрим, что происходит при вызове функции pow (). Её прототип выглядит следующим образом:

double pow (double x, double y);

Из прототипа понятно, что функция работает с параметрами с плавающей точкой и возвращает такой же результат, а это значит, что она будет задействовать сопроцессор (FPU).

Сокращение вызовов функции pow () действительно даёт оптимизацию, и вот почему. Вызов любой функции требует ощутимых накладных расходов. Рассмотрим, что происходит на центральном процессоре при вызове функции в общем, и в частности при вызове функции pow (). В скобках, рядом с командами процессора, стоит приблизительное количество «циклов» (микроопераций) процессора на команду. Рассматриваем на примере x86-ой машины:

1. (При необходимости) вычисление или каким-то иным образом получение всех входных параметров, передаваемых функции (в данном примере это вычисление выражения exp/2). Здесь возможна работа с памятью (а она медленная) и вызовы других, вложенных функций. Если они есть, то стоит пройти все их начиная с этого же пункта.

2. «Раскладывание» параметров, вычисленных или полученных на предыдущем этапе в соответствии с ABI. После вычисления их, они могут оказаться в «местах» (память, регистры), не соответствующих сигнатуре рассматриваемой функции. Это некоторое количество команд mov (~1).

3. Вызов команды call (~10), которая, в свою очередь, сохраняет адрес возврата в стеке, затем осуществляет переход потока выполнения на (указанный адрес) рассматриваемой нами функции.

4. Сама функция pow (), как и любая другая, имеет в себе «преамбулу» (или «пролог»). В этой секции кода происходит сохранение регистров общего назначения путём выполнения нескольких команд семейства push, резервирование пространства в стеке для внутренних нужд функции несколькими манипуляциями с указателем стека. Напомним, что всё это уже происходит один раз в нашей, вызывающей функции.

5. Так как pow () работает с числами с плавающей точкой, она должна сохранить регистры и состояние сопроцессора — так называемую «среду сопроцессора», включающую в себя стек сопроцессора, регистры его состояния, управления, тегов, указатели данных и команд. Так же функция должна сбросить состояние FPU при входе, так как неизвестно в каком состоянии он будет к этому моменту. К счастью у нас есть простые команды для сохранения всей среды сопроцессора — fsave/fnsave (120-150 и более) и finit/fninit (15-20 и более) — для сброса его состояния. Как эти, так и описанные ниже команды восстановления среды FPU, достаточно тяжёлые, так как работают с достаточно большим объёмом информации — всей средой сопроцессора и с памятью (а она, не забываем, у нас — медленная).

6. pow (), вероятно, имеет множество проверок и инициализацию локальных переменных в своей реализации, а они нам здесь не нужны.

7. Реализация самих вычислений функции. При работе с FPU, есть вероятность необходимости вызова команды fwait — дождаться выполнения операции на FPU (на x86 FPU работает параллельно с CPU).

8. После завершения своей работы, функции нужно восстановить регистры FPU и его состояние (что так же уже, возможно, делается в нашей функции). Это команда frstor (~100).

9. В конце функции есть «эпилог», включающий в себя восстановление состояния стека — некоторые манипуляции с указателем стека и регистров общего назначения CPU при выходе — выполнение нескольких команд семейства pop.

10. По завершению вызывается команда ret (15-25), которая извлекает адрес возврата из стека и изменяет указатель текущей инструкции процессора на этот адрес. Таким образом, модуль выборки команд x86, после окончания обработки команды ret, начнёт загружать и выполнять команды с адреса, хранящегося в указателе текущей инструкции.

На ARM'е накладные расходы будут схожими.

Таким образом, мы видим, что основные накладные расходы, исключением которых достигнута оптимизация в этом примере, заключаются в управлении потоком исполнения, исключении некоторых проверок, встроенных в вызываемую функцию (что, в данной ситуации, нужно лишь для вычисления значения, которое уже есть).

Но есть и ещё один нюанс. Мы никогда не знаем сколько раз операционная система переключит контекст нашего приложения (в данной ситуации — функции), пока оно работает. А любая, современная операционная система работает по принципу вытесняющей многозадачности. Следовательно, чем меньше список команд, требуемый для получения результата — тем больше вероятность, что наш код будет прерван меньшее количество раз — наша задача будет делиться на меньшее количество квантов выделяемого времени. В критических ко времени вычислениях, когда результат зависит от внешних обстоятельств, например — поток данных, приходящих по сети, такая оптимизация может глобально улучшить результат работы приложения (либо и вовсе спасти код/алгоритм от признания непригодным).

Из этого можно сделать вывод, что такая оптимизация особенно желательна в критичных местах — в «верхних половинах» kernel-space (там лучше вообще не делать никаких вычислений, но мы рассматриваем оптимизацию через сокращение количества вызовов функций в общем), в обработчиках прерываний на Bare-Metal/RTOS.

Теперь опишем, что происходит в оптимизированном варианте. Умножая, в данной ситуации, число само на себя, без вызова функции, мы всего лишь пишем одну команду из семейства fmul, которая в упрощённом варианте (при правильном использовании) умножает два верхних регистра FPU и кладёт результат в самый верхний — ST(0). Который по правилам ABI x86_64, в свою очередь, является возвращаемым значением функции, работающей с числами с плавающей точкой. А если мы пойдём дальше, и сами будем писать код этих операций, то мы сделаем так, чтобы к моменту этого умножения, у нас операнды были уже в двух верхних регистрах FPU, в правильной последовательности. Вот какая оптимизация происходит — практически автоматическая работа процессора на нас.

Кто-то может возразить, что x86-ая машина имеет множество оптимизаций и, что, благодаря им, многие операции из рассмотренного участка кода будут выполнены в параллель, на опережение, или вовсе опущены. Да, это так. Но зачем нам грузить вычислительную машину лишними операциями, когда мы можем избежать их на этапе написания кода? Пусть она использует свои возможности для оптимизации чего-то другого.

P.S.
По описанным выше причинам, предостерегу вас от достаточно очевидного манёвра с этим участком кода. А именно, использовать вместо умножения вызов всё той же функции pow () с result в качестве первого параметра и двойкой — в качестве второго. Умножение числа на само себя — есть возведение его в квадрат. Математически и идеологически, кому-то это может показаться правильнее или «красивее», но технически — правильнее так, как мы рассмотрели. В противном случае это будет «пример плохого кода».

P.P.S.
А вот, например, сократить количество машинных операций, передавая в функцию выражение exp/2 вычисленное заранее извне — хороший вариант. Во-первых, внутри функции не будет заниматься лишнее место на стеке (для проведения этой операции). Во-вторых, при множественном вызове такой функции, с одинаковым значением какого-то из параметров, сократится время на вычисления — он будет вычислен единожды в вызывающей функции и затем повторно использоваться. А если у нас exp/2 будет равно двойке, то и вовсе проще дважды умножить base на себя и выйти, вернув этот результат.

05/01/2022

System concepts (1): BSS — long forgotten but still ever-present

Preface

In this post we'll take a look at one interesting concept of modern operating systems — BSS. Possibly, some of you have not heard of it at all; some of you may think of it as of some sort of ancient thing and suppose it is not used these days. In first part of this post we will examine the purpose it was ever invented for. In second part we'll show how it is used these days ubiquitously even if you don't know about it.

The purpose of BSS

Historically, BSS stands for «Block Started by Symbol» or «Block Starting Symbol». Technically, BSS is a section of data in (object or executable) file. If it is a section, you may suppose we can declare it in the assembly language with .section directive. Well, that's right. Let's do it.


.section .bss .lcomm var, 1 #1000 .global main .text main: xorq %rax, %rax retq

By the way, modern assembly translators do not require keyword .section — .bss is enough. 

Let's explain what is done here. We declared .bss section with a variable named var in it with a parameter 1 (which may look like a value, but it is not). Compile and look at the resulting a.out, it's size in my case (Linux/GCC) is 16496 bytes. Now we change the parameter 1 to 1000, for example. Compile and look at size of a.out — it remains the same. «What kind of magic is that?!» It's «white» magic and now it's time to explain the whole thing. BSS was invented to save space on disk (or other storage or network bandwidth). And, yes, it's really that «ancient» invention — it originates to the 1950s. You can use it in cases when you don't need to specify values of storage area (variable), for example — to declare buffers which you will write to later, at runtime. You see that variables in .bss are declared in a different manner. It has no .globl directive — it uses .lcomm/.comm instead to specify its visibility. .lcomm stands for local module visibility, while .comm — for global (some sort of .globl directive). The parameter (1, 1000 in our case or whatever you want) is the size of the buffer. How it works? Linker writes symbol with variable name and address and count of bytes in resulting module. At runtime .bss variables are expanded in memory to specified size and (while it's not standard, usually) initialised with zeroes.

The opposite way to declare zero-filled array is to use .fill directive on regular variable in .data section — in this case all zeroes will be written to resulting module increasing its size. I'll omit this example here, but you may check it by yourself:


.data big_var: .fill 1000000

At this moment you may think — «This is a good idea. But could I use it to optimise my high level language programs with this knowledge?». I've had the same thoughts and have checked it. The answer is «yes», moreover — you already do this often. Here starts the second part of our little research.

Use of BSS these days

The short receipt is — just declare your variables as global arrays and initialize them as { 0 }. Let's prove it:


char lBSSVar[1] = { 0 }; int main () { return 0; }

Compile and check the resulting file size. For example, on my machine a.out is 16496 bytes (same size as a.out I've got from assembly language code). Now change the size of lBSSVar to 1000, recompile and see the size of a.out is not changed.

Let's see if it is BSS or something else by examining assembly code we get of our C-code:


.globl lBSSVar .bss .align 32 .type lBSSVar, @object .size lBSSVar, 1000 lBSSVar: .zero 1000

We see in this list (I've posted here the part that we are interested in only) that compiler made .bss section from our C-code. Syntax differs from my raw assembly example but technically idea is the same.

Conclusion

The idea to save space in object files I've demonstrated in this post is really old. But as we see in the last list syntax may differ. For example, clang uses .zerofill directive to describe uninitialised buffers. Thus different compilers may use different syntax. So, in my opinion, if you code your application in raw assembly language you can use syntax I've shown in first part of this post — it is a short way to use BSS idea. Second part of this post lets you know how to declare buffers you don't need to initialise in high-level languages saving some extra space on storage devices and a little time on loading it.

16/09/2021

Маленький взлом системы (2): заставим процессор выполнить переменную

В предыдущей статье (Маленький взлом системы (1): наконец-то вы сможете изменять строки типа char* String) мы рассмотрели как можно писать в область памяти, в которую запись запрещена. Сегодня мы разовьём эту тему и попробуем выполнить переменную.

N.B.
Всё, что описывается в этой статье — это строго про x86-ую машину. Если вы попытаетесь проделать это на другой архитектуре, то ваш процессор сгорит!

Начнём с подготовительных работ. Как и в прошлый раз, нам придётся изменить режим доступа к памяти, так чтобы её можно было исполнять, то есть, чтобы выполнить call или jmp на неё. Для этого объявим переменную следующим образом:

uint8_t lMagicCode [] = { };

Содержание её мы рассмотрим ниже. А сейчас выполним установку необходимых нам режимов доступа к этой переменной. Здесь повторим действия из примера в предыдущей статье:

void* lPageBoundary = (void*) ((long) lMagicCode & ~(getpagesize () - 1));
mprotect (lPageBoundary, 1, PROT_EXEC | PROT_WRITE);

Мы добавили режим доступа PROT_EXEC, который и позволит нам выполнить переменную. Как вы заметили, я оставил режим PROT_WRITE. Это сделано потому что MMU работает со страницами. На наших машинах её размер, вероятнее всего будет 4kB, что довольно много и помеченная страница скорее всего заденет область, следующую за интересующей нас переменной. А нам нужен режим чтения и записи для обвязки нашего эксперимента. Поэтому чтобы не схватить SIGSEGV после вызова mprotect, мы выставляем совмещённый режим — запись (которая на x86 MMU не бывает без режима чтения) и выполнение.

Далее нам нужно как-то указать машине, как и когда выполнить эту переменную. На всякий случай помечу: эта переменная сама по себе никогда не выполнится, функция mprotect не запустит её, а лишь пометит, как доступную для выполнения. Перейдём к последнему этапу подготовительных работ на высоком уровне (на уровне C), который заключается в том, чтобы объявить функцию, ссылающуюся на адрес этой переменной, что в последствии, позволит нам выполнять эту переменную:

unsigned int (*NewExit)(unsigned long _ExitCode) = (void*)lMagicCode;

Здесь мы объявили указатель на функцию с названием NewExit, принимающую один параметр _ExitCode и возвращающую значение. Теперь мы можем выполнить нашу переменную и получить возвращаемое ею значение простой строчкой:

unsigned int lResult = NewExit (1);

Пока не надо этого делать — пытаясь выполнить пустую переменную, то есть, выполняя call на адрес пустой переменной, вы по сути дела, «провалитесь» дальше (как было в примере предыдущей статьи с выводом строки), а там может быть что угодно и, скорее всего, данные, даже не похожие на последовательность байт, представляющую собой корректную машинную команду с операндами. Что, вероятнее всего, приведёт к ошибке Illegal instruction.

Далее нам нужно заполнить нашу переменную корректным кодом. Начнём, допустим с возврата, то есть исключим «проваливание» потока выполнения при вызове этой функции. По справочникам найдём код операции ret, который очень простой и равен C3h.

uint8_t lMagicCode [] = { 0xC3 };

На самом деле это retn — return near, то есть ближний возврат или внутрисегментный возврат — возврат в пределах одного сегмента кода.

Теперь можно выполнить нашу функцию, не боясь неопределённых последствий, так как теперь произойдёт следующее: команда call сохранит в стэке адрес возврата равный адресу операнда следующему сразу за ним (адрес call + длинна инструкции call и его операнда), затем перейдёт по указанному адресу (адресу нашей переменной), в которой лежит код команды ret, которая, в свою очередь извлечёт адрес возврата из стэка и выполнит переход по нему.

printf ("The result of NewExit is: %d.\n", lResult);

Сейчас мы будем видеть «мусор» на выходе из функции. Для получения какого-то осмысленного результата, вернём значение. Значение из функции по правилам x86_64 ABI возвращается через регистр «семейства» AX. Мы объявили нашу функцию как возвращающую значение unsigned int, то есть 32 бита. Значит нам нужно записать результат в EAX — 32-битный регистр. Найдём код загрузки константы в EAX — это B8h. При заполнении команды нужно учитывать размерность операнда. Здесь мы не можем написать B8h, 04h. Нам нужно указать всё значение полностью.

В языках высокого уровня это за нас делает компилятор. GAS так же подставляет дополненные значения в зависимости от суффикса мнемонического представления команды, например movl $0x04, %eax запишет в реальный код B804000000h, дополнив нашу четвёрку нулями до длинны long. Здесь это не тот long, о котором мы говорили в моделях памяти (LP64), это long с точки зрения x86-ой машины длинной 32 бита. Некоторые трансляторы даже подбирают код конкретной операции из обобщённого мнемонического представления и дополняют размерность операнда в зависимости от указанных размерностей приёмника и источника.

В противном случае, если мы не распишем все байты составляющие 32-битное значение, последующий код, который мы запишем как следующую инструкцию или операнд, в процессе выборки команды процессором будет воспринят как данные для загрузки в EAX. Поэтому соберём код B8h, 07h, 00h, 00h, 00h. И наша переменная приобретёт следующий вид:

uint8_t lMagicCode [] =
{
  0xB8, 0x07, 0x00, 0x00, 0x00, // movl $0x7, %eax
  0xC3,                         // retn
};

Теперь, вызвав эту функцию как

printf ("The result of NewExit is: %d.\n", NewExit (0));

Мы получим:

The result of NewExit is: 7

Функция названа NewExit. Давайте придадим ей этот смысл. Для этого мы воспользуемся системной функцией под номером 60/3Ch и вызовем её при помощи syscall, которая имеет код операции 0F05h. Операционная система, при вызове системных функций от пользовательских процессов, принимает номер функции в регистре EAX. Писать туда мы уже умеем. Наша переменная с машинным кодом приобретёт такой вид (возврат из этой функции нам уже не нужен):

uint8_t lMagicCode [] =
{
   0xB8, 0x3C, 0, 0, 0, // movl $0x3C, %eax, 3Ch/60 - system call exit()
   0x0F, 0x05,          // syscall
};

У нашей функции есть один параметр. Этот параметр попадёт в возвращаемое значение функции main, то есть код нашей переменной аналогичен функции exit. Вы можете это проверить запустив программу на исполнение и проверив код выхода при помощи echo $?. Вы увидите число переданное вами в функцию NewExit.

Хоть мы и передаём int в качестве параметра, возвращаемое из функции main значение всегда снижается системой до одного байта, поэтому не имеет смысла задавать значения более 255.

Здесь может возникнуть вопрос — «А почему так? Мы так много кода писали для простейших действий, а возвращаемое значение попадает в систему без каких либо операций вообще». Дело в том, что по правилам x86_64 ABI первый параметр, указанный в функции, записывается в регистр RDI. А системная функция exit, 60/3Ch возвращает в систему в качестве кода выхода значение RDI. Так совпало — наше значение «провалилось» насквозь и попало в оболочку, в переменную $? и писать нам для этого действительно ничего не пришлось.

P.S.
Интересно отметить тот факт, что отлаживать участки программы, представленные в виде переменных и сформированные в качестве их содержания, будет проблематично. Это связано с тем, что этот код попадает в секцию .data, которая отладчиком не рассматривается как код. Даже если посмотреть ассемблерный вывод после компилятора, то мы увидим просто переменную, в которой будут числовые значения — перечень наших байт в объявленном массиве.

        .size   lMagicCode, 7
lMagicCode:
        .byte   -72
        .byte   60
        .byte   0
        .byte   0
        .byte   0
        .byte   15
        .byte   5

Ниже приведу всю программу:

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/mman.h>

int main (void)
{
  uint8_t lMagicCode [] =
  {
//     0xB8, 0x3C, 0, 0, 0,          // movl $0x3C, %eax # 3Ch/60 - system call exit()
//     0x0F, 0x05,                   // syscall
    0xB8, 0x07, 0x00, 0x00, 0x00, // movl $0x7, %eax
    0xC3,                         // retn
  };
  
  void* lPageBoundary = (void*) ((long) lMagicCode & ~(getpagesize () - 1));
  
  mprotect (lPageBoundary, 1, PROT_EXEC | PROT_WRITE);
  
  unsigned int (*NewExit)(unsigned long _ExitCode) = (void*)lMagicCode;
  
  unsigned long lResult = NewExit (2);
  
  printf ("The result of NewExit is: %d. Or will never be printed...\n", NewExit (0));
  
  return 0;
}

12/09/2021

Little hack of system (1): finally, you can modify strings of type char* String

Preface

It's hard to find a person who would argue that it's impossible to count how often we want to change contents of a string declared as:

char* String = "Hello, World!";

Despite the fact that this operation looks absolutely ordinary and we expect a very straight and simple result from it, while trying to do something like:

String[1] = 'a';

we get Segmentation fault or SIGSEGV. And, usually, whole development ends at this point.

Don't even dare to do this — your CPU will catch fire immediately and all your unsaved data will be lost!

Segmentation fault occurs when a process attempts to write (or read, see below) to an area of ​​memory that is inaccessible to it. What is that memory area we can't write to? In our example, it's the area in the data segment marked as read-only — RO DATA. Let's look at the output of a program that declares a char* String. From a code like this:

int main ()
{
  char* lString = "Hello, World!";
}

we get:

    .section   .rodata
.LC0:
    .string "Hello, World!"

Of course we can replace .section .rodata with .section .data. But we won't suggest intervening the building process of our code every time in, actually, not most handy stage — translation.

Solution

Let's have a look at POSIX function — mprotect(). This function changes the access conditions to a memory area.

There is a misstep or inaccuracy associated with this function. In documentation — as in man as on the Internet, it's claimed that mprotect() marks memory starting with address of a page and ending with address of that page plus length in bytes minus 1. I had to do a little search and research to clarify that the length is specified in pages, not bytes. That looks more clear because MMU operates with pages, not with bytes. And in the following examples I've proved this — specifying 1 as a length parameter I've got marked enough memory for all of our variables. The conclusion is — mprotect() assumes length is in count of pages.

The function takes address, length and flag as parameters. In our case, we are most interested in address and flag. We need PROT_WRITE flag — it's simple. But the things about address is a little more complicated. As MMU works with pages, the starting address we want to modify access to, should be aligned to page size. To get such address we'll calculate the closest (from the lower side) address of variable we're interested in. We'll do this in the following manner. First, we'll request the size of the page. Second, we'll drop all the least significant bits of the variable address that match the page size. Simply put, we zero the variable address bits on the least significant side to the bits of the page size.

For example: the address of lString is 555555556004h, we get the page size from the system, in my case (most probably you'll get the same) it is 4096. Subtract 1 from the page size, since it's actually addressed from 0 to 4095, and we'll get FFFh. We see that pages of this size are multiples of three halfbytes, or 1.5 bytes. In our example, the address of the page closest to the variable is 555555556000h. To calculate this address, we need to drop the outer 1.5 bytes of the variable's address. By inverting the page size we get a mask for the logical operation — FFFFFFFFFFFFF000h. Casting this to the void* type gives us the full memory address size for any architecture. This leads to the following preprocessing results:

void* lPageBoundary = (void*) ((long) lStr1 & ~(getpagesize () - 1));

For our research we'll set the length of memory we modify access to as one page. The size of a page allows us not only to play with writing to different areas, but also to experiment with boundaries of variables:

mprotect (lPageBoundary, 1, PROT_WRITE);

That's it. From this point on, unprecedented miracles begin. For example, the following program displays «World!» instead of the already annoying and tedious «Segmentation fault»:

#include "string.h"
#include "unistd.h"
#include "stdio.h"
#include "sys/mman.h"

int main ()
{
  char *lStr1 = "Hello";
  char *lStr2 = " orld!";
  void* lPageBoundary = (void*) ((long) lStr1 & ~(getpagesize () - 1));

  // Comment next line to turn magic off:
  mprotect (lPageBoundary, 1, PROT_WRITE);
  lStr2[0] = 'W';
  printf ("%s\n", lStr2);
}

But I suggest to go a little further and play with addresses a little more. As you can see, I've declared two variables — lStr1 and lStr2. char* is an asciz or LPSZ (Long Pointer to Zero Terminated String) variable. As we know, string functions determine lengths and terminations of strings based on this zero. Let's check what happens if we replace the terminating zero in lStr1 with a space and output this string using printf(). Here, we'll demonstrate that we can write (modify memory) within the entire memory region access to which was modified by mprotect() function. I propose implementing the experiment of removing the last zero from lStr1 by writing to the address of lStr2 - 1:

lStr2[-1] = ' ';
printf ("%s\n", lStr1);

Since our strings are located in memory one after other, it turns out we've removed the terminating zero from lStr1 and replaced it with a space symbol. Consequently, lStr1 is no longer asciiz/LPSZ, and thus, printf() should «fall thru» lStr1 to the first occurrence of zero which will be the terminating zero of lStr2. Let's check this. And we get the following output:

Hello World!

That's right, printf() reached the first terminating null, which turned out to be the terminating null of string lStr2. We got the output of the «concatenated» string.

In fact, this only looks unusual in C. In assembly language, this kind of data handling is ordinary routine — for example, the length of a string (or ascii/asciz) or array can be calculated by subtracting the address of the variable following it from its own address.

But that's not all. Perhaps at this moment, the thought has crossed your mind: «If this is possible, then maybe I can change the values ​​of variables declared as const?» The answer is yes — this long-held dream can be realised. But there's a some caveat. As we know, the compiler won't let us write to variables declared with the const modifier. An attempt to do:

const char* lStr3 = "hello world!";
lStr3[0] = 'H';

will lead to:

./mprotect.c:18:12: error: assignment of read-only location '*lStr3'
   lStr3[0] = 'H';
            ^

To resolve this situation, we trick the compiler as follows:

*((char*)lStr3 + 0) = 'H';

We obtained the variable's address, added an offset to it, and wrote whatever we wanted to it. Now the code compiles and works. The offset here is zero; it doesn't have any technical meaning. I wrote the offset here to fully explain the notation for accessing variables declared as const. Using this notation, you can address any character in the string... and not just that character, and not just forward, since we can write in boundaries of the entire page we've granted access to.

NB
It seems obvious, but I think I should warn you. We've removed the write protection on a memory area, and you can remove the protection on a larger memory area. This means you can modify memory without any control from the OS, MMU, or compiler, as we've completely eliminated this functionality. You can write to these memory areas, but if you want to maintain proper functionality of your code, you need to be even more careful about the boundaries of the memory areas you modify!

P.S.
You may have noticed that we used the PROT_WRITE access flag without PROT_READ, and we were reading data from these areas. This was because the x86 MMU (this research was made on x86 machine) doesn't have a write mode without reading, so you can use PROT_WRITE | PROT_READ, but this is pointless. If you want to play with access, you can try PROT_NONE. In this case, you won't have any access to the memory page, and even an attempt to read it, for example via printf(), will result in a segmentation fault. This feature could be used in some way in practice, but it's hampered by the fact that we can only mark an entire page, and they only come 4K/2M/4M and 4Gb in size, depending on the architecture and/or operating mode. 4K is quite too much to use memory access mechanisms as some kind of «trap». However, if the program is large enough, we can group flags, the changes to which we want to react in certain conditions, into 4Kb blocks and implement the logic for reacting to a triggered security exception in the signal handler.

08/09/2021

Маленький взлом системы (1): наконец-то вы сможете изменять строки типа char* String

N.B.
Всё, что описывается в этой статье — это строго про x86-ую машину. Если вы попытаетесь проделать это на другой архитектуре, то ваш процессор сгорит!

Вряд ли найдутся люди, готовые поспорить с тем, что невозможно сосчитать как часто нам хочется изменить содержание строки объявленной как

char* String = "Hello, World!";

Несмотря на то, что эта операция выглядит абсолютно логично и мы ожидаем от неё весьма конкретного и несложного результата, пытаясь сделать что-то вроде

String[1] = 'a';

мы получаем ошибку сегментации (Segmentation fault и сигнал SIGSEGV). И, как правило, на этом вся разработка заканчивается.

Ни в коем случае не пытайтесь это сделать — ваш процессор немедленно сгорит и все несохранённые данные будут потеряны!

Ошибка сегментации возникает в случае, когда процесс «лезет» в недоступную ему область памяти с целью записи (или чтения, см. ниже). А что это за область памяти такая, в которую мы не можем писать? В нашем примере, это область в сегменте данных, помеченная как память только для чтения — RO DATA. Посмотрим что получается в коде программы, в которой объявлена строка char* String. Из программы типа:

int main ()
{
  char* lString = "Hello, World!";
}

мы получим:

    .section   .rodata
.LC0:
    .string "Hello, World!"

Конечно, можно просто заменить .section .rodata на .section .data, но каждый раз вмешиваться в сборку проекта на не самом удобном этапе — трансляции, мы предлагать не будем.

Я решил рассмотреть функцию POSIX — mprotect(). Функция изменяет условия доступа к области памяти.

Но с этой функцией связана одна ошибка. В документации — как в man, так и в интернете, указано, что mprotect() помечает память начиная от адреса страницы до адреса страницы + длинна в байтах за вычетом единицы. В интернете я случайно нашёл упоминание, что длинна здесь указывается в количестве страниц. Что логично, так как MMU работает со страницами, а не с байтами. На нашем примере я подтвердил это — указывая в качестве длинны единицу я пометил достаточное количество памяти для всех наших переменных, то есть, видимо, mprotect() действительно берёт длину в количестве страниц.

Принимает функция на вход адрес, длину и флаг. В нашем примере нас будет интересовать, флаг и, как ни странно, адрес. Флаг нам нужен PROT_WRITE. А с адресом всё чуть более интересно. Так как MMU работает со страницами, начальный адрес, должен быть кратным размеру страницы. С тем, чтобы получить нужный нам адрес, мы вычислим ближайшую (в меньшую сторону) к интересующей нас переменной границу страницы памяти. Сделаем это мы следующим образом. Запросим размер страницы, сбросим у адреса переменной все правые биты, совпадающие с размером страницы. Проще говоря — обнулим адрес переменной справа на величину размера страницы.

Например: адрес lString равен 555555556004h, размер страницы получаем от системы, в моём случае он оказался равен 4096. Из размера страницы уберём единицу, так как фактически она адресуется с 0 по 4095, получим FFFh. Видно, что страницы с таким размером кратны трём полубайтам или полутора байтам. В нашем примере адрес ближайшей к переменной странице равен 555555556000h. Чтобы вычислить этот, адрес нужно сбросить крайние полтора байта адреса переменной. Инвертировав размер страницы получаем маску для логической операции FFFFFFFFFFFFF000h. Приведём это к типу void*, что даст нам полный размер адреса в памяти для любой архитектуры. В результате получим следующие результаты подготовки:

void* lPageBoundary = (void*) ((long) lStr1 & ~(getpagesize () - 1));
Длину, для нашего эксперимента мы поставим равной одной странице. Размер страницы позволит нам поиграть не только с записью в запретные места, но и с границами переменных.
mprotect (lPageBoundary, 1, PROT_WRITE);

Всё. С этого момента начинаются невиданные до сих пор чудеса. Например, следующая программа выводит «World!», а не столь неприятный и уже надоевший «Segmentation fault»:

#include "string.h"
#include "unistd.h"
#include "stdio.h"
#include "sys/mman.h"

int main ()
{
  char *lStr1 = "Hello";
  char *lStr2 = " orld!";
  void* lPageBoundary = (void*) ((long) lStr1 & ~(getpagesize () - 1));

  // Comment next line to turn magic off:
  mprotect (lPageBoundary, 1, PROT_WRITE);
  lStr2[0] = 'W';
  printf ("%s\n", lStr2);
}

Но я предлагаю пройти дальше и ещё чуть-чуть поиграть с адресами. Как вы можете видеть, я объявил две переменные — lStr1 и lStr2. char* — это переменная типа asciz или LPSZ (Long Pointer to Zero Terminated String) или, по-русски — строка оконченная нулём. Как известно, функции, работающие со строками, определяют их длину и окончание по этому самому нулю. Давайте проверим, что будет, если вместо оконечного нуля lStr1 поставить пробел и вывести эту строку при помощи printf(). Здесь же продемонстрируем что мы можем писать (изменять память) в пределах всей памяти модифицированной функцией mprotect(). Эксперимент с удалением последнего нуля из строки lStr1 я предлагаю реализовать путём записи по адресу строки lStr2 - 1:

lStr2[-1] = ' ';
printf ("%s\n", lStr1);

Так как строки расположены в памяти непосредственно одна за второй, получается, что я удалил завершающий нуль lStr1 и поставил не его место пробел. Соответственно, строка lStr1 перестала быть asciz и по логике, printf() должен «провалиться» дальше. Проверим это, получим вывод:

Hello World!

Всё верно, printf() прошёл до первого завершающего нуля, а им оказался завершающий нуль строки lStr2. Мы получили вывод «совмещённой» строки.

На самом деле это выглядит непривычно только на C. На ассемблере подобная работа с данными является повседневной нормой — например длинна строки (string или ascii/asciz) или массива может быть вычислена вычитанием адреса следующей за ней переменной из её собственного адреса.

Но и это ещё не всё. Возможно, к этому моменту, у вас в голове возникла мысль — «Если можно так, то, может, я смогу изменять значения переменных, объявленных как const»? Ответ положителен — эту давнюю мечту можно реализовать. Но с небольшим нюансом. Как мы знаем, компилятор нам не позволит писать в переменные, объявленные с модификатором const. Попытка сделать:

const char* lStr3 = "hello world!";
lStr3[0] = 'H';

приведёт к:

./mprotect.c:18:12: error: assignment of read-only location '*lStr3'
   lStr3[0] = 'H';
            ^

Для разрешения этой ситуации обманем компилятор следующим образом:

*((char*)lStr3 + 0) = 'H';

Мы взяли адрес от переменной, добавили к нему смещение и по нему прописали, что хотели. Теперь всё собирается и работает. За смещение здесь взят нуль, это не имеет технического смысла. Я написал здесь смещение для того чтобы в полной мере раскрыть форму записи доступа к переменным объявленным как const. По этой форме записи вы можете адресоваться на любой символ строки... и не только на него, и не только вперёд, так как мы «взяли» себе целую страницу.

NB
Вроде и очевидно, но считаю что я должен предупредить. Мы сняли запрет записи на область памяти, возможно вы снимете запрет на большую область памяти. Это значит, что вы можете модифицировать память без какого либо вообще контроля со стороны ОС, MMU и компилятора, так как мы полностью исключили этот функционал. Вы можете писать в эти области памяти, но, если вы хотите сохранить адекватную работоспособность своего кода, вам нужно ещё более тщательно следить за границами областей памяти изменяемых вами!

P.S.
Возможно вы заметили, что мы использовали флаг доступа PROT_WRITE, без PROT_READ и, при этом мы читали данные из этих областей. Всё это было так потому что у MMU x86 (а этот эксперимент проводился на x86-ой машине) нет режима записи без чтения, поэтому можно поставить PROT_WRITE | PROT_READ, но смысла в этом нет. Если вы хотите поиграть с доступом, вы можете попробовать PROT_NONE. В этом случае вы не будете иметь никакого доступа к странице памяти и даже попытка чтения, например через printf(), приведёт к ошибке сегментации. Эту особенность можно было бы использовать каким-то образом на практике, но это затруднено тем, что мы можем помечать только целую страницу, а они бывают только 4Kb/2Mb/4Mb и 4Gb размером, в зависимости от архитектуры и/или режима работы. 4Kb — довольно много для использования механизмов доступа к памяти в качестве какой-нибудь «ловушки». Хотя, если программа достаточно большая, можно группировать флаги, на изменение которых в какие-то моменты мы хотим реагировать, в блоки по 4Kb и в обработчике сигнала реализовать логику реакции на сработавшее исключение защиты.