Exemplo n.º 1
0
/*
 * term_init: does all terminal initialization... reads termcap info, sets
 * the terminal to CBREAK, no ECHO mode.   Chooses the best of the terminal
 * attributes to use ..  for the version of this function that is called for
 * wserv, we set the termial to RAW, no ECHO, so that all the signals are
 * ignored.. fixes quite a few problems...  -phone, jan 1993..
 */
void
term_init(void)
{
#ifndef	STTY_ONLY
	char	bp[TGETENT_BUFSIZ],
		*term,
		*ptr;

	if ((term = getenv("TERM")) == NULL)
	{
		fprintf(stderr, "irc: No TERM variable set!\n");
		fprintf(stderr,"irc: You may still run irc by using the -d switch\n");
		exit(1);
	}
	if (tgetent(bp, term) < 1)
	{
		fprintf(stderr, "irc: No termcap entry for %s.\n", term);
		fprintf(stderr,"irc: You may still run irc by using the -d switch\n");
		exit(1);
	}

	if ((co = tgetnum("co")) == -1)
		co = 80;
	if ((li = tgetnum("li")) == -1)
		li = 24;
	ptr = termcap;

	/*
	 * Thanks to Max Bell ([email protected]) for info about TVI
	 * terminals and the sg terminal capability
	 */
	SG = tgetnum("sg");
	CM = tgetstr("cm", &ptr);
	CL = tgetstr("cl", &ptr);
	if ((CM == NULL) ||
	    (CL == NULL))
	{
		fprintf(stderr, "This terminal does not have the necessary "
				 "capabilities to run IRCII\n"
				 "in full screen mode. You may still run "
				 "irc by using the -d switch\n");
		exit(1);
	}
	if ((CR = tgetstr("cr", &ptr)) == NULL)
		CR = "\r";
	if ((NL = tgetstr("nl", &ptr)) == NULL)
		NL = "\n";

	if ((CE = tgetstr("ce", &ptr)) != NULL)
		term_clear_to_eol_func = term_CE_clear_to_eol;
	else
		term_clear_to_eol_func = term_null_function;

	TE = tgetstr("te", &ptr);
	if (!use_termcap_enterexit() && TE && (TI = tgetstr("ti", &ptr)) != NULL )
		tputs_x(TI);
	else
		TE = TI = NULL;

	/* if ((ND = tgetstr("nd", &ptr)) || (ND = tgetstr("kr", &ptr))) */
	if ((ND = tgetstr("nd", &ptr)) != NULL)
		term_cursor_right_func = term_ND_cursor_right;
	else
		term_cursor_right_func = term_null_function;

	/* if ((LE = tgetstr("le", &ptr)) || (LE = tgetstr("kl", &ptr))) */
	if ((LE = tgetstr("le", &ptr)) != NULL)
		term_cursor_left_func = term_LE_cursor_left;
	else if (tgetflag("bs"))
		term_cursor_left_func = term_BS_cursor_left;
	else
		term_cursor_left_func = term_null_function;

	SF = tgetstr("sf", &ptr);
	SR = tgetstr("sr", &ptr);

	if ((CS = tgetstr("cs", &ptr)) != NULL)
		term_scroll_func = term_CS_scroll;
	else if ((AL = tgetstr("AL", &ptr)) && (DL = tgetstr("DL", &ptr)))
		term_scroll_func = term_param_ALDL_scroll;
	else if ((AL = tgetstr("al", &ptr)) && (DL = tgetstr("dl", &ptr)))
		term_scroll_func = term_ALDL_scroll;
	else
		term_scroll_func = (int (*)(int, int, int)) term_null_function;

	if ((IC = tgetstr("ic", &ptr)) != NULL)
		term_insert_func = term_IC_insert;
	else
	{
		if ((IM = tgetstr("im", &ptr)) && (EI = tgetstr("ei", &ptr)))
			term_insert_func = term_IMEI_insert;
		else
			term_insert_func = (int (*)(u_int)) term_null_function;
	}

	if ((DC = tgetstr("dc", &ptr)) != NULL)
		term_delete_func = term_DC_delete;
	else
		term_delete_func = term_null_function;

	SO = tgetstr("so", &ptr);
	SE = tgetstr("se", &ptr);
	if ((SO == NULL) || (SE == NULL))
	{
		SO = CP(empty_string());
		SE = CP(empty_string());
	}
	US = tgetstr("us", &ptr);
	UE = tgetstr("ue", &ptr);
	if ((US == NULL) || (UE == NULL))
	{
		US = CP(empty_string());
		UE = CP(empty_string());
	}
	MD = tgetstr("md", &ptr);
	ME = tgetstr("me", &ptr);
	if ((MD == NULL) || (ME == NULL))
	{
		MD = CP(empty_string());
		ME = CP(empty_string());
	}
	if ((BL = tgetstr("bl", &ptr)) == NULL)
		BL = "\007";
#endif /* STTY_ONLY */

	if (getenv("IRC_DEBUG")|| (tty_des = open("/dev/tty", O_RDWR, 0)) == -1)
		tty_des = 0;

	tcgetattr(tty_des, &oldb);

	newb = oldb;
	newb.c_lflag &= ~(ICANON | ECHO);	/* set equivalent of
						 * CBREAK and no ECHO
						 */
	newb.c_cc[VMIN] = 1;	/* read() satified after 1 char */
	newb.c_cc[VTIME] = 0;	/* No timer */

#ifndef _POSIX_VDISABLE
# define _POSIX_VDISABLE 0
#endif

	newb.c_cc[VQUIT] = _POSIX_VDISABLE;
#ifdef VDISCARD
	newb.c_cc[VDISCARD] = _POSIX_VDISABLE;
#endif
#ifdef VDSUSP
	newb.c_cc[VDSUSP] = _POSIX_VDISABLE;
#endif
#ifdef VSUSP
	newb.c_cc[VSUSP] = _POSIX_VDISABLE;
#endif

#ifndef STTY_ONLY
	if (!use_flow_control())
		newb.c_iflag &= ~IXON;	/* No XON/XOFF */
#endif /* STTY_ONLY */

	tcsetattr(tty_des, TCSADRAIN, &newb);
}
Exemplo n.º 2
0
Variant HHVM_FUNCTION(wordwrap, const String& str, int64_t linewidth /* = 75 */,
                      const String& brk /* = s_nl */, bool cut /* = false */) {
    const char* brkstr = brk.data();
    size_t textlen = str.size();
    size_t brklen = brk.size();

    if (textlen == 0) {
        return empty_string();
    }
    if (brklen == 0) {
        raise_warning("Break string cannot be empty");
        return false;
    }
    if (linewidth == 0 && cut) {
        raise_warning("Can't force cut when width is zero");
        return false;
    }
    size_t w = linewidth >= 0 ? linewidth : 0;

    // If the string's length is less than or equal to the specified
    // width, there's nothing to do and we can just return the string.
    if (textlen <= w) return str;

    // Special case for a single-character break as it needs no
    // additional storage space
    if (brklen == 1 && !cut) {
        auto new_sd = StringData::Make(str.get(), CopyString);
        new_sd->invalidateHash();
        auto ret = Variant::attach(new_sd);
        char* newtext = new_sd->mutableData();
        auto bc = brkstr[0];
        size_t current = 0, laststart = 0, lastspace = 0;
        for (; current < textlen; current++) {
            if (newtext[current] == bc) {
                laststart = lastspace = current + 1;
            } else if (newtext[current] == ' ') {
                if (current - laststart >= w) {
                    newtext[current] = bc;
                    laststart = current + 1;
                }
                lastspace = current;
            } else if (current - laststart >= w && laststart != lastspace) {
                newtext[lastspace] = bc;
                laststart = lastspace + 1;
            }
        }
        return ret;
    }

    // Multiple character line break or forced cut

    // Estimate how big the output string will be. It's okay if this estimate
    // is wrong as we will grow or shrink as needed. The goals here are two-
    // fold: (1) avoid the need to grow or shrink in the common case, and
    // (2) for extreme cases where it's hard to make an accurate estimate
    // (ex. when w is very small or brk is very large) we should be careful
    // to avoid making huge over-estimations.
    StringBuffer strbuf(
        textlen +
        textlen / (std::max<size_t>(w, 16) - 8) * std::min<size_t>(brklen, 8));

    const char* text = str.data();
    size_t current = 0, laststart = 0, lastspace = 0;
    for (; current < textlen; current++) {
        // when we hit an existing break, copy to new buffer, and
        // fix up laststart and lastspace
        if (text[current] == brkstr[0] && current + brklen < textlen &&
                !strncmp(text + current, brkstr, brklen)) {
            strbuf.append(text + laststart, current - laststart + brklen);
            current += brklen - 1;
            laststart = lastspace = current + 1;
        }
        // if it is a space, check if it is at the line boundary,
        // copy and insert a break, or just keep track of it
        else if (text[current] == ' ') {
            if (current - laststart >= w) {
                strbuf.append(text + laststart, current - laststart);
                strbuf.append(brkstr, brklen);
                laststart = current + 1;
            }
            lastspace = current;
        }
        // if we are cutting, and we've accumulated enough
        // characters, and we haven't see a space for this line,
        // copy and insert a break.
        else if (current - laststart >= w && cut && laststart >= lastspace) {
            strbuf.append(text + laststart, current - laststart);
            strbuf.append(brkstr, brklen);
            laststart = lastspace = current;
        }
        // if the current word puts us over width w, copy back up
        // until the last space, insert a break, and move up the
        // laststart
        else if (current - laststart >= w && laststart < lastspace) {
            strbuf.append(text + laststart, lastspace - laststart);
            strbuf.append(brkstr, brklen);
            laststart = lastspace = lastspace + 1;
        }
    }
    // copy over any stragglers
    if (laststart != current) {
        strbuf.append(text + laststart, current - laststart);
    }

    auto s = strbuf.detach();

    // if it's not possible to reduce the output string's capacity by more
    // than 25%, then we can just return the string as is.
    size_t estShrinkCap =
        MemoryManager::estimateCap(sizeof(StringData) + s.size() + 1);
    if (estShrinkCap * 4 >= (size_t)s.capacity() * 3) {
        return s;
    }
    // reallocate into a smaller buffer so that we don't waste memory
    return Variant::attach(StringData::Make(s.get(), CopyString));
}
Exemplo n.º 3
0
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("SString_Test"));

  {

    /* Set #1 */
    ACE_CString s0 ("hello");
    ACE_CString s1 ("hello");
    ACE_CString s2 ("world");
    ACE_CString s3 ("ll");
    ACE_CString s4 ("ello");
    ACE_CString s5 = s1 + " " + s2;

    char single_character = 'z';
    ACE_CString single_character_string (single_character);

    ACE_CString empty_string;
    ACE_CString zero_size_string (s1.c_str (), 0, 0, 1);

    if (ACE_CString::npos == 0)
      ACE_ERROR((LM_ERROR,"Set #1: npos is incorrect.\n"));

    // Not equal comparisons. Error if they are equal
    if (s1 == s2){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1 == s5){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Equal comparisons. Error if they are not equal
    if (s1 != s1){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1 != s0){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Substring match. Error if they are not equal
    if (s1.strstr (s2) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.strstr (s3) != 2){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s3.strstr (s1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.strstr (s4) != 1){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Substring creation. Error if they are not equal
    if (s1.substring (0) != s1){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.substring (1) != s4){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.substring (2, 2) != s3){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.substring (0, 0) != empty_string){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.substring (4, 10).length () != 1){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Forward search. Error if they are not equal
    if (s1.find (s3) != 2){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s3.find (s1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.find (s3, 2) != 2){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s3.find (s1, 1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.find (s2) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.find ('o') != 4){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Reverse search. Error if they are not equal
    if (s1.rfind ('l') != 3){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    if (s1.rfind ('l', 3) != 2){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}

    // Assignment. Error if they are not equal
    ACE_CString s6;
    s6 = s0;
    if (s6 != s0){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    s6 = s4;
    if (s4 != s6){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
    s6 = s5;
    if (s6 != s5){ACE_ERROR((LM_ERROR,"Set #1:\n"));return 1;}
  }

  {
    /* Set #2 */
    ACE_CString s0 = "hello";
    ACE_CString s1 ("hello", 0, false);
    ACE_CString s2 ("world", 0, false);
    ACE_CString s3 ("ll", 0, false);
    ACE_CString s4 ("ello", 0, false);
    ACE_CString s5 = s1 + " " + s2;

    char single_character = 'z';
    ACE_CString single_character_string (single_character);

    ACE_CString empty_string (0, 0, false);
    ACE_CString zero_size_string (s1.c_str (), 0, 0, false);

    // Not equal comparisons. Error if they are equal
    if (s1 == s2){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1 == s5){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Equal comparisons. Error if they are not equal
    if (s1 != s1){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1 != s0){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Substring match. Error if they are not equal
    if (s1.strstr (s2) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.strstr (s3) != 2){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s3.strstr (s1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.strstr (s4) != 1){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Substring creation. Error if they are not equal
    if (s1.substring (0) != s1){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.substring (1) != s4){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.substring (2, 2) != s3){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.substring (0, 0) != empty_string){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Forward search. Error if they are not equal
    if (s1.find (s3) != 2){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s3.find (s1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.find (s3, 2) != 2){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s3.find (s1, 1) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.find (s2) != ACE_CString::npos){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.find ('o') != 4){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Reverse search. Error if they are not equal
    if (s1.rfind ('l') != 3){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    if (s1.rfind ('l', 3) != 2){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Assignment. Error if they are not equal
    ACE_CString s6;
    s6 = s0;
    if (s6 != s0){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    s6 = s4;
    if (s4 != s6){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
    s6 = s5;
    if (s6 != s5){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Clear. Error if they are not equal
    s0.clear();
    if (s0.length() != 0){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}

    // Rep. Error if they are not equal
    ACE_Auto_Basic_Array_Ptr<char> s (s1.rep ());
    if (ACE_OS::strlen (s.get ()) != s1.length ())
      {
        ACE_ERROR((LM_ERROR,"Auto_ptr s:\n"));
      };

    ACE_CString s7 (s.get ());
    if (s1 != s7){ACE_ERROR((LM_ERROR,"Set #2:\n"));return 1;}
  }

  {
    /* Set #3 */
    ACE_NS_WString s0 ("hello");
    ACE_NS_WString s1 ("hello");
    ACE_NS_WString s2 ("world");
    ACE_NS_WString s3 ("ll");
    ACE_NS_WString s4 ("ello");
    ACE_NS_WString s5 = s1 + " " + s2;
    ACE_NS_WString s6 = ("hella"); // Same length as s1, off by one char.

    ACE_WCHAR_T single_character = 'z';
    ACE_NS_WString single_character_string (single_character);

    ACE_NS_WString empty_string;
    ACE_NS_WString zero_size_string (s1.c_str (), 0, 0);

    // Not equal comparisons. Error if they are equal
    if (s1 == s2){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1 == s5){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1 == s6){ACE_ERROR((LM_ERROR,"Set #3: off-by-one failed\n"));return 1;}

    // Equal comparisons. Error if they are not equal
    if (s1 != s1){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1 != s0){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Substring match. Error if they are not equal
    if (s1.strstr (s2) != ACE_NS_WString::npos){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.strstr (s3) != 2){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s3.strstr (s1) != ACE_NS_WString::npos){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.strstr (s4) != 1){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Substring creation. Error if they are not equal
    if (s1.substring (0) != s1){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.substring (1) != s4){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.substring (2, 2) != s3){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.substring (0, 0) != empty_string){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Forward search. Error if they are not equal
    if (s1.find (s3) != 2){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s3.find (s1) != ACE_NS_WString::npos){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.find (s3, 2) != 2){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s3.find (s1, 1) != ACE_NS_WString::npos){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.find (s2) != ACE_NS_WString::npos){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.find ('o') != 4){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Reverse search. Error if they are not equal
    if (s1.rfind ('l') != 3){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    if (s1.rfind ('l', 3) != 2){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Assignment. Error if they are not equal
    ACE_NS_WString s7;
    s7 = s0;
    if (s7 != s0){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    s7 = s4;
    if (s4 != s7){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
    s7 = s5;
    if (s7 != s5){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}

    // Clear. Error if they are not equal
    s0.clear();
    if (s0.length() != 0){ACE_ERROR((LM_ERROR,"Set #3:\n"));return 1;}
  }

  {
    /* Set #4 */
    ACE_CString s1("dog");
    ACE_CString s2("d");

    if (s1 == s2){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if (!(s1 > s2)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if (s1 < s2){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    ACE_CString s3 ("dog");
    ACE_CString s4 ("dogbert");

    if (s3 == s4){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if (!(s3 < s4)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if (s3 > s4){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    ACE_CString s5 ("dogbert",3);
    ACE_CString s6 ("dogbert",5);

    if(s5 == s6){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(!(s5 < s6)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(s5 > s6){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    ACE_CString s7 ("dogbert",4);
    ACE_CString s8 ("dogbert",2);

    if(s7 == s8){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(!(s7 > s8)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(s7 < s8){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    ACE_CString s9 ("dogbert",3);
    ACE_CString s10 ("dogbert");

    if(s9 == s10){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(!(s9 < s10)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(s9 > s10){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    ACE_CString s11 ("dogbert",5);
    ACE_CString s12 ("dog");

    if(s11 == s12){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(!(s11 > s12)){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}
    if(s11 < s12){ACE_ERROR((LM_ERROR,"Set #4:\n"));return 1;}

    s11.fast_clear ();
    if (s11.length () != 0)
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("fast_clear didn't yield 0 length\n")));
  }

  {
    // Set 1 for ACE_SString, which is not tested
    ACE_SString sstr;

    const char *old = sstr.rep ();
    const char *str = "What_a_day_it_has_been";

    sstr.rep (const_cast<char *>(str));

    ACE_SString tmp =
      sstr.substring (2, 300);

    if (tmp.length () == 300)
      ACE_ERROR ((LM_ERROR, "SString substring\n"));

    // Constring an ACE_SString without a character pointer or from an
    // existing ACE_SString causes memory to be allocated that will not
    // be delete (apparently by design).
    ACE_Allocator::instance ()->free (const_cast<char *> (old));
    ACE_Allocator::instance ()->free (const_cast<char *> (tmp.rep ()));
  }

  int err = testConcatenation ();
  err += testIterator ();
  err += testConstIterator ();

  ACE_END_TEST;
  return err;
}
TEST(fxcrt, ByteStringOperatorEQ) {
  CFX_ByteString null_string;
  EXPECT_TRUE(null_string == null_string);

  CFX_ByteString empty_string("");
  EXPECT_TRUE(empty_string == empty_string);
  EXPECT_TRUE(empty_string == null_string);
  EXPECT_TRUE(null_string == empty_string);

  CFX_ByteString deleted_string("hello");
  deleted_string.Delete(0, 5);
  EXPECT_TRUE(deleted_string == deleted_string);
  EXPECT_TRUE(deleted_string == null_string);
  EXPECT_TRUE(deleted_string == empty_string);
  EXPECT_TRUE(null_string == deleted_string);
  EXPECT_TRUE(empty_string == deleted_string);

  CFX_ByteString byte_string("hello");
  EXPECT_TRUE(byte_string == byte_string);
  EXPECT_FALSE(byte_string == null_string);
  EXPECT_FALSE(byte_string == empty_string);
  EXPECT_FALSE(byte_string == deleted_string);
  EXPECT_FALSE(null_string == byte_string);
  EXPECT_FALSE(empty_string == byte_string);
  EXPECT_FALSE(deleted_string == byte_string);

  CFX_ByteString byte_string_same1("hello");
  EXPECT_TRUE(byte_string == byte_string_same1);
  EXPECT_TRUE(byte_string_same1 == byte_string);

  CFX_ByteString byte_string_same2(byte_string);
  EXPECT_TRUE(byte_string == byte_string_same2);
  EXPECT_TRUE(byte_string_same2 == byte_string);

  CFX_ByteString byte_string1("he");
  CFX_ByteString byte_string2("hellp");
  CFX_ByteString byte_string3("hellod");
  EXPECT_FALSE(byte_string == byte_string1);
  EXPECT_FALSE(byte_string == byte_string2);
  EXPECT_FALSE(byte_string == byte_string3);
  EXPECT_FALSE(byte_string1 == byte_string);
  EXPECT_FALSE(byte_string2 == byte_string);
  EXPECT_FALSE(byte_string3 == byte_string);

  CFX_ByteStringC null_string_c;
  CFX_ByteStringC empty_string_c("");
  EXPECT_TRUE(null_string == null_string_c);
  EXPECT_TRUE(null_string == empty_string_c);
  EXPECT_TRUE(empty_string == null_string_c);
  EXPECT_TRUE(empty_string == empty_string_c);
  EXPECT_TRUE(deleted_string == null_string_c);
  EXPECT_TRUE(deleted_string == empty_string_c);
  EXPECT_TRUE(null_string_c == null_string);
  EXPECT_TRUE(empty_string_c == null_string);
  EXPECT_TRUE(null_string_c == empty_string);
  EXPECT_TRUE(empty_string_c == empty_string);
  EXPECT_TRUE(null_string_c == deleted_string);
  EXPECT_TRUE(empty_string_c == deleted_string);

  CFX_ByteStringC byte_string_c_same1("hello");
  EXPECT_TRUE(byte_string == byte_string_c_same1);
  EXPECT_TRUE(byte_string_c_same1 == byte_string);

  CFX_ByteStringC byte_string_c1("he");
  CFX_ByteStringC byte_string_c2("hellp");
  CFX_ByteStringC byte_string_c3("hellod");
  EXPECT_FALSE(byte_string == byte_string_c1);
  EXPECT_FALSE(byte_string == byte_string_c2);
  EXPECT_FALSE(byte_string == byte_string_c3);
  EXPECT_FALSE(byte_string_c1 == byte_string);
  EXPECT_FALSE(byte_string_c2 == byte_string);
  EXPECT_FALSE(byte_string_c3 == byte_string);

  const char* c_null_string = nullptr;
  const char* c_empty_string = "";
  EXPECT_TRUE(null_string == c_null_string);
  EXPECT_TRUE(null_string == c_empty_string);
  EXPECT_TRUE(empty_string == c_null_string);
  EXPECT_TRUE(empty_string == c_empty_string);
  EXPECT_TRUE(deleted_string == c_null_string);
  EXPECT_TRUE(deleted_string == c_empty_string);
  EXPECT_TRUE(c_null_string == null_string);
  EXPECT_TRUE(c_empty_string == null_string);
  EXPECT_TRUE(c_null_string == empty_string);
  EXPECT_TRUE(c_empty_string == empty_string);
  EXPECT_TRUE(c_null_string == deleted_string);
  EXPECT_TRUE(c_empty_string == deleted_string);

  const char* c_string_same1 = "hello";
  EXPECT_TRUE(byte_string == c_string_same1);
  EXPECT_TRUE(c_string_same1 == byte_string);

  const char* c_string1 = "he";
  const char* c_string2 = "hellp";
  const char* c_string3 = "hellod";
  EXPECT_FALSE(byte_string == c_string1);
  EXPECT_FALSE(byte_string == c_string2);
  EXPECT_FALSE(byte_string == c_string3);
  EXPECT_FALSE(c_string1 == byte_string);
  EXPECT_FALSE(c_string2 == byte_string);
  EXPECT_FALSE(c_string3 == byte_string);
}
Exemplo n.º 5
0
int get_sources_list(Arb_connection *adm_connection, char *sqlquery,
   COM_SOURCE ***srclist)
{
   COM_SOURCE **src_table;

   EXT_CONTACTS con;

   EXT_CONTACTS_STATUS con_stat;

   int i;
   int j;
   int num_sources;
   int rowcount = 0;

   *srclist = NULL;

/*-------------------------------------------------------------------------+
 | Determine how many external contact sources there are to access.
 +------------------------------------------------------------------------*/

   arb_dbcmd(adm_connection,  "SELECT COUNT(*) ");
   arb_dbcmd(adm_connection,  "FROM EXT_CONTACTS, EXT_CONTACTS_STATUS ");
   arb_dbcmd(adm_connection,  "WHERE ");
   arb_dbcmd(adm_connection,  "   EXT_CONTACTS.ext_contact_id ");
   arb_dbcmd(adm_connection,  "      = EXT_CONTACTS_STATUS.ext_contact_id ");
   arb_dbfcmd(adm_connection, "AND (process_name IS NULL OR process_name='%s') ",
      arb_get_process_id());
   arb_dbfcmd(adm_connection, "AND active_dt <= %s ", arb_server_getdate());
   arb_dbfcmd(adm_connection, "AND (inactive_dt IS NULL OR %s < inactive_dt) ",
      arb_server_getdate());
   /*CBS00097804*/
   arb_dbfcmd(adm_connection, "AND (retry_count<retry_limit OR retry_limit IS NULL OR retry_limit=0) ");

   if (!empty_string(sqlquery))
      /*  --  CAMqa51929  --  */
      /*  --  replaced arb_dbfcmd call with following 3 arb_dbcmd calls  --  */
      /*  --  arb_dbfcmd(adm_connection," and (%s)", sqlquery);  --  */
      arb_dbcmd(adm_connection, " and ");
      arb_dbcmd(adm_connection, sqlquery);
      arb_dbcmd(adm_connection, " ");


   arb_exec_string(adm_connection, "", SQL_DEFER_EXECUTE);

   arb_dbbind(adm_connection, 1, ARB_TYPE_INT32, 0, &rowcount);

   while (arb_next_row(adm_connection) == ARB_MORE_DATA) 
      ;

   if (arb_query_status(adm_connection) != SUCCESS)
      return -1;

   if (rowcount == 0)
      return 0;

/*-------------------------------------------------------------------------+
 | Allocate space for the working table of external contact source
 | information. Make sure the table is NULL terminated.
 +------------------------------------------------------------------------*/

   src_table = (COM_SOURCE **) calloc(rowcount+1, sizeof(COM_SOURCE *));
   if (!src_table)
   {
      emit(ERRLOC, CALLOC_FAILURE, "COM_SOURCE *", rowcount);
      return -1;
   }

   src_table[rowcount] = NULL;

/*-------------------------------------------------------------------------+
 | Fill table with external contact source information.
 +------------------------------------------------------------------------*/

   arb_dbcmd(adm_connection,  "SELECT EXT_CONTACTS.ext_contact_id, ");
   arb_dbcmd(adm_connection,  "   is_send, source_id, ext_client_id, ");
   arb_dbcmd(adm_connection,  "   access_method, respond_to_id, ext_ebcdic, ");
   arb_dbcmd(adm_connection,  "   prefix_match, postfix_match, unique_ext_name, ");
   arb_dbcmd(adm_connection,  "   arbor_ready, arbor_done, arbor_error, ");
   arb_dbcmd(adm_connection,  "   arbor_work, max_time_gap, retry_delay, ");
   arb_dbcmd(adm_connection,  "   retry_limit, is_rfr_required, rfr_path, ");
   arb_dbcmd(adm_connection,  "   rfr_filename, rfr_delay, file_name_alter_type, error_code, ");
   arb_dbcmd(adm_connection,  "   retry_count, control_file_expected, ");
   arb_dbcmd(adm_connection,  "   process_name ");
   arb_dbcmd(adm_connection,  "FROM EXT_CONTACTS, EXT_CONTACTS_STATUS ");
   arb_dbcmd(adm_connection,  "WHERE ");
   arb_dbcmd(adm_connection,  "   EXT_CONTACTS.ext_contact_id ");
   arb_dbcmd(adm_connection,  "      = EXT_CONTACTS_STATUS.ext_contact_id ");
   arb_dbfcmd(adm_connection, "AND (process_name IS NULL OR process_name='%s') ",
      arb_get_process_id());
   arb_dbfcmd(adm_connection, "AND active_dt <= %s ", arb_server_getdate());
   arb_dbfcmd(adm_connection, "AND (inactive_dt IS NULL OR %s < inactive_dt) ",
      arb_server_getdate());
   /*CBS00097804*/
   arb_dbfcmd(adm_connection, "AND (retry_count<retry_limit OR retry_limit IS NULL OR retry_limit=0) ");

   if (!empty_string(sqlquery))
      /*  --  CAMqa51929  --  */
      /*  --  replaced arb_dbfcmd call with following 3 arb_dbcmd calls  --  */
      /*  --  arb_dbfcmd(adm_connection," and (%s)", sqlquery);  --  */
      arb_dbcmd(adm_connection, " and ");
      arb_dbcmd(adm_connection, sqlquery);
      arb_dbcmd(adm_connection, " ");


   arb_exec_string(adm_connection, "", SQL_DEFER_EXECUTE);

   j = 1;
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT16,    0, &con.ext_contact_id);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT8,     0, &con.is_send);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con.source_id);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.ext_client_id), con.ext_client_id);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT8,     0, &con.access_method);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT16,    0, &con.respond_to_id);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_BIT,      0, &con.ext_ebcdic);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.prefix_match), con.prefix_match);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.postfix_match), con.postfix_match);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_BIT,      0, &con.unique_ext_name);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.arbor_ready), con.arbor_ready);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.arbor_done), con.arbor_done);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.arbor_error), con.arbor_error);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.arbor_work), con.arbor_work);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con.max_time_gap);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con.retry_delay);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con.retry_limit);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT8,     0, &con.is_rfr_required);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.rfr_path), con.rfr_path);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con.rfr_filename), con.rfr_filename);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT16,    0, &con.rfr_delay);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT8,     0, &con.file_name_alter_type);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con_stat.error_code);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_INT32,    0, &con_stat.retry_count);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_BIT,      0, &con.control_file_expected);
   arb_dbbind(adm_connection, j++, 
      ARB_TYPE_STRING,   sizeof(con_stat.process_name), con_stat.process_name);

   i = -1;
   while (arb_next_row(adm_connection) == ARB_MORE_DATA) 
   {
      if (++i >= rowcount)
         break;

      emit(ERRLOC, COM_DATASRC_DEBUG2, con.ext_contact_id, con.access_method);

      con_stat.ext_contact_id = con.ext_contact_id;

      if ((src_table[i] = alloc_com_source()) == NULL)
      {
         free_sources_list(src_table);
         return -1;
      }

      memcpy(src_table[i]->contact, &con, sizeof(EXT_CONTACTS));
      memcpy(src_table[i]->contact_status, &con_stat, sizeof(EXT_CONTACTS_STATUS));

      emit(ERRLOC, COM_DATASRC_DEBUG4, src_table[i]->contact->ext_contact_id, 
         src_table[i]->contact->access_method);
   }

   num_sources = i;

   if (arb_query_status(adm_connection) != SUCCESS)
   {
      free_sources_list(src_table);
      return -1;
   }

   if (num_sources >= rowcount)
   {
      /* ERROR: More entries than we counted */
      emit(ERRLOC, COM_TABLE_FLUX, "EXT_CONTACTS");
      free_sources_list(src_table);
      return -1;
   }

/*-------------------------------------------------------------------------+
 | Define output parameter "srclist".
 +------------------------------------------------------------------------*/

   *srclist = src_table;

   if (num_sources < 0)
      return 0;
   else
      return num_sources + 1;

} /* get_sources_list() */
Exemplo n.º 6
0
/*
 * numbered_command: does (hopefully) the right thing with the numbered
 * responses from the server.  I wasn't real careful to be sure I got them
 * all, but the default case should handle any I missed (sorry) 
 */
void
numbered_command(u_char *from, int comm, u_char **ArgList)
{
	u_char	*user;
	u_char	none_of_these = 0;
	u_char	blah[BIG_BUFFER_SIZE];
	int	flag,
		lastlog_level;
	const	int	from_server = parsing_server();
#if 0
	int	user_cnt,
		inv_cnt,
		server_cnt;
#endif /* 0 */

	if (!from || !*from)
		return;
	if (!*ArgList[0])
		user = NULL;
	else
		user = ArgList[0];
	if (!ArgList[1])
		return;
	lastlog_level = set_lastlog_msg_level(LOG_CRAP);
	save_message_from();
	message_from(NULL, LOG_CRAP);
	ArgList++;
	current_numeric_local = -comm;	/* must be negative of numeric! */
	switch (comm)
	{
	case 001:	/* #define RPL_WELCOME          001 */
		PasteArgs(ArgList, 0);
		if (my_strcmp(user, server_get_nickname(from_server)) != 0)
		{
			yell("=== Setting this servers nickname to \"%s\" from \"%s\"", user, server_get_nickname(from_server));
			server_set_nickname(from_server, user);
		}
		if (do_hook(current_numeric(), "%s %s", from, *ArgList)) 
			display_msg(from, ArgList);
		clean_whois_queue();
		break;
	case 002:	/* #define RPL_YOURHOST         002 */
		PasteArgs(ArgList, 0);
		snprintf(CP(blah), sizeof blah, "*** %s", ArgList[0]);
		got_initial_version(blah);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		break;

/* should do something with this some day, 2.8 had channel/user mode switches */
	case 004:	/* #define RPL_MYINFO           004 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		break;

/*
 * this part of ircii has been broken for most of ircd 2.7, so someday I'll
 * make it work for ircd 2.8 ...  phone..
 */
#if 0
	case 251:		/* #define RPL_LUSERCLIENT      251 */
		display_msg(from, ArgList);
		if (is_server_connected(from_server))
			break;
		if (from_server == get_primary_server() && ((sscanf(ArgList[1],
		    "There are %d users and %d invisible on %d servers",
		    &user_cnt, &inv_cnt, &server_cnt) == 3)||(sscanf(ArgList[1],
		    "There are %d users and %d invisible on %d servers",
		    &user_cnt, &inv_cnt, &server_cnt) == 3)))
		{
			user_cnt =+ inv_cnt;
			if ((server_cnt < get_int_var(MINIMUM_SERVERS_VAR)) ||
			    (user_cnt < get_int_var(MINIMUM_USERS_VAR)))
			{
				say("Trying better populated server...");
				get_connected(from_server + 1);
			}
		}
		break;
#endif /* 0 */
	case 301:		/* #define RPL_AWAY             301 */
		user_is_away(from, ArgList);
		break;

	case 302:		/* #define RPL_USERHOST         302 */
		userhost_returned(from, ArgList);
		break;

	case 303:		/* #define RPL_ISON             303 */
		ison_returned(from, ArgList);
		break;

	case 311:		/* #define RPL_WHOISUSER        311 */
		whois_name(from, ArgList);
		break;

	case 312:		/* #define RPL_WHOISSERVER      312 */
		whois_server(from, ArgList);
		break;

	case 313:		/* #define RPL_WHOISOPERATOR    313 */
		whois_oper(from, ArgList);
		break;

	case 314:		/* #define RPL_WHOWASUSER       314 */
		whowas_name(from, ArgList);
		break;

	case 316:		/* #define RPL_WHOISCHANOP      316 */
		whois_chop(from, ArgList);
		break;

	case 317:		/* #define RPL_WHOISIDLE        317 */
		whois_lastcom(from, ArgList);
		break;

	case 318:		/* #define RPL_ENDOFWHOIS       318 */
		end_of_whois(from, ArgList);
		break;

	case 319:		/* #define RPL_WHOISCHANNELS    319 */
		whois_channels(from, ArgList);
		break;

	case 321:		/* #define RPL_LISTSTART        321 */
		ArgList[0] = UP("Channel\0Users\0Topic");
		ArgList[1] = ArgList[0] + 8;
		ArgList[2] = ArgList[1] + 6;
		ArgList[3] = NULL;
		funny_list(from, ArgList);
		break;

	case 322:		/* #define RPL_LIST             322 */
		funny_list(from, ArgList);
		break;

	case 324:		/* #define RPL_CHANNELMODEIS    324 */
		funny_mode(from, ArgList);
		break;

	case 341:		/* #define RPL_INVITING         341 */
		invite(from, ArgList);
		break;

	case 352:		/* #define RPL_WHOREPLY         352 */
		whoreply(NULL, ArgList);
		break;

	case 353:		/* #define RPL_NAMREPLY         353 */
		funny_namreply(from, ArgList);
		break;

	case 366:		/* #define RPL_ENDOFNAMES       366 */
		{
			u_char	*tmp = NULL,
				*chan;

			PasteArgs(ArgList, 0);
			malloc_strcpy(&tmp, ArgList[0]);
			chan = next_arg(tmp, 0);
			flag = do_hook(current_numeric(), "%s %s", from, ArgList[0]);
			
			if (flag &&
			    channel_mode_lookup(chan, CHAN_NAMES | CHAN_MODE, 0) &&
			    get_int_var(SHOW_END_OF_MSGS_VAR) && flag)
				display_msg(from, ArgList);

			new_free(&tmp);
		}
		break;

	case 381: 		/* #define RPL_YOUREOPER        381 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		server_set_operator(parsing_server(), 1);
		update_all_status();	/* fix the status line */
		break;

	case 401:		/* #define ERR_NOSUCHNICK       401 */
		no_such_nickname(from, ArgList);
		break;

	case 405:		/* #define ERR_TOOMANYCHANNELS  405 */
		remove_channel(ArgList[0], parsing_server());
		break;
		
	case 421:		/* #define ERR_UNKNOWNCOMMAND   421 */
		if (check_screen_redirect(ArgList[0]))
			break;
		if (check_wait_command(ArgList[0]))
			break;
		PasteArgs(ArgList, 0);
		flag = do_hook(current_numeric(), "%s %s", from, *ArgList);
		if (!my_strncmp("ISON", *ArgList, 4) || !my_strncmp("USERHOST",
		    *ArgList, 8))
		{
			server_set_2_6_2(parsing_server(), 0);
			convert_to_whois();
		}
		else if (flag)
			display_msg(from, ArgList);
		break;

	case 432:		/* #define ERR_ERRONEUSNICKNAME 432 */
	case 433:		/* #define ERR_NICKNAMEINUSE    433 */ 
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		reset_nickname(from);
		break;

	case 437:		/* #define ERR_UNAVAILRESOURCE  437 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		if (!is_channel(*ArgList))
			reset_nickname(from);
		break;

	case 463:		/* #define ERR_NOPERMFORHOST    463 */
		display_msg(from, ArgList);
		close_server(parsing_server(), empty_string());
		window_check_servers();
		if (!connected_to_server())
			get_connected(parsing_server() + 1);
		break;

	case 464:		/* #define ERR_PASSWDMISMATCH   464 */
		PasteArgs(ArgList, 0);
		flag = do_hook(current_numeric(), "%s %s", from, ArgList[0]);
		if (server_get_oper_command())
		{
			if (flag)
				display_msg(from, ArgList);
		}
		else
			get_password();
		break;

	case 465:		/* #define ERR_YOUREBANNEDCREEP 465 */
		{
			int	klined_server = parsing_server();

			PasteArgs(ArgList, 0);
			if (do_hook(current_numeric(), "%s %s", from, ArgList[0]))
				display_msg(from, ArgList);
			close_server(parsing_server(), empty_string());
			window_check_servers();
			if (number_of_servers() > 1)
				remove_from_server_list(klined_server);
			if (!connected_to_server())
				say("You are not connected to a server. Use /SERVER to connect.");
			break;
		}

	case 471:		/* #define ERR_CHANNELISFULL    471 */
	case 473:		/* #define ERR_INVITEONLYCHAN   473 */
	case 474:		/* #define ERR_BANNEDFROMCHAN   474 */
	case 475: 		/* #define ERR_BADCHANNELKEY    475 */
	case 476:		/* #define ERR_BADCHANMASK      476 */
		cannot_join_channel(from, ArgList);
		break;

	case 484:		/* #define ERR_RESTRICTED       484 */
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		server_set_flag(parsing_server(), USER_MODE_R, 1);
		break;

		/*
		 * The following accumulates the remaining arguments
		 * in ArgSpace for hook detection.  We can't use
		 * PasteArgs here because we still need the arguments
		 * separated for use elsewhere.
		 */
	default:
		{
			u_char	*ArgSpace = NULL;
			int	i,
				do_message_from = 0;
			size_t	len;

			for (i = len = 0; ArgList[i]; len += my_strlen(ArgList[i++]))
				;
			len += (i - 1);
			ArgSpace = new_malloc(len + 1);
			ArgSpace[0] = '\0';
			/* this is cheating */
			if (ArgList[0] && is_channel(ArgList[0]))
				do_message_from = 1;
			for (i = 0; ArgList[i]; i++)
			{
				if (i)
					my_strcat(ArgSpace, " ");
				my_strcat(ArgSpace, ArgList[i]);
			}
			if (do_message_from)
				message_from(ArgList[0], LOG_CRAP);
			i = do_hook(current_numeric(), "%s %s", from, ArgSpace);
			new_free(&ArgSpace);
			if (do_message_from)
				restore_message_from();
			if (i == 0)
				goto done;
			none_of_these = 1;
		}
	}
	/* the following do not hurt the ircII if intercepted by a hook */
	if (none_of_these)
	{
		switch (comm)
		{
		case 221: 		/* #define RPL_UMODEIS          221 */
			put_it("%s Your user mode is \"%s\"", numeric_banner(),
				ArgList[0]);
			break;

		case 242:		/* #define RPL_STATSUPTIME      242 */
			PasteArgs(ArgList, 0);
			if (from && !my_strnicmp(server_get_itsname(parsing_server()),
			    from, my_strlen(server_get_itsname(parsing_server()))))
				from = NULL;
			if (from)
				put_it("%s %s from (%s)", numeric_banner(),
					*ArgList, from);
			else
				put_it("%s %s", numeric_banner(), *ArgList);
			break;

		case 332:		/* #define RPL_TOPIC            332 */
			channel_topic(from, ArgList);
			break;

		case 351:		/* #define RPL_VERSION          351 */
			version(from, ArgList);
			break;

		case 364:		/* #define RPL_LINKS            364 */
			if (ArgList[2])
			{
				PasteArgs(ArgList, 2);
				put_it("%s %-20s %-20s %s", numeric_banner(),
					ArgList[0], ArgList[1], ArgList[2]);
			}
			else
			{
				PasteArgs(ArgList, 1);
				put_it("%s %-20s %s", numeric_banner(),
					ArgList[0], ArgList[1]);
			}
			break;

		case 372:		/* #define RPL_MOTD             372 */
			if (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server()))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			break;

		case 375:		/* #define RPL_MOTDSTART        375 */
			if (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server()))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			break;

		case 376:		/* #define RPL_ENDOFMOTD        376 */
			if (server_get_attempting_to_connect(parsing_server()))
				got_initial_version(UP("*** Your host is broken and not running any version"));
			if (get_int_var(SHOW_END_OF_MSGS_VAR) &&
			    (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server())))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			server_set_motd(parsing_server(), 0);
			break;

		case 384:		/* #define RPL_MYPORTIS         384 */
			PasteArgs(ArgList, 0);
			put_it("%s %s %s", numeric_banner(), ArgList[0], user);
			break;

		case 385:		/* #define RPL_NOTOPERANYMORE   385 */
			server_set_operator(parsing_server(), 0);
			display_msg(from, ArgList);
			update_all_status();
			break;

		case 403:		/* #define ERR_NOSUCHCHANNEL    403 */
			not_valid_channel(from, ArgList);
			break;

		case 451:		/* #define ERR_NOTREGISTERED    451 */
	/*
	 * Sometimes the server doesn't catch the USER line, so
	 * here we send a simplified version again  -lynx 
	 */
			send_to_server("USER %s %s . :%s", my_username(),
				irc_umode(), my_realname());
			send_to_server("NICK %s",
				server_get_nickname(parsing_server()));
			break;

		case 462:		/* #define ERR_ALREADYREGISTRED 462 */
			display_msg(from, ArgList);
			break;

#define RPL_CLOSEEND         363
#define RPL_SERVLISTEND      235
		case 315:		/* #define RPL_ENDOFWHO         315 */
		case 323:               /* #define RPL_LISTEND          323 */
			funny_print_widelist();

		case 219:		/* #define RPL_ENDOFSTATS       219 */
		case 232:		/* #define RPL_ENDOFSERVICES    232 */
		case 365:		/* #define RPL_ENDOFLINKS       365 */
		case 368:		/* #define RPL_ENDOFBANLIST     368 */
		case 369:		/* #define RPL_ENDOFWHOWAS      369 */
		case 374:		/* #define RPL_ENDOFINFO        374 */
#if 0	/* this case needs special handing - see above */
		case 376:		/* #define RPL_ENDOFMOTD        376 */
#endif /* 0 */
		case 394:		/* #define RPL_ENDOFUSERS       394 */
			if (!get_int_var(SHOW_END_OF_MSGS_VAR))
				break;
		default:
			display_msg(from, ArgList);
		}
	}
	set_lastlog_msg_level(lastlog_level);
done:
	restore_message_from();
}
Exemplo n.º 7
0
int main(int argc,char *argv[])
{
  FILE                    *input;
  int                      out       = -1;
  int                      filecount = 1;
  size_t                   count;
  uint8_t                  outpacket[1500];
  struct greylist_request *glq;
  char                    *line;
  size_t                   linesize;
  
  input    = stdin;
  line     = NULL;
  linesize = 0;
  
  parse_command_line(argc,argv);
  
  if (g_inputfile)
    input = fopen(g_inputfile,"r");
  
  count = g_count;
  
  while(getline(&line,&linesize,input) > 0)
  {
    char    *nl;
    char    *from;
    char    *to;
    size_t   sfrom;
    size_t   sto;
    size_t   packetsize;
    uint8_t *p;
    CRC32    crc;
    
    nl = strchr(line,'\n'); if (nl) *nl = '\0';
    
    if (count == g_count)
    {
      char filename[BUFSIZ];
      
      close(out);
      sprintf(filename,g_outputfile,filecount++);
      out = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0644);
      if (out == -1)
      {
        perror(filename);
        exit(EXIT_FAILURE);
      }
      count = 0;
    }
      
    if (empty_string(line)) continue;
    
    glq = (struct greylist_request *)outpacket;
    p   = glq->data;
    
    glq->version = htons(VERSION);
    glq->MTA     = htons(MTA_POSTFIX);
    glq->type    = htons(CMD_GREYLIST);
    glq->ipsize  = htons(4);
    
    *p++ = strtoul(line,&from,10); from++;
    *p++ = strtoul(from,&from,10); from++;
    *p++ = strtoul(from,&from,10); from++;
    *p++ = strtoul(from,&from,10); from++;
    
    to = strchr(from,' ');
    if (to == NULL) continue;
    *to++ = '\0';
    
    if (strcmp(from,"-") == 0)
      from = "";
    
    if (strcmp(to,"-") == 0)
      to = "";
    
    sfrom = min(strlen(from),200);
    sto   = min(strlen(to),200);
    
    glq->fromsize = htons(sfrom);
    glq->tosize   = htons(sto);
    
    memcpy(p,from,sfrom); p += sfrom;
    memcpy(p,to,  sto);   p += sto;
    
    packetsize = (size_t)(p - outpacket);
    crc        = crc32(INIT_CRC32,&glq->version,packetsize - sizeof(CRC32));
    crc        = crc32(crc,g_secret,g_secretsize);
    glq->crc   = htonl(crc);
    
    write(out,&packetsize,sizeof(packetsize));
    write(out,outpacket,packetsize);
    count++;
  }
  
  free(line);
  close(out);
  fclose(input);
  return(EXIT_SUCCESS);
}
Exemplo n.º 8
0
int add_lock_file_status(Arb_connection *adm_connection, char *file_name,
   char *ctrl_file_name, int file_byte_count, EXT_CONTACTS *contact,
   int *file_id, tiny *server_id, short * file_type)
{
   FILE_STATUS file_struct;

   boolean brand_new_file = TRUE;

   char process_name[szProcessID+1];

   int stat;

   tiny file_status;
   tiny is_send;

/*-------------------------------------------------------------------------+
 | Initialize file status structure values that are dervied from input
 | arguments. Set up a transaction to contain all database changes.
 +------------------------------------------------------------------------*/

   file_struct.ext_contact_id = contact->ext_contact_id;
   strcpy(file_struct.file_name, file_name);
   strcpy(file_struct.ctrl_file_name, ctrl_file_name);
   file_struct.file_byte_count = file_byte_count;

   if (arb_begin_tran(adm_connection, arb_get_process_id()) != SUCCESS)
      return ERR_FAILED;

/*-------------------------------------------------------------------------+
 | If duplicate names are not allowed for this ext_contact_id, then see if
 | there is already en entry in the FILE_STATUS table for this file. If
 | duplicate names ARE allowed, then don't bother checking for an entry
 | since a new file will always be created.
 +------------------------------------------------------------------------*/

   if (contact->unique_ext_name)
   {

#ifdef NEW_FS_FUNCS
      stat = get_file_status_by_name(adm_connection, file_name,
         contact->ext_contact_id, file_id, server_id, file_type, &is_send,
         &file_status, process_name);
#else
      stat = get_file_status_by_name(adm_connection, file_name,
         contact->ext_contact_id, file_id, server_id, &is_send,
         &file_status, process_name);
#endif


      if (stat < 0)
      {
         stat = ERR_FAILED;
         goto err_add_lock_file_status;
      }

/*-------------------------------------------------------------------------+
 |    Zero or more matching entries were found in the FILE_STATUS table
 |    (stat indicates the number found). There are three possibilities at
 |    this point:
 |
 |    1. Zero matching entries were found. There are no possible conflicts,
 |       so simply proceed and create a new file. 
 |    2. One matching entry was found. Continue checking the state of the
 |       entry found to determine if the entry can be used.
 |    3. More than one matching entry was found. This condition cannot be
 |       supported for this contact (it's unique_ext_name flag is TRUE!).
 |       This situation can only occur if the contact allowed duplicate
 |       names in the past, some duplicates were received, and then the
 |       contact was changed to not support duplicate names. In this case,
 |       there could already be duplicates within Arbor. Mark the file as
 |       a duplicate and raise an error.
 +------------------------------------------------------------------------*/

      if (stat > 0)
      {
#ifdef DEBUG_MAX
         sprintf(gstrScratch, "DUP CHECK: %d matches; contact: %d, name: %s", 
            stat, contact->ext_contact_id, file_name);
         emit(ERRLOC, COM_GENERIC_DEBUG, gstrScratch);
#endif

         if (stat > 1)
         {
            emit(ERRLOC, COM_UNEXPECTED_DUP, contact->ext_contact_id,
               file_name);
            stat = DUPLICATE_FILE;
            goto err_add_lock_file_status;
         }

/*-------------------------------------------------------------------------+
 |       There is a FILE_STATUS entry for this file_name. The current
 |       status of the entry will now determine how to proceed:
 |
 |       FILE_STAT_DONE or FILE_STAT_AUDIT - indicates that this file has
 |          already been processed (loaded into database for file_status
 |          DONE or written off/superceeded for file_status AUDIT). New
 |          file to be processed  in this run is thus a duplicate.
 |       FILE_STAT_INUSE or entry marked with another process' name - file
 |          is in use by this process or another process. If a system
 |          failure has left the file in this state, you must use the
 |          cleanup script to reset it.
 |       anything else - indicates that there is an entry for this file,
 |          but the file has not been loaded into the database. This
 |          situation can occur because an Arbor processing module has not
 |          gotten to it yet (file_status NEW) or because an earlier
 |          attempt to process the file failed (file_status ERROR). In
 |          either case, allow re-transfer of the unprocessed file by
 |          locking the file for us by this process.
 +------------------------------------------------------------------------*/

         if ((file_status == FILE_STAT_DONE) || (file_status == FILE_STAT_AUDIT))
         {
            stat = DUPLICATE_FILE;
            goto err_add_lock_file_status;
         } 
         else if ((file_status == FILE_STAT_INUSE) ||
                  (! empty_string(process_name) &&         /* Locked, */
                  (strcmp(process_name, arb_get_process_id()) != 0))) 
         {
            stat = FILE_LOCKED;
            goto err_add_lock_file_status;
         } 
         else 
         {

#ifdef NEW_FS_FUNCS
            stat = lock_file_status(adm_connection, *file_id, *server_id, *file_type);
#else
            stat = lock_file_status(adm_connection, *file_id, *server_id);
#endif

            if (stat == -2)
            {
               stat = FILE_TO_LOCK_NF;
               goto err_add_lock_file_status;

            } 
            else if (stat == -1)
            {
               stat = ERR_FAILED;
               emit(ERRLOC, MCOM_LOCK_STAT_ERR, *file_id, *server_id);
               goto err_add_lock_file_status;

            } 
            else if (stat == 0) 
            {
               stat = FILE_LOCKED;
               goto err_add_lock_file_status;
            } 
            else 
            {
               brand_new_file = FALSE;
            }
         }
      }
   }

/*-------------------------------------------------------------------------+
 | Either a unique file name is not required or no matchinf entries were
 | found for the file in the FILE_STATUS table. Thus, this is a new file.
 | Add a "locked" entry for it in the FILE_STATUS table.
 +------------------------------------------------------------------------*/

   if (brand_new_file)
   {
      *server_id = giAdminServerId;
      file_struct.server_id = *server_id;
      file_struct.file_status = FILE_STAT_INUSE;
      file_struct.is_send = FILE_STAT_RECEIVE;
      file_struct.file_type = 0; /* unknown */
      file_struct.file_group_id = 0; /* unknown */
      strcpy(file_struct.ext_file_id, ""); /* unknown */

      stat = add_file_status(adm_connection, &file_struct, file_id);

#ifdef DEBUG_MAX
      printf("add_file_status: file_id = %d\n");
      printf("stat = %d\n", stat );      
#endif


      if (stat == FAILURE)
      {
         stat = ERR_FAILED;
         goto err_add_lock_file_status;
      }
   }

/*-------------------------------------------------------------------------+
 | If we get this far, then the input file has been indentified and/or
 | loaded into the FILE_STATUS table and locked. Commit the transaction to
 | save the data base changes and return SUCCESS.
 +------------------------------------------------------------------------*/

   if (arb_commit_tran(adm_connection) == FAILURE)
   {
      stat = ERR_FAILED;
      goto err_add_lock_file_status;
   }

   return SUCCESS;

/*-------------------------------------------------------------------------+
 | An error has occurred somewhere along the line. Rollback the transaction
 | so the database won't be affected by the error and return.
 +------------------------------------------------------------------------*/

err_add_lock_file_status:

   arb_rollback_tran(adm_connection, arb_get_process_id());

   return stat;

} /* add_lock_file_status() */
TEST(fxcrt, WideStringOperatorEQ) {
  CFX_WideString null_string;
  EXPECT_TRUE(null_string == null_string);

  CFX_WideString empty_string(L"");
  EXPECT_TRUE(empty_string == empty_string);
  EXPECT_TRUE(empty_string == null_string);
  EXPECT_TRUE(null_string == empty_string);

  CFX_WideString deleted_string(L"hello");
  deleted_string.Delete(0, 5);
  EXPECT_TRUE(deleted_string == deleted_string);
  EXPECT_TRUE(deleted_string == null_string);
  EXPECT_TRUE(deleted_string == empty_string);
  EXPECT_TRUE(null_string == deleted_string);
  EXPECT_TRUE(null_string == empty_string);

  CFX_WideString wide_string(L"hello");
  EXPECT_TRUE(wide_string == wide_string);
  EXPECT_FALSE(wide_string == null_string);
  EXPECT_FALSE(wide_string == empty_string);
  EXPECT_FALSE(wide_string == deleted_string);
  EXPECT_FALSE(null_string == wide_string);
  EXPECT_FALSE(empty_string == wide_string);
  EXPECT_FALSE(deleted_string == wide_string);

  CFX_WideString wide_string_same1(L"hello");
  EXPECT_TRUE(wide_string == wide_string_same1);
  EXPECT_TRUE(wide_string_same1 == wide_string);

  CFX_WideString wide_string_same2(wide_string);
  EXPECT_TRUE(wide_string == wide_string_same2);
  EXPECT_TRUE(wide_string_same2 == wide_string);

  CFX_WideString wide_string1(L"he");
  CFX_WideString wide_string2(L"hellp");
  CFX_WideString wide_string3(L"hellod");
  EXPECT_FALSE(wide_string == wide_string1);
  EXPECT_FALSE(wide_string == wide_string2);
  EXPECT_FALSE(wide_string == wide_string3);
  EXPECT_FALSE(wide_string1 == wide_string);
  EXPECT_FALSE(wide_string2 == wide_string);
  EXPECT_FALSE(wide_string3 == wide_string);

  CFX_WideStringC null_string_c;
  CFX_WideStringC empty_string_c(L"");
  EXPECT_TRUE(null_string == null_string_c);
  EXPECT_TRUE(null_string == empty_string_c);
  EXPECT_TRUE(empty_string == null_string_c);
  EXPECT_TRUE(empty_string == empty_string_c);
  EXPECT_TRUE(deleted_string == null_string_c);
  EXPECT_TRUE(deleted_string == empty_string_c);
  EXPECT_TRUE(null_string_c == null_string);
  EXPECT_TRUE(empty_string_c == null_string);
  EXPECT_TRUE(null_string_c == empty_string);
  EXPECT_TRUE(empty_string_c == empty_string);
  EXPECT_TRUE(null_string_c == deleted_string);
  EXPECT_TRUE(empty_string_c == deleted_string);

  CFX_WideStringC wide_string_c_same1(L"hello");
  EXPECT_TRUE(wide_string == wide_string_c_same1);
  EXPECT_TRUE(wide_string_c_same1 == wide_string);

  CFX_WideStringC wide_string_c1(L"he");
  CFX_WideStringC wide_string_c2(L"hellp");
  CFX_WideStringC wide_string_c3(L"hellod");
  EXPECT_FALSE(wide_string == wide_string_c1);
  EXPECT_FALSE(wide_string == wide_string_c2);
  EXPECT_FALSE(wide_string == wide_string_c3);
  EXPECT_FALSE(wide_string_c1 == wide_string);
  EXPECT_FALSE(wide_string_c2 == wide_string);
  EXPECT_FALSE(wide_string_c3 == wide_string);

  const wchar_t* c_null_string = nullptr;
  const wchar_t* c_empty_string = L"";
  EXPECT_TRUE(null_string == c_null_string);
  EXPECT_TRUE(null_string == c_empty_string);
  EXPECT_TRUE(empty_string == c_null_string);
  EXPECT_TRUE(empty_string == c_empty_string);
  EXPECT_TRUE(deleted_string == c_null_string);
  EXPECT_TRUE(deleted_string == c_empty_string);
  EXPECT_TRUE(c_null_string == null_string);
  EXPECT_TRUE(c_empty_string == null_string);
  EXPECT_TRUE(c_null_string == empty_string);
  EXPECT_TRUE(c_empty_string == empty_string);
  EXPECT_TRUE(c_null_string == deleted_string);
  EXPECT_TRUE(c_empty_string == deleted_string);

  const wchar_t* c_string_same1 = L"hello";
  EXPECT_TRUE(wide_string == c_string_same1);
  EXPECT_TRUE(c_string_same1 == wide_string);

  const wchar_t* c_string1 = L"he";
  const wchar_t* c_string2 = L"hellp";
  const wchar_t* c_string3 = L"hellod";
  EXPECT_FALSE(wide_string == c_string1);
  EXPECT_FALSE(wide_string == c_string2);
  EXPECT_FALSE(wide_string == c_string3);
  EXPECT_FALSE(c_string1 == wide_string);
  EXPECT_FALSE(c_string2 == wide_string);
  EXPECT_FALSE(c_string3 == wide_string);
}
Exemplo n.º 10
0
int parse_file(const char *filename, struct dive_table *table)
{
	struct git_repository *git;
	const char *branch = NULL;
	char *current_sha = copy_string(saved_git_id);
	struct memblock mem;
	char *fmt;
	int ret;

	git = is_git_repository(filename, &branch, NULL, false);
	if (prefs.cloud_git_url &&
	    strstr(filename, prefs.cloud_git_url)
	    && git == dummy_git_repository) {
		/* opening the cloud storage repository failed for some reason
		 * give up here and don't send errors about git repositories */
		free(current_sha);
		return -1;
	}
	/* if this is a git repository, do we already have this exact state loaded ?
	 * get the SHA and compare with what we currently have */
	if (git && git != dummy_git_repository) {
		const char *sha = get_sha(git, branch);
		if (!empty_string(sha) &&
		    same_string(sha, current_sha) &&
		    !unsaved_changes()) {
			fprintf(stderr, "already have loaded SHA %s - don't load again\n", sha);
			free(current_sha);
			return 0;
		}
	}
	free(current_sha);
	if (git)
		return git_load_dives(git, branch);

	if ((ret = readfile(filename, &mem)) < 0) {
		/* we don't want to display an error if this was the default file  */
		if (same_string(filename, prefs.default_filename))
			return 0;

		return report_error(translate("gettextFromC", "Failed to read '%s'"), filename);
	} else if (ret == 0) {
		return report_error(translate("gettextFromC", "Empty file '%s'"), filename);
	}

	fmt = strrchr(filename, '.');
	if (fmt && (!strcasecmp(fmt + 1, "DB") || !strcasecmp(fmt + 1, "BAK") || !strcasecmp(fmt + 1, "SQL"))) {
		if (!try_to_open_db(filename, &mem, table)) {
			free(mem.buffer);
			return 0;
		}
	}

	/* Divesoft Freedom */
	if (fmt && (!strcasecmp(fmt + 1, "DLF"))) {
		ret = parse_dlf_buffer(mem.buffer, mem.size, table);
		free(mem.buffer);
		return ret;
	}

	/* DataTrak/Wlog */
	if (fmt && !strcasecmp(fmt + 1, "LOG")) {
		ret = datatrak_import(&mem, table);
		free(mem.buffer);
		return ret;
	}

	/* OSTCtools */
	if (fmt && (!strcasecmp(fmt + 1, "DIVE"))) {
		free(mem.buffer);
		ostctools_import(filename, table);
		return 0;
	}

	ret = parse_file_buffer(filename, &mem, table);
	free(mem.buffer);
	return ret;
}
Exemplo n.º 11
0
void
parse_command_line(int argc, char *argv[], int spec)
{
    const char *arg, *aispec;
    char tmpspec[100], tmpargbuf[CLIBUFSIZE], blurb[BLURBSIZE];
    int i, n, numused, total_arg_space, tmpargbuflen = 0;

/* This macro just checks that a required next argument is actually
   there. */

#define REQUIRE_ONE_ARG  \
  if (i + 1 >= argc) {  \
    fprintf(stderr, "Error: `%s' requires an argument, exiting now\n", argv[i]);  \
    had_error = TRUE;  \
    continue;  \
  }  \
  numused = 2;

/* Each of these causes argument parsing to skip over the option if
   it's not the right time to look at it. */

#define GENERAL_OPTION if (spec != general_options) continue;
#define VARIANT_OPTION if (spec != variant_options) continue;
#define PLAYER_OPTION  if (spec != player_options)  continue;

    /* (should peel off any path stuff) */
    program_name = argv[0];

    if (spec == general_options)
      init_options();

    total_arg_space = 0;
    for (i = 0; i < argc; ++i) {
      if (!empty_string(argv[i])) {
        strncpy(tmpargbuf, argv[i], CLIBUFSIZE);
        tmpargbuf[CLIBUFSIZE - 1] = 0;
        tmpargbuflen = strlen(tmpargbuf);
	total_arg_space += tmpargbuflen + 2;
        (argv[i])[tmpargbuflen] = 0; 
      }
    }
    if (args_used == NULL)
      args_used = (char *)xmalloc (total_arg_space);

    for (i = 1; i < argc; ++i) {
	if (argv[i] == NULL || (argv[i])[0] == '\0') {
	    /* Empty or already munched, nothing to do. */
	} else if ((argv[i])[0] == '-') {
	    arg = argv[i];
	    Dprintf("%s\n", arg);
	    numused = 1;
	    if (strcmp(arg, "-c") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		checkpoint_interval = atoi(argv[i+1]);
	    } else if (strcmp(arg, "-design") == 0) {
		GENERAL_OPTION;
#ifdef DESIGNERS
		allbedesigners = TRUE;
#else
		fprintf(stderr,
			"No designing available, ignoring option `%s'\n", arg);
#endif /* DESIGNERS */
	    } else if (strncmp(arg, "-D", 2) == 0) {
		GENERAL_OPTION;
#ifdef DEBUGGING
		Debug = TRUE;
		if (strchr(arg+2, '-'))
		  Debug = FALSE;
		if (strchr(arg+2, 'M'))
		  DebugM = TRUE;
		if (strchr(arg+2, 'G'))
		  DebugG = TRUE;
#else
		fprintf(stderr,
			"No debugging available, ignoring option `%s'\n", arg);
#endif /* DEBUGGING */
	    } else if (strncmp(arg, "-e", 2) == 0) {
		REQUIRE_ONE_ARG;
		PLAYER_OPTION;
		n = atoi(argv[i+1]);
		/* A comma indicates that the name of a particular
		   desired AI type follows. */
		if (strlen(arg) > 2) {
		    aispec = arg + 2;
		    if (*aispec != ',') {
			sprintf(tmpspec, "%s%s", default_ai_type, aispec);
			aispec = tmpspec;
		    }
		} else {
		    aispec = default_ai_type;
		}
		while (n-- > 0)
		  add_a_raw_player_spec(aispec);
	    } else if (strcmp(arg, "-f") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		add_a_module(NULL, argv[i+1]); 
	    } else if (strcmp(arg, "-g") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		add_a_module(copy_string(argv[i+1]), NULL);
	    } else if (strcmp(arg, "-h") == 0) {
		REQUIRE_ONE_ARG;
		PLAYER_OPTION;
		n = atoi(argv[i+1]);
		option_num_to_wait_for += n;
		while (n-- > 0)
		  add_a_raw_player_spec("?@");
	    } else if (strcmp(arg, "-help") == 0) {
		GENERAL_OPTION;
		help_wanted = TRUE;
		/* Will display help info later. */
	    } else if (strcmp(arg, "-host") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		option_game_to_host = copy_string(argv[i+1]);
	    } else if (strcmp(arg, "-join") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		option_game_to_join = copy_string(argv[i+1]);
	    } else if (strcmp(arg, "-L") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
		if (strcmp(argv[i+1], "-") == 0)
		  add_library_path(NULL);
		else
		  add_library_path(argv[i+1]);
	    } else if (strcmp(arg, "-M") == 0) {
		REQUIRE_ONE_ARG;
		VARIANT_OPTION;
		parse_world_option(argv[i+1]);
	    } else if (strcmp(arg, "-noai") == 0) {
		PLAYER_OPTION;
		initially_no_ai = TRUE;
	    } else if (strcmp(arg, "-r") == 0) {
		PLAYER_OPTION;
		option_add_default_player = FALSE;
	    } else if (strcmp(arg, "-R") == 0) {
		REQUIRE_ONE_ARG;
		GENERAL_OPTION;
#ifdef DEBUGGING
		init_xrandom(atoi(argv[i+1]));
#else
		fprintf(stderr,
			"No debugging available, ignoring option `%s'\n", arg);
#endif /* DEBUGGING */
	    } else if (strcmp(arg, "-seq") == 0) {
		VARIANT_OPTION;
		push_key_int_binding(&variant_settings, K_SEQUENTIAL, 1);
	    } else if (strcmp(arg, "-sim") == 0) {
		VARIANT_OPTION;
		push_key_int_binding(&variant_settings, K_SEQUENTIAL, 0);
	    } else if (strncmp(arg, "-t", 2) == 0) {
		REQUIRE_ONE_ARG;
		VARIANT_OPTION;
		parse_realtime_option(arg, argv[i+1]);
	    } else if (strncmp(arg, "-v", 2) == 0) {
		VARIANT_OPTION;
		parse_variant(arg + 2);
	    } else if (strcmp(arg, "-V") == 0) {
		VARIANT_OPTION;
		push_key_int_binding(&variant_settings, K_SEE_ALL, 1);
	    } else if (strcmp(arg, "-V0") == 0) {
		VARIANT_OPTION;
		push_key_int_binding(&variant_settings, K_SEE_ALL, 0);
	    } else if (strcmp(arg, "-Vfalse") == 0) {
		VARIANT_OPTION;
		push_key_int_binding(&variant_settings, K_SEE_ALL, 0);
	    } else if (strcmp(arg, "-w") == 0) {
		GENERAL_OPTION;
		warnings_suppressed = TRUE;
	    } else if (strcmp(arg, "-x") == 0) {
		GENERAL_OPTION;
		option_popup_new_game_dialog = TRUE;
	    } else if (strcmp(arg, "--help") == 0) {
		GENERAL_OPTION;
		help_wanted = TRUE;
		/* Will display help info later. */
	    } else if (strcmp(arg, "--version") == 0) {
		GENERAL_OPTION;
		version_wanted = TRUE;
	    } else {
		numused = 0;
		/* Anything unrecognized during the last parse is an error. */
		if (spec >= leftover_options) {
		    fprintf(stderr, "Unrecognized option `%s'\n", arg);
		    had_error = TRUE;
		}
	    }
	    if (numused >= 1) {
		strcat(args_used, " ");
		strcat(args_used, argv[i]);
		argv[i] = NULL;
	    }
	    if (numused >= 2) {
		strcat(args_used, " ");
		strcat(args_used, argv[i+1]);
		argv[i+1] = NULL;
	    }
	    if (numused >= 1)
	      i += (numused - 1);
	} else {
	    if (spec == player_options) {
		if (*(argv[i]) == '+' || *(argv[i]) == '@') {
		    raw_default_player_spec = argv[i];
		} else {
		    add_a_raw_player_spec(argv[i]);
		}
		strcat(args_used, " ");
		strcat(args_used, argv[i]);
		argv[i] = NULL;
	    }
	}
    }
    if (version_wanted) {
	version_info();
    }
    if (had_error || help_wanted || variant_help_wanted) {
	/* If we want to get help about a particular game, have to
           load it first. */
	if (help_wanted || variant_help_wanted)
	  load_all_modules();
	if (had_error || help_wanted)
	  general_usage_info();
	if (had_error || help_wanted)
	  player_usage_info();
	if (help_wanted && mainmodule != NULL) {
	    printf("\nGame info:\n\n");
	    if (!empty_string(mainmodule->title))
	      printf("%s (%s)\n", mainmodule->title, mainmodule->name);
	    else
	      printf("%s\n", mainmodule->name);
	    printf("    \n");
	    if (mainmodule->blurb != lispnil) {
	    	append_blurb_strings(blurb, mainmodule->blurb);
	    	printf("%s", blurb);
	    } else {
	    	printf("(no description)");
	    }
	}
	/* Display variant info here so it comes after basic info
	   about the game module. */
	if (had_error || help_wanted || variant_help_wanted)
	  game_usage_info();
    }
    if (had_error || help_wanted || variant_help_wanted || version_wanted) {
	exit(had_error);
    }
}
Exemplo n.º 12
0
/**
 * New sprintf implementation for PHP.
 *
 * Modifiers:
 *
 *  " "   pad integers with spaces
 *  "-"   left adjusted field
 *   n    field size
 *  "."n  precision (floats only)
 *  "+"   Always place a sign (+ or -) in front of a number
 *
 * Type specifiers:
 *
 *  "%"   literal "%", modifiers are ignored.
 *  "b"   integer argument is printed as binary
 *  "c"   integer argument is printed as a single character
 *  "d"   argument is an integer
 *  "f"   the argument is a float
 *  "o"   integer argument is printed as octal
 *  "s"   argument is a string
 *  "x"   integer argument is printed as lowercase hexadecimal
 *  "X"   integer argument is printed as uppercase hexadecimal
 */
String string_printf(const char *format, int len, const Array& args) {
  Array vargs = args;
  if (!vargs.isNull() && !vargs->isVectorData()) {
    vargs = Array::Create();
    for (ArrayIter iter(args); iter; ++iter) {
      vargs.append(iter.second());
    }
  }

  if (len == 0) {
    return empty_string();
  }

  int size = 240;
  StringBuffer result(size);

  int argnum = 0, currarg = 1;
  for (int inpos = 0; inpos < len; ++inpos) {
    char ch = format[inpos];

    int expprec = 0;
    if (ch != '%') {
      result.append(ch);
      continue;
    }

    if (format[inpos + 1] == '%') {
      result.append('%');
      inpos++;
      continue;
    }

    /* starting a new format specifier, reset variables */
    int alignment = ALIGN_RIGHT;
    int adjusting = 0;
    char padding = ' ';
    int always_sign = 0;
    int width, precision;
    inpos++;      /* skip the '%' */
    ch = format[inpos];

    if (isascii(ch) && !isalpha(ch)) {
      /* first look for argnum */
      int temppos = inpos;
      while (isdigit((int)format[temppos])) temppos++;
      if (format[temppos] == '$') {
        argnum = getnumber(format, &inpos);
        if (argnum <= 0) {
          throw_invalid_argument("argnum: must be greater than zero");
          return String();
        }
        inpos++;  /* skip the '$' */
      } else {
        argnum = currarg++;
      }

      /* after argnum comes modifiers */
      for (;; inpos++) {
        ch = format[inpos];

        if (ch == ' ' || ch == '0') {
          padding = ch;
        } else if (ch == '-') {
          alignment = ALIGN_LEFT;
          /* space padding, the default */
        } else if (ch == '+') {
          always_sign = 1;
        } else if (ch == '\'' && inpos != len - 1) {
          padding = format[++inpos];
        } else {
          break;
        }
      }
      ch = format[inpos];

      /* after modifiers comes width */
      if (isdigit(ch)) {
        if ((width = getnumber(format, &inpos)) < 0) {
          throw_invalid_argument("width: must be greater than zero "
                                 "and less than %d", INT_MAX);
          return String();
        }
        adjusting |= ADJ_WIDTH;
      } else {
        width = 0;
      }
      ch = format[inpos];

      /* after width and argnum comes precision */
      if (ch == '.') {
        ch = format[++inpos];
        if (isdigit((int)ch)) {
          if ((precision = getnumber(format, &inpos)) < 0) {
            throw_invalid_argument("precision: must be greater than zero "
                                   "and less than %d", INT_MAX);
            return String();
          }
          ch = format[inpos];
          adjusting |= ADJ_PRECISION;
          expprec = 1;
        } else {
          precision = 0;
        }
      } else {
        precision = 0;
      }
    } else {
      width = precision = 0;
      argnum = currarg++;
    }

    if (argnum > vargs.size()) {
      throw_invalid_argument("arguments: (too few)");
      return String();
    }

    if (ch == 'l') {
      ch = format[++inpos];
    }
    /* now we expect to find a type specifier */
    Variant tmp = vargs[argnum-1];

    switch (ch) {
    case 's': {
      String s = tmp.toString();
      appendstring(&result, s.c_str(),
                   width, precision, padding, alignment, s.size(),
                   0, expprec, 0);
      break;
    }
    case 'd':
      appendint(&result, tmp.toInt64(),
                width, padding, alignment, always_sign);
      break;
    case 'u':
      appenduint(&result, tmp.toInt64(),
                 width, padding, alignment);
      break;

    case 'g':
    case 'G':
    case 'e':
    case 'E':
    case 'f':
    case 'F':
      appenddouble(&result, tmp.toDouble(),
                   width, padding, alignment, precision, adjusting,
                   ch, always_sign);
      break;

    case 'c':
      result.append(tmp.toByte());
      break;

    case 'o':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 3, hexchars, expprec);
      break;

    case 'x':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 4, hexchars, expprec);
      break;

    case 'X':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 4, HEXCHARS, expprec);
      break;

    case 'b':
      append2n(&result, tmp.toInt64(),
               width, padding, alignment, 1, hexchars, expprec);
      break;

    case '%':
      result.append('%');

      break;
    default:
      break;
    }
  }

  return result.detach();
}
Exemplo n.º 13
0
_clState *initCl(unsigned int gpu, char *name, size_t nameSize, algorithm_t *algorithm)
{
  _clState *clState = (_clState *)calloc(1, sizeof(_clState));
  struct cgpu_info *cgpu = &gpus[gpu];
  cl_platform_id platform = NULL;
  char pbuff[256];
  build_kernel_data *build_data = (build_kernel_data *) alloca(sizeof(struct _build_kernel_data));
  cl_uint preferred_vwidth;
  cl_device_id *devices;
  cl_uint numDevices;
  cl_int status;

  if (!get_opencl_platform(opt_platform_id, &platform)) {
    return NULL;
  }

  numDevices = clDevicesNum();

  if (numDevices <= 0 ) return NULL;

  devices = (cl_device_id *)alloca(numDevices*sizeof(cl_device_id));

  /* Now, get the device list data */

  status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Getting Device IDs (list)", status);
    return NULL;
  }

  applog(LOG_INFO, "List of devices:");

  unsigned int i;
  for (i = 0; i < numDevices; i++) {
    status = clGetDeviceInfo(devices[i], CL_DEVICE_NAME, sizeof(pbuff), pbuff, NULL);
    if (status != CL_SUCCESS) {
      applog(LOG_ERR, "Error %d: Getting Device Info", status);
      return NULL;
    }

    applog(LOG_INFO, "\t%i\t%s", i, pbuff);

    if (i == gpu) {
      applog(LOG_INFO, "Selected %i: %s", gpu, pbuff);
      strncpy(name, pbuff, nameSize);
    }
  }

  if (gpu >= numDevices) {
    applog(LOG_ERR, "Invalid GPU %i", gpu);
    return NULL;
  }

  status = create_opencl_context(&clState->context, &platform);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Creating Context. (clCreateContextFromType)", status);
    return NULL;
  }

  status = create_opencl_command_queue(&clState->commandQueue, &clState->context, &devices[gpu], cgpu->algorithm.cq_properties);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Creating Command Queue. (clCreateCommandQueue)", status);
    return NULL;
  }

  clState->hasBitAlign = get_opencl_bit_align_support(&devices[gpu]);

  status = clGetDeviceInfo(devices[gpu], CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT, sizeof(cl_uint), (void *)&preferred_vwidth, NULL);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT", status);
    return NULL;
  }
  applog(LOG_DEBUG, "Preferred vector width reported %d", preferred_vwidth);

  status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), (void *)&clState->max_work_size, NULL);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_WORK_GROUP_SIZE", status);
    return NULL;
  }
  applog(LOG_DEBUG, "Max work group size reported %d", (int)(clState->max_work_size));

  size_t compute_units = 0;
  status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(size_t), (void *)&compute_units, NULL);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_COMPUTE_UNITS", status);
    return NULL;
  }
  // AMD architechture got 64 compute shaders per compute unit.
  // Source: http://www.amd.com/us/Documents/GCN_Architecture_whitepaper.pdf
  clState->compute_shaders = compute_units * 64;
  applog(LOG_DEBUG, "Max shaders calculated %d", (int)(clState->compute_shaders));

  status = clGetDeviceInfo(devices[gpu], CL_DEVICE_MAX_MEM_ALLOC_SIZE , sizeof(cl_ulong), (void *)&cgpu->max_alloc, NULL);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Failed to clGetDeviceInfo when trying to get CL_DEVICE_MAX_MEM_ALLOC_SIZE", status);
    return NULL;
  }
  applog(LOG_DEBUG, "Max mem alloc size is %lu", (long unsigned int)(cgpu->max_alloc));

  /* Create binary filename based on parameters passed to opencl
   * compiler to ensure we only load a binary that matches what
   * would have otherwise created. The filename is:
   * name + g + lg + lookup_gap + tc + thread_concurrency + nf + nfactor + w + work_size + l + sizeof(long) + .bin
   */
  char filename[255];
  char strbuf[32];

  sprintf(strbuf, "%s.cl", (!empty_string(cgpu->algorithm.kernelfile) ? cgpu->algorithm.kernelfile : cgpu->algorithm.name));
  strcpy(filename, strbuf);
  applog(LOG_DEBUG, "Using source file %s", filename);

  /* For some reason 2 vectors is still better even if the card says
   * otherwise, and many cards lie about their max so use 256 as max
   * unless explicitly set on the command line. Tahiti prefers 1 */
  if (strstr(name, "Tahiti"))
    preferred_vwidth = 1;
  else if (preferred_vwidth > 2)
    preferred_vwidth = 2;

  /* All available kernels only support vector 1 */
  cgpu->vwidth = 1;

  /* Vectors are hard-set to 1 above. */
  if (likely(cgpu->vwidth))
    clState->vwidth = cgpu->vwidth;
  else {
    clState->vwidth = preferred_vwidth;
    cgpu->vwidth = preferred_vwidth;
  }

  clState->goffset = true;

  if (cgpu->work_size && cgpu->work_size <= clState->max_work_size)
    clState->wsize = cgpu->work_size;
  else
    clState->wsize = 256;

  if (!cgpu->opt_lg) {
    applog(LOG_DEBUG, "GPU %d: selecting lookup gap of 2", gpu);
    cgpu->lookup_gap = 2;
  } else
    cgpu->lookup_gap = cgpu->opt_lg;

  if ((strcmp(cgpu->algorithm.name, "zuikkis") == 0) && (cgpu->lookup_gap != 2)) {
    applog(LOG_WARNING, "Kernel zuikkis only supports lookup-gap = 2 (currently %d), forcing.", cgpu->lookup_gap);
    cgpu->lookup_gap = 2;
  }

  if ((strcmp(cgpu->algorithm.name, "bufius") == 0) && ((cgpu->lookup_gap != 2) && (cgpu->lookup_gap != 4) && (cgpu->lookup_gap != 8))) {
    applog(LOG_WARNING, "Kernel bufius only supports lookup-gap of 2, 4 or 8 (currently %d), forcing to 2", cgpu->lookup_gap);
    cgpu->lookup_gap = 2;
  }

  // neoscrypt calculates TC differently
  if (!safe_cmp(cgpu->algorithm.name, "neoscrypt")) {
    int max_int = ((cgpu->dynamic) ? MAX_INTENSITY : cgpu->intensity);
    size_t glob_thread_count = 1UL << max_int;

    // if TC is entered by user, use that value... otherwise use default
    cgpu->thread_concurrency = ((cgpu->opt_tc) ? cgpu->opt_tc : ((glob_thread_count < cgpu->work_size) ? cgpu->work_size : glob_thread_count));

    // if TC * scratchbuf size is too big for memory... reduce to max
    if (((uint64_t)cgpu->thread_concurrency * NEOSCRYPT_SCRATCHBUF_SIZE) >(uint64_t)cgpu->max_alloc) {
      /* Selected intensity will not run on this GPU. Not enough memory.
      * Adapt the memory setting. */
      glob_thread_count = cgpu->max_alloc / NEOSCRYPT_SCRATCHBUF_SIZE;

      /* Find highest significant bit in glob_thread_count, which gives
      * the intensity. */
      while (max_int && ((1U << max_int) & glob_thread_count) == 0) {
        --max_int;
      }

      /* Check if max_intensity is >0. */
      if (max_int < MIN_INTENSITY) {
        applog(LOG_ERR, "GPU %d: Max intensity is below minimum.", gpu);
        max_int = MIN_INTENSITY;
      }

      cgpu->intensity = max_int;
      cgpu->thread_concurrency = 1U << max_int;
    }

    applog(LOG_DEBUG, "GPU %d: computing max. global thread count to %u", gpu, (unsigned)(cgpu->thread_concurrency));

  }
  else if (!cgpu->opt_tc) {
    unsigned int sixtyfours;

    sixtyfours =  cgpu->max_alloc / 131072 / 64 / (algorithm->n/1024) - 1;
    cgpu->thread_concurrency = sixtyfours * 64;
    if (cgpu->shaders && cgpu->thread_concurrency > cgpu->shaders) {
      cgpu->thread_concurrency -= cgpu->thread_concurrency % cgpu->shaders;
      if (cgpu->thread_concurrency > cgpu->shaders * 5) {
        cgpu->thread_concurrency = cgpu->shaders * 5;
      }
    }
    applog(LOG_DEBUG, "GPU %d: selecting thread concurrency of %d", gpu, (int)(cgpu->thread_concurrency));
  }
  else {
    cgpu->thread_concurrency = cgpu->opt_tc;
  }


  cl_uint slot, cpnd;

  slot = cpnd = 0;

  build_data->context = clState->context;
  build_data->device = &devices[gpu];

  // Build information
  strcpy(build_data->source_filename, filename);
  strcpy(build_data->platform, name);
  strcpy(build_data->sgminer_path, sgminer_path);
  if (opt_kernel_path && *opt_kernel_path) {
    build_data->kernel_path = opt_kernel_path;
  }
  else {
    build_data->kernel_path = NULL;
  }

  build_data->work_size = clState->wsize;
  build_data->has_bit_align = clState->hasBitAlign;

  build_data->opencl_version = get_opencl_version(devices[gpu]);
  build_data->patch_bfi = needs_bfi_patch(build_data);

  strcpy(build_data->binary_filename, (!empty_string(cgpu->algorithm.kernelfile) ? cgpu->algorithm.kernelfile : cgpu->algorithm.name));
  strcat(build_data->binary_filename, name);
  if (clState->goffset)
    strcat(build_data->binary_filename, "g");

  set_base_compiler_options(build_data);
  if (algorithm->set_compile_options)
    algorithm->set_compile_options(build_data, cgpu, algorithm);

  strcat(build_data->binary_filename, ".bin");
  applog(LOG_DEBUG, "Using binary file %s", build_data->binary_filename);

  // Load program from file or build it if it doesn't exist
  if (!(clState->program = load_opencl_binary_kernel(build_data))) {
    applog(LOG_NOTICE, "Building binary %s", build_data->binary_filename);

    if (!(clState->program = build_opencl_kernel(build_data, filename)))
      return NULL;

    if (save_opencl_kernel(build_data, clState->program)) {
      /* Program needs to be rebuilt, because the binary was patched */
      if (build_data->patch_bfi) {
        clReleaseProgram(clState->program);
        clState->program = load_opencl_binary_kernel(build_data);
      }
    } else {
      if (build_data->patch_bfi)
        quit(1, "Could not save kernel to file, but it is necessary to apply BFI patch");
    }
  }

  // Load kernels
  applog(LOG_NOTICE, "Initialising kernel %s with%s bitalign, %spatched BFI, nfactor %d, n %d",
         filename, clState->hasBitAlign ? "" : "out", build_data->patch_bfi ? "" : "un",
         algorithm->nfactor, algorithm->n);

  /* get a kernel object handle for a kernel with the given name */
  clState->kernel = clCreateKernel(clState->program, "search", &status);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: Creating Kernel from program. (clCreateKernel)", status);
    return NULL;
  }


  clState->n_extra_kernels = algorithm->n_extra_kernels;
  if (clState->n_extra_kernels > 0) {
    unsigned int i;
    char kernel_name[9]; // max: search99 + 0x0

    clState->extra_kernels = (cl_kernel *)malloc(sizeof(cl_kernel) * clState->n_extra_kernels);

    for (i = 0; i < clState->n_extra_kernels; i++) {
      snprintf(kernel_name, 9, "%s%d", "search", i + 1);
      clState->extra_kernels[i] = clCreateKernel(clState->program, kernel_name, &status);
      if (status != CL_SUCCESS) {
        applog(LOG_ERR, "Error %d: Creating ExtraKernel #%d from program. (clCreateKernel)", status, i);
        return NULL;
      }
    }
  }

  size_t bufsize;
  size_t readbufsize = 128;

  if (algorithm->rw_buffer_size < 0) {
    // calc buffer size for neoscrypt
    if (!safe_cmp(algorithm->name, "neoscrypt")) {
      /* The scratch/pad-buffer needs 32kBytes memory per thread. */
      bufsize = NEOSCRYPT_SCRATCHBUF_SIZE * cgpu->thread_concurrency;

      /* This is the input buffer. For neoscrypt this is guaranteed to be
      * 80 bytes only. */
      readbufsize = 80;

      applog(LOG_DEBUG, "Neoscrypt buffer sizes: %lu RW, %lu R", (unsigned long)bufsize, (unsigned long)readbufsize);
      // scrypt/n-scrypt
    }
    else {
      size_t ipt = (algorithm->n / cgpu->lookup_gap + (algorithm->n % cgpu->lookup_gap > 0));
      bufsize = 128 * ipt * cgpu->thread_concurrency;
      applog(LOG_DEBUG, "Scrypt buffer sizes: %lu RW, %lu R", (unsigned long)bufsize, (unsigned long)readbufsize);
    }
  }
  else {
    bufsize = (size_t)algorithm->rw_buffer_size;
    applog(LOG_DEBUG, "Buffer sizes: %lu RW, %lu R", (unsigned long)bufsize, (unsigned long)readbufsize);
  }

  clState->padbuffer8 = NULL;

  if (bufsize > 0) {
    applog(LOG_DEBUG, "Creating read/write buffer sized %lu", (unsigned long)bufsize);
    /* Use the max alloc value which has been rounded to a power of
     * 2 greater >= required amount earlier */
    if (bufsize > cgpu->max_alloc) {
      applog(LOG_WARNING, "Maximum buffer memory device %d supports says %lu",
           gpu, (unsigned long)(cgpu->max_alloc));
      applog(LOG_WARNING, "Your settings come to %lu", (unsigned long)bufsize);
    }

    /* This buffer is weird and might work to some degree even if
     * the create buffer call has apparently failed, so check if we
     * get anything back before we call it a failure. */
    clState->padbuffer8 = clCreateBuffer(clState->context, CL_MEM_READ_WRITE, bufsize, NULL, &status);
    if (status != CL_SUCCESS && !clState->padbuffer8) {
      applog(LOG_ERR, "Error %d: clCreateBuffer (padbuffer8), decrease TC or increase LG", status);
      return NULL;
    }
  }

  applog(LOG_DEBUG, "Using read buffer sized %lu", (unsigned long)readbufsize);
  clState->CLbuffer0 = clCreateBuffer(clState->context, CL_MEM_READ_ONLY, readbufsize, NULL, &status);
  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: clCreateBuffer (CLbuffer0)", status);
    return NULL;
  }
  
  applog(LOG_DEBUG, "Using output buffer sized %lu", BUFFERSIZE);
  clState->outputBuffer = clCreateBuffer(clState->context, CL_MEM_WRITE_ONLY, BUFFERSIZE, NULL, &status);

  if (status != CL_SUCCESS) {
    applog(LOG_ERR, "Error %d: clCreateBuffer (outputBuffer)", status);
    return NULL;
  }

  return clState;
}