The non-android ASharedMemory_create has a bug, where if two calls to create memory regions use the same 'name', they will be mapped to the to same /dev/shm file and trip over each other (particularly if they're different sizes).

This CL ensures that each created memory region is unique.

PiperOrigin-RevId: 322593774
Change-Id: Ib1137045604955871dd2e33aae8205275201d4b1
This commit is contained in:
A. Unique TensorFlower 2020-07-22 09:46:33 -07:00 committed by TensorFlower Gardener
parent 3ebd3f8ff4
commit 23f6e460f3

View File

@ -20,6 +20,7 @@ limitations under the License.
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <cstdlib>
#ifdef __ANDROID__
@ -64,8 +65,20 @@ void* LoadFunction(void* handle, const char* name, bool optional) {
#ifndef __ANDROID__
// Add /dev/shm implementation of shared memory for non-Android platforms
int ASharedMemory_create(const char* name, size_t size) {
int fd = shm_open(name, O_RDWR | O_CREAT, 0644);
int ASharedMemory_create(const char* /* name */, size_t size) {
// name should not be used to identify the memory region (hence
// 'anonymous' shared memory). Generate a unique name for every create call.
char _tmpname[L_tmpnam];
if (tmpnam_r(_tmpname) == nullptr) {
return -1;
}
// tmpnam will produce a string containing with slashes, but shm_open
// won't like that.
std::string _name = std::string(_tmpname);
std::replace(_name.begin(), _name.end(), '/', '-');
int fd = shm_open(_name.c_str(), O_RDWR | O_CREAT, 0644);
if (fd < 0) {
return fd;
}