Exercises — Memory protection units (MPU) — preventing stack overflow, access faults
5.5.24 · D4· Coding › Embedded Systems & Real-Time Software › Memory protection units (MPU) — preventing stack overflow, a
Shuru karne se pehle, ek visual dekho jo us vocabulary ko fix karega jo hum har problem mein reuse karenge.

Picture ko dheere-dheere dekho — poore page pe milne wale har term is picture mein hai.
- Baayein taraf ka lamba arrow address axis hai: yeh upar high addresses ki taraf aur neeche low addresses ki taraf point karta hai. Memory bas bytes ki ek numbered ladder hai; yeh arrow woh ladder khadi karke rakhi hui hai.
- Shaded blue box ek region hai — us ladder ka ek single contiguous slice. Ek region = ek continuous run of addresses jiske liye ek set of rules hain (kya tum isse read kar sakte ho? write kar sakte ho? iska code run kar sakte ho?).
- Box ke bottom pe yellow line base address hai: region ka sabse low address, yani woh jagah jahan slice shuru hoti hai.
- Top pe pink dashed line
BASE + SIZEhai: woh first address jo region se bilkul bahar hai. Dhyan do yeh ek past the top hai, region ka last byte nahi — region un addresses ka malik hai jahan (top excluded). - Box ke left edge pe double-headed arrow size hai: slice kitni tall hai, hamesha power of two, bytes.
Toh ek region sirf do numbers se fully describe hota hai — kahan se shuru hota hai (base) aur kitna tall hai (size) — plus uske rules. Alignment rule "base, size ka multiple hona chahiye" woh ek cheez hai jo yeh figure ab bhi justify nahi karta; hum kyun neeche #L2 Application mein samjhenge.
L1 Recognition
Problem 1.1 (L1) — Size field decode karo
ARM Cortex-M pe, region size ko RASR (Region Attribute and Size Register) mein SIZE naam ke ek field ke roop mein encode kiya jaata hai. Region ki actual byte-size hai
SIZE field ko parent ke code mein (k << 1) ke roop mein likha jaata hai. Upar wale definition mein explain kiya gaya hai, k << 1 numeric value ko RASR ke bit 1 se shuru hone wale SIZE field mein place karta hai, isliye field ki value hai. Agar code (9 << 1) likhta hai, toh SIZE = 9, region kitne bytes ka hai?
Recall Solution 1.1
Field value hai . Plug in karo: Humne kya kiya: field value ko size formula mein substitute kiya. Kyun: hardware exponent minus one store karta hai bits bachane ke liye — ek 5-bit field (32 B) se (4 GB) tak sab kuch cover karta hai. Toh stored matlab exponent hai, yani bytes. ✅
Problem 1.2 (L1) — AP = 000 ka matlab kya hai, aur baaki codes kya hain?
RASR mein AP (Access Permission) field (v << 24) ke roop mein likha jaata hai — teen bits bit 24 se shuru hote hue place kiye jaate hain. Parent note ne guard region ke liye (0 << 24) use kiya. Words mein, AP = 000 kya access deta hai, aur baaki legal codes kya hain?
Recall Solution 1.2
AP = 000 ka matlab hai No access — na privileged na unprivileged code is region ko read ya write kar sakta hai. Yeh exactly wahi hai jo ek guard band chahta hai: pehla touch fault karta hai. Full ARMv7-M AP encoding table (Armv7-M Architecture Reference Manual, MPU section) yeh hai:
AP |
Privileged | Unprivileged |
|---|---|---|
| 000 | No access | No access |
| 001 | RW | No access |
| 010 | RW | RO (read-only) |
| 011 | RW | RW |
| 100 | reserved (unpredictable) | — |
| 101 | RO | No access |
| 110 | RO | RO |
| 111 | RO | RO |
Edge cases jo jaanne chahiye:
- Code
100sirf ek reserved code hai — isse likhna unpredictable behaviour deta hai, toh kabhi use mat karo. - Code
101reserved nahi hai; yeh ek normal, architecturally-defined code hai jiska matlab hai "privileged read-only, no user access" — read-only kernel data ke liye useful. Reserved100ko perfectly legal101se mat confuse karo; sirf single value100off-limits hai. - Codes
110aur111dono ka matlab "sabke liye read-only" hai (yeh equivalent hain; hardware unhe same treat karta hai).
Parent ne sirf 000, 001, aur 011 use kiya, lekin ek real driver ko often 010 (kernel writes, user reads) aur 110/111 (read-only constants / flash) bhi chahiye. ✅
L2 Application
Problem 2.1 (L2) — Kya yeh base address legal hai?
Ek programmer 64-byte () region chahta hai aur base address 0x20000010 likhta hai. Kya yeh base legal (properly aligned) hai, aur agar nahi, toh hardware region ko actually kahan place karta hai?
Recall Solution 2.1
Alignment rule: -byte region ke liye, base ke low bits sab zero hone chahiye (base, size ka multiple ho). Yahan hai, isliye low 6 bits zero hone chahiye, yani base 64 ka multiple hona chahiye.
0x20000010 = 0x20000000 + 0x10 = base + 16. Kya 16, 64 ka multiple hai? Nahi. 0x...10 ke low 6 bits 010000 hain — sab zero nahi. Toh base illegal hai.
Kahan land karta hai: hardware low 6 bits mask kar deta hai. Yaad karo ~ har bit flip karta hai (upar wala definition dekho): ~(64 - 1) = ~0x3F hai "all ones except low 6 bits", toh 0x20000010 & ~0x3F = 0x20000000. Tumhara protection window silently slide hokar 0x20000000–0x20000040 ho jaata hai, na ki tumhara intended 0x20000010–0x20000050.
Kaisa dikhta hai: neeche wala figure dekho — intended window (pink) versus actual masked window (blue). ✅

Problem 2.2 (L2) — Ek aligned base compute karo
Tumhe 32-byte guard band protect karna hai jo us stack ke bilkul bottom pe baitha hai jiska bottom 0x20000C00 pe hai. base = addr & ~(size - 1) use karte hue, 32-byte guard ke liye tum kya base likhoge?
Recall Solution 2.2
Size hai, toh size - 1 = 31 = 0x1F. Mask hai ~0x1F = "all ones, low 5 bits clear".
0x20000C00 ke low 5 bits already zero hain (, last 5 bits 00000), isliye masking kuch nahi badlata:
Kyun pehle se aligned tha: 0xC00 = 3072 hai, aur exactly — 32-byte blocks ki poori sankhya. Acche stack layouts isliye choose kiye jaate hain taaki guards aisi boundaries pe land karein. Dekho Stack memory layout. ✅
L3 Analysis
Problem 3.1 (L3) — Overlap pe kaun si region jeet jaati hai?
Region 0: BASE = 0x20000000, SIZE = 2^10 (1 KB), AP = RW.
Region 1: BASE = 0x20000000, SIZE = 2^5 (32 B), AP = No access (guard).
Ek task address 0x20000004 pe write karta hai. Kaun si region ke rules apply honge, aur write succeed hogi ya fault?
Recall Solution 3.1
Step 1 — kaun si regions match karti hain? Region match karti hai agar .
- Region 0: → matches.
- Region 1: → matches (4 < 32).
Step 2 — tie resolve karo. Dono match karte hain. Upar wale callout mein justify kiya gaya hai, hardware highest-numbered matching region pick karta hai taaki specific exceptions broad backgrounds ko override karein. Region 1 > Region 0 hai, toh Region 1 jeet jaati hai.
Step 3 — Region 1 ka rule apply karo. Region 1 No access hai. Write faults karta hai → CPU MemManage_Handler() pe vector karta hai. Yeh exactly woh desired guard behaviour hai. ✅
Dekho Memory faults and exception handling taaki jaano handler aage kya karta hai.
Problem 3.2 (L3) — Same layout numbers swap karke
Ab maano kisine accidentally guard ko Region 0 mein daala (32 B, No access) aur broad RW stack ko Region 1 mein (1 KB, RW). Same write 0x20000004 pe. Kya guard abhi bhi bottom protect karta hai?
Recall Solution 3.2
Dono regions abhi bhi 0x20000004 match karte hain (same address ranges as before). Lekin ab highest-numbered matching region Region 1 hai, jo RW hai. Toh Region 1 jeet jaata hai, write succeed karta hai, aur Region 0 mein guard silently ignore ho jaata hai.
Conclusion: guard ki protection completely is baat pe depend karti hai ki uska region number zyada ho. Numbering, configuration ka order nahi, priority decide karta hai. Yeh callout se layering rule galat use kiya gaya: broad background low-numbered hona chahiye, specific exception high-numbered. ✅

L4 Synthesis
Problem 4.1 (L4) — Do-task isolation layout design karo
Tumhare paas 0x20000000 se shuru hoti 4 KB RAM hai. MPU layout design karo jisme:
- Task A stack: 1 KB, RW, bottom pe 32-byte no-access guard ke saath.
- Task B stack: 1 KB, RW, bottom pe 32-byte no-access guard ke saath.
- Saare stacks XN (execute-never) hone chahiye.
- Har base apni size ke saath aligned ho; guards apne stacks pe jeet-ne chahiye.
Har region ke liye base address, size field value, AP, aur region number do.
Recall Solution 4.1
Layout (stacks downward grow karte hain, isliye guard har stack ke low end pe baitha hai):
| Region | Base | Size | SIZE field |
AP | XN | Purpose |
|---|---|---|---|---|---|---|
| 0 | 0x20000000 |
1 KB () | 9 | RW (011) | 1 | Task A stack |
| 1 | 0x20000000 |
32 B () | 4 | No access (000) | 1 | Task A guard |
| 2 | 0x20000400 |
1 KB () | 9 | RW (011) | 1 | Task B stack |
| 3 | 0x20000400 |
32 B () | 4 | No access (000) | 1 | Task B guard |
Checks:
- Alignment:
0x200000001024 ka multiple hai (yeh 0 hai) aur 32 ka bhi → ✅.0x20000400 = 1024hai, 1024 aur 32 ka multiple → ✅. - Priority: har guard (regions 1, 3) ka higher number hai uske stack (regions 0, 2) ki tulna mein. ✅ (Problem 3.1 ke anusaar).
- XN: chaalon chaalon ke
XN = 1hai, kisi bhi stack se code execution block karta hai — stack shellcode ko defeat karta hai (upar wala XN definition dekho). Dekho Buffer overflow attacks. SIZEfield: 1 KB → → field ; 32 B → → field . ✅ (Problem 1.1 ke anusaar).
Total RAM used: B 4 KB mein se — kafi room hai. Guards stack bottoms ko overlap karte hain, isliye unhe koi extra RAM nahi chahiye.
Kyun overlapping guard ko extra RAM nahi lagti: ek MPU region ek allocation nahi hai — yeh bytes reserve ya consume nahi karta. Yeh sirf ek rule hai jo MPU har access pe check karta hai: "is range mein addresses ke liye, yeh permissions apply karo." Guard region aur stack region do rules hain jo happen to same physical bytes describe karte hain (stack ke low 32). Woh bytes already 1 KB stack ke andar counted the; guard bas un par verdict badal deta hai (no-access ki jagah RW), woh nayi memory claim nahi karta. Regions overlays hain, reservations nahi. Sirf real cost yeh hai ki woh 32 overlaid bytes stack ke taur pe unusable ho jaate hain — Problem 5.1 dekho. ✅
Yeh exactly woh pattern hai jo RTOS task switching har context switch pe reprogram karta hai: incoming task ke stack + guard ke liye regions 0–1 swap karo.
L5 Mastery
Problem 5.1 (L5) — Guard fire karne se pehle latest-safe stack size
Task A ka region 0x20000000–0x20000400 (1 KB) hai jisme 0x20000000–0x20000020 pe 32-byte guard hai. Stack pointer top (0x20000400) se shuru hota hai aur downward grow karta hai. Ek function ek local array of bytes ek shot mein allocate karta hai (char buf[S]), SP ko se neeche push karta hai.
(a) Sabse bada kya hai jo guard ko touch nahi karta? (b) Sabse chhota kya hai jo fault trigger karta hai?
Recall Solution 5.1
Guard un addresses ko occupy karta hai jahan hai, yani bytes 0x00–0x1F. bytes ki stack write [0x20000400 - S, 0x20000400) touch karti hai.
(a) Yeh guard ke bahar rehta hai agar uska lowest written byte guard ke top par ya usse upar ho, yani , jo rearrange hoke deta hai.
(b) Sabse chhota fault-triggering allocation ek byte zyada hai: pe, lowest written byte hai, jo guard mein hai → MemManage fault. ✅
Takeaway: guard nominal stack ke 32 bytes le leta hai, isliye apna worst-case stack depth B ke against budget karo, B ke nahi.
Problem 5.2 (L5) — Bada guard kitna pehle catch karta hai?
Same 1 KB stack pe 32-byte guard aur 128-byte guard compare karo. Kitne bytes overflow ke pehle 128-byte guard downward overflow ko catch karta hai, aur RAM cost kya hai?
Recall Solution 5.2
Ek clean model set up karo aur usse stick karo. bytes ka ek guard [0x20000000, 0x20000000 + G) occupy karta hai. Uska top address 0x20000000 + G pe hai. Downward-growing stack tab fault karta hai jab uska lowest written byte us top ke neeche gir jaata hai, yani guard mein. Toh woh single quantity jo matter karti hai woh hai guard-top address — jitna upar yeh baitha hai, utni jaldi (kam descent ke saath) overflow isse hit karti hai.
- 32-byte guard: guard-top =
0x20000020. Fault jab write0x20000020ke neeche pahunchi. - 128-byte guard: guard-top =
0x20000080. Fault jab write0x20000080ke neeche pahunchi.
Kitna pehle? Do guard-top addresses ka difference lo: 128-byte guard ka top 96 bytes upar baitha hai, isliye descending stack use 96 kam bytes overflow ke baad meet karta hai — yeh 96 bytes pehle fire karta hai.
RAM cost: guard stack ko overlap karta hai (yeh ek rule hai, allocation nahi — Problem 4.1 dekho), isliye yeh RAM add nahi karta — lekin usable stack remove karta hai (jaisa Problem 5.1 mein mile, usable hai):
- 32-byte guard B usable chhod-ta hai.
- 128-byte guard B usable chhod-ta hai.
Tum 96 bytes usable stack trade karte ho 96 bytes earlier detection ke liye — yeh dono equal hain, jo sense banata hai: guard mein har byte add karna ek byte top ko raise karta hai aur usable stack ka ek byte lose karta hai. Tight RAM pe, guard ko 32-byte minimum pe rakho; ek elusive overflow bug chase karte waqt, temporarily ise widen karo. ✅
Recall Self-test summary (right column dhako)
Field value 9 kitne bytes encode karta hai? ::: B
k << 1 value k ke saath kya karta hai? ::: Bits ko left mein 1 shift karta hai (= ), isse bit 1 se shuru hone wale field mein place karta hai.
~x kya karta hai? ::: Bitwise NOT — har bit flip karta hai; alignment masks banane ke liye use hota hai.
RBAR aur RASR ka matlab kya hai? ::: Region Base Address Register aur Region Attribute and Size Register.
Kya misaligned base fault karta hai? ::: Nahi — hardware low bits mask kar deta hai aur galat range silently protect karta hai.
Overlap pe kaun si region jeet ti hai aur kyun? ::: Highest-numbered — taaki specific high-index exceptions broad low-index backgrounds ko override karein.
Kaun sa AP code reserved hai? ::: Sirf 100 (unpredictable — kabhi use mat karo); 101 ek legal privileged-RO code hai.
1 KB region mein 32 B guard ke saath usable stack kitna hai? ::: 992 bytes.
AP = 000 ka matlab kya hai? ::: No access (privileged ya unprivileged).
Kyun overlapping guard extra RAM nahi leta? ::: Ek region ek permission rule hai, allocation nahi — woh bytes re-describe karta hai jo stack already own karta hai.
XN = 1 kya forbid karta hai, aur stacks pe kyun? ::: Instruction fetch (execute); overflowed stack pe shellcode ko run hone se rokta hai.