Example #1
0
static llvm::StringRef substrBefore(llvm::StringRef whole,
                                    llvm::StringRef part) {
  return whole.slice(0, part.data() - whole.data());
}
Example #2
0
Error
Socket::TcpListen (llvm::StringRef host_and_port,
                   bool child_processes_inherit,
                   Socket *&socket,
                   Predicate<uint16_t>* predicate,
                   int backlog)
{
    std::unique_ptr<Socket> listen_socket;
    NativeSocket listen_sock = kInvalidSocketValue;
    Error error;

    const sa_family_t family = AF_INET;
    const int socktype = SOCK_STREAM;
    const int protocol = IPPROTO_TCP;
    listen_sock = ::CreateSocket (family, socktype, protocol, child_processes_inherit);
    if (listen_sock == kInvalidSocketValue)
    {
        SetLastError (error);
        return error;
    }

    listen_socket.reset(new Socket(listen_sock, ProtocolTcp, true));

    // enable local address reuse
    listen_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);

    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
    if (log)
        log->Printf ("Socket::TcpListen (%s)", host_and_port.data());

    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
        return error;

    SocketAddress bind_addr;
    bool bind_addr_success = false;

    // Only bind to the loopback address if we are expecting a connection from
    // localhost to avoid any firewall issues.
    if (host_str == "127.0.0.1")
        bind_addr_success = bind_addr.SetToLocalhost (family, port);
    else
        bind_addr_success = bind_addr.SetToAnyAddress (family, port);

    if (bind_addr_success)
    {
        int err = ::bind (listen_sock, bind_addr, bind_addr.GetLength());
        if (err == -1)
        {
            SetLastError (error);
            return error;
        }

        err = ::listen (listen_sock, backlog);
        if (err == -1)
        {
            SetLastError (error);
            return error;
        }

        // We were asked to listen on port zero which means we
        // must now read the actual port that was given to us
        // as port zero is a special code for "find an open port
        // for me".
        if (port == 0)
            port = listen_socket->GetLocalPortNumber();

        // Set the port predicate since when doing a listen://<host>:<port>
        // it often needs to accept the incoming connection which is a blocking
        // system call. Allowing access to the bound port using a predicate allows
        // us to wait for the port predicate to be set to a non-zero value from
        // another thread in an efficient manor.
        if (predicate)
            predicate->SetValue (port, eBroadcastAlways);

        socket = listen_socket.release();
    }

    return error;
}
Example #3
0
Error Socket::UdpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&send_socket, Socket *&recv_socket)
{
    std::unique_ptr<Socket> final_send_socket;
    std::unique_ptr<Socket> final_recv_socket;
    NativeSocket final_send_fd = kInvalidSocketValue;
    NativeSocket final_recv_fd = kInvalidSocketValue;

    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_CONNECTION));
    if (log)
        log->Printf ("Socket::UdpConnect (host/port = %s)", host_and_port.data());

    Error error;
    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
        return error;

    // Setup the receiving end of the UDP connection on this localhost
    // on port zero. After we bind to port zero we can read the port.
    final_recv_fd = ::CreateSocket (AF_INET, SOCK_DGRAM, 0, child_processes_inherit);
    if (final_recv_fd == kInvalidSocketValue)
    {
        // Socket creation failed...
        SetLastError (error);
    }
    else
    {
        final_recv_socket.reset(new Socket(final_recv_fd, ProtocolUdp, true));

        // Socket was created, now lets bind to the requested port
        SocketAddress addr;
        addr.SetToAnyAddress (AF_INET, 0);

        if (::bind (final_recv_fd, addr, addr.GetLength()) == -1)
        {
            // Bind failed...
            SetLastError (error);
        }
    }

    assert(error.Fail() == !(final_recv_socket && final_recv_socket->IsValid()));
    if (error.Fail())
        return error;

    // At this point we have setup the receive port, now we need to 
    // setup the UDP send socket

    struct addrinfo hints;
    struct addrinfo *service_info_list = NULL;

    ::memset (&hints, 0, sizeof(hints)); 
    hints.ai_family = AF_INET; 
    hints.ai_socktype = SOCK_DGRAM;
    int err = ::getaddrinfo (host_str.c_str(), port_str.c_str(), &hints, &service_info_list);
    if (err != 0)
    {
        error.SetErrorStringWithFormat("getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)", 
                                       host_str.c_str(), 
                                       port_str.c_str(),
                                       err,
                                       gai_strerror(err));
        return error;        
    }

    for (struct addrinfo *service_info_ptr = service_info_list; 
         service_info_ptr != NULL; 
         service_info_ptr = service_info_ptr->ai_next) 
    {
        final_send_fd = ::CreateSocket (service_info_ptr->ai_family,
                                        service_info_ptr->ai_socktype,
                                        service_info_ptr->ai_protocol,
                                        child_processes_inherit);

        if (final_send_fd != kInvalidSocketValue)
        {
            final_send_socket.reset(new Socket(final_send_fd, ProtocolUdp, true));
            final_send_socket->m_udp_send_sockaddr = service_info_ptr;
            break;
        }
        else
            continue;
    }

    :: freeaddrinfo (service_info_list);

    if (final_send_fd == kInvalidSocketValue)
    {
        SetLastError (error);
        return error;
    }

    send_socket = final_send_socket.release();
    recv_socket = final_recv_socket.release();
    error.Clear();
    return error;
}
Example #4
0
Error
PipePosix::Delete(llvm::StringRef name)
{
    return FileSystem::Unlink(FileSpec{name.data(), true});
}
Example #5
0
Error Socket::TcpConnect(llvm::StringRef host_and_port, bool child_processes_inherit, Socket *&socket)
{
    // Store the result in a unique_ptr in case we error out, the memory will get correctly freed.
    std::unique_ptr<Socket> final_socket;
    NativeSocket sock = kInvalidSocketValue;
    Error error;

    Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION));
    if (log)
        log->Printf ("Socket::TcpConnect (host/port = %s)", host_and_port.data());

    std::string host_str;
    std::string port_str;
    int32_t port = INT32_MIN;
    if (!DecodeHostAndPort (host_and_port, host_str, port_str, port, &error))
        return error;

    // Create the socket
    sock = CreateSocket (AF_INET, SOCK_STREAM, IPPROTO_TCP, child_processes_inherit);
    if (sock == kInvalidSocketValue)
    {
        SetLastError (error);
        return error;
    }

    // Since they both refer to the same socket descriptor, arbitrarily choose the send socket to
    // be the owner.
    final_socket.reset(new Socket(sock, ProtocolTcp, true));

    // Enable local address reuse
    final_socket->SetOption(SOL_SOCKET, SO_REUSEADDR, 1);

    struct sockaddr_in sa;
    ::memset (&sa, 0, sizeof (sa));
    sa.sin_family = AF_INET;
    sa.sin_port = htons (port);

    int inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);

    if (inet_pton_result <= 0)
    {
        struct hostent *host_entry = gethostbyname (host_str.c_str());
        if (host_entry)
            host_str = ::inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
        inet_pton_result = ::inet_pton (AF_INET, host_str.c_str(), &sa.sin_addr);
        if (inet_pton_result <= 0)
        {
            if (inet_pton_result == -1)
                SetLastError(error);
            else
                error.SetErrorStringWithFormat("invalid host string: '%s'", host_str.c_str());

            return error;
        }
    }

    if (-1 == ::connect (sock, (const struct sockaddr *)&sa, sizeof(sa)))
    {
        SetLastError (error);
        return error;
    }

    // Keep our TCP packets coming without any delays.
    final_socket->SetOption(IPPROTO_TCP, TCP_NODELAY, 1);
    error.Clear();
    socket = final_socket.release();
    return error;
}
 // Is this 'description' valid?
 operator bool() const {
   return Abbrev != nullptr && Name.data() != nullptr && !Name.empty();
 }
Example #7
0
  InputValidator::ValidationResult
  InputValidator::validate(llvm::StringRef line) {
    ValidationResult Res = kComplete;

    Token Tok;
    const char* curPos = line.data();
    do {
      MetaLexer::LexPunctuatorAndAdvance(curPos, Tok);
      int kind = (int)Tok.getKind();

      // if (kind == tok::hash) {
      //   // Handle #ifdef ...
      //   //          ...
      //   //        #endif
      //   MetaLexer Lexer(curPos);
      //   Lexer.Lex(Tok);
      //   if (Tok.getKind() == tok::ident) {
      //     if (Tok.getIdent().startswith("if")) {
      //       Res = kIncomplete;
      //       m_ParenStack.push_back(kind);
      //     }
      //     else if (Tok.getIdent().startswith("end")) {
      //       assert(m_ParenStack.back() == kind && "No coresponding # to pop?");
      //       m_ParenStack.pop_back();
      //     }
      //   }
      // }

      if (kind >= (int)tok::stringlit && kind <= (int)tok::charlit) {
        MetaLexer::LexQuotedStringAndAdvance(curPos, Tok);
      } else

      // In case when we need closing brace.
      if (kind >= (int)tok::l_square && kind <= (int)tok::r_brace) {
        // The closing paren kind is open paren kind + 1 (i.e odd number)
        if (kind % 2) {
          // closing the right one?
          if (m_ParenStack.empty()) {
            Res = kMismatch;
            break;
          }
          int prev = m_ParenStack.back();
          if (prev != kind - 1) {
            Res = kMismatch;
            break;
          }
          m_ParenStack.pop_back();
        }
        else
          m_ParenStack.push_back(kind);
      }
    }
    while (Tok.isNot(tok::eof));

    if (!m_ParenStack.empty() && Res != kMismatch)
      Res = kIncomplete;

    if (!m_Input.empty()) {
      if (!m_ParenStack.empty() && (m_ParenStack.back() == tok::stringlit
                                    || m_ParenStack.back() == tok::charlit))
        m_Input.append("\\n");
      else
        m_Input.append("\n");
    }
    else
      m_Input = "";

    m_Input.append(line);

    return Res;
  }
Example #8
0
bool CudaDeviceAction::IsValidGpuArchName(llvm::StringRef ArchName) {
  return GpuArchToComputeName(ArchName.data()) != nullptr;
}
Example #9
0
void StringEntry<llvm::StringRef>::setValue(llvm::StringRef pVal) {
  char* data = reinterpret_cast<char*>(malloc(pVal.size() + 1));
  strcpy(data, pVal.data());
  m_Value = llvm::StringRef(data, pVal.size());
}
Example #10
0
Error
PipePosix::Delete(llvm::StringRef name)
{
    return FileSystem::Unlink(name.data());
}
Example #11
0
static void ConvertToC(llvm::StringRef in, char** out) {
  *out = static_cast<char*>(std::malloc(in.size() + 1));
  std::memmove(*out, in.data(), in.size());
  (*out)[in.size()] = '\0';
}
Example #12
0
 MetaLexer::MetaLexer(llvm::StringRef line) 
   : bufferStart(line.data()), curPos(line.data()) 
 { }
Example #13
0
EventDataBytes::EventDataBytes(llvm::StringRef str) : m_bytes() {
  SetBytes(str.data(), str.size());
}
Example #14
0
  // Add the input to the memory buffer, parse it, and add it to the AST.
  IncrementalParser::EParseResult
  IncrementalParser::ParseInternal(llvm::StringRef input) {
    if (input.empty()) return IncrementalParser::kSuccess;

    Sema& S = getCI()->getSema();

    const CompilationOptions& CO
       = m_Consumer->getTransaction()->getCompilationOpts();

    assert(!(S.getLangOpts().Modules
             && CO.CodeGenerationForModule)
           && "CodeGenerationForModule to be removed once PCMs are available!");

    // Recover resources if we crash before exiting this method.
    llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);

    Preprocessor& PP = m_CI->getPreprocessor();
    if (!PP.getCurrentLexer()) {
       PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),
                          0, SourceLocation());
    }
    assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
    PP.enableIncrementalProcessing();

    smallstream source_name;
    source_name << "input_line_" << (m_MemoryBuffers.size() + 1);

    // Create an uninitialized memory buffer, copy code in and append "\n"
    size_t InputSize = input.size(); // don't include trailing 0
    // MemBuffer size should *not* include terminating zero
    std::unique_ptr<llvm::MemoryBuffer>
      MB(llvm::MemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
                                                   source_name.str()));
    char* MBStart = const_cast<char*>(MB->getBufferStart());
    memcpy(MBStart, input.data(), InputSize);
    MBStart[InputSize] = '\n';

    SourceManager& SM = getCI()->getSourceManager();

    // Create SourceLocation, which will allow clang to order the overload
    // candidates for example
    SourceLocation NewLoc = getLastMemoryBufferEndLoc().getLocWithOffset(1);

    llvm::MemoryBuffer* MBNonOwn = MB.get();

    // Create FileID for the current buffer.
    FileID FID;
    // Create FileEntry and FileID for the current buffer.
    // Enabling the completion point only works on FileEntries.
    const clang::FileEntry* FE
      = SM.getFileManager().getVirtualFile(source_name.str(), InputSize,
                                           0 /* mod time*/);
    SM.overrideFileContents(FE, std::move(MB));
    FID = SM.createFileID(FE, NewLoc, SrcMgr::C_User);
    if (CO.CodeCompletionOffset != -1) {
      // The completion point is set one a 1-based line/column numbering.
      // It relies on the implementation to account for the wrapper extra line.
      PP.SetCodeCompletionPoint(FE, 1/* start point 1-based line*/,
                                CO.CodeCompletionOffset+1/* 1-based column*/);
    }

    m_MemoryBuffers.push_back(std::make_pair(MBNonOwn, FID));

    // NewLoc only used for diags.
    PP.EnterSourceFile(FID, /*DirLookup*/0, NewLoc);
    m_Consumer->getTransaction()->setBufferFID(FID);

    DiagnosticsEngine& Diags = getCI()->getDiagnostics();

    FilteringDiagConsumer::RAAI RAAITmp(*m_DiagConsumer, CO.IgnorePromptDiags);

    DiagnosticErrorTrap Trap(Diags);
    Sema::SavePendingInstantiationsRAII SavedPendingInstantiations(S);

    Parser::DeclGroupPtrTy ADecl;
    while (!m_Parser->ParseTopLevelDecl(ADecl)) {
      // If we got a null return and something *was* parsed, ignore it.  This
      // is due to a top-level semicolon, an action override, or a parse error
      // skipping something.
      if (Trap.hasErrorOccurred())
        m_Consumer->getTransaction()->setIssuedDiags(Transaction::kErrors);
      if (ADecl)
        m_Consumer->HandleTopLevelDecl(ADecl.get());
    };
    // If never entered the while block, there's a chance an error occured
    if (Trap.hasErrorOccurred())
      m_Consumer->getTransaction()->setIssuedDiags(Transaction::kErrors);

    if (CO.CodeCompletionOffset != -1) {
      assert((int)SM.getFileOffset(PP.getCodeCompletionLoc())
             == CO.CodeCompletionOffset
             && "Completion point wrongly set!");
      assert(PP.isCodeCompletionReached()
             && "Code completion set but not reached!");

      // Let's ignore this transaction:
      m_Consumer->getTransaction()->setIssuedDiags(Transaction::kErrors);

      return kSuccess;
    }

#ifdef LLVM_ON_WIN32
    // Microsoft-specific:
    // Late parsed templates can leave unswallowed "macro"-like tokens.
    // They will seriously confuse the Parser when entering the next
    // source file. So lex until we are EOF.
    Token Tok;
    do {
      PP.Lex(Tok);
    } while (Tok.isNot(tok::eof));
#endif

#ifndef NDEBUG
    Token AssertTok;
    PP.Lex(AssertTok);
    assert(AssertTok.is(tok::eof) && "Lexer must be EOF when starting incremental parse!");
#endif

    // Process any TopLevelDecls generated by #pragma weak.
    for (llvm::SmallVector<Decl*,2>::iterator I = S.WeakTopLevelDecls().begin(),
         E = S.WeakTopLevelDecls().end(); I != E; ++I) {
      m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
    }

    if (m_Consumer->getTransaction()->getIssuedDiags() == Transaction::kErrors)
      return kFailed;
    else if (Diags.getNumWarnings())
      return kSuccessWithWarnings;

    return kSuccess;
  }
Example #15
0
File: JIT.cpp Project: KitoHo/rpcs3
	virtual void NotifyObjectEmitted(const llvm::object::ObjectFile& obj, const llvm::RuntimeDyld::LoadedObjectInfo& inf) override
	{
		const llvm::StringRef elf = obj.getData();
		fs::file(fs::get_config_dir() + "LLVM.obj", fs::rewrite)
			.write(elf.data(), elf.size());
	}
Example #16
0
void
ExecutionContext::executeFunction(llvm::StringRef funcname, 
                                  llvm::GenericValue* returnValue)
{
   // Call an extern C function without arguments
  //runCodeGen();

  // Rewire atexit:
  llvm::Function* atExit =  m_engine->FindFunctionNamed("__cxa_atexit");
  llvm::Function* clingAtExit =  m_engine->FindFunctionNamed("cling_cxa_atexit");
  if (atExit && clingAtExit) {
    void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);
    if (clingAtExitAddr) {
      m_engine->updateGlobalMapping(atExit, clingAtExitAddr);
    }
  }

   llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());
   if (!f) {
      fprintf(
           stderr
         , "ExecutionContext::executeFunction: Could not find function named: %s\n"
         , funcname.data()
      );
      return;
   }
   JITtedFunctionCollector listener;
   // register the listener
   m_engine->RegisterJITEventListener(&listener);
   m_engine->getPointerToFunction(f);
   // check if there is any unresolved symbol in the list
   if (!m_vec_unresolved.empty()) {
      std::cerr << "ExecutionContext::executeFunction:" << std::endl;
      for (size_t i = 0, e = m_vec_unresolved.size(); i != e; ++i) {
         std::cerr << "Error: Symbol \'" << m_vec_unresolved[i] << 
                      "\' unresolved!" << std::endl;
         llvm::Function *ff = m_engine->FindFunctionNamed(m_vec_unresolved[i].c_str());
         if (ff) {
            m_engine->updateGlobalMapping(ff, 0);
            m_engine->freeMachineCodeForFunction(ff);
         }
         else {
            std::cerr << "Error: Canot find symbol \'" << m_vec_unresolved[i] << 
                         std::endl;
         }
      }
      m_vec_unresolved.clear();
      // cleanup functions
      listener.UnregisterFunctionMapping(*m_engine);   
      m_engine->UnregisterJITEventListener(&listener);
      return;
   }
   // cleanup list and unregister our listener
   listener.CleanupList();
   m_engine->UnregisterJITEventListener(&listener);

   std::vector<llvm::GenericValue> args;
   llvm::GenericValue val;
   if (!returnValue)
      returnValue = &val;

   *returnValue = m_engine->runFunction(f, args);
   //
   //fprintf(stderr, "Finished running generated code with JIT.\n");
   //
   // Print the result.
   //llvm::outs() << "Result: " << ret.IntVal << "\n";
   m_engine->freeMachineCodeForFunction(f);
}