Skip to content

Commit

Permalink
Adjust isRiscV helper to check for PVM\0 bytes (#1895)
Browse files Browse the repository at this point in the history
* Adjust `isRiscV` helper to check for `PVM\0` bytes

* Also check for ELF

* Adjust tests

* Update description
  • Loading branch information
jacogr authored Nov 17, 2023
1 parent a2cfdb8 commit bd21e73
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Contributed:
Changes:

- Adjust logger check for `process.env`
- Adjust `isRiscV` helper to check for `PVM\0` bytes
- Drop support for Node 16 (EOL 11 Sep 2023)
- Upgrade dependencies to latest stable versions

Expand Down
14 changes: 10 additions & 4 deletions packages/util/src/is/riscv.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,31 @@
import { isRiscV } from './index.js';

describe('isRiscV', (): void => {
it('is false on non-risc-v header', (): void => {
it('is false on non-elf/non-pvm header', (): void => {
expect(isRiscV(new Uint8Array([0, 97, 115, 109, 1, 2, 3]))).toEqual(false);
});

it('is false on partial-risc-v header', (): void => {
it('is false on partial-elf/pvm header', (): void => {
expect(isRiscV(new Uint8Array([0x7f, 0x45, 0x4c]))).toEqual(false);
});

it('is false on empty byte before risc-v header', (): void => {
it('is false on empty byte before elf/pvm header', (): void => {
expect(
isRiscV(
new Uint8Array([0x00, 0x7f, 0x45, 0x4c, 0x46, 0xff, 0x00, 0x42, 0x23])
)
).toEqual(false);
});

it('is true when a risc-v header is found', (): void => {
it('is true when a elf header is found', (): void => {
expect(
isRiscV(new Uint8Array([0x7f, 0x45, 0x4c, 0x46, 0xff, 0x00, 0x42, 0x23]))
).toEqual(true);
});

it('is true when a pvm header is found', (): void => {
expect(
isRiscV(new Uint8Array([0x50, 0x56, 0x4d, 0x00, 0xff, 0x00, 0x42, 0x23]))
).toEqual(true);
});
});
12 changes: 11 additions & 1 deletion packages/util/src/is/riscv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,24 @@
import { u8aEq } from '../u8a/eq.js';
import { isU8a } from './u8a.js';

// general elf header
const ELF_MAGIC = new Uint8Array([0x7f, 0x45, 0x4c, 0x46]); // ELF magic bytes: 0x7f, 'E', 'L', 'F'

// contract-specific PVM header
const PVM_MAGIC = new Uint8Array([0x50, 0x56, 0x4d, 0x00]); // 'P', 'V', 'M', 0x00

/**
* @name isRiscV
* @summary Tests if the input has a RISC-V header
* @description
* Checks to see if the input Uint8Array contains a valid RISC-V header
*/
export function isRiscV (bytes: unknown): bytes is Uint8Array {
return isU8a(bytes) && u8aEq(bytes.subarray(0, 4), ELF_MAGIC);
if (isU8a(bytes)) {
const start = bytes.subarray(0, 4);

return u8aEq(start, PVM_MAGIC) || u8aEq(start, ELF_MAGIC);
}

return false;
}

0 comments on commit bd21e73

Please sign in to comment.