Add support for mmap(2)

This commit is contained in:
Michal Moskal 2017-07-07 18:26:49 +01:00
parent 08d4af19b0
commit b86a552a5b
4 changed files with 116 additions and 0 deletions

76
libs/core/mmap.cpp Normal file
View File

@ -0,0 +1,76 @@
#include "pxt.h"
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace pxt {
PXT_VTABLE_CTOR(MMap) {
length = 0;
fd = -1;
data = 0;
}
void MMap::print() {
DMESG("MMap %p r=%d len=%d fd=%d data=%p", this, refcnt, length, fd, data);
}
void MMap::destroy() {
munmap(data, length);
close(fd);
}
}
namespace control {
/** Create new file mapping in memory */
//%
MMap *mmap(String filename, int size, int offset) {
int fd = open(filename->data, O_RDWR, 0);
if (fd < 0)
return 0;
void *data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
if (data == MAP_FAILED) {
close(fd);
return 0;
}
auto r = new MMap();
r->fd = fd;
r->length = size;
r->data = (uint8_t*)data;
return r;
}
}
namespace MMapMethods {
/**
* Write a number in specified format in the buffer.
*/
//%
void setNumber(MMap *buf, NumberFormat format, int offset, TNumber value) {
if (offset < 0)
return;
setNumberCore(buf->data + offset, buf->length - offset, format, value);
}
/**
* Read a number in specified format from the buffer.
*/
//%
TNumber getNumber(MMap *buf, NumberFormat format, int offset) {
if (offset < 0)
return fromInt(0);
return getNumberCore(buf->data + offset, buf->length - offset, format);
}
/** Returns the length of a Buffer object. */
//% property
int length(MMap *s) {
return s->length;
}
}

View File

@ -14,6 +14,20 @@ class Button;
typedef Button *Button_; typedef Button *Button_;
extern "C" void target_init(); extern "C" void target_init();
class MMap : public RefObject {
public:
int length;
int fd;
uint8_t *data;
MMap();
void destroy();
void print();
};
} }
#define DEVICE_EVT_ANY 0 #define DEVICE_EVT_ANY 0

View File

@ -7,6 +7,7 @@
"pxt.h", "pxt.h",
"pxtcore.h", "pxtcore.h",
"linux.cpp", "linux.cpp",
"mmap.cpp",
"control.cpp", "control.cpp",
"buttons.cpp", "buttons.cpp",
"screen.cpp", "screen.cpp",

25
libs/core/shims.d.ts vendored
View File

@ -1,4 +1,29 @@
// Auto-generated. Do not edit. // Auto-generated. Do not edit.
declare namespace control {
/** Create new file mapping in memory */
//% shim=control::mmap
function mmap(filename: string, size: int32, offset: int32): MMap;
}
declare interface MMap {
/**
* Write a number in specified format in the buffer.
*/
//% shim=MMapMethods::setNumber
setNumber(format: NumberFormat, offset: int32, value: number): void;
/**
* Read a number in specified format from the buffer.
*/
//% shim=MMapMethods::getNumber
getNumber(format: NumberFormat, offset: int32): number;
/** Returns the length of a Buffer object. */
//% property shim=MMapMethods::length
length: int32;
}
declare namespace control { declare namespace control {
/** /**