<commit_before>/*************************************************************************
 *
 *  $RCSfile: commoncontrol.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-25 16:03:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROLLISTENER_HXX_
#include "brwcontrollistener.hxx"
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif

//............................................................................
namespace pcr
{
//............................................................................
    //==================================================================
    //= OCommonBehaviourControl
    //==================================================================
    //------------------------------------------------------------------
    OCommonBehaviourControl::OCommonBehaviourControl(Window* _pMeAsWin)
        :m_pListener(NULL)
        ,m_pData(NULL)
        ,m_bDir(sal_True)
        ,m_bLocked(sal_False)
        ,m_bModified(sal_False)
        ,m_nLine(0)
        ,m_sStandardString(getStandardString())
        ,m_pMeAsWindow(_pMeAsWin)
    {
        DBG_ASSERT(m_pMeAsWindow != NULL, "OCommonBehaviourControl::OCommonBehaviourControl: invalid window!");
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::SetLocked(sal_Bool _bFlag)
    {
        m_bLocked = _bFlag;
        Font aFont = m_pMeAsWindow->GetFont();
        if (m_bLocked)
        {
            aFont.SetColor(Color(COL_GRAY));
        }
        else
        {
            aFont = m_pMeAsWindow->GetParent()->GetFont();
        }
        m_pMeAsWindow->SetFont(aFont);
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::autoSizeWindow()
    {
        ComboBox aComboBox(m_pMeAsWindow, WB_DROPDOWN);
        aComboBox.SetPosSizePixel(Point(0,0), Size(100,100));
        m_pMeAsWindow->SetSizePixel(aComboBox.GetSizePixel());
    }

    //------------------------------------------------------------------
    sal_Bool OCommonBehaviourControl::handlePreNotify(NotifyEvent& rNEvt)
    {
        if (EVENT_KEYINPUT == rNEvt.GetType())
        {
            const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
            sal_uInt16 nKey = aKeyCode.GetCode();

            if (nKey == KEY_RETURN && !aKeyCode.IsShift())
            {
                LoseFocusHdl(m_pMeAsWindow);
                m_bDir = sal_True;
                if (m_pListener != NULL)
                    m_pListener->TravelLine(this);
                return sal_True;
            }
        }
        return sal_False;
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::CommitModified()
    {
        if (IsModified() && getListener())
            getListener()->Commit(this);
        m_bModified = sal_False;
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::modified(Window* _pSource)
    {
        m_bModified = sal_True;
        if (m_pListener != NULL)
            m_pListener->Modified(this);
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::getFocus(Window* _pSource)
    {
        if (m_pListener != NULL)
            m_pListener->GetFocus(this);
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::commitModified(Window* _pSource)
    {
        if (m_pListener != NULL && m_bModified)
            m_pListener->Commit(this);
        m_bModified = sal_False;
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, ModifiedHdl, Window*, _pWin )
    {
        modified(_pWin);
        return 0;
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, GetFocusHdl, Window*, _pWin )
    {
        getFocus(_pWin);
        return 0;
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, LoseFocusHdl, Window*, _pWin )
    {
        commitModified(_pWin);
        return 0;
    }

//............................................................................
} // namespace pcr
//............................................................................

<commit_msg>INTEGRATION: CWS eforms2 (1.2.154); FILE MERGED 2004/07/16 15:41:43 fs 1.2.154.2: #114856# +DateTime type, and some cleanup at the IBrowserControl 2004/04/26 11:30:29 fs 1.2.154.1: some cleanup/consolidation<commit_after>/*************************************************************************
 *
 *  $RCSfile: commoncontrol.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 12:03:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _EXTENSIONS_PROPCTRLR_COMMONCONTROL_HXX_
#include "commoncontrol.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROLLISTENER_HXX_
#include "brwcontrollistener.hxx"
#endif
#ifndef _SV_COMBOBOX_HXX
#include <vcl/combobox.hxx>
#endif

//............................................................................
namespace pcr
{
//............................................................................
    //==================================================================
    //= OCommonBehaviourControl
    //==================================================================
    //------------------------------------------------------------------
    OCommonBehaviourControl::OCommonBehaviourControl(Window* _pMeAsWin)
        :m_pListener(NULL)
        ,m_bModified(sal_False)
        ,m_nLine(0)
        ,m_sStandardString(getStandardString())
        ,m_pMeAsWindow(_pMeAsWin)
    {
        DBG_ASSERT(m_pMeAsWindow != NULL, "OCommonBehaviourControl::OCommonBehaviourControl: invalid window!");
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::autoSizeWindow()
    {
        ComboBox aComboBox(m_pMeAsWindow, WB_DROPDOWN);
        aComboBox.SetPosSizePixel(Point(0,0), Size(100,100));
        m_pMeAsWindow->SetSizePixel(aComboBox.GetSizePixel());
    }

    //------------------------------------------------------------------
    sal_Bool OCommonBehaviourControl::handlePreNotify(NotifyEvent& rNEvt)
    {
        if (EVENT_KEYINPUT == rNEvt.GetType())
        {
            const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
            sal_uInt16 nKey = aKeyCode.GetCode();

            if (nKey == KEY_RETURN && !aKeyCode.IsShift())
            {
                LoseFocusHdl(m_pMeAsWindow);
                if (m_pListener != NULL)
                    m_pListener->TravelLine(this);
                return sal_True;
            }
        }
        return sal_False;
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::CommitModified()
    {
        if (IsModified() && getListener())
            getListener()->Commit(this);
        m_bModified = sal_False;
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::modified(Window* _pSource)
    {
        m_bModified = sal_True;
        if (m_pListener != NULL)
            m_pListener->Modified(this);
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::getFocus(Window* _pSource)
    {
        if (m_pListener != NULL)
            m_pListener->GetFocus(this);
    }

    //------------------------------------------------------------------
    void OCommonBehaviourControl::commitModified(Window* _pSource)
    {
        CommitModified();
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, ModifiedHdl, Window*, _pWin )
    {
        modified(_pWin);
        return 0;
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, GetFocusHdl, Window*, _pWin )
    {
        getFocus(_pWin);
        return 0;
    }

    //------------------------------------------------------------------
    IMPL_LINK( OCommonBehaviourControl, LoseFocusHdl, Window*, _pWin )
    {
        commitModified(_pWin);
        return 0;
    }

//............................................................................
} // namespace pcr
//............................................................................

<|endoftext|>


<commit_before>/*
 *
 * Copyright (C) 2001  Frank Dabek (fdabek@lcs.mit.edu),
 *   		       Massachusetts Institute of Technology
 *
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include "sfsmisc.h"
#include "dhash_prot.h"
#include "dhash.h"
#include "crypt.h"
#include <sys/time.h>

static bigint *IDs;
static void **data;
str control_socket;
static FILE *outfile;
unsigned int datasize;

int out = 0;
int MAX_OPS_OUT = 1024;

chordID
make_block (void *data)
{
  // size must be word sized
  assert (datasize % sizeof (long) == 0);

  long *rd = (long *)data;
  for (unsigned int i = 0; i < datasize/sizeof(long); i++)
    rd[i] = random();

  return compute_hash (rd, datasize);
}

void
prepare_test_data (int num)
{
  IDs = New chordID[num];
  data = (void **)malloc(sizeof(void *)*num);
  for (int i = 0; i < num; i++) {
    data[i] = malloc(datasize);
    IDs[i] = make_block(data[i]);
  }
}

void
store_cb (bool error, chordID key)
{
  out--;

  if (error)
    fprintf (outfile, "store error\n");
}

int
store (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    dhash.insert ((char *)data[i], datasize, wrap (store_cb));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck ();

  return 0;
}

void
fetch_cb (int i, struct timeval start, ptr<dhash_block> blk)
{
  out--;

  if (!blk) {
    strbuf buf;
    buf << "Error: " << IDs[i] << "\n";
    fprintf (outfile, str (buf).cstr ());
  }
  else if (datasize != blk->len || memcmp (data[i], blk->data, datasize) != 0)
    fatal << "verification failed";
  else {
    struct timeval end;
    gettimeofday(&end, NULL);
    float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
    fprintf (outfile, "%f\n", elapsed);
  }
}

void
fetch (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    struct timeval start;
    gettimeofday (&start, NULL);

    dhash.retrieve (IDs[i], wrap (fetch_cb, i, start));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck();
}

void
usage (char *progname)
{
  warn << "vnode_num control_socket num_trials data_size file <f or s> nops seed\n";
  exit(0);
}

int
main (int argc, char **argv)
{
  setprogname (argv[0]);

  sfsconst_init ();

  if (argc < 9) {
    usage (argv[0]);
    exit (1);
  }

  control_socket = argv[2];
  dhashclient dhash (control_socket);

  int num = atoi(argv[3]);
  datasize = atoi(argv[4]);

  char *output = argv[5];
  if (strcmp(output, "-") == 0)
    outfile = stdout;
  else
    outfile = fopen(output, "w");

  if (!outfile) {
    printf ("could not open %s\n", output);
    exit(1);
  }

  int i = atoi(argv[1]);
  bool err = dhash.sync_setactive (i);
  assert (!err);

  unsigned int seed = strtoul (argv[8], NULL, 10);
  srandom (seed);
  prepare_test_data (num);

  MAX_OPS_OUT = atoi(argv[7]);

  struct timeval start;
  gettimeofday (&start, NULL);

  if (argv[6][0] == 's')
    store (dhash, num);
  else
    fetch (dhash, num);

  struct timeval end;
  gettimeofday (&end, NULL);
  float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
  fprintf(outfile, "Total Elapsed: %f\n", elapsed);
}
<commit_msg>print out hops<commit_after>/*
 *
 * Copyright (C) 2001  Frank Dabek (fdabek@lcs.mit.edu),
 *   		       Massachusetts Institute of Technology
 *
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include "sfsmisc.h"
#include "dhash_prot.h"
#include "dhash.h"
#include "crypt.h"
#include <sys/time.h>

static bigint *IDs;
static void **data;
str control_socket;
static FILE *outfile;
unsigned int datasize;

int out = 0;
int MAX_OPS_OUT = 1024;

chordID
make_block (void *data)
{
  // size must be word sized
  assert (datasize % sizeof (long) == 0);

  long *rd = (long *)data;
  for (unsigned int i = 0; i < datasize/sizeof(long); i++)
    rd[i] = random();

  return compute_hash (rd, datasize);
}

void
prepare_test_data (int num)
{
  IDs = New chordID[num];
  data = (void **)malloc(sizeof(void *)*num);
  for (int i = 0; i < num; i++) {
    data[i] = malloc(datasize);
    IDs[i] = make_block(data[i]);
  }
}

void
store_cb (bool error, chordID key)
{
  out--;

  if (error)
    fprintf (outfile, "store error\n");
}

int
store (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    dhash.insert ((char *)data[i], datasize, wrap (store_cb));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck ();

  return 0;
}

void
fetch_cb (int i, struct timeval start, ptr<dhash_block> blk)
{
  out--;

  if (!blk) {
    strbuf buf;
    buf << "Error: " << IDs[i] << "\n";
    fprintf (outfile, str (buf).cstr ());
  }
  else if (datasize != blk->len || memcmp (data[i], blk->data, datasize) != 0)
    fatal << "verification failed";
  else {
    struct timeval end;
    gettimeofday(&end, NULL);
    float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
    fprintf (outfile, "%f %d\n", elapsed, blk->hops);
  }
}

void
fetch (dhashclient &dhash, int num)
{
  for (int i = 0; i < num; i++) {
    out++;
    struct timeval start;
    gettimeofday (&start, NULL);

    dhash.retrieve (IDs[i], wrap (fetch_cb, i, start));
    while (out > MAX_OPS_OUT)
      acheck ();
  }

  while (out > 0)
    acheck();
}

void
usage (char *progname)
{
  warn << "vnode_num control_socket num_trials data_size file <f or s> nops seed\n";
  exit(0);
}

int
main (int argc, char **argv)
{
  setprogname (argv[0]);

  sfsconst_init ();

  if (argc < 9) {
    usage (argv[0]);
    exit (1);
  }

  control_socket = argv[2];
  dhashclient dhash (control_socket);

  int num = atoi(argv[3]);
  datasize = atoi(argv[4]);

  char *output = argv[5];
  if (strcmp(output, "-") == 0)
    outfile = stdout;
  else
    outfile = fopen(output, "w");

  if (!outfile) {
    printf ("could not open %s\n", output);
    exit(1);
  }

  int i = atoi(argv[1]);
  bool err = dhash.sync_setactive (i);
  assert (!err);

  unsigned int seed = strtoul (argv[8], NULL, 10);
  srandom (seed);
  prepare_test_data (num);

  MAX_OPS_OUT = atoi(argv[7]);

  struct timeval start;
  gettimeofday (&start, NULL);

  if (argv[6][0] == 's')
    store (dhash, num);
  else
    fetch (dhash, num);

  struct timeval end;
  gettimeofday (&end, NULL);
  float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)/1000.0;
  fprintf(outfile, "Total Elapsed: %f\n", elapsed);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/nss_ssl_util.h"

#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>
#include <sslproto.h>

#include <string>

#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"

namespace net {

class NSSSSLInitSingleton {
 public:
  NSSSSLInitSingleton() {
    crypto::EnsureNSSInit();

    NSS_SetDomesticPolicy();

#if defined(USE_SYSTEM_SSL)
    // Use late binding to avoid scary but benign warning
    // "Symbol `SSL_ImplementedCiphers' has different size in shared object,
    //  consider re-linking"
    // TODO(wtc): Use the new SSL_GetImplementedCiphers and
    // SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
    const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
        dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
    if (pSSL_ImplementedCiphers == NULL) {
      NOTREACHED() << "Can't get list of supported ciphers";
      return;
    }
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif

    // Explicitly enable exactly those ciphers with keys of at least 80 bits
    // except TLS_RSA_WITH_RC4_128_MD5.
    for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
      SSLCipherSuiteInfo info;
      if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
                                 sizeof(info)) == SECSuccess) {
        SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
                                 (info.effectiveKeyBits >= 80));
      }
    }
    SSL_CipherPrefSetDefault(SSL_RSA_WITH_RC4_128_MD5, PR_FALSE);

    // Enable SSL.
    SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);

    // All other SSL options are set per-session by SSLClientSocket and
    // SSLServerSocket.
  }

  ~NSSSSLInitSingleton() {
    // Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
    SSL_ClearSessionCache();
  }
};

static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
    LAZY_INSTANCE_INITIALIZER;

// Initialize the NSS SSL library if it isn't already initialized.  This must
// be called before any other NSS SSL functions.  This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
  // Initializing SSL causes us to do blocking IO.
  // Temporarily allow it until we fix
  //   http://code.google.com/p/chromium/issues/detail?id=59847
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  g_nss_ssl_init_singleton.Get();
}

// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
  if (result >=0)
    return result;

  switch (result) {
    case ERR_IO_PENDING:
      return PR_WOULD_BLOCK_ERROR;
    case ERR_ACCESS_DENIED:
    case ERR_NETWORK_ACCESS_DENIED:
      // For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
      return PR_NO_ACCESS_RIGHTS_ERROR;
    case ERR_NOT_IMPLEMENTED:
      return PR_NOT_IMPLEMENTED_ERROR;
    case ERR_SOCKET_NOT_CONNECTED:
      return PR_NOT_CONNECTED_ERROR;
    case ERR_INTERNET_DISCONNECTED:  // Equivalent to ENETDOWN.
      return PR_NETWORK_UNREACHABLE_ERROR;  // Best approximation.
    case ERR_CONNECTION_TIMED_OUT:
    case ERR_TIMED_OUT:
      return PR_IO_TIMEOUT_ERROR;
    case ERR_CONNECTION_RESET:
      return PR_CONNECT_RESET_ERROR;
    case ERR_CONNECTION_ABORTED:
      return PR_CONNECT_ABORTED_ERROR;
    case ERR_CONNECTION_REFUSED:
      return PR_CONNECT_REFUSED_ERROR;
    case ERR_ADDRESS_UNREACHABLE:
      return PR_HOST_UNREACHABLE_ERROR;  // Also PR_NETWORK_UNREACHABLE_ERROR.
    case ERR_ADDRESS_INVALID:
      return PR_ADDRESS_NOT_AVAILABLE_ERROR;
    case ERR_NAME_NOT_RESOLVED:
      return PR_DIRECTORY_LOOKUP_ERROR;
    default:
      LOG(WARNING) << "MapErrorToNSS " << result
                   << " mapped to PR_UNKNOWN_ERROR";
      return PR_UNKNOWN_ERROR;
  }
}

// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
  // TODO(port): fill this out as we learn what's important
  switch (err) {
    case PR_WOULD_BLOCK_ERROR:
      return ERR_IO_PENDING;
    case PR_ADDRESS_NOT_SUPPORTED_ERROR:  // For connect.
    case PR_NO_ACCESS_RIGHTS_ERROR:
      return ERR_ACCESS_DENIED;
    case PR_IO_TIMEOUT_ERROR:
      return ERR_TIMED_OUT;
    case PR_CONNECT_RESET_ERROR:
      return ERR_CONNECTION_RESET;
    case PR_CONNECT_ABORTED_ERROR:
      return ERR_CONNECTION_ABORTED;
    case PR_CONNECT_REFUSED_ERROR:
      return ERR_CONNECTION_REFUSED;
    case PR_NOT_CONNECTED_ERROR:
      return ERR_SOCKET_NOT_CONNECTED;
    case PR_HOST_UNREACHABLE_ERROR:
    case PR_NETWORK_UNREACHABLE_ERROR:
      return ERR_ADDRESS_UNREACHABLE;
    case PR_ADDRESS_NOT_AVAILABLE_ERROR:
      return ERR_ADDRESS_INVALID;
    case PR_INVALID_ARGUMENT_ERROR:
      return ERR_INVALID_ARGUMENT;
    case PR_END_OF_FILE_ERROR:
      return ERR_CONNECTION_CLOSED;
    case PR_NOT_IMPLEMENTED_ERROR:
      return ERR_NOT_IMPLEMENTED;

    case SEC_ERROR_INVALID_ARGS:
      return ERR_INVALID_ARGUMENT;
    case SEC_ERROR_NO_MEMORY:
      return ERR_OUT_OF_MEMORY;
    case SEC_ERROR_NO_KEY:
      return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
    case SEC_ERROR_INVALID_KEY:
    case SSL_ERROR_SIGN_HASHES_FAILURE:
      return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
    // A handshake (initial or renegotiation) may fail because some signature
    // (for example, the signature in the ServerKeyExchange message for an
    // ephemeral Diffie-Hellman cipher suite) is invalid.
    case SEC_ERROR_BAD_SIGNATURE:
      return ERR_SSL_PROTOCOL_ERROR;

    case SSL_ERROR_SSL_DISABLED:
      return ERR_NO_SSL_VERSIONS_ENABLED;
    case SSL_ERROR_NO_CYPHER_OVERLAP:
    case SSL_ERROR_UNSUPPORTED_VERSION:
      return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
    case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
    case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
    case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
      return ERR_SSL_PROTOCOL_ERROR;
    case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
      return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
    case SSL_ERROR_BAD_MAC_ALERT:
      return ERR_SSL_BAD_RECORD_MAC_ALERT;
    case SSL_ERROR_UNSAFE_NEGOTIATION:
      return ERR_SSL_UNSAFE_NEGOTIATION;
    case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
      return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
    case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
      return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
    case SEC_ERROR_BAD_KEY:
    case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
    // TODO(wtc): the following errors may also occur in contexts unrelated
    // to the peer's public key.  We should add new error codes for them, or
    // map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
    // General unsupported/unknown key algorithm error.
    case SEC_ERROR_UNSUPPORTED_KEYALG:
    // General DER decoding errors.
    case SEC_ERROR_BAD_DER:
    case SEC_ERROR_EXTRA_INPUT:
      return ERR_SSL_BAD_PEER_PUBLIC_KEY;

    default: {
      if (IS_SSL_ERROR(err)) {
        LOG(WARNING) << "Unknown SSL error " << err
                     << " mapped to net::ERR_SSL_PROTOCOL_ERROR";
        return ERR_SSL_PROTOCOL_ERROR;
      }
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return ERR_FAILED;
    }
  }
}

// Context-sensitive error mapping functions.
int MapNSSHandshakeError(PRErrorCode err) {
  switch (err) {
    // If the server closed on us, it is a protocol error.
    // Some TLS-intolerant servers do this when we request TLS.
    case PR_END_OF_FILE_ERROR:
      return ERR_SSL_PROTOCOL_ERROR;
    default:
      return MapNSSError(err);
  }
}

// Extra parameters to attach to the NetLog when we receive an error in response
// to a call to an NSS function.  Used instead of SSLErrorParams with
// events of type TYPE_SSL_NSS_ERROR.  Automatically looks up last PR error.
class SSLFailedNSSFunctionParams : public NetLog::EventParameters {
 public:
  // |param| is ignored if it has a length of 0.
  SSLFailedNSSFunctionParams(const std::string& function,
                             const std::string& param)
      : function_(function), param_(param), ssl_lib_error_(PR_GetError()) {
  }

  virtual Value* ToValue() const {
    DictionaryValue* dict = new DictionaryValue();
    dict->SetString("function", function_);
    if (!param_.empty())
      dict->SetString("param", param_);
    dict->SetInteger("ssl_lib_error", ssl_lib_error_);
    return dict;
  }

 private:
  const std::string function_;
  const std::string param_;
  const PRErrorCode ssl_lib_error_;
};

void LogFailedNSSFunction(const BoundNetLog& net_log,
                          const char* function,
                          const char* param) {
  net_log.AddEvent(
      NetLog::TYPE_SSL_NSS_ERROR,
      make_scoped_refptr(new SSLFailedNSSFunctionParams(function, param)));
}

}  // namespace net
<commit_msg>Revert 125571 - Turn off TLS_RSA_WITH_RC4_128_MD5.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/socket/nss_ssl_util.h"

#include <nss.h>
#include <secerr.h>
#include <ssl.h>
#include <sslerr.h>

#include <string>

#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "crypto/nss_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"

namespace net {

class NSSSSLInitSingleton {
 public:
  NSSSSLInitSingleton() {
    crypto::EnsureNSSInit();

    NSS_SetDomesticPolicy();

#if defined(USE_SYSTEM_SSL)
    // Use late binding to avoid scary but benign warning
    // "Symbol `SSL_ImplementedCiphers' has different size in shared object,
    //  consider re-linking"
    // TODO(wtc): Use the new SSL_GetImplementedCiphers and
    // SSL_GetNumImplementedCiphers functions when we require NSS 3.12.6.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=496993.
    const PRUint16* pSSL_ImplementedCiphers = static_cast<const PRUint16*>(
        dlsym(RTLD_DEFAULT, "SSL_ImplementedCiphers"));
    if (pSSL_ImplementedCiphers == NULL) {
      NOTREACHED() << "Can't get list of supported ciphers";
      return;
    }
#else
#define pSSL_ImplementedCiphers SSL_ImplementedCiphers
#endif

    // Explicitly enable exactly those ciphers with keys of at least 80 bits
    for (int i = 0; i < SSL_NumImplementedCiphers; i++) {
      SSLCipherSuiteInfo info;
      if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,
                                 sizeof(info)) == SECSuccess) {
        SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],
                                 (info.effectiveKeyBits >= 80));
      }
    }

    // Enable SSL.
    SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);

    // All other SSL options are set per-session by SSLClientSocket and
    // SSLServerSocket.
  }

  ~NSSSSLInitSingleton() {
    // Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY.
    SSL_ClearSessionCache();
  }
};

static base::LazyInstance<NSSSSLInitSingleton> g_nss_ssl_init_singleton =
    LAZY_INSTANCE_INITIALIZER;

// Initialize the NSS SSL library if it isn't already initialized.  This must
// be called before any other NSS SSL functions.  This function is
// thread-safe, and the NSS SSL library will only ever be initialized once.
// The NSS SSL library will be properly shut down on program exit.
void EnsureNSSSSLInit() {
  // Initializing SSL causes us to do blocking IO.
  // Temporarily allow it until we fix
  //   http://code.google.com/p/chromium/issues/detail?id=59847
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  g_nss_ssl_init_singleton.Get();
}

// Map a Chromium net error code to an NSS error code.
// See _MD_unix_map_default_error in the NSS source
// tree for inspiration.
PRErrorCode MapErrorToNSS(int result) {
  if (result >=0)
    return result;

  switch (result) {
    case ERR_IO_PENDING:
      return PR_WOULD_BLOCK_ERROR;
    case ERR_ACCESS_DENIED:
    case ERR_NETWORK_ACCESS_DENIED:
      // For connect, this could be mapped to PR_ADDRESS_NOT_SUPPORTED_ERROR.
      return PR_NO_ACCESS_RIGHTS_ERROR;
    case ERR_NOT_IMPLEMENTED:
      return PR_NOT_IMPLEMENTED_ERROR;
    case ERR_SOCKET_NOT_CONNECTED:
      return PR_NOT_CONNECTED_ERROR;
    case ERR_INTERNET_DISCONNECTED:  // Equivalent to ENETDOWN.
      return PR_NETWORK_UNREACHABLE_ERROR;  // Best approximation.
    case ERR_CONNECTION_TIMED_OUT:
    case ERR_TIMED_OUT:
      return PR_IO_TIMEOUT_ERROR;
    case ERR_CONNECTION_RESET:
      return PR_CONNECT_RESET_ERROR;
    case ERR_CONNECTION_ABORTED:
      return PR_CONNECT_ABORTED_ERROR;
    case ERR_CONNECTION_REFUSED:
      return PR_CONNECT_REFUSED_ERROR;
    case ERR_ADDRESS_UNREACHABLE:
      return PR_HOST_UNREACHABLE_ERROR;  // Also PR_NETWORK_UNREACHABLE_ERROR.
    case ERR_ADDRESS_INVALID:
      return PR_ADDRESS_NOT_AVAILABLE_ERROR;
    case ERR_NAME_NOT_RESOLVED:
      return PR_DIRECTORY_LOOKUP_ERROR;
    default:
      LOG(WARNING) << "MapErrorToNSS " << result
                   << " mapped to PR_UNKNOWN_ERROR";
      return PR_UNKNOWN_ERROR;
  }
}

// The default error mapping function.
// Maps an NSS error code to a network error code.
int MapNSSError(PRErrorCode err) {
  // TODO(port): fill this out as we learn what's important
  switch (err) {
    case PR_WOULD_BLOCK_ERROR:
      return ERR_IO_PENDING;
    case PR_ADDRESS_NOT_SUPPORTED_ERROR:  // For connect.
    case PR_NO_ACCESS_RIGHTS_ERROR:
      return ERR_ACCESS_DENIED;
    case PR_IO_TIMEOUT_ERROR:
      return ERR_TIMED_OUT;
    case PR_CONNECT_RESET_ERROR:
      return ERR_CONNECTION_RESET;
    case PR_CONNECT_ABORTED_ERROR:
      return ERR_CONNECTION_ABORTED;
    case PR_CONNECT_REFUSED_ERROR:
      return ERR_CONNECTION_REFUSED;
    case PR_NOT_CONNECTED_ERROR:
      return ERR_SOCKET_NOT_CONNECTED;
    case PR_HOST_UNREACHABLE_ERROR:
    case PR_NETWORK_UNREACHABLE_ERROR:
      return ERR_ADDRESS_UNREACHABLE;
    case PR_ADDRESS_NOT_AVAILABLE_ERROR:
      return ERR_ADDRESS_INVALID;
    case PR_INVALID_ARGUMENT_ERROR:
      return ERR_INVALID_ARGUMENT;
    case PR_END_OF_FILE_ERROR:
      return ERR_CONNECTION_CLOSED;
    case PR_NOT_IMPLEMENTED_ERROR:
      return ERR_NOT_IMPLEMENTED;

    case SEC_ERROR_INVALID_ARGS:
      return ERR_INVALID_ARGUMENT;
    case SEC_ERROR_NO_MEMORY:
      return ERR_OUT_OF_MEMORY;
    case SEC_ERROR_NO_KEY:
      return ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY;
    case SEC_ERROR_INVALID_KEY:
    case SSL_ERROR_SIGN_HASHES_FAILURE:
      return ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED;
    // A handshake (initial or renegotiation) may fail because some signature
    // (for example, the signature in the ServerKeyExchange message for an
    // ephemeral Diffie-Hellman cipher suite) is invalid.
    case SEC_ERROR_BAD_SIGNATURE:
      return ERR_SSL_PROTOCOL_ERROR;

    case SSL_ERROR_SSL_DISABLED:
      return ERR_NO_SSL_VERSIONS_ENABLED;
    case SSL_ERROR_NO_CYPHER_OVERLAP:
    case SSL_ERROR_UNSUPPORTED_VERSION:
      return ERR_SSL_VERSION_OR_CIPHER_MISMATCH;
    case SSL_ERROR_HANDSHAKE_FAILURE_ALERT:
    case SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT:
    case SSL_ERROR_ILLEGAL_PARAMETER_ALERT:
      return ERR_SSL_PROTOCOL_ERROR;
    case SSL_ERROR_DECOMPRESSION_FAILURE_ALERT:
      return ERR_SSL_DECOMPRESSION_FAILURE_ALERT;
    case SSL_ERROR_BAD_MAC_ALERT:
      return ERR_SSL_BAD_RECORD_MAC_ALERT;
    case SSL_ERROR_UNSAFE_NEGOTIATION:
      return ERR_SSL_UNSAFE_NEGOTIATION;
    case SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY:
      return ERR_SSL_WEAK_SERVER_EPHEMERAL_DH_KEY;
    case SSL_ERROR_HANDSHAKE_NOT_COMPLETED:
      return ERR_SSL_HANDSHAKE_NOT_COMPLETED;
    case SEC_ERROR_BAD_KEY:
    case SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE:
    // TODO(wtc): the following errors may also occur in contexts unrelated
    // to the peer's public key.  We should add new error codes for them, or
    // map them to ERR_SSL_BAD_PEER_PUBLIC_KEY only in the right context.
    // General unsupported/unknown key algorithm error.
    case SEC_ERROR_UNSUPPORTED_KEYALG:
    // General DER decoding errors.
    case SEC_ERROR_BAD_DER:
    case SEC_ERROR_EXTRA_INPUT:
      return ERR_SSL_BAD_PEER_PUBLIC_KEY;

    default: {
      if (IS_SSL_ERROR(err)) {
        LOG(WARNING) << "Unknown SSL error " << err
                     << " mapped to net::ERR_SSL_PROTOCOL_ERROR";
        return ERR_SSL_PROTOCOL_ERROR;
      }
      LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
      return ERR_FAILED;
    }
  }
}

// Context-sensitive error mapping functions.
int MapNSSHandshakeError(PRErrorCode err) {
  switch (err) {
    // If the server closed on us, it is a protocol error.
    // Some TLS-intolerant servers do this when we request TLS.
    case PR_END_OF_FILE_ERROR:
      return ERR_SSL_PROTOCOL_ERROR;
    default:
      return MapNSSError(err);
  }
}

// Extra parameters to attach to the NetLog when we receive an error in response
// to a call to an NSS function.  Used instead of SSLErrorParams with
// events of type TYPE_SSL_NSS_ERROR.  Automatically looks up last PR error.
class SSLFailedNSSFunctionParams : public NetLog::EventParameters {
 public:
  // |param| is ignored if it has a length of 0.
  SSLFailedNSSFunctionParams(const std::string& function,
                             const std::string& param)
      : function_(function), param_(param), ssl_lib_error_(PR_GetError()) {
  }

  virtual Value* ToValue() const {
    DictionaryValue* dict = new DictionaryValue();
    dict->SetString("function", function_);
    if (!param_.empty())
      dict->SetString("param", param_);
    dict->SetInteger("ssl_lib_error", ssl_lib_error_);
    return dict;
  }

 private:
  const std::string function_;
  const std::string param_;
  const PRErrorCode ssl_lib_error_;
};

void LogFailedNSSFunction(const BoundNetLog& net_log,
                          const char* function,
                          const char* param) {
  net_log.AddEvent(
      NetLog::TYPE_SSL_NSS_ERROR,
      make_scoped_refptr(new SSLFailedNSSFunctionParams(function, param)));
}

}  // namespace net
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QString>
#include <QtTest/QtTest>

#include <QVariant>
#include <QSignalSpy>

#include <qsensorgesture.h>
#include <qsensorgesturemanager.h>

#include <qsensorgesturerecognizer.h>
#include <qsensorgestureplugininterface.h>

#include "test_backends.h"

class Tst_qsensorgesturePluginsTest : public QObject
{
    Q_OBJECT

public:
    Tst_qsensorgesturePluginsTest();

private Q_SLOTS:

    void tst_sensor_plugins_shake();
    void tst_sensor_plugins_qtsensors_data();
    void tst_sensor_plugins_qtsensors();
    void tst_sensor_plugins_qtsensors_all();

};

Tst_qsensorgesturePluginsTest::Tst_qsensorgesturePluginsTest()
{
    qputenv("QTSENSORS_LOAD_PLUGINS", "0"); // Do not load plugins
    register_test_backends();
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_shake()
{

    QSensorGestureManager manager;
    QVERIFY(manager.gestureIds().contains("QtSensors.shake"));

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer("QtSensors.shake");

    QCOMPARE(recognizer->isActive(), false);

    QTest::ignoreMessage(QtWarningMsg, "Not starting. Gesture Recognizer not initialized ");
    recognizer->startBackend();
    QCOMPARE(recognizer->isActive(), false);

    QTest::ignoreMessage(QtWarningMsg, "Not stopping. Gesture Recognizer not initialized ");
    recognizer->stopBackend();
    QCOMPARE(recognizer->isActive(), false);

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(QStringList() << "QtSensors.shake"));

    QCOMPARE(gesture->isActive(),false);
    QCOMPARE(gesture->validIds(), QStringList() << "QtSensors.shake");

    QCOMPARE(QStringList() << recognizer->id(), gesture->validIds());

    gesture->startDetection();
    QCOMPARE(gesture->isActive(),true);
    QCOMPARE(recognizer->isActive(), true);

    gesture->stopDetection();
    QCOMPARE(recognizer->isActive(), false);
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors_data()
{
    QTest::addColumn<QString>("gestureId");

    QTest::newRow("QtSensors.cover") << "QtSensors.cover";
    QTest::newRow("QtSensors.doubletap") << "QtSensors.doubletap";
    QTest::newRow("QtSensors.hover") << "QtSensors.hover";
    QTest::newRow("QtSensors.hover") << "QtSensors.hover";
    QTest::newRow("QtSensors.shake2") << "QtSensors.shake2";
    QTest::newRow("QtSensors.slam") << "QtSensors.slam";
    QTest::newRow("QtSensors.turnover") << "QtSensors.turnover";
    QTest::newRow("QtSensors.twist") << "QtSensors.twist";
    QTest::newRow("QtSensors.whip") << "QtSensors.whip";
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors()
{
    QFETCH(QString, gestureId);

    QSensorGestureManager manager;

    QVERIFY(manager.gestureIds().contains(gestureId));

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(QStringList() << gestureId));
    QScopedPointer<QSensorGesture> gesture2(new QSensorGesture(QStringList() << gestureId));

    QCOMPARE(gesture->isActive(),false);
    QCOMPARE(gesture->validIds(), QStringList() << gestureId);

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer(gestureId);

    QCOMPARE(QStringList() << recognizer->id(), gesture->validIds());

    QCOMPARE(QStringList() << QStringList(), gesture->invalidIds());

    QVERIFY(recognizer->isActive() == false);
    QVERIFY(gesture->isActive() == false);
    QVERIFY(gesture2->isActive() == false);

    gesture->startDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == false);

    QVERIFY(recognizer->isActive() == true);

    gesture2->startDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == true);
    QVERIFY(recognizer->isActive() == true);

    gesture2->stopDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == false);
    QVERIFY(recognizer->isActive() == true);

    gesture->stopDetection();

    QVERIFY(gesture->isActive() == false);
    QVERIFY(gesture2->isActive() == false);
    QVERIFY(recognizer->isActive() == false);

    QVERIFY(recognizer->gestureSignals().count() > 1);
    QVERIFY(recognizer->gestureSignals().contains("detected(QString)"));

}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors_all()
{
    QStringList list;
    list << "QtSensors.cover";
    list << "QtSensors.doubletap";
    list << "QtSensors.hover";
    list << "QtSensors.pickup";
    list << "QtSensors.shake2";
    list << "QtSensors.slam";
    list << "QtSensors.turnover";
    list << "QtSensors.twist";
    list << "QtSensors.whip";

    QSensorGestureManager manager;

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(list));
    QVERIFY(gesture->invalidIds().count() == 0);
    QVERIFY(gesture->validIds().count() == 9);
    QVERIFY(gesture->gestureSignals().count() == 14);

    gesture->startDetection();
    QVERIFY(gesture->isActive());

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer("QtSensors.turnover");
    recognizer->stopBackend();
    QVERIFY(!recognizer->isActive());
    QVERIFY(gesture->isActive());

}

QTEST_MAIN(Tst_qsensorgesturePluginsTest);

#include "tst_qsensorgesturepluginstest.moc"
<commit_msg>The variable is QT_SENSORS_LOAD_PLUGINS<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QString>
#include <QtTest/QtTest>

#include <QVariant>
#include <QSignalSpy>

#include <qsensorgesture.h>
#include <qsensorgesturemanager.h>

#include <qsensorgesturerecognizer.h>
#include <qsensorgestureplugininterface.h>

#include "test_backends.h"

class Tst_qsensorgesturePluginsTest : public QObject
{
    Q_OBJECT

public:
    Tst_qsensorgesturePluginsTest();

private Q_SLOTS:

    void tst_sensor_plugins_shake();
    void tst_sensor_plugins_qtsensors_data();
    void tst_sensor_plugins_qtsensors();
    void tst_sensor_plugins_qtsensors_all();

};

Tst_qsensorgesturePluginsTest::Tst_qsensorgesturePluginsTest()
{
    qputenv("QT_SENSORS_LOAD_PLUGINS", "0"); // Do not load plugins
    register_test_backends();
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_shake()
{

    QSensorGestureManager manager;
    QVERIFY(manager.gestureIds().contains("QtSensors.shake"));

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer("QtSensors.shake");

    QCOMPARE(recognizer->isActive(), false);

    QTest::ignoreMessage(QtWarningMsg, "Not starting. Gesture Recognizer not initialized ");
    recognizer->startBackend();
    QCOMPARE(recognizer->isActive(), false);

    QTest::ignoreMessage(QtWarningMsg, "Not stopping. Gesture Recognizer not initialized ");
    recognizer->stopBackend();
    QCOMPARE(recognizer->isActive(), false);

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(QStringList() << "QtSensors.shake"));

    QCOMPARE(gesture->isActive(),false);
    QCOMPARE(gesture->validIds(), QStringList() << "QtSensors.shake");

    QCOMPARE(QStringList() << recognizer->id(), gesture->validIds());

    gesture->startDetection();
    QCOMPARE(gesture->isActive(),true);
    QCOMPARE(recognizer->isActive(), true);

    gesture->stopDetection();
    QCOMPARE(recognizer->isActive(), false);
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors_data()
{
    QTest::addColumn<QString>("gestureId");

    QTest::newRow("QtSensors.cover") << "QtSensors.cover";
    QTest::newRow("QtSensors.doubletap") << "QtSensors.doubletap";
    QTest::newRow("QtSensors.hover") << "QtSensors.hover";
    QTest::newRow("QtSensors.hover") << "QtSensors.hover";
    QTest::newRow("QtSensors.shake2") << "QtSensors.shake2";
    QTest::newRow("QtSensors.slam") << "QtSensors.slam";
    QTest::newRow("QtSensors.turnover") << "QtSensors.turnover";
    QTest::newRow("QtSensors.twist") << "QtSensors.twist";
    QTest::newRow("QtSensors.whip") << "QtSensors.whip";
}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors()
{
    QFETCH(QString, gestureId);

    QSensorGestureManager manager;

    QVERIFY(manager.gestureIds().contains(gestureId));

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(QStringList() << gestureId));
    QScopedPointer<QSensorGesture> gesture2(new QSensorGesture(QStringList() << gestureId));

    QCOMPARE(gesture->isActive(),false);
    QCOMPARE(gesture->validIds(), QStringList() << gestureId);

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer(gestureId);

    QCOMPARE(QStringList() << recognizer->id(), gesture->validIds());

    QCOMPARE(QStringList() << QStringList(), gesture->invalidIds());

    QVERIFY(recognizer->isActive() == false);
    QVERIFY(gesture->isActive() == false);
    QVERIFY(gesture2->isActive() == false);

    gesture->startDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == false);

    QVERIFY(recognizer->isActive() == true);

    gesture2->startDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == true);
    QVERIFY(recognizer->isActive() == true);

    gesture2->stopDetection();

    QVERIFY(gesture->isActive() == true);
    QVERIFY(gesture2->isActive() == false);
    QVERIFY(recognizer->isActive() == true);

    gesture->stopDetection();

    QVERIFY(gesture->isActive() == false);
    QVERIFY(gesture2->isActive() == false);
    QVERIFY(recognizer->isActive() == false);

    QVERIFY(recognizer->gestureSignals().count() > 1);
    QVERIFY(recognizer->gestureSignals().contains("detected(QString)"));

}

void Tst_qsensorgesturePluginsTest::tst_sensor_plugins_qtsensors_all()
{
    QStringList list;
    list << "QtSensors.cover";
    list << "QtSensors.doubletap";
    list << "QtSensors.hover";
    list << "QtSensors.pickup";
    list << "QtSensors.shake2";
    list << "QtSensors.slam";
    list << "QtSensors.turnover";
    list << "QtSensors.twist";
    list << "QtSensors.whip";

    QSensorGestureManager manager;

    QScopedPointer<QSensorGesture> gesture(new QSensorGesture(list));
    QVERIFY(gesture->invalidIds().count() == 0);
    QVERIFY(gesture->validIds().count() == 9);
    QVERIFY(gesture->gestureSignals().count() == 14);

    gesture->startDetection();
    QVERIFY(gesture->isActive());

    QSensorGestureRecognizer *recognizer = manager.sensorGestureRecognizer("QtSensors.turnover");
    recognizer->stopBackend();
    QVERIFY(!recognizer->isActive());
    QVERIFY(gesture->isActive());

}

QTEST_MAIN(Tst_qsensorgesturePluginsTest);

#include "tst_qsensorgesturepluginstest.moc"
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwas/common/hwas.C $                                  */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2011,2012              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file hwas.C
 *
 *  HardWare Availability Service functions.
 *  See hwas.H for doxygen documentation tags.
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>

#include <targeting/common/commontargeting.H>

#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwasError.H>

namespace HWAS
{

using namespace TARGETING;
using namespace HWAS::COMMON;

// trace setup; used by HWAS_DBG and HWAS_ERR macros
HWAS_TD_t g_trac_dbg_hwas   = NULL; // debug - fast
HWAS_TD_t g_trac_imp_hwas   = NULL; // important - slow

TRAC_INIT(&g_trac_dbg_hwas, "HWAS",     1024 );
TRAC_INIT(&g_trac_imp_hwas, "HWAS_I",   1024 );

/**
 * @brief       simple helper fn to get and set hwas state to poweredOn,
 *                  present, functional
 *
 * @param[in]   i_target    pointer to target that we're looking at
 * @param[in]   i_present   boolean indicating present or not
 * @param[in]   i_functional boolean indicating functional or not
 *
 * @return      none
 *
 */
void enableHwasState(Target *i_target, bool i_present, bool i_functional)
{
    HwasState hwasState     = i_target->getAttr<ATTR_HWAS_STATE>();
    hwasState.poweredOn     = true;
    hwasState.present       = i_present;
    hwasState.functional    = i_functional;
    i_target->setAttr<ATTR_HWAS_STATE>( hwasState );
}

errlHndl_t discoverTargets()
{
    HWAS_INF("discoverTargets entry");
    errlHndl_t errl = NULL;

    //  loop through all the targets and set HWAS_STATE to a known default
    for (TargetIterator target = targetService().begin();
            target != targetService().end();
            ++target)
    {
        HwasState hwasState             = target->getAttr<ATTR_HWAS_STATE>();
        hwasState.poweredOn             = false;
        hwasState.present               = false;
        hwasState.functional            = false;
        hwasState.changedSinceLastIPL   = false;
        target->setAttr<ATTR_HWAS_STATE>(hwasState);
    }

    // ASSUMPTIONS:
    // CLASS_SYS (exactly 1) - mark as present
    // CLASS_ENC (>=1) - mark as present
    // TYPE_PROC TYPE_MEMBUF TYPE_DIMM (ALL require hardware query)
    //                                  - call platPresenceDetect
    //  \->children: CLASS_* (NONE require hardware query) - mark as present

    do
    {
        // find CLASS_SYS (the top level target)
        Target* pSys;
        targetService().getTopLevelTarget(pSys);

        HWAS_ASSERT(pSys,
                "HWAS discoverTargets: no CLASS_SYS TopLevelTarget found");

        // mark this as present
        enableHwasState(pSys, true, true);
        HWAS_DBG("pSys %.8X - marked present",
            pSys->getAttr<ATTR_HUID>());

        // find CLASS_ENC
        PredicateCTM predEnc(CLASS_ENC);
        TargetHandleList pEncList;
        targetService().getAssociated( pEncList, pSys,
            TargetService::CHILD, TargetService::ALL, &predEnc );

        for (TargetHandleList::iterator pEnc_it = pEncList.begin();
                pEnc_it != pEncList.end();
                pEnc_it++)
        {
            TargetHandle_t pEnc = *pEnc_it;

            // mark it as present
            enableHwasState(pEnc, true, true);
            HWAS_DBG("pEnc %.8X - marked present",
                pEnc->getAttr<ATTR_HUID>());
        } // for pEnc_it

        PredicateCTM predChip(CLASS_CHIP);
        PredicateCTM predDimm(CLASS_LOGICAL_CARD, TYPE_DIMM);
        PredicatePostfixExpr checkExpr;
        checkExpr.push(&predChip).push(&predDimm).Or();

        TargetHandleList pCheckPres;
        targetService().getAssociated( pCheckPres, pSys,
            TargetService::CHILD, TargetService::ALL, &checkExpr );

        // pass this list to the hwas platform-specific api where
        // pCheckPres will be modified to only have present targets
        HWAS_DBG("pCheckPres size: %d", pCheckPres.size());
        errl = platPresenceDetect(pCheckPres);
        HWAS_DBG("pCheckPres size: %d", pCheckPres.size());

        if (errl != NULL)
        {
            break; // break out of the do/while so that we can return
        }

        // no errors - keep going
        // for each, read their ID/EC level. if that works,
        //  mark them and their descendants as present
        //  read the partialGood vector to determine if any are not functional

        for (TargetHandleList::iterator pTarget_it = pCheckPres.begin();
                pTarget_it != pCheckPres.end();
                pTarget_it++
            )
        {
            TargetHandle_t pTarget = *pTarget_it;

            bool chipFunctional = true;
            bool chipPresent = true;
            uint16_t pgData[VPD_CP00_PG_DATA_LENGTH / sizeof(uint16_t)];
            bzero(pgData, sizeof(pgData));
            if (pTarget->getAttr<ATTR_CLASS>() == CLASS_CHIP)
            {
                // read Chip ID/EC data from these physical chips
                errl = platReadIDEC(pTarget);

                if (errl)
                {   // read of ID/EC failed even tho we were present..
                    chipFunctional = false;

                    // commit the error but keep going
                    errlCommit(errl, HWAS_COMP_ID);
                    // errl is now NULL
                }

                if (pTarget->getAttr<ATTR_TYPE>() == TYPE_PROC)
                {
                    // read partialGood vector from these as well.
                    errl = platReadPartialGood(pTarget, pgData);

                    if (errl)
                    {   // read of PG failed even tho we were present..
                        chipFunctional = false;

                        // commit the error but keep going
                        errlCommit(errl, HWAS_COMP_ID);
                        // errl is now NULL
                    }
                    else
                    // look at the 'nest' logic to override the functionality
                    //  of this proc
                    if (pgData[VPD_CP00_PG_PIB_INDEX] !=
                                    VPD_CP00_PG_PIB_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - PIB bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PIB_INDEX,
                            VPD_CP00_PG_PIB_GOOD);
                        chipFunctional = false;
                    }
                    else
                    if (pgData[VPD_CP00_PG_PERVASIVE_INDEX] !=
                                    VPD_CP00_PG_PERVASIVE_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - Pervasive bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PERVASIVE_INDEX,
                            VPD_CP00_PG_PERVASIVE_GOOD);
                        chipFunctional = false;
                    }
                    else
                    if (pgData[VPD_CP00_PG_POWERBUS_INDEX] !=
                                    VPD_CP00_PG_POWERBUS_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - PowerBus bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_POWERBUS_INDEX,
                            VPD_CP00_PG_POWERBUS_GOOD);
                        chipFunctional = false;
                    }
                } // TYPE_PROC
            } // CLASS_CHIP

            // TODO: Story 35077 - add PR processing. roughly:
            //  totalcores = readPR();
            //  for each child ex in chip c
            //      if goodcores < totalcores
            //          if ex->functional==true
            //              goodcores++
            //      else
            //          ex->functional = false

            HWAS_DBG("pTarget %.8X - detected present, %sfunctional",
                pTarget->getAttr<ATTR_HUID>(),
                chipFunctional ? "" : "NOT ");

            // now need to mark all of this target's
            //  physical descendants as present and functional as appropriate
            TargetHandleList pDescList;
            targetService().getAssociated( pDescList, pTarget,
                TargetService::CHILD, TargetService::ALL);
            for (TargetHandleList::iterator pDesc_it = pDescList.begin();
                    pDesc_it != pDescList.end();
                    pDesc_it++)
            {
                TargetHandle_t pDesc = *pDesc_it;
                // by default, the descendant's functionality is 'inherited'
                bool descFunctional = chipFunctional;

                if (chipFunctional)
                {   // if the chip is functional, the look through the
                    //  partialGood vector to see if its chiplets
                    //  are functional
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_XBUS) &&
                        (pgData[VPD_CP00_PG_XBUS_INDEX] !=
                            VPD_CP00_PG_XBUS_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - XBUS bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_XBUS_INDEX,
                            VPD_CP00_PG_XBUS_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_ABUS) &&
                        (pgData[VPD_CP00_PG_ABUS_INDEX] !=
                            VPD_CP00_PG_ABUS_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - ABUS "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_ABUS_INDEX,
                            VPD_CP00_PG_ABUS_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_PCI) &&
                        (pgData[VPD_CP00_PG_PCIE_INDEX] !=
                            VPD_CP00_PG_PCIE_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - PCIe "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PCIE_INDEX,
                            VPD_CP00_PG_PCIE_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_EX) ||
                        (pDesc->getAttr<ATTR_TYPE>() == TYPE_CORE)
                       )
                    {
                      ATTR_CHIP_UNIT_type indexEX =
                                pDesc->getAttr<ATTR_CHIP_UNIT>();
                      if (pgData[VPD_CP00_PG_EX0_INDEX + indexEX] !=
                            VPD_CP00_PG_EX0_GOOD)
                      {
                        HWAS_DBG("pDesc %.8X - EX%d "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(), indexEX,
                            VPD_CP00_PG_EX0_INDEX + indexEX,
                            VPD_CP00_PG_EX0_GOOD);
////////////////////////////////////////////////////////////////////////////////
                        // RTC: 49991 for now, return true because the VPD in
                        // hostboot is broken (has 0xF200 instead of 0xF300,
                        // and has the last 6 cores in the incorrect place)
                        descFunctional = true;
                        //descFunctional = false;
////////////////////////////////////////////////////////////////////////////////
                      }
                    }
                } // chipFunctional

                // for sub-parts, if it's not functional, it's not present.
                enableHwasState(pDesc, descFunctional, descFunctional);
                HWAS_DBG("pDesc %.8X - marked %spresent, %sfunctional",
                    pDesc->getAttr<ATTR_HUID>(),
                    descFunctional ? "" : "NOT ",
                    descFunctional ? "" : "NOT ");
            }

            // set HWAS state to show CHIP is present, functional per above
            enableHwasState(pTarget, chipPresent, chipFunctional);

        } // for pTarget_it

    } while (0);

    if (errl == NULL)
    {
        HWAS_INF("discoverTargets exit with no error");
    }
    else
    {
        HWAS_ERR("discoverTargets returning errl %p", errl);
    }
    return errl;
} // discoverTargets

};   // end namespace

<commit_msg>remove workaround, allow full partial good vpd checks.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwas/common/hwas.C $                                  */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2011,2012              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file hwas.C
 *
 *  HardWare Availability Service functions.
 *  See hwas.H for doxygen documentation tags.
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/
#include <stdint.h>

#include <targeting/common/commontargeting.H>

#include <hwas/common/hwas.H>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwasError.H>

namespace HWAS
{

using namespace TARGETING;
using namespace HWAS::COMMON;

// trace setup; used by HWAS_DBG and HWAS_ERR macros
HWAS_TD_t g_trac_dbg_hwas   = NULL; // debug - fast
HWAS_TD_t g_trac_imp_hwas   = NULL; // important - slow

TRAC_INIT(&g_trac_dbg_hwas, "HWAS",     1024 );
TRAC_INIT(&g_trac_imp_hwas, "HWAS_I",   1024 );

/**
 * @brief       simple helper fn to get and set hwas state to poweredOn,
 *                  present, functional
 *
 * @param[in]   i_target    pointer to target that we're looking at
 * @param[in]   i_present   boolean indicating present or not
 * @param[in]   i_functional boolean indicating functional or not
 *
 * @return      none
 *
 */
void enableHwasState(Target *i_target, bool i_present, bool i_functional)
{
    HwasState hwasState     = i_target->getAttr<ATTR_HWAS_STATE>();
    hwasState.poweredOn     = true;
    hwasState.present       = i_present;
    hwasState.functional    = i_functional;
    i_target->setAttr<ATTR_HWAS_STATE>( hwasState );
}

errlHndl_t discoverTargets()
{
    HWAS_INF("discoverTargets entry");
    errlHndl_t errl = NULL;

    //  loop through all the targets and set HWAS_STATE to a known default
    for (TargetIterator target = targetService().begin();
            target != targetService().end();
            ++target)
    {
        HwasState hwasState             = target->getAttr<ATTR_HWAS_STATE>();
        hwasState.poweredOn             = false;
        hwasState.present               = false;
        hwasState.functional            = false;
        hwasState.changedSinceLastIPL   = false;
        target->setAttr<ATTR_HWAS_STATE>(hwasState);
    }

    // ASSUMPTIONS:
    // CLASS_SYS (exactly 1) - mark as present
    // CLASS_ENC (>=1) - mark as present
    // TYPE_PROC TYPE_MEMBUF TYPE_DIMM (ALL require hardware query)
    //                                  - call platPresenceDetect
    //  \->children: CLASS_* (NONE require hardware query) - mark as present

    do
    {
        // find CLASS_SYS (the top level target)
        Target* pSys;
        targetService().getTopLevelTarget(pSys);

        HWAS_ASSERT(pSys,
                "HWAS discoverTargets: no CLASS_SYS TopLevelTarget found");

        // mark this as present
        enableHwasState(pSys, true, true);
        HWAS_DBG("pSys %.8X - marked present",
            pSys->getAttr<ATTR_HUID>());

        // find CLASS_ENC
        PredicateCTM predEnc(CLASS_ENC);
        TargetHandleList pEncList;
        targetService().getAssociated( pEncList, pSys,
            TargetService::CHILD, TargetService::ALL, &predEnc );

        for (TargetHandleList::iterator pEnc_it = pEncList.begin();
                pEnc_it != pEncList.end();
                pEnc_it++)
        {
            TargetHandle_t pEnc = *pEnc_it;

            // mark it as present
            enableHwasState(pEnc, true, true);
            HWAS_DBG("pEnc %.8X - marked present",
                pEnc->getAttr<ATTR_HUID>());
        } // for pEnc_it

        PredicateCTM predChip(CLASS_CHIP);
        PredicateCTM predDimm(CLASS_LOGICAL_CARD, TYPE_DIMM);
        PredicatePostfixExpr checkExpr;
        checkExpr.push(&predChip).push(&predDimm).Or();

        TargetHandleList pCheckPres;
        targetService().getAssociated( pCheckPres, pSys,
            TargetService::CHILD, TargetService::ALL, &checkExpr );

        // pass this list to the hwas platform-specific api where
        // pCheckPres will be modified to only have present targets
        HWAS_DBG("pCheckPres size: %d", pCheckPres.size());
        errl = platPresenceDetect(pCheckPres);
        HWAS_DBG("pCheckPres size: %d", pCheckPres.size());

        if (errl != NULL)
        {
            break; // break out of the do/while so that we can return
        }

        // no errors - keep going
        // for each, read their ID/EC level. if that works,
        //  mark them and their descendants as present
        //  read the partialGood vector to determine if any are not functional

        for (TargetHandleList::iterator pTarget_it = pCheckPres.begin();
                pTarget_it != pCheckPres.end();
                pTarget_it++
            )
        {
            TargetHandle_t pTarget = *pTarget_it;

            bool chipFunctional = true;
            bool chipPresent = true;
            uint16_t pgData[VPD_CP00_PG_DATA_LENGTH / sizeof(uint16_t)];
            bzero(pgData, sizeof(pgData));
            if (pTarget->getAttr<ATTR_CLASS>() == CLASS_CHIP)
            {
                // read Chip ID/EC data from these physical chips
                errl = platReadIDEC(pTarget);

                if (errl)
                {   // read of ID/EC failed even tho we were present..
                    chipFunctional = false;

                    // commit the error but keep going
                    errlCommit(errl, HWAS_COMP_ID);
                    // errl is now NULL
                }

                if (pTarget->getAttr<ATTR_TYPE>() == TYPE_PROC)
                {
                    // read partialGood vector from these as well.
                    errl = platReadPartialGood(pTarget, pgData);

                    if (errl)
                    {   // read of PG failed even tho we were present..
                        chipFunctional = false;

                        // commit the error but keep going
                        errlCommit(errl, HWAS_COMP_ID);
                        // errl is now NULL
                    }
                    else
                    // look at the 'nest' logic to override the functionality
                    //  of this proc
                    if (pgData[VPD_CP00_PG_PIB_INDEX] !=
                                    VPD_CP00_PG_PIB_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - PIB bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PIB_INDEX,
                            VPD_CP00_PG_PIB_GOOD);
                        chipFunctional = false;
                    }
                    else
                    if (pgData[VPD_CP00_PG_PERVASIVE_INDEX] !=
                                    VPD_CP00_PG_PERVASIVE_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - Pervasive bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PERVASIVE_INDEX,
                            VPD_CP00_PG_PERVASIVE_GOOD);
                        chipFunctional = false;
                    }
                    else
                    if (pgData[VPD_CP00_PG_POWERBUS_INDEX] !=
                                    VPD_CP00_PG_POWERBUS_GOOD)
                    {
                        HWAS_DBG("pTarget %.8X - PowerBus bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pTarget->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_POWERBUS_INDEX,
                            VPD_CP00_PG_POWERBUS_GOOD);
                        chipFunctional = false;
                    }
                } // TYPE_PROC
            } // CLASS_CHIP

            // TODO: Story 35077 - add PR processing. roughly:
            //  totalcores = readPR();
            //  for each child ex in chip c
            //      if goodcores < totalcores
            //          if ex->functional==true
            //              goodcores++
            //      else
            //          ex->functional = false

            HWAS_DBG("pTarget %.8X - detected present, %sfunctional",
                pTarget->getAttr<ATTR_HUID>(),
                chipFunctional ? "" : "NOT ");

            // now need to mark all of this target's
            //  physical descendants as present and functional as appropriate
            TargetHandleList pDescList;
            targetService().getAssociated( pDescList, pTarget,
                TargetService::CHILD, TargetService::ALL);
            for (TargetHandleList::iterator pDesc_it = pDescList.begin();
                    pDesc_it != pDescList.end();
                    pDesc_it++)
            {
                TargetHandle_t pDesc = *pDesc_it;
                // by default, the descendant's functionality is 'inherited'
                bool descFunctional = chipFunctional;

                if (chipFunctional)
                {   // if the chip is functional, the look through the
                    //  partialGood vector to see if its chiplets
                    //  are functional
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_XBUS) &&
                        (pgData[VPD_CP00_PG_XBUS_INDEX] !=
                            VPD_CP00_PG_XBUS_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - XBUS bad. "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_XBUS_INDEX,
                            VPD_CP00_PG_XBUS_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_ABUS) &&
                        (pgData[VPD_CP00_PG_ABUS_INDEX] !=
                            VPD_CP00_PG_ABUS_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - ABUS "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_ABUS_INDEX,
                            VPD_CP00_PG_ABUS_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_PCI) &&
                        (pgData[VPD_CP00_PG_PCIE_INDEX] !=
                            VPD_CP00_PG_PCIE_GOOD))
                    {
                        HWAS_DBG("pDesc %.8X - PCIe "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(),
                            VPD_CP00_PG_PCIE_INDEX,
                            VPD_CP00_PG_PCIE_GOOD);
                        descFunctional = false;
                    }
                    else
                    if ((pDesc->getAttr<ATTR_TYPE>() == TYPE_EX) ||
                        (pDesc->getAttr<ATTR_TYPE>() == TYPE_CORE)
                       )
                    {
                      ATTR_CHIP_UNIT_type indexEX =
                                pDesc->getAttr<ATTR_CHIP_UNIT>();
                      if (pgData[VPD_CP00_PG_EX0_INDEX + indexEX] !=
                            VPD_CP00_PG_EX0_GOOD)
                      {
                        HWAS_DBG("pDesc %.8X - EX%d "
                                    "pgPdata[%d]: expected 0x%04X - bad",
                            pDesc->getAttr<ATTR_HUID>(), indexEX,
                            VPD_CP00_PG_EX0_INDEX + indexEX,
                            VPD_CP00_PG_EX0_GOOD);
                        descFunctional = false;
                      }
                    }
                } // chipFunctional

                // for sub-parts, if it's not functional, it's not present.
                enableHwasState(pDesc, descFunctional, descFunctional);
                HWAS_DBG("pDesc %.8X - marked %spresent, %sfunctional",
                    pDesc->getAttr<ATTR_HUID>(),
                    descFunctional ? "" : "NOT ",
                    descFunctional ? "" : "NOT ");
            }

            // set HWAS state to show CHIP is present, functional per above
            enableHwasState(pTarget, chipPresent, chipFunctional);

        } // for pTarget_it

    } while (0);

    if (errl == NULL)
    {
        HWAS_INF("discoverTargets exit with no error");
    }
    else
    {
        HWAS_ERR("discoverTargets returning errl %p", errl);
    }
    return errl;
} // discoverTargets

};   // end namespace

<|endoftext|>