Skip to content

Instantly share code, notes, and snippets.

@Un1Gfn
Last active April 5, 2024 15:50
Show Gist options
  • Save Un1Gfn/59998ce82e1fc0e53519c5a676f63716 to your computer and use it in GitHub Desktop.
Save Un1Gfn/59998ce82e1fc0e53519c5a676f63716 to your computer and use it in GitHub Desktop.
// https://cmcenroe.me/2018/01/30/fbclock.html
// gcc -std=gnu11 -Wall -Wextra -O0 -g framebuffer.c
// fbgrab -d /dev/fb0 -s 5 -v -z 9 framebuffer.png
#include <assert.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
int main(){
int fb=open("/dev/fb0",O_RDWR);
assert(fb>0);
// https://www.kernel.org/doc/Documentation/fb/api.txt
// https://www.kernel.org/doc/html/latest/driver-api/frame-buffer.html?highlight=fb_var_screeninfo
struct fb_var_screeninfo info=(struct fb_var_screeninfo){};
assert(ioctl(fb,FBIOGET_VSCREENINFO,&info)==0);
size_t len=4*info.xres*info.yres;
uint32_t *buf=mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fb, 0);
assert(buf!=MAP_FAILED);
printf("\033[999E\n"); // Move cursor to the bottom
printf("\033[2K\n");
printf("\033[3J\n");
#define buf(r,c,color) buf[r*info.xres+c]=color & 0x00FFFFFF
#define vline(c,color,rBeg,rEnd) {for(uint32_t r=rBeg;r<=rEnd;++r)buf(r,c,color);}
#define hline(r,color,cBeg,cEnd) {for(uint32_t c=cBeg;c<=cEnd;++c)buf(r,c,color);}
#define area(color,rBeg,rEnd,cBeg,cEnd) {for(uint32_t r=rBeg;r<=rEnd;++r)for(uint32_t c=cBeg;c<=cEnd;++c)buf(r,c,color);}
// vline(10,0xFFFFFF,10,100);
const uint32_t rBeg=10;
const uint32_t rEnd=110;
uint32_t cBeg=0;
uint32_t cEnd=0;
#define next {cBeg=cEnd+10;cEnd=cBeg+100;}
next;area(0xFFFFFF,rBeg,rEnd,cBeg,cEnd);
next;area(0x00FFFF,rBeg,rEnd,cBeg,cEnd);
next;area(0xFF00FF,rBeg,rEnd,cBeg,cEnd);
next;area(0xFFFF00,rBeg,rEnd,cBeg,cEnd);
next;area(0xFF0000,rBeg,rEnd,cBeg,cEnd);
next;area(0x00FF00,rBeg,rEnd,cBeg,cEnd);
next;area(0x0000FF,rBeg,rEnd,cBeg,cEnd);
// free(buf); // crash
buf=NULL;
return 0;
}
@pmelly93
Copy link

pmelly93 commented Apr 5, 2024

free(buf) crashes because this operation is invalid.
You must call munmap(buf, len) then close(fb) as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment