PIC18F45K80: Reading an Image Backwards, From Behaviour to Code
There are two directions to work in. Forwards is the familiar one: an image exists, and the question is what it does. Backwards is the one that appears when the array is closed but the device is alive: behaviour exists, and the question is what the code must be to produce it.
The backwards direction is not guesswork, and it is not less rigorous. It is constraint-solving, and the constraints come from measurement. On a 32K device with a defined job, they usually narrow the answer to something a rebuild can satisfy.
The first constraint is the clock
Everything else depends on it. Instruction timing, peripheral timing, communication rates and control loop periods all scale with the clock, and the clock is measurable at a pin if the oscillator output is enabled, or inferable from any timed output.
Once the clock is known, every timing measurement converts into a cycle count, and cycle counts are the currency of this kind of reconstruction. A loop that runs every 400 microseconds at 16 MHz is 6,400 cycles, and 6,400 cycles is a quantity that constrains what the loop can contain.
The second constraint is the pin assignment
A 44-pin device with fixed peripheral functions means the pin map is a statement about the firmware. Which pins are outputs, which are analog, which carry a serial function, and at what rate — all measurable, all constraining.
| Observation | Constrains |
|---|---|
| Pin driven at a fixed frequency | A timer, and its period |
| Pin toggling on an external event | An interrupt path and its latency |
| Analog pin with a known reference | An ADC configuration and its resolution |
| Serial line at a known rate | A UART or CAN configuration and its clock source |
The fourth row is the most informative on this family, because serial rates are exact. A bus running at a specific rate fixes the oscillator and the divider, and the oscillator is the input to every other calculation.
The third constraint is the response
Step the input. The output’s shape tells you the control law’s structure, independently of its parameters:
- Immediate proportion with no overshoot: proportional only.
- Slow approach with no steady-state error: integral action.
- Overshoot and ringing: derivative action, or a second-order plant.
- Saturation with a defined recovery: limiting logic, which is firmware behaviour and not plant behaviour.
Each of those is a structural statement, and structure is what a rebuild needs. Parameters follow from measurement once the structure is fixed.
Where a partial image helps
If some blocks are readable, they constrain the reconstruction directly. A readable boot region tells you the image format and the entry address. A readable application block tells you the instruction mix, which tells you what the compiler was, which tells you what the source probably looked like.
| Readable region | What it gives |
|---|---|
| Boot region | Entry address, update format, verification method |
| Lower application block | Vector table, initialisation, peripheral setup |
| Upper application block | Tables and constants, often the domain knowledge |
| Data array | Calibration values and settings layout |
The last row is the one that converts a reconstruction from approximate to precise. Calibration constants in the data array are the numbers the code uses, and their magnitudes and ordering reveal the scaling and the sequence of operations.
Assembling it
The reconstruction procedure that produces something testable:
- Measure the clock and derive the cycle budget for each observable period.
- Map the pins and identify each peripheral function and its configuration.
- Characterise the response to step, ramp and fault inputs.
- Read whatever regions are open, and extract the frame: vectors, initialisation, tables.
- Write an implementation to the constraints.
- Compare against the original at every observable point, and iterate on the differences.
Step six is where the work is. A first implementation meets the coarse constraints and misses the fine ones — an off-by-one in a scaling factor, a filter coefficient slightly wrong, a timing margin that differs. Each difference is information about the original.
Honest limits
- A reconstruction is an equivalent, not a copy. It will differ in details that are not observable.
- Behaviour that the device never exercises cannot be inferred, and a rebuild may therefore fail in conditions the original handled.
- On this family, protection is configuration bits and there is no password; once reads are gated, they stay gated until an erase, and an erase ends the reconstruction’s reference device.
The third point is a warning about method. A working reference device is the most valuable object in a backwards project, and it is destroyed by exactly the operation people reach for when a read fails.
Related reading
- PIC18F46K80 and the same family at 64K — where the larger array changes the timing budget.
- PIC18F25K80 and the CAN interface — the measurement that gives the most exact constraint.
- PIC18F66K80 and restoring a rebuilt image — what has to match for the rebuild to run.
FAQ
Can a rebuild be byte-identical? No. Reconstruction produces equivalent behaviour, not the original instruction stream.
What measurement matters most? The clock, because every other timing measurement depends on it.
Does a readable block help if the rest is closed? Yes. It fixes the instruction set in use, the calling conventions, and often the compiler.
What destroys a backwards project? Erasing the reference device to attempt a read. The reference is the source of every constraint.
How close is close enough? When the rebuilt device is indistinguishable at every point the application can observe.
Conclusion
Working from behaviour to code is constraint-solving: clock, pins, response, and whatever the array will still show. It produces an equivalent rather than a copy, and on a part whose reads are gated it is often the only direction available — which makes the reference device worth protecting more carefully than the file it might have produced.
PIC18F26K80: Getting Past “Secured Flash” as a Description
“Secured flash” is a conclusion, not an observation. It is what someone writes after a programmer returned zeros, and it collapses a set of quite different device states into one word. On a 64K part with four application blocks, a boot region and separate table-read protection, that collapse loses almost everything useful.
The useful version of the statement names which region is closed. That is obtainable, and it changes what the next step should be.
The layout that the word hides
The array is organised as a boot region at the bottom and application blocks above it, with protection applied per block. The boot region holds the reset vector and, usually, a loader.
| Region | Holds | Protectable separately |
|---|---|---|
| Boot region | Reset vector, loader | Yes |
| Application block 0 | Application entry, interrupt vectors | Yes |
| Application block 1 | Application code | Yes |
| Application block 2 | Application code | Yes |
| Application block 3 | Application code, constants | Yes |
Six independent decisions, in other words, each of which can be open or closed, readable or write-protected. A device described as “secured” is a device where all of them happen to be closed — or a device where one is closed and the read attempt hit it first.
The reading that distinguishes them
Protection state is held in configuration, and configuration is readable through the programmer. So the first operation on an unknown device is not a read of the array; it is a read of the configuration, followed by interpretation.
From it you learn, per block, whether reads are gated and whether writes are gated. Four combinations per block, six blocks, and the pattern tells you what the vendor intended:
- Boot region closed, application open — the vendor’s loader is secret, the customer’s code is not.
- Boot region open, application closed — the loader is documented and the application is the asset.
- Everything closed — the device shipped locked, and the only question is whether the password-equivalent exists (on this family there is none; the bits are the mechanism).
- Nothing closed — the device is readable and the word “secured” was a mistake.
The fourth case is more common than it should be, and it is worth eliminating before any technique is considered.
Behavioural evidence when blocks are closed
A device with a closed application block still runs, and its behaviour is measurable. Three measurements give a good deal:
Start-up timing. Measured from reset release to first output activity, it bounds the initialisation work — and a device with a loader spends longer at start-up than one without.
Bus traffic. A K80 in a CAN product emits frames from the first moments after reset if its loader announces itself. Silence at start-up then traffic later is a different architecture from traffic throughout.
Response to the loader entry condition. If the device accepts an update, the loader is present and functional, and the update format describes the application’s layout.
The third is the most valuable and the least used. A device that can be updated over CAN is a device whose application begins at a known address, whose image has a known format, and whose verification is defined — all stated by the loader’s behaviour.
What cannot be recovered and why
On this family there is no password to supply. Protection is a set of configuration bits; a device with the read bits set will not produce its array for any sequence of operations that does not first erase it.
That makes the honest boundary sharp:
- Configuration is recoverable.
- Behaviour is recoverable.
- The array is not, once read protection is set, unless it is erased first.
Any technique that claims otherwise is either erasing the device and calling the result a recovery, or reading a device that was not protected as believed.
A procedure that avoids waste
- Read and interpret the configuration.
- Identify which blocks, if any, are open, and read those.
- If the boot region is open, read the loader and extract the application’s expected layout.
- If a field-update path exists, exercise it and record the protocol.
- Decide, with the evidence, whether the remaining unknown justifies further work.
Step five is a decision, not a formality. On a device whose function is understood from behaviour and whose update path is functional, the value of further work is often zero — and saying so is more useful than continuing.
Related reading
- PIC18F26K80 and the protection settings in detail — the same silicon analysed from the bits rather than the regions.
- PIC18F25K80 and the CAN update path — the interface that usually decides the outcome.
- PIC18F23K22 and why erasing is not unprotecting — the mistake that turns a diagnosis into a loss.
FAQ
Is there a password on this family? No. Protection is configuration bits, and there is no value to guess.
Can a partially protected device be read? Yes, block by block, subject to the bits for each block.
Does a closed block still execute? Yes. Protection gates reads, not execution.
What does a working CAN update imply? That a loader exists at a known location, with a known image format and a defined entry point.
When is further work not worth it? When behaviour and update path together describe everything the project actually needs.
Conclusion
“Secured flash” describes a conclusion rather than a device. On the K80 family the device has six independent protection decisions, a readable configuration that states them, and behaviour that continues regardless. Naming which region is closed — and accepting that the array itself is not available once it is — turns a vague problem into a short, decidable list.
PIC18F25K80: CAN Is a Second Door Into the Same Room
When a device is chosen for its CAN controller, the product usually speaks CAN for more than control. Field updates over the vehicle or machine bus are common, and where they exist there is a bootloader in the device listening for them. That loader is a documented, functional, write-capable interface — and it is present whether or not the array is protected.
Starting from that interface rather than from the programmer changes the shape of the work. It answers different questions, and on many projects it answers the only questions that mattered.
What the CAN path provides
A bootloader reached over CAN typically implements:
- an entry condition, triggered by a specific frame or a pin state at reset;
- an identification exchange, so the host knows which device and which version answered;
- an erase command;
- a data transfer with addressing;
- a verification step, and a jump to the application.
Each of those is a fact about the design. The identification exchange especially: a loader that reports a version and a part identifier is telling you what the vendor considered sufficient to distinguish builds.
| Loader feature | What it reveals |
|---|---|
| Entry trigger | How production and service enter the loader |
| Identification | Part, version, sometimes a variant code |
| Erase granularity | How the vendor thinks about the memory map |
| Address scheme in transfers | Where the application is expected to live |
| Verification | Whether the loader checksums, and over what range |
The message objects are in RAM
The CAN controller holds its filter and message objects in RAM, configured by firmware at start-up. That matters for two reasons.
First, the configuration is a fingerprint. The set of identifiers a device accepts, the masks it applies, and the number of objects it uses describe the protocol it implements, and all of it is observable on the bus without any access to memory.
Second, because the objects are in RAM, they are not part of the flash image. A recovered image does not contain the device’s CAN configuration — it contains the code that writes it. Reproducing the configuration means running the code, not copying a table.
Reading the bus instead of the array
For a device on a working machine, the bus is a richer source than the array in one specific respect: it is live. Behaviour under real load is available, and the firmware’s decisions are visible as messages.
A capture gives:
- the identifier set, and therefore the message structure;
- the cycle times, and therefore the scheduler’s period;
- the payload layouts, and therefore the signals, scaling and units;
- the fault handling, when something is disconnected.
The fourth item is the one people forget to provoke. Disconnecting a sensor and capturing what the device does reveals its fault policy, which is usually a distinctive part of the firmware and not derivable from normal operation.
What the loader gives up
A CAN bootloader designed for field updates cannot be protected against being used. If it were, updates would not work. So on a device with a loader, there is always an interface that will accept a program.
That has a consequence worth stating: a locked K80 device with a working CAN loader is not a lost device. It is a device that can be restored to a known image at any time — and if the goal is a working unit, the loader is the whole solution.
The distinction between restoring and reading remains the same as everywhere else in this family. The loader writes. It does not read. A device restored through CAN is a device running a known program, not a device recovered.
When both are needed
Some projects need both: the unit restored, and the original’s behaviour understood. In that case the order is:
- Capture CAN traffic from the working device, including fault conditions.
- Exercise the loader and record its protocol.
- Restore a replacement unit with a known image and confirm it behaves like the original.
- If the original’s program is still required, treat that as a separate problem with separate techniques.
Step three is often the end of the project. Organisations frequently commission a “firmware recovery” when what they need is a supply of working units and a documented protocol — both of which are obtainable without reading a protected array.
Practical notes
- CAN bit timing depends on the device clock; a capture at the wrong rate produces error frames rather than data.
- Loader entry conditions vary; some require a specific frame within a short window after reset, others a pin held low.
- The loader may preserve the data array during updates, which means calibration survives a reflash — useful when restoring, and a source of surprise when it does not.
- A device that answers on CAN is running code; a failure to read its array says nothing about whether it is alive.
Related reading
- PIC18F26K80 and the protection settings on the same silicon — the gates that the loader operates behind.
- PIC18F26K80 and boot block mechanics — where the loader lives in the array.
- PIC18F45K80 and the 44-pin variant — the same family in a different package.
FAQ
Can the CAN loader read the existing program? No. It writes and verifies; it has no read command.
Does code protection stop the loader working? No. The loader writes, and protection gates reads.
Are CAN settings part of the flash image? The code that configures them is; the registers themselves are RAM and are rebuilt at start-up.
Why capture during faults? Because fault handling is firmware behaviour that normal operation does not exercise.
Is restoring through CAN the same as recovery? It produces a working unit running a known image. It does not recover what was there.
Conclusion
On a part built for CAN, the bus is a second door: a write channel with a protocol that must remain functional, and a live view of the firmware’s decisions. For most projects that door is enough, and the harder question — what was in the array — turns out not to be the one that needed answering.
PIC18F46K20: Where a 64K Copy Diverges From the Original
At sixty-four kilobytes the array is large enough that a copy is a serious operation and small enough that every byte is meaningful. Reading it and writing it elsewhere is mechanical. Making the second device behave like the first is not, and the divergences are all in places that a file comparison will show as differences with no obvious cause.
Four of them account for most failed replications.
One: padding between sections
Linkers align sections, and the space between them is filled with the erased value or with a defined padding byte depending on the toolchain’s settings. A copy that reproduces the code but not the padding differs in the gaps.
Does the padding matter? Sometimes. A routine that reads past the end of its table, or a checksum that covers an aligned range, will see the difference. On a part where a verification routine checksums a range rather than a section, padding is part of the verified content.
The rule: copy the array as read, gaps included, rather than reconstructing it from sections.
Two: regions that were never written
Not every address in a 64K array holds content. A device using 40K has 24K of erased flash, and a copy that fills those regions with anything else differs.
This is usually harmless, and it becomes visible when something reads the erased region deliberately — a version scan, a memory dump command, a self-test. A device that reports “unused space is zeros” on the original and “unused space is FF” on the copy is a device whose copy is detectable.
| Region | Original value | Copy risk |
|---|---|---|
| Programmed sections | Content | None if copied exactly |
| Section padding | Toolchain-defined fill | Differs if reconstructed |
| Unused flash | Erased value | Differs if filled |
| Configuration | Set at production | Differs if not copied |
| Data array | Per-unit | Differs by design |
Three: table encoding
Constant tables are where a copy is most likely to be subtly wrong, because the representation is a convention rather than a specification. A 16-bit constant in a table might appear as two words, as one word per byte, or as a single word if the values fit.
A copy taken byte for byte is correct by construction. A copy reconstructed from a disassembly is not, and the resulting errors are small — a filter coefficient that is slightly wrong produces a device that works and sounds different.
The rule is the same as for padding: copy the array, do not rebuild it.
Four: configuration
Configuration is not in the array and decides the oscillator, watchdog, brown-out and protection. It is discussed in detail elsewhere; here it belongs in the list because it is the divergence that produces the largest behavioural difference with the smallest file difference — often zero bytes of code difference.
The verification that catches all four
Compare four things, in this order:
- The array, byte for byte, including gaps and unused regions.
- The configuration, byte for byte, against the recorded source values.
- The data array, by decision — copied, or deliberately blank.
- Behaviour, on a bench, against recorded behaviour of the original.
Steps one and two catch everything mechanical. Step four catches what the files cannot: timing, start-up order, response to faults.
What a copy cannot reproduce
- Analog trim, which belongs to the die.
- Silicon revision, which decides errata.
- The unique identifier on parts that carry one.
- The device’s history, if the firmware records usage in the data array.
Each of those produces small, consistent differences that are properties of the device rather than defects in the copy. Recognising them prevents a long search for a bug that is not there.
The larger point
Replication is a matching problem with four dimensions, and the easiest one — the code — is the one that a file comparison addresses. The other three are configuration, data and silicon, and a replication that succeeds at the first and ignores the rest produces a device that runs and is not the same device.
Related reading
- PIC18F45K20 and distinguishing blocked reads — what has to succeed before replication begins.
- PIC18F44K20 and the order of operations — how the copy is written correctly.
- PIC18F43K22 and the four dimensions of a duplicate — the same argument at smaller scale.
FAQ
Does padding matter in a copy? Sometimes. If anything checksums an aligned range, it is part of the verified content.
Should unused flash be filled? No. Copy it as read, or leave it untouched.
Why do tables cause trouble? Because their encoding is a convention. A byte copy is correct; a reconstruction may not be.
What is the costliest divergence? Configuration, because it changes behaviour with no difference in the code.
Can a copy be exact? Only at the array level. Trim, revision and identifier belong to the die.
Conclusion
A 64K copy diverges in four places: padding, unused regions, table encoding and configuration. Three are solved by copying the array rather than rebuilding it, and the fourth by treating configuration as content. The remainder — trim, revision, identifier — cannot be copied, and knowing that saves the search for a bug that is a property of silicon.
PIC18F45K20: Two Kinds of “Blocked”, and Telling Them Apart
A device that will not give up its program has failed in one of two quite different ways. Either the read completed and returned a substitute value, or the read never completed at all. The first is protection working as designed. The second is an interface problem, and treating it as protection destroys devices.
The distinction is not subtle once stated, and it is constantly lost in practice, because both outcomes look like “the programmer could not read it”.
The two events
Substituted read. The device responds, in the expected number of cycles, with a value that is not the content. On this family the substitute is a fixed pattern, and it is stable: reading the same address ten times returns the same value ten times.
Failed read. The device does not respond, responds with an error, times out, or returns a value that changes between attempts.
| Symptom | Meaning | Next step |
|---|---|---|
| Stable uniform values | Protection, or genuinely erased | Read configuration |
| Values change between reads | Interface, voltage, or sampling | Fix the connection |
| No response at all | Entry sequence failed | Check programming mode |
| Response, wrong length | Wrong part selected in the tool | Correct the device selection |
The third row is the one that wastes the most bench time and is the easiest to fix: the device never entered programming mode, so nothing was ever attempted.
Entry, and why it fails quietly
Programming mode is entered by a specific sequence on specific pins, sometimes with a raised voltage. If the sequence is not applied correctly — a pin held by a circuit on the board, a capacitor slowing an edge, a supply that does not reach the required level — the device simply carries on executing its program.
Nothing reports this. The programmer’s tool may report a failure, or may report success with implausible data, depending on how it handles the absence of a response.
On this family the low-voltage programming option changes which entry methods are accepted, and a device configured without it requires the higher-voltage sequence. That is a configuration fact with a hardware consequence, and it is invisible until someone tries to connect.
Why stable values suggest protection
A protected read goes through the same path as a normal one: the address is presented, the array is accessed, and the substitution happens at the output. The timing is identical and the result is deterministic.
That determinism is the diagnostic. Protection produces the same answer every time; a marginal connection does not.
The caveat is erasure: an erased block also returns a stable value. So stability separates “device or interface” but not “protected or blank”. The configuration word separates those, and it is why every article in this series begins with it.
Protection as a set of blocks
Four blocks, each with a read bit and a write bit. The state that matters is the pattern, not the aggregate:
- all open — a development device or an oversight;
- first open, rest closed — a loader is visible;
- first closed, rest open — the vectors are gone;
- all closed — a shipped, locked product.
Each pattern leads to a different next step. The second suggests exercising the update path. The third suggests decoding without anchors. The fourth suggests behavioural work or stopping.
What is worth trying, in order
- Confirm entry: does the device respond at all, with the expected device identifier?
- Read the configuration; it states the pattern.
- Read a known-populated address; the reset vector if the first block is open.
- Read each block in turn; record the boundary.
- Only then consider the device’s behaviour.
Steps one to four take minutes and eliminate the majority of misdiagnoses. Everything expensive comes after, and most of the time it is not needed.
The cost of getting it wrong
The specific cost on this family is that the remedy for a failed entry looks like the remedy for protection: erase the device and start again.
On a device whose content was expendable, that works. On one whose content was the point of the exercise, it converts a solvable problem into an unsolvable one — and it does so at the moment when the diagnosis was least certain.
That is the argument for the sequence above, and it is why the sequence appears in every article about this family.
Related reading
- PIC18F44K20 and the order of operations — what to do once a read has succeeded.
- PIC18F43K20 and the two-block array — the same analysis with fewer boundaries.
- PIC18F23K20 and configuration as the first read — the read that distinguishes protection from erasure.
FAQ
How do I tell protection from a bad connection? Repeat the read. Protection is deterministic; a marginal connection is not.
Why does the device not enter programming mode? Usually a pin held by the circuit, an edge slowed by capacitance, or a configuration that disables the low-voltage entry.
Does an erased device read like a protected one? Yes at a single address. The configuration distinguishes them.
Which block holds the vectors? The first, along with start-up code.
What erases the protection? A full erase, which also erases the content. That is why the diagnosis comes first.
Conclusion
Two kinds of blocked read, distinguishable by repetition and by whether the device responds at all. Separating them costs minutes and prevents the one irreversible mistake available on this part — erasing a device whose contents were the reason for the exercise.
PIC18F44K20: The Order of Operations in a Restoration
The sequence most people use is the sequence the task suggests: erase the device, write the code, set the configuration. It works often enough to become a habit, and it fails in a specific and confusing way — a device that is half programmed, refuses further writes, and reports nothing useful.
The failure has a cause, and it is the same cause that makes the correct order counter-intuitive: configuration is not a setting applied to the device, it is content that governs access to the device.
What the order determines
Configuration decides which regions are write-protected, which are read-protected, and how the device may be entered. Once write-protection is in place for a region, that region cannot be programmed.
So writing configuration first means the remaining programming operations run against bits that may forbid them. Whether the result is a device that works depends on whether the configuration happened to leave the rest writable — which is a coin flip depending on the source’s protection state.
| Order | Outcome |
|---|---|
| Erase → code → configuration | Works, provided configuration is written last |
| Erase → configuration → code | Works only if configuration leaves everything writable |
| Erase → configuration with protection → code | Fails partway, device needs a second erase |
The third row is the one that produces a confusing support case, because the tool reports success on the configuration write and then fails on the first code write, which reads as a tool problem.
The full sequence that holds
- Erase. Full erase, including configuration. A partial erase leaves configuration from a previous life, and the new program inherits it.
- Verify erased. Read a few addresses across the array and confirm the erased value. An incomplete erase is invisible until programming fails.
- Program code. The application image, at its addresses.
- Program the data array, if it is being restored, or decide deliberately to leave it blank.
- Program configuration, last, with every field compared against the recorded source values.
- Verify. Read back code, data and configuration, and compare against records.
Step five last is the rule. Step two is the one people skip, and it is the one that catches a device whose erase did not complete — usually because the programming voltage was marginal.
Why configuration deserves its own step
Configuration is often treated as a checkbox in a programmer’s interface. On this family it is fourteen or so bytes with fields that decide oscillator, watchdog, brown-out, programming interface and protection.
Each of those changes behaviour, and each is invisible in the code image. A restoration that gets eleven of them right produces a device that works in the lab and fails in the field, typically on the watchdog or the brown-out setting.
The discipline is to read the configuration from the source device, record it as bytes, and compare it byte for byte after writing — not field by field through a tool’s display, which merges and hides reserved bits.
The data array decision
This family has a separate data array, separately protected. During a restoration it must be an explicit choice:
- copy the source’s contents, reproducing its calibration and accumulated state;
- leave it blank, letting the firmware initialise defaults;
- write known values from documentation.
Whichever is chosen, the choice belongs in the record. “The data array was left as erased” is a statement that answers questions later; silence does not.
Verification, and what it must include
Reading back and comparing is the only step that proves the restoration. It must cover:
- the code, word for word across the programmed range;
- the configuration, byte for byte;
- the data array, if it was written;
- the behaviour, on a bench, against the recorded behaviour of the source.
The fourth is the one that catches a correct file and a wrong configuration, because a wrong oscillator shows in timing long before it shows in logic.
When a restoration fails
Three failure signatures and what they mean:
Programming fails partway with no obvious cause. Erase incomplete, or configuration written too early.
Device programs and does not run. Configuration points at a clock source the board does not provide, or the reset vector is not where the program puts it.
Device runs and behaves differently. Configuration fields other than the clock — watchdog, brown-out — or the data array.
All three are answered by comparing against the record, which is why the record is made before the source device is disturbed.
Related reading
- PIC18F43K20 and the smaller array — where the same sequence applies with less to lose.
- PIC18F45K20 and the four protection blocks — the configuration that makes ordering matter.
- PIC18F24K20 and the data array — the decision that belongs in the record.
FAQ
Why is configuration written last? Because it governs write access to the array. Written early, it can forbid the writes that follow.
Does a partial erase matter? Yes. Leftover configuration applies to the new program and produces behaviour nobody intended.
Should the data array be written? Only by decision. Leaving it blank is acceptable; leaving it undecided is not.
How is configuration compared? Byte by byte against the source’s recorded values, not through a tool’s field display.
What if the device programs and does not run? Usually the oscillator setting, or a reset vector that the program does not place where the configuration expects.
Conclusion
Restoration has an order because configuration is access control as well as content. Erase fully, verify the erase, program code and data, then write configuration and compare it byte for byte. The sequence is short, the failure it prevents is expensive, and the record made beforehand is what makes any of it checkable.
PIC18F43K20: Eight Kilobytes, Two Vectors, and No Room to Hide
There is a relationship between array size and how much a firmware can conceal. Eight kilobytes is roughly four thousand instructions, and after start-up code, a serial stack and a couple of tables, the application-specific part is small — small enough that the code’s structure is largely determined by what the device does.
The 40-pin package sharpens this. More pins means more I/O, which means the firmware’s job is visible at the edges. A device with eight pins could be doing almost anything; a device with thirty-two I/O pins is doing something specific, and the specific thing is measurable.
Where the vectors sit, and why it matters
On this family the reset vector and the interrupt vectors occupy the bottom of the array, in the same protection block as the start of the application. That has a consequence for partial reads: if the first block is protected, the vectors are gone.
Losing the vectors costs more than losing the same number of bytes elsewhere, because the vectors are the primary anchor for disassembly. Without them, entry points have to be found by scanning for branch-shaped words and testing candidates — a slower and less certain method.
| Block | Typical contents | What is lost if closed |
|---|---|---|
| First | Vectors, start-up, small functions | Every entry point |
| Second | Application body | Control flow details |
| Third, fourth (if present) | Tables, remaining code | Domain constants |
On an 8K part there are two blocks, so the loss is coarser: half the application, including the anchors.
Reading with a missing lower block
If the first block is closed and the second is not, the image begins with code whose entry points are unknown. Three techniques recover the structure:
- Scan for call targets. A call instruction encodes its destination. Collect every destination in the readable region and the frequently-called addresses will emerge as functions.
- Look for the interrupt handlers by shape. A handler saves context, does a little work, restores and returns. The shape is recognisable even without the vector that points at it.
- Use the tables. On a small part, tables are indexed by measured quantities; the instructions that read them identify the routines that use them.
None of these is as good as the vector table. All of them are enough to produce a call graph for a four-thousand-instruction image.
The pin map as a specification
With 40 pins, the pin assignment is most of the specification. What can be measured without any access to memory:
- which pins are outputs, and their idle states;
- which toggle at a fixed rate, and therefore which timers are configured;
- which carry a serial protocol, and at what rate;
- which are analog inputs, from the presence of a reference and the shape of the readings.
Add the response of each output to a change in each input and the interaction structure appears. On a device this size that is often enough to describe the application completely, with the code contributing confirmation rather than discovery.
Protection on this part
Two protection concepts, as on the rest of the family: code protection per block, and write protection per block, plus table-read protection for reads from code.
For an 8K device the practical effect is stark. A protected part loses half its array at minimum, and a fully protected part loses all of it. There is no partial outcome that leaves a useful fraction, which is why the behavioural route matters more here than on a 64K part.
What an 8K image tells you about its compiler
Small images have a distinctive texture. A compiler optimising for size emits denser code, reuses registers more aggressively, and inlines short functions. The result is a listing where function boundaries are less obvious and where a routine may be entered at more than one point.
That texture is worth recognising, because applying a 64K-part reading method to an 8K image produces confusion: the code does not look like well-separated functions, because it was not written that way.
Expectations
- Half the array is the smallest useful unit of loss on this part.
- The vectors are worth more than their size.
- The pin map is a specification in its own right.
- A fully protected 8K device is a behavioural problem, and a short one.
Related reading
- PIC18F44K20 and the 16K version — what one more block buys.
- PIC18F23K20 and reading configuration first — the step that decides whether the lower block is available.
- PIC18F45K20 and four protection blocks — where granularity starts to help.
FAQ
How many protection blocks does an 8K member have? Two. On a device this size that is a coarse division.
Where are the interrupt vectors? At the bottom of the array, in the first block. If that block is closed, they are unavailable.
Can entry points be found without vectors? Yes, from call targets and handler shapes, at some cost in certainty.
Is the pin map really a specification? For a device with this many I/O pins, largely yes — it defines the interfaces the firmware serves.
Why does the code look unsmooth? Small-image compilers optimise for size, which merges and inlines functions.
Conclusion
An eight-kilobyte part in a forty-pin package is legible because it cannot afford to be otherwise. The vectors are the expensive loss, the pin map is the specification, and the analysis is short enough to complete. Where the array is closed, that brevity is the compensating advantage.
PIC18F26K20: Recovery Produces an Image, Not Source Code
The request is usually phrased as “recover the source”. It is a reasonable way to describe the goal — something that can be modified, rebuilt and maintained — and it is not what a flash array contains. The array contains instructions and constants. Everything a source file carries beyond that was discarded by the compiler.
Understanding the size of that gap is not pedantry. It determines what can be done with a recovered image, what has to be rebuilt, and what nobody should promise.
What the compiler discards
| Present in source | Present in the image |
|---|---|
| Instructions | Yes |
| Constant values | Yes |
| Function boundaries | Partially — called from somewhere, or not |
| Names | No |
| Types | No |
| Comments, structure | No |
| Loop constructs | No — only branches |
The first two are the program. The rest is the part that makes a program maintainable, and it is gone in a way that no tool recovers. A disassembler produces labels like code_0x1A42, because that is the only name the information supports.
What an image does support
Three things, and they are more than they sound:
Behaviour. The instructions, executed, produce observable effects. That is the program’s meaning, and it survives complete loss of structure.
Structure, partially. A region called from twelve places is a utility. A region with a jump table is a dispatcher. A region that reads a table and multiplies is a filter. These are inferences, and they are usually right.
Layout. Where code lives, where tables live, how much space each occupies. That is a map of the application’s size and complexity.
What is missing is the vocabulary: what the variables mean, what the functions are for, what the constants represent.
The reconstruction gap in practice
A team that receives an image and needs to modify it faces a specific, bounded problem. Their options:
- Patch the image directly. Change a constant, redirect a branch. Feasible for small changes and requires no source.
- Reconstruct a source that compiles to the same behaviour. Feasible for small programs, and rarely byte-identical.
- Rebuild from specification. Feasible always, and produces something maintainable rather than something equal.
The second option is what people usually expect from “recovery”, and it is the least reliable of the three: the result is a program that behaves like the original and shares none of its code, maintained by people who have never seen either.
Why byte-identical matters less than it seems
There is a persistent expectation that a recovered program should rebuild to the same binary. It cannot, in general, and it is not required. What is required is that the replacement satisfies the same constraints:
- the same interfaces, at the same rates;
- the same timing behaviour;
- the same responses to the same inputs, including faults;
- the same use of non-volatile storage.
Those four are testable. Byte-identity is not even a good proxy for them, since a compiler change produces different bytes with identical behaviour.
The 64K case
On this part the array is large enough to hold a substantial application, which makes the structure question more pressing. A 64K image has real modularity: multiple files’ worth of code, a scheduler, protocol stacks, tables.
That modularity is visible in the call graph, and the call graph is the closest thing to a file structure that survives. Reconstructing along the call graph’s clusters produces something that resembles the original’s organisation, which is why a disciplined reader can produce a source tree that a maintainer recognises — even though every name is invented.
Honest statements to make
- The image can be recovered; the source cannot.
- Behaviour can be characterised; intent has to be inferred.
- A reconstruction can be maintained; a copy can only be patched.
- A byte-identical rebuild is not a realistic objective, and not a useful one.
Saying these four things at the start prevents the most common disappointment in this work, which is a technically successful recovery being received as a failure because it was not what was imagined.
Related reading
- PIC18F25K20 and what the hex file records — the container the image travels in.
- PIC18F26K22 and the 64K address space — how a large image is laid out and read.
- PIC18F45K80 and reconstruction from behaviour — the route when no image is available at all.
FAQ
Can source code be recovered from a microcontroller? No. Instructions can. Names, types and structure were discarded at build time.
Is a disassembly usable for maintenance? For patching, yes. For development, a reconstruction is usually better.
Why not aim for a byte-identical rebuild? Because compiler and library differences make it unattainable, and behaviour is the objective that matters.
What is the most valuable output of recovery? A characterised behaviour plus an image: the first for rebuilding, the second for replacement.
Does array size change the answer? It changes the scale, not the nature. Larger images have more structure to infer, and no more names.
Conclusion
Recovery yields an image, and an image is behaviour rather than source. The gap is not closable by effort, and recognising it early turns an impossible expectation into a tractable one: characterise the behaviour, keep the image, and rebuild only where maintenance is required.
PIC18F25K20: What a Hex File of a Locked Part Can Honestly Contain
A hex file has a shape that implies completeness: records from the first address to the last, an end-of-file marker, checksums on every line. It is a format that reports success. Nothing in it says “this region was not readable”, because the format has no way to say that.
On a device read under protection, the file therefore contains less than it appears to. The gap between appearance and content is where recovered firmware goes wrong — not at the moment of recovery, but years later, when someone programs the file and cannot understand why the device behaves oddly.
What the format can express
Intel HEX can express: data at an address, an end marker, an extended address change. That is all. It cannot express a hole, an uncertainty, or a comment.
| Fact about the recovery | Expressible in hex |
|---|---|
| Bytes at an address | Yes |
| A region that was not readable | No |
| Whether configuration was captured | Only as records, with no marker |
| The silicon revision | No |
| Which blocks were protected | No |
The first row is the format’s whole vocabulary. Everything else has to live outside it.
Filling a hole: the three options
When a region could not be read, a file has to do something about it. Three choices, each defensible, each with a different failure mode:
Omit the region. The file has no records there. A tool loading it leaves those addresses at whatever the destination contains — usually erased, sometimes not.
Fill with the erased value. The file has records covering the region, filled with the value an erased cell reads as. The file is continuous and the content is a lie that looks like a blank device.
Fill with zeros. The same, with a value that is also what a protected read returns, which makes the file indistinguishable from one captured from an unlocked device with a zeroed region.
The second is the most common and the least harmful in practice, because a device with an erased region behaves like an unprogrammed one and the symptom is obvious. The third is the most dangerous, because a run of zeros looks like data and produces a device that runs into a halt or a reset somewhere unexpected.
Configuration, and the assumption that it came along
Whether the configuration is in the file depends on the export. Many tools write it only if asked. A file without it produces a device configured however the destination part happened to be configured, which on a virgin part means factory defaults.
Factory defaults are frequently wrong for the application: internal oscillator instead of crystal, watchdog off, brown-out at the lowest setting. The device runs and behaves differently from the original in ways that look like code differences.
The remedy is not in the file. It is in the record kept alongside: the configuration bytes, read from the source device, stored with the image as text.
The header that makes a file durable
A recovered image should be accompanied by, at minimum:
- source device part number, revision and unique identifier if present;
- configuration bytes, verbatim;
- block map, stating which regions were read and which were not;
- the date and the method;
- what the data array contained, if it was read.
Five lines of text. Their absence is why files recovered in one year are misinterpreted in another, and the cost of writing them is minutes.
Why “reverse” is the right verb here
Working with a locked device of this size inverts the usual direction. You do not start from the code and ask what it does; you start from the device and ask what the code must be. Everything measurable — timing, pin behaviour, protocol, response — is evidence about an image that is only partly available.
The hex file is then a record of what was obtained, not a description of the device. Treating it as the latter is the mistake this article exists to prevent.
Practical sequence
- Read what is readable; record the block map as you go.
- Read the configuration.
- Record part number and revision.
- Assemble the file, choosing deliberately among omit, fill and zero.
- Write the header.
- Verify by loading the file into a tool that displays its address map, and confirm the map matches the record.
Step six is the only defence against the silent errors, because it is the only step that compares what the file says against what the device gave.
Related reading
- PIC18F24K22 and finding the readable boundary — how the block map is established.
- PIC18F23K20 and reading configuration first — the step that supplies the header’s most important line.
- PIC18F26K20 and what recovery does not produce — why the result is an image and not source.
FAQ
Can a hex file represent an unreadable region? No. The format carries data and addresses, and nothing about provenance.
Which fill value is safest? The erased value, because a device with an erased region fails obviously rather than subtly.
Is configuration always included in an export? No. It must be checked and, if absent, recorded separately.
Why does a recovered file produce a device with the wrong clock? Because the configuration was not captured and the destination used factory defaults.
What is the minimum documentation? Part, revision, configuration bytes, block map, date and method.
Conclusion
A hex file is a record of bytes, and a recovered file is a record of the bytes that were obtainable. The format cannot say so, which makes the accompanying header part of the deliverable rather than an optional courtesy — and makes the honest description of a partial recovery more valuable than a file that pretends to be complete.
PIC18F24K20: Program and Data Are Two Arrays With Two Rules
“Program and data” in a recovery request usually means two things: the code, and whatever constants the code depends on. On this family those two things live in different arrays with different access rules and different protection bits, and the difference is not academic — one of them is routinely readable when the other is not.
For an instrumentation product, that asymmetry is decisive. The code describes what the device does; the data array describes how it is calibrated. A readable data array on a locked device can therefore yield the more commercially sensitive half of the design.
The two arrays
Program memory holds instructions and, in practice, also constant tables. Data EEPROM is a separate array, byte-writable, addressed through a small register window rather than through the program counter.
| Property | Program array | Data EEPROM |
|---|---|---|
| Addressed by | Program counter, table reads | Address registers |
| Granularity | Words | Bytes |
| Protection bit | Per block | One bit, separate |
| Erased by | Bulk or block erase | Bulk erase, or byte write |
| Typical contents | Code, tables | Calibration, settings, counters |
The separate protection bit is the whole point of this article. Set program protection and leave data protection clear, and the device will hand over its constants while refusing its code. The reverse is unusual but possible.
Why a designer would do that
The configuration is not a mistake. Consider a product whose calibration is performed at end of line and written into the data array, and whose code is the vendor’s intellectual property. Protecting the code and leaving the data readable lets a service technician verify or re-enter calibration without exposing the firmware.
That is a reasonable policy and it has a side effect: any technician, or anyone with a programmer, can read the calibration. For a sensor product, calibration curves frequently encode as much design effort as the firmware.
Reading the data array
Where the data array is unprotected, reading it is straightforward and does not depend on the program array at all:
- Enter programming mode.
- Read the data EEPROM address range through the programmer’s data-array access.
- Record it as bytes, not words — the array is byte-organised even though the core is word-organised.
The third step matters for the same reason it matters for program memory. A file that represents bytes as words doubles every value and produces constants that are wrong by a factor of 256, which then look like plausible fixed-point values in a disassembly.
What the data array tells you about the code
A data array is a description of the program’s assumptions. Three patterns are worth extracting:
Calibration constants grouped in a fixed order. The order matches the order the code reads them, which reveals the sequence of measurements the device performs.
Stored settings with defaults. A block of bytes that looks like a configuration record with a version byte at the front identifies the settings structure the code parses.
Counters and timestamps. Uniform-looking runs with occasional increments are usage counters, and they reveal how the device records its own history — useful for dating a build.
None of that is code, and all of it constrains the code. A rebuild that reads the same constants in the same order is far more likely to reproduce the original behaviour than one written from first principles.
When the program array is readable and the data is not
The opposite configuration appears when data protection was enabled and later forgotten, or when a bootloader set it. The practical effect is unusual: the code can be read, and its constants cannot.
The recovery then depends on the code being self-sufficient. Some firmware copies its constants into RAM at startup from the data array; the copy routine reveals the layout, and the values themselves have to be measured from the device’s behaviour — an instrument that reads slightly wrong tells you its offset and gain by how wrong it is.
Bulk erase and the order of loss
A complication specific to this family: a bulk erase clears both arrays. There is no way to erase the program array and keep the data array, or the reverse.
That makes the sequence of operations a decision rather than a procedure. Read both arrays, in whatever order the protection allows, before erasing anything — because after an erase there is nothing left to read and no partial outcome to salvage.
The rule is worth stating as a rule because it is violated constantly: on a device whose program is protected and whose data is not, an erase performed to remove program protection destroys the data first, and it is the data that was readable.
Practical checklist
- Read the configuration; establish the state of both protection bits.
- Read the data array first if it is open, and record it byte-exact.
- Read the program array if it is open, and record the block map.
- Only then consider any operation that modifies the device.
- When comparing against a known build, compare the data array separately — it differs between units by design.
The last item prevents a common false conclusion: two units with identical firmware will have different data arrays, and a comparison that expects them to match will report a difference that means nothing.
Related reading
- PIC18F23K20 and the configuration registers — where both protection bits are set.
- PIC18F25K22 and rebuilding a working part — what has to match besides code.
- PIC18F26K20 and the limits of source recovery — why a recovered image is not source.
FAQ
Does program protection cover the data EEPROM? Not on this family. The data array has its own protection bit.
Can the data array be read while the program array is locked? Yes, if data protection is clear. That is a common production configuration.
Does a bulk erase clear both arrays? Yes. Neither array survives it.
Are data arrays identical across units of the same product? No. Calibration differs by design, so comparisons must treat the data array separately.
Is the data array byte-addressed? Yes, and recording it as words corrupts every value.
Conclusion
Two arrays, two protection bits, one erase that clears both. On this part the data array is frequently the readable half and the informative one, which makes the order of operations a decision with consequences rather than a formality — and makes “program and data” a request that needs to specify which is which.