std::string Generator::interchangeTypeStr(const CXType &type) const
{
    switch (type.kind) {
    case CXType_Int:
        return "int";
    case CXType_Float:
        return "float";
    case CXType_Double:
        return "double";
    case CXType_Bool:
        return "bool";
    case CXType_Unexposed:
        if (stringize(type) == "CCPointer<CCArray>")
            return "CCArray *";
        else if (stringize(type) == "CCPointer<CCDictionary>")
            return "CCDictionary *";
        else if (stringize(type) == "string")
            return "const std::string &";
        else
            reportWarning("Unexposed type: " + stringize(type));
        break;
    default:
        reportWarning("Unhandled type: " + stringize(type));
        break;
    }
    return "";
}
Esempio n. 2
0
int main() {
    boost::tuple<char, int, char, int> decim('-', 10, 'e', 5);
    assert(stringize(decim) == "-10e5");

    std::pair<short, std::string> value_and_type(270, "Kelvin");
    assert(stringize(value_and_type) == "270Kelvin");
}
void HeaderGenerator::declareRecord()
{
    std::vector<CXCursor> fields;
    std::string baseClass = "ISerializableRecord";
    visitCursorChildren(context().self, [this, &fields, &baseClass]() -> CXChildVisitResult {
        if (context().self.kind == CXCursor_FieldDecl)
            fields.push_back(context().self);
        if (context().self.kind == CXCursor_CXXBaseSpecifier) {
            baseClass = context().selfName;
            const size_t spaceIndex = baseClass.rfind(" ");
            if (spaceIndex != std::string::npos)
                baseClass = baseClass.substr(spaceIndex + 1);
        }
        return CXChildVisit_Continue;
    });

    // make: constructor, save, load
    out() << "struct " << context().selfName << " : public " << baseClass << "\n";
    out() << "{\n";
    out() << "    " << context().selfName << "();\n";
    out() << "    void saveDataTo(CCDictionary *dict) const;\n";
    out() << "    void loadDataFrom(CCDictionary *dict);\n";

    // make: getters
    for (auto cursor : fields) {
        auto printGetter = [this, cursor] (const std::string &typeName) -> void {
            out() << "    " << typeName << " " << getterNameStr(cursor, typeName) << "() const;\n";
        };
        printGetter(interchangeTypeStr(clang_getCursorType(cursor)));
    }
    out() << "\n";

    // make: setters
    for (auto cursor : fields) {
        auto printSetter = [this, cursor] (const std::string &typeName) -> void {
            std::string cname = stringize(cursor);
            if (!cname.empty())
                cname[0] = toupper(cname[0]);
            cname = "set" + cname;
            out() << "    void " << cname << "(" << typeName << ");\n";
        };
        printSetter(interchangeTypeStr(clang_getCursorType(cursor)));
    }
    out() << "\n";

    // make: members
    out() << "protected:\n";
    for (auto cursor : fields) {
        auto type = clang_getCursorType(cursor);
        std::string tname = stringize(type);
        if (tname == "string") // HACK: for std::string
            tname = "std::string";
        out() << "    " << tname << " " << memberNameStr(cursor, type) << ";\n";
    }

    // finish
    out() << "};\n\n";

    // make: getters
}
void Generator::pushContext(const CXCursor &self, const CXCursor &parent) const
{
    m_stack.push_back(m_context);

    m_context.self = self;
    m_context.selfName = stringize(self);
    m_context.parent = parent;
    m_context.parentName = stringize(parent);
}
std::string Generator::getterNameStr(const CXCursor &cursor, const std::string &typeStr)
{
    if (typeStr == "bool") {
        return stringize(cursor);
    }
    std::string cname = stringize(cursor);
    if (!cname.empty())
        cname[0] = toupper(cname[0]);
    cname = "get" + cname;
    return cname;
}
Esempio n. 6
0
int main() {
    tuple_example();
    fusion_tuple_example();
    stringize_tup2_example();

    boost::fusion::vector<cat, int, std::string> tup1(cat(), 0, "_0");
    boost::tuple<cat, int, std::string> tup2(cat(), 0, "_0");
    std::pair<cat, cat> cats;
    boost::array<cat, 10> many_cats;

    std::cout << stringize(tup1) << '\n' 
        << stringize(tup2) << '\n'
        << stringize(cats) << '\n'
        << stringize(many_cats) << '\n';
}
Esempio n. 7
0
/*-----------------------------------------------------------------------------------*/
void
config_read(char *filename)
{
  int file;

  file = cfs_open(filename, CFS_READ);
  if(file < 0) {
    log_message(filename, ": File not found");
    error_exit();
  }

  if(cfs_read(file, &config, sizeof(config)) < sizeof(uip_ipaddr_t) * 4
                                             + sizeof(uint16_t)) {
    log_message(filename, ": No config file");
    error_exit();
  }

  cfs_close(file);

  log_message("IP Address:  ", ipaddrtoa(&config.hostaddr, uip_buf));
  log_message("Subnet Mask: ", ipaddrtoa(&config.netmask, uip_buf));
  log_message("Def. Router: ", ipaddrtoa(&config.draddr, uip_buf));
  log_message("DNS Server:  ", ipaddrtoa(&config.resolvaddr, uip_buf));

#ifdef STATIC_DRIVER
  #define _stringize(arg) #arg
  #define  stringize(arg) _stringize(arg)
#if WITH_SLIP
  log_message("SLIP Driver: ", stringize(STATIC_DRIVER));
#else /* WITH_SLIP */
  log_message("Eth. Driver: ", stringize(STATIC_DRIVER));
#endif /* WITH_SLIP */
  #undef  _stringize
  #undef   stringize
#else /* STATIC_DRIVER */
  log_message("Eth. Driver: ", config.ethernet.name);
#endif /* STATIC_DRIVER */
#if !WITH_SLIP
  log_message("Driver Port: $", utoa(config.ethernet.addr, uip_buf, 16));
#endif /* !WITH_SLIP */

  uip_sethostaddr(&config.hostaddr);
  uip_setnetmask(&config.netmask);
  uip_setdraddr(&config.draddr);
#if WITH_DNS
  uip_nameserver_update(&config.resolvaddr, UIP_NAMESERVER_INFINITE_LIFETIME);
#endif /* WITH_DNS */
}
Esempio n. 8
0
spark::JSONValue spark::JSONValue::parse(char *json, size_t size) {
    detail::JSONDataPtr d(new(std::nothrow) detail::JSONData);
    if (!d) {
        return JSONValue();
    }
    size_t tokenCount = 0;
    if (!tokenize(json, size, &d->tokens, &tokenCount)) {
        return JSONValue();
    }
    const jsmntok_t *t = d->tokens; // Root token
    if (t->type == JSMN_PRIMITIVE) {
        // RFC 7159 allows JSON document to consist of a single primitive value, such as a number.
        // In this case, original data is copied to a larger buffer to ensure room for term. null
        // character (see stringize() method)
        d->json = new(std::nothrow) char[size + 1];
        if (!d->json) {
            return JSONValue();
        }
        memcpy(d->json, json, size);
        d->freeJson = true; // Set ownership flag
    } else {
        d->json = json;
    }
    if (!stringize(d->tokens, tokenCount, d->json)) {
        return JSONValue();
    }
    return JSONValue(t, d);
}
/**
 * CXSourceLocation - 4-byte number, we need to call clang_getSpellingLocation
 * or clang_getExpansionLocation to retrieve line, column and file name.
 */
void Generator::getLocationParts(const CXSourceLocation &location, std::string &fileName, unsigned &line, unsigned &column) const
{
    CXFile file;
    unsigned offset = 0;
    clang_getSpellingLocation(location, &file, &line, &column, &offset);
    (void)offset;

    fileName = stringize(clang_getFileName(file));
}
Esempio n. 10
0
 void stringize_object::test<1>()
 {
     ensure_equals(stringize(c),    "c");
     ensure_equals(stringize(s),    "17");
     ensure_equals(stringize(i),    "34");
     ensure_equals(stringize(l),    "68");
     ensure_equals(stringize(f),    "3.14159");
     ensure_equals(stringize(d),    "3.14159");
     ensure_equals(stringize(abc),  "abc def");
     ensure_equals(stringize(llsd), "{'abc':'abc def','d':r3.14159,'i':i34}");
 }
Esempio n. 11
0
/*-----------------------------------------------------------------------------------*/
struct ethernet_config * CC_FASTCALL
config_read(char *filename)
{
  static struct {
    uip_ipaddr_t           hostaddr;
    uip_ipaddr_t           netmask;
    uip_ipaddr_t           draddr;
    uip_ipaddr_t           resolvaddr;
    struct ethernet_config ethernetcfg;
  } config;
  int file;

  file = cfs_open(filename, CFS_READ);
  if(file < 0) {
    log_message(filename, ": File not found");
    error_exit();
  }

  if(cfs_read(file, &config, sizeof(config)) < sizeof(config)
					     - sizeof(config.ethernetcfg.name)) {
    log_message(filename, ": No config file");
    error_exit();
  }

  cfs_close(file);

  log_message("IP Address:  ",  ipaddrtoa(&config.hostaddr, uip_buf));
  log_message("Subnet Mask: ",  ipaddrtoa(&config.netmask, uip_buf));
  log_message("Def. Router: ",  ipaddrtoa(&config.draddr, uip_buf));
  log_message("DNS Server:  ",  ipaddrtoa(&config.resolvaddr, uip_buf));

#ifndef ETHERNET
  log_message("Eth. Driver: ",  config.ethernetcfg.name);
#else /* !ETHERNET */
  #define _stringize(arg) #arg
  #define  stringize(arg) _stringize(arg)
  log_message("Eth. Driver: ",  stringize(ETHERNET));
  #undef  _stringize
  #undef   stringize
#endif /* !ETHERNET */
  log_message("Driver Port: $", utoa(config.ethernetcfg.addr, uip_buf, 16));

  uip_sethostaddr(&config.hostaddr);
  uip_setnetmask(&config.netmask);
  uip_setdraddr(&config.draddr);
#if WITH_DNS
  resolv_conf(&config.resolvaddr);
#endif /* WITH_DNS */

  return &config.ethernetcfg;
}
Esempio n. 12
0
File: cpp.c Progetto: rui314/8cc-old
/*
 * Substitutes parameters in macro definition body with actual arguments.
 */
static List *subst(CppContext *ctx, Macro *macro, List *args, List *hideset) {
    List *r = make_list();
    for (int i = 0; i < LIST_LEN(macro->body); i++) {
        bool islast = (i == LIST_LEN(macro->body) - 1);
        Token *t0 = LIST_REF(macro->body, i);
        Token *t1 = islast ? NULL : LIST_REF(macro->body, i + 1);
        bool t0_param = t0->toktype == TOKTYPE_MACRO_PARAM;
        bool t1_param = !islast && t1->toktype == TOKTYPE_MACRO_PARAM;

        if (is_punct(t0, '#') && t1_param) {
            list_push(r, stringize(t0, LIST_REF(args, t1->val.i)));
            i++;
            continue;
        }
        if (is_punct(t0, KEYWORD_TWOSHARPS) && t1_param) {
            List *arg = LIST_REF(args, t1->val.i);
            if (!LIST_IS_EMPTY(arg)) {
                glue_push(r, (Token *)LIST_REF(arg, 0));
                List *tmp = make_list();
                for (int i = 1; i < LIST_LEN(arg); i++)
                    list_push(tmp, LIST_REF(arg, i));
                list_append(r, expand_all(ctx, tmp));
            }
            i++;
            continue;
        }
        if (is_punct(t0, KEYWORD_TWOSHARPS) && !islast) {
            hideset = t1->hideset; // wrong?
            glue_push(r, t1);
            i++;
            continue;
        }
        if (t0_param && !islast && is_punct(t1, KEYWORD_TWOSHARPS)) {
            hideset = t1->hideset; // wrong?
            List *arg = LIST_REF(args, t0->val.i);
            if (LIST_IS_EMPTY(arg))
                i++;
            else
                list_append(r, arg);
            continue;
        }
        if (t0_param) {
            List *arg = LIST_REF(args, t0->val.i);
            list_append(r, expand_all(ctx, arg));
            continue;
        }
        list_push(r, t0);
    }
    return add_hide_set(r, hideset);
}
Esempio n. 13
0
int 
phGetVersion()
{
  if (!ph_reqsock)
    {
      /* phInit was not called yet */
      static const char versn[] = stringize(PHAPI_VERSION);
      char *subv = strstr(versn, ".");
      int v,s,r;

      v = atoi(versn);
      s = atoi(subv+1);
      r = atoi(strstr(subv+1, "."));

      return (v << 16) | (s << 8) | r;
    }

  return ph_rpc("VER");

}  
Esempio n. 14
0
spark::JSONValue spark::JSONValue::parseCopy(const char *json, size_t size) {
    detail::JSONDataPtr d(new(std::nothrow) detail::JSONData);
    if (!d) {
        return JSONValue();
    }
    size_t tokenCount = 0;
    if (!tokenize(json, size, &d->tokens, &tokenCount)) {
        return JSONValue();
    }
    d->json = new(std::nothrow) char[size + 1];
    if (!d->json) {
        return JSONValue();
    }
    memcpy(d->json, json, size); // TODO: Copy only token data
    d->freeJson = true;
    if (!stringize(d->tokens, tokenCount, d->json)) {
        return JSONValue();
    }
    return JSONValue(d->tokens, d);
}
Esempio n. 15
0
int
parse_vir (int fd)
{
	struct vir vir;

	readall (fd, &vir, sizeof(vir));

	cond_print ("Version Identification Record:\n");
	cond_print ("  File ID: 0x%08x (\"%c%c%c%c\")\n", vir.file_id,
				((char *)&vir.file_id)[3],
				((char *)&vir.file_id)[2],
				((char *)&vir.file_id)[1],
				((char *)&vir.file_id)[0]);
	cond_print ("  Version: %u.%02u\n", vir.version / 100, vir.version % 100);

	if (vir.file_id != FILE_ID) {
		cond_print ("Error:  VIR file ID is not correct.  Should be " stringize(FILE_ID) " (\"KpGr\")\n");
		valid = 0;
	}

	return 1;
}
Esempio n. 16
0
File: xmp.cpp Progetto: mor-vfx/oiio
static void
gather_xmp_attribs (const ImageSpec &spec,
                    std::vector<std::pair<int,std::string> > &list)
{
    // Loop over all params...
    for (ImageIOParameterList::const_iterator p = spec.extra_attribs.begin();
         p != spec.extra_attribs.end();  ++p) {
        // For this param, see if there's a table entry with a matching
        // name, where the xmp name is in the right category.
        for (int i = 0;  xmptag[i].xmpname;  ++i) {
            if (! Strutil::iequals (p->name().c_str(), xmptag[i].oiioname))
                continue;   // Name doesn't match
            if (xmptag[i].special & Suppress) {
                break;   // Purposely suppressing
            }
            std::string s = stringize (p,xmptag[i]);
            if (s.size()) {
                list.push_back (std::pair<int,std::string>(i, s));
                //std::cerr << "  " << xmptag[i].xmpname << " = " << s << "\n"; 
            }
        }
    }
}
Esempio n. 17
0
static void
gather_xmp_attribs(const ImageSpec& spec,
                   std::vector<std::pair<const XMPtag*, std::string>>& list)
{
    // Loop over all params...
    for (ParamValueList::const_iterator p = spec.extra_attribs.begin();
         p != spec.extra_attribs.end(); ++p) {
        // For this param, see if there's a table entry with a matching
        // name, where the xmp name is in the right category.
        const XMPtag* tag = xmp_tagmap_ref().find(p->name());
        if (tag) {
            if (!Strutil::iequals(p->name(), tag->oiioname))
                continue;  // Name doesn't match
            if (tag->special & Suppress) {
                break;  // Purposely suppressing
            }
            std::string s = stringize(p, *tag);
            if (s.size()) {
                list.emplace_back(tag, s);
                //std::cerr << "  " << tag->xmpname << " = " << s << "\n";
            }
        }
    }
}
Esempio n. 18
0
  {"GFORTRAN_UNBUFFERED_ALL", 0, &options.all_unbuffered, init_boolean,
   show_boolean,
   "If TRUE, all output is unbuffered.  This will slow down large writes "
   "but can be\nuseful for forcing data to be displayed immediately.", 0},

  {"GFORTRAN_SHOW_LOCUS", 1, &options.locus, init_boolean, show_boolean,
   "If TRUE, print filename and line number where runtime errors happen.", 0},

  {"GFORTRAN_OPTIONAL_PLUS", 0, &options.optional_plus, init_boolean, show_boolean,
   "Print optional plus signs in numbers where permitted.  Default FALSE.", 0},

  {"GFORTRAN_DEFAULT_RECL", DEFAULT_RECL, &options.default_recl,
   init_unsigned_integer, show_integer,
   "Default maximum record length for sequential files.  Most useful for\n"
   "adjusting line length of preconnected units.  Default "
   stringize (DEFAULT_RECL), 0},

  {"GFORTRAN_LIST_SEPARATOR", 0, NULL, init_sep, show_sep,
   "Separator to use when writing list output.  May contain any number of "
   "spaces\nand at most one comma.  Default is a single space.", 0},

  /* Memory related controls */

  {"GFORTRAN_MEM_INIT", 0, NULL, init_mem, show_mem,
   "How to initialize allocated memory.  Default value is NONE for no "
   "initialization\n(faster), NAN for a Not-a-Number with the mantissa "
   "0x40f95 or a custom\nhexadecimal value", 0},

  {"GFORTRAN_MEM_CHECK", 0, &options.mem_check, init_boolean, show_boolean,
   "Whether memory still allocated will be reported when the program ends.",
   0},
Esempio n. 19
0
/*
 * Substitute the arguments args appearing in the input sequence is
 * Result is created in the output sequence os and finally has the specified
 * hide set added to it, before getting returned.
 */
static PtokenSequence
subst(const Macro &m, dequePtoken is, const mapArgval &args, HideSet hs, bool skip_defined, const Macro *caller)
{
	PtokenSequence os;	// output sequence

	while (!is.empty()) {
		if (DP())
			cout << "subst: is=" << is << " os=" << os << endl;
		const Ptoken head(is.front());
		is.pop_front();		// is is now the tail
		dequePtoken::iterator ti, ti2;
		mapArgval::const_iterator ai;
		switch (head.get_code()) {
		case '#':		// Stringizing operator
			ti = find_nonspace(is.begin(), is.end());
			if (ti != is.end() && (ai = find_formal_argument(args, *ti)) != args.end()) {
				is.erase(is.begin(), ++ti);
				os.push_back(stringize(ai->second));
				continue;
			}
			break;
		case CPP_CONCAT:
			ti = find_nonspace(is.begin(), is.end());
			if (ti != is.end()) {
				if ((ai = find_formal_argument(args, *ti)) != args.end()) {
					is.erase(is.begin(), ++ti);
					if (ai->second.size() != 0)	// Only if actuals can be empty
						os = glue(os, ai->second);
				} else {
					PtokenSequence t(ti, ti + 1);
					is.erase(is.begin(), ++ti);
					os = glue(os, t);
				}
				continue;
			}
			break;
		default:
			ti = find_nonspace(is.begin(), is.end());
			if (ti != is.end() && ti->get_code() == CPP_CONCAT) {
				/*
				 * Implement the following gcc extension:
				 *  "`##' before a
				 *   rest argument that is empty discards the preceding sequence of
				 *   non-whitespace characters from the macro definition.  (If another macro
				 *   argument precedes, none of it is discarded.)"
				 * Otherwise, break to process a non-formal argument in the default way
				 */
				if ((ai = find_formal_argument(args, head)) == args.end()) {
					if (m.get_is_vararg()) {
						ti2 = find_nonspace(ti + 1, is.end());
						if (ti2 != is.end() && (ai = find_formal_argument(args, *ti2)) != args.end() && ai->second.size() == 0) {
							// All conditions satisfied; discard elements:
							// <non-formal> <##> <empty-formal>
							is.erase(is.begin(), ++ti2);
							continue;
						}
					}
					break;	// Non-formal arguments don't deserve special treatment
				}
				// Paste but not expand LHS, RHS
				if (ai->second.size() == 0) {	// Only if actuals can be empty
					is.erase(is.begin(), ++ti);	// Erase including ##
					ti = find_nonspace(is.begin(), is.end());
					if (ti != is.end() && (ai = find_formal_argument(args, *ti)) != args.end()) {
						is.erase(is.begin(), ++ti);	// Erase the ## RHS
						PtokenSequence actual(ai->second);
						os.splice(os.end(), actual);
					}
				} else {
					is.erase(is.begin(), ti);	// Erase up to ##
					PtokenSequence actual(ai->second);
					os.splice(os.end(), actual);
				}
				continue;
			}
			if ((ai = find_formal_argument(args, head)) == args.end())
				break;
			// Othewise expand head
			PtokenSequence expanded(macro_expand(ai->second, false, skip_defined, caller));
			os.splice(os.end(), expanded);
			continue;
		}
		os.push_back(head);
	}
	return (hsadd(hs, os));
}
Esempio n. 20
0
OWPL_RESULT
owplInit
(
	const int asyncCallbackMode,
	short udpPort,
	short tcpPort,
	short tlsPort,
	const char* szBindToAddr,
	const int bUserSequentialPorts
)
{
	int return_code;
	short useUdp = (udpPort == -1 ? 0 : 1);
	short useTcp = (tcpPort == -1 ? 0 : 1);
	short useTls = (tlsPort == -1 ? 0 : 1);
	const char* ptime;

	return_code = owplAdapterInitialize();
	if (return_code != 0)
	{
		owplLogError("owplAdapterInitialize failed");
		return OWPL_RESULT_FAILURE;
	}
	return_code = owplAdapterNortelInitialize("nortel");
	if (return_code != 0)
	{
		owplLogError("owplAdapterNortelInitialize failed");
		return OWPL_RESULT_FAILURE;
	}

	phcb = (phCallbacks_t * ) malloc(sizeof(phCallbacks_t));
	memset(phcb, 0, sizeof(phCallbacks_t));

	phcfg.asyncmode = asyncCallbackMode;

	return_code = owplInitOwsl(useUdp, useTcp, useTls);
	if (return_code != 0)
	{
		owplLogError("owplInitOwsl failed");
		return OWPL_RESULT_FAILURE;
	}

	osip_trace_initialize_func(OSIP_INFO3, owplOsipLogFunction);

	return_code = eXosip_init(0, 0, udpPort, tcpPort, tlsPort);
	if (return_code != 0)
	{
		owplLogError("eXosip_init failed");
		return OWPL_RESULT_FAILURE;
	}

	{

		const char version[] = stringize(VOXOXVERSION);//VOXOX - CJC - 2009.06.27 
		// VOXOX CHANGE by ASV 06-27-2009: modified the code to be compatible with GCC
		char ua[50] = "VoxOx "; // We need to define he size to make sure strcat has enough space to copy version in ua
		strcat(ua, version);//VOXOX - CJC - 2009.06.27 
		// VOXOX CHANGE by ASV - end
		eXosip_set_user_agent(ua);
	}

	ph_avcodec_init();
	ph_calls_init();

#ifdef FORCE_VAD
/* HACK for test */
#ifdef EMBED
	phcfg.vad = VAD_VALID_MASK | (500 & VAD_THRESHOLD_MASK);
#else
	phcfg.vad = VAD_VALID_MASK | (1000 & VAD_THRESHOLD_MASK);
#endif
#endif

#ifdef FORCE_CNG
  /* HACK for test */
  phcfg.cng = 1;
#endif

	ph_media_init(phcfg.plugin_path);

	ph_vlines_init();

	ph_payloads_init();

	if (!phcfg.audio_dev || phcfg.audio_dev[0] == '\0')
	{
		// Set default audio device if no one has been set before
		owplAudioSetConfigString(0);
	}
#if 0	
	ptime = getenv("EXOSIP_FORCE_PTIME");
	if (!ptime || !*ptime)
	{
		putenv("EXOSIP_FORCE_PTIME=20");
	}
#endif	
	/* register callbacks? */
	eXosip_set_mode(EVENT_MODE);

	if (!phcfg.asyncmode)
	{
		phWaitTimeout = 1;
	}
	else 
	{
		phWaitTimeout = 500;
	}

	if (phcfg.asyncmode)
	{
		osip_thread_create(20000, ph_api_thread, 0);
	}

	pthread_mutex_init(&ph_media_stop_mutex, NULL);

	phIsInitialized = 1;

	owplLogDebug("owplInit finished");

	return OWPL_RESULT_SUCCESS;
}
Esempio n. 21
0
#include "../Common/RSAHelper.inl"

#include "../simpleini/SimpleIni.h"

const char HELP_STRING[] =
	"Usage: server [OPTION]...\n"
	"Run the Smarter Lock server\n"
	"\n"
	"Options:\n"
	"\t--help               Show this help\n"
	"\t--nogui              No OpenCV WebCam window\n"
	"\n"
	"Default:\n"
	"gui,\n"
	"port=" stringize(SERVER_DEFAULT_PORT) "\n"
	"#threads=" stringize(SERVER_DEFAULT_NUM_THREADS) "\n"
	"width=" stringize(CAM_DEFAULT_WIDTH) "\n"
	"height=" stringize(CAM_DEFAULT_HEIGHT) "\n"
	"unlock-pin=" GPIO_DEFAULT_UNLOCK "\n"
	"wait=" stringize(CAM_WAIT) "\n"
	"rsa=" SAFETY_DEFAULT_RSA_FILE "\n"
	"passwd=" SAFETY_DEFAULT_PASSWD "\n"
	"apn_host=" APN_DEFAULT_HOST "\n"
	"apn_port=" stringize(APN_DEFAULT_PORT) "\n"
	"apn_rsa=" APN_DEFAULT_RSA_FILE "\n"
	"qr_expire=" stringize(MISC_DEFAULT_QR_EXP) "\n"
	;

void cleanup() {
	printf("Doing cleanups...\n");
Esempio n. 22
0
int main(int argc, const char * argv[]) {
	CSimpleIniA ini;
	
	ini.SetUnicode();
	if (ini.LoadFile("config.ini") == SI_FILE) {
		std::cout<< KWARN "Warning:" <<KREST << " Cannot load config.ini. Default setting is used.\n\n";
	}

	bool gui = true;
	
	uint16_t port = atoi(ini.GetValue("server", "port", stringize(SERVER_DEFAULT_PORT)));
	uint32_t numThreads = atoi(ini.GetValue("server", "threads", stringize(SERVER_DEFAULT_NUM_THREADS)));
	
	int width = atoi(ini.GetValue("camera", "width", stringize(CAM_DEFAULT_WIDTH)));
	int height = atoi(ini.GetValue("camera", "height", stringize(CAM_DEFAULT_HEIGHT)));
	uint32_t wait = atoi(ini.GetValue("camera", "wait", stringize(CAM_WAIT)));
	int dev = atoi(ini.GetValue("camera", "device", stringize(CAM_DEV)));
	
	const char* unlockPin = ini.GetValue("gpio", "unlock", GPIO_DEFAULT_UNLOCK);
	const char* errorPin = ini.GetValue("gpio", "error", GPIO_DEFAULT_ERROR);
	
	const char* rsapath = ini.GetValue("safety", "pem", SAFETY_DEFAULT_RSA_FILE);
	const char* passwd = ini.GetValue("safety", "password", SAFETY_DEFAULT_PASSWD);
	
	uint32_t qrexp = atoi(ini.GetValue("misc", "qrexpire", stringize(MISC_DEFAULT_QR_EXP)));
	
	for (int i = 1; i < argc; i++) {
		const char* arg = argv[i];
		
		if (strcmp(arg, "--help") == 0) {
			printf("%s", HELP_STRING);
			exit(0);
		} else if (strcmp(arg, "--nogui") == 0) {
			gui = false;
		} else {
			std::cerr<<KERR <<"Error:" << KREST << "unknown argument \""<<arg<<'"'<<std::endl;
			exit(2);
		}
	}
	
	ServerThreads::qrexp = qrexp;
	ServerThreads::port = port;
	ServerThreads::numThreads = numThreads;
	ServerThreads::gpioUnlock = unlockPin;
	ServerThreads::gpioError = errorPin;
	ServerThreads::rsaFile = rsapath;

	if (signal(SIGINT, sigHandler) == SIG_ERR)
		std::cerr<<"Can't catch SIGINT\n";
	
	pthread_t serverThreadId;
	pthread_create(&serverThreadId, nullptr, ServerThreads::startServer, nullptr);
	
	const char* apnRsaFile = ini.GetValue("apn", "pem", APN_DEFAULT_RSA_FILE);
	
	APNClient::DefaultClient.host = ini.GetValue("apn", "host", APN_DEFAULT_HOST);
	APNClient::DefaultClient.port = atoi(ini.GetValue("apn", "port", stringize(APN_DEFAULT_PORT)));
	APNClient::DefaultClient.rsa = rsaFromFile(apnRsaFile, true);
	
	REPL::cleanupFn = cleanup;
	REPL::password = passwd;
	pthread_t replThreadId;
	pthread_create(&replThreadId, nullptr, REPL::startLoop, nullptr);
    
    pthread_t btThreadId;
    pthread_create(&btThreadId, nullptr, BluetoothThread::startLoop, nullptr);
	
	CameraLoop::loop(dev, width, height, gui, wait);
	
    return 1;
}
std::string Generator::stringize(const CXType &type, const std::string &varName, bool makeConstReference) const
{
    std::string result;

    if (makeConstReference) {
        switch (type.kind) {
        case CXType_LValueReference:
        case CXType_RValueReference:
        case CXType_Pointer:
        case CXType_Enum:
        case CXType_Bool:
        case CXType_Char_S:
        case CXType_Char_U:
        case CXType_Char16:
        case CXType_Int:
        case CXType_Long:
        case CXType_LongLong:
        case CXType_Float:
        case CXType_Double:
        case CXType_LongDouble:
            makeConstReference = false;
            break;
        default:
            break;
        }
    }

    if (makeConstReference || clang_isConstQualifiedType(type))
        result += "const ";

    switch (type.kind) {
    case CXType_Void:
        result += "void";
        if (!varName.empty())
            result += ' ';
        break;
    case CXType_Bool:
        result += "bool";
        if (!varName.empty())
            result += ' ';
        break;

    case CXType_Int:
        result += "int";
        if (!varName.empty())
            result += ' ';
        break;

    case CXType_Float:
        result += "float";
        if (!varName.empty())
            result += ' ';
        break;

    case CXType_Double:
        result += "double";
        if (!varName.empty())
            result += ' ';
        break;

    case CXType_Pointer: {
        CXType pointee = clang_getPointeeType(type);
        result += stringize(pointee);
        result += " *";
    }
        break;

    case CXType_LValueReference: {
        CXType pointee = clang_getPointeeType(type);
        result += stringize(pointee);
    }
        break;
    case CXType_Record:
    case CXType_Enum: {
        result += stringize(clang_getTypeDeclaration(type));
        if (!varName.empty())
            result += ' ';
    }
        break;

    case CXType_Unexposed:
        result += stringize(clang_getCursorDisplayName(clang_getTypeDeclaration(type)));
        if (!varName.empty())
            result += ' ';
        break;
    case CXType_Overload:
        result += "<CXType_Overload>";
        reportWarning("stringize: CXType_Overload not handled: " + stringize(clang_getCursorDisplayName(clang_getTypeDeclaration(type))));
        break;
    case CXType_Dependent:
        result += "<CXType_Dependent>";
        reportWarning("stringize: CXType_Dependent not handled: " + stringize(clang_getCursorDisplayName(clang_getTypeDeclaration(type))));
        break;
    case CXType_Invalid:
        result += "<CXType_Invalid>";
        reportWarning("stringize: CXType_Invalid not handled: " + stringize(clang_getCursorDisplayName(clang_getTypeDeclaration(type))));
        break;
    default:
        result += "<other CXTypeKind>";
        reportWarning("stringize: such CXTypeKind not handled: " + stringize(clang_getCursorDisplayName(clang_getTypeDeclaration(type))));
        break;
    }

    if (makeConstReference) {
        result += "&";
    }

    result += varName;
    return result;
}
std::string Generator::stringize(const CXCursor &cursor) const
{
    return stringize(clang_getCursorSpelling(cursor));
}
std::string Generator::memberNameStr(const CXCursor &cursor, const CXType &type)
{
    if (type.kind == CXType_Bool)
        return "m_" + stringize(cursor);
    return stringize(cursor);
}
Esempio n. 26
0
template<> std::string toString<longdouble>(const longdouble& f) {
	char buf[128];
	snprintf(buf,sizeof(buf),"%." stringize(LDBL_DIG) "Lf",f);
	return (const char*)buf;
}
Esempio n. 27
0
std::string LLViewerRegion::getDescription() const
{
    return stringize(*this);
}
Esempio n. 28
0
void LLPluginProcessParent::idle(void)
{
	bool idle_again;

	do
	{
		// process queued messages
		mIncomingQueueMutex.lock();
		while(!mIncomingQueue.empty())
		{
			LLPluginMessage message = mIncomingQueue.front();
			mIncomingQueue.pop();
			mIncomingQueueMutex.unlock();
				
			receiveMessage(message);
			
			mIncomingQueueMutex.lock();
		}

		mIncomingQueueMutex.unlock();
		
		// Give time to network processing
		if(mMessagePipe)
		{
			// Drain any queued outgoing messages
			mMessagePipe->pumpOutput();
			
			// Only do input processing here if this instance isn't in a pollset.
			if(!mPolledInput)
			{
				mMessagePipe->pumpInput();
			}
		}
		
		if(mState <= STATE_RUNNING)
		{
			if(APR_STATUS_IS_EOF(mSocketError))
			{
				// Plugin socket was closed.  This covers both normal plugin termination and plugin crashes.
				errorState();
			}
			else if(mSocketError != APR_SUCCESS)
			{
				// The socket is in an error state -- the plugin is gone.
				LL_WARNS("Plugin") << "Socket hit an error state (" << mSocketError << ")" << LL_ENDL;
				errorState();
			}
		}	
		
		// If a state needs to go directly to another state (as a performance enhancement), it can set idle_again to true after calling setState().
		// USE THIS CAREFULLY, since it can starve other code.  Specifically make sure there's no way to get into a closed cycle and never return.
		// When in doubt, don't do it.
		idle_again = false;
		switch(mState)
		{
			case STATE_UNINITIALIZED:
			break;

			case STATE_INITIALIZED:
			{
	
				apr_status_t status = APR_SUCCESS;
				apr_sockaddr_t* addr = NULL;
				mListenSocket = LLSocket::create(gAPRPoolp, LLSocket::STREAM_TCP);
				mBoundPort = 0;
				
				// This code is based on parts of LLSocket::create() in lliosocket.cpp.
				
				status = apr_sockaddr_info_get(
					&addr,
					"127.0.0.1",
					APR_INET,
					0,	// port 0 = ephemeral ("find me a port")
					0,
					gAPRPoolp);
					
				if(ll_apr_warn_status(status))
				{
					killSockets();
					errorState();
					break;
				}

				// This allows us to reuse the address on quick down/up. This is unlikely to create problems.
				ll_apr_warn_status(apr_socket_opt_set(mListenSocket->getSocket(), APR_SO_REUSEADDR, 1));
				
				status = apr_socket_bind(mListenSocket->getSocket(), addr);
				if(ll_apr_warn_status(status))
				{
					killSockets();
					errorState();
					break;
				}

				// Get the actual port the socket was bound to
				{
					apr_sockaddr_t* bound_addr = NULL;
					if(ll_apr_warn_status(apr_socket_addr_get(&bound_addr, APR_LOCAL, mListenSocket->getSocket())))
					{
						killSockets();
						errorState();
						break;
					}
					mBoundPort = bound_addr->port;	

					if(mBoundPort == 0)
					{
						LL_WARNS("Plugin") << "Bound port number unknown, bailing out." << LL_ENDL;
						
						killSockets();
						errorState();
						break;
					}
				}
				
				LL_DEBUGS("Plugin") << "Bound tcp socket to port: " << addr->port << LL_ENDL;

				// Make the listen socket non-blocking
				status = apr_socket_opt_set(mListenSocket->getSocket(), APR_SO_NONBLOCK, 1);
				if(ll_apr_warn_status(status))
				{
					killSockets();
					errorState();
					break;
				}

				apr_socket_timeout_set(mListenSocket->getSocket(), 0);
				if(ll_apr_warn_status(status))
				{
					killSockets();
					errorState();
					break;
				}
				
				// If it's a stream based socket, we need to tell the OS
				// to keep a queue of incoming connections for ACCEPT.
				status = apr_socket_listen(
					mListenSocket->getSocket(),
					10); // FIXME: Magic number for queue size
					
				if(ll_apr_warn_status(status))
				{
					killSockets();
					errorState();
					break;
				}
				
				// If we got here, we're listening.
				setState(STATE_LISTENING);
			}
			break;
			
			case STATE_LISTENING:
			{
				// Launch the plugin process.
				
				// Only argument to the launcher is the port number we're listening on
				mProcessParams.args.add(stringize(mBoundPort));
				if (! (mProcess = LLProcess::create(mProcessParams)))
				{
					errorState();
				}
				else
				{
					if(mDebug)
					{
						#if LL_DARWIN
						// If we're set to debug, start up a gdb instance in a new terminal window and have it attach to the plugin process and continue.
						
						// The command we're constructing would look like this on the command line:
						// osascript -e 'tell application "Terminal"' -e 'set win to do script "gdb -pid 12345"' -e 'do script "continue" in win' -e 'end tell'

						LLProcess::Params params;
						params.executable = "/usr/bin/osascript";
						params.args.add("-e");
						params.args.add("tell application \"Terminal\"");
						params.args.add("-e");
						params.args.add(STRINGIZE("set win to do script \"gdb -pid "
												  << mProcess->getProcessID() << "\""));
						params.args.add("-e");
						params.args.add("do script \"continue\" in win");
						params.args.add("-e");
						params.args.add("end tell");
						mDebugger = LLProcess::create(params);

						#endif
					}
					
					// This will allow us to time out if the process never starts.
					mHeartbeat.start();
					mHeartbeat.setTimerExpirySec(mPluginLaunchTimeout);
					setState(STATE_LAUNCHED);
				}
			}
			break;

			case STATE_LAUNCHED:
				// waiting for the plugin to connect
				if(pluginLockedUpOrQuit())
				{
					errorState();
				}
				else
				{
					// Check for the incoming connection.
					if(accept())
					{
						// Stop listening on the server port
						mListenSocket.reset();
						setState(STATE_CONNECTED);
					}
				}
			break;
			
			case STATE_CONNECTED:
				// waiting for hello message from the plugin

				if(pluginLockedUpOrQuit())
				{
					errorState();
				}
			break;

			case STATE_HELLO:
				LL_DEBUGS("Plugin") << "received hello message" << LL_ENDL;
				
				// Send the message to load the plugin
				{
					LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_INTERNAL, "load_plugin");
					message.setValue("file", mPluginFile);
					message.setValue("dir", mPluginDir);
					sendMessage(message);
				}

				setState(STATE_LOADING);
			break;
			
			case STATE_LOADING:
				// The load_plugin_response message will kick us from here into STATE_RUNNING
				if(pluginLockedUpOrQuit())
				{
					errorState();
				}
			break;
			
			case STATE_RUNNING:
				if(pluginLockedUpOrQuit())
				{
					errorState();
				}
			break;
			
			case STATE_EXITING:
				if (! LLProcess::isRunning(mProcess))
				{
					setState(STATE_CLEANUP);
				}
				else if(pluginLockedUp())
				{
					LL_WARNS("Plugin") << "timeout in exiting state, bailing out" << LL_ENDL;
					errorState();
				}
			break;

			case STATE_LAUNCH_FAILURE:
				if(mOwner != NULL)
				{
					mOwner->pluginLaunchFailed();
				}
				setState(STATE_CLEANUP);
			break;

			case STATE_ERROR:
				if(mOwner != NULL)
				{
					mOwner->pluginDied();
				}
				setState(STATE_CLEANUP);
			break;
			
			case STATE_CLEANUP:
				LLProcess::kill(mProcess);
				killSockets();
				setState(STATE_DONE);
			break;
			
			
			case STATE_DONE:
				// just sit here.
			break;
			
		}
	
	} while (idle_again);
}
Esempio n. 29
0
template<> std::string toString<float128>(const float128& f) {
	char buf[128];
	quadmath_snprintf(buf,sizeof(buf),"%." stringize(FLT128_DIG) "Qf",f);
	return (const char*)buf;
}
void SourceGenerator::defineRecord()
{
    std::vector<CXCursor> fields;
    std::string base;
    visitCursorChildren(context().self, [this, &fields, &base]() -> CXChildVisitResult {
        if (context().self.kind == CXCursor_FieldDecl)
            fields.push_back(context().self);
        if (context().self.kind == CXCursor_CXXBaseSpecifier && context().selfName != "struct ISerializableRecord") {
            base = context().selfName;
            const std::string prefix = "struct ";
            if (base.size() >= prefix.size() && base.substr(0, prefix.size()) == prefix)
                base = base.substr(prefix.size());
        }
        return CXChildVisit_Continue;
    });

    // make: constructor
    out() << context().selfName << "::" << context().selfName << "()\n";
    bool isFirstInitializer = true;
    auto printFunc = [&isFirstInitializer, this](const CXCursor &cursor, const CXType &type, const std::string &initializer) {
        out() << "    " << (isFirstInitializer ? ":" : ",") << " ";
        out() << memberNameStr(cursor, type) << "(" << initializer << ")\n";
        isFirstInitializer = false;
    };

    for (auto cursor : fields) {
        auto type = clang_getCursorType(cursor);
        switch (type.kind) {
        case CXType_Pointer:
            printFunc(cursor, type, "NULL");
            break;
        case CXType_Double:
        case CXType_Float:
            printFunc(cursor, type, "0.0");
            break;
        case CXType_Int:
        case CXType_UInt:
        case CXType_Short:
        case CXType_UShort:
        case CXType_Char_S:
        case CXType_Char_U:
            printFunc(cursor, type, "0");
            break;
        case CXType_Bool:
            printFunc(cursor, type, "false");
            break;
        case CXType_Unexposed:
            if (stringize(type) == "CCPointer<CCArray>")
                printFunc(cursor, type, "CCArray::create()");
            else if (stringize(type) == "CCPointer<CCDictionary>")
                printFunc(cursor, type, "CCDictionary::create()");
            else if (stringize(type) != "string" && stringize(type) != "queue<int>")
                reportWarning("Unexposed type (constructor): " + stringize(type));
            break;
        default:
            break;
        }
    }
    out() << "{\n"
          << "}\n"
          << "\n";

    // make: void save(CCDictionary *dict) const
    out() << "void " << context().selfName << "::saveDataTo(CCDictionary *dict) const\n"
          << "{\n";
    if (!base.empty())
        out() << "    " << base << "::saveDataTo(dict);\n";
    out() << "    CCDictionaryBuilder h(dict);\n";
    for (auto cursor : fields) {
        auto type = clang_getCursorType(cursor);
        auto printSave = [this, cursor, type] (const std::string &typeNameCapitalized) -> void {
            out() << "    h.set"
                  << typeNameCapitalized
                  << "("<< memberNameStr(cursor, type) << ", \"" << stringize(cursor) << "\");\n";
        };

        switch (type.kind) {
        case CXType_Int:
            printSave("Int");
            break;
        case CXType_Float:
        case CXType_Double:
            printSave("Double");
            break;
        case CXType_Bool:
            printSave("Bool");
            break;
        case CXType_Unexposed:
            if (stringize(type) == "CCPointer<CCArray>")
                printSave("Array");
            else if (stringize(type) == "CCPointer<CCDictionary>")
                printSave("Dictionary");
            else if (stringize(type) == "string")
                printSave("String");
            else
                reportWarning("Unexposed type (save): " + stringize(type));
            break;
        default:
            reportWarning("Unhandled type (save): " + stringize(type));
            break;
        }
    }
    out() << "}\n"
          << "\n";

    // make: void load(CCDictionary *dict)
    out() << "void " << context().selfName << "::loadDataFrom(CCDictionary *dict)\n"
          << "{\n";
    if (!base.empty())
        out() << "    " << base << "::loadDataFrom(dict);\n";
    out() << "    DictionaryReader h(dict);\n";
    for (auto cursor : fields) {
        auto type = clang_getCursorType(cursor);
        auto printLoad = [this, cursor, type] (const std::string &typeNameCapitalized) -> void {
            out() << "    " << memberNameStr(cursor, type) << " = h.get"
                  << typeNameCapitalized
                  << "(\"" << stringize(cursor) << "\");\n";
        };

        switch (type.kind) {
        case CXType_Int:
            printLoad("Int");
            break;
        case CXType_Float:
        case CXType_Double:
            printLoad("Double");
            break;
        case CXType_Bool:
            printLoad("Bool");
            break;
        case CXType_Unexposed:
            if (stringize(type) == "CCPointer<CCArray>")
                printLoad("Array");
            else if (stringize(type) == "CCPointer<CCDictionary>")
                printLoad("Dictionary");
            else if (stringize(type) == "string")
                printLoad("String");
            else
                reportWarning("Unexposed type (load): " + stringize(type));
            break;
        default:
            reportWarning("Unhandled type (load): " + stringize(type));
            break;
        }
    }
    out() << "}\n"
          << "\n";

    // make: getters
    for (auto cursor : fields) {
        auto printGetter = [this, cursor] (const CXType &type) -> void {
            const std::string typeName = interchangeTypeStr(type);
            out() << typeName << " " << context().selfName << "::" << getterNameStr(cursor, typeName) << "() const\n"
                  << "{\n"
                  << "    return " << memberNameStr(cursor, type) << ";\n"
                  << "}\n"
                  << "\n";
        };
        printGetter(clang_getCursorType(cursor));
    }
    out() << "\n";

    // make: setters
    for (auto cursor : fields) {
        auto printSetter = [this, cursor] (const CXType &type) -> void {
            std::string cname = stringize(cursor);
            if (!cname.empty())
                cname[0] = toupper(cname[0]);
            cname = "set" + cname;
            out() << "void " << context().selfName << "::" << cname << "(" << interchangeTypeStr(type) << " var)\n"
                  << "{\n"
                  << "    " << memberNameStr(cursor, type) << " = var;\n"
                  << "}\n"
                  << "\n";
        };
        printSetter(clang_getCursorType(cursor));
    }
    out() << "\n";
}