text:
<?xml version="1.0" encoding="utf-8" ?>
<!--
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you under the Apache License, Version 2.0 (the            *
 * "License"); you may not use this file except in compliance   *
 * with the License.  You may obtain a copy of the License at   *
 *                                                              *
 *   http://www.apache.org/licenses/LICENSE-2.0                 *
 *                                                              *
 * Unless required by applicable law or agreed to in writing,   *
 * software distributed under the License is distributed on an  *
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
 * KIND, either express or implied.  See the License for the    *
 * specific language governing permissions and limitations      *
 * under the License.                                           *
-->
<project name="etch-cpp-runtime" basedir="." default="help">
    <description>Etch-to-CPP runtime binding implementation</description>
    <property name="Etch.basedir" location="${basedir}/../.." />

    <loadproperties srcFile="build.properties"/>

    <!-- import custom rules which can be used by depending projects to override ant targets -->
    <import file="custom_rules.xml" optional="true" />

    <!-- import etch generics -->
    <import file="${Etch.basedir}/build-support/etch.includes.xml" />

    <!-- Static properties of the sub-project -->
    <property name="proj"                 location="${Etch.basedir}/binding-cpp/runtime" />
    <property name="target"               location="${proj}/target" />
    <property name="capu3rd"              location="${target}/3rd/capu" />
    <property name="testResultsDirectory" location="${target}/test-results" />

    <property name="binaryDir"            location="${Etch.dist}/binding-cpp/bin"/>
    <property name="libaryDir"            location="${Etch.dist}/binding-cpp/lib"/>
    <property name="headerDir"            location="${Etch.dist}/binding-cpp/include"/>

    <!-- INIT TARGET -->
    <!-- Modify this target to define project specific properties that can only be set at runtime -->
    <target name="do-init" >
        <property name="target_platform"                location="${target}/${platform}"/>
        <mkdir dir="${target_platform}" />
        <mkdir dir="${testResultsDirectory}" />
    </target>

    <!-- CLEAN TARGET -->
    <target name="do-clean">
        <delete dir="${target}" />
    </target>

    <!-- BUILD TARGET -->

    <!-- overriding build target from etch.include.xml -->
    <target name="build" depends="">
        <!-- Build platform targets -->
        <if>
            <not><isset property="${target.platforms}"/></not>
            <then>
                <echo level="warn">No target.platforms set. Trying to build for detected host platform...</echo>
                    <if>
                        <os family="windows" />
                        <then>
                            <property name="target.platforms" value="Windows_X86_32"/>
                        </then>
                    </if>
                    <if>
                        <os family="unix" />
                        <then>
                            <property name="target.platforms" value="Linux_X86_32"/>
                        </then>
                    </if>
            </then>
        </if>

        <if>
            <equals arg1="${target.platforms}" arg2=""/>
            <then>
                <echo>${target.platforms}</echo>
                <fail message="Not able to detect platform. target.platforms is not set. Aborting."/>
            </then>
        </if>
        <for list="${target.platforms}" param="platform" delimiter="," trim="true">
            <sequential>
                <var name="platform" value="@{platform}"/>
                <var name="cmake.build.etchtests" unset="true"/>
                <var name="etchtests.writeTestResultsToFile" unset="true"/>
                <if>
                    <isset property="target.platforms.${platform}.buildTests" />
                        <then>
                            <propertycopy name="cmake.build.etchtests" from="target.platforms.${platform}.buildTests" />
                        </then>
                        <else>
                            <property name="cmake.build.etchtests" value="YES" />
                        </else>
                </if>
                <if>
                    <isset property="target.platforms.${platform}.writeTestResultsToFile" />
                        <then>
                            <propertycopy name="etchtests.writeTestResultsToFile" from="target.platforms.${platform}.writeTestResultsToFile" />
                        </then>
                        <else>
                            <property name="etchtests.writeTestResultsToFile" value="YES" />
                        </else>
                </if>
                <echo>Init platform: ${platform}</echo>
                <antcall target="init"/>
                <echo>Building platform: ${platform}</echo>
                <antcall target="do-build"/>
                <echo>Testing platform: ${platform}</echo>
                <if>
                    <equals arg1="${etchtests.writeTestResultsToFile}" arg2="YES"/>
                    <then>
                        <antcall target="do-test"/>
                    </then>
                    <else>
                        <antcall target="do-test-noTestResults"/>
                    </else>
                </if>

            </sequential>
        </for>

    </target>

    <target name="do-build-info" unless="USE.cmake">
        <echo message="**********************************" />
        <echo message="binding-cpp build will not be done." />
        <echo message="**********************************" />
    </target>

    <target name="do-build-generate-sources" if="USE.cmake">
        <mkdir dir="${Etch.dist}/binding-cpp" />
        <!-- package up etch-java-runtime src -->
        <zip destfile="${Etch.dist}/binding-cpp/${etch-cpp-runtime-src.zip}">
            <fileset dir="${proj}">
                <exclude name="target/" />
                <exclude name="doc/" />
                <exclude name="**/.svn" />
            </fileset>
        </zip>
    </target>

    <target name="do-build-main" if="USE.cmake">
        <property name="defaultCMakeToolchainDir" value="${basedir}/toolchains"/>
        <if>
            <isset property="target.platforms.${platform}.toolchainfile"/>
            <then>
                <propertycopy name="cmake.toolchainfile" from="target.platforms.${platform}.toolchainfile" />
            </then>
            <else>
                <property name="cmake.toolchainfile" value="${defaultCMakeToolchainDir}/${platform}.toolchain"/>
            </else>
        </if>

        <if>
            <isset property="CAPU_INCLUDE_DIR"/>
            <then>
                <property name="use.capu.include.dir" value="${CAPU_INCLUDE_DIR}"/>
            </then>
            <else>
                <property name="use.capu.include.dir" value=""/>
            </else>
        </if>

        <if>
            <isset property="CAPU_LIBRARY_DIR"/>
            <then>
                <property name="use.capu.library.dir" value="${CAPU_LIBRARY_DIR}"/>
            </then>
            <else>
                <property name="use.capu.library.dir" value=""/>
            </else>
        </if>

        <if>
            <isset property="LOCAL_CAPU_SOURCE_DIR"/>
            <then>
                <property name="use.capu.local.source.dir" value="${LOCAL_CAPU_SOURCE_DIR}"/>
            </then>
            <else>
                <property name="use.capu.local.source.dir" value=""/>
            </else>
        </if>

        <if>
            <isset property="CUSTOM_BUILD_OPTIONS"/>
            <then>
                <property name="use.custom.build.options" value="${CUSTOM_BUILD_OPTIONS}"/>
            </then>
            <else>
                <property name="use.custom.build.options" value=""/>
            </else>
        </if>

        <if>
            <isset property="ios.sdkVersion" />
                <then>
                    <propertycopy name="cmake.ios.sdkVersion" from="ios.sdkVersion" />
                </then>
                <else>
                    <property name="cmake.ios.sdkVersion" value="7.1" />
                </else>
        </if>

        <if>
            <isset property="target.platforms.${platform}.generator"/>
            <then>
                <!-- use specified generator -->
                <propertycopy name="cmake.generator" from="target.platforms.${platform}.generator" />
                <echo>Configuring CMake build</echo>
                <echo>Using generator: ${cmake.generator}</echo>
                <echo>Using toolchain file: ${cmake.toolchainfile}</echo>

                <mkdir dir="${target}/${platform}/${Etch.build.target}"/>

                <!-- CMake configuration -->
                <exec dir="${target}/${platform}/${Etch.build.target}" executable="cmake" failonerror="true">
                    <arg value="-G${cmake.generator}"/>
                    <arg value="-DETCH_EXTERNAL_DEPENDS:PATH=${env.ETCH_EXTERNAL_DEPENDS}" />
                    <arg value="-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${cmake.toolchainfile}" />
                    <arg value="-DETCH_INSTALL_DIR:PATH=${Etch.dist}/binding-cpp"/>
                    <arg value="-DETCH_TARGET_PLATFORM:STRING=${platform}"/>
                    <arg value="-DCMAKE_BUILD_TYPE:STRING=${Etch.build.target}"/>
                    <arg value="-DCAPU_INCLUDE_DIR:PATH=${use.capu.include.dir}"/>
                    <arg value="-DCAPU_LIBRARY_DIR:PATH=${use.capu.library.dir}"/>
                    <arg value="-DCAPU_BUILD_DIR:PATH=${capu3rd}" />
                    <arg value="-DSDK_VERSION:STRING=${cmake.ios.sdkVersion}" />
                    <arg value="-DLOCAL_CAPU_SOURCE_DIR:PATH=${use.capu.local.source.dir}"/>
                    <arg value="-DCONFIG_BUILD_TESTS:BOOL=${cmake.build.etchtests}" />
                    <arg value="${basedir}"/>
                </exec>

                <!-- run the build -->
                <exec dir="${target}/${platform}/${Etch.build.target}" executable="cmake" failonerror="false">
                    <arg line="--build . --target rebuild_cache --config ${Etch.build.target}"/>
                </exec>

                <!-- run the build -->
                <exec dir="${target}/${platform}/${Etch.build.target}" executable="cmake" failonerror="true">
                    <arg line="--build . --target install --config ${Etch.build.target}"/>
                </exec>

            </then>
            <else>
                <!-- try default generator -->
                <echo>Configuring CMake build</echo>
                <echo>Using default generator</echo>
                <echo>Using toolchain file: ${cmake.toolchainfile}</echo>

                <mkdir dir="${target}/${platform}/${Etch.build.target}"/>

                <!-- CMake configuration -->
                <exec dir="${target}/${platform}/${Etch.build.target}" executable="cmake" failonerror="true">
                    <arg value="-DETCH_EXTERNAL_DEPENDS:PATH=${env.ETCH_EXTERNAL_DEPENDS}" />
                    <arg value="-DCMAKE_TOOLCHAIN_FILE:FILEPATH=${cmake.toolchainfile}" />
                    <arg value="-DETCH_INSTALL_DIR:PATH=${Etch.dist}/binding-cpp"/>
                    <arg value="-DETCH_TARGET_PLATFORM:STRING=${platform}"/>
                    <arg value="-DCMAKE_BUILD_TYPE:STRING=${Etch.build.target}"/>
                    <arg value="-DCAPU_INCLUDE_DIR:PATH=${use.capu.include.dir}"/>
                    <arg value="-DCAPU_LIBRARY_DIR:PATH=${use.capu.library.dir}"/>
                    <arg value="-DLOCAL_CAPU_SOURCE_DIR:PATH=${use.capu.local.source.dir}"/>
                    <arg value="-DCAPU_BUILD_DIR:PATH=${capu3rd}" />
                    <arg value="-DSDK_VERSION:STRING=${cmake.ios.sdkVersion}" />
                    <arg value="-DCONFIG_BUILD_TESTS:BOOL=${cmake.build.etchtests}" />
                    <arg value="${basedir}"/>
                </exec>

                <!-- run the build -->
                <exec dir="${target}/${platform}/${Etch.build.target}" executable="cmake" failonerror="true">
                    <arg line="--build . --target install --config ${Etch.build.target} -- ${use.custom.build.options}"/>
                </exec>

            </else>
        </if>
    </target>

    <target name="do-build" depends="do-build-info,do-build-generate-sources,do-build-main" if="USE.cmake">

    </target>

    <!-- TEST TARGET -->
    <target name="test" depends="postbuild">
    </target>

    <target name="postbuild" depends="build,do-postbuild">
    </target>

    <target name="do-test" unless="skip.tests">
        <if>
            <not><equals arg1="${cmake.build.etchtests}" arg2="YES"/></not>
            <then>
                <echo>Test execution has been disabled.</echo>
            </then>
            <else>
                <!-- Run Etch Unit Tests -->
                <!-- Run Etch Unit Tests on Windows-->
                <exec executable="${binaryDir}/${platform}/${Etch.build.target}/etch-cpp-test.exe" osfamily="windows"  failonerror="true">
                    <arg value="--gtest_output=xml:${testResultsDirectory}/"/>
                </exec>
                <!-- Run Etch Unit Tests on Unix -->
                <exec executable="${binaryDir}/${platform}/${Etch.build.target}/etch-cpp-test" osfamily="unix"  failonerror="true">
                    <arg value="--gtest_output=xml:${testResultsDirectory}/"/>
                </exec>
            </else>
        </if>
    </target>

    <target name="do-test-noTestResults" unless="skip.tests">
         <if>
            <not><equals arg1="${cmake.build.etchtests}" arg2="YES"/></not>
            <then>
                <echo>Test execution has been disabled.</echo>
            </then>
            <else>
                <!-- Run Etch Unit Tests -->
                <!-- Run Etch Unit Tests on Windows-->
                <exec executable="${binaryDir}/${platform}/${Etch.build.target}/etch-cpp-test.exe" osfamily="windows"  failonerror="true" />
                <!-- Run Etch Unit Tests on Unix -->
                <exec executable="${binaryDir}/${platform}/${Etch.build.target}/etch-cpp-test" osfamily="unix"  failonerror="true" />
            </else>
        </if>
    </target>

    <target name="do-publish" if="build.tests.fail">
        <!-- Set flag file if any tests failed -->
        <touch file="${Etch.runtime.tests.fail}"/>
    </target>

</project>


text:
#include <libcgc.h>
#include <stdint.h>
#include "libc.h"
#include "prng.h"
#include "malloc.h"
#include "fs.h"

#define ROAMTIMEOUT 2
#define VERSION 0xc0ff33

/**
 * Read in data from stdin with a timeout
 *
 * @param s struct to cgc_read into
 * @return 1 on success, 0 on failure
 */
#define READDATATIMEOUT(s) (sizeof(s) == readall_timeout(stdin,(char *)&s,sizeof(s)) ? 1 : 0)

/**
 * Read in data from stdin and decrypt
 *
 * @param s struct to cgc_read into
 * @return 1 on success, 0 on failure
 */
#define EREADDATA(s) (sizeof(s) == ereadall(stdin,(char *)&s,sizeof(s)) ? 1 : 0)

/**
 * Encrypt data and send to stdout
 *
 * @param s struct to cgc_write
 * @return 1 on success, 0 on failure
 */
#define ESENDDATA(s) (sizeof(s) == esendall(stdout,(char *)&s,sizeof(s)) ? 1 : 0)

enum Status {OK, EXIT, DISCON, ERR} typedef status_t;

enum MsgType {MKDIR, LIST, PUT, GET, RM, RMDIR,
    QUIT} typedef msgtype_t;

enum RespType {MKDIR_OK, MKDIR_FAIL, LIST_OK,
    LIST_FAIL, PUT_OK, PUT_FAIL, GET_OK, GET_FAIL,
    RM_OK, RM_FAIL, RMDIR_OK, RMDIR_FAIL, QUIT_OK} typedef resptype_t;

struct msg {
    msgtype_t type;
    char buf[1024];
} typedef msg_t;

struct resp {
    resptype_t type;
    char buf[1024];
} typedef resp_t;

struct config {
    uint32_t max_ver;
    uint32_t min_ver;
    uint32_t encrypt;
    uint32_t allow_reconnect;
    size_t buf_size;
} typedef config_t;

static config_t conf;
static char *last;

/**
 * Attempt to cgc_read a fixed number of bytes, timeout after 2 seconds
 *
 * @param fd File descriptor to cgc_read from.
 * @param buf Buffer to cgc_write cgc_read bytes to.
 * @param s Maximum number of bytes to cgc_read
 * @return Number of bytes cgc_read
 */
static size_t readall_timeout(int fd, char *buf, size_t s) {
    fd_set readfds;
    int numready = 0;
    struct timeval timeout = {ROAMTIMEOUT, 0};
    size_t i, res, recvd = 0;

    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);

    for (i=0; i < s; i+=recvd) {
        res = fdwait(fd+1, &readfds, NULL, &timeout, &numready);
        if (!res && numready) {
            if (receive(fd, buf+i, s-i, &recvd) || recvd == 0)
                DIE(READFAIL);
        } else {
            break;
        }
    }

    return i;
}

/**
 * Attempt to cgc_read a fixed number of bytes and decrypt
 *
 * @param fd File descriptor to cgc_read from.
 * @param buf Buffer to cgc_write cgc_read bytes to.
 * @param s Maximum number of bytes to cgc_read
 * @return Number of bytes cgc_read
 */
static size_t ereadall(int fd, char *buf, size_t s) {
    size_t i = 0;
    uint32_t *buf32 = (uint32_t*)buf;

    if ((s % 4) != 0) {
        debug("Encrypted recv must be 4 byte aligned!\n");
        DIE(READFAIL);
    }

    if (s != (i = readall_timeout(fd, buf, s))) {
        debug("readall failed, returns @h\n", i);
        return i;
    }

    for (i = 0; i < s/4; i++) {
        uint32_t tmp;
        tmp = getshifty();
        buf32[i] ^= tmp;
    }
    return s;
}

/**
 * Attempt to encrypt then send a fixed number of bytes
 *
 * @param fd File descriptor to cgc_write to
 * @param buf Buffer to cgc_read bytes from
 * @param s Number of bytes to send
 * @return Number of bytes sent.
 */
static size_t esendall(int fd, char *buf, size_t s) {
    int i;
    uint32_t *buf32 = (uint32_t*)buf;
    size_t res;

    if ((s % sizeof(uint32_t)) != 0) {
        debug("Encrypted sends must be 4 byte aligned!\n");
        DIE(WRITEFAIL);
    }

    for (i = 0; i < s/sizeof(uint32_t); i++)
        buf32[i] ^= getshifty();

    res = sendall(fd, buf, s);

    if (s != res)
        DIE(WRITEFAIL);

    return s;
}

/**
 * Handle a mkdir request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_mkdir(msg_t *msg) {
    resp_t *resp = calloc(sizeof(resp_t));

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    if (!add_dir(msg->buf)) {
        resp->type = MKDIR_OK;
        cgc_memset(resp->buf, 0, sizeof(resp->buf));
    } else {
        debug("Adding directory failed.\n");
        resp->type = MKDIR_FAIL;
    }

    return resp;
}

/**
 * Handle a list request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_list(msg_t *msg) {
    char *dirlist;
    resp_t *resp = calloc(sizeof(resp_t));

    debug("Attempting to list directory...\n");

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    dirlist = ls_dir(msg->buf);

    if (!dirlist) {
        debug("Listing directory failed.\n");
        resp->type = LIST_FAIL;
        return resp;
    }

    //truncate if too long
    if (cgc_strlen(dirlist) > MAX_FILE_SIZE)
        *(dirlist+MAX_FILE_SIZE) = '\0';
    strcpy(resp->buf, dirlist);

    resp->type = LIST_OK;

    free(dirlist);

    return resp;
}

/**
 * Handle a put request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_put(msg_t *msg) {
    char *fn;
    char *data;
    size_t fnlen, datalen;

    debug("Attempting put...\n");

    resp_t *resp = calloc(sizeof(resp_t));

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    fnlen = cgc_strlen(msg->buf);

    if (fnlen > MAX_FILENAME_SIZE) {
        debug("Filename too large.\n");
        resp->type = PUT_FAIL;
        return resp;
    }

    fn = malloc(fnlen+1);
    strcpy(fn, msg->buf);

    datalen = cgc_strlen(msg->buf+fnlen+1);

    if (datalen > MAX_FILE_SIZE) {
        debug("File data too large.\n");
        resp->type = PUT_FAIL;
        free(fn);
        return resp;
    }

    data = malloc(datalen+1);
    strcpy(data, msg->buf+fnlen+1);

    if (!add_file(fn, data)) {
        resp->type = PUT_OK;
    } else {
        debug("Put failed.\n");
        resp->type = PUT_FAIL;
    }

    free(fn);
    free(data);

    return resp;
}

/**
 * Handle a get request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_get(msg_t *msg) {
    char *data;

    debug("Attempting to get file...\n");

    resp_t *resp = calloc(sizeof(resp_t));

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    if (!(data = readfile(msg->buf))) {
        debug("Failed to read file.\n");
        resp->type = GET_FAIL;
        return resp;
    }

    resp->type = GET_OK;
    cgc_memcpy(resp->buf, data, sizeof(resp->buf));
    return resp;
}

/**
 * Handle a rm request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_rm(msg_t *msg) {
    resp_t *resp = calloc(sizeof(resp_t));

    debug("Attempting to remove file...\n");

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    if (!rm_file(msg->buf)) {
        resp->type = RM_OK;
        return resp;
    } else {
        debug("Failed to rm file.\n");
        resp->type = RM_FAIL;
        return resp;
    }

    cgc_memcpy(resp, msg, sizeof(resp_t));
    return resp;
}

/**
 * Handle a rmdir request
 *
 * @param msg client message data
 * @return Response data, NULL on allocation error
 */
resp_t *do_rmdir(msg_t *msg) {
    resp_t *resp = calloc(sizeof(resp_t));

    debug("Attempting to remove dir...\n");

    if (!resp) {
        debug("Failed to allocate response.\n");
        return NULL;
    }

    if (!rm_dir(msg->buf)) {
        resp->type = RMDIR_OK;
        return resp;
    } else {
        debug("Failed to rm dir.\n");
        resp->type = RMDIR_FAIL;
        return resp;
    }

    cgc_memcpy(resp, msg, sizeof(resp_t));
    return resp;
}

/**
 * Process the next incoming request
 *
 * @return status response
 */
status_t process_req() {
    msg_t *msg = malloc(sizeof(msg_t));
    resp_t *resp = NULL;

    if (!EREADDATA(*msg)) {
        debug("Disconnected!\n");
        return DISCON;
    }

    msg->buf[sizeof(msg->buf)-1] = '\0';

    switch (msg->type) {
        case MKDIR:
            resp = do_mkdir(msg);
            break;
        case LIST:
            resp = do_list(msg);
            break;
        case PUT:
            resp = do_put(msg);
            break;
        case GET:
            resp = do_get(msg);
            break;
        case RM:
            resp = do_rm(msg);
            break;
        case RMDIR:
            resp = do_rmdir(msg);
            break;
        case QUIT:
            return EXIT;
        default:
            return ERR;
    }

    if (!resp)
        return ERR;

    ESENDDATA(*resp);

    if (last)
        free(last);

    last = (char *)resp;

    return OK;
}

/**
 * Main request handling loop
 *
 * @return 0 on success, err code on failure
 */
int go(void) {
    int i;
    int res;
    uint32_t tmp = 0;
    uint32_t *seed;
    char *resend;
    size_t tosend;
    size_t offset;
    uint32_t *f;

    init_fs();
    debug("fs init complete\n");

    if (!READDATATIMEOUT(conf)) {
        debug("failed to recv conf\n");
        res = 0;
        SENDDATA(res);
        return 3;
    }

    if (conf.min_ver > VERSION || conf.max_ver < VERSION) {
        debug("version mismatch\n");
        res = 0;
        SENDDATA(res);
        return 5;
    }
    //send success ack
    res = 1;
    SENDDATA(res);

    //seed our PRNG
    //because of how it works, seeding with 0's == no encryption
    seed = (uint32_t*)(FLAG_PAGE + (8*sizeof(uint32_t)));

    f = malloc(8*sizeof(uint32_t));

    if (!f)
        return 1;

    cgc_memcpy(f, seed, 8*sizeof(uint32_t));

    if (!conf.encrypt)
        seed = calloc(8*sizeof(uint32_t));

    srand(seed);

    //inform client of seed
    for (i = 0; i < 8; i+=2) {
        if (conf.encrypt)
            tmp = f[i]^f[i+1];
        SENDDATA(tmp);
    }

    #ifdef PATCHED_1
    cgc_memset(f, '\0', 8*sizeof(uint32_t));
    #endif
    debug("flag data: @h\n",f);

    free(f);

    while (1) {
        res = process_req();
        if (res == ERR || res == EXIT) {
             break;
        } else if (res == DISCON && conf.allow_reconnect && last) {
            debug("disconnected, retrying\n");
            if (!READDATATIMEOUT(conf)) {
                debug("failed to recv conf\n");
                return 3;
            }

            if (!last)
                continue;

            debug("Allocating resend buffer of @h bytes.\n",conf.buf_size+sizeof(resp_t));
            #ifdef PATCHED_1
            resend = calloc(conf.buf_size+sizeof(resp_t));
            #else
            resend = malloc(conf.buf_size+sizeof(resp_t));
            #endif
            debug("resend data: @h\n",resend);

            if (!READDATA(offset)) {
                debug("failed to recv offset\n");
                return 4;
            }

            tosend = sizeof(resp_t)-offset;
            tosend = tosend > sizeof(resp_t) ? sizeof(resp_t) : tosend;

            if (offset > conf.buf_size || offset > sizeof(resp_t)
            #ifdef PATCHED_1
                    || tosend > (conf.buf_size+sizeof(resp_t))
            #endif
            ){
                debug("failed to validate offset.\n");
                return 1;
            } else {
                debug("copying last out\n");
                cgc_memcpy(resend, last+offset, sizeof(resp_t)-offset);
            }

            #ifdef PATCHED_1
            if (tosend != esendall(stdout, resend, tosend))
            #else
            if (tosend != esendall(stdout, resend, sizeof(resp_t)))
            #endif
                return 4;
            debug("Resent all, should be back!\n");

            free(resend);
            free(last);
            last = NULL;
        }
    }
    return 0;
}

/**
 * Calculate checksum of .text
 *
 * @return csum of the .text section
 */
uint32_t get_text_checksum() {
#if !(defined(PATCHED_1) || defined(DEBUG))
    char *cur = (char *) go;
    uint32_t csum = 0;

    //ensure our functions are still happy
    if (!((void*)go < (void*)longjmp))
        _terminate(2);

    //now lets calculate our checksum
    do {
        csum ^= *(uint32_t*)cur;
        cur += sizeof(uint32_t);
        //close enough :)
    } while (cur < (char *)longjmp);

    return csum;
#else
    uint32_t *flag = (uint32_t*)FLAG_PAGE;
    return 0x1337b33f ^ flag[0] ^ flag[1];
#endif
}

bool verify_integrity() {
/* Ensure our client is running a valid binary!
 * Send to server for validation! */

    uint32_t res = 0;

    #if !(defined(PATCHED_1) || defined(DEBUG))
    res = getshifty();
    #endif
    res ^= get_text_checksum();

    //verify that this is correct
    //in practice, the poll just refuses to respond if wrong
    printf("@h",res);
    if(!READDATA(res))
        return 0;
    return res;
}

int main() {
    if (verify_integrity())
        return go();
    else
        return 2;
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

////////////

//load async deps for any of your suman tests
export default ($core: Object, $deps: Object) => {

  return {

    dependencies: {

      'chuck': function () {
        return 'berry';
      },

      'mark': function (cb: Function) {
        cb(null, 'rutherfurd');
      },

    }

  };

};


text:
  {% include common/socialmedia.html %}

        The contents of this website are
        © {{ site.time | date: '%Y' }} under the terms of the MIT License.

Made with ♥ in Montreal


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="?selectableItemBackground"
    tools:context=".ui.InviteActivity">

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
        tools:text="test@example.com" />

    <com.pr0gramm.app.ui.views.UsernameView
        android:id="@+id/username"
        android:visibility="gone"
        android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        tools:text="noch nicht eingelöst, vor 1 Tag" />

</LinearLayout>


text: AngularJS controlpanel for testing purposes


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MusicStore.Areas.Identity.Pages.Account
{
    public class AccessDeniedModel : PageModel
    {
        public void OnGet()
        {

        }
    }
}


text:
package org.sirix.saxon.wrapper;

import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmItem;

import org.custommonkey.xmlunit.XMLTestCase;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sirix.Holder;
import org.sirix.TestHelper;
import org.sirix.api.Database;
import org.sirix.exception.SirixException;
import org.sirix.saxon.evaluator.XPathEvaluator;

/**
 * Test XPath S9Api.
 *
 * @author Johannes Lichtenberger, University of Konstanz
 *
 */
public final class TestNodeWrapperS9ApiXPath extends XMLTestCase {

	/**
	 * sirix database on sirix test document {@link Database}.
	 */
	private transient Holder mHolder;

	@Override
	@Before
	public void setUp() throws SirixException {
		XMLUnit.setIgnoreWhitespace(true);
		TestHelper.deleteEverything();
		TestHelper.createTestDocument();
		mHolder = Holder.generateRtx();
	}

	@Override
	@After
	public void tearDown() throws SirixException {
		mHolder.close();
	}

	@Test
	public void testB1() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("//b[1]",
				mHolder.getSession()).build().call();

		final StringBuilder strBuilder = new StringBuilder();

		for (final XdmItem item : selector) {
			strBuilder.append(item.toString());
		}

		assertXMLEqual("expected pieces to be similar",
				"foo<c xmlns:p=\"ns\"/>", strBuilder.toString());
	}

	@Test
	public void testB1String() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("//b[1]/text()",
				mHolder.getSession()).build().call();

		final StringBuilder strBuilder = new StringBuilder();

		for (final XdmItem item : selector) {
			strBuilder.append(item.toString());
		}

		assertEquals("foo", strBuilder.toString());
	}

	@Test
	public void testB2() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("//b[2]",
				mHolder.getSession()).build().call();

		final StringBuilder strBuilder = new StringBuilder();

		for (final XdmItem item : selector) {
			strBuilder.append(item.toString());
		}

		assertXMLEqual("expected pieces to be similar",
				"<c xmlns:p=\"ns\"/>bar",
				strBuilder.toString());
	}

	@Test
	public void testB2Text() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("//b[2]/text()",
				mHolder.getSession()).build().call();

		final StringBuilder strBuilder = new StringBuilder();

		for (final XdmItem item : selector) {
			strBuilder.append(item.toString());
		}

		assertEquals("bar", strBuilder.toString());
	}

	@Test
	public void testB() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("//b",
				mHolder.getSession()).build().call();

		final StringBuilder strBuilder = new StringBuilder();

		strBuilder.append("<result>");
		for (final XdmItem item : selector) {
			strBuilder.append(item.toString());
		}
		strBuilder.append("</result>");

		assertXMLEqual(
				"expected pieces to be similar",
				"<result>foo<c xmlns:p=\"ns\"/>"
						+ "<c xmlns:p=\"ns\"/>bar</result>", strBuilder.toString());
	}

	@Test
	public void testCountB() throws Exception {
		final XPathSelector selector = new XPathEvaluator.Builder("count(//b)",
				mHolder.getSession()).build().call();

		final StringBuilder sb = new StringBuilder();

		for (final XdmItem item : selector) {
			sb.append(item.getStringValue());
		}

		assertEquals("2", sb.toString());
	}

}


text:
import Vue from 'vue';
import Router from 'vue-router';

import Login from '../page/login/login.vue';
import Layout from '../layout/App.vue';

Vue.use(Router);

export default new Router({
	routes: [
		{
			path: '/layout',
			name: 'Layout',
			component: Layout
		},
		{
			path: '/',
			redirect: '/login'
		},
		{
			path: '/login',
			name: 'Login',
			component: Login
		}
		// {
		// 	path: '/login',
		// 	component: resolve => require(['../pages/login/login.vue'], resolve)
		// },
		// {
		// 	path: '/layout',
		// 	component: resolve => require(['../layout/Layout.vue'])
		// }
	]
})


text:
package org.wildfly.security.ssl;

import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;

import org.wildfly.common.Assert;
import org.wildfly.security._private.ElytronMessages;

/**
 * @author David M. Lloyd
 */
class SNIServerSSLEngine extends SSLEngine {

    private final AtomicReference<SSLEngine> currentRef;

    SNIServerSSLEngine(final SNIServerSSLContextSelector selector) {
        currentRef = new AtomicReference<>(new InitialState(selector));
    }

    public SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
        return currentRef.get().wrap(srcs, offset, length, dst);
    }

    public SSLEngineResult wrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException {
        return currentRef.get().wrap(src, dst);
    }

    public SSLEngineResult wrap(final ByteBuffer[] srcs, final ByteBuffer dst) throws SSLException {
        return currentRef.get().wrap(srcs, dst);
    }

    public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
        return currentRef.get().unwrap(src, dsts, offset, length);
    }

    public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException {
        return currentRef.get().unwrap(src, dst);
    }

    public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts) throws SSLException {
        return currentRef.get().unwrap(src, dsts);
    }

    public String getPeerHost() {
        return currentRef.get().getPeerHost();
    }

    public int getPeerPort() {
        return currentRef.get().getPeerPort();
    }

    public SSLSession getHandshakeSession() {
        return currentRef.get().getHandshakeSession();
    }

    public SSLParameters getSSLParameters() {
        return currentRef.get().getSSLParameters();
    }

    public void setSSLParameters(final SSLParameters params) {
        currentRef.get().setSSLParameters(params);
    }

    public Runnable getDelegatedTask() {
        return currentRef.get().getDelegatedTask();
    }

    public void closeInbound() throws SSLException {
        currentRef.get().closeInbound();
    }

    public boolean isInboundDone() {
        return currentRef.get().isInboundDone();
    }

    public void closeOutbound() {
        currentRef.get().closeOutbound();
    }

    public boolean isOutboundDone() {
        return currentRef.get().isOutboundDone();
    }

    public String[] getSupportedCipherSuites() {
        return currentRef.get().getSupportedCipherSuites();
    }

    public String[] getEnabledCipherSuites() {
        return currentRef.get().getEnabledCipherSuites();
    }

    public void setEnabledCipherSuites(final String[] cipherSuites) {
        currentRef.get().setEnabledCipherSuites(cipherSuites);
    }

    public String[] getSupportedProtocols() {
        return currentRef.get().getSupportedProtocols();
    }

    public String[] getEnabledProtocols() {
        return currentRef.get().getEnabledProtocols();
    }

    public void setEnabledProtocols(final String[] protocols) {
        currentRef.get().setEnabledProtocols(protocols);
    }

    public SSLSession getSession() {
        return currentRef.get().getSession();
    }

    public void beginHandshake() throws SSLException {
        currentRef.get().beginHandshake();
    }

    public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
        return currentRef.get().getHandshakeStatus();
    }

    public void setUseClientMode(final boolean clientMode) {
        currentRef.get().setUseClientMode(clientMode);
    }

    public boolean getUseClientMode() {
        return currentRef.get().getUseClientMode();
    }

    public void setNeedClientAuth(final boolean clientAuth) {
         currentRef.get().setNeedClientAuth(clientAuth);
    }

    public boolean getNeedClientAuth() {
        return currentRef.get().getNeedClientAuth();
    }

    public void setWantClientAuth(final boolean want) {
        currentRef.get().setWantClientAuth(want);
    }

    public boolean getWantClientAuth() {
        return currentRef.get().getWantClientAuth();
    }

    public void setEnableSessionCreation(final boolean flag) {
        currentRef.get().setEnableSessionCreation(flag);
    }

    public boolean getEnableSessionCreation() {
        return currentRef.get().getEnableSessionCreation();
    }

    static final int FL_WANT_C_AUTH = 1 << 0;
    static final int FL_NEED_C_AUTH = 1 << 1;
    static final int FL_SESSION_CRE = 1 << 2;

    class InitialState extends SSLEngine {

        private final SNIServerSSLContextSelector selector;
        private final AtomicInteger flags = new AtomicInteger(FL_SESSION_CRE);

        InitialState(final SNIServerSSLContextSelector selector) {
            this.selector = selector;
        }

        public String getPeerHost() {
            return super.getPeerHost();
        }

        public int getPeerPort() {
            return super.getPeerPort();
        }

        public SSLSession getHandshakeSession() {
            return null;
        }

        public SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
            return new SSLEngineResult(SSLEngineResult.Status.OK, SSLEngineResult.HandshakeStatus.NEED_UNWRAP, 0, 0);
        }

        public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
            SSLEngine next;
            final int mark = src.position();
            try {
                if (src.remaining() < SSLExplorer.RECORD_HEADER_SIZE) {
                    return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, SSLEngineResult.HandshakeStatus.NEED_UNWRAP, 0, 0);
                }
                final int requiredSize = SSLExplorer.getRequiredSize(src);
                if (src.remaining() < requiredSize) {
                    return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, SSLEngineResult.HandshakeStatus.NEED_UNWRAP, 0, 0);
                }
                final SSLCapabilities capabilities = SSLExplorer.explore(src);
                final List<SNIServerName> serverNames = capabilities.getServerNames();
                SSLContext sslContext;
                final Iterator<SNIServerName> iterator = serverNames.iterator();
                if (! iterator.hasNext()) {
                    sslContext = selector.selectContext(null);
                } else do {
                    final SNIServerName serverName = iterator.next();
                    sslContext = selector.selectContext(serverName);
                    if (sslContext != null) {
                        break;
                    }
                } while (iterator.hasNext());
                if (sslContext == null) {
                    // no SSL context is available
                    throw ElytronMessages.log.noHostForSslConnection();
                }
                next = sslContext.createSSLEngine();
                next.setUseClientMode(false);
                final int flagsVal = flags.get();
                if ((flagsVal & FL_WANT_C_AUTH) != 0) {
                    next.setWantClientAuth(true);
                } else if ((flagsVal & FL_NEED_C_AUTH) != 0) {
                    next.setNeedClientAuth(true);
                }
                if ((flagsVal & FL_SESSION_CRE) != 0) {
                    next.setEnableSessionCreation(true);
                }
                currentRef.set(next);
            } finally {
                src.position(mark);
            }
            return next.unwrap(src, dsts, offset, length);
        }

        public Runnable getDelegatedTask() {
            return null;
        }

        public void closeInbound() throws SSLException {
            currentRef.set(CLOSED_STATE);
        }

        public boolean isInboundDone() {
            return false;
        }

        public void closeOutbound() {
            currentRef.set(CLOSED_STATE);
        }

        public boolean isOutboundDone() {
            return false;
        }

        public String[] getSupportedCipherSuites() {
            throw Assert.unsupported();
        }

        public String[] getEnabledCipherSuites() {
            throw Assert.unsupported();
        }

        public void setEnabledCipherSuites(final String[] suites) {
            throw Assert.unsupported();
        }

        public String[] getSupportedProtocols() {
            throw Assert.unsupported();
        }

        public String[] getEnabledProtocols() {
            throw Assert.unsupported();
        }

        public void setEnabledProtocols(final String[] protocols) {
            throw Assert.unsupported();
        }

        public SSLSession getSession() {
            return null;
        }

        public void beginHandshake() throws SSLException {
        }

        public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
            return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
        }

        public void setUseClientMode(final boolean mode) {
            if (mode) throw Assert.unsupported();
        }

        public boolean getUseClientMode() {
            return false;
        }

        public void setNeedClientAuth(final boolean need) {
            final AtomicInteger flags = this.flags;
            int oldVal, newVal;
            do {
                oldVal = flags.get();
                if (((oldVal & FL_NEED_C_AUTH) != 0) == need) {
                    return;
                }
                newVal = oldVal & FL_SESSION_CRE | FL_NEED_C_AUTH;
            } while (! flags.compareAndSet(oldVal, newVal));
        }

        public boolean getNeedClientAuth() {
            return (flags.get() & FL_NEED_C_AUTH) != 0;
        }

        public void setWantClientAuth(final boolean want) {
            final AtomicInteger flags = this.flags;
            int oldVal, newVal;
            do {
                oldVal = flags.get();
                if (((oldVal & FL_WANT_C_AUTH) != 0) == want) {
                    return;
                }
                newVal = oldVal & FL_SESSION_CRE | FL_WANT_C_AUTH;
            } while (! flags.compareAndSet(oldVal, newVal));
        }

        public boolean getWantClientAuth() {
            return (flags.get() & FL_WANT_C_AUTH) != 0;
        }

        public void setEnableSessionCreation(final boolean flag) {
            final AtomicInteger flags = this.flags;
            int oldVal, newVal;
            do {
                oldVal = flags.get();
                if (((oldVal & FL_SESSION_CRE) != 0) == flag) {
                    return;
                }
                newVal = oldVal ^ FL_SESSION_CRE;
            } while (! flags.compareAndSet(oldVal, newVal));
        }

        public boolean getEnableSessionCreation() {
            return (flags.get() & FL_SESSION_CRE) != 0;
        }
    }

    static final SSLEngine CLOSED_STATE = new SSLEngine() {
        public SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
            throw ElytronMessages.log.sslClosed();
        }

        public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
            throw ElytronMessages.log.sslClosed();
        }

        public Runnable getDelegatedTask() {
            return null;
        }

        public void closeInbound() throws SSLException {
        }

        public boolean isInboundDone() {
            return true;
        }

        public void closeOutbound() {

        }

        public boolean isOutboundDone() {
            return true;
        }

        public String[] getSupportedCipherSuites() {
            throw Assert.unsupported();
        }

        public String[] getEnabledCipherSuites() {
            throw Assert.unsupported();
        }

        public void setEnabledCipherSuites(final String[] suites) {
            throw Assert.unsupported();
        }

        public String[] getSupportedProtocols() {
            throw Assert.unsupported();
        }

        public String[] getEnabledProtocols() {
            throw Assert.unsupported();
        }

        public void setEnabledProtocols(final String[] protocols) {
            throw Assert.unsupported();
        }

        public SSLSession getSession() {
            return null;
        }

        public void beginHandshake() throws SSLException {
            throw ElytronMessages.log.sslClosed();
        }

        public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
            return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
        }

        public void setUseClientMode(final boolean mode) {
            throw Assert.unsupported();
        }

        public boolean getUseClientMode() {
            return false;
        }

        public void setNeedClientAuth(final boolean need) {
        }

        public boolean getNeedClientAuth() {
            return false;
        }

        public void setWantClientAuth(final boolean want) {
        }

        public boolean getWantClientAuth() {
            return false;
        }

        public void setEnableSessionCreation(final boolean flag) {
        }

        public boolean getEnableSessionCreation() {
            return false;
        }
    };
}


text:
import { defineMessages } from 'react-intl'

defineMessages({
  a: {
    id: 'b.a',
    description: 'a message of the b module',
    defaultMessage: 'the a message',
  },
  b: {
    id: 'b.b',
    description: 'b message of the b module',
    defaultMessage: 'the b message',
  },
  c: {
    id: 'b.c',
    description: 'c message of the b module',
    defaultMessage: 'the c message',
  },
})


text:
#ifndef NRFX_TWI_H__
#define NRFX_TWI_H__

#include <nrfx.h>
#include <hal/nrf_twi.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup nrfx_twi TWI driver
 * @{
 * @ingroup nrf_twi
 * @brief   TWI peripheral driver.
 */

/**
 * @brief Structure for the TWI master driver instance.
 */
typedef struct
{
    NRF_TWI_Type * p_twi;        ///< Pointer to a structure with TWI registers.
    uint8_t        drv_inst_idx; ///< Driver instance index.
} nrfx_twi_t;

/**
 * @brief Macro for creating a TWI master driver instance.
 */
#define NRFX_TWI_INSTANCE(id)                               \
{                                                           \
    .p_twi        = NRFX_CONCAT_2(NRF_TWI, id),             \
    .drv_inst_idx = NRFX_CONCAT_3(NRFX_TWI, id, _INST_IDX), \
}

enum {
#if NRFX_CHECK(NRFX_TWI0_ENABLED)
    NRFX_TWI0_INST_IDX,
#endif
#if NRFX_CHECK(NRFX_TWI1_ENABLED)
    NRFX_TWI1_INST_IDX,
#endif
    NRFX_TWI_ENABLED_COUNT
};

/**
 * @brief Structure for the TWI master driver instance configuration.
 */
typedef struct
{
    uint32_t            scl;                 ///< SCL pin number.
    uint32_t            sda;                 ///< SDA pin number.
    nrf_twi_frequency_t frequency;           ///< TWI frequency.
    uint8_t             interrupt_priority;  ///< Interrupt priority.
    bool                hold_bus_uninit;     ///< Hold pull up state on gpio pins after uninit.
} nrfx_twi_config_t;

/**
 * @brief TWI master driver instance default configuration.
 */
#define NRFX_TWI_DEFAULT_CONFIG                                                   \
{                                                                                \
    .frequency          = (nrf_twi_frequency_t)NRFX_TWI_DEFAULT_CONFIG_FREQUENCY, \
    .scl                = 31,                                                     \
    .sda                = 31,                                                     \
    .interrupt_priority = NRFX_TWI_DEFAULT_CONFIG_IRQ_PRIORITY,                   \
    .hold_bus_uninit    = NRFX_TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT,                \
}

#define NRFX_TWI_FLAG_NO_XFER_EVT_HANDLER (1UL << 2) /**< Interrupt after each transfer is suppressed, and the event handler is not called. */
#define NRFX_TWI_FLAG_TX_NO_STOP          (1UL << 5) /**< Flag indicating that the TX transfer will not end with a stop condition. */

/**
 * @brief TWI master driver event types.
 */
typedef enum
{
    NRFX_TWI_EVT_DONE,         ///< Transfer completed event.
    NRFX_TWI_EVT_ADDRESS_NACK, ///< Error event: NACK received after sending the address.
    NRFX_TWI_EVT_DATA_NACK     ///< Error event: NACK received after sending a data byte.
} nrfx_twi_evt_type_t;

/**
 * @brief TWI master driver transfer types.
 */
typedef enum
{
    NRFX_TWI_XFER_TX,          ///< TX transfer.
    NRFX_TWI_XFER_RX,          ///< RX transfer.
    NRFX_TWI_XFER_TXRX,        ///< TX transfer followed by RX transfer with repeated start.
    NRFX_TWI_XFER_TXTX         ///< TX transfer followed by TX transfer with repeated start.
} nrfx_twi_xfer_type_t;

/**
 * @brief Structure for a TWI transfer descriptor.
 */
typedef struct
{
    nrfx_twi_xfer_type_t    type;             ///< Type of transfer.
    uint8_t                 address;          ///< Slave address.
    size_t                  primary_length;   ///< Number of bytes transferred.
    size_t                  secondary_length; ///< Number of bytes transferred.
    uint8_t *               p_primary_buf;    ///< Pointer to transferred data.
    uint8_t *               p_secondary_buf;  ///< Pointer to transferred data.
} nrfx_twi_xfer_desc_t;

/**@brief Macro for setting the TX transfer descriptor. */
#define NRFX_TWI_XFER_DESC_TX(addr, p_data, length) \
    {                                               \
        .type = NRFX_TWI_XFER_TX,                   \
        .address = addr,                            \
        .primary_length = length,                   \
        .p_primary_buf  = p_data,                   \
    }

/**@brief Macro for setting the RX transfer descriptor. */
#define NRFX_TWI_XFER_DESC_RX(addr, p_data, length) \
    {                                               \
        .type = NRFX_TWI_XFER_RX,                   \
        .address = addr,                            \
        .primary_length = length,                   \
        .p_primary_buf  = p_data,                   \
    }

/**@brief Macro for setting the TXRX transfer descriptor. */
#define NRFX_TWI_XFER_DESC_TXRX(addr, p_tx, tx_len, p_rx, rx_len)   \
    {                                                               \
        .type = NRFX_TWI_XFER_TXRX,                                 \
        .address = addr,                                            \
        .primary_length   = tx_len,                                 \
        .secondary_length = rx_len,                                 \
        .p_primary_buf    = p_tx,                                   \
        .p_secondary_buf  = p_rx,                                   \
    }

/**@brief Macro for setting the TXTX transfer descriptor. */
#define NRFX_TWI_XFER_DESC_TXTX(addr, p_tx, tx_len, p_tx2, tx_len2) \
    {                                                               \
        .type = NRFX_TWI_XFER_TXTX,                                 \
        .address = addr,                                            \
        .primary_length   = tx_len,                                 \
        .secondary_length = tx_len2,                                \
        .p_primary_buf    = p_tx,                                   \
        .p_secondary_buf  = p_tx2,                                  \
    }

/**
 * @brief Structure for a TWI event.
 */
typedef struct
{
    nrfx_twi_evt_type_t  type;      ///< Event type.
    nrfx_twi_xfer_desc_t xfer_desc; ///< Transfer details.
} nrfx_twi_evt_t;

/**
 * @brief TWI event handler prototype.
 */
typedef void (* nrfx_twi_evt_handler_t)(nrfx_twi_evt_t const * p_event,
                                        void *                 p_context);

/**
 * @brief Function for initializing the TWI driver instance.
 *
 * @param[in] p_instance      Pointer to the driver instance structure.
 * @param[in] p_config        Pointer to the structure with initial configuration.
 * @param[in] event_handler   Event handler provided by the user. If NULL, blocking mode is enabled.
 * @param[in] p_context       Context passed to event handler.
 *
 * @retval NRFX_SUCCESS             If initialization was successful.
 * @retval NRFX_ERROR_INVALID_STATE If the driver is in invalid state.
 * @retval NRFX_ERROR_BUSY          If some other peripheral with the same
 *                                  instance ID is already in use. This is
 *                                  possible only if @ref nrfx_prs module
 *                                  is enabled.
 */
nrfx_err_t nrfx_twi_init(nrfx_twi_t const *        p_instance,
                         nrfx_twi_config_t const * p_config,
                         nrfx_twi_evt_handler_t    event_handler,
                         void *                    p_context);

/**
 * @brief Function for uninitializing the TWI instance.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 */
void nrfx_twi_uninit(nrfx_twi_t const * p_instance);

/**
 * @brief Function for enabling the TWI instance.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 */
void nrfx_twi_enable(nrfx_twi_t const * p_instance);

/**
 * @brief Function for disabling the TWI instance.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 */
void nrfx_twi_disable(nrfx_twi_t const * p_instance);

/**
 * @brief Function for sending data to a TWI slave.
 *
 * The transmission will be stopped when an error occurs. If a transfer is ongoing,
 * the function returns the error code @ref NRFX_ERROR_BUSY.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 * @param[in] address    Address of a specific slave device (only 7 LSB).
 * @param[in] p_data     Pointer to a transmit buffer.
 * @param[in] length     Number of bytes to send.
 * @param[in] no_stop    If set, the stop condition is not generated on the bus
 *                       after the transfer has completed successfully (allowing
 *                       for a repeated start in the next transfer).
 *
 * @retval NRFX_SUCCESS                  If the procedure was successful.
 * @retval NRFX_ERROR_BUSY               If the driver is not ready for a new transfer.
 * @retval NRFX_ERROR_INTERNAL           If an error was detected by hardware.
 * @retval NRFX_ERROR_DRV_TWI_ERR_ANACK  If NACK received after sending the address in polling mode.
 * @retval NRFX_ERROR_DRV_TWI_ERR_DNACK  If NACK received after sending a data byte in polling mode.
 */
nrfx_err_t nrfx_twi_tx(nrfx_twi_t const * p_instance,
                       uint8_t            address,
                       uint8_t const *    p_data,
                       size_t             length,
                       bool               no_stop);

/**
 * @brief Function for reading data from a TWI slave.
 *
 * The transmission will be stopped when an error occurs. If a transfer is ongoing,
 * the function returns the error code @ref NRFX_ERROR_BUSY.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 * @param[in] address    Address of a specific slave device (only 7 LSB).
 * @param[in] p_data     Pointer to a receive buffer.
 * @param[in] length     Number of bytes to be received.
 *
 * @retval NRFX_SUCCESS                    If the procedure was successful.
 * @retval NRFX_ERROR_BUSY                 If the driver is not ready for a new transfer.
 * @retval NRFX_ERROR_INTERNAL             If an error was detected by hardware.
 * @retval NRFX_ERROR_DRV_TWI_ERR_OVERRUN  If the unread data was replaced by new data
 * @retval NRFX_ERROR_DRV_TWI_ERR_ANACK    If NACK received after sending the address in polling mode.
 * @retval NRFX_ERROR_DRV_TWI_ERR_DNACK    If NACK received after sending a data byte in polling mode.
 */
nrfx_err_t nrfx_twi_rx(nrfx_twi_t const * p_instance,
                       uint8_t            address,
                       uint8_t *          p_data,
                       size_t             length);

/**
 * @brief Function for preparing a TWI transfer.
 *
 * The following transfer types can be configured (@ref nrfx_twi_xfer_desc_t::type):
 * - @ref NRFX_TWI_XFER_TXRX: Write operation followed by a read operation (without STOP condition in between).
 * - @ref NRFX_TWI_XFER_TXTX: Write operation followed by a write operation (without STOP condition in between).
 * - @ref NRFX_TWI_XFER_TX:   Write operation (with or without STOP condition).
 * - @ref NRFX_TWI_XFER_RX:   Read operation  (with STOP condition).
 *
 * @note TXRX and TXTX transfers are supported only in non-blocking mode.
 *
 * Additional options are provided using the flags parameter:
 * - @ref NRFX_TWI_FLAG_NO_XFER_EVT_HANDLER: No user event handler after transfer completion. In most cases, this also means no interrupt at the end of the transfer.
 * - @ref NRFX_TWI_FLAG_TX_NO_STOP: No stop condition after TX transfer.
 *
 * @note
 * Some flag combinations are invalid:
 * - @ref NRFX_TWI_FLAG_TX_NO_STOP with @ref nrfx_twi_xfer_desc_t::type different than @ref NRFX_TWI_XFER_TX
 *
 * @param[in] p_instance        Pointer to the driver instance structure.
 * @param[in] p_xfer_desc       Pointer to the transfer descriptor.
 * @param[in] flags             Transfer options (0 for default settings).
 *
 * @retval NRFX_SUCCESS                    If the procedure was successful.
 * @retval NRFX_ERROR_BUSY                 If the driver is not ready for a new transfer.
 * @retval NRFX_ERROR_NOT_SUPPORTED        If the provided parameters are not supported.
 * @retval NRFX_ERROR_INTERNAL             If an error was detected by hardware.
 * @retval NRFX_ERROR_DRV_TWI_ERR_OVERRUN  If the unread data was replaced by new data (TXRX and RX)
 * @retval NRFX_ERROR_DRV_TWI_ERR_ANACK    If NACK received after sending the address.
 * @retval NRFX_ERROR_DRV_TWI_ERR_DNACK    If NACK received after sending a data byte.
 */
nrfx_err_t nrfx_twi_xfer(nrfx_twi_t           const * p_instance,
                         nrfx_twi_xfer_desc_t const * p_xfer_desc,
                         uint32_t                     flags);

/**
 * @brief Function for checking the TWI driver state.
 *
 * @param[in] p_instance TWI instance.
 *
 * @retval true  If the TWI driver is currently busy performing a transfer.
 * @retval false If the TWI driver is ready for a new transfer.
 */
bool nrfx_twi_is_busy(nrfx_twi_t const * p_instance);

/**
 * @brief Function for getting the transferred data count.
 *
 * @param[in] p_instance Pointer to the driver instance structure.
 *
 * @return     Data count.
 */
size_t nrfx_twi_data_count_get(nrfx_twi_t const * const p_instance);

/**
 * @brief Function for returning the address of a STOPPED TWI event.
 *
 * A STOPPED event can be used to detect the end of a transfer if the @ref NRFX_TWI_FLAG_NO_XFER_EVT_HANDLER
 * option is used.
 *
 * @param[in]  p_instance Pointer to the driver instance structure.
 *
 * @return     STOPPED event address.
 */
uint32_t nrfx_twi_stopped_event_get(nrfx_twi_t const * p_instance);

void nrfx_twi_0_irq_handler(void);
void nrfx_twi_1_irq_handler(void);

/** @} */

#ifdef __cplusplus
}
#endif

#endif // NRFX_TWI_H__


text:
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/codegangsta/cli"
	"github.com/golang/glog"

	"tower.pro/renderer/command"
)

var version string

func main() {
	defer glog.Flush()
	flag.CommandLine.Parse([]string{"-logtostderr"})

	app := cli.NewApp()
	app.Name = "renderer"
	app.Usage = "components compiler, renderer and command line tool with web interface"
	app.Version = version
	app.HideVersion = true
	app.Commands = command.Commands
	app.Flags = []cli.Flag{
		cli.IntFlag{
			Name:   "v",
			Usage:  "verbosity (disables logs if < 0)",
			EnvVar: "VERBOSITY",
		},
	}
	app.Before = glogFlags
	app.Run(os.Args)
}

func glogFlags(c *cli.Context) error {
	v := c.Int("v")
	if v < 0 {
		flag.Set("logtostderr", "false")
	} else if v > 0 {
		flag.Set("v", fmt.Sprintf("%d", v))
	}
	return nil
}