Skip to content

Instantly share code, notes, and snippets.

@pelletier
Last active October 10, 2023 17:10
Show Gist options
  • Select an option

  • Save pelletier/7b679c2a010ae11604a878df2b6ad130 to your computer and use it in GitHub Desktop.

Select an option

Save pelletier/7b679c2a010ae11604a878df2b6ad130 to your computer and use it in GitHub Desktop.

Revisions

  1. pelletier revised this gist Oct 10, 2023. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions avx2_vpblendvb.c
    Original file line number Diff line number Diff line change
    @@ -66,3 +66,10 @@ int main(int argc, char **argv) {

    return 0;
    }


    // Output:
    //
    // page at: 0x7f2e2ae94000
    // -> FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00
    // segmentation fault
  2. pelletier created this gist Oct 10, 2023.
    68 changes: 68 additions & 0 deletions avx2_vpblendvb.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    #include <immintrin.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/mman.h>

    const char mask_bytes[] = {
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,

    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    };

    char *ymm_s(__m256i ymm) {
    static char buf[32 * 3];

    char v[32];
    memcpy(v, &ymm, sizeof(v));

    for (int i = 0; i < 32; i++) {
    sprintf(&buf[i * 3], "%02X ", v[i]);
    }
    buf[32 * 3 - 1] = 0;

    return buf;
    }

    int main(int argc, char **argv) {
    int page = 4096;

    char *p = mmap(NULL, 2 * page, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (p == 0) {
    fprintf(stderr, "could not mmap\n");
    return 1;
    }

    int err = mprotect(p, page, PROT_READ | PROT_WRITE);
    if (err != 0) {
    fprintf(stderr, "could not change protection of first page: %d\n", err);
    return 1;
    }

    printf("page at: %p\n", p);

    memset(p, 'X', page);

    // 31 bytes from end of good page. 1 byte in the protected page
    char *start = p + page - 31;

    __m256i mask =
    (__m256i)(_mm256_loadu_si256((__m256i const *)(mask_bytes + 1)));
    printf("-> %s\n", ymm_s(mask));

    __m256i zero = {0, 0, 0, 0};
    __m256i out;

    // segfault => touching read-protected page
    asm("vpblendvb %3, %2, %1, %0"
    : "=x"(out)
    : "x"(zero), "m"(*(__m256i *)(start)), "x"(mask));

    printf("== %s\n", ymm_s(out));

    return 0;
    }