Skip to content

Commit

Permalink
Adding TLS workaroung for C applications (#50)
Browse files Browse the repository at this point in the history
* Adding TLS workaroung for C applications

* tls support for c

* fixed memory overrun

* Incorporating review comments

---------

Co-authored-by: Madhu B A <[email protected]>
  • Loading branch information
bamadhu and Madhu B A authored May 7, 2024
1 parent c9a5b6c commit f54bb5b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
19 changes: 19 additions & 0 deletions include/zos-tls.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,23 @@ template <typename T> class __Z_EXPORT __tlssim {
};

#endif // __cplusplus


struct __tlsanchor {
pthread_once_t once;
pthread_key_t key;
size_t sz;
};

typedef struct __tlsanchor tls_t;

#if defined(__cplusplus)
extern "C" {
#endif
void * __tlsValue(tls_t *);
char** __tlsArray(tls_t *,int ,int);
#if defined(__cplusplus)
}
#endif

#endif // ZOS_TLS_H_
26 changes: 21 additions & 5 deletions src/zos-tls.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

static void _cleanup(void *p) {
pthread_key_t key = *((pthread_key_t *)p);
Expand Down Expand Up @@ -74,11 +75,6 @@ static void *__tlsPtr(pthread_key_t *key) { return pthread_getspecific(*key); }
static void __tlsDelete(pthread_key_t *key) { pthread_key_delete(*key); }
#endif

struct __tlsanchor {
pthread_once_t once;
pthread_key_t key;
size_t sz;
};

struct __tlsanchor *__tlsvaranchor_create(size_t sz) {
struct __tlsanchor *a =
Expand All @@ -96,3 +92,23 @@ void __tlsvaranchor_destroy(struct __tlsanchor *anchor) {
void *__tlsPtrFromAnchor(struct __tlsanchor *anchor, const void *initvalue) {
return __tlsPtrAlloc(anchor->sz, &(anchor->key), &(anchor->once), initvalue);
}
void * __tlsValue(tls_t *a) {
void *val = NULL;
char * initvalue = (char *)malloc(sizeof(char)*(a->sz));
assert(initvalue != NULL);
bzero(initvalue,a->sz);
val = __tlsPtrAlloc(a->sz, &(a->key), &(a->once),(void *)initvalue);
free(initvalue);
return val;
}

char** __tlsArray(tls_t *a, int rows, int columns) {
char **val = NULL;
a->sz = ((rows*sizeof(char *))+(rows*columns*(a->sz)));
val = (char **)__tlsValue(a);
for (int i = 0; i < rows; i++) {
val[i] = (char*)(val + rows) + i * columns;
}
return val;
}

0 comments on commit f54bb5b

Please sign in to comment.