Пример #1
0
void rparse_do(char* yytext, int* out_line, bstring* out_filename)
{
    bstring str = bfromcstr(yytext);
    bstring space = bfromcstr(" ");

    // Determine the space positions.
    int firstSpace = binstr(str, 0, space);
    int secondSpace = binstr(str, firstSpace + 1, space);

    // Create substrings.
    bstring bline = bmidstr(str, firstSpace + 1, secondSpace - firstSpace);
    bstring file = bmidstr(str, secondSpace + 1, blength(str) - secondSpace);

    // Convert the line number and trim file name.
    int line = strtoul((const char*)bline->data, NULL, 10);
    btrimws(file);

    // Set variables.
    if (*out_filename == NULL)
        *out_filename = bfromcstr("");
    bassign(*out_filename, file);
    *out_line = line;

    // Free resources.
    bdestroy(file);
    bdestroy(bline);
    bdestroy(space);
    bdestroy(str);
}
Пример #2
0
Object*
String_to_object(bstring string)
{
  Object *obj = NULL;

  if (bchar(string, 0) == '"') {
    int len = blength(string) - 2;
    obj = Object_create_string(bmidstr(string, 1, len));
  } else if (bchar(string, 0) == '[') {
    int strlen = blength(string) - 2;
    bstring inner_str = bmidstr(string, 1, strlen);
    struct bstrList *elements = bsplit(inner_str, ',');

    int len = elements->qty;
    int i = 0;

    DArray *array = DArray_create(sizeof(Object*), len);
    bstring *ptr = elements->entry;
    for(i = 0; i < len; i++) {
      btrimws(*ptr);
      DArray_push(array, String_to_object(*ptr));
      ptr++;
    }
    obj = Object_create_array(array);
  } else {
    int value = atoi(bdata(string));
    if (value != 0) {
      obj = Object_create_integer(atoi(bdata(string)));
    } else {
      return NULL;
    }
  }
  return obj;
}
Пример #3
0
uint64_t bstr_to_doubleSize(const_bstring str, DataType type)
{
    int ret;
    bstring unit = bmidstr(str, blength(str)-2, 2);
    bstring sizeStr = bmidstr(str, 0, blength(str)-2);
    uint64_t sizeU = 0;
    uint64_t junk = 0;
    uint64_t bytesize = 0;
    if (blength(sizeStr) == 0)
    {
        return 0;
    }
    ret = str2int(bdata(sizeStr));
    if (ret >= 0)
    {
        sizeU = str2int(bdata(sizeStr));
    }
    else
    {
        return 0;
    }

    switch (type)
    {
        case SINGLE:
            bytesize = sizeof(float);
            break;

        case DOUBLE:
            bytesize = sizeof(double);
            break;

        case INT:
            bytesize = sizeof(int);
            break;
    }

    if ((biseqcstr(unit, "kB"))||(biseqcstr(unit, "KB")))
    {
        junk = (sizeU *1000)/bytesize;
    }
    else if (biseqcstr(unit, "MB"))
    {
        junk = (sizeU *1000000)/bytesize;
    }
    else if (biseqcstr(unit, "GB"))
    {
        junk = (sizeU *1000000000)/bytesize;
    }
    else if (biseqcstr(unit, "B"))
    {
        junk = (sizeU)/bytesize;
    }
    bdestroy(unit);
    bdestroy(sizeStr);
    return junk;
}
Пример #4
0
static int
parse_addr(const char *addr, struct sockaddr *out, socklen_t *out_len)
{
	struct addrinfo hints, *info;
	bstring str, host, service;
	int i, ret = -1;

	if ((NULL == addr) || (NULL == out) || (NULL == out_len))
		return (-1);

	str = bfromcstr(addr);
	if (NULL == str)
		return (-1);

	i = bstrrchr(str, ':');
	if ((BSTR_ERR == i) || (i <= 0)) {
		bdestroy(str);
		return (-1);
	}
	if (('[' == bchar(str, 0)) && (']' == bchar(str, i - 1)))
		host = bmidstr(str, 1, i - 2);  /* IPv6 */
	else
		host = bmidstr(str, 0, i);      /* IPv4 */
	if (NULL == host) {
		bdestroy(str);
		return (-1);
	}
	service = bmidstr(str, i + 1, blength(str) - i);
	if (NULL == service) {
		bdestroy(str);
		bdestroy(host);
		return (-1);
	}
	if ((0 != blength(host)) && (0 != blength(service))) {
		/* Use getaddrinfo to parse the strings */
		memset(&hints, 0, sizeof(hints));
		hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		if (0 == getaddrinfo(bdata(host), bdata(service), &hints,
			    &info)) {
			if (*out_len >= info->ai_addrlen) {
				memcpy(out, info->ai_addr, info->ai_addrlen);
				*out_len = info->ai_addrlen;
				ret = 0;
			}
			freeaddrinfo(info);
		}
	}
	bdestroy(str);
	bdestroy(host);
	bdestroy(service);

	return (ret);
}
Пример #5
0
SkObject *sk_message_dispatch_simple(SkObject *self) {
    SkObject *result = NULL;
    bstring name = sk_string_get_bstring(sk_message_get_name(self));
    /* is a string */
    if(bchar(name, 0) == '"' && bchar(name, name->slen - 1) == '"') {
        return sk_string_from_bstring(self->vm, bmidstr(name, 1, name->slen - 2));
    } 
    /* is a number */
    else if(is_number(name)) {
        return sk_number_create(self->vm, atoi(bstr2cstr(name, '\0')));
    }
    /* is a command terminator. */
    else if(biseqcstr(name, ";") == 1) {
        return NULL;
    }
    /* a message. */
    else {
        int i;
        SkObjectList *callstack = sk_vm_callstack(SK_VM);
        for(i = kv_size(*callstack) - 1; i >= 0; i--) {
            SkObject *object = kv_A(*callstack, i);
            result = sk_object_dispatch_message(object, self);
            if(result) {
                return result;
            }
        }
        sk_printf("name: %s\n", name->data);
        sk_printf("thread: 0x%x\n", (unsigned int)pthread_self());
        sk_exc_raise(SK_VM, sk_exception_create_lazy(SK_VM, "MessageError",
                    bformat("Nobody is answering to the message '%s'.", name->data)));
        return NULL;
    }
}
Пример #6
0
int screen_move_right(struct te_buffer *buf)
{
	if (buf == NULL)
		return ERR;

	if (move_right(buf) == ERR) /* last char of the document */
		return ERR;

	if (prev_char(buf) == '\n') {
		screen_next_line(buf);
	} else { 
		/* tab is the only character larger than 1 */
			if (prev_char(buf) == '\t') {
				buf->x += TAB_LEN;
			} else {
				buf->x++;
			}

			if(buf->x == COLS - 1) { 
				bstring s = current_line_as_bstring(buf->contents, buf->point);
				int off = screen_numchar_to_offset(s, COLS - 1);
				bstring s2 = bmidstr(s, off, blength(s) - off);
				draw_line(s2, buf->y);
				bdestroy(s);
				bdestroy(s2);
				wmove(buffer_win, buf->y, 0);
				refresh();
			}
	}

	move(buf->y, buf->x);
	return OK;
}
Пример #7
0
void hash_file(hash *hashtable[], char *file, unsigned int tablesize)
{
    FILE *fp;
    bstring buffer;
    bstring value;
    int poseq;

    fp = fopen(file, "r");
    if (fp == NULL)
    {
        fp = fopen(file, "w+"); /* create the file */
        if (fp == NULL)
            fprintf(stderr, "Could not create file (%s)\n", file);
        return;
    }

    while ((buffer = bgets((bNgetc) fgetc, fp, '\n')) != NULL)
    {
        /* seriously, wtf is a \10 doing in my buffer you
           c********r? let's get rid of it: */
        poseq = bstrchrp(buffer, '=', 0);
        value = bmidstr(buffer, poseq+1, blength(buffer) - poseq - 2);
        btrunc(buffer, poseq);
        /*printf("%s=%s\n", bdata(buffer), bdata(value));*/
        hash_add(hashtable, buffer, value, tablesize);
    }
    fclose(fp);
    bdestroy(buffer);
    bdestroy(value);
}
Пример #8
0
static void
nodeMeminfo(int node, uint64_t* totalMemory, uint64_t* freeMemory)
{
    FILE *fp;
    bstring filename;
    bstring totalString = bformat("MemTotal:");
    bstring freeString  = bformat("MemFree:");
    int i;

    filename = bformat("/sys/devices/system/node/node%d/meminfo", node);

    if (NULL != (fp = fopen (bdata(filename), "r"))) 
    {
        bstring src = bread ((bNread) fread, fp);
        struct bstrList* tokens = bsplit(src,(char) '\n');

        for (i=0;i<tokens->qty;i++)
        {
            if (binstr(tokens->entry[i],0,totalString) != BSTR_ERR)
            {
                 bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18 );
                 bltrimws(tmp);
                 struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                 *totalMemory = str2int(bdata(subtokens->entry[0]));
            }
            else if (binstr(tokens->entry[i],0,freeString) != BSTR_ERR)
            {
                 bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18  );
                 bltrimws(tmp);
                 struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                 *freeMemory = str2int(bdata(subtokens->entry[0]));
            }
        }
    }
    else
    {
        ERROR;
    }

    fclose(fp);
}
Пример #9
0
int32_t sky_importer_token_parse_int(bstring source, jsmntok_t *token)
{
    if(token->type == JSMN_PRIMITIVE) {
        int toklen = token->end - token->start;
        bstring str;
        str = bmidstr(source, token->start, toklen);
        int32_t value = (int32_t)atoi(bdata(str));
        bdestroy(str);
        return value;
    }
    
    return 0;
}
Пример #10
0
Файл: Reader.c Проект: denji/mdr
bstring getContentFromLine(bstring line, int formatPaddingLen, int * leadingSpaces)
{
    // Remove padding from front of string.
    bstring content = bmidstr(line, formatPaddingLen, line->slen);
    *leadingSpaces = 0;
    // Remove and count leading whitespace.
    while (content->slen > 0 && content->data[0] == ' ')
    {
        bdelete(content, 0, 1);
        (*leadingSpaces)++;
    }
    return content;
}
Пример #11
0
uint64_t bstr_to_doubleSize(const_bstring str, DataType type)
{
    bstring unit = bmidstr(str, blength(str)-2, 2);
    bstring sizeStr = bmidstr(str, 0, blength(str)-2);
    uint64_t sizeU = str2int(bdata(sizeStr));
    uint64_t junk = 0;
    uint64_t bytesize = 0;

    switch (type)
    {
        case SINGLE:
            bytesize = 4;
            break;

        case DOUBLE:
            bytesize = 8;
            break;
    }

    if ((biseqcstr(unit, "kB"))||(biseqcstr(unit, "KB")))
    {
        junk = (sizeU *1000)/bytesize;
    }
    else if (biseqcstr(unit, "MB"))
    {
        junk = (sizeU *1000000)/bytesize;
    }
    else if (biseqcstr(unit, "GB"))
    {
        junk = (sizeU *1000000000)/bytesize;
    }
    else if (biseqcstr(unit, "B"))
    {
        junk = (sizeU)/bytesize;
    }

    return junk;
}
Пример #12
0
bool do_uninstall_all(CURL* curl)
{
    // define used variables
    DIR* dir;
    bool something_was_removed;
    struct dirent* entry;
    bstring fname, sstr;
    bstring ext = bfromcstr(".lua");
    bstring modpath = osutil_getmodulepath();

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }
    bdestroy(modpath);

    // iterate through the installed modules
    something_was_removed = false;
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        do_uninstall(curl, bfromcstr(sstr->data));
        something_was_removed = true;
        bdestroy(sstr);
        bdestroy(fname);
    }
    if (!something_was_removed)
        printd(LEVEL_DEFAULT, "No changes were made.\n");

    return 0;
}
Пример #13
0
Node *FrameSource_recv(FrameSource frame, bstring *hbuf, Node **header)
{
  Node *msg = NULL;
  unsigned short length = 0;
  int rc = 0;
  size_t from = 0;
  bstring data = NULL;

  assert_not(header, NULL);

  *hbuf = NULL; *header = NULL;

  rc = io_ensure_sbuf(frame.in, frame.fd, sizeof(uint16_t));
  if(!rc) return NULL;  // got closed, nothing to do

  rc = sbuf_get_ntohs(frame.in, &length);
  check(rc, "length read failure");
  check(length > 0, "zero length message");

  rc = io_ensure_sbuf(frame.in, frame.fd, length);
  check(rc, "io read failure");

  data = sbuf_read_bstr(frame.in, length);
  check(data, "failed to read a single bstr");
  check(blength(data) == length, "didn't get what we asked for from the sbuf");

  *header = Node_parse_seq(data, &from);
  check(*header, "failed to parse a header");
  // carve out the hbuf bstring for comparison
  *hbuf = bmidstr(data, 0, from);

  if(from < length) {
    // more to read
    msg = Node_parse_seq(data, &from);
    check(msg, "failed to read body");
  }
  check(from == length, "trailing data violates");

  ensure(bdestroy(data); return msg);
}
Пример #14
0
void rparse_dol(char* yytext, int* out_line)
{
    bstring str = bfromcstr(yytext);
    bstring space = bfromcstr(" ");

    // Determine the space positions.
    int firstSpace = binstr(str, 0, space);

    // Create substrings.
    bstring bline = bmidstr(str, firstSpace + 1, blength(str));

    // Convert the line number and trim file name.
    int line = strtoul((const char*)bline->data, NULL, 10);

    // Set variables.
    *out_line = line;

    // Free resources.
    bdestroy(bline);
    bdestroy(space);
    bdestroy(str);
}
Пример #15
0
const char* glswGetShader(const char* pEffectKey, const char* pContentsFromMemory)
{
    glswContext* gc = __glsw__Context;
    bstring effectKey;
    glswList* closestMatch = 0;
    struct bstrList* tokens;
    bstring effectName;
    glswList* pLoadedEffect;
    glswList* pShaderEntry;
    bstring shaderKey = 0;

    if (!gc)
    {
        return 0;
    }

    // Extract the effect name from the effect key
    effectKey = bfromcstr(pEffectKey);
    tokens = bsplit(effectKey, '.');
    if (!tokens || !tokens->qty)
    {
        bdestroy(gc->ErrorMessage);
        gc->ErrorMessage = bformat("Malformed effect key key '%s'.", pEffectKey);
        bstrListDestroy(tokens);
        bdestroy(effectKey);
        return 0;
    }
    effectName = tokens->entry[0];

    // Check if we already loaded this effect file
    pLoadedEffect = gc->LoadedEffects;
    while (pLoadedEffect)
    {
        if (1 == biseq(pLoadedEffect->Key, effectName))
        {
            break;
        }
        pLoadedEffect = pLoadedEffect->Next;
    }

    // If we haven't loaded this file yet, load it in
    if (!pLoadedEffect)
    {
        bstring effectContents;
        struct bstrList* lines;
        int lineNo;

        if (!pContentsFromMemory) {
            FILE* fp;
            bstring effectFile;

            // Decorate the effect name to form the fullpath
            effectFile = bstrcpy(effectName);
            binsert(effectFile, 0, gc->PathPrefix, '?');
            bconcat(effectFile, gc->PathSuffix);

            // Attempt to open the file
            fp = fopen((const char*) effectFile->data, "rb");
            if (!fp)
            {
                bdestroy(gc->ErrorMessage);
                gc->ErrorMessage = bformat("Unable to open effect file '%s'.", effectFile->data);
                bdestroy(effectFile);
                bdestroy(effectKey);
                bstrListDestroy(tokens);
                return 0;
            }

            // Add a new entry to the front of gc->LoadedEffects
            {
                glswList* temp = gc->LoadedEffects;
                gc->LoadedEffects = (glswList*) calloc(sizeof(glswList), 1);
                gc->LoadedEffects->Key = bstrcpy(effectName);
                gc->LoadedEffects->Next = temp;
            }

            // Read in the effect file
            effectContents = bread((bNread) fread, fp);
            fclose(fp);
            bdestroy(effectFile);
        } else {
            effectContents = bfromcstr(pContentsFromMemory);
        }

        lines = bsplit(effectContents, '\n');
        bdestroy(effectContents);
        effectContents = 0;

        for (lineNo = 0; lineNo < lines->qty; lineNo++)
        {
            bstring line = lines->entry[lineNo];

            // If the line starts with "--", then it marks a new section
            if (blength(line) >= 2 && line->data[0] == '-' && line->data[1] == '-')
            {
                // Find the first character in [A-Za-z0-9_].
                int colNo;
                for (colNo = 2; colNo < blength(line); colNo++)
                {
                    char c = line->data[colNo];
                    if (__glsw__Alphanumeric(c))
                    {
                        break;
                    }
                }

                // If there's no alphanumeric character,
                // then this marks the start of a new comment block.
                if (colNo >= blength(line))
                {
                    bdestroy(shaderKey);
                    shaderKey = 0;
                }
                else
                {
                    // Keep reading until a non-alphanumeric character is found.
                    int endCol;
                    for (endCol = colNo; endCol < blength(line); endCol++)
                    {
                        char c = line->data[endCol];
                        if (!__glsw__Alphanumeric(c))
                        {
                            break;
                        }
                    }

                    bdestroy(shaderKey);
                    shaderKey = bmidstr(line, colNo, endCol - colNo);

                    // Add a new entry to the shader map.
                    {
                        glswList* temp = gc->ShaderMap;
                        gc->ShaderMap = (glswList*) calloc(sizeof(glswList), 1);
                        gc->ShaderMap->Key = bstrcpy(shaderKey);
                        gc->ShaderMap->Next = temp;
                        gc->ShaderMap->Value = bformat("#line %d\n", lineNo);

                        binsertch(gc->ShaderMap->Key, 0, 1, '.');
                        binsert(gc->ShaderMap->Key, 0, effectName, '?');
                    }

                    // Check for a version mapping.
                    if (gc->TokenMap)
                    {
                        struct bstrList* tokens = bsplit(shaderKey, '.');
                        glswList* pTokenMapping = gc->TokenMap;

                        while (pTokenMapping)
                        {
                            bstring directive = 0;
                            int tokenIndex;

                            // An empty key in the token mapping means "always prepend this directive".
                            // The effect name itself is also checked against the token mapping.
                            if (0 == blength(pTokenMapping->Key) ||
                                1 == biseq(pTokenMapping->Key, effectName))
                            {
                                directive = pTokenMapping->Value;
                                binsert(gc->ShaderMap->Value, 0, directive, '?');
                            }

                            // Check all tokens in the current section divider for a mapped token.
                            for (tokenIndex = 0; tokenIndex < tokens->qty && !directive; tokenIndex++)
                            {
                                bstring token = tokens->entry[tokenIndex];
                                if (1 == biseq(pTokenMapping->Key, token))
                                {
                                    directive = pTokenMapping->Value;
                                    binsert(gc->ShaderMap->Value, 0, directive, '?');
                                }
                            }

                            pTokenMapping = pTokenMapping->Next;
                        }

                        bstrListDestroy(tokens);
                    }
                }

                continue;
            }
            if (shaderKey)
            {
                bconcat(gc->ShaderMap->Value, line);
                bconchar(gc->ShaderMap->Value, '\n');
            }
        }

        // Cleanup
        bstrListDestroy(lines);
        bdestroy(shaderKey);
    }

    // Find the longest matching shader key
    pShaderEntry = gc->ShaderMap;

    while (pShaderEntry)
    {
        if (binstr(effectKey, 0, pShaderEntry->Key) == 0 &&
            (!closestMatch || blength(pShaderEntry->Key) > blength(closestMatch->Key)))
        {
            closestMatch = pShaderEntry;
        }

        pShaderEntry = pShaderEntry->Next;
    }

    bstrListDestroy(tokens);
    bdestroy(effectKey);

    if (!closestMatch)
    {
        bdestroy(gc->ErrorMessage);
        gc->ErrorMessage = bformat("Could not find shader with key '%s'.", pEffectKey);
        return 0;
    }

    return (const char*) closestMatch->Value->data;
}
Пример #16
0
bool do_search(CURL* curl, bstring name, bool all)
{
    DIR* dir;
    bool printed;
    CURLcode res;
    FILE* fp;
    list_t installed;
    struct bStream* stream;
    long httpcode = 0;
    bstring buffer, fname, sstr;
    bstring ext = bfromcstr(".lua");
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/search?q=");
    bstring modpath = osutil_getmodulepath();
    struct dirent* entry;
    list_init(&installed);
    list_attributes_copy(&installed, list_meter_string, 1);
    list_attributes_comparator(&installed, list_comparator_string);

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }

    // Append the temporary search file name.
    bcatcstr(modpath, "/.search");
    bconcat(url, name);

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "querying module repository...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 || httpcode != 200)
    {
        bdestroy(url);
        bdestroy(name);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);

    // Print the local results.
    if (all)
        printd(LEVEL_DEFAULT, "all modules:\n");
    else
        printd(LEVEL_DEFAULT, "search results for %s:\n", name->data);
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (binstr(fname, 0, name) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        printd(LEVEL_DEFAULT, "   %s (installed)\n", sstr->data);
        list_append(&installed, sstr->data);
        bdestroy(sstr);
        bdestroy(fname);
    }

    // Print the online results.
    fp = fopen(modpath->data, "r");
    stream = bsopen(&read_data, fp);
    buffer = bfromcstr("");
    printed = false;
    while (bsreadln(buffer, stream, '\n') != BSTR_ERR)
    {
        btrimws(buffer);
        sstr = bmidstr(buffer, 0, blength(buffer) - 4);
        if (!list_contains(&installed, sstr->data))
            printd(LEVEL_DEFAULT, "  %s\n", sstr->data);
        printed = true;
        bdestroy(sstr);
    }
    if (!printed)
        printd(LEVEL_DEFAULT, "   <no online results>\n");
    bsclose(stream);
    fclose(fp);

    // Clean up.
    curl_easy_cleanup(curl);
    return 0;
}
Пример #17
0
bool do_install_all(CURL* curl)
{
    // define used variables
    DIR* dir;
    FILE* fp;
    CURLcode res;
    bool printed;
    bool install_status;
    bool something_errored;
    bool if_something_was_installed;
    list_t installed;
    long httpcode = 0;
    struct dirent* entry;
    struct bStream* stream;
    bstring buffer, fname, sstr;
    bstring modpath = osutil_getmodulepath();
    bstring ext = bfromcstr(".lua");
    bstring url = bfromcstr("http://dms.dcputoolcha.in/modules/list");
    list_init(&installed);
    list_attributes_copy(&installed, list_meter_string, 1);
    list_attributes_comparator(&installed, list_comparator_string);

    // Attempt to open the modules directory.
    dir = opendir(modpath->data);
    if (dir == NULL)
    {
        printd(LEVEL_ERROR, "unable to query local repository.\n");
        return 1;
    }

    // add the filename we wish to query to the modules folder path
    bcatcstr(modpath, "/.all_avail");

    // Open the file and do the cURL transfer.
    printd(LEVEL_DEFAULT, "loading a list of all the modules...\n");
    fp = fopen(modpath->data, "wb");
    curl_easy_setopt(curl, CURLOPT_URL, url->data);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
    res = curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &httpcode);
    if (res != 0 || httpcode != 200)
    {
        bdestroy(url);
        bdestroy(modpath);
        printd(LEVEL_ERROR, "curl failed with error code %i, HTTP error code %i.\n", res, httpcode);
        return 1;
    }
    fclose(fp);


    // create a list of already installed modules
    while ((entry = readdir(dir)) != NULL)
    {
        fname = bfromcstr(&entry->d_name[0]);
        if (binstr(fname, blength(fname) - 4, ext) == BSTR_ERR)
        {
            bdestroy(fname);
            continue;
        }
        if (entry->d_type != DT_REG)
        {
            bdestroy(fname);
            continue;
        }
        sstr = bmidstr(fname, 0, blength(fname) - 4);
        list_append(&installed, sstr->data);
        bdestroy(sstr);
        bdestroy(fname);
    }

    printd(LEVEL_DEFAULT, "\n");

    // Print the names of the modules, and install them through the do_install function
    fp = fopen(modpath->data, "r");
    stream = bsopen(&read_data, fp);
    buffer = bfromcstr("");
    printed = false;
    if_something_was_installed = false;
    something_errored = false;
    while (bsreadln(buffer, stream, '\n') != BSTR_ERR)
    {
        btrimws(buffer);
        sstr = bmidstr(buffer, 0, blength(buffer) - 4);

        // if the module is not already installed
        if (!list_contains(&installed, sstr->data))
        {
            install_status = do_install(curl, bfromcstr(sstr->data));
            if_something_was_installed = true;
            // check whether the installation was successful
            if (install_status != 0)
            {
                printd(LEVEL_DEFAULT, "  %s failed to install.\n", sstr->data);
                something_errored = true;
            }
            printd(LEVEL_DEFAULT, "\n");
        }

        printed = true;
        bdestroy(sstr);
    }
    if (!printed)
        printd(LEVEL_DEFAULT, "  <no modules available>\n");
    if (something_errored)
        printd(LEVEL_DEFAULT, "errors occured\n");
    if (!if_something_was_installed)
        printd(LEVEL_DEFAULT, "no changes were made\n");
    bsclose(stream);
    fclose(fp);

    // Clean up.
    curl_easy_cleanup(curl);

    return 0;
}
Пример #18
0
/* String:strmid(String:Source, start = 0, length = cellmax) */
static cell AMX_NATIVE_CALL n_bstrmid(AMX *amx,cell *params)
{
  cell hstr = bmidstr((const bstring)params[1], (int)params[2], (int)params[3]);
  VERIFY( gc_mark(hstr) );
  return hstr;
}
Пример #19
0
static int
ssh_parse_args(obfsproxyssh_client_session_t *session, const char * args)
{
	obfsproxyssh_t *state = session->client->state;
	struct tagbstring hkey_rsa_prefix = bsStatic("hostkey-rsa=");
	struct tagbstring hkey_dss_prefix = bsStatic("hostkey-dsa=");
	struct tagbstring user_prefix = bsStatic("user="******"privkey=");
	struct tagbstring orport_prefix = bsStatic("orport=");
	struct tagbstring arg_str;
	struct bstrList *arg_list;
	bstring tmp;
	int i;

	/*
	 * Arguments are passed in as a single NULL terminated string,
	 * separated by ";" (Eg: "rocks=20;height=5.6m").
	 *
	 * Supported args:
	 *  * "hostkey-rsa=XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX"
	 *  * "hostkey-dsa=YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY:YY"
	 *  * "user=USERNAME"
	 *  * "privkey=PRIVATEKEY" "PEM" format RSA key, with the header/footer/
	 *  *                      newlines stripped.
	 *  * "orport=XXXXX" Port on the remote peer's loopback interface that
	 *                   Tor is listening on (Temporary argument since once
	 *                   there's an actual server implementation it should
	 *                   handle that automatically).
	 */

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Waddress"
	btfromcstr(arg_str, args);
	arg_list = bsplit(&arg_str, ';');
	for (i = 0; i < arg_list->qty; i++) {
		if (0 == bstrncmp(&hkey_rsa_prefix, arg_list->entry[i],
					blength(&hkey_rsa_prefix))) {
			session->hostkey_rsa = bmidstr(arg_list->entry[i],
					blength(&hkey_rsa_prefix),
					blength(arg_list->entry[i]) -
					blength(&hkey_rsa_prefix));
		} else if (0 == bstrncmp(&hkey_dss_prefix, arg_list->entry[i],
					blength(&hkey_dss_prefix))) {
			session->hostkey_dss = bmidstr(arg_list->entry[i],
					blength(&hkey_dss_prefix),
					blength(arg_list->entry[i]) -
					blength(&hkey_dss_prefix));
		} else if (0 == bstrncmp(&user_prefix, arg_list->entry[i],
					blength(&user_prefix))) {
			session->user = bmidstr(arg_list->entry[i],
					blength(&user_prefix),
					blength(arg_list->entry[i]) -
					blength(&user_prefix));
		} else if (0 == bstrncmp(&privkey_prefix, arg_list->entry[i],
					blength(&privkey_prefix))) {
			tmp = bmidstr(arg_list->entry[i],
					blength(&privkey_prefix),
					blength(arg_list->entry[i]) -
					blength(&user_prefix));
			session->privkey_pem = ssh_arg_to_privkey(tmp);
			bdestroy(tmp);
		} else if (0 == bstrncmp(&orport_prefix, arg_list->entry[i],
					blength(&orport_prefix))) {
			tmp = bmidstr(arg_list->entry[i],
					blength(&orport_prefix),
					blength(arg_list->entry[i]) -
					blength(&orport_prefix));
#pragma GCC diagnostic ignored "-Wnonnull"
			session->orport = atoi(bdata(tmp));
			bdestroy(tmp);
		}
	}
#pragma GCC diagnostic pop

	bstrListDestroy(arg_list);

	if (NULL == session->hostkey_rsa && NULL == session->hostkey_dss)
		return -1;

	if (NULL == session->user || NULL == session->privkey_pem ||
			0 == session->orport)
		return -1;

	/* Generate libssh compatible keys from the PEM */
	session->privkey = read_rsa_private_key_from_memory(
			bdata(session->privkey_pem),
			blength(session->privkey_pem));
	if (NULL == session->privkey) {
		log_f(state, "SOCKS: Error: %s Unable to decode private key",
					bdata(session->socks_addr));
		return -1;
	}

	return 0;
}
Пример #20
0
bstring sky_importer_token_parse_bstring(bstring source, jsmntok_t *token)
{
    int toklen = token->end - token->start;
    return bmidstr(source, token->start, toklen);
}
Пример #21
0
// Generates the LuaJIT header given a Lua script and a property file. The
// header file is generated based on the property usage of the 'event'
// variable in the script.
//
// source          - The source code of the Lua script.
// property_file   - The property file used to lookup properties.
// event_decl      - A pointer to where the struct def should be returned.
// init_descriptor_func - A pointer to where the descriptor init function should be returned.
//
// Returns 0 if successful, otherwise returns -1.
int sky_lua_generate_event_info(bstring source,
                                sky_property_file *property_file,
                                bstring *event_decl,
                                bstring *init_descriptor_func)
{
    int rc;
    bstring identifier = NULL;
    assert(source != NULL);
    assert(property_file != NULL);
    assert(event_decl != NULL);
    assert(init_descriptor_func != NULL);

    // Initialize returned value.
    *event_decl = bfromcstr(
        "  int64_t timestamp;\n"
        "  uint16_t action_id;\n"
    );
    check_mem(*event_decl);
    *init_descriptor_func = bfromcstr(
        "  ffi.C.sky_data_descriptor_set_timestamp_offset(descriptor, ffi.offsetof(\"sky_lua_event_t\", \"timestamp\"));\n"
        "  ffi.C.sky_data_descriptor_set_action_id_offset(descriptor, ffi.offsetof(\"sky_lua_event_t\", \"action_id\"));\n"
    );
    check_mem(*init_descriptor_func);

    // Setup a lookup of properties.
    bool lookup[SKY_PROPERTY_ID_COUNT+1];
    memset(lookup, 0, sizeof(lookup));

    // Loop over every mention of an "event." property.
    int pos = 0;
    struct tagbstring EVENT_DOT_STR = bsStatic("event.");
    while((pos = binstr(source, pos, &EVENT_DOT_STR)) != BSTR_ERR) {
        // Make sure that this is not part of another identifier.
        bool skip = false;
        if(pos > 0 && (isalnum(bchar(source, pos-1)) || bchar(source, pos-1) == '_')) {
            skip = true;
        }
        
        // Move past the "event." string.
        pos += blength(&EVENT_DOT_STR);

        if(!skip) {
            // Read in identifier.
            int i;
            for(i=pos+1; i<blength(source); i++) {
                char ch = bchar(source, i);
                if(!(isalnum(ch) || ch == '_')) {
                    break;
                }
            }
            identifier = bmidstr(source, pos, i-pos); check_mem(identifier);
            if(blength(identifier)) {
                sky_property *property = NULL;
                rc = sky_property_file_find_by_name(property_file, identifier, &property);
                check(rc == 0, "Unable to find property by name: %s", bdata(identifier));
                check(property != NULL, "Property not found: %s", bdata(identifier));
            
                if(!lookup[property->id-SKY_PROPERTY_ID_MIN]) {
                    // Append property definition to event decl and function.
                    switch(property->data_type) {
                        case SKY_DATA_TYPE_STRING: {
                            bformata(*event_decl, "  char %s[];\n", bdata(property->name));
                            break;
                        }
                        case SKY_DATA_TYPE_INT: {
                            bformata(*event_decl, "  int64_t %s;\n", bdata(property->name));
                            break;
                        }
                        case SKY_DATA_TYPE_DOUBLE: {
                            bformata(*event_decl, "  double %s;\n", bdata(property->name));
                            break;
                        }
                        case SKY_DATA_TYPE_BOOLEAN: {
                            bformata(*event_decl, "  bool %s;\n", bdata(property->name));
                            break;
                        }
                        default:{
                            sentinel("Invalid sky lua type: %d", property->data_type);
                        }
                    }
                    check_mem(*event_decl);

                    bformata(*init_descriptor_func, "  ffi.C.sky_data_descriptor_set_property(descriptor, %d, ffi.offsetof(\"sky_lua_event_t\", \"%s\"), %d);\n", property->id, bdata(property->name), property->data_type);
                    check_mem(*init_descriptor_func);

                    // Flag the property as already processed.
                    lookup[property->id - SKY_PROPERTY_ID_MIN] = true;
                }
            }

            bdestroy(identifier);
            identifier = NULL;
        }
    }

    // Wrap properties in a struct.
    bassignformat(*event_decl, "typedef struct {\n%s} sky_lua_event_t;", bdata(*event_decl));
    check_mem(*event_decl);

    // Wrap info function.
    bassignformat(*init_descriptor_func,
        "function sky_init_descriptor(_descriptor)\n"
        "  descriptor = ffi.cast(\"sky_data_descriptor_t*\", _descriptor)\n"
        "%s"
        "end\n",
        bdata(*init_descriptor_func)
    );
    check_mem(*init_descriptor_func);

    return 0;

error:
    bdestroy(identifier);
    bdestroy(*event_decl);
    *event_decl = NULL;
    bdestroy(*init_descriptor_func);
    *init_descriptor_func = NULL;
    return -1;
}
Пример #22
0
static int
parse_server_xport_option(allium_ptcfg *cfg, const bstring arg_str)
{
	struct allium_ptcfg_method_s *m;
	struct allium_ptcfg_xport_opt_s *opt;
	bstring transport;
	bstring key;
	bstring value;
	int i, j;

	assert(cfg);
	assert(arg_str);

	if (0 == blength(arg_str))
		return (-1);

	/*
	 * Figure out what transport this argument is for.  We don't need to
	 * unescape method names as they conform to "[a-zA-Z_][a-zA-Z0-9_]*"
	 */
	i = bstrchr(arg_str, ':');
	if (BSTR_ERR == i)
		return (-1);

	transport = bmidstr(arg_str, 0, i);
	if (NULL == transport)
		return (-1);

	m = get_method(cfg, bdata(transport));
	bdestroy(transport);    /* Done with the transport at this point */
	if (NULL == m)
		return (-1);

	/*
	 * Figure out what key the transport is expecting the value for.
	 *
	 * XXX: If people want to use the escaped characters in their keys they
	 * get what they deserve (Note this as a gotcha and fix it when people
	 * cry about it).
	 */
	j = bstrchrp(arg_str, '=', i);
	if (BSTR_ERR == j)
		return (-1);

	key = bmidstr(arg_str, i + 1, j - i - 1);
	if (NULL == key)
		return (-1);

	opt = get_xport_opt(m, key);
	if ((NULL != opt) || (0 == blength(key))) {
		/* We don't support redefining existing key/value pairs */
		bdestroy(key);
		return (-1);
	}

	/* Parse the value, unescaping as needed */
	value = bmidstr(arg_str, j + 1, blength(arg_str) - j - 1);
	if (NULL == value) {
		bdestroy(key);
		return (-1);
	}
	unescape_opt_value(value);

	/* Stash it away so people can get to it */
	opt = calloc(1, sizeof(*opt));
	if (NULL == opt) {
		bdestroy(key);
		bdestroy_safe(value);
		return (-1);
	}
	opt->key = key;
	opt->value = value;
	opt->next = m->xport_opts;
	m->xport_opts = opt;

	return (0);
}
Пример #23
0
uint64_t
getTotalNodeMem(int nodeId)
{
    int i;
    FILE *fp;
    uint64_t total = 0;
    bstring totalString  = bformat("MemTotal:");
    bstring sysfilename = bformat("/sys/devices/system/node/node%d/meminfo", nodeId);
    bstring procfilename = bformat("/proc/meminfo");
    char *sptr = bdata(procfilename);

    if (NULL != (fp = fopen (bdata(sysfilename), "r")))
    {
        bstring src = bread ((bNread) fread, fp);
        struct bstrList* tokens = bsplit(src,(char) '\n');

        for (i=0;i<tokens->qty;i++)
        {
            if (binstr(tokens->entry[i],0,totalString) != BSTR_ERR)
            {
                 bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18  );
                 bltrimws(tmp);
                 struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                 total = str2int(bdata(subtokens->entry[0]));
                 bdestroy(tmp);
                 bstrListDestroy(subtokens);
            }
        }
        bstrListDestroy(tokens);
        bdestroy(src);
        fclose(fp);
    }
    else if (!access(sptr, R_OK))
    {
        if (NULL != (fp = fopen (bdata(procfilename), "r")))
        {
            bstring src = bread ((bNread) fread, fp);
            struct bstrList* tokens = bsplit(src,(char) '\n');
            for (i=0;i<tokens->qty;i++)
            {
                if (binstr(tokens->entry[i],0,totalString) != BSTR_ERR)
                {
                     bstring tmp = bmidstr (tokens->entry[i], 10, blength(tokens->entry[i])-10  );
                     bltrimws(tmp);
                     struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                     total = str2int(bdata(subtokens->entry[0]));
                     bdestroy(tmp);
                     bstrListDestroy(subtokens);
                }
            }
            bstrListDestroy(tokens);
            bdestroy(src);
            fclose(fp);
        }
    }
    else
    {
        bdestroy(totalString);
        bdestroy(sysfilename);
        bdestroy(procfilename);
        ERROR;
    }

    bdestroy(totalString);
    bdestroy(sysfilename);
    bdestroy(procfilename);
    return total;
}
Пример #24
0
Файл: bstraux.c Проект: adsr/a
/*  bstring bHead (bstring b, int n)
 *
 *  Return with a string of the first n characters of b.
 */
bstring bHead (bstring b, int n) {
	if (b == NULL || n < 0 || (b->mlen < b->slen && b->mlen > 0)) return NULL;
	if (n >= b->slen) return bstrcpy (b);
	return bmidstr (b, 0, n);
}
Пример #25
0
/* ----------------------------------------------------------
 * FUNCTION     : parse_line
 * DESCRIPTION  : This function will process a line of data
 *              : from a configuration file.
 * INPUT        : 0 - Line (bstring)
 * ---------------------------------------------------------- */
void parse_line (bstring line)
{
    bstring param, value;
    struct bstrList *list;
    int i;

    /* Check to see if this line has something to read. */
    if (line->data[0] == '\0' || line->data[0] == '#')
       return;

    /* Check to see if this line has a comment in it. */
    if ((list = bsplit(line, '#')) != NULL) {
        if ((bassign(line, list->entry[0])) == -1) {
            log_message("warning:  'bassign' in function 'parse_line' failed.");
        }
        if (list != NULL)
            bstrListDestroy(list);
    }

    /* Seperate line into a parameter and a value. */
    if ((i = bstrchr(line, ' ')) == BSTR_ERR)
        return;
    if ((param = bmidstr(line, 0, i)) == NULL)
        return;
    if ((value = bmidstr(line, i + 1, line->slen - i)) == NULL)
        return;

    /* Normalize Strings */
    if ((btolower(param)) != 0)
        log_message("warning:  'btolower' in function 'parse_line' failed.");
    if ((bltrim(value)) != 0)
        log_message("warning:  'bltrim' in function 'parse_line' failed.");
    if ((brtrim(value)) != 0)
        log_message("warning:  'brtrim' in function 'parse_line' failed.");

    /* Do something based upon value. */
    if ((biseqcstr(param, "daemon")) == 1) {
        /* DAEMON */
        if (!gc.daemon_mode) {
            if (value->data[0] == '1')
                gc.daemon_mode = 1;
            else
                gc.daemon_mode = 0;
        }

    } else if ((biseqcstr(param, "pid_file")) == 1) {
            /* PID FILE */
        gc.pid_file = bstrcpy(value);

    } else if ((biseqcstr(param, "sig_file")) == 1) {
        /* SIGNATURE FILE */
        gc.sig_file = bstrcpy(value);
   
    } else if ((biseqcstr(param, "mac_file")) == 1) {
        /* MAC / VENDOR RESOLUTION FILE */
        gc.mac_file = bstrcpy(value);

    } else if ((biseqcstr(param, "output")) == 1) {
        /* OUTPUT */
        conf_module_plugin(value, &activate_output_plugin);

    } else if ((biseqcstr(param, "user")) == 1) {
        /* USER */
        gc.priv_user = bstrcpy(value);

    } else if ((biseqcstr(param, "group")) == 1) {
        /* GROUP */
        gc.priv_group = bstrcpy(value);

    } else if ((biseqcstr(param, "interface")) == 1) {
        /* INTERFACE */
        gc.dev = bstr2cstr(value, '-');

    } else if ((biseqcstr(param, "filter")) == 1) {
        /* FILTER */
        gc.pcap_filter = bstr2cstr(value, '-');

    } else if ((biseqcstr(param, "network")) == 1) {
        /* NETWORK */
        parse_networks(bdata(value));

    }

    verbose_message("config - PARAM:  |%s| / VALUE:  |%s|", bdata(param), bdata(value));

    /* Clean Up */
    if (param != NULL)
        bdestroy(param);
    if (value != NULL)
        bdestroy(value);
}
Пример #26
0
int main(int argc, char** argv)
{
    int attrib[] = {
        GLX_RENDER_TYPE, GLX_RGBA_BIT,
        GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
        GLX_DOUBLEBUFFER, True,
        GLX_RED_SIZE, 8,
        GLX_GREEN_SIZE, 8,
        GLX_BLUE_SIZE, 8,
        GLX_ALPHA_SIZE, 8,
        GLX_DEPTH_SIZE, 24,
        None
    };
    
    PlatformContext context;

    context.MainDisplay = XOpenDisplay(NULL);
    int screenIndex = DefaultScreen(context.MainDisplay);
    Window root = RootWindow(context.MainDisplay, screenIndex);

    int fbcount;
    PFNGLXCHOOSEFBCONFIGPROC glXChooseFBConfig = (PFNGLXCHOOSEFBCONFIGPROC)glXGetProcAddress((GLubyte*)"glXChooseFBConfig");
    GLXFBConfig *fbc = glXChooseFBConfig(context.MainDisplay, screenIndex, attrib, &fbcount);
    if (!fbc)
        pezFatal("Failed to retrieve a framebuffer config\n");

    PFNGLXGETVISUALFROMFBCONFIGPROC glXGetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) glXGetProcAddress((GLubyte*)"glXGetVisualFromFBConfig");
    if (!glXGetVisualFromFBConfig)
        pezFatal("Failed to get a GLX function pointer\n");

    PFNGLXGETFBCONFIGATTRIBPROC glXGetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) glXGetProcAddress((GLubyte*)"glXGetFBConfigAttrib");
    if (!glXGetFBConfigAttrib)
        pezFatal("Failed to get a GLX function pointer\n");

    if (PezGetConfig().Multisampling) {
        int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
        for ( int i = 0; i < fbcount; i++ ) {
            XVisualInfo *vi = glXGetVisualFromFBConfig( context.MainDisplay, fbc[i] );
            if (!vi) {
                continue;
            }
            int samp_buf, samples;
            glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf );
            glXGetFBConfigAttrib( context.MainDisplay, fbc[i], GLX_SAMPLES       , &samples  );
            //printf( "  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
            //        " SAMPLES = %d\n", 
            //        i, (unsigned int) vi->visualid, samp_buf, samples );
            if ( best_fbc < 0 || (samp_buf && samples > best_num_samp) )
                best_fbc = i, best_num_samp = samples;
            if ( worst_fbc < 0 || !samp_buf || samples < worst_num_samp )
                worst_fbc = i, worst_num_samp = samples;
            XFree( vi );
        }
        fbc[0] = fbc[ best_fbc ];
    }

    XVisualInfo *visinfo = glXGetVisualFromFBConfig(context.MainDisplay, fbc[0]);
    if (!visinfo)
        pezFatal("Error: couldn't create OpenGL window with this pixel format.\n");

    XSetWindowAttributes attr;
    attr.background_pixel = 0;
    attr.border_pixel = 0;
    attr.colormap = XCreateColormap(context.MainDisplay, root, visinfo->visual, AllocNone);
    attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask |
                      PointerMotionMask | ButtonPressMask | ButtonReleaseMask;

    context.MainWindow = XCreateWindow(
        context.MainDisplay,
        root,
        0, 0,
        PezGetConfig().Width, PezGetConfig().Height, 0,
        visinfo->depth,
        InputOutput,
        visinfo->visual,
        CWBackPixel | /*CWBorderPixel |*/ CWColormap | CWEventMask,
        &attr
    );

    int borderless = 1;
    if (borderless) {
        Atom mwmHintsProperty = XInternAtom(context.MainDisplay, "_MOTIF_WM_HINTS", 0);
        MwmHints hints = {0};
        hints.flags = MWM_HINTS_DECORATIONS;
        hints.decorations = 0;
        XChangeProperty(context.MainDisplay, context.MainWindow, mwmHintsProperty, mwmHintsProperty, 32,
                        PropModeReplace, (unsigned char *)&hints, PROP_MWM_HINTS_ELEMENTS);
    }

    XMapWindow(context.MainDisplay, context.MainWindow);

    int centerWindow = 1;
    if (centerWindow) {
        Screen* pScreen = XScreenOfDisplay(context.MainDisplay, screenIndex);
        int left = XWidthOfScreen(pScreen)/2 - PezGetConfig().Width/2;
        int top = XHeightOfScreen(pScreen)/2 - PezGetConfig().Height/2;
        XMoveWindow(context.MainDisplay, context.MainWindow, left, top);
    }

    GLXContext glcontext = 0;
    if (PEZ_FORWARD_COMPATIBLE_GL) {
        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribs = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((GLubyte*)"glXCreateContextAttribsARB");
        if (!glXCreateContextAttribs) {
            pezFatal("Your platform does not support OpenGL 4.0.\n"
                     "Try changing PEZ_FORWARD_COMPATIBLE_GL to 0.\n");
        }
        int attribs[] = {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 4,
            GLX_CONTEXT_MINOR_VERSION_ARB, 0,
            GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
            0
        };
        glcontext = glXCreateContextAttribs(context.MainDisplay, fbc[0], NULL, True, attribs);
    } else {
        glcontext = glXCreateContext(context.MainDisplay, visinfo, NULL, True);
    }

    glXMakeCurrent(context.MainDisplay, context.MainWindow, glcontext);
    PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress((GLubyte*)"glXSwapIntervalSGI");
    if (glXSwapIntervalSGI) {
        glXSwapIntervalSGI(PezGetConfig().VerticalSync ? 1 : 0);
    }
/*
    GLenum err = glewInit();
    if (GLEW_OK != err)
        pezFatal("GLEW Error: %s\n", glewGetErrorString(err));

    // Work around some GLEW issues:    
    #define glewGetProcAddress(name) (*glXGetProcAddressARB)(name)
    glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)glewGetProcAddress((const GLubyte*)"glPatchParameteri");
    glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glBindVertexArray");
    glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glDeleteVertexArrays");
    glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)glewGetProcAddress((const GLubyte*)"glGenVertexArrays");
    glIsVertexArray = (PFNGLISVERTEXARRAYPROC)glewGetProcAddress((const GLubyte*)"glIsVertexArray");
*/
    // Reset OpenGL error state:
    glGetError();

    // Lop off the trailing .c
    bstring name = bfromcstr(PezGetConfig().Title);
    bstring shaderPrefix = bmidstr(name, 0, blength(name) - 1);
    pezSwInit(bdata(shaderPrefix));
    bdestroy(shaderPrefix);

    // Set up the Shader Wrangler
    pezSwAddPath("./", ".glsl");
    pezSwAddPath("../", ".glsl");
    char qualifiedPath[128];
    strcpy(qualifiedPath, pezResourcePath());
    strcat(qualifiedPath, "/");
    pezSwAddPath(qualifiedPath, ".glsl");
    pezSwAddDirective("*", "#version 420");

    // Perform user-specified intialization
    pezPrintString("OpenGL Version: %s\n", glGetString(GL_VERSION));
    PezInitialize();
    bstring windowTitle = bmidstr(name, 5, blength(name) - 7);
    XStoreName(context.MainDisplay, context.MainWindow, bdata(windowTitle));
    bdestroy(windowTitle);
    bdestroy(name);
    
    // -------------------
    // Start the Game Loop
    // -------------------

    unsigned int previousTime = GetMicroseconds();
    int done = 0;
    while (!done) {
        
        if (glGetError() != GL_NO_ERROR)
            pezFatal("OpenGL error.\n");

        if (XPending(context.MainDisplay)) {
            XEvent event;
    
            XNextEvent(context.MainDisplay, &event);
            switch (event.type)
            {
                case Expose:
                    //redraw(display, event.xany.window);
                    break;
                
                case ConfigureNotify:
                    //resize(event.xconfigure.width, event.xconfigure.height);
                    break;
                
#ifdef PEZ_MOUSE_HANDLER
                case ButtonPress:
                    PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_DOWN);
                    break;

                case ButtonRelease:
                    PezHandleMouse(event.xbutton.x, event.xbutton.y, PEZ_UP);
                    break;

                case MotionNotify:
                    PezHandleMouse(event.xmotion.x, event.xmotion.y, PEZ_MOVE);
                    break;
#endif

                case KeyRelease:
                case KeyPress: {
                    XComposeStatus composeStatus;
                    char asciiCode[32];
                    KeySym keySym;
                    int len;
                    
                    len = XLookupString(&event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus);
                    switch (asciiCode[0]) {
                        case 'x': case 'X': case 'q': case 'Q':
                        case 0x1b:
                            done = 1;
                            break;
                    }
                }
            }
        }

        unsigned int currentTime = GetMicroseconds();
        unsigned int deltaTime = currentTime - previousTime;
        previousTime = currentTime;
        
        PezUpdate((float) deltaTime / 1000000.0f);

        PezRender(0);
        glXSwapBuffers(context.MainDisplay, context.MainWindow);
    }

    pezSwShutdown();

    return 0;
}
Пример #27
0
uint64_t
getFreeNodeMem(int nodeId)
{
    FILE *fp;
    bstring filename;
    uint64_t free = 0;
    bstring freeString  = bformat("MemFree:");
    int i;

    filename = bformat("/sys/devices/system/node/node%d/meminfo", nodeId);

    if (NULL != (fp = fopen (bdata(filename), "r")))
    {
        bstring src = bread ((bNread) fread, fp);
        struct bstrList* tokens = bsplit(src,(char) '\n');

        for (i=0;i<tokens->qty;i++)
        {
            if (binstr(tokens->entry[i],0,freeString) != BSTR_ERR)
            {
                 bstring tmp = bmidstr (tokens->entry[i], 18, blength(tokens->entry[i])-18  );
                 bltrimws(tmp);
                 struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                 free = str2int(bdata(subtokens->entry[0]));
                 bdestroy(tmp);
                 bstrListDestroy(subtokens);
            }
        }
        bstrListDestroy(tokens);
        bdestroy(src);
        fclose(fp);
    }
    else if (!access("/proc/meminfo", R_OK))
    {
        bdestroy(filename);
        filename = bfromcstr("/proc/meminfo");
        if (NULL != (fp = fopen (bdata(filename), "r")))
        {
            bstring src = bread ((bNread) fread, fp);
            struct bstrList* tokens = bsplit(src,(char) '\n');
            for (i=0;i<tokens->qty;i++)
            {
                if (binstr(tokens->entry[i],0,freeString) != BSTR_ERR)
                {
                     bstring tmp = bmidstr (tokens->entry[i], 10, blength(tokens->entry[i])-10  );
                     bltrimws(tmp);
                     struct bstrList* subtokens = bsplit(tmp,(char) ' ');
                     free = str2int(bdata(subtokens->entry[0]));
                     bdestroy(tmp);
                     bstrListDestroy(subtokens);
                }
            }
            bstrListDestroy(tokens);
            bdestroy(src);
            fclose(fp);
        }
    }
    else
    {
        bdestroy(freeString);
        bdestroy(filename);
        ERROR;
    }
    bdestroy(freeString);
    bdestroy(filename);
    return free;
}
Пример #28
0
///
/// Flattens all of the current bins into a single contigious
/// bin.
///
void bins_flatten(freed_bstring name)
{
	struct lconv_entry* entry;
	struct ldbin* target;
	struct ldbin* bin;
	bstring start, desired;
	size_t i;

	// Create the output bin.
	target = bin_create(name, false);
	target->provided = list_create();
	target->required = list_create();
	target->adjustment = list_create();
	target->output = list_create();

	// Loop through all of the current bins and evaluate them.
	list_iterator_start(&ldbins.bins);
	while (list_iterator_hasnext(&ldbins.bins))
	{
		bin = list_iterator_next(&ldbins.bins);

		list_iterator_start(bin->output);
		while (list_iterator_hasnext(bin->output))
		{
			entry = list_iterator_next(bin->output);

			printd(LEVEL_DEBUG, "%s: will output %s at 0x%4X\n", bin->name->data, entry->label->data, entry->address);
		}
		list_iterator_stop(bin->output);

		// Skip if the name begins with SECTION.
		start = bmidstr(bin->name, 0, 8);
		if (biseqcstr(start, "SECTION "))
		{
			bdestroy(start);
			continue;
		}
		bdestroy(start);

		// Move all of the code from this bin into the
		// created bin.
		bin_move(target, bin, list_size(&target->words), 0, list_size(&bin->words));

	}
	list_iterator_stop(&ldbins.bins);

	// Sort the output bins in *reverse* order since we want
	// to insert the last output first.
	list_sort(target->output, -1);

	// Search for all of the output entries in the flattened
	// output bin.
	list_iterator_start(target->output);
	while (list_iterator_hasnext(target->output))
	{
		entry = list_iterator_next(target->output);

		// Find the section that matches.
		desired = bfromcstr("SECTION ");
		bconcat(desired, entry->label);
		bin = list_seek(&ldbins.bins, desired);

		// TODO: Throw a proper error.
		assert(bin != NULL);

		// Insert the required code.
		bin_insert(target, bin, entry->address, 0, list_size(&bin->words));
	}
	list_iterator_stop(target->output);

	// Delete all of the bins.
	// TODO: Free data stored in the list before clearing.
	//for (i = list_size(&ldbins.bins) - 1; i >= 0; i--)
	//	bin_destroy(list_get_at(&ldbins.bins, i));
	list_clear(&ldbins.bins);

	// Add the flattened bin to the list of bins.
	list_append(&ldbins.bins, target);

	// Print result information.
	for (i = 0; i < list_size(&ldbins.bins); i++)
	{
		bin = list_get_at(&ldbins.bins, i);
		printd(LEVEL_VERBOSE, "flattened bin: %s\n", bin->name->data);
		bin->provided != NULL ? printd(LEVEL_VERBOSE, "	 total provided: %u\n", list_size(bin->provided)) : false;
		bin->required != NULL ? printd(LEVEL_VERBOSE, "	 total required: %u\n", list_size(bin->required)) : false;
		bin->adjustment != NULL ? printd(LEVEL_VERBOSE, "  total adjustment: %u\n", list_size(bin->adjustment)) : false;
		bin->section != NULL ? printd(LEVEL_VERBOSE, "	total sections: %u\n", list_size(bin->section)) : false;
		bin->output != NULL ? printd(LEVEL_VERBOSE, "  total outputs: %u\n", list_size(bin->output)) : false;
		printd(LEVEL_VERBOSE, "	 total words: 0x%04X\n", list_size(&bin->words));
		list_iterator_start(&bin->words);
		while (list_iterator_hasnext(&bin->words))
			printd(LEVEL_VERBOSE, "	   0x%04X\n", *(uint16_t*)list_iterator_next(&bin->words));
		list_iterator_stop(&bin->words);
		printd(LEVEL_VERBOSE, "	 \n");
	}
}