Example #1
0
int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr,
                "Expected usage:  %s <sd-leak-file>\n"
                "  sd-leak-file: Output of --shutdown-leaks=<file> option.\n",
                argv[0]);
        return 1;
    }

    NS_InitXPCOM2(NULL, NULL, NULL);

    ADLog log;
    if (!log.Read(argv[1])) {
        fprintf(stderr,
                "%s: Error reading input file %s.\n", argv[0], argv[1]);
    }

    const size_t count = log.count();

    PLHashTable *memory_map =
        PL_NewHashTable(count * 8, hash_pointer, PL_CompareValues,
                        PL_CompareValues, 0, 0);
    if (!memory_map) {
        fprintf(stderr, "%s: Out of memory.\n", argv[0]);
        return 1;
    }

    // Create one |AllocationNode| object for each log entry, and create
    // entries in the hashtable pointing to it for each byte it occupies.
    AllocationNode *nodes = new AllocationNode[count];
    if (!nodes) {
        fprintf(stderr, "%s: Out of memory.\n", argv[0]);
        return 1;
    }

    {
        AllocationNode *cur_node = nodes;
        for (ADLog::const_iterator entry = log.begin(), entry_end = log.end();
             entry != entry_end; ++entry, ++cur_node) {
            const ADLog::Entry *e = cur_node->entry = *entry;
            cur_node->reached = false;

            for (ADLog::Pointer p = e->address,
                            p_end = e->address + e->datasize;
                 p != p_end; ++p) {
                PLHashEntry *e = PL_HashTableAdd(memory_map, p, cur_node);
                if (!e) {
                    fprintf(stderr, "%s: Out of memory.\n", argv[0]);
                    return 1;
                }
            }
        }
    }

    // Construct graph based on pointers.
    for (AllocationNode *node = nodes, *node_end = nodes + count;
         node != node_end; ++node) {
        const ADLog::Entry *e = node->entry;
        for (const char *d = e->data, *d_end = e->data + e->datasize -
                                         e->datasize % sizeof(ADLog::Pointer);
             d != d_end; d += sizeof(ADLog::Pointer)) {
            AllocationNode *target = (AllocationNode*)
                PL_HashTableLookup(memory_map, *(void**)d);
            if (target) {
                target->pointers_from.AppendElement(node);
                node->pointers_to.AppendElement(target);
            }
        }
    }

    // Do a depth-first search on the graph (i.e., by following
    // |pointers_to|) and assign the post-order index to |index|.
    {
        PRUint32 dfs_index = 0;
        nsVoidArray stack;

        for (AllocationNode *n = nodes, *n_end = nodes+count; n != n_end; ++n) {
            if (n->reached) {
                continue;
            }
            stack.AppendElement(n);

            do {
                PRUint32 pos = stack.Count() - 1;
                AllocationNode *n =
                    static_cast<AllocationNode*>(stack[pos]);
                if (n->reached) {
                    n->index = dfs_index++;
                    stack.RemoveElementAt(pos);
                } else {
                    n->reached = true;

                    // When doing post-order processing, we have to be
                    // careful not to put reached nodes into the stack.
                    nsVoidArray &pt = n->pointers_to;
                    for (PRInt32 i = pt.Count() - 1; i >= 0; --i) {
                        if (!static_cast<AllocationNode*>(pt[i])->reached) {
                            stack.AppendElement(pt[i]);
                        }
                    }
                }
            } while (stack.Count() > 0);
        }
    }

    // Sort the nodes by their DFS index, in reverse, so that the first
    // node is guaranteed to be in a root SCC.
    AllocationNode **sorted_nodes = new AllocationNode*[count];
    if (!sorted_nodes) {
        fprintf(stderr, "%s: Out of memory.\n", argv[0]);
        return 1;
    }

    {
        for (size_t i = 0; i < count; ++i) {
            sorted_nodes[i] = nodes + i;
        }
        NS_QuickSort(sorted_nodes, count, sizeof(AllocationNode*),
                     sort_by_reverse_index, 0);
    }

    // Put the nodes into their strongly-connected components.
    PRUint32 num_sccs = 0;
    {
        for (size_t i = 0; i < count; ++i) {
            nodes[i].reached = false;
        }
        nsVoidArray stack;
        for (AllocationNode **sn = sorted_nodes,
                        **sn_end = sorted_nodes + count; sn != sn_end; ++sn) {
            if ((*sn)->reached) {
                continue;
            }

            // We found a new strongly connected index.
            stack.AppendElement(*sn);
            do {
                PRUint32 pos = stack.Count() - 1;
                AllocationNode *n =
                    static_cast<AllocationNode*>(stack[pos]);
                stack.RemoveElementAt(pos);

                if (!n->reached) {
                    n->reached = true;
                    n->index = num_sccs;
                    stack.AppendElements(n->pointers_from);
                }
            } while (stack.Count() > 0);
            ++num_sccs;
        }
    }

    // Identify which nodes are leak roots by using DFS, and watching
    // for component transitions.
    PRUint32 num_root_nodes = count;
    {
        for (size_t i = 0; i < count; ++i) {
            nodes[i].is_root = true;
        }

        nsVoidArray stack;
        for (AllocationNode *n = nodes, *n_end = nodes+count; n != n_end; ++n) {
            if (!n->is_root) {
                continue;
            }

            // Loop through pointers_to, and add any that are in a
            // different SCC to stack:
            for (int i = n->pointers_to.Count() - 1; i >= 0; --i) {
                AllocationNode *target =
                    static_cast<AllocationNode*>(n->pointers_to[i]);
                if (n->index != target->index) {
                    stack.AppendElement(target);
                }
            }

            while (stack.Count() > 0) {
                PRUint32 pos = stack.Count() - 1;
                AllocationNode *n =
                    static_cast<AllocationNode*>(stack[pos]);
                stack.RemoveElementAt(pos);

                if (n->is_root) {
                    n->is_root = false;
                    --num_root_nodes;
                    stack.AppendElements(n->pointers_to);
                }
            }
        }
    }

    // Sort the nodes by their SCC index.
    NS_QuickSort(sorted_nodes, count, sizeof(AllocationNode*),
                 sort_by_index, 0);

    // Print output.
    {
        printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
               "<html>\n"
               "<head>\n"
               "<title>Leak analysis</title>\n"
               "<style type=\"text/css\">\n"
               "  .root { background: white; color: black; }\n"
               "  .nonroot { background: #ccc; color: black; }\n"
               "</style>\n"
               "</head>\n");
        printf("<body>\n\n"
               "<p>Generated %d entries (%d in root SCCs) and %d SCCs.</p>\n\n",
               count, num_root_nodes, num_sccs);

        for (size_t i = 0; i < count; ++i) {
            nodes[i].reached = false;
        }

        // Loop over the sorted nodes twice, first printing the roots
        // and then the non-roots.
        for (PRInt32 root_type = true;
             root_type == true || root_type == false; --root_type) {
            if (root_type) {
                printf("\n\n"
                       "<div class=\"root\">\n"
                       "<h1 id=\"root\">Root components</h1>\n");
            } else {
                printf("\n\n"
                       "<div class=\"nonroot\">\n"
                       "<h1 id=\"nonroot\">Non-root components</h1>\n");
            }
            PRUint32 component = (PRUint32)-1;
            bool one_object_component;
            for (const AllocationNode *const* sn = sorted_nodes,
                                  *const* sn_end = sorted_nodes + count;
                 sn != sn_end; ++sn) {
                const AllocationNode *n = *sn;
                if (n->is_root != root_type)
                    continue;
                const ADLog::Entry *e = n->entry;

                if (n->index != component) {
                    component = n->index;
                    one_object_component =
                        sn + 1 == sn_end || (*(sn+1))->index != component;
                    if (!one_object_component)
                        printf("\n\n<h2 id=\"c%d\">Component %d</h2>\n",
                               component, component);
                }

                if (one_object_component) {
                    printf("\n\n<div id=\"c%d\">\n", component);
                    printf("<h2 id=\"o%d\">Object %d "
                           "(single-object component %d)</h2>\n",
                           n-nodes, n-nodes, component);
                } else {
                    printf("\n\n<h3 id=\"o%d\">Object %d</h3>\n",
                           n-nodes, n-nodes);
                }
                printf("<pre>\n");
                printf("%p &lt;%s&gt; (%d)\n",
                       e->address, e->type, e->datasize);
                for (size_t d = 0; d < e->datasize;
                     d += sizeof(ADLog::Pointer)) {
                    AllocationNode *target = (AllocationNode*)
                        PL_HashTableLookup(memory_map, *(void**)(e->data + d));
                    if (target) {
                        printf("        <a href=\"#o%d\">0x%08X</a> &lt;%s&gt;",
                               target - nodes,
                               *(unsigned int*)(e->data + d),
                               target->entry->type);
                        if (target->index != n->index) {
                            printf(", component %d", target->index);
                        }
                        printf("\n");
                    } else {
                        printf("        0x%08X\n",
                               *(unsigned int*)(e->data + d));
                    }
                }

                if (n->pointers_from.Count()) {
                    printf("\nPointers from:\n");
                    for (PRUint32 i = 0, i_end = n->pointers_from.Count();
                         i != i_end; ++i) {
                        AllocationNode *t = static_cast<AllocationNode*>
                                                       (n->pointers_from[i]);
                        const ADLog::Entry *te = t->entry;
                        printf("    <a href=\"#o%d\">%s</a> (Object %d, ",
                               t - nodes, te->type, t - nodes);
                        if (t->index != n->index) {
                            printf("component %d, ", t->index);
                        }
                        if (t == n) {
                            printf("self)\n");
                        } else {
                            printf("%p)\n", te->address);
                        }
                    }
                }

                print_escaped(stdout, e->allocation_stack);

                printf("</pre>\n");
                if (one_object_component) {
                    printf("</div>\n");
                }
            }
            printf("</div>\n");
        }
        printf("</body>\n"
               "</html>\n");
    }

    delete [] sorted_nodes;
    delete [] nodes;

    NS_ShutdownXPCOM(NULL);

    return 0;
}
Example #2
0
int main (int argc, char* argv[]) 
{
  nsresult                     rv;
  nsCOMPtr<nsIURI>             pURI;
  nsCOMPtr<nsIChannel>         pChannel;
  nsCOMPtr<nsIInputStream>     pInputStream;
  PRUint32                     uiContentLength;
  nsCOMPtr<nsIDOMParser>       pDOMParser;
  nsCOMPtr<nsIDOMDocument>     pDOMDocument;
  nsCOMPtr<nsIXMLHttpRequest>  pXMLHttpRequest;

  nsIServiceManager *servMgr;

  rv = NS_InitXPCOM2(&servMgr, nsnull, nsnull);
  if (NS_FAILED(rv)) return rv;

  if (argc > 2) {
    if (nsCRT::strcasecmp( argv[1], "parsestr" ) == 0) {
      pDOMParser = do_CreateInstance( NS_DOMPARSER_CONTRACTID,
                                     &rv );

      if (NS_SUCCEEDED( rv )) {
        nsString str; str.AssignWithConversion(argv[2]);
        rv = pDOMParser->ParseFromString(str.get(), "application/xml",
                                          getter_AddRefs( pDOMDocument ) );

        if (NS_SUCCEEDED( rv )) {
          printf( "DOM parse string of\n\n%s\n\nsuccessful\n", argv[2] );
        }
        else {
          printf( "DOM parse of \n%s\n NOT successful\n", argv[2] );
        }
      }
      else {
        printf( "do_CreateInstance of DOMParser failed for %s - %08X\n", argv[2], rv );
      }
    } else if (nsCRT::strcasecmp( argv[1], "parse" ) == 0) {
      // DOM Parser
      rv = NS_NewURI( getter_AddRefs( pURI ),
                      argv[2] );

      if (NS_SUCCEEDED( rv )) {
        rv = NS_NewChannel( getter_AddRefs( pChannel ),
                         pURI,
                         nsnull,
                         nsnull );

        if (NS_SUCCEEDED( rv )) {
          rv = pChannel->Open( getter_AddRefs( pInputStream ) );

          if (NS_SUCCEEDED( rv )) {
            rv = pInputStream->Available(&uiContentLength );

            if (NS_SUCCEEDED( rv )) {
              pDOMParser = do_CreateInstance( NS_DOMPARSER_CONTRACTID,
                                             &rv );

              if (NS_SUCCEEDED( rv )) {
                pDOMParser->SetBaseURI(pURI);

                rv = pDOMParser->ParseFromStream( pInputStream,
                                                  "UTF-8",
                                                  uiContentLength,
                                                  "application/xml",
                                                  getter_AddRefs( pDOMDocument ) );
                if (NS_SUCCEEDED( rv )) {
                  printf( "DOM parse of %s successful\n", argv[2] );
                }
                else {
                  printf( "DOM parse of %s NOT successful\n", argv[2] );
                }
              }
              else {
                printf( "do_CreateInstance of DOMParser failed for %s - %08X\n", argv[2], rv );
              }
            }
            else {
              printf( "pInputSteam->Available failed for %s - %08X\n", argv[2], rv );
            }
          }
          else {
            printf( "pChannel->OpenInputStream failed for %s - %08X\n", argv[2], rv );
          }
        }
        else {
          printf( "NS_NewChannel failed for %s - %08X\n", argv[2], rv );
        }
      }
      else {
        printf( "NS_NewURI failed for %s - %08X\n", argv[2], rv );
      }
    }
    else if (nsCRT::strcasecmp( argv[1], "syncread" ) == 0) {
      // Synchronous Read
      pXMLHttpRequest = do_CreateInstance( NS_XMLHTTPREQUEST_CONTRACTID,
                                          &rv );

      if (NS_SUCCEEDED( rv )) {
        const nsAString& emptyStr = EmptyString();
        rv = pXMLHttpRequest->OpenRequest( NS_LITERAL_CSTRING("GET"),
                                           nsDependentCString(argv[2]),
                                           PR_FALSE, emptyStr, emptyStr );

        if (NS_SUCCEEDED( rv )) {
          rv = pXMLHttpRequest->Send( nsnull );

          if (NS_SUCCEEDED( rv )) {
            rv = pXMLHttpRequest->GetResponseXML( getter_AddRefs( pDOMDocument ) );

            if (NS_SUCCEEDED( rv )) {

              if (pDOMDocument) {
                printf( "Synchronous read of %s successful, DOMDocument created\n", argv[2] );
              }
              else {
                printf( "Synchronous read of %s NOT successful, DOMDocument NOT created\n", argv[2] );
              }
            }
            else {
              printf( "pXMLHttpRequest->GetResponseXML failed for %s - %08X\n", argv[2], rv );
            }
          }
          else {
            printf( "pXMLHttpRequest->Send failed for %s - %08X\n", argv[2], rv );
          }
        }
        else {
          printf( "pXMLHttpRequest->OpenRequest failed for %s - %08X\n", argv[2], rv );
        }
      }
      else {
        printf( "do_CreateInstance of XMLHttpRequest failed for %s - %08X\n", argv[2], rv );
      }
    }
#if 0
    else if (nsCRT::strcasecmp( argv[1], "load" ) == 0) {
      nsMyListener * listener = new nsMyListener();
      listener->Start(argv[2]);
    }
#endif
    else {
      usage( );
    }
  }
  else {
    usage( );
  }

  if (pDOMDocument) {
    nsCOMPtr<nsIDOMElement> element;
    pDOMDocument->GetDocumentElement(getter_AddRefs(element));
    nsAutoString tagName;
    if (element) element->GetTagName(tagName);
    char *s = ToNewCString(tagName);
    printf("Document element=\"%s\"\n",s);
    nsCRT::free(s);
    nsCOMPtr<nsIDocument> doc = do_QueryInterface(pDOMDocument);
    if (doc) {
      nsCAutoString spec;
      doc->GetDocumentURI()->GetSpec(spec);
      printf("Document URI=\"%s\"\n",spec.get());
    }
  }

  pURI = nsnull;
  pChannel = nsnull;
  pInputStream = nsnull;
  pDOMParser = nsnull;
  pDOMDocument = nsnull;
  pXMLHttpRequest = nsnull;

  if (servMgr)
    rv = NS_ShutdownXPCOM(servMgr);
  
  return rv;
}
int
main(int argc, char* argv[])
{
    if (test_common_init(&argc, &argv) != 0)
        return -1;

    int returnCode = 0;
    nsresult rv = NS_OK;
    PRFileDesc *serverFD = nullptr;

    do { // act both as a scope for nsCOMPtrs to be released before XPCOM
        // shutdown, as well as a easy way to abort the test
        PRStatus status = PR_SUCCESS;

        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        UDP_ASSERT(registrar, "Null nsIComponentRegistrar");
        if (registrar)
            registrar->AutoRegister(nullptr);

        // listen for a incoming UDP connection on localhost
        serverFD = PR_OpenUDPSocket(PR_AF_INET);
        UDP_ASSERT(serverFD, "Cannot open UDP socket for listening");

        PRSocketOptionData socketOptions;
        socketOptions.option = PR_SockOpt_Nonblocking;
        socketOptions.value.non_blocking = false;
        status = PR_SetSocketOption(serverFD, &socketOptions);
        UDP_ASSERT_PRSTATUS("Failed to set server socket as blocking");

        PRNetAddr addr;
        status = PR_InitializeNetAddr(PR_IpAddrLoopback, UDP_PORT, &addr);
        UDP_ASSERT_PRSTATUS("Failed to initialize loopback address");

        status = PR_Bind(serverFD, &addr);
        UDP_ASSERT_PRSTATUS("Failed to bind server socket");

        // dummy IOService to get around bug 379890
        nsCOMPtr<nsISupports> ios =
            do_GetService("@mozilla.org/network/io-service;1");

        // and have a matching UDP connection for the client
        nsCOMPtr<nsISocketTransportService> sts =
            do_GetService("@mozilla.org/network/socket-transport-service;1", &rv);
        UDP_ASSERT_NSRESULT("Cannot get socket transport service");

        nsCOMPtr<nsISocketTransport> transport;
        const char *protocol = "udp";
        rv = sts->CreateTransport(&protocol, 1, NS_LITERAL_CSTRING("localhost"),
                                  UDP_PORT, nullptr, getter_AddRefs(transport));
        UDP_ASSERT_NSRESULT("Cannot create transport");

        uint32_t count, read;
        const uint32_t data = 0xFF0056A9;

        // write to the output stream
        nsCOMPtr<nsIOutputStream> outstream;
        rv = transport->OpenOutputStream(nsITransport::OPEN_BLOCKING,
                                         0, 0, getter_AddRefs(outstream));
        UDP_ASSERT_NSRESULT("Cannot open output stream");

        rv = outstream->Write((const char*)&data, sizeof(uint32_t), &count);
        UDP_ASSERT_NSRESULT("Cannot write to output stream");
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not write enough bytes to output stream");

        // read from NSPR to check it's the same
        count = PR_RecvFrom(serverFD, &read, sizeof(uint32_t), 0, &addr, 1);
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not read enough bytes from NSPR");
        status = (read == data ? PR_SUCCESS : PR_FAILURE);
        UDP_ASSERT_PRSTATUS("Did not read expected data from NSPR");

        // write to NSPR
        count = PR_SendTo(serverFD, &data, sizeof(uint32_t), 0, &addr, 1);
        status = (count == sizeof(uint32_t) ? PR_SUCCESS : PR_FAILURE);
        UDP_ASSERT_PRSTATUS("Did not write enough bytes to NSPR");

        // read from stream
        nsCOMPtr<nsIInputStream> instream;
        rv = transport->OpenInputStream(nsITransport::OPEN_BLOCKING,
                                        0, 0, getter_AddRefs(instream));
        UDP_ASSERT_NSRESULT("Cannot open input stream");

        rv = instream->Read((char*)&read, sizeof(uint32_t), &count);
        UDP_ASSERT_NSRESULT("Cannot read from input stream");
        UDP_ASSERT(count == sizeof(uint32_t),
                   "Did not read enough bytes from input stream");
        UDP_ASSERT(read == data, "Did not read expected data from stream");

    } while (false); // release all XPCOM things
    if (serverFD) {
        PRStatus status = PR_Close(serverFD);
        if (status != PR_SUCCESS) {
            PRErrorCode err = PR_GetError();
            fprintf(stderr, "FAIL: Cannot close server: (%08x) %s\n",
                    err, PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
        }
    }
    rv = NS_ShutdownXPCOM(nullptr);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");

    return returnCode;
}
int
main(int argc, char* argv[])
{
    nsresult rv;
    {
        XRE_AddStaticComponent(&kTestModule);

        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
    
        nsCOMPtr<nsIThread> thread = do_GetCurrentThread();

        nsCOMPtr<nsICategoryManager> catman =
            do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
        if (NS_FAILED(rv)) return rv;
        nsCString previous;

        nsCOMPtr<nsIStreamConverterService> StreamConvService =
                 do_GetService(kStreamConverterServiceCID, &rv);
        if (NS_FAILED(rv)) return rv;

        // Define the *from* content type and *to* content-type for conversion.
        static const char fromStr[] = "a/foo";
        static const char toStr[] = "c/foo";
    
#ifdef ASYNC_TEST
        // ASYNCHRONOUS conversion

        // Build up a channel that represents the content we're
        // starting the transaction with.
        //
        // sample multipart mixed content-type string:
        // "multipart/x-mixed-replacE;boundary=thisrandomstring"
#if 0
        nsCOMPtr<nsIChannel> channel;
        nsCOMPtr<nsIURI> dummyURI;
        rv = NS_NewURI(getter_AddRefs(dummyURI), "http://meaningless");
        if (NS_FAILED(rv)) return rv;

        rv = NS_NewInputStreamChannel(getter_AddRefs(channel),
                                      dummyURI,
                                      nsnull,   // inStr
                                      "text/plain", // content-type
                                      -1);      // XXX fix contentLength
        if (NS_FAILED(rv)) return rv;

        nsCOMPtr<nsIRequest> request(do_QueryInterface(channel));
#endif

        nsCOMPtr<nsIRequest> request;

        // setup a listener to receive the converted data. This guy is the end
        // listener in the chain, he wants the fully converted (toType) data.
        // An example of this listener in mozilla would be the DocLoader.
        nsIStreamListener *dataReceiver = new EndListener();
        NS_ADDREF(dataReceiver);

        // setup a listener to push the data into. This listener sits inbetween the
        // unconverted data of fromType, and the final listener in the chain (in this case
        // the dataReceiver.
        nsIStreamListener *converterListener = nsnull;
        rv = StreamConvService->AsyncConvertData(fromStr, toStr,
                                                 dataReceiver, nsnull, &converterListener);
        if (NS_FAILED(rv)) return rv;
        NS_RELEASE(dataReceiver);

        // at this point we have a stream listener to push data to, and the one
        // that will receive the converted data. Let's mimic On*() calls and get the conversion
        // going. Typically these On*() calls would be made inside their respective wrappers On*()
        // methods.
        rv = converterListener->OnStartRequest(request, nsnull);
        if (NS_FAILED(rv)) return rv;

        rv = SEND_DATA("aaa");
        if (NS_FAILED(rv)) return rv;

        rv = SEND_DATA("aaa");
        if (NS_FAILED(rv)) return rv;

        // Finish the request.
        rv = converterListener->OnStopRequest(request, nsnull, rv);
        if (NS_FAILED(rv)) return rv;

        NS_RELEASE(converterListener);
#else
        // SYNCHRONOUS conversion
        nsCOMPtr<nsIInputStream> convertedData;
        rv = StreamConvService->Convert(inputData, fromStr, toStr,
                                        nsnull, getter_AddRefs(convertedData));
        if (NS_FAILED(rv)) return rv;
#endif

        // Enter the message pump to allow the URL load to proceed.
        while ( gKeepRunning ) {
            if (!NS_ProcessNextEvent(thread))
                break;
        }
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    NS_ShutdownXPCOM(nsnull);
    return rv;
}
int
main(int argc, char* argv[])
{
    if (test_common_init(&argc, &argv) != 0)
        return -1;

    nsresult rv;

    if (argc < 4) {
        printf("usage: TestSocketTransport <host> <port> <path>\n");
        return -1;
    }

    {
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
        if (registrar)
            registrar->AutoRegister(nsnull);

#if defined(PR_LOGGING)
        gTestLog = PR_NewLogModule("Test");
#endif

        // Make sure the DNS service is initialized on the main thread
        nsCOMPtr<nsIDNSService> dns =
                 do_GetService(NS_DNSSERVICE_CONTRACTID, &rv);
        if (NS_FAILED(rv)) return rv;

        nsCOMPtr<nsPISocketTransportService> sts =
            do_GetService(kSocketTransportServiceCID, &rv);
        if (NS_FAILED(rv)) return rv;

        LOG(("phase 1 tests...\n"));

        LOG(("flags = { OPEN_UNBUFFERED, OPEN_UNBUFFERED }\n"));
        rv = RunCloseTest(sts, argv[1], atoi(argv[2]),
                          nsITransport::OPEN_UNBUFFERED,
                          nsITransport::OPEN_UNBUFFERED);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed");

        LOG(("flags = { OPEN_BUFFERED, OPEN_UNBUFFERED }\n"));
        rv = RunCloseTest(sts, argv[1], atoi(argv[2]),
                          0 /* nsITransport::OPEN_BUFFERED */,
                          nsITransport::OPEN_UNBUFFERED);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed");

        LOG(("flags = { OPEN_UNBUFFERED, OPEN_BUFFERED }\n"));
        rv = RunCloseTest(sts, argv[1], atoi(argv[2]),
                          nsITransport::OPEN_UNBUFFERED,
                          0 /*nsITransport::OPEN_BUFFERED */);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed");

        LOG(("flags = { OPEN_BUFFERED, OPEN_BUFFERED }\n"));
        rv = RunCloseTest(sts, argv[1], atoi(argv[2]),
                          0 /*nsITransport::OPEN_BUFFERED */,
                          0 /*nsITransport::OPEN_BUFFERED */);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunCloseTest failed");

        LOG(("calling Shutdown on socket transport service:\n"));
        sts->Shutdown();

        LOG(("calling Init on socket transport service:\n"));
        sts->Init();

        LOG(("phase 2 tests...\n"));

        LOG(("flags = { OPEN_UNBUFFERED, OPEN_UNBUFFERED }\n"));
        rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3],
                     nsITransport::OPEN_UNBUFFERED,
                     nsITransport::OPEN_UNBUFFERED);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed");

        LOG(("flags = { OPEN_BUFFERED, OPEN_UNBUFFERED }\n"));
        rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3],
                     0 /* nsITransport::OPEN_BUFFERED */,
                     nsITransport::OPEN_UNBUFFERED);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed");

        LOG(("flags = { OPEN_UNBUFFERED, OPEN_BUFFERED }\n"));
        rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3],
                     nsITransport::OPEN_UNBUFFERED,
                     0 /*nsITransport::OPEN_BUFFERED */);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed");

        LOG(("flags = { OPEN_BUFFERED, OPEN_BUFFERED }\n"));
        rv = RunTest(sts, argv[1], atoi(argv[2]), argv[3],
                     0 /*nsITransport::OPEN_BUFFERED */,
                     0 /*nsITransport::OPEN_BUFFERED */);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed");

        LOG(("waiting 1 second before calling Shutdown...\n"));
        PR_Sleep(PR_SecondsToInterval(1));

        LOG(("calling Shutdown on socket transport service:\n"));
        sts->Shutdown();

        // give background threads a chance to finish whatever work they may
        // be doing.
        LOG(("waiting 1 second before exiting...\n"));
        PR_Sleep(PR_SecondsToInterval(1));
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    rv = NS_ShutdownXPCOM(nsnull);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
    return 0;
}
Example #6
0
int
main(int argc, char **argv)
{
    int numberOfThreads = 1;

    if (argc > 1)
        numberOfThreads = atoi(argv[1]);

    NS_InitXPCOM2(nsnull, nsnull, nsnull);

    // Scope code so everything is destroyed before we run call NS_ShutdownXPCOM
    {
        nsCOMPtr<nsIComponentRegistrar> registrar;
        NS_GetComponentRegistrar(getter_AddRefs(registrar));
        registrar->AutoRegister(nsnull);

        RunApartmentTest();

        nsCOMPtr<nsIThread> eventLoopThread;
        NS_NewThread(getter_AddRefs(eventLoopThread));

        nsCOMPtr<nsIRunnable> test = new TestSyncProxyToSelf();
        eventLoopThread->Dispatch(test, NS_DISPATCH_NORMAL);

        PRThread *eventLoopPRThread;
        eventLoopThread->GetPRThread(&eventLoopPRThread);
        PR_ASSERT(eventLoopPRThread);
        
        LOG(("TEST: Spawn Threads:\n"));
        nsCOMArray<nsIThread> threads;
        for (PRInt32 spawn = 0; spawn < numberOfThreads; spawn++)
        {
            test = new ProxyTest(eventLoopPRThread, spawn);

            nsCOMPtr<nsIThread> thread;
            NS_NewThread(getter_AddRefs(thread), test);

            threads.AppendObject(thread);

            LOG(("TEST: \tThread (%d) spawned\n", spawn));

            PR_Sleep( PR_MillisecondsToInterval(250) );
        }

        LOG(("TEST: All Threads Spawned.\n"));
        
        LOG(("TEST: Wait for threads.\n"));
        for (PRInt32 i = 0; i < numberOfThreads; i++)
        {
            LOG(("TEST: Thread (%d) Join...\n", i));
            nsresult rv = threads[i]->Shutdown();
            LOG(("TEST: Thread (%d) Joined. (error: %x).\n", i, rv));
        }

        LOG(("TEST: Shutting down event loop thread\n"));
        eventLoopThread->Shutdown();
    }

    LOG(("TEST: Calling Cleanup.\n"));
    NS_ShutdownXPCOM(nsnull);

    LOG(("TEST: Return zero.\n"));
    return 0;
}
Example #7
0
HRESULT Shutdown()
{
    HRESULT rc = S_OK;

#if !defined(VBOX_WITH_XPCOM)

    /* EventQueue::uninit reference counting fun. */
    RTTHREAD hSelf = RTThreadSelf();
    if (    hSelf == gCOMMainThread
        &&  hSelf != NIL_RTTHREAD)
    {
        if (-- gCOMMainInitCount == 0)
        {
            EventQueue::uninit();
            ASMAtomicWriteHandle(&gCOMMainThread, NIL_RTTHREAD);
        }
    }

    CoUninitialize();

#else /* !defined (VBOX_WITH_XPCOM) */

    nsCOMPtr<nsIEventQueue> eventQ;
    rc = NS_GetMainEventQ(getter_AddRefs(eventQ));

    if (NS_SUCCEEDED(rc) || rc == NS_ERROR_NOT_AVAILABLE)
    {
        /* NS_ERROR_NOT_AVAILABLE seems to mean that
         * nsIEventQueue::StopAcceptingEvents() has been called (see
         * nsEventQueueService.cpp). We hope that this error code always means
         * just that in this case and assume that we're on the main thread
         * (it's a kind of unexpected behavior if a non-main thread ever calls
         * StopAcceptingEvents() on the main event queue). */

        PRBool isOnMainThread = PR_FALSE;
        if (NS_SUCCEEDED(rc))
        {
            rc = eventQ->IsOnCurrentThread(&isOnMainThread);
            eventQ = nsnull; /* early release before shutdown */
        }
        else
        {
            isOnMainThread = PR_TRUE;
            rc = NS_OK;
        }

        if (NS_SUCCEEDED(rc) && isOnMainThread)
        {
            /* only the main thread needs to uninitialize XPCOM and only if
             * init counter drops to zero */
            if (--gXPCOMInitCount == 0)
            {
                EventQueue::uninit();
                rc = NS_ShutdownXPCOM(nsnull);

                /* This is a thread initialized XPCOM and set gIsXPCOMInitialized to
                 * true. Reset it back to false. */
                bool wasInited = ASMAtomicXchgBool(&gIsXPCOMInitialized, false);
                Assert(wasInited == true);
                NOREF(wasInited);

# if defined (XPCOM_GLUE)
                XPCOMGlueShutdown();
# endif
            }
        }
    }

#endif /* !defined(VBOX_WITH_XPCOM) */

    AssertComRC(rc);

    return rc;
}
Example #8
0
int main()
{
    JSRuntime *rt;
    JSContext *jscontext;
    JSObject *glob;
    nsresult rv;

    gErrFile = stderr;
    gOutFile = stdout;
    {
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
    
        // get the JSRuntime from the runtime svc, if possible
        nsCOMPtr<nsIJSRuntimeService> rtsvc =
                 do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
        if(NS_FAILED(rv) || NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt)
            DIE("FAILED to get a JSRuntime");

        jscontext = JS_NewContext(rt, 8192);
        if(!jscontext)
            DIE("FAILED to create a JSContext");

        JS_SetErrorReporter(jscontext, my_ErrorReporter);

        nsCOMPtr<nsIXPConnect> xpc(do_GetService(nsIXPConnect::GetCID(), &rv));
        if(!xpc)
            DIE("FAILED to get xpconnect service\n");

        nsCOMPtr<nsIJSContextStack> cxstack =
                 do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
        if(NS_FAILED(rv))
            DIE("FAILED to get the nsThreadJSContextStack service!\n");

        if(NS_FAILED(cxstack->Push(jscontext)))
            DIE("FAILED to push the current jscontext on the nsThreadJSContextStack service!\n");

        // XXX I'd like to replace this with code that uses a wrapped xpcom object
        // as the global object. The old TextXPC did this. The support for this
        // is not working now in the new xpconnect code.

        {
            JSAutoRequest ar(jscontext);
            glob = JS_NewCompartmentAndGlobalObject(jscontext, &global_class, NULL);
            if (!glob)
                DIE("FAILED to create global object");

            JSAutoEnterCompartment ac;
            if (!ac.enter(jscontext, glob))
                DIE("FAILED to enter compartment");

            if (!JS_InitStandardClasses(jscontext, glob))
                DIE("FAILED to init standard classes");
            if (!JS_DefineFunctions(jscontext, glob, glob_functions))
                DIE("FAILED to define global functions");
            if (NS_FAILED(xpc->InitClasses(jscontext, glob)))
                DIE("FAILED to init xpconnect classes");
        }

        /**********************************************/
        // run the tests...

        TestCategoryManmager();
        TestSecurityManager(jscontext, glob, xpc);
        TestArgFormatter(jscontext, glob, xpc);
        TestThreadJSContextStack(jscontext);

        /**********************************************/

        if(NS_FAILED(cxstack->Pop(nsnull)))
            DIE("FAILED to pop the current jscontext from the nsThreadJSContextStack service!\n");

        {
            JSAutoRequest ar(jscontext);
            JS_ClearScope(jscontext, glob);
            JS_GC(jscontext);
            JS_GC(jscontext);
        }
        JS_DestroyContext(jscontext);
        xpc->DebugDump(4);

        cxstack = nsnull;   // release service held by nsCOMPtr
        xpc     = nsnull;   // release service held by nsCOMPtr
        rtsvc   = nsnull;   // release service held by nsCOMPtr
    }
    rv = NS_ShutdownXPCOM( NULL );
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM FAILED");

    return 0;
}
int
main(void)
{
//	OSErr	err;
    printf("hello world\n");

    unsigned long now = time(0);
    srand(now);

    nsCOMPtr<nsIFile>       file;
    nsCOMPtr<nsIFile>  localFile;
    nsresult  rv = NS_OK;
    {
        // Start up XPCOM
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
        if (registrar)
            registrar->AutoRegister(nsnull);

        // Get default directory
        rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR,
                                    getter_AddRefs(file));
        if (NS_FAILED(rv)) {
            printf("NS_GetSpecialDirectory() failed : 0x%.8x\n", rv);
            goto exit;
        }
        char * currentDirPath;
        rv = file->GetPath(&currentDirPath);
        if (NS_FAILED(rv)) {
            printf("currentProcessDir->GetPath() failed : 0x%.8x\n", rv);
            goto exit;
        }

        printf("Current Process Directory: %s\n", currentDirPath);


        // Generate name for cache block file
	rv = file->Append("_CACHE_001_");
        if (NS_FAILED(rv)) goto exit;

        // Delete existing file
        rv = file->Delete(false);
        if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND) goto exit;

        // Need nsIFile to open
	localFile = do_QueryInterface(file, &rv);
        if (NS_FAILED(rv)) {
            printf("do_QueryInterface(file) failed : 0x%.8x\n", rv);
            goto exit;
        }

        nsDiskCacheBlockFile * blockFile = new nsDiskCacheBlockFile;
        if (!blockFile) {
            rv = NS_ERROR_OUT_OF_MEMORY;
            goto exit;
        }

        //----------------------------------------------------------------
        //  local variables used in tests
        //----------------------------------------------------------------
        PRUint32 bytesWritten = 0;
        PRInt32  startBlock;
        PRInt32  i = 0;


        //----------------------------------------------------------------
        //  Test 1: Open nonexistent file
        //----------------------------------------------------------------
        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 1: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 1: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 1: passed\n");


        //----------------------------------------------------------------
        //  Test 2: Open existing file (with no allocation)
        //----------------------------------------------------------------
        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 2: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 2: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 2: passed\n");


        //----------------------------------------------------------------
        //  Test 3: Open existing file (bad format) size < kBitMapBytes
        //----------------------------------------------------------------

        // Delete existing file
        rv = localFile->Delete(false);
        if (NS_FAILED(rv)) {
            printf("Test 3 failed (Delete returned: 0x%.8x)\n", rv);
            goto exit;
        }

        // write < kBitMapBytes to file
        nsANSIFileStream * stream = new nsANSIFileStream;
        if (!stream) {
            printf("Test 3 failed (unable to allocate stream\n", rv);
            goto exit;
        }
        NS_ADDREF(stream);
        rv = stream->Open(localFile);
        if (NS_FAILED(rv)) {
            NS_RELEASE(stream);
            printf("Test 3 failed (stream->Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        bytesWritten = 0;
        rv = stream->Write("Tell me something good.\n", 24, &bytesWritten);
        if (NS_FAILED(rv)) {
            NS_RELEASE(stream);
            printf("Test 3 failed (stream->Write returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = stream->Close();
        if (NS_FAILED(rv)) {
            NS_RELEASE(stream);
            printf("Test 3 failed (stream->Close returned: 0x%.8x)\n", rv);
            goto exit;
        }
        NS_RELEASE(stream);

        rv = blockFile->Open(localFile, 256);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 3: failed (Open erroneously succeeded)\n", rv);

            (void) blockFile->Close();
            goto exit;
        }

        printf("Test 3: passed\n");


        //----------------------------------------------------------------
        //  Test 4: Open nonexistent file (again)
        //----------------------------------------------------------------

        // Delete existing file
        rv = localFile->Delete(false);
        if (NS_FAILED(rv)) {
            printf("Test 4 failed (Delete returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 4: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 4: passed\n");


        //----------------------------------------------------------------
        //  Test 5: AllocateBlocks: invalid block count (0, 5)
        //----------------------------------------------------------------


        startBlock = blockFile->AllocateBlocks(0);
        if (startBlock > -1) {
            printf("Test 5: failed (AllocateBlocks(0) erroneously succeeded)\n");
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(5);
        if (startBlock > -1) {
            printf("Test 5: failed (AllocateBlocks(5) erroneously succeeded)\n");
            goto exit;
        }
        printf("Test 5: passed\n");


        //----------------------------------------------------------------
        //  Test 6: AllocateBlocks: valid block count (1, 2, 3, 4)
        //----------------------------------------------------------------
        startBlock = blockFile->AllocateBlocks(1);
        if (startBlock != 0) {
            printf("Test 6: failed (AllocateBlocks(1) failed)\n");
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(2);
        if (startBlock != 1) {
            printf("Test 6: failed (AllocateBlocks(2) failed)\n");
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(3);
        if (startBlock != 4) {
            printf("Test 6: failed (AllocateBlocks(3) failed)\n");
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(4);
        if (startBlock != 8) {
            printf("Test 6: failed (AllocateBlocks(4) failed)\n");
            goto exit;
        }

        // blocks allocated should be 1220 3330 4444
        printf("Test 6: passed\n");  // but bits could be mis-allocated



        //----------------------------------------------------------------
        //  Test 7: VerifyAllocation
        //----------------------------------------------------------------
        rv = blockFile->VerifyAllocation(0,1);
        if (NS_FAILED(rv)) {
            printf("Test 7: failed (VerifyAllocation(0,1) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->VerifyAllocation(1,2);
        if (NS_FAILED(rv)) {
            printf("Test 7: failed (VerifyAllocation(1,2) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->VerifyAllocation(4,3);
        if (NS_FAILED(rv)) {
            printf("Test 7: failed (VerifyAllocation(4,3) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->VerifyAllocation(8,4);
        if (NS_FAILED(rv)) {
            printf("Test 7: failed (VerifyAllocation(8,4) returned: 0x%.8x)\n", rv);
            goto exit;
        }
        printf("Test 7: passed\n");


        //----------------------------------------------------------------
        //  Test 8: LastBlock
        //----------------------------------------------------------------
        PRInt32  lastBlock = blockFile->LastBlock();
        if (lastBlock != 11) {
            printf("Test 8: failed (LastBlock() returned: %d)\n", lastBlock);
            goto exit;
        }
        printf("Test 8: passed\n");


        //----------------------------------------------------------------
        //  Test 9: DeallocateBlocks: bad startBlock ( < 0)
        //----------------------------------------------------------------
        rv = blockFile->DeallocateBlocks(-1, 4);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 9: failed (DeallocateBlocks(-1, 4) erroneously succeeded)\n");
            goto exit;
        }
        printf("Test 9: passed\n");


        //----------------------------------------------------------------
        //  Test 10: DeallocateBlocks: bad numBlocks (0, 5)
        //----------------------------------------------------------------
        rv = blockFile->DeallocateBlocks(0, 0);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 10: failed (DeallocateBlocks(0, 0) erroneously succeeded)\n");
            goto exit;
        }

        rv = blockFile->DeallocateBlocks(0, 5);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 10: failed (DeallocateBlocks(0, 5) erroneously succeeded)\n");
            goto exit;
        }

        printf("Test 10: passed\n");


        //----------------------------------------------------------------
        //  Test 11: DeallocateBlocks: unallocated blocks
        //----------------------------------------------------------------
        rv = blockFile->DeallocateBlocks(12, 1);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 11: failed (DeallocateBlocks(12, 1) erroneously succeeded)\n");
            goto exit;
        }

        printf("Test 11: passed\n");


        //----------------------------------------------------------------
        //  Test 12: DeallocateBlocks: 1, 2, 3, 4 (allocated in Test 6)
        //----------------------------------------------------------------
        rv = blockFile->DeallocateBlocks(0, 1);
        if (NS_FAILED(rv)) {
            printf("Test 12: failed (DeallocateBlocks(12, 1) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->DeallocateBlocks(1, 2);
        if (NS_FAILED(rv)) {
            printf("Test 12: failed (DeallocateBlocks(1, 2) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->DeallocateBlocks(4, 3);
        if (NS_FAILED(rv)) {
            printf("Test 12: failed (DeallocateBlocks(4, 3) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->DeallocateBlocks(8, 4);
        if (NS_FAILED(rv)) {
            printf("Test 12: failed (DeallocateBlocks(8, 4) returned: 0x%.8x)\n", rv);
            goto exit;
        }

        // zero blocks should be allocated
        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 12: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 12: passed\n");


        //----------------------------------------------------------------
        //  Test 13: Allocate/Deallocate boundary test
        //----------------------------------------------------------------

        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 13: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        // fully allocate, 1 block at a time
        for (i=0; i< kBitMapBytes * 8; ++i) {
            startBlock = blockFile->AllocateBlocks(1);
            if (startBlock < 0) {
                printf("Test 13: failed (AllocateBlocks(1) failed on i=%d)\n", i);
                goto exit;
            }
        }

        // attempt allocation with full bit map
        startBlock = blockFile->AllocateBlocks(1);
        if (startBlock >= 0) {
            printf("Test 13: failed (AllocateBlocks(1) erroneously succeeded i=%d)\n", i);
            goto exit;
        }

        // deallocate all the bits
        for (i=0; i< kBitMapBytes * 8; ++i) {
            rv = blockFile->DeallocateBlocks(i,1);
            if (NS_FAILED(rv)) {
                printf("Test 13: failed (DeallocateBlocks(%d,1) returned: 0x%.8x)\n", i,rv);
                goto exit;
            }
        }

        // attempt deallocation beyond end of bit map
        rv = blockFile->DeallocateBlocks(i,1);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 13: failed (DeallocateBlocks(%d,1) erroneously succeeded)\n", i);
            goto exit;
        }

        // bit map should be empty

        // fully allocate, 2 block at a time
        for (i=0; i< kBitMapBytes * 8; i+=2) {
            startBlock = blockFile->AllocateBlocks(2);
            if (startBlock < 0) {
                printf("Test 13: failed (AllocateBlocks(2) failed on i=%d)\n", i);
                goto exit;
            }
        }

        // attempt allocation with full bit map
        startBlock = blockFile->AllocateBlocks(2);
        if (startBlock >= 0) {
            printf("Test 13: failed (AllocateBlocks(2) erroneously succeeded i=%d)\n", i);
            goto exit;
        }

        // deallocate all the bits
        for (i=0; i< kBitMapBytes * 8; i+=2) {
            rv = blockFile->DeallocateBlocks(i,2);
            if (NS_FAILED(rv)) {
                printf("Test 13: failed (DeallocateBlocks(%d,2) returned: 0x%.8x)\n", i,rv);
                goto exit;
            }
        }

        // bit map should be empty

        // fully allocate, 4 block at a time
        for (i=0; i< kBitMapBytes * 8; i+=4) {
            startBlock = blockFile->AllocateBlocks(4);
            if (startBlock < 0) {
                printf("Test 13: failed (AllocateBlocks(4) failed on i=%d)\n", i);
                goto exit;
            }
        }

        // attempt allocation with full bit map
        startBlock = blockFile->AllocateBlocks(4);
        if (startBlock >= 0) {
            printf("Test 13: failed (AllocateBlocks(4) erroneously succeeded i=%d)\n", i);
            goto exit;
        }

        // deallocate all the bits
        for (i=0; i< kBitMapBytes * 8; i+=4) {
            rv = blockFile->DeallocateBlocks(i,4);
            if (NS_FAILED(rv)) {
                printf("Test 13: failed (DeallocateBlocks(%d,4) returned: 0x%.8x)\n", i,rv);
                goto exit;
            }
        }

        // bit map should be empty

        // allocate as many triple-blocks as possible
        for (i=0; i< kBitMapBytes * 8; i+=4) {
            startBlock = blockFile->AllocateBlocks(3);
            if (startBlock < 0) {
                printf("Test 13: failed (AllocateBlocks(3) failed on i=%d)\n", i);
                goto exit;
            }
        }

        // attempt allocation with "full" bit map
        startBlock = blockFile->AllocateBlocks(3);
        if (startBlock >= 0) {
            printf("Test 13: failed (AllocateBlocks(3) erroneously succeeded i=%d)\n", i);
            goto exit;
        }

        // leave some blocks allocated

        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 13: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 13: passed\n");


        //----------------------------------------------------------------
        //  Test 14: ValidateFile (open existing file w/size < allocated blocks
        //----------------------------------------------------------------
        rv = blockFile->Open(localFile, 256);
        if (NS_SUCCEEDED(rv)) {
            printf("Test 14: failed (Open erroneously succeeded)\n");
            goto exit;
        }

        // Delete existing file
        rv = localFile->Delete(false);
        if (NS_FAILED(rv)) {
            printf("Test 14 failed (Delete returned: 0x%.8x)\n", rv);
            goto exit;
        }
        printf("Test 14: passed\n");


        //----------------------------------------------------------------
        //  Test 15: Allocate/Deallocate stress test
        //----------------------------------------------------------------

        rv = StressTest(localFile, 15, false);
        if (NS_FAILED(rv))
            goto exit;

        printf("Test 15: passed\n");


        //----------------------------------------------------------------
        //  Test 16: WriteBlocks
        //----------------------------------------------------------------

        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 16: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        char * one   = new char[256 * 1];
        char * two   = new char[256 * 2];
        char * three = new char[256 * 3];
        char * four  = new char[256 * 4];
        if (!one || !two || !three || !four) {
            printf("Test 16: failed - out of memory\n");
            rv = NS_ERROR_OUT_OF_MEMORY;
            goto exit;
        }

        memset(one,   1, 256);
        memset(two,   2, 256 * 2);
        memset(three, 3, 256 * 3);
        memset(four,  4, 256 * 4);

        startBlock = blockFile->AllocateBlocks(1);
        if (startBlock != 0) {
            printf("Test 16: failed (AllocateBlocks(1) failed)\n");
            goto exit;
        }

        rv = blockFile->WriteBlocks(one, startBlock, 1);
        if (NS_FAILED(rv)) {
            printf("Test 16: failed (WriteBlocks(1) returned 0x%.8x)\n", rv);
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(2);
        if (startBlock != 1) {  // starting with empy map, this allocation should begin at block 1
            printf("Test 16: failed (AllocateBlocks(2) failed)\n");
            goto exit;
        }

        rv = blockFile->WriteBlocks(two, startBlock, 2);
        if (NS_FAILED(rv)) {
            printf("Test 16: failed (WriteBlocks(2) returned 0x%.8x)\n", rv);
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(3);
        if (startBlock != 4) {  // starting with empy map, this allocation should begin at block 4
            printf("Test 16: failed (AllocateBlocks(3) failed)\n");
            goto exit;
        }

        rv = blockFile->WriteBlocks(three, startBlock, 3);
        if (NS_FAILED(rv)) {
            printf("Test 16: failed (WriteBlocks(3) returned 0x%.8x)\n", rv);
            goto exit;
        }

        startBlock = blockFile->AllocateBlocks(4);
        if (startBlock != 8) {  // starting with empy map, this allocation should begin at block 8
            printf("Test 16: failed (AllocateBlocks(4) failed)\n");
            goto exit;
        }

        rv = blockFile->WriteBlocks(four, startBlock, 4);
        if (NS_FAILED(rv)) {
            printf("Test 16: failed (WriteBlocks(4) returned 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 16: passed\n");


        //----------------------------------------------------------------
        //  Test 17: ReadBlocks
        //----------------------------------------------------------------

        rv = blockFile->ReadBlocks(one, 0, 1);
        if (NS_FAILED(rv)) {
            printf("Test 17: failed (ReadBlocks(1) returned 0x%.8x)\n", rv);
            goto exit;
        }

        // Verify buffer
        for (i = 0; i < 256; i++) {
            if (one[i] != 1) {
                printf("Test 17: failed (verifying buffer 1)\n");
                rv = NS_ERROR_FAILURE;
                goto exit;
            }
        }

        rv = blockFile->ReadBlocks(two, 1, 2);
        if (NS_FAILED(rv)) {
            printf("Test 17: failed (ReadBlocks(2) returned 0x%.8x)\n", rv);
            goto exit;
        }

        // Verify buffer
        for (i = 0; i < 256 * 2; i++) {
            if (two[i] != 2) {
                printf("Test 17: failed (verifying buffer 2)\n");
                rv = NS_ERROR_FAILURE;
                goto exit;
            }
        }

        rv = blockFile->ReadBlocks(three, 4, 3);
        if (NS_FAILED(rv)) {
            printf("Test 17: failed (ReadBlocks(3) returned 0x%.8x)\n", rv);
            goto exit;
        }

        // Verify buffer
        for (i = 0; i < 256 * 3; i++) {
            if (three[i] != 3) {
                printf("Test 17: failed (verifying buffer 3)\n");
                rv = NS_ERROR_FAILURE;
                goto exit;
            }
        }

        rv = blockFile->ReadBlocks(four, 8, 4);
        if (NS_FAILED(rv)) {
            printf("Test 17: failed (ReadBlocks(4) returned 0x%.8x)\n", rv);
            goto exit;
        }

        // Verify buffer
        for (i = 0; i < 256 * 4; i++) {
            if (four[i] != 4) {
                printf("Test 17: failed (verifying buffer 4)\n");
                rv = NS_ERROR_FAILURE;
                goto exit;
            }
        }

        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 17: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 17: passed\n");


        //----------------------------------------------------------------
        //  Test 18: ValidateFile (open existing file with blocks allocated)
        //----------------------------------------------------------------
        rv = blockFile->Open(localFile, 256);
        if (NS_FAILED(rv)) {
            printf("Test 18: failed (Open returned: 0x%.8x)\n", rv);
            goto exit;
        }

        rv = blockFile->Close();
        if (NS_FAILED(rv)) {
            printf("Test 18: failed (Close returned: 0x%.8x)\n", rv);
            goto exit;
        }

        printf("Test 18: passed\n");

        //----------------------------------------------------------------
        //  Test 19: WriteBlocks/ReadBlocks stress
        //----------------------------------------------------------------

        rv = StressTest(localFile, 19, false);
        if (NS_FAILED(rv))
            goto exit;

        printf("Test 19: passed\n");


exit:

        if (currentDirPath)
            nsMemory::Free(currentDirPath);
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    if (NS_FAILED(rv))
        printf("Test failed: 0x%.8x\n", rv);

    rv = NS_ShutdownXPCOM(nsnull);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");

    printf("XPCOM shut down.\n\n");
    return 0;
}
Example #10
0
/**
 * Initializes the COM runtime.
 *
 * This method must be called on each thread of the client application that
 * wants to access COM facilities. The initialization must be performed before
 * calling any other COM method or attempting to instantiate COM objects.
 *
 * On platforms using XPCOM, this method uses the following scheme to search for
 * XPCOM runtime:
 *
 * 1. If the VBOX_APP_HOME environment variable is set, the path it specifies
 *    is used to search XPCOM libraries and components. If this method fails to
 *    initialize XPCOM runtime using this path, it will immediately return a
 *    failure and will NOT check for other paths as described below.
 *
 * 2. If VBOX_APP_HOME is not set, this methods tries the following paths in the
 *    given order:
 *
 *    a) Compiled-in application data directory (as returned by
 *       RTPathAppPrivateArch())
 *    b) "/usr/lib/virtualbox" (Linux only)
 *    c) "/opt/VirtualBox" (Linux only)
 *
 *    The first path for which the initialization succeeds will be used.
 *
 * On MS COM platforms, the COM runtime is provided by the system and does not
 * need to be searched for.
 *
 * Once the COM subsystem is no longer necessary on a given thread, Shutdown()
 * must be called to free resources allocated for it. Note that a thread may
 * call Initialize() several times but for each of tese calls there must be a
 * corresponding Shutdown() call.
 *
 * @return S_OK on success and a COM result code in case of failure.
 */
HRESULT Initialize(bool fGui)
{
    HRESULT rc = E_FAIL;

#if !defined(VBOX_WITH_XPCOM)

    /*
     * We initialize COM in GUI thread in STA, to be compliant with QT and
     * OLE requirments (for example to allow D&D), while other threads
     * initialized in regular MTA. To allow fast proxyless access from
     * GUI thread to COM objects, we explicitly provide our COM objects
     * with free threaded marshaller.
     * !!!!! Please think twice before touching this code !!!!!
     */
    DWORD flags = fGui ?
                  COINIT_APARTMENTTHREADED
                | COINIT_SPEED_OVER_MEMORY
                :
                  COINIT_MULTITHREADED
                | COINIT_DISABLE_OLE1DDE
                | COINIT_SPEED_OVER_MEMORY;

    rc = CoInitializeEx(NULL, flags);

    /* the overall result must be either S_OK or S_FALSE (S_FALSE means
     * "already initialized using the same apartment model") */
    AssertMsg(rc == S_OK || rc == S_FALSE, ("rc=%08X\n", rc));

    /* To be flow compatible with the XPCOM case, we return here if this isn't
     * the main thread or if it isn't its first initialization call.
     * Note! CoInitializeEx and CoUninitialize does it's own reference
     *       counting, so this exercise is entirely for the EventQueue init. */
    bool fRc;
    RTTHREAD hSelf = RTThreadSelf();
    if (hSelf != NIL_RTTHREAD)
        ASMAtomicCmpXchgHandle(&gCOMMainThread, hSelf, NIL_RTTHREAD, fRc);
    else
        fRc = false;

    if (fGui)
        Assert(RTThreadIsMain(hSelf));

    if (!fRc)
    {
        if (   gCOMMainThread == hSelf
            && SUCCEEDED(rc))
            gCOMMainInitCount++;

        AssertComRC(rc);
        return rc;
    }
    Assert(RTThreadIsMain(hSelf));

    /* this is the first main thread initialization */
    Assert(gCOMMainInitCount == 0);
    if (SUCCEEDED(rc))
        gCOMMainInitCount = 1;

#else /* !defined (VBOX_WITH_XPCOM) */

    /* Unused here */
    NOREF(fGui);

    if (ASMAtomicXchgBool(&gIsXPCOMInitialized, true) == true)
    {
        /* XPCOM is already initialized on the main thread, no special
         * initialization is necessary on additional threads. Just increase
         * the init counter if it's a main thread again (to correctly support
         * nested calls to Initialize()/Shutdown() for compatibility with
         * Win32). */

        nsCOMPtr<nsIEventQueue> eventQ;
        rc = NS_GetMainEventQ(getter_AddRefs(eventQ));

        if (NS_SUCCEEDED(rc))
        {
            PRBool isOnMainThread = PR_FALSE;
            rc = eventQ->IsOnCurrentThread(&isOnMainThread);
            if (NS_SUCCEEDED(rc) && isOnMainThread)
                ++gXPCOMInitCount;
        }

        AssertComRC(rc);
        return rc;
    }
    Assert(RTThreadIsMain(RTThreadSelf()));

    /* this is the first initialization */
    gXPCOMInitCount = 1;
    bool const fInitEventQueues = true;

    /* prepare paths for registry files */
    char szCompReg[RTPATH_MAX];
    char szXptiDat[RTPATH_MAX];

    int vrc = GetVBoxUserHomeDirectory(szCompReg, sizeof(szCompReg));
    if (vrc == VERR_ACCESS_DENIED)
        return NS_ERROR_FILE_ACCESS_DENIED;
    AssertRCReturn(vrc, NS_ERROR_FAILURE);
    strcpy(szXptiDat, szCompReg);

    vrc = RTPathAppend(szCompReg, sizeof(szCompReg), "compreg.dat");
    AssertRCReturn(vrc, NS_ERROR_FAILURE);
    vrc = RTPathAppend(szXptiDat, sizeof(szXptiDat), "xpti.dat");
    AssertRCReturn(vrc, NS_ERROR_FAILURE);

    LogFlowFunc(("component registry  : \"%s\"\n", szCompReg));
    LogFlowFunc(("XPTI data file      : \"%s\"\n", szXptiDat));

#if defined (XPCOM_GLUE)
    XPCOMGlueStartup(nsnull);
#endif

    static const char *kAppPathsToProbe[] =
    {
        NULL, /* 0: will use VBOX_APP_HOME */
        NULL, /* 1: will try RTPathAppPrivateArch() */
#ifdef RT_OS_LINUX
        "/usr/lib/virtualbox",
        "/opt/VirtualBox",
#elif RT_OS_SOLARIS
        "/opt/VirtualBox/amd64",
        "/opt/VirtualBox/i386",
#elif RT_OS_DARWIN
        "/Application/VirtualBox.app/Contents/MacOS",
#endif
    };

    /* Find out the directory where VirtualBox binaries are located */
    for (size_t i = 0; i < RT_ELEMENTS(kAppPathsToProbe); ++ i)
    {
        char szAppHomeDir[RTPATH_MAX];

        if (i == 0)
        {
            /* Use VBOX_APP_HOME if present */
            vrc = RTEnvGetEx(RTENV_DEFAULT, "VBOX_APP_HOME", szAppHomeDir, sizeof(szAppHomeDir), NULL);
            if (vrc == VERR_ENV_VAR_NOT_FOUND)
                continue;
            AssertRC(vrc);
        }
        else if (i == 1)
        {
            /* Use RTPathAppPrivateArch() first */
            vrc = RTPathAppPrivateArch(szAppHomeDir, sizeof(szAppHomeDir));
            AssertRC(vrc);
        }
        else
        {
            /* Iterate over all other paths */
            szAppHomeDir[RTPATH_MAX - 1] = '\0';
            strncpy(szAppHomeDir, kAppPathsToProbe[i], RTPATH_MAX - 1);
            vrc = VINF_SUCCESS;
        }
        if (RT_FAILURE(vrc))
        {
            rc = NS_ERROR_FAILURE;
            continue;
        }

        char szCompDir[RTPATH_MAX];
        vrc = RTPathAppend(strcpy(szCompDir, szAppHomeDir), sizeof(szCompDir), "components");
        if (RT_FAILURE(vrc))
        {
            rc = NS_ERROR_FAILURE;
            continue;
        }
        LogFlowFunc(("component directory : \"%s\"\n", szCompDir));

        nsCOMPtr<DirectoryServiceProvider> dsProv;
        dsProv = new DirectoryServiceProvider();
        if (dsProv)
            rc = dsProv->init(szCompReg, szXptiDat, szCompDir, szAppHomeDir);
        else
            rc = NS_ERROR_OUT_OF_MEMORY;
        if (NS_FAILED(rc))
            break;

        /* Setup the application path for NS_InitXPCOM2. Note that we properly
         * answer the NS_XPCOM_CURRENT_PROCESS_DIR query in our directory
         * service provider but it seems to be activated after the directory
         * service is used for the first time (see the source NS_InitXPCOM2). So
         * use the same value here to be on the safe side. */
        nsCOMPtr <nsIFile> appDir;
        {
            char *appDirCP = NULL;
            vrc = RTStrUtf8ToCurrentCP(&appDirCP, szAppHomeDir);
            if (RT_SUCCESS(vrc))
            {
                nsCOMPtr<nsILocalFile> file;
                rc = NS_NewNativeLocalFile(nsEmbedCString(appDirCP),
                                           PR_FALSE, getter_AddRefs(file));
                if (NS_SUCCEEDED(rc))
                    appDir = do_QueryInterface(file, &rc);

                RTStrFree(appDirCP);
            }
            else
                rc = NS_ERROR_FAILURE;
        }
        if (NS_FAILED(rc))
            break;

        /* Set VBOX_XPCOM_HOME to the same app path to make XPCOM sources that
         * still use it instead of the directory service happy */
        vrc = RTEnvSetEx(RTENV_DEFAULT, "VBOX_XPCOM_HOME", szAppHomeDir);
        AssertRC(vrc);

        /* Finally, initialize XPCOM */
        {
            nsCOMPtr<nsIServiceManager> serviceManager;
            rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), appDir, dsProv);
            if (NS_SUCCEEDED(rc))
            {
                nsCOMPtr<nsIComponentRegistrar> registrar =
                    do_QueryInterface(serviceManager, &rc);
                if (NS_SUCCEEDED(rc))
                {
                    rc = registrar->AutoRegister(nsnull);
                    if (NS_SUCCEEDED(rc))
                    {
                        /* We succeeded, stop probing paths */
                        LogFlowFunc(("Succeeded.\n"));
                        break;
                    }
                }
            }
        }

        /* clean up before the new try */
        rc = NS_ShutdownXPCOM(nsnull);

        if (i == 0)
        {
            /* We failed with VBOX_APP_HOME, don't probe other paths */
            break;
        }
    }

#endif /* !defined (VBOX_WITH_XPCOM) */

    // for both COM and XPCOM, we only get here if this is the main thread;
    // only then initialize the autolock system (AutoLock.cpp)
    Assert(RTThreadIsMain(RTThreadSelf()));
    util::InitAutoLockSystem();

    AssertComRC(rc);

    /*
     * Init the main event queue (ASSUMES it cannot fail).
     */
    if (SUCCEEDED(rc))
        EventQueue::init();

    return rc;
}
Example #11
0
int main(int argc, char **argv)
{
  nsresult rv;

  PRBool serverMode = PR_FALSE;
  if (argc > 1)
  {
    if (strcmp(argv[1], "-server") == 0)
    {
      serverMode = PR_TRUE;
    }
    else
    {
      printf("usage: %s [-server]\n", argv[0]);
      return -1;
    }
  }

  {
    nsCOMPtr<nsIServiceManager> servMan;
    NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
    nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
    NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
    if (registrar)
        registrar->AutoRegister(nsnull);

    // Create the Event Queue for this thread...
    nsCOMPtr<nsIEventQueueService> eqs =
             do_GetService(kEventQueueServiceCID, &rv);
    RETURN_IF_FAILED(rv, "do_GetService(EventQueueService)");

    rv = eqs->CreateMonitoredThreadEventQueue();
    RETURN_IF_FAILED(rv, "CreateMonitoredThreadEventQueue");

    rv = eqs->GetThreadEventQueue(NS_CURRENT_THREAD, &gEventQ);
    RETURN_IF_FAILED(rv, "GetThreadEventQueue");

    nsCOMPtr<ipcIService> ipcServ(do_GetService(IPC_SERVICE_CONTRACTID, &rv));
    RETURN_IF_FAILED(rv, "do_GetService(ipcServ)");
    NS_ADDREF(gIpcServ = ipcServ);

    if (!serverMode)
    {
      rv = DoTest();
      RETURN_IF_FAILED(rv, "DoTest()");
    }
    else
    {
      gIpcServ->AddName("DConnectServer");
    }

    PLEvent *ev;
    while (gKeepRunning)
    {
      gEventQ->WaitForEvent(&ev);
      gEventQ->HandleEvent(ev);
    }

    NS_RELEASE(gIpcServ);

    printf("*** processing remaining events\n");

    // process any remaining events
    while (NS_SUCCEEDED(gEventQ->GetEvent(&ev)) && ev)
        gEventQ->HandleEvent(ev);

    printf("*** done\n");
  } // this scopes the nsCOMPtrs

  // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
  rv = NS_ShutdownXPCOM(nsnull);
  NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
}
int
main(int argc, char* argv[])
{
    if (test_common_init(&argc, &argv) != 0)
        return -1;

    nsresult rv;

    if (argc < 2) {
        printf("usage: %s <file-to-read>\n", argv[0]);
        return -1;
    }
    char* fileName = argv[1];
    {
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
        NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
        if (registrar)
            registrar->AutoRegister(nullptr);

#if defined(PR_LOGGING)
        gTestLog = PR_NewLogModule("Test");
#endif

        nsCOMPtr<nsIFile> srcFile;
        rv = NS_NewNativeLocalFile(nsDependentCString(fileName), false, getter_AddRefs(srcFile));
        if (NS_FAILED(rv)) return rv;

        nsCOMPtr<nsIFile> destFile;
        rv = srcFile->Clone(getter_AddRefs(destFile));
        if (NS_FAILED(rv)) return rv;

        nsCAutoString leafName;
        rv = destFile->GetNativeLeafName(leafName);
        if (NS_FAILED(rv)) return rv;

        nsCAutoString newName(leafName);
        newName.Append(NS_LITERAL_CSTRING(".1"));
        rv = destFile->SetNativeLeafName(newName);
        if (NS_FAILED(rv)) return rv;

        rv = RunTest(srcFile, destFile);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunTest failed");

        newName = leafName;
        newName.Append(NS_LITERAL_CSTRING(".2"));
        rv = destFile->SetNativeLeafName(newName);
        if (NS_FAILED(rv)) return rv;

        rv = RunBlockingTest(srcFile, destFile);
        NS_ASSERTION(NS_SUCCEEDED(rv), "RunBlockingTest failed");

        // give background threads a chance to finish whatever work they may
        // be doing.
        PR_Sleep(PR_SecondsToInterval(1));
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    rv = NS_ShutdownXPCOM(nullptr);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
    return NS_OK;
}
int
main(void)
{
    nsresult rv;

    XPCOMGlueStartup(nullptr);

    // Initialize XPCOM
    nsCOMPtr<nsIServiceManager> servMan;
    rv = NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
    if (NS_FAILED(rv))
    {
        printf("ERROR: XPCOM intialization error [%x].\n",
               static_cast<uint32_t>(rv));
        return -1;
    }

    nsCOMPtr<nsIComponentManager> manager = do_QueryInterface(servMan);

    // Create an instance of our component
    nsCOMPtr<nsISample> mysample;
    rv = manager->CreateInstanceByContractID(NS_SAMPLE_CONTRACTID,
                                             nullptr,
                                             NS_GET_IID(nsISample),
                                             getter_AddRefs(mysample));
    if (NS_FAILED(rv))
    {
        printf("ERROR: Cannot create instance of component " NS_SAMPLE_CONTRACTID " [%x].\n"
               "Debugging hint:\n"
               "\tsetenv NSPR_LOG_MODULES nsComponentManager:5\n"
               "\tsetenv NSPR_LOG_FILE xpcom.log\n"
               "\t./nsTestSample\n"
               "\t<check the contents for xpcom.log for possible cause of error>.\n",
               static_cast<uint32_t>(rv));
        return -2;
    }

    // Call methods on our sample to test it out.
    rv = mysample->WriteValue("Inital print:");
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::WriteValue() [%x]\n",
               static_cast<uint32_t>(rv));
        return -3;
    }

    const char *testValue = "XPCOM defies gravity";
    rv = mysample->SetValue(testValue);
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::SetValue() [%x]\n",
               static_cast<uint32_t>(rv));
        return -3;
    }
    printf("Set value to: %s\n", testValue);
    char *str;
    rv = mysample->GetValue(&str);

    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::GetValue() [%x]\n",
               static_cast<uint32_t>(rv));
        return -3;
    }
    if (strcmp(str, testValue))
    {
        printf("Test FAILED.\n");
        return -4;
    }

    NS_Free(str);

    rv = mysample->WriteValue("Final print :");
    printf("Test passed.\n");
    
    // All nsCOMPtr's must be deleted prior to calling shutdown XPCOM
    // as we should not hold references passed XPCOM Shutdown.
    servMan = 0;
    manager = 0;
    mysample = 0;
    
    // Shutdown XPCOM
    NS_ShutdownXPCOM(nullptr);

    XPCOMGlueShutdown();
    return 0;
}
Example #14
0
/** entry point */
int main(int argc, char *argv[])
{
    const char *uuid = NULL;
    int c;
    int listHostModes = 0;
    int quit = 0;
    const struct option options[] =
    {
        { "help",          no_argument,       NULL, 'h' },
        { "startvm",       required_argument, NULL, 's' },
        { "fixedres",      required_argument, NULL, 'f' },
        { "listhostmodes", no_argument,       NULL, 'l' },
        { "scale",         no_argument,       NULL, 'c' }
    };

    printf("VirtualBox DirectFB GUI built %s %s\n"
           "(C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
           "(C) 2004-2005 secunet Security Networks AG\n", __DATE__, __TIME__);

    for (;;)
    {
        c = getopt_long(argc, argv, "s:", options, NULL);
        if (c == -1)
            break;
        switch (c)
        {
            case 'h':
            {
                showusage();
                exit(0);
                break;
            }
            case 's':
            {
                // UUID as string, parse it
                RTUUID buuid;
                if (!RT_SUCCESS(RTUuidFromStr((PRTUUID)&buuid, optarg)))
                {
                    printf("Error, invalid UUID format given!\n");
                    showusage();
                    exit(-1);
                }
                uuid = optarg;
                break;
            }
            case 'f':
            {
                if (sscanf(optarg, "%ux%ux%u", &fixedVideoMode.width, &fixedVideoMode.height,
                           &fixedVideoMode.bpp) != 3)
                {
                    printf("Error, invalid resolution argument!\n");
                    showusage();
                    exit(-1);
                }
                useFixedVideoMode = 1;
                break;
            }
            case 'l':
            {
                listHostModes = 1;
                break;
            }
            case 'c':
            {
                scaleGuest = 1;
                break;
            }
            default:
                break;
        }
    }

    // check if we got a UUID
    if (!uuid)
    {
        printf("Error, no UUID given!\n");
        showusage();
        exit(-1);
    }


    /**
     * XPCOM setup
     */

    nsresult rc;
    /*
     * Note that we scope all nsCOMPtr variables in order to have all XPCOM
     * objects automatically released before we call NS_ShutdownXPCOM at the
     * end. This is an XPCOM requirement.
     */
    {
        nsCOMPtr<nsIServiceManager> serviceManager;
        rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
        if (NS_FAILED(rc))
        {
            printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
            exit(-1);
        }

        // register our component
        nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
        if (!registrar)
        {
            printf("Error: could not query nsIComponentRegistrar interface!\n");
            exit(-1);
        }
        registrar->AutoRegister(nsnull);

        /*
         * Make sure the main event queue is created. This event queue is
         * responsible for dispatching incoming XPCOM IPC messages. The main
         * thread should run this event queue's loop during lengthy non-XPCOM
         * operations to ensure messages from the VirtualBox server and other
         * XPCOM IPC clients are processed. This use case doesn't perform such
         * operations so it doesn't run the event loop.
         */
        nsCOMPtr<nsIEventQueue> eventQ;
        rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
        if (NS_FAILED(rc))
        {
            printf("Error: could not get main event queue! rc=%08X\n", rc);
            return -1;
        }

        /*
         * Now XPCOM is ready and we can start to do real work.
         * IVirtualBox is the root interface of VirtualBox and will be
         * retrieved from the XPCOM component manager. We use the
         * XPCOM provided smart pointer nsCOMPtr for all objects because
         * that's very convenient and removes the need deal with reference
         * counting and freeing.
         */
        nsCOMPtr<nsIComponentManager> manager;
        rc = NS_GetComponentManager (getter_AddRefs (manager));
        if (NS_FAILED(rc))
        {
            printf("Error: could not get component manager! rc=%08X\n", rc);
            exit(-1);
        }

        nsCOMPtr<IVirtualBox> virtualBox;
        rc = manager->CreateInstanceByContractID(NS_VIRTUALBOX_CONTRACTID,
                                                 nsnull,
                                                 NS_GET_IID(IVirtualBox),
                                                 getter_AddRefs(virtualBox));
        if (NS_FAILED(rc))
        {
            printf("Error, could not instantiate object! rc=0x%x\n", rc);
            exit(-1);
        }

        nsCOMPtr<ISession> session;
        rc = manager->CreateInstance(CLSID_Session,
                                     nsnull,
                                     NS_GET_IID(ISession),
                                     getter_AddRefs(session));
        if (NS_FAILED(rc))
        {
            printf("Error: could not instantiate Session object! rc = %08X\n", rc);
            exit(-1);
        }

        // open session for this VM
        rc = virtualBox->OpenSession(session, NS_ConvertUTF8toUTF16(uuid).get());
        if (NS_FAILED(rc))
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IMachine> machine;
        session->GetMachine(getter_AddRefs(machine));
        if (!machine)
        {
            printf("Error: given machine not found!\n");
            exit(-1);
        }
        nsCOMPtr<IConsole> console;
        session->GetConsole(getter_AddRefs(console));
        if (!console)
        {
            printf("Error: cannot get console!\n");
            exit(-1);
        }

        nsCOMPtr<IDisplay> display;
        console->GetDisplay(getter_AddRefs(display));
        if (!display)
        {
            printf("Error: could not get display object!\n");
            exit(-1);
        }

        nsCOMPtr<IKeyboard> keyboard;
        nsCOMPtr<IMouse> mouse;
        VBoxDirectFB *frameBuffer = NULL;

        /**
         * Init DirectFB
         */
        IDirectFB *dfb = NULL;
        IDirectFBSurface *surface = NULL;
        IDirectFBInputDevice *dfbKeyboard = NULL;
        IDirectFBInputDevice *dfbMouse = NULL;
        IDirectFBEventBuffer *dfbEventBuffer = NULL;
        DFBSurfaceDescription dsc;
        int screen_width, screen_height;

        DFBCHECK(DirectFBInit(&argc, &argv));
        DFBCHECK(DirectFBCreate(&dfb));
        DFBCHECK(dfb->SetCooperativeLevel(dfb, DFSCL_FULLSCREEN));
        // populate our structure of supported video modes
        DFBCHECK(dfb->EnumVideoModes(dfb, enumVideoModesHandler, NULL));

        if (listHostModes)
        {
            printf("*****************************************************\n");
            printf("Number of available host video modes: %u\n", numVideoModes);
            for (uint32_t i = 0; i < numVideoModes; i++)
            {
                printf("Mode %u: xres = %u, yres = %u, bpp = %u\n", i,
                       videoModes[i].width, videoModes[i].height, videoModes[i].bpp);
            }
            printf("Note: display modes with bpp < have been filtered out\n");
            printf("*****************************************************\n");
            goto Leave;
        }

        if (useFixedVideoMode)
        {
            int32_t bestVideoMode = getBestVideoMode(fixedVideoMode.width,
                                                     fixedVideoMode.height,
                                                     fixedVideoMode.bpp);
            // validate the fixed mode
            if ((bestVideoMode == -1) ||
                ((fixedVideoMode.width  != videoModes[bestVideoMode].width) ||
                (fixedVideoMode.height != videoModes[bestVideoMode].height) ||
                (fixedVideoMode.bpp    != videoModes[bestVideoMode].bpp)))
            {
                printf("Error: the specified fixed video mode is not available!\n");
                exit(-1);
            }
        } else
        {
            initialVideoMode = getBestVideoMode(640, 480, 16);
            if (initialVideoMode == -1)
            {
                printf("Error: initial video mode 640x480x16 is not available!\n");
                exit(-1);
            }
        }

        dsc.flags = DSDESC_CAPS;
        dsc.caps = DSCAPS_PRIMARY;
        DFBCHECK(dfb->CreateSurface(dfb, &dsc, &surface));
        DFBCHECK(surface->Clear(surface, 0, 0, 0, 0));
        DFBCHECK(surface->GetSize(surface, &screen_width, &screen_height));
        DFBCHECK(dfb->GetInputDevice(dfb, DIDID_KEYBOARD, &dfbKeyboard));
        DFBCHECK(dfbKeyboard->CreateEventBuffer(dfbKeyboard, &dfbEventBuffer));
        DFBCHECK(dfb->GetInputDevice(dfb, DIDID_MOUSE, &dfbMouse));
        DFBCHECK(dfbMouse->AttachEventBuffer(dfbMouse, dfbEventBuffer));


        if (useFixedVideoMode)
        {
            printf("Information: setting video mode to %ux%ux%u\n", fixedVideoMode.width,
                   fixedVideoMode.height, fixedVideoMode.bpp);
            DFBCHECK(dfb->SetVideoMode(dfb, fixedVideoMode.width,
                                       fixedVideoMode.height, fixedVideoMode.bpp));
        } else
        {
            printf("Information: starting with default video mode %ux%ux%u\n",
                   videoModes[initialVideoMode].width, videoModes[initialVideoMode].height,
                   videoModes[initialVideoMode].bpp);
            DFBCHECK(dfb->SetVideoMode(dfb, videoModes[initialVideoMode].width,
                                            videoModes[initialVideoMode].height,
                                            videoModes[initialVideoMode].bpp));
        }

        // register our framebuffer
        frameBuffer = new VBoxDirectFB(dfb, surface);
        display->SetFramebuffer(0, frameBuffer);

        /**
         * Start the VM execution thread
         */
        console->PowerUp(NULL);

        console->GetKeyboard(getter_AddRefs(keyboard));
        console->GetMouse(getter_AddRefs(mouse));

        /**
         * Main event loop
         */
        #define MAX_KEYEVENTS 10
        PRInt32 keyEvents[MAX_KEYEVENTS];
        int numKeyEvents;

        while (!quit)
        {
            DFBInputEvent event;

            numKeyEvents = 0;
            DFBCHECK(dfbEventBuffer->WaitForEvent(dfbEventBuffer));
            while (dfbEventBuffer->GetEvent(dfbEventBuffer, DFB_EVENT(&event)) == DFB_OK)
            {
                int mouseXDelta = 0;
                int mouseYDelta = 0;
                int mouseZDelta = 0;
                switch (event.type)
                {
                    #define QUEUEEXT() keyEvents[numKeyEvents++] = 0xe0
                    #define QUEUEKEY(scan) keyEvents[numKeyEvents++] = scan | (event.type == DIET_KEYRELEASE ? 0x80 : 0x00)
                    #define QUEUEKEYRAW(scan) keyEvents[numKeyEvents++] = scan
                    case DIET_KEYPRESS:
                    case DIET_KEYRELEASE:
                    {
                        // @@@AH development hack to get out of it!
                        if ((event.key_id == DIKI_ESCAPE) && (event.modifiers & (DIMM_CONTROL | DIMM_ALT)))
                            quit = 1;

                        if (numKeyEvents < MAX_KEYEVENTS)
                        {
                            //printf("%s: key_code: 0x%x\n", event.type == DIET_KEYPRESS ? "DIET_KEYPRESS" : "DIET_KEYRELEASE", event.key_code);
                            switch ((uint32_t)event.key_id)
                            {
                                case DIKI_CONTROL_R:
                                    QUEUEEXT();
                                    QUEUEKEY(0x1d);
                                    break;
                                case DIKI_INSERT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x52);
                                    break;
                                case DIKI_DELETE:
                                    QUEUEEXT();
                                    QUEUEKEY(0x53);
                                    break;
                                case DIKI_HOME:
                                    QUEUEEXT();
                                    QUEUEKEY(0x47);
                                    break;
                                case DIKI_END:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4f);
                                    break;
                                case DIKI_PAGE_UP:
                                    QUEUEEXT();
                                    QUEUEKEY(0x49);
                                    break;
                                case DIKI_PAGE_DOWN:
                                    QUEUEEXT();
                                    QUEUEKEY(0x51);
                                    break;
                                case DIKI_LEFT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4b);
                                    break;
                                case DIKI_RIGHT:
                                    QUEUEEXT();
                                    QUEUEKEY(0x4d);
                                    break;
                                case DIKI_UP:
                                    QUEUEEXT();
                                    QUEUEKEY(0x48);
                                    break;
                                case DIKI_DOWN:
                                    QUEUEEXT();
                                    QUEUEKEY(0x50);
                                    break;
                                case DIKI_KP_DIV:
                                    QUEUEEXT();
                                    QUEUEKEY(0x35);
                                    break;
                                case DIKI_KP_ENTER:
                                    QUEUEEXT();
                                    QUEUEKEY(0x1c);
                                    break;
                                case DIKI_PRINT:
                                    // the break code is inverted!
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEY(0x2a);
                                        QUEUEEXT();
                                        QUEUEKEY(0x37);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEY(0x37);
                                        QUEUEEXT();
                                        QUEUEKEY(0x2a);
                                    }
                                    break;
                                case DIKI_PAUSE:
                                    // This is a super weird key. No break code and a 6 byte
                                    // combination.
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEKEY(0xe1);
                                        QUEUEKEY(0x1d);
                                        QUEUEKEY(0x45);
                                        QUEUEKEY(0xe1);
                                        QUEUEKEY(0x9d);
                                        QUEUEKEY(0xc5);
                                    }
                                    break;
                                case DIKI_META_L:
                                    // the left Windows logo is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x1f);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x1f);
                                    }
                                    break;
                                case DIKI_META_R:
                                    // the right Windows logo is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x27);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x27);
                                    }
                                    break;
                                case DIKI_SUPER_R:
                                    // the popup menu is a bit different
                                    if (event.type == DIET_KEYPRESS)
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0x2f);
                                    } else
                                    {
                                        QUEUEEXT();
                                        QUEUEKEYRAW(0xf0);
                                        QUEUEKEYRAW(0x2f);
                                    }
                                    break;

                                default:
                                    // check if we got a hardware scancode
                                    if (event.key_code != -1)
                                    {
                                        // take the scancode from DirectFB as is
                                        QUEUEKEY(event.key_code);
                                    } else
                                    {
                                        // XXX need extra handling!
                                    }
                            }
                        }
                        break;
                    }
                    #undef QUEUEEXT
                    #undef QUEUEKEY
                    #undef QUEUEKEYRAW

                    case DIET_AXISMOTION:
                    {
                        switch (event.axis)
                        {
                            case DIAI_X:
                                mouseXDelta += event.axisrel;
                                break;
                            case DIAI_Y:
                                mouseYDelta += event.axisrel;
                                break;
                            case DIAI_Z:
                                mouseZDelta += event.axisrel;
                                break;
                            default:
                                break;
                        }
                        // fall through
                    }
                    case DIET_BUTTONPRESS:
                        // fall through;
                    case DIET_BUTTONRELEASE:
                    {
                        int buttonState = 0;
                        if (event.buttons & DIBM_LEFT)
                            buttonState |= MouseButtonState::LeftButton;
                        if (event.buttons & DIBM_RIGHT)
                            buttonState |= MouseButtonState::RightButton;
                        if (event.buttons & DIBM_MIDDLE)
                            buttonState |= MouseButtonState::MiddleButton;
                        mouse->PutMouseEvent(mouseXDelta, mouseYDelta, mouseZDelta,
                                             buttonState);
                        break;
                    }
                    default:
                        break;
                }
            }
            // did we get any keyboard events?
            if (numKeyEvents > 0)
            {
                uint32_t codesStored;
                if (numKeyEvents > 1)
                {
                    keyboard->PutScancodes(numKeyEvents, keyEvents,
                                           &codesStored);
                } else
                {
                    keyboard->PutScancode(keyEvents[0]);
                }
            }
        }
        {
            nsCOMPtr<IProgress> progress;
            console->PowerDown(getter_AddRefs(progress));
            progress->WaitForCompletion(-1);
        }
    }

Leave:
    /*
     * Perform the standard XPCOM shutdown procedure.
     */
    NS_ShutdownXPCOM(nsnull);

    return 0;
}
int WINAPI WinMain(HINSTANCE inst, 
                   HINSTANCE prevInstance, 
                   LPSTR lpszCmdLine,
                   int nShowCmd)
{
	char* lpszAppName = "HelloWorld";
	HWND wnd;
	WNDCLASSEX wndclass;
	int retCode;

    {	//  Needed to scope all nsCOMPtr within XPCOM Init and Shutdown
      nsresult rv;
      nsCOMPtr<nsIServiceManager> servMan;
      rv = NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);
      if(NS_FAILED(rv))
      {
        ErrorBox("Failed to initialize xpcom.");
        return -1;
      }
      
      nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
      NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
      registrar->AutoRegister(nullptr);
      
      nsCOMPtr<nsINativeApp> nativeAppService(do_GetService(kNativeAppCID, &rv));

      if(NS_FAILED(rv))
      {
        ErrorBox("Failed to get nativeAppService");
        return -1;
      }
      wndclass.cbSize        = sizeof(wndclass);
      wndclass.style         = CS_HREDRAW | CS_VREDRAW;
      wndclass.lpfnWndProc   = WndProc;
      wndclass.cbClsExtra    = 0;
      wndclass.cbWndExtra    = 0;
      wndclass.hInstance     = inst;
      wndclass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
      wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
      wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
      wndclass.lpszMenuName  = NULL;
      wndclass.lpszClassName = lpszAppName;
      wndclass.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

      RegisterClassEx(&wndclass) ;
      
      wnd = CreateWindow(lpszAppName, "The Hello World",
                         WS_OVERLAPPEDWINDOW,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         CW_USEDEFAULT, CW_USEDEFAULT,
                         NULL, NULL, inst, NULL);		     
      
      ShowWindow(wnd, nShowCmd);
      UpdateWindow(wnd);
      
      nsCOMPtr<nsIEventLoop> eventLoop;
      
      if(NS_FAILED(nativeAppService->CreateEventLoop(L"_MainLoop", 
                                                     nsEventLoopTypes::MainAppLoop, getter_AddRefs(eventLoop))))
        {
          ErrorBox("Failed to create event Loop");
          return 0;
        } 
      
      eventLoop->Run(nullptr, nullptr, nullptr, &retCode);
      eventLoop = nullptr; // Clear out before Shutting down XPCOM
      
      InfoBox("Hello World app is out of loop");
    }
	NS_ShutdownXPCOM(nullptr);
	InfoBox("Hello World app is exiting");
	return retCode;
}
Example #16
0
int
main(int argc, char* argv[])
{
    if (test_common_init(&argc, &argv) != 0)
        return -1;

    nsresult rv;

    if (argc < 2) {
        printf("usage: %s <url> <file-to-upload>\n", argv[0]);
        return -1;
    }
    char* uriSpec  = argv[1];
    char* fileName = argv[2];

#if defined(PR_LOGGING)
    gTestLog = PR_NewLogModule("Test");
#endif

    {
        nsCOMPtr<nsIServiceManager> servMan;
        NS_InitXPCOM2(getter_AddRefs(servMan), nullptr, nullptr);

        // first thing to do is create ourselves a stream that
        // is to be uploaded.
        nsCOMPtr<nsIInputStream> uploadStream;
        rv = NS_NewPostDataStream(getter_AddRefs(uploadStream),
                                  true,
                                  nsDependentCString(fileName)); // XXX UTF-8
        if (NS_FAILED(rv)) return -1;

        nsCOMPtr<nsIIOService> ioService(do_GetService(kIOServiceCID, &rv));

        // create our url.
        nsCOMPtr<nsIURI> uri;
        rv = NS_NewURI(getter_AddRefs(uri), uriSpec);
        if (NS_FAILED(rv)) return -1;

        nsCOMPtr<nsIChannel> channel;
        rv = ioService->NewChannelFromURI(uri, getter_AddRefs(channel));
        if (NS_FAILED(rv)) return -1;

        // QI and set the upload stream
        nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(channel));
        uploadChannel->SetUploadStream(uploadStream, EmptyCString(), -1);

        // create a dummy listener
        InputTestConsumer* listener;

        listener = new InputTestConsumer;
        if (!listener) {
            NS_ERROR("Failed to create a new stream listener!");
            return -1;
        }
        NS_ADDREF(listener);

        channel->AsyncOpen(listener, nullptr);

        PumpEvents();
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    rv = NS_ShutdownXPCOM(nullptr);
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");

    return 0;
}
Example #17
0
int main(int argc, char **argv)
{
#ifdef WIN32
    PRBool bLoadMySQL = PR_FALSE;

#ifdef DEBUG
    // the pref setting for debug is too late.  Let's use a cmdline arg of -debug
    for(int i=1; i<argc; i++)
    {
        if (stricmp(argv[i], "-debug") == 0)
        {        
            char szMessage [256];
            wsprintf (szMessage, "Please attach a debugger to the process 0x%X"
                                 " [%d] and click OK",
                      GetCurrentProcessId(), GetCurrentProcessId() );
            MessageBox(NULL, szMessage, "Jaxer Debug Time!",
                       MB_OK | MB_SERVICE_NOTIFICATION);

            removeArg(&argc, &argv[i]);
            break;
        }
    }
#endif
#endif

    nsresult rv;

	nsIServiceManager* serviceManager;
    AppDirectoryProvider appDirectoryProvider;
    nsCOMPtr<nsIDirectoryServiceProvider> dirProvider(&appDirectoryProvider);


	/* Preprocess specific command line args */
	for (int i = 1; i < argc; /*NOP*/ ) {
		if (!strcmp(argv[i], "-tempdir") || !strcmp(argv[i], "--tempdir")) {
			removeArg(&argc, &argv[i]);
			if (i < argc) {
				appDirectoryProvider.SetTempPath(nsDependentCString(argv[i]));
				removeArg(&argc, &argv[i]);
			}
		} else if (!strcmp(argv[i], "-extensions") || !strcmp(argv[i], "--extensions")) {
			removeArg(&argc, &argv[i]);
			if (i < argc) {
				appDirectoryProvider.SetExtensionsPath(nsDependentCString(argv[i]));
				removeArg(&argc, &argv[i]);
			}
		} else if (!strcmp(argv[i], "-handlewinmysqlclientbug") || !strcmp(argv[i], "--handlewinmysqlclientbug")) {
			removeArg(&argc, &argv[i]);
			if (i < argc) {
#ifdef _WIN32
				if(!stricmp(argv[i], "true") || !strcmp(argv[i], "1"))
                    bLoadMySQL = PR_TRUE;
#endif
				removeArg(&argc, &argv[i]);
			}
		} else if (!PL_strcasecmp(argv[i], "-webserverconfig")) {
			removeArg(&argc, &argv[i]);
			if (i < argc) {
				gWebServerConfig = strdup(argv[i]);
				removeArg(&argc, &argv[i]);
			}
		} else {
			++i;
		}
	}

#ifdef _WIN32
    HINSTANCE hMySQL = NULL;
    BOOL bSuccess = FALSE;
    if (bLoadMySQL)
    {
        //printf("Enabled LoadMySQL\n");
        hMySQL = LoadLibrary("libmysql.dll");
        if (hMySQL)
        {
            bSuccess = DisableThreadLibraryCalls(hMySQL);
            if (!bSuccess)
                fprintf(stderr, "Failed to disable thread library call: err=%d\n", GetLastError());
        }else
        {
            fprintf(stderr, "Failed to load libmysql.dll: err=%d\n", GetLastError());
        }
    }
#endif

#ifdef _BUILD_STATIC_BIN
    // Combine the static components and the app components.
    PRUint32 combinedCount = kStaticModuleCount + kModulesCount;
    static nsStaticModuleInfo *sCombined = new nsStaticModuleInfo[combinedCount];
    NS_ENSURE_TRUE(sCombined, NS_ERROR_OUT_OF_MEMORY);

    memcpy(sCombined, kPStaticModules,
           sizeof(nsStaticModuleInfo) * kStaticModuleCount);
    memcpy(sCombined + kStaticModuleCount, &kStaticModules,
           sizeof(nsStaticModuleInfo) * kModulesCount);

    // Spin up the XPCOM infrastructure.
    NS_InitXPCOM3(&serviceManager, nsnull, dirProvider, sCombined, combinedCount);
#else
    // Spin up the XPCOM infrastructure.
    NS_InitXPCOM3(&serviceManager, nsnull, dirProvider, &kStaticModules, kModulesCount); 
#endif
	
    // Exit immediately if we're only interested in XPCOM auto-registration.
    int exitCode = 1;
    if (argc > 1 && !strcmp(argv[1], "-reg")) {
        exitCode = 0;
        gJaxerLog.Log(eDEBUG, "Jaxer -reg call.");
    } else {
        // Give FCGX a chance to adopt stdin/stdout.
	do {
		/* Initialize appData */
		nsCOMPtr<nsIFile> processDir;
		rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, getter_AddRefs(processDir));
		if (NS_FAILED(rv)) {
			fprintf(stderr, "Get current process directory failed: rv=0x%x", rv);
			break;
		}

		nsCOMPtr<nsILocalFile> xreDirectory(do_QueryInterface(processDir));
		appData.xreDirectory = xreDirectory;
		NS_IF_ADDREF(appData.xreDirectory);

#ifdef MOZ_CRASHREPORTER
		rv = CrashReporter::SetExceptionHandler(appData.xreDirectory, appData.crashReporterURL);
		if (NS_SUCCEEDED(rv)) {
			// pass some basic info from the app data
			if (appData.vendor)
				CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("Vendor"),
											 nsDependentCString(appData.vendor));
			if (appData.name)
				CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("ProductName"),
											 nsDependentCString(appData.name));
			if (appData.version)
				CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("Version"),
											 nsDependentCString(appData.version));
			if (appData.buildID)
				CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("BuildID"),
											 nsDependentCString(appData.buildID));
		}

		nsCOMPtr<nsIFile> dumpD;
		rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(dumpD));
		if (NS_FAILED(rv)) {
			fprintf(stderr, "Jaxer: Cannot get OS tmp dir. rv=0x%x", rv);
			break;
		}

		nsAutoString pathStr;
		rv = dumpD->GetPath(pathStr);
		if(NS_SUCCEEDED(rv)) {
		  CrashReporter::SetMinidumpPath(pathStr);
		}
#endif

		// call Jaxer main
		exitCode = jaxerMain(argc, argv);
	} while(PR_FALSE);
    }


#ifdef MOZ_CRASHREPORTER
	CrashReporter::UnsetExceptionHandler();
#endif
	NS_IF_RELEASE(appData.xreDirectory);

	appDirectoryProvider.DoShutdown();
	dirProvider = nsnull;

	NS_ShutdownXPCOM(serviceManager);

#ifdef _BUILD_STATIC_BIN
    delete[] sCombined;
#endif

#ifdef _WIN32
    if (bLoadMySQL && hMySQL)
        FreeLibrary(hMySQL);
#endif

    return exitCode;
}
Example #18
0
 ~ScopedXPCOM()
 {
   if (NS_SUCCEEDED(rv))
     NS_ShutdownXPCOM(nullptr);
 }
Example #19
0
int
main(void)
{
    nsresult rv;

#ifdef XPCOM_GLUE
    XPCOMGlueStartup(nsnull);
#endif

    // Initialize XPCOM
    nsCOMPtr<nsIServiceManager> servMan;
    rv = NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
    if (NS_FAILED(rv))
    {
        printf("ERROR: XPCOM intialization error [%x].\n", rv);
        return -1;
    }
    // register all components in our default component directory
    nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
    NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
    registrar->AutoRegister(nsnull);
    
    nsCOMPtr<nsIComponentManager> manager = do_QueryInterface(registrar);
    NS_ASSERTION(registrar, "Null nsIComponentManager");
    
    // Create an instance of our component
    nsCOMPtr<nsISample> mysample;
    rv = manager->CreateInstanceByContractID(NS_SAMPLE_CONTRACTID,
                                             nsnull,
                                             NS_GET_IID(nsISample),
                                             getter_AddRefs(mysample));
    if (NS_FAILED(rv))
    {
        printf("ERROR: Cannot create instance of component " NS_SAMPLE_CONTRACTID " [%x].\n"
               "Debugging hint:\n"
               "\tsetenv NSPR_LOG_MODULES nsComponentManager:5\n"
               "\tsetenv NSPR_LOG_FILE xpcom.log\n"
               "\t./nsTestSample\n"
               "\t<check the contents for xpcom.log for possible cause of error>.\n",
               rv);
        return -2;
    }

    // Call methods on our sample to test it out.
    rv = mysample->WriteValue("Inital print:");
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::WriteValue() [%x]\n", rv);
        return -3;
    }

    const char *testValue = "XPCOM defies gravity";
    rv = mysample->SetValue(testValue);
    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::SetValue() [%x]\n", rv);
        return -3;
    }
    printf("Set value to: %s\n", testValue);
#ifndef XPCOM_GLUE
    nsXPIDLCString str;
    rv = mysample->GetValue(getter_Copies(str));
#else
    char *str;
    rv = mysample->GetValue(&str);
#endif

    if (NS_FAILED(rv))
    {
        printf("ERROR: Calling nsISample::GetValue() [%x]\n", rv);
        return -3;
    }
    if (strcmp(str, testValue))
    {
        printf("Test FAILED.\n");
        return -4;
    }

#ifdef XPCOM_GLUE
    nsMemory::Free(str);
#endif
    rv = mysample->WriteValue("Final print :");
    printf("Test passed.\n");
    
    // All nsCOMPtr's must be deleted prior to calling shutdown XPCOM
    // as we should not hold references passed XPCOM Shutdown.
    servMan = 0;
    registrar = 0;
    manager = 0;
    mysample = 0;
    
    // Shutdown XPCOM
    NS_ShutdownXPCOM(nsnull);

#ifdef XPCOM_GLUE
    XPCOMGlueShutdown();
#endif
    return 0;
}