Esempio n. 1
0
NS_IMETHODIMP
nsDebugImpl::Assertion(const char *aStr, const char *aExpr, const char *aFile, PRInt32 aLine)
{
   InitLog();

   char buf[1000];
   PR_snprintf(buf, sizeof(buf),
              "###!!! ASSERTION: %s: '%s', file %s, line %d",
              aStr, aExpr, aFile, aLine);

   // Write out the assertion message to the debug log
   PR_LOG(gDebugLog, PR_LOG_ERROR, ("%s", buf));
   PR_LogFlush();

   // And write it out to the stderr
   fprintf(stderr, "%s\n", buf);
   fflush(stderr);

#if defined(_WIN32)
   char* assertBehavior = getenv("XPCOM_DEBUG_BREAK");
   if (assertBehavior && strcmp(assertBehavior, "warn") == 0)
     return NS_OK;

   if(!InDebugger())
      {
      DWORD code = IDRETRY;

      /* Create the debug dialog out of process to avoid the crashes caused by 
       * Windows events leaking into our event loop from an in process dialog.
       * We do this by launching windbgdlg.exe (built in xpcom/windbgdlg).
       * See http://bugzilla.mozilla.org/show_bug.cgi?id=54792
       */
      PROCESS_INFORMATION pi;
      STARTUPINFO si;
      char executable[MAX_PATH];
      char* pName;

      memset(&pi, 0, sizeof(pi));

      memset(&si, 0, sizeof(si));
      si.cb          = sizeof(si);
      si.wShowWindow = SW_SHOW;

      if(GetModuleFileName(GetModuleHandle(XPCOM_DLL), executable, MAX_PATH) &&
         NULL != (pName = strrchr(executable, '\\')) &&
         NULL != strcpy(pName+1, "windbgdlg.exe") &&
#ifdef DEBUG_jband
         (printf("Launching %s\n", executable), PR_TRUE) &&
#endif         
         CreateProcess(executable, buf, NULL, NULL, PR_FALSE,
                       DETACHED_PROCESS | NORMAL_PRIORITY_CLASS,
                       NULL, NULL, &si, &pi) &&
         WAIT_OBJECT_0 == WaitForSingleObject(pi.hProcess, INFINITE) &&
         GetExitCodeProcess(pi.hProcess, &code))
      {
        CloseHandle(pi.hProcess);
      }                         

      switch(code)
         {
         case IDABORT:
            //This should exit us
            raise(SIGABRT);
            //If we are ignored exit this way..
            _exit(3);
            break;
         
         case IDIGNORE:
            return NS_OK;
            // Fall Through
         }
      }
#endif

#if defined(XP_OS2)
   char* assertBehavior = getenv("XPCOM_DEBUG_BREAK");
   if (assertBehavior && strcmp(assertBehavior, "warn") == 0)
     return NS_OK;

      char msg[1200];
      PR_snprintf(msg, sizeof(msg),
                "%s\n\nClick Cancel to Debug Application.\n"
                "Click Enter to continue running the Application.", buf);
      ULONG code = MBID_ERROR;
      code = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, msg, 
                           "nsDebug::Assertion", 0,
                           MB_ERROR | MB_ENTERCANCEL);

      /* It is possible that we are executing on a thread that doesn't have a
       * message queue.  In that case, the message won't appear, and code will
       * be 0xFFFF.  We'll give the user a chance to debug it by calling
       * Break()
       * Actually, that's a really bad idea since this happens a lot with threadsafe
       * assertions and since it means that you can't actually run the debug build
       * outside a debugger without it crashing constantly.
       */
      if(( code == MBID_ENTER ) || (code == MBID_ERROR))
      {
         return NS_OK;
         // If Retry, Fall Through
      }
#endif

      Break(aFile, aLine);
      return NS_OK;
}
Esempio n. 2
0
static void bt_handler(int sig) {
  // In case we crash again in the signal hander or something
  signal(sig, SIG_DFL);

  // Generating a stack dumps significant time, try to stop threads
  // from flushing bad data or generating more faults meanwhile
  if (sig==SIGQUIT || sig==SIGILL || sig==SIGSEGV || sig==SIGBUS) {
    SegFaulting=true;
    LightProcess::Close();
    // leave running for SIGTERM SIGFPE SIGABRT
  }

  // Turn on stack traces for coredumps
  StackTrace::Enabled = true;
  StackTraceNoHeap st;

  char pid[sizeof(Process::GetProcessId())*3+2]; // '-' and \0
  sprintf(pid,"%u",Process::GetProcessId());
  char tracefn[StackTraceBase::ReportDirectory.length()
               + strlen("/stacktrace..log") + strlen(pid) + 1];
  sprintf(tracefn, "%s/stacktrace.%s.log",
          StackTraceBase::ReportDirectory.c_str(), pid);

  st.log(strsignal(sig), tracefn, pid);

  int fd = ::open(tracefn, O_APPEND|O_WRONLY, S_IRUSR|S_IWUSR);
  if (fd >= 0) {
    if (!g_context.isNull()) {
      dprintf(fd, "\nPHP Stacktrace:\n\n%s",
              debug_string_backtrace(false).data());
    }
    ::close(fd);
  }

  if (!StackTrace::ReportEmail.empty()) {
    char format [] = "cat %s | mail -s \"Stack Trace from %s\" '%s'";
    char cmdline[strlen(format)+strlen(tracefn)
                 +strlen(Process::GetAppName().c_str())
                 +strlen(StackTrace::ReportEmail.c_str())+1];
    sprintf(cmdline, format, tracefn, Process::GetAppName().c_str(),
            StackTrace::ReportEmail.c_str());
    Util::ssystem(cmdline);
  }

  // Calling all of these library functions in a signal handler
  // is completely undefined behavior, but we seem to get away with it.
  // Do it last just in case

  Logger::Error("Core dumped: %s", strsignal(sig));

  if (hhvm && !g_context.isNull()) {
    // sync up gdb Dwarf info so that gdb can do a full backtrace
    // from the core file. Do this at the very end as syncing needs
    // to allocate memory for the ELF file.
    g_vmContext->syncGdbState();
  }

  // re-raise the signal and pass it to the default handler
  // to terminate the process.
  raise(sig);
}
Esempio n. 3
0
File: io.cpp Progetto: Zoxc/mirb
void IO::assert_stream()
{
    if(!stream)
        raise(context->io_error, "IO object is closed");
}
Esempio n. 4
0
static void cleanup_children_on_signal(int sig)
{
    cleanup_children(sig, 1);
    sigchain_pop(sig);
    raise(sig);
}
Esempio n. 5
0
void *net_thread_function(void *arg) {
    /* This thread puts data into a ring buffer from a socket*/
    BufferSocket *bs = (BufferSocket *)arg;
    RING_ITEM *this_slot;

    socket_t sock = setup_network_listener((short) bs->port);
    SA_in addr; // packet source's address
    socklen_t addr_len = sizeof(addr);
    ssize_t num_bytes = 0;
    fd_set readset;
    struct timeval tv;
    struct timespec ts;
    long timeouts = 0;

    // If sock open fails, end all threads
    if (sock == -1) {
        fprintf(stderr, "Unable to open socket.\n");
        bs->run_threads = 0;
        return NULL;
    }

    while (bs->run_threads) {
        this_slot = bs->buf->write_ptr;
        if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
            fprintf(stderr, "Net: clock_gettime returned nonzero.\n");
            bs->run_threads = 0;
            continue;
        }
        ts.tv_nsec += TIMEOUT_USEC*1000;
        // Wait for next buffer slot to open up
        if (sem_timedwait(&this_slot->write_mutex, &ts) == -1) continue;
        
        // Poll to see if socket has data
        while (bs->run_threads) {
            FD_ZERO(&readset);
            FD_SET(sock, &readset);
            tv.tv_sec = 0; tv.tv_usec = TIMEOUT_USEC;
            num_bytes = select(sock + 1, &readset, NULL, NULL, &tv);
            // Read data from socket into ring buffer
            if (num_bytes > 0) {
                num_bytes = recvfrom(sock, this_slot->data, 
                    bs->buf->buffer_size / bs->buf->list_length, 
                    0, (SA *)&addr, &addr_len);
                timeouts = 0;
                break;
            } else if (num_bytes < 0) {
                if (errno == EINTR) continue;
                fprintf(stderr, "Unable to receive packets.\n");
                bs->run_threads = 0;
            } else  { // num_bytes == 0
                timeouts += TIMEOUT_USEC;
                if(timeouts >= 60*1000*1000) {
                    fprintf(stdout, "No packets received for 60 seconds on port %d.\n", bs->port);
                    syslog(LOG_WARNING, "no packets received for 60 seconds on port %d\n", bs->port);
                    // Send self the INT signal (simulate ctrl-c)
                    raise(SIGINT);
                    timeouts = 0;
                }
            }
            //printf("run_threads=%d num_bytes=%d errno=%d(%d)\n", bs->run_threads, num_bytes, errno, EINTR);
        }

        if (num_bytes > 0) {
            //printf("Wrote in a packet: size=%d slot=%d\n", num_bytes, this_slot - bs->buf->list_ptr);
            this_slot->size = num_bytes;
            // Mark this slot ready for readout
            sem_post(&this_slot->read_mutex);
            bs->buf->write_ptr = this_slot->next;
        }
    }
    close(sock);
    return NULL;
}
Esempio n. 6
0
void default_unix_signal_handler(int signum, siginfo_t *info, void *)
{
	// Unix implementation of synchronous signal handler
	// This runs in the thread that threw the signal.
	// We do the somewhat sketchy operation of blocking in here until the error handler
	// has gracefully stopped the app.

	if (LLApp::sLogInSignal)
	{
		llinfos << "Signal handler - Got signal " << signum << " - " << apr_signal_description_get(signum) << llendl;
	}


	switch (signum)
	{
	case SIGCHLD:
		if (LLApp::sLogInSignal)
		{
			llinfos << "Signal handler - Got SIGCHLD from " << info->si_pid << llendl;
		}

		// Check result code for all child procs for which we've
		// registered callbacks THIS WILL NOT WORK IF SIGCHLD IS SENT
		// w/o killing the child (Go, launcher!)
		// TODO: Now that we're using SIGACTION, we can actually
		// implement the launcher behavior to determine who sent the
		// SIGCHLD even if it doesn't result in child termination
		if (LLApp::sChildMap.count(info->si_pid))
		{
			LLApp::sChildMap[info->si_pid].mGotSigChild = TRUE;
		}
		
		LLApp::incSigChildCount();

		return;
	case SIGABRT:
		// Abort just results in termination of the app, no funky error handling.
		if (LLApp::sLogInSignal)
		{
			llwarns << "Signal handler - Got SIGABRT, terminating" << llendl;
		}
		clear_signals();
		raise(signum);
		return;
	case SIGINT:
	case SIGHUP:
	case SIGTERM:
		if (LLApp::sLogInSignal)
		{
			llwarns << "Signal handler - Got SIGINT, HUP, or TERM, exiting gracefully" << llendl;
		}
		// Graceful exit
		// Just set our state to quitting, not error
		if (LLApp::isQuitting() || LLApp::isError())
		{
			// We're already trying to die, just ignore this signal
			if (LLApp::sLogInSignal)
			{
				llinfos << "Signal handler - Already trying to quit, ignoring signal!" << llendl;
			}
			return;
		}
		LLApp::setQuitting();
		return;
	case SIGALRM:
	case SIGPIPE:
	case SIGUSR2:
	default:
		if (signum == LL_SMACKDOWN_SIGNAL ||
		    signum == SIGBUS ||
		    signum == SIGILL ||
		    signum == SIGFPE ||
		    signum == SIGSEGV ||
		    signum == SIGQUIT)
		{ 
			if (signum == LL_SMACKDOWN_SIGNAL)
			{
				// Smackdown treated just like any other app termination, for now
				if (LLApp::sLogInSignal)
				{
					llwarns << "Signal handler - Handling smackdown signal!" << llendl;
				}
				else
				{
					// Don't log anything, even errors - this is because this signal could happen anywhere.
					LLError::setDefaultLevel(LLError::LEVEL_NONE);
				}
				
				// Change the signal that we reraise to SIGABRT, so we generate a core dump.
				signum = SIGABRT;
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - Handling fatal signal!" << llendl;
			}
			if (LLApp::isError())
			{
				// Received second fatal signal while handling first, just die right now
				// Set the signal handlers back to default before handling the signal - this makes the next signal wipe out the app.
				clear_signals();
				
				if (LLApp::sLogInSignal)
				{
					llwarns << "Signal handler - Got another fatal signal while in the error handler, die now!" << llendl;
				}
				raise(signum);
				return;
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - Flagging error status and waiting for shutdown" << llendl;
			}
			// Flag status to ERROR, so thread_error does its work.
			LLApp::setError();
			// Block in the signal handler until somebody says that we're done.
			while (LLApp::sErrorThreadRunning && !LLApp::isStopped())
			{
				ms_sleep(10);
			}
			
			if (LLApp::sLogInSignal)
			{
				llwarns << "Signal handler - App is stopped, reraising signal" << llendl;
			}
			clear_signals();
			raise(signum);
			return;
		} else {
			if (LLApp::sLogInSignal)
			{
				llinfos << "Signal handler - Unhandled signal " << signum << ", ignoring!" << llendl;
			}
		}
	}
}
Esempio n. 7
0
object_t *kernel_eval(static_context_t *this_context, object_t *self, int argc, object_t **argv)
{
	if (!this_context->parent)
		return Qnil;
	/* i could just make eval arity -2, and not handle this here. breaks with ruby though,
	 * where c functions neverr have neg arity < -1
	 */
	if (!argc)
		raise(ArgumentError, "wrong number of arguments (0 for 1)");
	char *code = STRING_PTR(coerce_to_s(this_context, argv[0]));
	char filename[256];
	static int eval_counter = 0;
	char entry_point[256];
	char so_file[256];
	eval_counter++;
	sprintf(filename, "temp_eval-%04d.rb", eval_counter);
	sprintf(so_file, "temp_eval-%04d.rb.so", eval_counter);
	sprintf(entry_point, "Init_temp_eval_%04d_rb", eval_counter);
	context_t *context;
	/* allow given binding to override */
	if (argc > 1) {
		/* TODO: TypeError: wrong argument type Fixnum (expected Proc/Binding) */
		binding_t *binding = (binding_t *)argv[1];
		/* a binding's context shouldn't need promoting */
		context = binding->data.context;
		// printf("context -> %p (%d)\n", context, context->locals.tally);
		self = binding->data.self;
	}
	else
		context = (context_t *)context_promote(this_context->parent->context);
	this_context->context = context;
	FILE *file = fopen(filename, "wb");
	if (!file)
		return Qnil;
	fprintf(file, "* Context data\n");
	while (context) {
		int i;
		for (i = 0; i < context->locals->tally; i++)
			/* we push strings here, instead of symbols (1.8 style) */
			fprintf(file, "%c - %s\n", i ? ' ' : '-', ((symbol_t *)context->locals->keys[i])->string);
		context = context->parent;
	}
	fprintf(file, "* Code\n");
	fprintf(file, "%s", code);
	fclose(file);
	/* we'll let the ruby compiler to do the job */
	char buf3[1024];
	sprintf(buf3, "ruby compiler.rb --eval %s %s %s", filename, so_file, entry_point);
	if (system(buf3))
		raise(ScriptError, "error compiling file - %s", filename);
	char abspath[PATH_MAX + 1];
	realpath(so_file, abspath);
	dlhandle_t *dl = dlopen(abspath, RTLD_NOW | RTLD_GLOBAL);
	if (!dl)
		raise(ScriptError, "error loading file - %s", dlerror());
	object_t *(*entry_point_ptr)(static_context_t *this_context, object_t *self);
	entry_point_ptr = dlsym(dl, entry_point);
	if (!entry_point_ptr)
		raise(ScriptError, "error loading file - %s", dlerror());
	return (*entry_point_ptr)(this_context, self);
}
Esempio n. 8
0
int main(int argc, char **argv)
{
  srvr_sockaddr_union_t me;
  struct tftphdr *tp;
  ssize_t n = 0;
  int arg = 1;
  unsigned short port = DEFAULT_PORT;
  curl_socket_t sock = CURL_SOCKET_BAD;
  int flag;
  int rc;
  int error;
  long pid;
  struct testcase test;
  int result = 0;

  memset(&test, 0, sizeof(test));

  while(argc>arg) {
    if(!strcmp("--version", argv[arg])) {
      printf("tftpd IPv4%s\n",
#ifdef ENABLE_IPV6
             "/IPv6"
#else
             ""
#endif
             );
      return 0;
    }
    else if(!strcmp("--pidfile", argv[arg])) {
      arg++;
      if(argc>arg)
        pidname = argv[arg++];
    }
    else if(!strcmp("--logfile", argv[arg])) {
      arg++;
      if(argc>arg)
        serverlogfile = argv[arg++];
    }
    else if(!strcmp("--ipv4", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv4";
      use_ipv6 = FALSE;
#endif
      arg++;
    }
    else if(!strcmp("--ipv6", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv6";
      use_ipv6 = TRUE;
#endif
      arg++;
    }
    else if(!strcmp("--port", argv[arg])) {
      arg++;
      if(argc>arg) {
        char *endptr;
        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
        if((endptr != argv[arg] + strlen(argv[arg])) ||
           (ulnum < 1025UL) || (ulnum > 65535UL)) {
          fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
                  argv[arg]);
          return 0;
        }
        port = curlx_ultous(ulnum);
        arg++;
      }
    }
    else if(!strcmp("--srcdir", argv[arg])) {
      arg++;
      if(argc>arg) {
        path = argv[arg];
        arg++;
      }
    }
    else {
      puts("Usage: tftpd [option]\n"
           " --version\n"
           " --logfile [file]\n"
           " --pidfile [file]\n"
           " --ipv4\n"
           " --ipv6\n"
           " --port [port]\n"
           " --srcdir [path]");
      return 0;
    }
  }

#ifdef WIN32
  win32_init();
  atexit(win32_cleanup);
#endif

  install_signal_handlers();

  pid = (long)getpid();

#ifdef ENABLE_IPV6
  if(!use_ipv6)
#endif
    sock = socket(AF_INET, SOCK_DGRAM, 0);
#ifdef ENABLE_IPV6
  else
    sock = socket(AF_INET6, SOCK_DGRAM, 0);
#endif

  if(CURL_SOCKET_BAD == sock) {
    error = SOCKERRNO;
    logmsg("Error creating socket: (%d) %s",
           error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

  flag = 1;
  if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
            (void *)&flag, sizeof(flag))) {
    error = SOCKERRNO;
    logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
           error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

#ifdef ENABLE_IPV6
  if(!use_ipv6) {
#endif
    memset(&me.sa4, 0, sizeof(me.sa4));
    me.sa4.sin_family = AF_INET;
    me.sa4.sin_addr.s_addr = INADDR_ANY;
    me.sa4.sin_port = htons(port);
    rc = bind(sock, &me.sa, sizeof(me.sa4));
#ifdef ENABLE_IPV6
  }
  else {
    memset(&me.sa6, 0, sizeof(me.sa6));
    me.sa6.sin6_family = AF_INET6;
    me.sa6.sin6_addr = in6addr_any;
    me.sa6.sin6_port = htons(port);
    rc = bind(sock, &me.sa, sizeof(me.sa6));
  }
#endif /* ENABLE_IPV6 */
  if(0 != rc) {
    error = SOCKERRNO;
    logmsg("Error binding socket on port %hu: (%d) %s",
           port, error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

  wrotepidfile = write_pidfile(pidname);
  if(!wrotepidfile) {
    result = 1;
    goto tftpd_cleanup;
  }

  logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);

  for (;;) {
    fromlen = sizeof(from);
#ifdef ENABLE_IPV6
    if(!use_ipv6)
#endif
      fromlen = sizeof(from.sa4);
#ifdef ENABLE_IPV6
    else
      fromlen = sizeof(from.sa6);
#endif
    n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
                          &from.sa, &fromlen);
    if(got_exit_signal)
      break;
    if (n < 0) {
      logmsg("recvfrom");
      result = 3;
      break;
    }

    set_advisor_read_lock(SERVERLOGS_LOCK);
    serverlogslocked = 1;

#ifdef ENABLE_IPV6
    if(!use_ipv6) {
#endif
      from.sa4.sin_family = AF_INET;
      peer = socket(AF_INET, SOCK_DGRAM, 0);
      if(CURL_SOCKET_BAD == peer) {
        logmsg("socket");
        result = 2;
        break;
      }
      if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
        logmsg("connect: fail");
        result = 1;
        break;
      }
#ifdef ENABLE_IPV6
    }
    else {
      from.sa6.sin6_family = AF_INET6;
      peer = socket(AF_INET6, SOCK_DGRAM, 0);
      if(CURL_SOCKET_BAD == peer) {
        logmsg("socket");
        result = 2;
        break;
      }
      if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
        logmsg("connect: fail");
        result = 1;
        break;
      }
    }
#endif

    maxtimeout = 5*TIMEOUT;

    tp = &buf.hdr;
    tp->th_opcode = ntohs(tp->th_opcode);
    if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
      memset(&test, 0, sizeof(test));
      if (do_tftp(&test, tp, n) < 0)
        break;
      if(test.buffer)
        free(test.buffer);
    }
    sclose(peer);
    peer = CURL_SOCKET_BAD;

    if(test.ofile > 0) {
      close(test.ofile);
      test.ofile = 0;
    }

    if(got_exit_signal)
      break;

    if(serverlogslocked) {
      serverlogslocked = 0;
      clear_advisor_read_lock(SERVERLOGS_LOCK);
    }

    logmsg("end of one transfer");

  }

tftpd_cleanup:

  if(test.ofile > 0)
    close(test.ofile);

  if((peer != sock) && (peer != CURL_SOCKET_BAD))
    sclose(peer);

  if(sock != CURL_SOCKET_BAD)
    sclose(sock);

  if(got_exit_signal)
    logmsg("signalled to die");

  if(wrotepidfile)
    unlink(pidname);

  if(serverlogslocked) {
    serverlogslocked = 0;
    clear_advisor_read_lock(SERVERLOGS_LOCK);
  }

  restore_signal_handlers();

  if(got_exit_signal) {
    logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
           ipv_inuse, (int)port, pid, exit_signal);
    /*
     * To properly set the return status of the process we
     * must raise the same signal SIGINT or SIGTERM that we
     * caught and let the old handler take care of it.
     */
    raise(exit_signal);
  }

  logmsg("========> tftpd quits");
  return result;
}
Esempio n. 9
0
static Cyg_ErrNo
termios_read(cyg_io_handle_t handle, void *_buf, cyg_uint32 *len)
{
    cyg_devtab_entry_t *dt = (cyg_devtab_entry_t *)handle;
    struct termios_private_info *priv = (struct termios_private_info *)dt->priv;
    cyg_io_handle_t chan = (cyg_io_handle_t)priv->dev_handle;
    struct termios *t = &priv->termios;
    cyg_uint32 clen;
    cyg_uint32 size;
    Cyg_ErrNo res;
    cyg_uint8 c;
    cyg_uint8 *buf = (cyg_uint8 *)_buf;
    cyg_bool discardc; // should c be discarded (not read, not printed)
    cyg_bool returnnow = false; // return back to user after this char

    // if receiver off
    if (0 == (t->c_cflag & CREAD) ) {
        *len = 0;
        return -EINVAL;
    }

    size = 0;
    if ( 0 == (t->c_lflag & ICANON) ) {
        // In non-canonical mode we return the min of *len and the
        // number of bytes available
        // So we query the driver for how many bytes are available - this
        // guarantees we won't block
        cyg_serial_buf_info_t dev_buf_conf;
        cyg_uint32 dbc_len = sizeof( dev_buf_conf );
        res = cyg_io_get_config( chan,
                                 CYG_IO_GET_CONFIG_SERIAL_BUFFER_INFO,
                                 &dev_buf_conf, &dbc_len );
        CYG_ASSERT( res == ENOERR, "Query buffer status failed!" );
        if (dev_buf_conf.rx_count > 0) {
            // Adjust length to be max characters currently available
            *len = *len < dev_buf_conf.rx_count ? *len : dev_buf_conf.rx_count;
        } else if (t->c_cc[VMIN] == 0) {
            // No chars available - don't block
            *len = 0;
            return ENOERR;
        }
    } // if

    while (!returnnow && size < *len) {
        clen = 1;
        discardc = false;
        res = cyg_io_read(chan, &c, &clen);
        if (res != ENOERR) {
            *len = size;
            return res;
        }

        // lock to prevent termios getting corrupted while we read from it
        cyg_drv_mutex_lock( &priv->lock );

        if ( t->c_iflag & ISTRIP )
            c &= 0x7f;

        // canonical mode: erase, kill, and newline processing
        if ( t->c_lflag & ICANON ) {
            if ( t->c_cc[ VERASE ] == c ) {
                discardc = true;
                // erase on display?
                if ( (t->c_lflag & ECHO) && (t->c_lflag & ECHOE) ) {
                    cyg_uint8 erasebuf[3];
                    erasebuf[0] = erasebuf[2] = t->c_cc[ VERASE ];
                    erasebuf[1] = ' ';
                    clen = sizeof(erasebuf);
                    // FIXME: what about error or non-blocking?
                    cyg_io_write(chan, erasebuf, &clen);
                }
                if ( size )
                    size--;
            } // if
            else if ( t->c_cc[ VKILL ] == c ) {
                // kill line on display?
                if ( (t->c_lflag & ECHO) && (t->c_lflag & ECHOK) ) {

                    // we could try and be more efficient here and
                    // output a stream of erases, and then a stream
                    // of spaces and then more erases. But this is poor
                    // because on a slow terminal the user will see characters
                    // delete from the middle forward in chunks!
                    // But at least we try and chunk up sets of writes
                    cyg_uint8 erasebuf[30];
                    cyg_uint8 erasechunks;
                    cyg_uint8 i;

                    erasechunks = size < (sizeof(erasebuf)/3) ?
                                  size : (sizeof(erasebuf)/3);

                    for (i=0; i<erasechunks; i++) {
                        erasebuf[i*3] = erasebuf[i*3+2] = t->c_cc[ VERASE ];
                        erasebuf[i*3+1] = ' ';
                    }

                    while( size ) {
                        cyg_uint8 j;

                        j = size < (sizeof(erasebuf)/3) ?
                            size : (sizeof(erasebuf)/3);
                        clen = (j*3);
                        // FIXME: what about error or non-blocking?
                        cyg_io_write( chan, erasebuf, &clen );
                        size -= j;
                    }
                } else
                    size = 0;
                discardc = true;
            } // else if
            // CR
            else if ( '\r' == c ) {
                if ( t->c_iflag & IGNCR )
                    discardc = true;
                else if ( t->c_iflag & ICRNL )
                    c = '\n';
            }
            // newlines or similar.
            // Note: not an else if to catch CRNL conversion
            if ( (t->c_cc[ VEOF ] == c) || (t->c_cc[ VEOL ] == c) ||
                    ('\n' == c) ) {
                if ( t->c_cc[ VEOF ] == c )
                    discardc = true;
                if ( t->c_lflag & ECHONL ) { // don't check ECHO in this case
                    clen = 1;
                    // FIXME: what about error or non-blocking?
                    // FIXME: what if INLCR is set?
                    cyg_io_write( chan, "\n", &clen );
                }
                if ( t->c_iflag & INLCR )
                    c = '\r';
                returnnow = true; // FIXME: true even for INLCR?
            } // else if
        } // if

#ifdef CYGSEM_IO_SERIAL_TERMIOS_USE_SIGNALS
        if ( (t->c_lflag & ISIG) && (t->c_cc[ VINTR ] == c) ) {
            discardc = true;
            if ( 0 == (t->c_lflag & NOFLSH) )
                size = 0;
            // raise could be a non-local jump - we should unlock mutex
            cyg_drv_mutex_unlock( &priv->lock );

            // FIXME: what if raise returns != 0?
            raise( SIGINT );
            cyg_drv_mutex_lock( &priv->lock );
        }

        if ( (t->c_lflag & ISIG) && (t->c_cc[ VQUIT ] == c) ) {
            discardc = true;
            if ( 0 == (t->c_lflag & NOFLSH) )
                size = 0;
            // raise could be a non-local jump - we should unlock mutex
            cyg_drv_mutex_unlock( &priv->lock );

            // FIXME: what if raise returns != 0?
            raise( SIGQUIT );
            cyg_drv_mutex_lock( &priv->lock );
        }
#endif
        if (!discardc) {
            buf[size++] = c;
            if ( t->c_lflag & ECHO ) {
                clen = 1;
                // FIXME: what about error or non-blocking?
                termios_write( handle, &c, &clen );
            }
        }

        if ( (t->c_lflag & ICANON) == 0 ) {
            // Check to see if read has been satisfied
            if ( t->c_cc[ VMIN ] && (size >= t->c_cc[ VMIN ]) )
                returnnow = true;
        }
        cyg_drv_mutex_unlock( &priv->lock );
    } // while

    *len = size;
    return ENOERR;
}
Esempio n. 10
0
void PropertiesDock::bringToFront()
{
    show();
    raise();
    mPropertyBrowser->setFocus();
}
Esempio n. 11
0
File: posix.cpp Progetto: Zoxc/mirb
		void NativeStream::print(const CharArray &string)
		{
			if(write(fd, string.str_ref(), string.size()) == -1)
				raise("Unable to write to file descriptor");
		}
Esempio n. 12
0
int jl_repl_raise_sigtstp(void)
{
    return raise(SIGTSTP);
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
    int ch, ret, sockfd;
    char ipstr[INET_ADDRSTRLEN];

    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    while ((ch = getopt(argc, argv, "46suh?")) != -1) {
        switch (ch) {
        case '4':
            hints.ai_family = AF_INET;
            break;
        case '6':
            hints.ai_family = AF_INET6;
            break;
        case 's':
            Flag_Stick_Around = true;
            break;
        case 'u':
            hints.ai_socktype = SOCK_DGRAM;
            break;
        case 'h':
        case '?':
        default:
            emit_help();
            /* NOTREACHED */
        }
    }
    argc -= optind;
    argv += optind;
    if (argc != 2)
        emit_help();

    setvbuf(stdout, (char *)NULL, _IOLBF, (size_t) 0);

    if ((ret = getaddrinfo(argv[0], argv[1], &hints, &res)) != 0)
        errx(EX_NOHOST, "getaddrinfo error: %s", gai_strerror(ret));
    for (remote = res; remote != NULL; remote = remote->ai_next) {
        if ((sockfd =
             socket(remote->ai_family, remote->ai_socktype,
                    remote->ai_protocol)) == -1) {
            warn("socket() error");
            continue;
        }
        /* Do need to connect first, unless you like seeing [::] or
         * 0.0.0.0 as your local address. */
        if (connect(sockfd, remote->ai_addr, remote->ai_addrlen) == -1) {
           warn("connect() error");
           continue;
        }
        break;
    }
    if (remote == NULL)
        errx(EX_IOERR, "could not connect to socket()");

    switch (remote->ai_family) {
    case AF_INET:
        if ((localsa = malloc(sizeof(struct sockaddr_in))) == NULL)
            err(EX_OSERR, "malloc() sockaddr_in failed");
        break;
    case AF_INET6:
        if ((localsa = malloc(sizeof(struct sockaddr_in6))) == NULL)
            err(EX_OSERR, "malloc() sockaddr_in6 failed");
        break;
    default:
        errx(EX_OSERR, "unknown address family???");
    }
    localsa_len = remote->ai_addrlen;

    if (getsockname(sockfd, localsa, &localsa_len) == -1)
        err(EX_OSERR, "getsockname() failed");

    switch (localsa->sa_family) {
    case AF_INET:
        inet_ntop(AF_INET, &(((struct sockaddr_in *) localsa)->sin_addr), ipstr,
                  localsa_len);
        printf("local %s:%u\n", ipstr,
               ntohs(((struct sockaddr_in *) localsa)->sin_port));
        break;
    case AF_INET6:
        inet_ntop(AF_INET6, &(((struct sockaddr_in6 *) localsa)->sin6_addr),
                  ipstr, localsa_len);
        printf("local [%s]:%u\n", ipstr,
               ntohs(((struct sockaddr_in6 *) localsa)->sin6_port));
        break;
    default:
        errx(EX_OSERR, "unknown address family???");
    }

    /* Cheap blocking trick. Then, presumably, `lsof -i -nP` or
     * `netstat` or something would be used to investigate what this
     * program has opened. `fg` will then bring the program back so
     * it can exit. */
    if (Flag_Stick_Around)
        raise(SIGTSTP);

    exit(EXIT_SUCCESS);
}
Esempio n. 14
0
/*---------------------------------------------------------------------+
|                               main ()                                |
| ==================================================================== |
|                                                                      |
| Function:  Main program  (see prolog for more details)               |
|                                                                      |
+---------------------------------------------------------------------*/
int main(int argc, char **argv)
{
	sigset_t newmask,	/* New signal mask */
	 oldmask,		/* Initial signal mask */
	 pendmask;		/* Pending signal mask */
	int i;			/* Loop index */

	/* Print out program header */
	printf("%s: IPC TestSuite program\n\n", *argv);

	/* Set up our signal handler */
	init_sig();

	/*
	 * Block ALL signals from interrupting the process
	 */
	printf("\tBlock all signals from interrupting the process\n");
	if (sigfillset(&newmask) < 0)
		error("sigfillset failed", __LINE__);
	if (sigprocmask(SIG_SETMASK, &newmask, &oldmask) < 0)
		error("sigprocmask failed", __LINE__);

	/*
	 * Send MAXSIG signals to the current process -- since ALL of the
	 * signals are blocked, none of the signals should interrupt the
	 * process
	 */
	printf("\n\tSend MAX (%d) SIGUSR1 signals to the process...\n", MAXSIG);
	for (i = 0; i < MAXSIG; i++)
		raise(SIGUSR1);

	/*
	 *  Sleep for a short time and the check to ensure that a SIGUSR1
	 *  signal is pending
	 */
	sleep(2);

	printf("\n\tEnsure at least one SIGUSR1 signal is pending\n");
	if (sigpending(&pendmask) < 0)
		error("sigpending failed", __LINE__);

	if (sigismember(&pendmask, SIGUSR1) == 0)
		error("sent multiple SIGUSR1 signals to process, "
		      "yet none are pending!", __LINE__);

	/*
	 * Change the signal mask to allow signals to interrupt the process
	 * and then suspend execution until a signal reaches the process
	 *
	 * Then verify that at least one signal was received
	 */
	printf("\n\tChange signal mask & wait for SIGUSR1 signal\n");
	if (sigsuspend(&oldmask) != -1 || errno != 4)
		error("sigsuspend failed", __LINE__);

	if (signals_received != 1) {
		printf("Signals are queued!  Sent %d signals, "
		       "while %d were queued\n", MAXSIG, signals_received);
	}

	/* Program completed successfully -- exit */
	printf("\nsuccessful!\n");
	return (0);
}
Esempio n. 15
0
/* main function */
int main()
{
	int ret;
	long rts;

	struct sigaction sa;

	/* Initialize output */
	output_init();

	/* Test the RTS extension */
	rts = sysconf(_SC_REALTIME_SIGNALS);

	if (rts < 0L)
	{
		UNTESTED("This test needs the RTS extension");
	}

	/* Set the signal handler */
	sa.sa_flags = SA_SIGINFO;

	sa.sa_sigaction = handler;

	ret = sigemptyset(&sa.sa_mask);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to empty signal set");
	}

	/* Install the signal handler for SIGHUP */
	ret = sigaction(SIGNAL, &sa, 0);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to set signal handler");
	}

	if (called)
	{
		FAILED("The signal handler has been called when no signal was raised");
	}

	ret = raise(SIGNAL);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to raise SIGHUP");
	}

	if (!called)
	{
		FAILED("the sa_handler was not called whereas SA_SIGINFO was not set");
	}

	/* Test passed */
#if VERBOSE > 0

	output("Test passed\n");

#endif

	PASSED;
}
Esempio n. 16
0
static void HandleUSR1(int sig)
{
    raise(SIGUSR2);
    raise(SIGUSR2);
}
Esempio n. 17
0
void Client::complete()
{
    WindowManager *wm = WindowManager::instance();
    xcb_connection_t* conn = wm->connection();
    xcb_ewmh_connection_t* ewmhConn = wm->ewmhConnection();
    if (mEwmhState.contains(ewmhConn->_NET_WM_STATE_STICKY)) {
        // don't put in layout
#warning support strut windows in layouts (reserved space)
#warning support partial struts
        Rect rect = wm->rect(mScreenNumber);
        if (mStrut.left) {
            if (mRect.width != static_cast<int>(mStrut.left))
                mRect.width = mStrut.left;
            mRect.x = rect.x;
            rect.x += mRect.width;
            rect.width -= mRect.width;
        } else if (mStrut.right) {
            if (mRect.width != static_cast<int>(mStrut.right))
                mRect.width = mStrut.right;
            mRect.x = rect.x + rect.width - mStrut.right;
            rect.width -= mStrut.right;
        } else if (mStrut.top) {
            if (mRect.height != static_cast<int>(mStrut.top))
                mRect.height = mStrut.top;
            mRect.y = rect.y;
            rect.y += mRect.height;
            rect.height -= mRect.height;
        } else if (mStrut.bottom) {
            if (mRect.height != static_cast<int>(mStrut.bottom))
                mRect.height = mStrut.bottom;
            mRect.y = rect.y + rect.height - mStrut.bottom;
            rect.height -= mStrut.bottom;
        }
        wm->setRect(rect, mScreenNumber);
        warning() << "fixed at" << mRect;
    } else {
        if (shouldLayout()) {
            wm->js().onLayout(this);
            warning() << "laid out at" << mRect;
        }
    }
#warning do startup-notification stuff here
    if (!mOwned)
        xcb_change_save_set(conn, XCB_SET_MODE_INSERT, mWindow);
    xcb_screen_t* scr = screen();
    mFrame = xcb_generate_id(conn);
    const uint32_t values[] = {
        scr->black_pixel,
        XCB_GRAVITY_NORTH_WEST,
        XCB_GRAVITY_NORTH_WEST,
        1,
        (XCB_EVENT_MASK_STRUCTURE_NOTIFY
         | XCB_EVENT_MASK_ENTER_WINDOW
         | XCB_EVENT_MASK_LEAVE_WINDOW
         | XCB_EVENT_MASK_EXPOSURE
         | XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT
         | XCB_EVENT_MASK_POINTER_MOTION
         | XCB_EVENT_MASK_BUTTON_PRESS
         | XCB_EVENT_MASK_BUTTON_RELEASE)
    };
    warning() << "creating frame window" << mRect;
    xcb_create_window(conn, XCB_COPY_FROM_PARENT, mFrame, scr->root,
                      mRect.x, mRect.y, mRect.width, mRect.height, 0,
                      XCB_COPY_FROM_PARENT, XCB_COPY_FROM_PARENT,
                      XCB_CW_BORDER_PIXEL | XCB_CW_BIT_GRAVITY | XCB_CW_WIN_GRAVITY
                      | XCB_CW_OVERRIDE_REDIRECT | XCB_CW_EVENT_MASK, values);
    {
        ServerGrabScope grabScope(conn);
        const uint32_t noValue[] = { 0 };
        xcb_change_window_attributes(conn, scr->root, XCB_CW_EVENT_MASK, noValue);
        xcb_reparent_window(conn, mWindow, mFrame, 0, 0);
        const uint32_t rootEvent[] = { Types::RootEventMask };
        xcb_change_window_attributes(conn, scr->root, XCB_CW_EVENT_MASK, rootEvent);
        xcb_grab_button(conn, false, mWindow, XCB_EVENT_MASK_BUTTON_PRESS,
                        XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC, scr->root,
                        XCB_NONE, 1, XCB_BUTTON_MASK_ANY);
        const uint32_t windowEvent[] = { Types::ClientInputMask };
        xcb_change_window_attributes(conn, mWindow, XCB_CW_EVENT_MASK, windowEvent);
    }

    {
        uint16_t windowMask = XCB_CONFIG_WINDOW_WIDTH|XCB_CONFIG_WINDOW_HEIGHT|XCB_CONFIG_WINDOW_BORDER_WIDTH;
        uint32_t windowValues[3];
        int i = 0;
        windowValues[i++] = mRect.width;
        windowValues[i++] = mRect.height;
        windowValues[i++] = 0;
        xcb_configure_window(conn, mWindow, windowMask, windowValues);
    }

#warning do xinerama placement
    const uint32_t stateMode[] = { XCB_ICCCM_WM_STATE_NORMAL, XCB_NONE };
    xcb_change_property(conn, XCB_PROP_MODE_REPLACE, mWindow, Atoms::WM_STATE, Atoms::WM_STATE, 32, 2, stateMode);

    map();
    raise();
    warning() << "created and mapped parent client for frame" << mFrame << "with window" << mWindow;
}
Esempio n. 18
0
void sigsegv(int sig, siginfo_t *info, void * uap) {
    signal(sig,SIG_DFL); //reset signal to default, just in case traceback itself crashes
    terratraceback(uap);  //call terra's pretty traceback
    raise(sig);   //rethrow the signal to the default handler
}
Esempio n. 19
0
static void wait_for_pager_signal(int signo)
{
	wait_for_pager(1);
	sigchain_pop(signo);
	raise(signo);
}
Esempio n. 20
0
void Progress::tic()
{
    setProgress(++n);
    raise();
    app->processEvents();
}
Esempio n. 21
0
File: main.c Progetto: aztrock/wmii
int
main(int argc, char *argv[]) {
	char *wmiirc;
	WMScreen *s;
	WinAttr wa;
	int i;

	fmtinstall('r', errfmt);
	fmtinstall('C', Cfmt);

	wmiirc = "wmiistartrc";

	ARGBEGIN{
	case 'v':
		print("%s", version);
		exit(0);
	case 'V':
		verbose = True;
		break;
	case 'a':
		address = EARGF(usage());
		break;
	case 'r':
		wmiirc = EARGF(usage());
		break;
	default:
		usage();
		break;
	}ARGEND;

	if(argc)
		usage();

	setlocale(LC_CTYPE, "");
	starting = True;

	initdisplay();

	xlib_errorhandler = XSetErrorHandler(errorhandler);

	check_other_wm = True;
	XSelectInput(display, scr.root.w,
			  SubstructureRedirectMask
			| EnterWindowMask);
	XSync(display, False);

	check_other_wm = False;

	passwd = getpwuid(getuid());
	user = estrdup(passwd->pw_name);

	init_environment();

	sock = ixp_announce(address);
	if(sock < 0)
		fatal("Can't create socket '%s': %r", address);

	if(wmiirc)
		spawn_command(wmiirc);

	init_traps();
	init_atoms();
	init_cursors();
	init_lock_keys();

	srv.preselect = check_preselect;
	ixp_listen(&srv, sock, &p9srv, serve_9pcon, nil);
	ixp_listen(&srv, ConnectionNumber(display), nil, check_x_event, closedisplay);

	def.font = loadfont(FONT);
	def.border = 1;
	def.colmode = Coldefault;

	def.mod = Mod1Mask;
	strcpy(def.grabmod, "Mod1");

	loadcolor(&def.focuscolor, FOCUSCOLORS);
	loadcolor(&def.normcolor, NORMCOLORS);

	num_screens = 1;
	screens = emallocz(num_screens * sizeof(*screens));
	screen = &screens[0];
	for(i = 0; i < num_screens; i++) {
		s = &screens[i];
		init_screen(s);

		s->ibuf = allocimage(Dx(s->r), Dy(s->r), scr.depth);

		wa.event_mask = 
				  SubstructureRedirectMask
				| SubstructureNotifyMask
				| EnterWindowMask
				| LeaveWindowMask
				| FocusChangeMask;
		wa.cursor = cursor[CurNormal];
		setwinattr(&scr.root, &wa,
				  CWEventMask
				| CWCursor);
		initbar(s);
	}

	screen->focus = nil;
	setfocus(screen->barwin, RevertToParent);

	scan_wins();
	starting = False;

	select_view("nil");
	update_views();
	write_event("FocusTag %s\n", screen->sel->name);

	check_x_event(nil);
	i = ixp_serverloop(&srv);
	if(i)
		fprint(2, "%s: error: %r\n", argv0);

	cleanup();

	if(exitsignal)
		raise(exitsignal);
	if(execstr)
		execl("/bin/sh", "sh", "-c", execstr, nil);
	return i;
}
Esempio n. 22
0
int main(int argc, char **argv) {
  char *gidmap = NULL, *inside = NULL, *outside = NULL, *uidmap = NULL;
  int hostnet = 0, master, option, stdio = 0;
  pid_t child, parent;

  while ((option = getopt(argc, argv, "+:cg:i:no:u:")) > 0)
    switch (option) {
      case 'c':
        stdio++;
        break;
      case 'g':
        gidmap = optarg;
        break;
      case 'i':
        inside = optarg;
        break;
      case 'n':
        hostnet++;
        break;
      case 'o':
        outside = optarg;
        break;
      case 'u':
        uidmap = optarg;
        break;
      default:
        usage(argv[0]);
    }

  if (argc <= optind)
    usage(argv[0]);

  parent = getpid();
  switch (child = fork()) {
    case -1:
      error(1, errno, "fork");
    case 0:
      raise(SIGSTOP);
      if (geteuid() != 0)
        denysetgroups(parent);
      writemap(parent, GID, gidmap);
      writemap(parent, UID, uidmap);

      if (outside) {
        if (setgid(getgid()) < 0 || setuid(getuid()) < 0)
          error(1, 0, "Failed to drop privileges");
        execlp(SHELL, SHELL, "-c", outside, NULL);
        error(1, errno, "exec %s", outside);
      }

      exit(EXIT_SUCCESS);
  }

  if (setgid(getgid()) < 0 || setuid(getuid()) < 0)
    error(1, 0, "Failed to drop privileges");

  if (unshare(CLONE_NEWIPC | CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS) < 0)
    error(1, 0, "Failed to unshare namespaces");

  if (!hostnet && unshare(CLONE_NEWNET) < 0)
      error(1, 0, "Failed to unshare network namespace");

  waitforstop(child);
  kill(child, SIGCONT);
  waitforexit(child);

  setgid(0);
  setgroups(0, NULL);
  setuid(0);

  master = stdio ? -1 : getconsole();
  createroot(argv[optind], master, inside);

  unshare(CLONE_NEWPID);
  switch (child = fork()) {
    case -1:
      error(1, errno, "fork");
    case 0:
      mountproc();
      if (!hostnet)
        mountsys();
      enterroot();

      if (master >= 0) {
        close(master);
        setconsole("/dev/console");
      }

      clearenv();
      putenv("container=contain");

      if (argv[optind + 1])
        execv(argv[optind + 1], argv + optind + 1);
      else
        execl(SHELL, SHELL, NULL);
      error(1, errno, "exec");
  }

  return supervise(child, master);
}
Esempio n. 23
0
static void handle_children_on_signal(int signo)
{
    kill_children(pp_for_signal, signo);
    sigchain_pop(signo);
    raise(signo);
}
Esempio n. 24
0
/* The main test function. */
int main(int argc, char * argv[])
{
	int ret, i, sig;
	long rts;
	sigset_t set;

	/* Initialize output */
	output_init();

	/* Test the RTS extension */
	rts = sysconf(_SC_REALTIME_SIGNALS);

	if (rts < 0L)
	{
		UNTESTED("This test needs the RTS extension");
	}

	/* Set the signal mask */
	ret = sigemptyset(&set);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to empty signal set");
	}

	/* Add all SIGRT signals */
	for (i = SIGRTMIN; i <= SIGRTMAX; i++)
	{

		ret = sigaddset(&set, i);

		if (ret != 0)
		{
			UNRESOLVED(ret, "failed to add signal to signal set");
		}
	}

	/* Block all RT signals */
	ret = pthread_sigmask(SIG_BLOCK, &set, NULL);

	if (ret != 0)
	{
		UNRESOLVED(ret, "Failed to block RT signals");
	}

	/* raise the signals in no particular order */
	for (i = SIGRTMIN + 1; i <= SIGRTMAX; i += 3)
	{
		ret = raise(i);

		if (ret != 0)
		{
			UNRESOLVED(ret, "Failed to raise the signal");
		}
	}

	for (i = SIGRTMIN; i <= SIGRTMAX; i += 3)
	{
		ret = raise(i);

		if (ret != 0)
		{
			UNRESOLVED(ret, "Failed to raise the signal");
		}
	}

	for (i = SIGRTMIN + 2; i <= SIGRTMAX; i += 3)
	{
		ret = raise(i);

		if (ret != 0)
		{
			UNRESOLVED(ret, "Failed to raise the signal");
		}
	}

	/* All RT signals are pending */

	/* Check the signals are delivered in order */
	for (i = SIGRTMIN; i <= SIGRTMAX; i++)
	{
		ret = sigwait(&set, &sig);

		if (ret != 0)
		{
			UNRESOLVED(ret , "Failed to sigwait for RT signal");
		}

		if (sig != i)
		{
			output("SIGRTMIN: %d, SIGRTMAX: %d, i: %d, sig:%d\n",
			        SIGRTMIN, SIGRTMAX, i, sig);
			FAILED("Got wrong signal");
		}
	}

	/* Test passed */
#if VERBOSE > 0
	output("Test passed\n");

#endif
	PASSED;
}
Esempio n. 25
0
void JavaExecuter::run() {
    init();

    std::string workingDir = combineString(Config::getInstant()->getTmpUserPath(), DIR_SEPARTOR, runId);
   
    int port = 0, status;
    int server_sock = CreateServerSocket(&port);
    struct sockaddr_un un;
    socklen_t len = sizeof(un);

    if(server_sock < 0) {
        BLOG("JavaExecuter::run(): create server sock error", SYSCALL_ERROR);
        this->_result = SERVER_ERROR;
        return;
    }

    pid_t pid = fork();

    if(pid < 0) {
        BLOG("JavaExecuter::run() fork error", SYSCALL_ERROR);
        this->_result = SERVER_ERROR;
        return;
    }

    if(pid == 0) {
        close(server_sock);

        if(chdir(workingDir.c_str()) == -1) {
            LLOG("Fail to change working dir to " + workingDir, SYSCALL_ERROR);
            raise(SIGKILL);
            return;
        }
        
        std::string rootPath = Config::getInstant()->getRootPath();
        if(stdinFileName[0] != '/' && stdinFileName[0] != '.') {
            stdinFileName = rootPath + stdinFileName;
        }
        if(stdoutFileName[0] != '/' && stdoutFileName[0] != '/') {
            stdoutFileName = rootPath + stdoutFileName;
        }

        std::string minMem = combineString("-Xms", limitMemory / 2 + 200, 'k');
        std::string maxMem = combineString("-Xmx", limitMemory + 200, 'k');
        std::string javaLib = combineString("-Djava.library.path=", rootPath, "bin"); 
        std::string jarPath = combineString(rootPath, "bin/JavaSandbox.jar");
        std::string portStr = combineString(port);
        std::string limitTimeStr = combineString(limitTime);
        std::string limitMemoryStr = combineString(limitMemory);
        std::string limitOutputStr = combineString(limitOutput);
        std::string uidStr = combineString(Config::getInstant()->getJobUID());
        std::string gidStr = combineString(Config::getInstant()->getJobGID());

        for(int i = 0; i < 100; i++) close(i);

        execlp("java",
                minMem.c_str(),
                maxMem.c_str(),
                javaLib.c_str(),
                "-jar",
                jarPath.c_str(),
                portStr.c_str(),
                limitTimeStr.c_str(),
                limitMemoryStr.c_str(),
                limitOutputStr.c_str(),
                uidStr.c_str(),
                gidStr.c_str(),
                stdinFileName.c_str(),
                stdoutFileName.c_str(),
                NULL);

        LLOG("JavaExecuter()::run() Fail to run java", SYSCALL_ERROR);
        exit(-1);
    } else {
        //parent
        while(1) {
            //the accept function will be interuppted by the SIGCHLD signal
            int client_sock = accept(server_sock, (struct sockaddr*)&un, &len);

            if(client_sock < 0) {
                if(errno != EINTR) {
                    BLOG("JavaExecuter::run() fail to accept", SYSCALL_ERROR);
                    close(server_sock);
                    this->_result = SERVER_ERROR;
                    return;
                }else if(waitpid(pid, &status, WNOHANG) > 0) {
                    break;
                }
            } else {
                unsigned int _time, _memory;
                while(ReadUint32(client_sock, &_time) >= 0 &&
                    ReadUint32(client_sock, &_memory) >= 0) {
                    this->_runnedTime = _time;
                    this->_runnedMemory = _memory;
                    judgeThread->updateRunInfo(_time, _memory);
                }
                close(client_sock);
                while(waitpid(pid, &status, 0) < 0 && errno != ECHILD) {
                
                }
                break;
            }
        }
        close(server_sock);

        if(WIFSIGNALED(status)) {
            switch(WTERMSIG(status)) {
                case SIGXCPU:
                    this->_result = TIME_LIMIT_EXCEEDED;
                    break;
                default:
                    DLOG(ERROR) << "Java process was terminated by signal " << WTERMSIG(status);
                    this->_result = RUNTIME_ERROR;
            }
        } else {
            this->_result = WEXITSTATUS(status);
            if(this->_result == 1) {
                this->_result = SERVER_ERROR;
            }else{
                if(this->_result)
                    this->_result += 1000;
            }

            if(this->_result == 0) {
                this->_result = TraceProcess::NORMAL;
                if(this->_runnedMemory > limitMemory) {
                    this->_result = MEMORY_LIMIT_EXCEEDED;
                }

                if(this->_runnedTime > limitTime) {
                    this->_result = TIME_LIMIT_EXCEEDED;
                }
            }
        }
    }
}
Esempio n. 26
0
ExportObjectDialog::ExportObjectDialog(QWidget &parent, CaptureFile &cf, ObjectType object_type) :
    WiresharkDialog(parent, cf),
    eo_ui_(new Ui::ExportObjectDialog),
    save_bt_(NULL),
    save_all_bt_(NULL),
    tap_name_(NULL),
    name_(NULL),
    tap_packet_(NULL),
    eo_protocoldata_resetfn_(NULL)
{
    QPushButton *close_bt;

    eo_ui_->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose, true);

#if defined(Q_OS_MAC)
    eo_ui_->progressLabel->setAttribute(Qt::WA_MacSmallSize, true);
    eo_ui_->progressBar->setAttribute(Qt::WA_MacSmallSize, true);
#endif

    export_object_list_.eod = this;

    switch (object_type) {
    case Dicom:
        tap_name_ = "dicom_eo";
        name_ = "DICOM";
        tap_packet_ = eo_dicom_packet;
        break;
    case Http:
        tap_name_ = "http_eo";
        name_ = "HTTP";
        tap_packet_ = eo_http_packet;
        break;
    case Smb:
        tap_name_ = "smb_eo";
        name_ = "SMB";
        tap_packet_ = eo_smb_packet;
        eo_protocoldata_resetfn_ = eo_smb_cleanup;
        break;
    case Tftp:
        tap_name_ = "tftp_eo";
        name_ = "TFTP";
        tap_packet_ = eo_tftp_packet;
        break;
    }

    save_bt_ = eo_ui_->buttonBox->button(QDialogButtonBox::Save);
    save_all_bt_ = eo_ui_->buttonBox->button(QDialogButtonBox::SaveAll);
    close_bt = eo_ui_->buttonBox->button(QDialogButtonBox::Close);

    setWindowTitle(wsApp->windowTitleString(QStringList() << tr("Export") << tr("%1 object list").arg(name_)));

    if (save_bt_) save_bt_->setEnabled(false);
    if (save_all_bt_) save_all_bt_->setEnabled(false);
    if (close_bt) close_bt->setDefault(true);

    connect(&cap_file_, SIGNAL(captureFileClosing()), this, SLOT(captureFileClosing()));

    show();
    raise();
    activateWindow();
}
Esempio n. 27
0
JL_DLLEXPORT int jl_repl_raise_sigtstp(void)
{
    return raise(SIGTSTP);
}
Esempio n. 28
0
static void ui_suspend(Ui *ui) {
	endwin();
	raise(SIGSTOP);
}
Esempio n. 29
0
void KstMonochromeDialogI::showMonochromeDialog() {
  updateMonochromeDialog();
  show();
  raise();
}
Esempio n. 30
0
/* This function is called when a segmentation fault is caught.  The system
   is in an instable state now.  This means especially that malloc() might
   not work anymore.  */
static void
catch_segfault (int signal, SIGCONTEXT ctx)
{
    struct layout *current;
    void *__unbounded top_frame;
    void *__unbounded top_stack;
    int fd;
    void **arr;
    size_t cnt;
    struct sigaction sa;

    /* This is the name of the file we are writing to.  If none is given
       or we cannot write to this file write to stderr.  */
    fd = 2;
    if (fname != NULL)
    {
        fd = open (fname, O_TRUNC | O_WRONLY | O_CREAT, 0666);
        if (fd == -1)
            fd = 2;
    }

    WRITE_STRING ("*** ");
    write_strsignal (fd, signal);
    WRITE_STRING ("\n");

#ifdef REGISTER_DUMP
    REGISTER_DUMP;
#endif

    WRITE_STRING ("\nBacktrace:\n");

    top_frame = GET_FRAME (ctx);
    top_stack = GET_STACK (ctx);

    /* First count how many entries we'll have.  */
    cnt = 1;
    current = BOUNDED_1 ((struct layout *) top_frame);
    while (!((void *) current INNER_THAN top_stack
             || !((void *) current INNER_THAN __libc_stack_end)))
    {
        ++cnt;

        current = ADVANCE_STACK_FRAME (current->next);
    }

    arr = alloca (cnt * sizeof (void *));

    /* First handle the program counter from the structure.  */
    arr[0] = GET_PC (ctx);

    current = BOUNDED_1 ((struct layout *) top_frame);
    cnt = 1;
    while (!((void *) current INNER_THAN top_stack
             || !((void *) current INNER_THAN __libc_stack_end)))
    {
        arr[cnt++] = current->return_address;

        current = ADVANCE_STACK_FRAME (current->next);
    }

    /* If the last return address was NULL, assume that it doesn't count.  */
    if (arr[cnt-1] == NULL)
        cnt--;

    /* Now generate nicely formatted output.  */
    __backtrace_symbols_fd (arr, cnt, fd);

    /* Pass on the signal (so that a core file is produced).  */
    sa.sa_handler = SIG_DFL;
    sigemptyset (&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction (signal, &sa, NULL);
    raise (signal);
}